[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 store-on-localhost/src/monobloco/components/new/Styleguide/components/EXPERIMENTAL_Table/hooks/useTableVisibility.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { useMemo, useState, useCallback } from 'react'

import { Column } from '../types'

export default function useTableVisibility({
  columns,
  hiddenColumns: initHiddenColumns = [],
}: VisibilityData) {
  const [hiddenColumns, setHiddenColumns] = useState(initHiddenColumns)

  const visibleColumns = useMemo(() => {
    const reducer = (acc: Array<Column>, col: Column) =>
      hiddenColumns.includes(col.id) ? acc : [...acc, col]

    return columns.reduce(reducer, [])
  }, [hiddenColumns, columns])

  const toggleColumn = useCallback((id: string) => {
    setHiddenColumns(col =>
      col.includes(id) ? col.filter(col => col !== id) : [...col, id]
    )
  }, [])

  const showAllColumns = () => {
    setHiddenColumns([])
  }

  const hideAllColumns = () => {
    setHiddenColumns(columns.map(col => col.id))
  }

  return {
    columns,
    visibleColumns,
    hiddenColumns,
    toggleColumn,
    showAllColumns,
    hideAllColumns,
  }
}

export type VisibilityData = {
  columns: Column[]
  hiddenColumns?: 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 store-on-localhost/src/monobloco/components/new/Styleguide/components/EXPERIMENTAL_Table/hooks/useTableMeasures.tsx from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```tsx
import { useMemo, useState } from 'react'

const DEFAULT_SCROLLBAR_WIDTH = 17
const EMPTY_STATE_SIZE_IN_ROWS = 5
export const TABLE_HEADER_HEIGHT = 36

export default function useTableMeasures({
  size = 0,
  density = Density.Regular,
}: MeasuresInput) {
  const [currentDensity, setCurrentDensity] = useState<Density>(density)

  const rowHeight = useMemo(() => getRowHeight(currentDensity), [
    currentDensity,
  ])

  const tableHeight = useMemo(() => calculateTableHeight(rowHeight, size), [
    rowHeight,
    size,
  ])

  return {
    currentDensity,
    rowHeight,
    tableHeight,
    setCurrentDensity,
  }
}

export type MeasuresInput = {
  size: number
  density: Density
}

export function calculateTableHeight(
  rowHeight: number,
  tableSize: number
): number {
  const multiplicator = tableSize !== 0 ? tableSize : EMPTY_STATE_SIZE_IN_ROWS
  return TABLE_HEADER_HEIGHT + rowHeight * multiplicator + getScrollbarWidth()
}

export function getScrollbarWidth(): number {
  if (!window || !document || !document.documentElement)
    return DEFAULT_SCROLLBAR_WIDTH
  const scrollbarWidth =
    window.innerWidth - document.documentElement.clientWidth
  return isNaN(scrollbarWidth) ? DEFAULT_SCROLLBAR_WIDTH : scrollbarWidth
}

export enum Density {
  Compact = 'compact',
  Regular = 'regular',
  Comfortable = 'comfortable',
}

export enum DesitySizes {
  Compact = 32,
  Regular = 48,
  Comfortable = 76,
}

export const DENSITY_OPTIONS = [
  Density.Compact,
  Density.Regular,
  Density.Comfortable,
]

export function getRowHeight(density: Density): number {
  switch (density) {
    case Density.Compact:
      return DesitySizes.Compact
    case Density.Regular:
      return DesitySizes.Regular
    case Density.Comfortable:
      return DesitySizes.Comfortable
  }
}

```


[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 store-on-localhost/src/monobloco/components/new/Styleguide/components/EXPERIMENTAL_Table/DataTable/index.tsx from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { FC } from 'react'
import classNames from 'classnames'

import EmptyState from '../../EmptyState/index.js'
import { NAMESPACES, ORDER_CLASSNAMES } from '../constants'
import { TABLE_HEADER_HEIGHT } from '../hooks/useTableMeasures'
import Loading from './Loading'
import useTableMotion from '../hooks/useTableMotion'
import { E2ETestable } from '../types'

const DataTable: FC<DataTableProps> = ({
  children,
  height,
  className,
  tagName: Tag,
  empty,
  loading,
  emptyState,
  motion,
  testId,
}) => {
  const showLoading = !empty && loading
  const showEmptyState = empty && emptyState
  return (
    <div
      style={{ minHeight: height, ...motion }}
      className={classNames(
        'order-1 mw-100 overflow-x-auto',
        ORDER_CLASSNAMES.TABLE
      )}>
      <Tag
        id={NAMESPACES.TABLE}
        data-testid={testId}
        className={`w-100 ${className}`}
        style={{ borderSpacing: 0 }}>
        {children}
      </Tag>
      {showLoading && (
        <Loading
          testId={`${testId}__loading`}
          motion={motion}
          height={height - TABLE_HEADER_HEIGHT}>
          {typeof loading !== 'boolean' &&
            loading.renderAs &&
            loading.renderAs()}
        </Loading>
      )}
      {showEmptyState && (
        <EmptyState testId={`${testId}__empty-state`} title={emptyState.label}>
          {emptyState.children}
        </EmptyState>
      )}
    </div>
  )
}

DataTable.defaultProps = {
  tagName: 'table',
  className: '',
}

export type DataTableProps = E2ETestable & {
  height: number
  tagName?: 'table' | 'div' | 'section'
  className?: string
  empty: boolean
  motion: ReturnType<typeof useTableMotion>
  loading?:
    | boolean
    | {
        renderAs?: () => React.ReactNode
      }
  emptyState?: {
    label?: string
    children?: Element
  }
}

export default DataTable

```


[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 store-on-localhost/src/monobloco/components/new/Styleguide/components/EXPERIMENTAL_Table/DataTable/Rows.tsx from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { FC } from 'react'
import pick from 'lodash/pick'

import Row, { RowProps, ROW_TRANSITIONS } from './Row'
import { Column, Items } from '../types'
import { Density } from '../hooks/useTableMeasures'
import { Checkboxes } from '../../EXPERIMENTAL_useCheckboxTree/types'
import useTableMotion from '../hooks/useTableMotion'
import { CellProps } from './Cell'

const Rows: FC<RowsProps> = ({
  columns,
  items,
  onRowClick,
  cellProps,
  rowProps,
  isRowActive,
  rowHeight,
  currentDensity,
  checkboxes,
  rowKey,
}) => {
  const motion = useTableMotion(ROW_TRANSITIONS)
  return items ? (
    <>
      {items.map(rowData => {
        const toggleChecked = () => checkboxes.toggle(rowData)

        const isRowChecked = checkboxes && checkboxes.isChecked(rowData)
        const isRowPartiallyChecked =
          checkboxes && checkboxes.isPartiallyChecked(rowData)
        const isRowSelected = isRowChecked || isRowPartiallyChecked

        const clickable = onRowClick
          ? {
              onClick: () => onRowClick({ rowData }),
              link: true,
            }
          : {}
        return (
          <Row
            {...rowProps}
            {...clickable}
            height={rowHeight}
            active={(isRowActive && isRowActive(rowData)) || isRowSelected}
            key={rowKey({ rowData })}
            motion={motion}>
            {columns.map((column: Column, cellIndex: number) => {
              const { cellRenderer, width } = column
              const data = column.condensed
                ? pick(rowData, column.condensed)
                : column.extended
                ? rowData
                : rowData[column.id]
              const content = cellRenderer
                ? cellRenderer({
                    data,
                    rowHeight,
                    currentDensity,
                    motion,
                  })
                : data
              return (
                <Row.Cell {...cellProps} key={column.id} width={width}>
                  {cellIndex === 0 && checkboxes && (
                    <Row.Cell.Prefix>
                      <span className="ph3">
                        <Row.Cell.Prefix.Checkbox
                          checked={isRowChecked}
                          partial={isRowPartiallyChecked}
                          disabled={checkboxes.isDisabled(rowData)}
                          onClick={toggleChecked}
                        />
                      </span>
                    </Row.Cell.Prefix>
                  )}
                  {content}
                </Row.Cell>
              )
            })}
          </Row>
        )
      })}
    </>
  ) : null
}

export type RowsProps = {
  columns: Array<Column>
  items: Items
  currentDensity: Density
  rowKey?: ({ rowData: unknown }) => string
  onRowClick?: ({ rowData: unknown }) => void
  isRowActive?: (rowData: unknown) => boolean
  rowProps?: RowProps
  rowHeight: number
  cellProps?: Pick<CellProps, 'tagName' | 'className'>
  checkboxes?: Checkboxes<unknown>
}

export default Rows

```


[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 store-on-localhost/src/monobloco/components/new/Styleguide/components/EXPERIMENTAL_Table/DataTable/Row.tsx from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { FC } from 'react'
import classNames from 'classnames'

import useTableMotion from '../hooks/useTableMotion'
import Cell, { CellProps, CellComposites } from './Cell'

const Row: FC<RowProps> & RowComposites = ({
  tagName: Tag = 'tr',
  children,
  height,
  onClick,
  active,
  motion,
}) => {
  const className = classNames('w-100 truncate overflow-x-hidden', {
    'pointer hover-c-link hover-bg-muted-5': onClick,
    'bg-action-secondary': active,
  })
  const style = {
    height,
    ...motion,
  }
  return (
    <Tag style={style} onClick={onClick} className={className}>
      {children}
    </Tag>
  )
}

Row.Cell = Cell

export const ROW_TRANSITIONS = [
  {
    prop: 'height',
    duration: 200,
    func: 'ease-in-out',
    delay: 0,
    optimize: true,
  },
]

export type RowComposites = {
  Cell: FC<CellProps> & CellComposites
}

export type RowProps = {
  tagName?: 'tr' | 'div' | 'ul'
  active?: boolean
  height?: number
  onClick?: () => void
  motion?: ReturnType<typeof useTableMotion>
}

export default Row

```


[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 store-on-localhost/src/monobloco/components/new/Styleguide/components/EXPERIMENTAL_Table/DataTable/Cell.tsx from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { FC, createContext, useContext, useState } from 'react'
import classNames from 'classnames'

import CaretDown from '../../icon/CaretDown/index.js'
import CaretUp from '../../icon/CaretUp/index.js'
import Checkbox, { CheckboxProps } from '../Checkbox'

const PREFIX_GAP = 35
const SUFIX_GAP = 0.5

const HoverContext = createContext<boolean>(false)

function HoverProvider({ children, value }) {
  return <HoverContext.Provider value={value}>{children}</HoverContext.Provider>
}

function useHover(init = false) {
  const [hover, setHover] = useState(init)

  const onMouseEnter = () => setHover(true)
  const onMouseLeave = () => setHover(false)

  return {
    hover,
    onMouseEnter,
    onMouseLeave,
  }
}

const Cell: FC<CellProps> & CellComposites = ({
  children,
  width,
  onClick,
  tagName: Tag = 'td',
  className: classNameProp = '',
  active = false,
  link = false,
}) => {
  const { hover, ...events } = useHover()
  const className = classNames(
    'v-mid ph3 pv0 tl bb b--muted-4',
    classNameProp,
    {
      pointer: onClick,
      'hover-c-link hover-bg-muted-5': link,
      'c-on-base': active,
    }
  )
  return (
    <Tag {...events} onClick={onClick} style={{ width }} className={className}>
      <HoverProvider value={hover}>{children}</HoverProvider>
    </Tag>
  )
}

const Prefix: FC<PrefixProps> & PrefixComposites = ({
  children,
  depth = 0,
}) => {
  const width = PREFIX_GAP * depth
  return (
    <>
      <div className="dib" style={{ width }} />
      <div className="dib pr3 v-mid">
        <div className="flex w-100 items-center">{children}</div>
      </div>
    </>
  )
}

function Eyesight({ children, visible }) {
  const className = classNames({ dn: !visible, inline: visible }, 'absolute')
  return (
    <span className={className} style={{ marginLeft: `${SUFIX_GAP}rem` }}>
      {children}
    </span>
  )
}

const Suffix: FC<SuffixProps> = ({ active, ascending }) => {
  const Caret = ascending ? CaretDown : CaretUp
  const hover = useContext(HoverContext)
  return (
    <Eyesight visible={active || hover}>
      <Caret className="ml2" size={10} />
    </Eyesight>
  )
}

Cell.Prefix = Prefix
Cell.Suffix = Suffix
Prefix.Checkbox = Checkbox

type PrefixComposites = {
  Checkbox?: FC<CheckboxProps>
}

type PrefixProps = {
  depth?: number
}

type SuffixProps = {
  active: boolean
  ascending: boolean
}

export type CellComposites = {
  Prefix?: FC<PrefixProps> & PrefixComposites
  Suffix?: FC<SuffixProps>
}

export type CellProps = {
  id?: string
  width?: number | string | React.ReactText
  tagName?: 'td' | 'th' | 'div' | 'li'
  className?: string
  onClick?: () => void
  showArrow?: boolean
  active?: boolean
  link?: boolean
}

export default Cell

```


[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 store-on-localhost/src/monobloco/components/new/Styleguide/components/EXPERIMENTAL_Table/DataTable/Loading.tsx from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { FC } from 'react'

import Spinner from '../../Spinner/index.js'
import useTableMotion from '../hooks/useTableMotion'
import { E2ETestable } from '../types'

const Loading: FC<Props> = ({ height, motion, children, testId }) => {
  return (
    <div
      data-testid={testId}
      className="flex justify-center items-center"
      style={{ height, ...motion }}>
      {children || <Spinner />}
    </div>
  )
}

type Props = E2ETestable & {
  height: number
  motion: ReturnType<typeof useTableMotion>
}

export default Loading

```


[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 store-on-localhost/src/monobloco/components/new/Styleguide/components/EXPERIMENTAL_Table/DataTable/Headings.tsx from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { FC } from 'react'
import classNames from 'classnames'

import { TABLE_HEADER_HEIGHT } from '../hooks/useTableMeasures'
import Row, { RowProps } from './Row'
import { Column } from '../types'
import { Checkboxes } from '../../EXPERIMENTAL_useCheckboxTree/types'
import Cell, { CellProps } from './Cell'
import useTableSort from '../hooks/useTableSort'

const Headings: FC<HeadingsProps> = ({
  columns,
  checkboxes,
  cellProps,
  rowProps,
  sorting,
}) => {
  return (
    <Row {...rowProps} height={TABLE_HEADER_HEIGHT}>
      {columns.map((columnData: Column, headerIndex: number) => {
        const { id, title, width, sortable } = columnData
        const cellClassName = classNames('bt normal', { pointer: sortable })
        const active = sorting && sorting.sorted && sorting.sorted.by === id
        const ascending = sorting && sorting.sorted.order !== 'DSC'
        const onclick =
          sortable && sorting ? { onClick: () => sorting.sort(id) } : {}
        return (
          <Row.Cell
            {...onclick}
            {...cellProps}
            active={active}
            className={cellClassName}
            key={headerIndex}
            width={width}>
            {checkboxes && headerIndex === 0 && (
              <Cell.Prefix>
                <span className="ph3">
                  <Cell.Prefix.Checkbox
                    checked={checkboxes.allChecked}
                    partial={checkboxes.someChecked}
                    disabled={checkboxes.allDisabled}
                    // eslint-disable-next-line react/jsx-handler-names
                    onClick={checkboxes.toggleAll}
                  />
                </span>
              </Cell.Prefix>
            )}
            {title}
            {sortable && <Cell.Suffix active={active} ascending={ascending} />}
          </Row.Cell>
        )
      })}
    </Row>
  )
}

Headings.defaultProps = {
  cellProps: {
    tagName: 'th',
  },
}

type HeadingsProps = {
  columns: Array<Column>
  rowProps?: RowProps
  cellProps?: Pick<CellProps, 'tagName'>
  checkboxes?: Checkboxes<unknown>
  sorting?: Partial<ReturnType<typeof useTableSort>>
}

export default React.memo(Headings)

```


[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 store-on-localhost/src/monobloco/components/new/FlexLayout/typings/global.d.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { FunctionComponent } from 'react'
import { TachyonsScaleInput } from '../modules/valuesParser'

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

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

  interface StorefrontElement extends ReactElement {
    schema?: object
    getSchema?(props: P): object
  }

  interface Gap {
    colGap: TachyonsScaleInput
    rowGap: TachyonsScaleInput
  }

  interface Flex {
    stretchContent: boolean
    grow: boolean
  }

  type BorderBase = 'top' | 'right' | 'bottom' | 'left' | 'all'

  interface Border {
    border: BorderBase | BorderBase[]
    borderWidth: TachyonsScaleInput
    borderColor: 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 store-on-localhost/src/monobloco/components/new/FlexLayout/typings/css.d.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
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 store-on-localhost/src/monobloco/components/new/FlexLayout/components/FlexLayoutContext.tsx from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

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

export enum FlexLayoutTypes {
  NONE = 'none',
  ROW = 'row',
  COL = 'col',
}

export interface FlexLayoutContextProps {
  parent: FlexLayoutTypes
  colGap: number
  rowGap: number
}

export type FlexLayoutContextValue = number | FlexLayoutTypes

export type FlexLayoutContext = FlexLayoutContextProps & {
  [key: string]: FlexLayoutContextValue
}

const FlexLayoutContext = React.createContext<FlexLayoutContext>({
  parent: FlexLayoutTypes.NONE,
  colGap: 0,
  rowGap: 0,
})

export const FlexLayoutContextProvider: FunctionComponent<
  FlexLayoutContextProps
> = ({ parent, colGap, rowGap, children }) => {
  const value = useMemo(
    () => ({
      parent,
      colGap,
      rowGap,
    }),
    [parent, colGap, rowGap]
  )

  return (
    <FlexLayoutContext.Provider value={value}>
      {children}
    </FlexLayoutContext.Provider>
  )
}

export const useFlexLayoutContext = () => useContext(FlexLayoutContext)

```


[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 store-on-localhost/src/monobloco/components/new/FlexLayout/__tests__/valuesParser.test.js from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```javascript
import { parseBorders } from '../modules/valuesParser'

describe('parseBorders', () => {
  it('should work with border as array', () => {
    const input = {
      border: ['left', 'bottom', 'right', 'top', 'all'],
      borderWidth: 1,
      borderColor: 'red',
    }

    const border = parseBorders(input)

    expect(border).toBe('bl bb br bt ba bw1 b--red')
  })
  it('should work with border as string', () => {
    const input = {
      border: 'all',
      borderWidth: 1,
      borderColor: 'red',
    }

    const border = parseBorders(input)

    expect(border).toBe('ba bw1 b--red')
  })
})

```


[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 store-on-localhost/src/monobloco/components/new/FlexLayout/hooks/responsiveWidth.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
import React, { ReactElement } from 'react'
import useDevice from '../../DeviceDetector/useDevice'
import { parseWidth } from '../modules/valuesParser'

interface DistributedWidthOptions {
  preserveLayoutOnMobile?: boolean
}

interface ColWithWidth {
  element: React.ReactNode
  width: number | string
  hasDefinedWidth: boolean
  isResponsive: boolean
}

/** Distributes the available width--width that remains after subtracting
 * the widths of the columns the user has set--between the columns that do
 * not have their widths set by the user.
 *
 * For example:
 * There are 3 columns. The user sets the width for the first one to 50%.
 * This function will set the widths of the second and third columns to 25%.
 */
const distributeAvailableWidth = (cols: ColWithWidth[]) => {
  const { availableWidth, remainingColsNum, hasAnyWidthGrow } = cols.reduce(
    (acc, col) => {
      const isGrow = col.width === 'grow'
      const width =
        typeof col.width === 'number' ? acc.availableWidth - col.width : 0

      return {
        availableWidth: isGrow ? 0 : width,
        remainingColsNum: acc.remainingColsNum + (col.hasDefinedWidth ? 0 : 1),
        hasAnyWidthGrow: acc.hasAnyWidthGrow || isGrow,
      }
    },
    {
      availableWidth: 100,
      remainingColsNum: 0,
      hasAnyWidthGrow: false,
    }
  )

  if (availableWidth < 0 && !hasAnyWidthGrow) {
    console.warn(
      'Total width set for columns of a flex-layout.row block exceeds 100%.'
    )
    const normalization = -(100 / availableWidth)
    cols = cols.map(col => ({
      ...col,
      width:
        typeof col.width === 'number' ? col.width * normalization : col.width,
    }))
  }

  return cols.map(col => {
    const definedWidth =
      typeof col.width === 'number' ? `${col.width}%` : col.width

    return {
      element: col.element,
      width: col.hasDefinedWidth
        ? definedWidth
        : `${Math.floor(Math.max(0, availableWidth) / remainingColsNum)}%`,
      hasDefinedWidth: col.hasDefinedWidth,
    }
  })
}

function isReactElement(element: any): element is ReactElement {
  return !!element && element.props
}

export const useResponsiveWidth = (
  children: React.ReactNode,
  options: DistributedWidthOptions
) => {
  const { device } = useDevice()

  const isPhone = device === 'phone'

  const { preserveLayoutOnMobile = false } = options || {}

  const cols: ColWithWidth[] = React.Children.toArray(children).map(col => {
    if (!isReactElement(col)) {
      return {
        element: col,
        width: 0,
        hasDefinedWidth: false,
        isResponsive: true,
      }
    }

    const width = parseWidth(
      col.props.width || (col.props.blockProps && col.props.blockProps.width)
    )

    if (width && typeof width === 'object') {
      return {
        element: col,
        width: isPhone ? width.mobile || 0 : width.desktop || 0,
        hasDefinedWidth: true,
        isResponsive: true,
      }
    }

    if (!preserveLayoutOnMobile && isPhone) {
      return {
        element: col,
        width: 0,
        hasDefinedWidth: false,
        isResponsive: false,
      }
    }

    if (typeof width === 'number' || typeof width === 'string') {
      return {
        element: col,
        width,
        hasDefinedWidth: true,
        isResponsive: false,
      }
    }

    return {
      element: col,
      width: 0,
      hasDefinedWidth: false,
      isResponsive: true,
    }
  })

  const isAnyColResponsive = cols.some(col => col.isResponsive)
  const breakOnMobile =
    !preserveLayoutOnMobile && isPhone && !isAnyColResponsive

  return {
    cols: distributeAvailableWidth(cols),
    breakOnMobile,
  }
}

```


[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 store-on-localhost/src/monobloco/components/new/FlexLayout/modules/valuesParser.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { fromPairs, pick, range, toPairs } from 'ramda'

export type TachyonsScaleInput = string | number | undefined
type Group<T, U> = { [key in keyof T]: U }
type TachyonsInputGroup<T> = Group<T, TachyonsScaleInput>
interface ResponsiveInput<T> {
  mobile: T
  desktop: T
}

const MAX_TACHYONS_SCALE = 11

//eslint-disable-next-line @typescript-eslint/no-explicit-any
const isResponsiveInput = <T>(value: any): value is ResponsiveInput<T> =>
  value && value.mobile != null && value.desktop != null

/** Takes a parser of units, and returns a parser that accepts either a
 * value or a responsive input of that same type of value
 * (i.e. {mobile: ..., desktop: ...}), and returns an object of the same
 * format of the input.
 */
export const parseResponsive = <T, U>(parse: (value: T) => U) => (
  value: T | ResponsiveInput<T>
): null | U | { mobile: U; desktop: U } => {
  if (isResponsiveInput(value)) {
    return {
      mobile: parse(value.mobile),
      desktop: parse(value.desktop),
    }
  }

  return parse(value)
}

/** Verifies if the input is a valid Tachyons scale value (i.e. a number
 * between 0 to 11) and converts to number if necessary
 */
const parseTachyonsValue = (value: TachyonsScaleInput, name?: string) => {
  if (!value) {
    return 0
  }

  const supportedValues = range(0, MAX_TACHYONS_SCALE + 1).map(String)

  if (!supportedValues.includes(String(value))) {
    if (name) {
      console.warn(
        `Invalid ${name} value ("${value}"). It should be an integer between 0 and ${MAX_TACHYONS_SCALE}.`
      )
    }

    return 0
  }

  return typeof value === 'string' ? parseInt(value, 10) : value
}

export const parseTachyonsGroup = <T>(group: TachyonsInputGroup<T>) => {
  const pairs = toPairs<TachyonsScaleInput>(group)

  const parsedValues = pairs.map<[string, number]>(([key, value]) => [
    key,
    parseTachyonsValue(value, key),
  ])

  return fromPairs(parsedValues) as Group<T, number>
}

const parseDimension = (input: string): null | number | string => {
  if (typeof input !== 'string') {
    return null
  }

  if (input === 'grow') {
    return 'grow'
  }

  const supportedUnits = ['%']
  const match = input.match(new RegExp(`(\\d*)(${supportedUnits.join('|')})`))

  if (!match) {
    return null
  }

  const value = match[1]
  // TODO: support multiple units
  // const unit = match[2]

  if (value == null) {
    return null
  }

  const parsedValue = parseInt(value, 10)

  return parsedValue
}

export const parseWidth = parseResponsive(parseDimension)

/** TODO: allow responsive values on height
 * (and verify height usage overall)
 **/
export const parseHeight = parseDimension

/** Maps objects keys to Tachyons classes, and returns a function
 * that parses Tachyons scale values to the mapped classes,
 * which in turn returns a string of classNames.
 **/
const mapToClasses = <T>(map: { [key in keyof T]: string }) => (
  props: { [key in keyof T]?: TachyonsScaleInput }
) => {
  const pickedProps = pick(Object.keys(map), props)

  const parsedProps = parseTachyonsGroup(pickedProps)

  const mappedProps = toPairs(parsedProps).map(
    ([key, value]) => `${map[key as (keyof T)] as string}${value}`
  )

  return mappedProps.join(' ')
}

// TODO: allow responsive values on paddings and margins
export const parsePaddings = mapToClasses({
  paddingTop: 'pt',
  paddingBottom: 'pb',
  paddingLeft: 'pl',
  paddingRight: 'pr',
})

export const parseMargins = mapToClasses({
  marginTop: 'mt',
  marginBottom: 'mb',
  marginLeft: 'ml',
  marginRight: 'mr',
})

const borderMap = {
  top: 'bt',
  right: 'br',
  bottom: 'bb',
  left: 'bl',
  all: 'ba',
}

export const parseBorders = ({ border, borderWidth, borderColor }: Border) => {
  const borders = border
    ? ([] as BorderBase[])
        .concat(border)
        .map(base => borderMap[base])
        .join(' ')
    : ''
  const width = borderWidth ? `bw${parseTachyonsValue(borderWidth, 'bw')}` : ''
  const color = borderColor ? `b--${borderColor.split(' ')[0]}` : ''

  return `${borders} ${width} ${color}`
}

```


[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 store-on-localhost/src/monobloco/components/new/SliderLayout/typings/globals.d.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { FunctionComponent } from 'react'
import { MaybeResponsiveValue } from 'vtex.responsive-values'

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

  interface SliderLayoutSiteEditorProps {
    infinite: boolean
    showNavigationArrows: 'mobileOnly' | 'desktopOnly' | 'always' | 'never'
    showPaginationDots: 'mobileOnly' | 'desktopOnly' | 'always' | 'never'
    usePagination: boolean
    fullWidth: boolean
    arrowSize: MaybeResponsiveValue<number>
  }

  interface SliderLayoutProps {
    totalItems?: number
    label: string
    slideTransition: {
      /** Transition speed in ms */
      speed: number
      /** Transition delay in ms */
      delay: number
      timing: string
    }
    autoplay?: {
      /** Timeout duration in ms */
      timeout: number
      stopOnHover?: boolean
    }
    navigationStep: number | 'page'
    itemsPerPage: {
      desktop: number
      tablet: number
      phone: number
    }
  }
}

```


[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 store-on-localhost/src/monobloco/components/new/SliderLayout/typings/vtex.css-handles.d.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.css-handles' {
  export const useCssHandles = <T extends CssHandlesInput>(
    handles: T
  ): CssHandles<T> => {
    let cssHandles: CssHandles<T>

    // This is not actually what is returned by useCssHandles
    // just a mock for typechecking and testing.
    handles.forEach(handle => {
      cssHandles[handle] = handle
    })

    return cssHandles
  }
}

type CssHandlesInput = readonly string[]
type ValueOf<T extends readonly any[]> = T[number]
type CssHandles<T extends CssHandlesInput> = Record<ValueOf<T>, 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 store-on-localhost/src/monobloco/components/new/SliderLayout/typings/vtex.render-runtime.d.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
/* eslint @typescript-eslint/no-explicit-any: 0 */
/* Typings for `render-runtime` */
declare module 'vtex.render-runtime' {
  import { Component, ReactElement } from 'react'

  export interface RenderContextProps {
    runtime: {
      account: string
    }
  }

  export interface InjectedRuntime {
    runtime: RenderRuntime
  }

  interface Pages {
    [name: string]: Page
  }

  interface Route {
    domain: string
    blockId: string
    canonicalPath?: string
    id: string
    params: Record<string, string>
    path: string
    title?: string
  }

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

  export interface RenderRuntime {
    account: string
    accountId: string
    appsEtag: string
    workspace: string
    disableSSR: boolean
    hints: {
      desktop: boolean
      mobile: boolean
      phone: boolean
      tablet: boolean
    }
    page: string
    route: Route
    version: string
    culture: Culture
    pages: Pages
    preview: boolean
    production: boolean
    publicEndpoint: string
    renderMajor: number
    query?: Record<string, string>
    start: boolean
    runtimeMeta: {
      version: string
      config?: any
    }
    settings: {
      [app: string]: any
    }
    segmentToken: string
    rootPath?: string
    workspaceCookie: string
    hasNewExtensions: boolean
  }

  export const Link: any
  export const NoSSR: any
  export const RenderContextConsumer: ReactElement
  export const canUseDOM: boolean
  export const withRuntimeContext: any
  export const Helmet: any
  export const useSSR: () => boolean
  export const useRuntime: () => RenderRuntime
}

```


[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 store-on-localhost/src/monobloco/components/new/SliderLayout/typings/vtex.device-detector.d.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.device-detector' {
  export function useDevice(): {
    device: 'desktop' | 'tablet' | 'phone'
    isMobile: boolean
  }
}

```


[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 store-on-localhost/src/monobloco/components/new/SliderLayout/typings/vtex.store-icons.d.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.store-icons' {
  export const IconCaret: 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 store-on-localhost/src/monobloco/components/new/SliderLayout/typings/css.d.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
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 store-on-localhost/src/monobloco/components/new/SliderLayout/components/Slider.tsx from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { FC, useRef, Fragment } from 'react'
import useDevice from '../../DeviceDetector/useDevice'
import useCssHandles from '../../CssHandles/useCssHandles'

import { useScreenResize } from '../hooks/useScreenResize'
import { useTouchHandlers } from '../hooks/useTouchHandlers'
import { useAutoplay } from '../hooks/useAutoplay'
import { useSliderState } from './SliderContext'
import SliderTrack from './SliderTrack'
import Arrow from './Arrow'
import PaginationDots from './PaginationDots'

interface Props extends SliderLayoutSiteEditorProps {
  totalItems: number
}

const CSS_HANDLES = ['sliderLayoutContainer', 'sliderTrackContainer'] as const

const Slider: FC<Props> = ({
  children,
  totalItems,
  infinite,
  showNavigationArrows,
  showPaginationDots,
  usePagination: shouldUsePagination,
  arrowSize,
  fullWidth,
}) => {
  const handles = useCssHandles(CSS_HANDLES)
  const { isMobile } = useDevice()
  const { label, slidesPerPage } = useSliderState()
  const containerRef = useRef<HTMLDivElement>(null)
  const controls = `${label
    .toLowerCase()
    .trim()
    .replace(/ /g, '-')}-items`

  useAutoplay(infinite, containerRef)
  useScreenResize(infinite)
  const { onTouchEnd, onTouchStart, onTouchMove } = useTouchHandlers({
    infinite,
  })
  const shouldBeStaticList = slidesPerPage >= totalItems

  const shouldShowArrows = Boolean(
    (showNavigationArrows === 'always' ||
      (showNavigationArrows === 'mobileOnly' && isMobile) ||
      (showNavigationArrows === 'desktopOnly' && !isMobile)) &&
      !shouldBeStaticList
  )
  const shouldShowPaginationDots = Boolean(
    (showPaginationDots === 'always' ||
      (showPaginationDots === 'mobileOnly' && isMobile) ||
      (showPaginationDots === 'desktopOnly' && !isMobile)) &&
      !shouldBeStaticList
  )

  const touchStartHandler = (e: React.TouchEvent) =>
    shouldUsePagination && !shouldBeStaticList ? onTouchStart(e) : null
  const touchEndHandler = (e: React.TouchEvent) =>
    shouldUsePagination && !shouldBeStaticList ? onTouchEnd(e) : null
  const touchMoveHandler = (e: React.TouchEvent) =>
    shouldUsePagination && !shouldBeStaticList ? onTouchMove(e) : null

  return (
    <section
      onTouchStart={touchStartHandler}
      onTouchEnd={touchEndHandler}
      onTouchMove={touchMoveHandler}
      aria-roledescription="carousel"
      aria-label={label}
      style={{
        WebkitOverflowScrolling: !shouldUsePagination ? 'touch' : undefined,
        paddingLeft: fullWidth ? undefined : arrowSize * 2,
        paddingRight: fullWidth ? undefined : arrowSize * 2,
      }}
      className={`w-100 flex items-center relative ${handles.sliderLayoutContainer}`}
    >
      <div
        className={`w-100 ${handles.sliderTrackContainer} ${
          shouldUsePagination ? 'overflow-hidden' : 'overflow-x-scroll'
        }`}
        ref={containerRef}
      >
        <SliderTrack totalItems={totalItems}>{children}</SliderTrack>
      </div>
      {shouldShowArrows && shouldUsePagination && (
        <Fragment>
          <Arrow
            totalItems={totalItems}
            orientation="left"
            controls={controls}
            infinite={infinite}
            arrowSize={arrowSize}
          />
          <Arrow
            totalItems={totalItems}
            orientation="right"
            controls={controls}
            infinite={infinite}
            arrowSize={arrowSize}
          />
        </Fragment>
      )}
      {shouldShowPaginationDots && shouldUsePagination && (
        <PaginationDots totalItems={totalItems} controls={controls} />
      )}
    </section>
  )
}

export default Slider

```


[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 store-on-localhost/src/monobloco/components/new/SliderLayout/components/Arrow.tsx from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { memo, FC, ReactNode } from 'react'
import IconCaret from '../../StoreIcons/IconCaret'

import useCssHandles from '../../CssHandles/useCssHandles'

import { useSliderState } from './SliderContext'

import useKeyboardArrows from '../hooks/useKeyboardArrows'
import { useSliderControls } from '../hooks/useSliderControls'

interface Props {
  custom?: ReactNode
  orientation: 'left' | 'right'
  controls: string
  totalItems: number
  infinite: boolean
  arrowSize: number
}

const CSS_HANDLES = ['sliderLeftArrow', 'sliderRightArrow', 'sliderArrows']

const Arrow: FC<Props> = ({
  custom,
  orientation,
  controls,
  totalItems,
  infinite,
  arrowSize,
}) => {
  const { currentSlide, slidesPerPage, navigationStep } = useSliderState()
  const { goBack, goForward } = useSliderControls(infinite)

  const handles = useCssHandles(CSS_HANDLES)

  const isLeftEndReach = !(
    currentSlide - (navigationStep ? navigationStep : 1) >=
    0
  )
  const isRightEndReach = !(currentSlide + 1 + slidesPerPage <= totalItems)
  const disabled =
    !infinite &&
    ((orientation === 'left' && isLeftEndReach) ||
      (orientation === 'right' && isRightEndReach))

  useKeyboardArrows(goBack, goForward)

  return (
    <button
      className={`${
        orientation === 'left'
          ? `${handles.sliderLeftArrow} left-0`
          : `${handles.sliderRightArrow} right-0`
      } ${
        handles.sliderArrows
      } absolute transparent ma2 flex items-center justify-center bn outline-0 pointer`}
      style={{ background: 'transparent' }}
      onClick={orientation === 'left' ? goBack : goForward}
      aria-controls={controls}
      aria-label={`${orientation === 'left' ? 'Previous' : 'Next'} Slide`}
      disabled={disabled}
    >
      {custom || <IconCaret size={arrowSize} orientation={orientation} thin />}
    </button>
  )
}

export default memo(Arrow)

```


[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 store-on-localhost/src/monobloco/components/new/SliderLayout/components/PaginationDots.tsx from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { memo, FC } from 'react'
import useCssHandles from '../../CssHandles/useCssHandles'

import { useSliderDispatch, useSliderState } from './SliderContext'

const DOTS_DEFAULT_SIZE = 0.625

interface Props {
  controls: string
  totalItems: number
}

const CSS_HANDLES = ['paginationDotsContainer', 'paginationDot'] as const

const getSelectedDot = (
  passVisibleSlides: boolean,
  currentSlide: number,
  slidesToShow: number
): number => {
  const realCurrentSlide = passVisibleSlides
    ? currentSlide + (slidesToShow - 1)
    : currentSlide
  return passVisibleSlides
    ? Math.floor(realCurrentSlide / slidesToShow)
    : realCurrentSlide
}

const getSlideIndices = (
  slidesToShow: number,
  passVisibleSlides: boolean,
  totalItems: number
): number[] =>
  slidesToShow
    ? [
        ...Array(
          passVisibleSlides ? Math.ceil(totalItems / slidesToShow) : totalItems
        ).keys() as any,
      ]
    : []

const PaginationDots: FC<Props> = ({ controls, totalItems }) => {
  const {
    slideWidth,
    slidesPerPage,
    currentSlide,
    navigationStep,
  } = useSliderState()
  const dispatch = useSliderDispatch()
  const handles = useCssHandles(CSS_HANDLES)
  const passVisibleSlides = navigationStep === slidesPerPage

  const slideIndexes = getSlideIndices(
    slidesPerPage,
    passVisibleSlides,
    totalItems
  )

  const handleDotClick = (index: number) => {
    const slideToGo = passVisibleSlides ? index * slidesPerPage : index
    const isLastDot = index === slideIndexes.length - 1
    const isExactDivision = totalItems % slidesPerPage === 0
    const overslideThreshold =
      !isExactDivision && isLastDot ? Math.floor(totalItems / slidesPerPage) : 0

    dispatch({
      type: 'SLIDE',
      payload: {
        transform: -(slideWidth * (slideToGo - overslideThreshold)),
        currentSlide: index,
      },
    })
  }

  return (
    <div
      className={`${handles.paginationDotsContainer} flex absolute justify-center pa0 ma0 bottom-0 left-0 right-0`}
      role="group"
      aria-label="Carousel Dots"
    >
      {slideIndexes.map(index => {
        const isActive =
          index ===
          getSelectedDot(passVisibleSlides, currentSlide, slidesPerPage)
        return (
          <div
            className={`${handles.paginationDot} ${
              isActive ? 'bg-emphasis' : 'bg-muted-3'
            } grow dib br-100 pa2 mr2 ml2 bw0 pointer outline-0`}
            style={{
              height: `${DOTS_DEFAULT_SIZE}rem`,
              width: `${DOTS_DEFAULT_SIZE}rem`,
            }}
            key={index}
            tabIndex={index}
            onKeyDown={() => handleDotClick(index)}
            onClick={() => handleDotClick(index)}
            role="button"
            aria-controls={controls}
            aria-label={`Dot ${index + 1} of ${slideIndexes.length}`}
          />
        )
      })}
    </div>
  )
}

export default memo(PaginationDots)

```


[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 store-on-localhost/src/monobloco/components/new/SliderLayout/components/SliderTrack.tsx from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { FC } from 'react'
import useListContext from '../../ListContext/useListContext'
import useCssHandles from '../../CssHandles/useCssHandles'

import { useSliderState } from './SliderContext'

const CSS_HANDLES = ['sliderTrack', 'slide', 'slideChildrenContainer']

const SliderTrack: FC<{ totalItems: number }> = ({ children, totalItems }) => {
  const {
    transform,
    slideWidth,
    slidesPerPage,
    currentSlide,
    isOnTouchMove,
    slideTransition: { speed, timing, delay },
  } = useSliderState()
  const handles = useCssHandles(CSS_HANDLES)
  const { list } = useListContext()

  const childrenArray = React.Children.toArray(children).concat(list)

  const isSlideVisible = (
    index: number,
    currentSlide: number,
    slidesToShow: number
  ): boolean => {
    return index >= currentSlide && index < currentSlide + slidesToShow
  }

  return (
    <div
      className={`${handles.sliderTrack} flex justify-around relative pa0 ma0`}
      style={{
        transition: isOnTouchMove
          ? undefined
          : `transform ${speed}ms ${timing}`,
        transitionDelay: `${delay}ms`,
        transform: `translate3d(${transform}%, 0, 0)`,
        width:
          slidesPerPage < totalItems
            ? `${(totalItems * 100) / slidesPerPage}%`
            : '100%',
      }}
      aria-atomic="false"
      aria-live="polite"
    >
      {childrenArray.map((child, index) => (
        <div
          key={index}
          className={`flex relative ${handles.slide}`}
          data-index={index}
          style={{
            width: `${slideWidth}%`,
          }}
          aria-hidden={
            isSlideVisible(index, currentSlide, slidesPerPage)
              ? 'false'
              : 'true'
          }
          role="group"
          aria-roledescription="slide"
          aria-label={`${index + 1} of ${totalItems}`}
        >
          <div
            className={`${handles.slideChildrenContainer} flex justify-center items-center w-100`}
          >
            {child}
          </div>
        </div>
      ))}
    </div>
  )
}

export default SliderTrack

```


[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 store-on-localhost/src/monobloco/components/new/SliderLayout/components/SliderContext.tsx from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { createContext, useReducer, useContext, FC } from 'react'
import useDevice from '../../DeviceDetector/useDevice'

interface AdjustOnResizeAction {
  type: 'ADJUST_ON_RESIZE'
  payload: {
    shouldCorrectItemPosition: boolean
    slidesPerPage: number
    navigationStep: number
  }
}

interface SlideAction {
  type: 'SLIDE'
  payload: {
    transform: number
    currentSlide: number
  }
}

interface TouchAction {
  type: 'TOUCH'
  payload: {
    transform?: number
    isOnTouchMove: boolean
  }
}

interface State extends SliderLayoutProps {
  /** Width of each slide */
  slideWidth: number
  /** Number of slides to show per page */
  slidesPerPage: number
  /** Index of the leftmost slide of the current page */
  currentSlide: number
  /** Current transform value */
  transform: number
  /** Total number of slides */
  totalItems: number
  /** Number of slides to slide in navigation */
  navigationStep: number
  /** Whether or not navigationStep prop is set to 'page' */
  isPageNavigationStep: boolean
  /** Whether or not a touchmove event is happening */
  isOnTouchMove: boolean
}

type Action = AdjustOnResizeAction | SlideAction | TouchAction
type Dispatch = (action: Action) => void

const SliderStateContext = createContext<State | undefined>(undefined)
const SliderDispatchContext = createContext<Dispatch | undefined>(undefined)

function sliderContextReducer(state: State, action: Action): State {
  switch (action.type) {
    case 'ADJUST_ON_RESIZE':
      return {
        ...state,
        slidesPerPage: action.payload.slidesPerPage,
        navigationStep: action.payload.navigationStep,
        transform: action.payload.shouldCorrectItemPosition
          ? -state.slideWidth * state.currentSlide
          : state.transform,
      }
    case 'SLIDE':
      return {
        ...state,
        transform: action.payload.transform,
        currentSlide: action.payload.currentSlide,
      }
    case 'TOUCH':
      return {
        ...state,
        transform: action.payload.transform || state.transform,
        isOnTouchMove: action.payload.isOnTouchMove,
      }
    default:
      return state
  }
}

const SliderContextProvider: FC<SliderLayoutProps & { totalItems: number }> = ({
  autoplay,
  children,
  totalItems,
  label = 'slider',
  navigationStep = 'page',
  slideTransition = {
    speed: 400,
    delay: 0,
    timing: '',
  },
  itemsPerPage = {
    desktop: 5,
    tablet: 3,
    phone: 1,
  },
}) => {
  const { device } = useDevice()
  const resolvedNavigationStep =
    navigationStep === 'page' ? itemsPerPage[device] : navigationStep

  const [state, dispatch] = useReducer(sliderContextReducer, {
    slideWidth: 100 / totalItems,
    slidesPerPage: itemsPerPage[device],
    currentSlide: 0,
    transform: 0,
    navigationStep: resolvedNavigationStep,
    slideTransition,
    itemsPerPage,
    label,
    autoplay,
    totalItems,
    isPageNavigationStep: navigationStep === 'page',
    isOnTouchMove: false,
  })

  return (
    <SliderStateContext.Provider value={state}>
      <SliderDispatchContext.Provider value={dispatch}>
        {children}
      </SliderDispatchContext.Provider>
    </SliderStateContext.Provider>
  )
}

function useSliderState() {
  const context = useContext(SliderStateContext)
  if (context === undefined) {
    throw new Error(
      'useSliderState must be used within a SliderContextProvider'
    )
  }
  return context
}

function useSliderDispatch() {
  const context = useContext(SliderDispatchContext)

  if (context === undefined) {
    throw new Error(
      'useSliderDispatch must be used within a SliderContextProvider'
    )
  }
  return context
}

export { SliderContextProvider, useSliderDispatch, useSliderState }

```


[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 store-on-localhost/src/monobloco/components/new/SliderLayout/hooks/useTouchHandlers.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

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

import { useSliderControls } from './useSliderControls'
import { useSliderDispatch, useSliderState } from '../components/SliderContext'

const SWIPE_THRESHOLD = 75

export const useTouchHandlers = ({ infinite }: { infinite: boolean }) => {
  const dispatch = useSliderDispatch()
  const { transform } = useSliderState()
  const { goForward, goBack } = useSliderControls(infinite)

  const [touchState, setTouchState] = useState({
    touchStartX: 0,
    touchInitialTransform: transform,
  })

  const onTouchStart = (e: React.TouchEvent) => {
    const startX = e.touches[0].clientX
    setTouchState({ touchStartX: startX, touchInitialTransform: transform })
  }

  const onTouchMove = (e: React.TouchEvent) => {
    const currentX = e.touches[0].clientX

    const newTransform =
      touchState.touchInitialTransform +
      (currentX - touchState.touchStartX) / 100

    dispatch({
      type: 'TOUCH',
      payload: { transform: newTransform, isOnTouchMove: true },
    })
  }

  const onTouchEnd = (e: React.TouchEvent) => {
    const endX = e.changedTouches[0].clientX
    const delta = endX - touchState.touchStartX

    if (Math.abs(delta) > SWIPE_THRESHOLD) {
      // Swipe from left to right
      if (delta > 0) {
        goBack()
      }

      // Swipe from right to left
      if (delta < 0) {
        goForward()
      }
    } else {
      // Ignore the swipe if the SWIPE_THRESHOLD is not reached
      dispatch({
        type: 'TOUCH',
        payload: {
          transform: touchState.touchInitialTransform,
          isOnTouchMove: false,
        },
      })
    }

    setTouchState({ touchStartX: 0, touchInitialTransform: transform })
    dispatch({
      type: 'TOUCH',
      payload: {
        isOnTouchMove: false,
      },
    })
  }

  return { onTouchEnd, onTouchStart, onTouchMove }
}

```


[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 store-on-localhost/src/monobloco/components/new/SliderLayout/hooks/useScreenResize.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { useEffect } from 'react'
import useDevice from '../../DeviceDetector/useDevice'

import { useSliderDispatch, useSliderState } from '../components/SliderContext'

export const useScreenResize = (infinite: boolean) => {
  const {
    navigationStep,
    isPageNavigationStep,
    itemsPerPage,
  } = useSliderState()
  const { device } = useDevice()
  const dispatch = useSliderDispatch()

  useEffect(() => {
    const setNewState = (shouldCorrectItemPosition: boolean) => {
      dispatch({
        type: 'ADJUST_ON_RESIZE',
        payload: {
          shouldCorrectItemPosition,
          slidesPerPage: itemsPerPage[device],
          navigationStep: isPageNavigationStep
            ? itemsPerPage[device]
            : navigationStep,
        },
      })
    }
    const onResize = (value?: UIEvent): void => {
      setNewState(!value || infinite)
    }
    setNewState(false)

    window.addEventListener('resize', onResize)
    return () => window.removeEventListener('resize', onResize)
  }, [
    infinite,
    dispatch,
    itemsPerPage,
    device,
    isPageNavigationStep,
    navigationStep,
  ])
}

```


[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 store-on-localhost/src/monobloco/components/new/SliderLayout/hooks/useAutoplay.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { useEffect } from 'react'
import { useSliderState } from '../components/SliderContext'
import { useSliderControls } from './useSliderControls'
import useHovering from './useHovering'

export const useAutoplay = (
  infinite: boolean,
  containerRef: React.RefObject<HTMLDivElement>
) => {
  const { autoplay } = useSliderState()
  const { isHovering } = useHovering(containerRef)

  const shouldStop = autoplay && autoplay.stopOnHover && isHovering

  const { goForward } = useSliderControls(infinite)

  useEffect(() => {
    if (!autoplay) {
      return
    }

    const timeout = setTimeout(() => {
      goForward()
    }, autoplay.timeout)

    shouldStop && clearTimeout(timeout)

    return () => clearTimeout(timeout)
  }, [goForward, shouldStop, autoplay])
}

```


[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 store-on-localhost/src/monobloco/components/new/SliderLayout/hooks/useSliderControls.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { useSliderDispatch, useSliderState } from '../components/SliderContext'

export const useSliderControls = (infinite: boolean) => {
  const {
    currentSlide,
    slidesPerPage,
    slideWidth,
    totalItems,
    navigationStep,
  } = useSliderState()
  const dispatch = useSliderDispatch()

  const goBack = () => {
    let nextSlide = 0
    let nextTransformValue = 0

    const nextMaximumSlides = currentSlide - navigationStep

    if (nextMaximumSlides >= 0) {
      /** Have more slides hidden on left */
      nextSlide = nextMaximumSlides
      nextTransformValue = -(slideWidth * nextSlide)
    } else if (nextMaximumSlides < 0 && currentSlide !== 0) {
      /** Prevent overslide */
      nextSlide = 0
      nextTransformValue = 0
    } else if (infinite) {
      /** If reach start, go to last slide */
      nextSlide = totalItems - slidesPerPage
      nextTransformValue = -(slideWidth * nextSlide)
    }

    dispatch({
      type: 'SLIDE',
      payload: {
        transform: nextTransformValue,
        currentSlide: nextSlide,
      },
    })
  }

  const goForward = () => {
    let nextSlides = 0
    let nextPosition = 0

    const nextMaximumSlides = currentSlide + 1 + slidesPerPage + navigationStep

    if (nextMaximumSlides <= totalItems) {
      /** Have more slides hidden on right */
      nextSlides = currentSlide + navigationStep
      nextPosition = -(slideWidth * nextSlides)
    } else if (
      nextMaximumSlides > totalItems &&
      currentSlide !== totalItems - slidesPerPage
    ) {
      /** Prevent overslide */
      nextSlides = totalItems - slidesPerPage
      nextPosition = -(slideWidth * nextSlides)
    } else if (infinite) {
      /** if reach end go to first slide */
      nextSlides = 0
      nextPosition = -(slideWidth * nextSlides)
    }

    dispatch({
      type: 'SLIDE',
      payload: {
        transform: nextPosition,
        currentSlide: nextSlides,
      },
    })
  }

  return { goForward, goBack }
}

```


[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 store-on-localhost/src/monobloco/components/new/SliderLayout/hooks/useKeyboardArrows.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

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

/**
 * Adds event listener to call passed functions by pressing the left or right arrows
 * @param onLeft Function that is called on left arrow key press
 * @param onRight Function that is called on arrow arrow key press
 */
const useKeyboardArrows = (onLeft: () => void, onRight: () => void) => {
  useEffect(() => {
    const onKeyDown = (event: KeyboardEvent) => {
      event.code === 'ArrowLeft' && onLeft()
      event.code === 'ArrowRight' && onRight()
    }

    window.addEventListener('keydown', onKeyDown)

    return () => {
      window.removeEventListener('keydown', onKeyDown)
    }
  }, [onLeft, onRight])
}

export default useKeyboardArrows

```


[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 store-on-localhost/src/monobloco/components/new/SliderLayout/hooks/useHovering.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { useState, useEffect } from 'react'

/**
 * Hook that returns the hover state of a passed ref
 * @param ref React ref
 */
const useHovering = (ref: React.RefObject<HTMLDivElement>) => {
  const [isHovering, setHovering] = useState(false)

  const onMouseEnter = () => setHovering(true)
  const onMouseLeave = () => setHovering(false)

  useEffect(() => {
    if (ref && ref.current) {
      ref.current.addEventListener('mouseenter', onMouseEnter)
      ref.current.addEventListener('mouseleave', onMouseLeave)
    }

    return () => {
      const { current } = ref
      if (current) {
        current.removeEventListener('mouseenter', onMouseEnter)
        current.removeEventListener('mouseleave', onMouseLeave)
      }
    }
  }, [ref])

  return { isHovering }
}

export default useHovering

```


[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 store-on-localhost/src/monobloco/components/new/AddToCartButton/typings/vtex.checkout-resources.d.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.checkout-resources/Mutations'
declare module 'vtex.checkout-resources/Utils'

```


[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 store-on-localhost/src/monobloco/components/new/AddToCartButton/typings/global.d.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
interface OrderForm {
  items: Item[]
  shipping?: Shipping
  marketingData: Maybe<OrderFormMarketingData>
  totalizers: Array<{
    id: string
    name: string
    value: number
  }>
  value: number
  messages: OrderFormMessages
}

interface OrderFormItemInput {
  id?: number
  index?: number
  quantity?: number
  seller?: string
  uniqueId?: string
  options?: AssemblyOptionInput[]
}

interface AssemblyOptionItem {
  id: string
  quantity: number
  seller: string
  initialQuantity: number
  choiceType: 'SINGLE' | 'TOGGLE' | 'MULTIPLE'
  name: string
  price: number
  children: Record<string, AssemblyOptionItem[]> | null
}

interface BuyButtonContextState {
  clicked: boolean
}

interface ProductContextState {
  selectedItem: Maybe<ProductContextItem>
  product: Maybe<Product>
  selectedQuantity: number
  skuSelector: {
    isVisible: boolean
    areAllVariationsSelected: boolean
  }
  buyButton: BuyButtonContextState
  assemblyOptions: {
    items: Record<string, AssemblyOptionItem[]>
    inputValues: Record<string, InputValues>
    areGroupsValid: Record<string, boolean>
  }
}

type InputValues = Record<string, string>

interface Product {
  cacheId: string
  productName: string
  productId: string
  description: string
  titleTag: string
  metaTagDescription: string
  linkText: string
  productReference: string
  categoryId: string
  categoriesIds: string[]
  categories: string[]
  categoryTree: {
    id: string
    name: string
    href: string
  }[]
  brand: string
  brandId: string
  properties: {
    name: string
    values: string
  }[]
  specificationGroups: {
    name: string
    specifications: {
      name: string
      values: string[]
    }[]
  }[]
  items: ProductContextItem[]
  itemMetadata: {
    items: ItemMetadata[]
    priceTable: any[]
  }
}

interface ProductContextItem {
  itemId: string
  name: string
  nameComplete: string
  complementName: string
  ean: string
  referenceId: {
    Key: string
    Value: string
  }[]
  measurementUnit: string
  unitMultiplier: number
  images: {
    imageId: string
    imageLabel: string
    imageTag: string
    imageUrl: string
    imageText: string
  }[]
  videos: {
    videoUrl: string
  }[]
  sellers: Seller[]
  variations: {
    name: string
    values: string[]
  }[]
  productClusters: {
    id: string
    name: string
  }[]
  clusterHighlights: {
    id: string
    name: string
  }[]
}

interface Seller {
  sellerId: string
  sellerName: string
  addToCartLink: string
  sellerDefault: string
  commertialOffer: {
    discountHighlights: {
      name: string
    }[]
    teasers: {
      name: string
    }[]
    Price: number
    ListPrice: number
    PriceWithoutDiscount: number
    RewardValue: number
    PriceValidUntil: string
    AvailableQuantity: number
    Tax: number
    CacheVersionUsedToCallCheckout: string
  }
}

interface ItemMetadata {
  items: {
    id: string
    name: string
    imageUrl: string
    seller: string
    assemblyOptions: {
      id: string
      name: string
      required: boolean
      inputValues: InputValue[]
      composition: Composition | null
    }
  }[]
  priceTable: {
    type: string
    values: {
      id: string
      assemblyId: string
      price: number | null
    }[]
  }[]
}

type InputValue = TextInputValue | BooleanInputValue | OptionsInputValue

enum InputValueType {
  'TEXT' = 'TEXT',
  'BOOLEAN' = 'BOOLEAN',
  'OPTIONS' = 'OPTIONS',
}

interface TextInputValue {
  type: InputValueType.TEXT
  defaultValue: ''
  label: string
  maxLength: number
  domain: null
}

interface BooleanInputValue {
  type: InputValueType.BOOLEAN
  defaultValue: boolean
  label: string
  maxLength: null
  domain: null
}

interface OptionsInputValue {
  type: InputValueType.OPTIONS
  defaultValue: string
  label: string
  maxLength: null
  domain: string[]
}

interface Composition {
  minQuantity: number
  maxQuantity: number
  items: {
    id: string
    minQuantity: number
    maxQuantity: number
    priceTable: string
    seller: string
    initialQuantity: number
  }[]
}

interface OrderFormMarketingData {
  utmCampaign?: string
  utmMedium?: string
  utmSource?: string
  utmiCampaign?: string
  utmiPart?: string
  utmipage?: string
  marketingTags?: string
  coupon?: string
}

interface Shipping {
  availableAddresses: CheckoutAddress[]
  countries: string[]
  deliveryOptions: DeliveryOption[]
  selectedAddress: CheckoutAddress | null
}

interface CheckoutAddress {
  addressId: string
  addressType: string
  city: string | null
  complement: string | null
  country: string
  geoCoordinates: number[]
  neighborhood: string | null
  number: string | null
  postalCode: string | null
  receiverName: string | null
  reference: string | null
  state: string | null
  street: string | null
}

interface DeliveryOption {
  id: string
  price: number
  estimate: string
  isSelected: boolean
}

interface OrderFormMessages {
  couponMessages: Message[]
  generalMessages: Message[]
}

interface Message {
  code: string
  text: string
  status: string
}

interface AssemblyOptionInput {
  id?: string
  quantity?: number
  assemblyId: string
  seller?: string
  inputValues?: Record<string, string | boolean>
  options?: AssemblyOptionInput[]
}

interface Item {
  additionalInfo: {
    brandName: string
    brandId: string
    offeringInfo: any | null
    offeringType: any | null
    offeringTypeId: any | null
  }
  availability: string
  detailUrl: string
  id: string
  imageUrls?: {
    at1x: string
    at2x: string
    at3x: string
  }
  listPrice: number
  measurementUnit: string
  name: string
  price: number
  productId: string
  quantity: number
  sellingPrice: number
  skuName: string
  skuSpecifications: SKUSpecification[]
  uniqueId: string
}

interface SKUSpecification {
  fieldName: string
  fieldValues: 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 store-on-localhost/src/monobloco/components/new/AddToCartButton/__tests__/index.test.tsx from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```tsx
describe('Orders List Scenarios', () => {
  it('should work', () => {
    expect(1).toBe(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 store-on-localhost/src/monobloco/components/new/AddToCartButton/modules/compareObjects.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
export function compareObjects(obj1: any, obj2: any) {
  //Loop through properties in object 1
  for (const p in obj1) {
    //Check property exists on both objects
    if (obj1.hasOwnProperty(p) !== obj2.hasOwnProperty(p)) return false

    switch (typeof obj1[p]) {
      //Deep compare objects
      case 'object':
        if (!compareObjects(obj1[p], obj2[p])) return false
        break
      //Compare function code
      case 'function':
        if (
          typeof obj2[p] == 'undefined' ||
          (p != 'compare' && obj1[p].toString() != obj2[p].toString())
        )
          return false
        break
      //Compare values
      default:
        if (obj1[p] != obj2[p]) return false
    }
  }

  //Check object 2 for any extra properties
  for (const p in obj2) {
    if (typeof obj1[p] == 'undefined') return false
  }
  return 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 store-on-localhost/src/monobloco/components/new/AddToCartButton/modules/catalogItemToCart.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { path } from 'ramda'

import {
  transformAssemblyOptions,
  sumAssembliesPrice,
  ParsedAssemblyOptionsMeta,
  Option,
} from './assemblyOptions'

interface MapCatalogItemToCartArgs {
  product: Maybe<Product>
  selectedItem: Maybe<ProductContextItem>
  selectedQuantity: number
  selectedSeller: any
  assemblyOptions?: {
    items: Record<string, AssemblyOptionItem[]>
    inputValues: Record<string, Record<string, string>>
    areGroupsValid: Record<string, boolean>
  }
}

export interface MapCatalogItemToCartReturn {
  index: 0
  quantity: number
  detailUrl: string
  name: string
  brand: string
  category: string
  productRefId: string
  seller: any
  price: number
  listPrice: number
  variant: string
  skuId: string
  imageUrl: string | undefined
  sellingPriceWithAssemblies: number
  options: Option[]
  assemblyOptions: ParsedAssemblyOptionsMeta
}

export function mapCatalogItemToCart({
  product,
  selectedItem,
  selectedQuantity,
  selectedSeller,
  assemblyOptions,
}: MapCatalogItemToCartArgs): MapCatalogItemToCartReturn[] {
  return (
    product &&
    selectedItem &&
    selectedSeller &&
    selectedSeller.commertialOffer && [
      {
        index: 0,
        quantity: selectedQuantity,
        detailUrl: `/${product.linkText}/p`,
        name: product.productName,
        brand: product.brand,
        category:
          product.categories && product.categories.length > 0
            ? product.categories[0]
            : '',
        productRefId: product.productReference,
        seller: selectedSeller.sellerId,
        price: selectedSeller.commertialOffer.Price,
        listPrice: selectedSeller.commertialOffer.ListPrice,
        variant: selectedItem.name,
        skuId: selectedItem.itemId,
        imageUrl: path(['images', '0', 'imageUrl'], selectedItem),
        ...transformAssemblyOptions(
          path(['items'], assemblyOptions),
          path(['inputValues'], assemblyOptions),
          selectedSeller.commertialOffer.Price,
          selectedQuantity
        ),
        sellingPriceWithAssemblies:
          selectedSeller.commertialOffer.Price +
          sumAssembliesPrice(path(['items'], assemblyOptions) || {}),
      },
    ]
  )
}

```


[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 store-on-localhost/src/monobloco/components/new/AddToCartButton/modules/assemblyOptions.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
type GroupId = string
type GroupTypes = 'SINGLE' | 'TOGGLE' | 'MULTIPLE'

export function sumAssembliesPrice(
  assemblyOptions: Record<GroupId, AssemblyOptionItem[]>
) {
  const cleanAssemblies = assemblyOptions || {}
  const assembliesGroupItems = Object.values(cleanAssemblies)
  return assembliesGroupItems.reduce<number>(
    (sum: number, groupItems: AssemblyOptionItem[]) => {
      const groupPrice = groupItems.reduce<number>((groupSum, item) => {
        const childrenPrice: number = item.children
          ? sumAssembliesPrice(item.children)
          : 0
        const itemCost = item.price * item.quantity
        return groupSum + itemCost + childrenPrice * item.quantity
      }, 0)
      return groupPrice + sum
    },
    0
  )
}

type InputValue = Record<string, string | boolean>

export interface AssemblyOptions {
  items: Record<GroupId, AssemblyOptionItem[]>
  inputValues: Record<GroupId, InputValue>
  areGroupsValid: Record<string, boolean>
}

export type Option = ItemOption

export interface ItemOption {
  assemblyId: string
  id?: string
  quantity?: number
  seller?: string
  options?: Option[]
  inputValues?: InputValue
}

interface AddedItem {
  id: string
  name: string
  quantity: number
  sellingPrice: number
  sellingPriceWithAssemblies: number
  assemblyOptions?: ParsedAssemblyOptionsMeta
}

interface CartAddedOption {
  normalizedQuantity: number
  extraQuantity: number
  choiceType: GroupTypes
  item: AddedItem
}

interface CartRemovedOption {
  name: string
  initialQuantity: number
  removedQuantity: number
}

export interface ParsedAssemblyOptionsMeta {
  added: CartAddedOption[]
  removed: CartRemovedOption[]
  parentPrice: number
}

interface ParsedAssemblyOptions {
  options: Option[]
  assemblyOptions: ParsedAssemblyOptionsMeta
}

export function transformAssemblyOptions(
  assemblyOptionsItems: Record<GroupId, AssemblyOptionItem[]> = {},
  inputValues: Record<GroupId, InputValue> = {},
  parentPrice: number,
  parentQuantity: number
): ParsedAssemblyOptions {
  // contains options sent as arguments to graphql mutation
  const options: Option[] = []

  // array with added assemblies data to show in minicart optimistic preview
  const added: CartAddedOption[] = []

  // array with removed assemblies data to show in minicart optimistic preview
  const removed: CartRemovedOption[] = []

  const assemblyItemsKeys: GroupId[] = Object.keys(assemblyOptionsItems)

  for (const groupId of assemblyItemsKeys) {
    const items = assemblyOptionsItems[groupId]
    for (const item of items) {
      const childrenAddedData = item.children
        ? transformAssemblyOptions(
            item.children,
            {},
            item.price,
            item.quantity * parentQuantity
          )
        : null

      const {
        options: childrenOptions,
        assemblyOptions: childrenAssemblyOptions,
      } = childrenAddedData || {
        options: undefined,
        assemblyOptions: undefined,
      }

      const { quantity, initialQuantity } = item

      if (quantity >= initialQuantity && quantity > 0) {
        added.push({
          normalizedQuantity: quantity,
          extraQuantity: quantity - initialQuantity,
          choiceType: item.choiceType,
          item: {
            name: item.name,
            sellingPrice: item.price,
            quantity,
            sellingPriceWithAssemblies:
              item.price + sumAssembliesPrice(item.children || {}),
            id: item.id,
            ...(childrenAssemblyOptions
              ? { assemblyOptions: childrenAssemblyOptions }
              : {}),
          },
        })
      }

      if (quantity < initialQuantity && item.choiceType === 'TOGGLE') {
        removed.push({
          name: item.name,
          initialQuantity,
          removedQuantity: initialQuantity - quantity,
        })
      }

      const addedChildrenCount = childrenAddedData
        ? childrenAddedData.options.length
        : 0

      if (quantity !== initialQuantity || addedChildrenCount > 0) {
        options.push({
          assemblyId: groupId,
          id: item.id,
          quantity: quantity * parentQuantity,
          seller: item.seller,
          ...(childrenOptions && childrenOptions.length > 0
            ? { options: childrenOptions }
            : {}),
        })
      }
    }
  }

  const assemblyInputValuesKeys: GroupId[] = Object.keys(inputValues)

  for (const groupId of assemblyInputValuesKeys) {
    const inputValuesObject = inputValues[groupId] || {}
    if (Object.keys(inputValuesObject).length > 0) {
      options.push({
        assemblyId: groupId,
        inputValues: inputValues[groupId],
      })
    }
  }

  return {
    options,
    assemblyOptions: {
      added,
      removed,
      parentPrice,
    },
  }
}

```


[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 store-on-localhost/src/monobloco/components/new/AddToCartButton/typings/vtex.product-context/ProductDispatchContext.d.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.product-context/ProductDispatchContext'

```


[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 store-on-localhost/src/monobloco/components/new/ResponsiveValues/typings/vtex.device-detector.d.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.device-detector' {
  interface Device {
    device: 'phone' | 'tablet' | 'desktop'
    isMobile: boolean
  }

  export function useDevice(): Device
}

```


[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 store-on-localhost/src/monobloco/components/new/ResponsiveValues/__tests__/normalizeResponsiveInput.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
import {
  isResponsiveInput,
  normalizeResponsiveInput,
} from '../hooks/normalizeResponsiveInput'

console.warn = jest.fn()

describe('useResponsiveValue', () => {
  afterEach(() => {
    jest.clearAllMocks()
  })
  describe('isResponsiveInput', () => {
    it('should return false if passed null', () => {
      const value = null

      expect(isResponsiveInput(value)).toBe(false)
    })
    it('should return false if passed a non-object', () => {
      const value = 2

      expect(isResponsiveInput(value)).toBe(false)
    })
    it('should return true if passed an object with a single device', () => {
      const value = {
        desktop: 1,
      }

      expect(isResponsiveInput(value)).toBe(true)
    })
    it('should return true if passed an object with all devices', () => {
      const value = {
        desktop: 1,
        mobile: 1,
        tablet: 1,
        phone: 1,
      }

      expect(isResponsiveInput(value)).toBe(true)
    })
    it('should return false if passed an object with an extraneous key', () => {
      const value = {
        desktop: 1,
        mobile: 1,
        tablet: 1,
        phone: 1,
        oops: 0,
      }

      expect(isResponsiveInput(value)).toBe(false)
    })
  })

  describe('responsiveValue', () => {
    it('should complain if "mobile" is defined along with "tablet"', () => {
      const value = {
        tablet: 1,
        phone: 1,
        mobile: 2,
        desktop: 3,
      }

      const result = normalizeResponsiveInput(value)

      expect(console.warn).toBeCalled()

      expect(result).toStrictEqual({
        phone: 1,
        tablet: 1,
        desktop: 3,
      })
    })

    it('should return an object with equal keys if the input has all the parameters', () => {
      const value = {
        desktop: 1,
        tablet: 2,
        phone: 3,
      }

      expect(normalizeResponsiveInput(value)).toStrictEqual({
        desktop: 1,
        tablet: 2,
        phone: 3,
      })
    })

    describe('fallbacks', () => {
      describe('single values should populate the object', () => {
        it('should work with straight values', () => {
          const value = 1

          expect(normalizeResponsiveInput(value)).toStrictEqual({
            desktop: 1,
            tablet: 1,
            phone: 1,
          })
        })
        it('should work with "desktop"', () => {
          const value = { desktop: 1 }

          expect(normalizeResponsiveInput(value)).toStrictEqual({
            desktop: 1,
            tablet: 1,
            phone: 1,
          })
        })
        it('should work with "mobile"', () => {
          const value = { mobile: 1 }

          expect(normalizeResponsiveInput(value)).toStrictEqual({
            desktop: 1,
            tablet: 1,
            phone: 1,
          })
        })
        it('should work with "tablet"', () => {
          const value = { tablet: 1 }

          expect(normalizeResponsiveInput(value)).toStrictEqual({
            desktop: 1,
            tablet: 1,
            phone: 1,
          })
        })
        it('should work with "phone"', () => {
          const value = {
            phone: 1,
          }

          expect(normalizeResponsiveInput(value)).toStrictEqual({
            desktop: 1,
            tablet: 1,
            phone: 1,
          })
        })
      })
      it('tablet should fallback to desktop instead of phone, when both are defined', () => {
        const value = {
          desktop: 1,
          phone: 2,
        }

        expect(normalizeResponsiveInput(value)).toStrictEqual({
          desktop: 1,
          tablet: 1,
          phone: 2,
        })
      })
      it('desktop should fallback to tablet instead of phone, when both are defined', () => {
        const value = {
          tablet: 1,
          phone: 2,
        }

        expect(normalizeResponsiveInput(value)).toStrictEqual({
          desktop: 1,
          tablet: 1,
          phone: 2,
        })
      })
      it('phone should fallback to tablet instead of desktop, when both are defined', () => {
        const value = {
          tablet: 1,
          desktop: 2,
        }

        expect(normalizeResponsiveInput(value)).toStrictEqual({
          desktop: 2,
          tablet: 1,
          phone: 1,
        })
      })
      it('tablet should fallback to mobile, ', () => {
        const value = {
          phone: 1,
          mobile: 2,
          desktop: 3,
        }

        expect(normalizeResponsiveInput(value)).toStrictEqual({
          desktop: 3,
          tablet: 2,
          phone: 1,
        })
      })
      it('phone and tablet should override mobile', () => {
        const value = {
          phone: 1,
          mobile: 2,
          tablet: 3,
          desktop: 4,
        }

        expect(normalizeResponsiveInput(value)).toStrictEqual({
          phone: 1,
          tablet: 3,
          desktop: 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 store-on-localhost/src/monobloco/components/new/ResponsiveValues/__tests__/useResponsiveValue.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
import {
  useResponsiveValue,
  useResponsiveValues,
} from '../hooks/useResponsiveValue'

/**  TODO: useDevice always returns 'desktop'
 * Multiple devices test cases should be tested */

describe('useResponsiveValue', () => {
  it('should return a single value for the current device', () => {
    const input = {
      desktop: 1,
      mobile: 2,
    }

    const value = useResponsiveValue(input)

    expect(value).toBe(1)
  })

  it('should return a single value if the input is also a single value', () => {
    const input = 1

    const value = useResponsiveValue(input)

    expect(value).toBe(1)
  })
})

describe('useResponsiveValues', () => {
  it('should return the correct values for different keys', () => {
    const input = {
      first: {
        desktop: 1,
        mobile: 2,
      },
      second: {
        desktop: 3,
        mobile: 4,
      },
    }

    const { first, second } = useResponsiveValues(input)

    expect(first).toBe(1)
    expect(second).toBe(3)
  })
})

```


[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 store-on-localhost/src/monobloco/components/new/ResponsiveValues/hooks/normalizeResponsiveInput.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
/** The user is able to input `mobile` as a device (as opposed to `desktop`),
 * but the output will be converted to `phone` and `tablet` */
export enum InputDevices {
  mobile = 'mobile',
  phone = 'phone',
  tablet = 'tablet',
  desktop = 'desktop',
}

export enum OutputDevices {
  phone = 'phone',
  tablet = 'tablet',
  desktop = 'desktop',
}

export type ResponsiveInput<T> = { [P in keyof typeof InputDevices]?: T }
export type MaybeResponsiveInput<T> = T | ResponsiveInput<T>

export type ResponsiveOutput<T> = { [P in keyof typeof OutputDevices]: T }

//eslint-disable-next-line @typescript-eslint/no-explicit-any
const isUndefined = (value: any) => typeof value === 'undefined'

/** Returns the first argument that is not undefined */
const firstDefinedValue = <T>(...values: T[]): T =>
  values.find(value => !isUndefined(value)) as T

/** Returns the first value of the input that is not undefined,
 * given a sorted array of keys */
const fallbackOrder = <T>(
  input: ResponsiveInput<T>,
  devices: (keyof ResponsiveInput<T>)[]
) => firstDefinedValue(...devices.map(key => input[key])) as T

/** Checks if the input value is a ResponsiveInput type (an object with
 * one or more keys of Device type--e.g. `desktop`, `mobile`) */
//eslint-disable-next-line @typescript-eslint/no-explicit-any
export const isResponsiveInput = <T>(value: any): value is ResponsiveInput<T> =>
  Boolean(
    value &&
      Object.keys(InputDevices).some(device => !isUndefined(value[device])) &&
      Object.keys(value).every(key => key in InputDevices)
  )

const showWarnings = <T>(value: ResponsiveInput<T>) => {
  if (!isUndefined(value.mobile)) {
    let devices: string[] = []
    if (!isUndefined(value.phone)) {
      devices.push('"phone"')
    }
    if (!isUndefined(value.tablet)) {
      devices.push('"tablet"')
    }
    if (devices.length === 0) {
      return
    }
    const devicesLabel = devices.join(' and ')
    console.warn(
      `You are defining a "mobile" value along with ${devicesLabel} ${
        devices.length > 1 ? 'values' : 'value'
      } in the props of a component. Please use "phone" and "tablet" in this case.`
    )
  }
}

/** Takes an input that might be a responsive object or not
 * (i.e. either "prop: {mobile: 1, desktop:2}" or just "prop: 2")
 * and returns an object of the values broken down into devices
 * (i.e. {phone: 1, tablet: 1, desktop: 2})
 */
export const normalizeResponsiveInput = <T>(
  value: MaybeResponsiveInput<T>
): ResponsiveOutput<T> => {
  if (isResponsiveInput(value)) {
    const { mobile, tablet, phone, desktop } = InputDevices

    showWarnings(value)

    return {
      phone: fallbackOrder(value, [phone, mobile, tablet, desktop]),
      tablet: fallbackOrder(value, [tablet, mobile, desktop, phone]),
      desktop: fallbackOrder(value, [desktop, tablet, phone, mobile]),
    }
  }

  return {
    phone: value,
    tablet: value,
    desktop: 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 store-on-localhost/src/monobloco/components/new/ResponsiveValues/hooks/useResponsiveValue.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
import useDevice from '../../DeviceDetector/useDevice'
import {
  normalizeResponsiveInput,
  MaybeResponsiveInput,
} from './normalizeResponsiveInput'

const useResponsiveValue = <T>(input: MaybeResponsiveInput<T>): T => {
  const { device } = useDevice()

  return normalizeResponsiveInput(input)[device]
}

const useResponsiveValues = <U>(input: U): U => {
  const { device } = useDevice()

  const keys = Object.keys(input) as (keyof U)[]

  let returnValue = { ...input }

  keys.forEach(key => {
    returnValue[key] = normalizeResponsiveInput(input[key])[device]
  })

  return returnValue
}

export { useResponsiveValue, useResponsiveValues }

```


[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 store-on-localhost/src/monobloco/components/new/Menu/constants/Options.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript

export default {
  EXTERNAL: 'external',
  INTERNAL: 'internal',
  LEFT: 'left',
  MIDDLE: 'middle',
  RIGHT: 'right',
}
```


[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 store-on-localhost/src/monobloco/components/new/Menu/typings/vtex.css-handles.d.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.css-handles' {
  export const useCssHandles
  export const withCssHandles
}
```


[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 store-on-localhost/src/monobloco/components/new/Menu/typings/vtex.store-components.d.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.store-components' {
  export const Container
}
```


[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 store-on-localhost/src/monobloco/components/new/Menu/typings/vtex.render-runtime.d.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
/* 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
  }

  interface ChildBlock<BlockProps> {
    props: BlockProps
  }

  export const ExtensionPoint: ComponentType<ExtensionPointProps>
  export const useChildBlock: <BlockProps>({id}: {id: string}) => ChildBlock<BlockProps> | null
  export const Helmet: ReactElement
  export const Link: ReactType
  export const NoSSR: ReactElement
  export const RenderContextConsumer: any
  export const TreePathContextConsumer: any
  export const useTreePath: any
  export const useRuntime: any
  export const canUseDOM: boolean
  export const withRuntimeContext: <TOriginalProps extends {}>(
    Component: ComponentType<TOriginalProps & RenderContextProps>
  ) => ComponentType<TOriginalProps>

  export const withSession: <TOriginalProps extends {}>(
    Component: ComponentType<TOriginalProps & RenderContextProps>
  ) => ComponentType<TOriginalProps>

  export const buildCacheLocator = (app: string, type: string, cacheId: string) => string

  interface RenderComponent<P = {}, S = {}> extends Component<P, S> {
    getCustomMessages?: (locale: string) => any
    schema: ComponentSchema
    getSchema?: (a: any, b: any?) => ComponentSchema
    uiSchema: UISchema
  }

  export interface ComponentsRegistry {
    [component: string]: RenderComponent<any, any>
  }

  export interface Window extends Window {
    __RENDER_7_COMPONENTS__: ComponentsRegistry
  }

  let global: Window
}

```


[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 store-on-localhost/src/monobloco/components/new/Menu/typings/vtex.native-types.d.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.native-types' {
  import { Component } from 'react'
  import { InjectedIntl, WrappedComponentProps } from 'react-intl'

  interface FormatIOMessageParams {
    id: string
    intl: InjectedIntl
  }

  export const formatIOMessage: (params: FormatIOMessageParams) => string

  interface IOMessageProps extends WrappedComponentProps {
    id: string
  }

  export const IOMessage: Component<IOMessageProps>
}

```


[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 store-on-localhost/src/monobloco/components/new/Menu/typings/menu.d.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
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 store-on-localhost/src/monobloco/components/new/Menu/typings/vtex.store-icons.d.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.store-icons' {
  export const Icon
}
```


[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 store-on-localhost/src/monobloco/components/new/Menu/typings/global.d.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

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

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

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

  interface StorefrontElement extends ReactElement {
    schema?: object
    getSchema?(props: P): 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 store-on-localhost/src/monobloco/components/new/Menu/typings/graphql.d.ts from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module '*.graphql' {
  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 store-on-localhost/src/monobloco/components/new/Menu/components/LevelContext.tsx from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```tsx
import { createContext } from 'react'

const LevelContext = createContext(0)

export default LevelContext

```


[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 store-on-localhost/src/monobloco/components/new/Menu/components/MenuContext.tsx from the store-on-localhost VTEX app.

[Assistant]
Here's the implementation:

```tsx
import { createContext } from 'react'

const MenuContext = createContext<MenuContextValue>({
  experimentalOptimizeRendering: false,
  hasTitle: false,
  orientation: 'horizontal',
  textType: 't-body',
})

interface MenuContextValue {
  hasTitle: boolean
  orientation: 'horizontal' | 'vertical'
  textType: string
  experimentalOptimizeRendering?: boolean
}

export default MenuContext

```