* type hooks
* type useStoreCart
* type the rest
* Remove old typedefs
* Specify that the return value from useDispatch is a Promise< void >
* Change return type of removeItem
* If ref.current is undefined then return value without checking shallowEq
* Revert "Specify that the return value from useDispatch is a Promise< void >"
This reverts commit 97863bd584d38024398913a79ce63fa6b964846a.
* Remove type parameter from removeItem and changeCartItemQuantity
* Change action return type to cater for generator functions
* Remove type parameter from addItemToCart
* Add mapped types file to help with actions that are generator functions
* Include addItemToCart in return types of cart actions
* Use custom DispatchFromMap
* Add todos for why we've redefined functionality that exists in Calypso
* update types
* remove fromEntries and use polyfill
* address review
* ignore ts no shadow
* fix test errors
Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
* Fix tslint warnings
* Install @automattic/data-stores to get access to some type generics for use with our data stores.
* improve ts typing of cart-data store.
* fix incorrect rebase conflict resolution.
* add typescript support
* Add type declarations for Cart and CartResponse interfaces
* make sure we’re resolving .ts files as well as .js files on imports
* add more types
* type the cart data store
* Apply suggestions from code review (implement .tsx in configs)
Co-authored-by: Jon Surrell <jon.surrell@automattic.com>
* remove global fetchMock declaration and directly import where used.
* rename type
* remove named action types and just infer by returning action creator values as const
* use interface instead of type
* rename
* renames
* create CartAction type as union of action creator returned types and implement in reducer
* remove unused imports
* refresh package-lock after rebase
* Add base TS config that projects will inherit from
* Add tsconfig for assets/js/data project
* Ignore TS error on cart store registration
We will address this in cooldown when we have time to investigate further
* Add tsc to build step to catch TypeScript errors
* add a separate command for tsc and tweak build command to use
* restore checkJs and allowJs values in config and remove ts check from build command
* Add ts:check-all command
* Add TypeScript checking workflows
* Change triggers for TypeScript workflow
* Use npm ci instead of npm install
* Remove ts:check-all from TypeScript workflow
* Remove TS Check GitHub workflow
* Remove type-defs dir from TS include, and remove ts:check-all script
We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work.
* fix coupon loading issues
* include .ts files only from type-defs folder
Co-authored-by: Jon Surrell <jon.surrell@automattic.com>
Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
* Expose schemas
* Accept strings for select shipping rate
* strings are allowed
* Refactor shipping package to hold it's own state
* Add extension data to cart hook
* Progress but state is broken
* Move state back to hook
* Progress but state is broken
* use shipping hook updates
* Fix re-render issue
* hide x1
* Shipping slot fill
* Working slot fills
* Do not export package
* Update extend usage in unit tests
* update mock test data
* Package per slotfill
* Resolved merge conflicts
* Update assets/js/blocks/cart-checkout/subscriptions-integration.js
Co-authored-by: Seghir Nadir <nadir.seghir@gmail.com>
* rename slot
* deriveSelectedRates return doc
* useCallback in throwError
* final class ExtendRestApi
* spacing
* Move shipping rate selection to package level
* remove const for counts
* Remove schemas from extend
* unused use
* move to a single fill for packages
* add todos
* move subs code
* fix extra extensions
Co-authored-by: Seghir Nadir <nadir.seghir@gmail.com>
* Correct docblock description
* Sync shipping address changes with billing data
* Update inline documentation
* Revert address sync because it fails when shipping is disabled explicitely
* Avoid loading shipping address from customer is shipping is disabled
* Rather than update order from the wc/store/checkout request, update the customer object
This is turn is synced to order, but also allows the cart calcultions to use the posted data. This means that taxes will be updated based on address data even if not displayed on the checkout.
* Add action that combines billing and shipping updates
* Add route for updating billing and shipping address
* Sync billing data to server on change
* Shared constants for billing data
* Skip address update if missing country
* Allow null values to skip formatting
* Add billing to cart schema
* Removed unwanted hooks from previous commit
* Decoding is handled in useStoreCart
* Remove hook
* Make shipping context hold state
* Make billing context hold state
* Add address processors
* Cart does not have billing
* Update tests, remove some unrelated changes affecting the diff
* Revert "Update inline documentation"
This reverts commit 0393f49316de3152c6dcf6fda1192c06a74f1b55.
* Make shippingRatesAreResolving conditonal based on API request
* Shared address processor in cart and checkout
* Rename REST endpoint
* CustomerDataProvider and hook
* Update shipping address type defs
* Rename customer address endpoint, and remove update-shipping
* Update tests
* Fix tests by restoring country validation
* typo
* Update assets/js/base/hooks/cart/use-store-cart.js
Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
* Simplify debounce and request handling
* Remove state from address sync
This will mean billing is "forgotten" if using the checbox, but this greatly simplifies logic.
* Rename shipping rates loading to customer data loading
* Sync based on useStoreCart data
* Made cart API less strict on addresses
* Fix useCheckoutAddress sync
* Add note on currentShippingAsBilling
* Use incoming isCart
* Add more detailed inline comment for shippingAsBilling toggle event
* Combine customer billing and shipping ref
* Update address docblock
* Error handling in pluckAddress
* Fix cart response after rebase
* Update customer tests
* Update src/StoreApi/Routes/CartUpdateCustomer.php
Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
* more setup configuration for rtl
* move default state for cart out of reducer
This also creates a file for default store states, it should make it easier to execute tests in various environments.
* Make sure there’s a default object for cart line item row
* set defaults for cartData
* add fetchMock as a global in eslint config
* add initial cart flow tests
This is just to get the ball rolling, the cart block needs more tests
* fix missing @wordpress/jest-console configs (because I overwrote the original configuration)
* update test because of change in branch
* switch import order
* add globals.d.ts file to declare globals we use.
This is a quick solution to prevent typescript linting warning about `fetchMock`. At some point we could also create a proper interface for it or import the types (if they exist) for the `jest-mock` package.
The new `globals.d.ts` file is excluded from published builds.
* Remove summary from API
* Add wordCountType to assets
* Update packages
* Remove summary from test data
* Featured product uses short desc
* Pass description instead of summary
* Use new Summary Component
* Component and tests
* Increased versititilty of methods
* Update assets/js/base/components/cart-checkout/product-summary/index.js
Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
* Extra tests for html tags
Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
* Return updated cart if there is a conflict (409 response) e.g. item no longer exists
* Receive updated carts
* Update tests and coupon handling
* Further rewording
* disable continue to checkout if item is being removed
* rename isPending and selectors/actions to isPendingDelete
* switch itemPendingDelete params order
* change to watching quantity changes not removal
* yield RECEIVE_REMOVED_ITEM
* update types and add return to select
* update tests
* switch params back
* only delete item after response from server
* update tests
* handle errors and unrelated unmounts
* disable row if is loading
* Switch add to cart events to useStoreCart hook
* Add to cart endpoint
* Inject dependenct schemas
* Feedback, cart items are based on product schema
* Variable typo
* Move hook to base
* Update totals correcrly
* Update tests to use schema/routes class
* Update tests to correctly use schema
* Remove type hint to prevent strict standards error
* add selecting rate resolution state to the cart store
* expose whether rate is being selected on useSelectShippingRate
* Cleanup and refactor ShippingDataProvider
- remove un-needed component and move shipping rates into context provider
- remove error handling (currently the ui/ux for the checkout should result in no errors and any api errors are non-recoverable).
- Add logic for shipping rate selection into context provider and add event emitters for it.
- increment/decrement checkout calculation counts when shipping rates are being selected.
* dispatch checkout error if there is an error
* disable place order button if checkout is calculating or has error
* update doc block
* fix convention for js comment blocks
* Disable authentication for the Store API completely.
This may also resolvewoocommerce/woocommerce-blocks#1991
* Add nonce handling to the abstract route
* Default state
* Add shared controls including nonce api fetch
* Use shared controls
* Hydrate inital nonce
* Update data stores
* Update nonce validation
* Fix tests by setting nonces
* Remove print_r debug
* Revert useStoreCart change
* Add nonce middleware
Co-Authored-By: Darren Ethier <darren@roughsmootheng.in>
* Switch back to apiFetchWithHeaders
* Docs
Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
* add errormessage handling to countryinput (along with storybook)
* add types for react
* Add validation context and implement
* implement validation context for country field validation
* tweak ValidationInputError so that it can receive property name for getting error from
* improve storybook webpack config to pull from tsconfig.json
* update storybook story to cover changes with context
* Wrap Checkout Provider with Validation Context Provider
* add screen-reader-text style to storybook
* add styles for input error validation to text input
* improve styling for ValidationInputError component
* add validation error handling to TotalsCouponCode component
And story
* make sure errors are cleared on successful receive/remove item
* dispatch loading cancellation on catching errors
This is needed because loading would be cancelled before the error is thrown so any error handling after the thrown error will not be able to rely on loading.
* implement validation setting for coupon errors
* add error color to labels on inputs too
* fix borders back and force border color
* remove extra structure and improve validation error with alignment for coupon code
* add aria-describedby for text inputs
* add back in validation context provider to fix rebase issue
* rework validation so it works for both checkout and cart
* Some styling tweaks
* more style fixes
* remove unnecessary method
* make sure new function is included in context defaults
* package.lock update? seems harmless so rolling with it.
* add a hook for throwing errors in a hook callback.
* implement new useThrowError hook
* throw errors when selected shipping rate results in a rest error
* add error handling for various shipping rate error response types
* fix borked merge conflict resolution
* remove throwing error and use correct property for coupons
* add missing default address in use-store-cart
* add missing notices provider
* Include shipping and billing address data in cart schema
* update cart hook (and data api) with new properties from endpoint
* add use-shipping-address hook and implement in use-shipping-rates
* update usages of useShippingRates through code
* update tests for use-shipping-rates
* update use-payment-method-interface and typedef to remove country field
This is provided reliably via the shippingAddress now.
* restore pluck comparison to effect.
Also added some clarification docs for why `iniitalAddress` is not included in the effect dependencies.
* remove billingAddress from cart schema
* clear city and postcode when changing country
* Update REST Api schemas aftere rebase
- CustomerSchema no longer exists
- Added ShippingAddressSchema implemented by Cart and Order schemas
- fix broken js because of bad merge conflict resolution.
* remove duplicate keys
* rework the quantity change generator action so the UI updates quick:
- work in progress - still need to figure out how to debounce API call
- add new action for updating quantity for an item
- don't set cart item as pending while quantity is updating
- this leaves QuantitySelector enabled so user can click more/less
- use receiveCartItemQuantity to update quantity in UI before sending request
* debounce line item quantity first cut:
- use local state for quantity, so ui allows multiple clicks up/down
- debounce store updates (and server/API call)
* correct comment on cart item quantity reducer
* remove recieveCartItemQuantity - no longer needed
* remove delegation for deleted RECEIVE_CART_ITEM_QUANTITY
* only update quantity in component sideffect if it has changed:
- reduces unnecessary renders
* factor out debounced quantity update into cartItem hook (hat tip @senadir)
* use quantity from store, instead of passing in to hook +
+ fix latent bug in useStoreCartItem - the cartItem value is now object:
- was previously single-item array
- (note no client code is using this at present)
* tidy/refactor cart item hook - separate dispatch from select
* remove dud reset of item pending flag (came back in rebase)
* add quantity to StoreCartItem hook return value typedef
* fix js error when adding cart block in editor – cartItem not found
* fix typedef
* fix logic for debouncing
* don’t update quantity on server unnecessarily
Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
* add select shipping endpoint to router
* add select shipping method
* add selected rates to cart
* better select rates
* move schema function to seperate function
* move validation to Cart Controller
* fix wrong session key
* Update shipping/cart endpoints (https://github.com/woocommerce/woocommerce-blocks/pull/1833)
* Items should not have keys in API response
* Include package ID in response (this is just a basic index)
* /cart/select-shipping-rate/package_id
* Add package_id to package array
* Update responses and add shipping-rates to main cart endpoint
* update-shipping endpoint
* Add querying selected shipping rate to the store (https://github.com/woocommerce/woocommerce-blocks/pull/1829)
* add selecting shipping to store
* directly call useSelectShippingRate
* refactor cart keys transformation to reducer
* remove selecting first result and accept selecting
* move update shipping to new endpoint
* pass selected rates down
* select shipping right directly and fix editor issues
* fix some broken prop types
* key -> package id
* Update and fix cart/shipping-rate tests
* fix case for when rates are set
* Update useShippingRates test
* add args to rest endpoint
* move selecting shipping rate logic to hook
* fix some naming issues
* update propTypes
* update action call
* fully watch cart state
* address review issues
* fix prop type issues
* fix issue with rates not loading in checkout
* remove extra package for shipping
* move ShippingCalculatorOptions to outside
Co-authored-by: Mike Jolley <mike.jolley@me.com>
Co-authored-by: Albert Juhé Lluveras <aljullu@gmail.com>
* ensure cart totals update when items are removed (prototype):
- return complete cart object from DELETE cart/items/:key
- use receiveCart on client to update whole cart including total
* move API endpoint for removing cart items to cart controller:
- returns full cart schema so should be part of cart controller
- is now a POST request with param - not strict REST
- fix up client action to use new API
* move API test for removing cart items (API has moved)
* use correct path for remove API in tests (doh!)
* add extra API test for remove_cart_item with bad key => 404 (experiment)
* experiment: delete test_remove_cart_item, does test_remove_bad_cart_item work?
* reinstate test_remove_cart_item with single valid request
* remove unnecessary newline
* tidy comments in PHP api tests, rerun travis?
* remove test_remove_cart_item which may be causing problems
* reinstate troublesome remove cart item api test (experiment):
- see if this works now travis issue is resolved
* whitespace
* show correct total when changing cart item quantity:
- move update cart item quantity API to cart controller
- & return full cart response
- update js action to new API route & receive full cart response
* simplify test_remove_cart_item API test - now just tests a valid remove succeeds
* remove test_update_item (API has moved) +
+ experimentally remove test_remove_bad_cart_item
- testing if cart remove tests interact with each other
* fix tests (🤞) - pass params in body, not as query params
* reinstate test for re-deleting same item
* update API docs - update/delete cart item have moved to /cart
* add response data checks to new cart API tests:
- extra protection against expected 404 "false positives"
* reinstate API test for changing cart item quantity
* fix remove cart item body tests - MIA items return error code, not cart
* fix test - quantity param is int not string
* attempt fix 404ing test_update_item:
- only allow POST, remove trailing `/`
- align array equals for good measure :)
* fix action for update-item - method=POST, now takes body params
* fix response body asserts in test_update_item
* reinstate update_item and delete_item on CartItems controller
* typos + examples in new cart items API docs
* reorder previous cart item docs to minimise diff/churn
* reinstate tabs in docs response example
* Working on store provider
* Working on store provider
* Reducer implementation
* Implement core/notices
* Add notices to store coupon hook with context
* Improve store notice text and styling
* Improve JS side API for notices
* Wrap functions with context additon
* Update test to []
* Implement props feedback and useInstanceId
* Update assets/js/base/context/store-notices-context.js
Co-Authored-By: Darren Ethier <darren@roughsmootheng.in>
* Update assets/js/base/context/store-notices-context.js
Co-Authored-By: Darren Ethier <darren@roughsmootheng.in>
* remove instance id
Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
* first cut - removing an item from cart:
- add actions to cart store for removing an item and keeping track of
pending removal API call
- add reducer logic for storing pending state on an item, and removing
an item
- expose removeCartItem on new useStoreCartItems hook
- hook it up to remove link / trashcan icon in row item
* disable cart quantity picker/remove link while API request in progress:
- expose cart item pending status from store using selector
- use selector to disable quantity related components in line item row
* add typedef for cart items store object provided by hook
* allow user to change quantity of cart items (first cut):
- add action for replacing a cart item in the store
- add generator action for changing quantity
- expose change quantity action on useStoreCartItems hook
- hook up to quantity UI in cart block
(work in progress)
* post-rebase fixes & fix broken typedef:
- rework cart item change quantity callback - now supplies item key like
remove callback
- fix hook StoreCartItem return value typedef - single item with
specified key, was array of all items
- add quantity JSDoc for changeCartItemQuantity action
- remove changeQuantity callback from UI (currently infinite looping)
* fix bug in recieveCartItem reducer - check keys for equality:
- was key === object
* fix invalid url in POST cart/items/quantity request
* hook up cart line item quantity to API:
- remove internal state/ref for QuantitySelector, is now a controlled
component
- call changeQuantity action from QuantitySelector change callback
* QuantitySelector no longer needs a ref to wrangle number input value
* hoist quantity state out of QuantitySelector into story (fix storybook)
* add product sold_individually option to cart item API response
* limit sold_individually items to 1 per cart/order:
- support optional max value in QuantitySelector
- set maximum dependent on sold_individually API field
* prevent user from requesting zero x cart item (API 500 errors):
- add minimum limit to QuantitySelector
- default limit to 1
+ fix bug with limiting to maximum value in number input change handler
* remove useStoreCartItems, zombie hook coming back from rebase 🧟♂️
* address various review feedback:
- inline undefined check, don't use lodash
- quantityInputOnKeyDown callback hook depends on canIncrease/canDecrease
- also removed undefined check for minimum, as minimum has default 0
* use safer typeof check for presence of maximum prop
* first cut - removing an item from cart:
- add actions to cart store for removing an item and keeping track of
pending removal API call
- add reducer logic for storing pending state on an item, and removing
an item
- expose removeCartItem on new useStoreCartItems hook
- hook it up to remove link / trashcan icon in row item
* disable cart quantity picker/remove link while API request in progress:
- expose cart item pending status from store using selector
- use selector to disable quantity related components in line item row
* fix jsdoc - getCartItem returns undefined if not found
* add typedef for cart items store object provided by hook
* fix rebase error - key prop went awol
* orient useStoreCartItem hook to single cart item:
- simplify interface for client component
- isPending bool (was callback)
- removeItem callback no need to specify item key
+ reinstate disabled prop on remove link when updating (lost in rebase)
* move cart item pending state out of cartItems, preserve API state shape:
- pending is now stored as array of keys
- fix isItemQuantityPending selector (now much simpler)
* ensure react knows that our useSelect depends on cartItemKey
* Move coupon code for API requests to body - fixes issues with coupon codes containing special characters
* Use wc_format_coupon_code when applying/removing coupons via the cart endpoint
* Add tests
* useStoreCartCoupons hook
* Apply coupon w/ basic error handling for the fetch
* Basic store specifically for cart data
* Working on error states
* Show error on coupon fail
* removeCoupon action
* Added extra endpoints for more efficient cart queries
* Apply/remove coupons working
* Track applying/removing state
* StoreCartCoupon typedef
* Use coupon code on index
* Remove custom controls definition
* Adjust storecartcoupons mapper and remove ref
* Move cartData defaults and remove ref
* Call API directly, avoid schema lookup
* Improved selectors
* StoreCart typedef
* Split up cart state data and add more typedefs
* Add API tests for apply/remove coupon
* Jest tests
* Move default cart data to constant
* Comment indentation