get_full_block_name() !== $metadata['name'] || $this->is_feature_enabled() ) { return $settings; } unset( $settings['block_hooks'] ); $settings['supports'] = isset( $settings['supports'] ) && is_array( $settings['supports'] ) ? $settings['supports'] : array(); $settings['supports']['inserter'] = false; return $settings; } /** * Whether the Saved for Later feature is enabled. * * @return bool */ private function is_feature_enabled(): bool { return wc_get_container()->get( ShopperListsController::class )->is_enabled( 'saved-for-later' ); } /** * Seed a default heading inner block on the auto-injected block. * * @param array|null $parsed_hooked_block The parsed hooked block array, or null to suppress insertion. * @param string $hooked_block_type The hooked block type name. * @param string $relative_position Position of the insertion point. * @param array $parsed_anchor_block The anchor block, in parsed block array format. * @return array|null */ public function set_hooked_block_attributes( $parsed_hooked_block, $hooked_block_type, $relative_position, $parsed_anchor_block ) { if ( null === $parsed_hooked_block || 'after' !== $relative_position ) { return $parsed_hooked_block; } if ( ! isset( $parsed_anchor_block['blockName'] ) || 'woocommerce/cart' !== $parsed_anchor_block['blockName'] ) { return $parsed_hooked_block; } // Seed a `core/heading` inner block so freshly-injected instances // ship with the same heading the editor template seeds. We append // unconditionally — extensions are free to hook // `hooked_block_woocommerce/saved-for-later` to add their own // inner blocks, and gating on `empty( innerBlocks )` would silently // suppress our heading whenever any other extension ran first. // // `core/heading` is a static block, so the serialised markup must // match what the editor would have saved (`

…

`) // or it'll fail block validation when the cart page is opened in the // editor. `attrs.content` mirrors what the editor's template seeds // (`{ content, level }`) so the parsed shape round-trips identically; // the value is the raw string because attrs are JSON-encoded into the // block comment and `esc_html()` would corrupt translations whose text // contains `&`, `<`, etc. The matching `null` push onto `innerContent` // is what makes `WP_Block::render()` walk into the heading when // building `$content`. $list_heading = __( 'Saved for later', 'woocommerce' ); $heading_html = '

' . esc_html( $list_heading ) . '

'; if ( ! isset( $parsed_hooked_block['innerBlocks'] ) || ! is_array( $parsed_hooked_block['innerBlocks'] ) ) { $parsed_hooked_block['innerBlocks'] = array(); } $parsed_hooked_block['innerBlocks'][] = array( 'blockName' => 'core/heading', 'attrs' => array( 'level' => 2, 'content' => $list_heading, ), 'innerBlocks' => array(), 'innerHTML' => $heading_html, 'innerContent' => array( $heading_html ), ); if ( ! isset( $parsed_hooked_block['innerContent'] ) || ! is_array( $parsed_hooked_block['innerContent'] ) ) { $parsed_hooked_block['innerContent'] = array(); } $parsed_hooked_block['innerContent'][] = null; return $parsed_hooked_block; } /** * Render the block. * * @param array $attributes Block attributes. * @param string $content Block content. * @param \WP_Block $block Block instance. * @return string Rendered block type output. */ protected function render( $attributes, $content, $block ) { // The block type is always registered, so a block persisted while the // feature was on can still reach render() after it's turned off. Render // nothing in that case. if ( ! $this->is_feature_enabled() ) { return ''; } // Guests have no personal list — bail before enqueuing assets or seeding state. if ( ! is_user_logged_in() ) { return ''; } // Set from render() (not Cart::enqueue_data via has_block()) so it works when this // block is auto-injected via the Block Hooks API and isn't in stored post_content. if ( wc_get_container()->get( LegacyProxy::class )->call_function( 'is_cart' ) ) { $this->asset_data_registry->add( 'cartPageHasSavedForLater', true ); } // Clamp to the 2-6 range the SCSS `@for $i from 2 through 6` loop and // the editor `RangeControl` both support. `absint()` first defends // against a code-editor override (the attribute can be set to any // JSON value there); the `min`/`max` then keep the value within the // range where a `&.columns-#{$i}` rule actually exists. $column_count = min( 6, max( 2, absint( $attributes['columnCount'] ?? 5 ) ) ); wp_enqueue_script_module( $this->get_full_block_name() ); $consent = 'I acknowledge that using private APIs means my theme or plugin will inevitably break in the next version of WooCommerce'; BlocksSharedState::load_store_config( $consent ); BlocksSharedState::load_placeholder_image( $consent ); // `Move to cart` calls into the shared cart store, which expects // `state.cart.items` and friends. Without this load the cart store // would have no hydrated cart and the action would throw on the // first click. BlocksSharedState::load_cart_state( $consent ); $items = $this->prefetch_items(); // Seed the shared shopper-lists store with the rest URL, the // pre-fetched items, and a starter nonce. The starter nonce is // what the cart store also seeds via `state.nonce` — the JS layer // keeps it fresh by reading the `Nonce` response header on every // subsequent request, so this is just the bootstrap value (and // avoids deadlocking mutations that await `isNonceReady` before // any GET has fired). wp_interactivity_state( 'woocommerce/shopper-lists', array( 'restUrl' => get_rest_url(), 'nonce' => wp_create_nonce( 'wc_store_api' ), 'lists' => array( self::LIST_SLUG => array( 'items' => $items, 'isLoading' => false, ), ), ) ); // Templates flow through `wp_interactivity_config` so the JS-side // getters can interpolate them (`%d`, `%s`). Visible strings (empty // state, error, action label) are rendered server-side and toggled // with directives, so they don't need to ride here too. wp_interactivity_config( 'woocommerce/saved-for-later', array( 'quantityLabelTemplate' => $this->get_quantity_label_template(), 'removeLabelTemplate' => $this->get_remove_label_template(), ) ); // `hasShownItems` seeds the per-block context so the empty message // stays hidden for new shoppers who land on a page with nothing // saved. The JS-side watcher flips it to `true` the first time the // list has any items (whether that's the SSR seed or a runtime add // via "Save for later"), and `state.isEmpty` only flips on when the // flag is set *and* the list is currently empty. The flag lives in // the per-block context, so it naturally resets on every full page // load — no extra Store API field or persisted flag needed. // `data-wp-context---notices` seeds the store-notices namespace // alongside the block's own context on the same wrapper. $wrapper_attributes = array( 'class' => 'wc-block-saved-for-later', 'data-wp-interactive' => 'woocommerce/saved-for-later', 'data-wp-context' => (string) wp_json_encode( array( 'hasShownItems' => ! empty( $items ), // `stdClass` so it serialises as `{}`, not `[]` — // iAPI's reactive proxy only fires updates on object // writes, not array expandos. 'pendingKeys' => new \stdClass(), ) ), 'data-wp-context---notices' => 'woocommerce/store-notices::' . (string) wp_json_encode( array( 'notices' => array() ) ), 'data-wp-watch' => 'callbacks.trackShownItems', ); $list_class = sprintf( 'wc-block-saved-for-later__list columns-%d', $column_count ); $ul_inner = $this->render_template_markup() . $this->render_items_markup( $items ) . $this->render_empty_markup(); $before_list = $this->render_header_markup( $content, empty( $items ) ) . ShopperListRenderer::render_interactivity_notices_region( 'wc-block-saved-for-later__notices' ); return ShopperListRenderer::render_grid_wrapper( $wrapper_attributes, $list_class, $ul_inner, $before_list ); } /** * Prefetch the saved-for-later items via `rest_do_request()`. Logged-out * users short-circuit to an empty list — the route requires authentication * and we don't want to fire an API call that's only going to 401. * * @return array> Items in the schema response shape. */ private function prefetch_items(): array { if ( ! is_user_logged_in() ) { return array(); } $request = new \WP_REST_Request( 'GET', '/wc/store/v1/shopper-lists/' . self::LIST_SLUG . '/items' ); $response = rest_do_request( $request ); if ( $response->is_error() ) { $error = $response->as_error(); $message = $error instanceof \WP_Error ? $error->get_error_message() : 'Unknown error'; // Logged at debug level on purpose: prefetch failures are // often transient (network blips, auth refresh races) and // the user-visible behaviour is the empty state — nothing // for ops to act on. Anyone investigating a regression can // flip the WC logger to debug to surface them. wc_get_logger()->debug( sprintf( 'Saved for Later prefetch failed: %s', $message ), array( 'source' => 'saved-for-later', 'data' => array( 'slug' => self::LIST_SLUG ), ) ); return array(); } $data = $response->get_data(); if ( ! is_array( $data ) && ! is_object( $data ) ) { return array(); } // The schema casts `prices` and image entries to stdClass so the // JSON response renders objects, not arrays. Round-trip through // JSON encode/decode to normalise everything to nested arrays so // the SSR markup helpers below can treat fields uniformly. $decoded = json_decode( (string) wp_json_encode( $data ), true ); return is_array( $decoded ) ? $decoded : array(); } /** * The `