diff --git a/projects/packages/forms/changelog/add-forms-list-dataviews-table b/projects/packages/forms/changelog/add-forms-list-dataviews-table new file mode 100644 index 000000000000..ad5d6876f24b --- /dev/null +++ b/projects/packages/forms/changelog/add-forms-list-dataviews-table @@ -0,0 +1,4 @@ +Significance: minor +Type: added + +Forms: add reusable forms list to dashboard. diff --git a/projects/packages/forms/src/contact-form/class-jetpack-form-endpoint.php b/projects/packages/forms/src/contact-form/class-jetpack-form-endpoint.php index 21552d641c58..5f0bc4a7f7c8 100644 --- a/projects/packages/forms/src/contact-form/class-jetpack-form-endpoint.php +++ b/projects/packages/forms/src/contact-form/class-jetpack-form-endpoint.php @@ -7,10 +7,19 @@ namespace Automattic\Jetpack\Forms\ContactForm; +use WP_REST_Request; + /** * REST endpoint for the jetpack_form custom post type. */ class Jetpack_Form_Endpoint extends \WP_REST_Posts_Controller { + /** + * Cached map of form_id => entries count for the current request. + * + * @var array|null + */ + private $entries_count_by_form_id = null; + /** * Constructor. */ @@ -18,6 +27,124 @@ public function __construct() { parent::__construct( Contact_Form::POST_TYPE ); } + /** + * Add opt-in dashboard fields. + * + * @return array + */ + public function get_collection_params() { + $params = parent::get_collection_params(); + + // Note: We do not use the built-in WP REST "context" param for this, because it's validated + // against core values (view/embed/edit). This param is for Jetpack Forms dashboard usage only. + $params['jetpack_forms_context'] = array( + 'description' => __( 'Request context for Jetpack Forms. Use "dashboard" to include dashboard-only fields.', 'jetpack-forms' ), + 'type' => 'string', + 'default' => '', + 'enum' => array( '', 'dashboard' ), + 'sanitize_callback' => 'sanitize_key', + ); + + return $params; + } + + /** + * Return a collection of forms. + * + * We override this to compute dashboard aggregate fields in a single pass. + * + * @param WP_REST_Request $request Full details about the request. + * @return \WP_REST_Response|\WP_Error + */ + public function get_items( $request ) { + $response = parent::get_items( $request ); + + if ( is_wp_error( $response ) ) { + return $response; + } + + $forms_context = (string) $request->get_param( 'jetpack_forms_context' ); + if ( 'dashboard' !== $forms_context ) { + return $response; + } + + $forms = $response->get_data(); + if ( ! is_array( $forms ) || empty( $forms ) ) { + return $response; + } + + $form_ids = array(); + foreach ( $forms as $form ) { + if ( isset( $form['id'] ) ) { + $form_ids[] = (int) $form['id']; + } + } + $form_ids = array_values( array_unique( array_filter( $form_ids ) ) ); + + $this->entries_count_by_form_id = $this->get_entries_count_by_form_id( $form_ids ); + + foreach ( $forms as &$form ) { + $form_id = isset( $form['id'] ) ? (int) $form['id'] : 0; + $form['entries_count'] = (int) ( $this->entries_count_by_form_id[ $form_id ] ?? 0 ); + if ( $form_id ) { + $form['edit_url'] = get_edit_post_link( $form_id, 'raw' ); + } + } + + $response->set_data( $forms ); + return $response; + } + + /** + * Batch compute feedback counts for a list of form IDs. + * + * @param int[] $form_ids Form IDs to count entries for. + * @return array Map of form_id => count + */ + private function get_entries_count_by_form_id( array $form_ids ): array { + global $wpdb; + + $form_ids = array_values( array_unique( array_map( 'absint', $form_ids ) ) ); + if ( empty( $form_ids ) ) { + return array(); + } + + // Count only "inbox-visible" feedback statuses. + // Note: This is about feedback (response) statuses, not form post statuses (publish/draft/pending/future/private). + $statuses = array( 'publish', 'draft' ); + + // Cache the grouped counts briefly to avoid repeated DB hits (e.g. on reload / concurrent requests). + sort( $form_ids ); + $cache_key = 'feedback_counts_' . md5( implode( ',', $form_ids ) . '|' . implode( ',', $statuses ) ); + $cache_group = 'jetpack_forms'; + $cached = wp_cache_get( $cache_key, $cache_group ); + if ( false !== $cached && is_array( $cached ) ) { + return $cached; + } + + $args = array_merge( array( Feedback::POST_TYPE ), $form_ids, $statuses ); + + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching + $rows = $wpdb->get_results( + $wpdb->prepare( + "SELECT post_parent, COUNT(1) AS entry_count + FROM {$wpdb->posts} + WHERE post_type = %s + AND post_parent IN (" . implode( ',', array_fill( 0, count( $form_ids ), '%d' ) ) . ') + AND post_status IN (' . implode( ',', array_fill( 0, count( $statuses ), '%s' ) ) . ') + GROUP BY post_parent', + $args + ) + ); + $counts_by_form_id = array(); + foreach ( (array) $rows as $row ) { + $counts_by_form_id[ (int) $row->post_parent ] = (int) $row->entry_count; + } + + wp_cache_set( $cache_key, $counts_by_form_id, $cache_group, 15 ); // 15 seconds. + return $counts_by_form_id; + } + /** * Checks if a given request has access to get items. * diff --git a/projects/packages/forms/src/dashboard/class-dashboard.php b/projects/packages/forms/src/dashboard/class-dashboard.php index 48ba05f9f2b5..90b5a16dd7dc 100644 --- a/projects/packages/forms/src/dashboard/class-dashboard.php +++ b/projects/packages/forms/src/dashboard/class-dashboard.php @@ -141,7 +141,29 @@ public function load_admin_scripts() { $initial_responses_path, $initial_responses_locale_path, ); - $preload_data_raw = array_reduce( $preload_paths, 'rest_preload_api_request', array() ); + + // Only preload the Forms list endpoint when centralized form management is enabled. + if ( Contact_Form_Plugin::has_editor_feature_flag( 'central-form-management' ) ) { + $forms_preload_params = array( + 'context' => 'edit', + 'page' => 1, + 'jetpack_forms_context' => 'dashboard', + 'order' => 'desc', + 'orderby' => 'modified', + 'per_page' => 20, + 'status' => 'publish,draft,pending,future,private', + ); + ksort( $forms_preload_params ); + $preload_paths[] = add_query_arg( $forms_preload_params, '/wp/v2/jetpack-forms' ); + $preload_paths[] = add_query_arg( + array_merge( + $forms_preload_params, + array( '_locale' => 'user' ) + ), + '/wp/v2/jetpack-forms' + ); + } + $preload_data_raw = array_reduce( $preload_paths, 'rest_preload_api_request', array() ); // Normalize keys to match what apiFetch will request (without domain). $preload_data = array(); diff --git a/projects/packages/forms/src/dashboard/components/empty-responses/index.tsx b/projects/packages/forms/src/dashboard/components/empty-responses/index.tsx index dafa76f4f67b..63ca8c7054bc 100644 --- a/projects/packages/forms/src/dashboard/components/empty-responses/index.tsx +++ b/projects/packages/forms/src/dashboard/components/empty-responses/index.tsx @@ -151,7 +151,7 @@ const useInstallAkismet = (): UseInstallAkismetReturn => { }; }; -const EmptyWrapper = ( { heading = '', body = '', actions = null }: EmptyWrapperProps ) => ( +export const EmptyWrapper = ( { heading = '', body = '', actions = null }: EmptyWrapperProps ) => ( { heading && ( diff --git a/projects/packages/forms/src/dashboard/forms/index.tsx b/projects/packages/forms/src/dashboard/forms/index.tsx index af283e90b357..900bd578fd3b 100644 --- a/projects/packages/forms/src/dashboard/forms/index.tsx +++ b/projects/packages/forms/src/dashboard/forms/index.tsx @@ -2,33 +2,139 @@ * External dependencies */ import { JetpackLogo } from '@automattic/jetpack-components'; -import { useEffect } from '@wordpress/element'; +import { DataViews } from '@wordpress/dataviews/wp'; +import { dateI18n, getSettings as getDateSettings } from '@wordpress/date'; +import { useCallback, useEffect, useMemo } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; import { useNavigate } from 'react-router'; /** * Internal dependencies */ import useConfigValue from '../../hooks/use-config-value.ts'; +import CreateFormButton from '../components/create-form-button/index.tsx'; +import { EmptyWrapper } from '../components/empty-responses/index.tsx'; import FormsResponsesTabs from '../components/forms-responses-tabs/index.tsx'; import Page from '../components/page/index.tsx'; +import useFormsData from '../hooks/use-forms-data.ts'; +import { defaultLayouts, useView } from './views.ts'; +import './style.scss'; +import type { FormListItem } from '../hooks/use-forms-data.ts'; /** - * Forms dashboard "Forms" route placeholder. + * Forms dashboard "Forms" route. * - * @return {JSX.Element|null} The placeholder page, or null when redirecting. + * @return {JSX.Element|null} The Forms list page, or null when redirecting. */ export default function FormsDashboardForms(): JSX.Element | null { const navigate = useNavigate(); const isCentralFormManagementEnabled = useConfigValue( 'isCentralFormManagementEnabled' ); + const isCentralFormManagementDisabled = isCentralFormManagementEnabled === false; + + const dateSettings = getDateSettings(); + const [ view, setView ] = useView(); + const { records, isLoading, totalItems, totalPages } = useFormsData( + view.page, + view.perPage, + view.search + ); useEffect( () => { - if ( isCentralFormManagementEnabled === false ) { + if ( isCentralFormManagementDisabled ) { navigate( '/responses', { replace: true } ); } - }, [ isCentralFormManagementEnabled, navigate ] ); + }, [ isCentralFormManagementDisabled, navigate ] ); + + const statusLabel = useCallback( ( status: string ) => { + switch ( status ) { + case 'publish': + return __( 'Published', 'jetpack-forms' ); + case 'draft': + return __( 'Draft', 'jetpack-forms' ); + case 'pending': + return __( 'Pending review', 'jetpack-forms' ); + case 'future': + return __( 'Scheduled', 'jetpack-forms' ); + case 'private': + return __( 'Private', 'jetpack-forms' ); + default: + return status; + } + }, [] ); + + const fields = useMemo( + () => [ + { + id: 'title', + label: __( 'Form name', 'jetpack-forms' ), + getValue: ( { item }: { item: FormListItem } ) => item.title, + render: ( { item }: { item: FormListItem } ) => + item.title || __( '(no title)', 'jetpack-forms' ), + enableSorting: false, + enableHiding: false, + }, + { + id: 'entries', + label: __( 'Entries', 'jetpack-forms' ), + getValue: ( { item }: { item: FormListItem } ) => item.entriesCount ?? 0, + render: ( { item }: { item: FormListItem } ) => item.entriesCount ?? 0, + enableSorting: false, + }, + { + id: 'status', + label: __( 'Status', 'jetpack-forms' ), + getValue: ( { item }: { item: FormListItem } ) => item.status, + render: ( { item }: { item: FormListItem } ) => statusLabel( item.status ), + enableSorting: false, + }, + { + id: 'modified', + label: __( 'Last updated', 'jetpack-forms' ), + type: 'date' as const, + render: ( { item }: { item: FormListItem } ) => + dateI18n( dateSettings.formats.datetime, item.modified ), + enableSorting: false, + }, + ], + [ dateSettings.formats.datetime, statusLabel ] + ); + + const actions = useMemo( + () => [ + { + id: 'edit-form', + isPrimary: false, + label: __( 'Edit', 'jetpack-forms' ), + supportsBulk: false, + async callback( items: FormListItem[] ) { + const [ item ] = items; + if ( ! item ) { + return; + } + const fallbackEditUrl = `post.php?post=${ item.id }&action=edit&post_type=jetpack_form`; + const editUrl = item.editUrl || fallbackEditUrl; + const url = new URL( editUrl, window.location.origin ); + window.location.href = url.toString(); + }, + }, + ], + [] + ); + + const paginationInfo = useMemo( + () => ( { + totalItems: totalItems ?? 0, + totalPages: totalPages ?? 0, + } ), + [ totalItems, totalPages ] + ); + + const onChangeView = useCallback( newView => setView( newView ), [ setView ] ); - // Avoid rendering the placeholder if the flag is off (we'll redirect). - if ( isCentralFormManagementEnabled === false ) { + const headerActions = useMemo( () => [ ], [] ); + const getItemId = useCallback( ( item: FormListItem ) => String( item.id ), [] ); + + // Avoid rendering if the flag is off (we'll redirect). + if ( isCentralFormManagementDisabled ) { return null; } @@ -43,11 +149,50 @@ export default function FormsDashboardForms(): JSX.Element | null { } subTitle={ __( 'View and manage all your forms in one place.', 'jetpack-forms' ) } tabs={ } + actions={ headerActions } hasPadding={ false } > -

- { __( 'Forms will appear here', 'jetpack-forms' ) } -

+ + } + /> + } + view={ view } + onChangeView={ onChangeView } + getItemId={ getItemId } + defaultLayouts={ defaultLayouts } + > +
+
+ +
+
+ + + +
+
+
+ + +
+
); diff --git a/projects/packages/forms/src/dashboard/forms/style.scss b/projects/packages/forms/src/dashboard/forms/style.scss new file mode 100644 index 000000000000..e0fcd738163f --- /dev/null +++ b/projects/packages/forms/src/dashboard/forms/style.scss @@ -0,0 +1,20 @@ +@use "@wordpress/base-styles/breakpoints"; +@use "@wordpress/base-styles/variables"; + +.jp-forms-filters-bar { + border-bottom: 1px solid var(--wpds-color-stroke-surface-neutral-weak); + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: variables.$grid-unit * 1.25; + background: var(--wpds-color-bg-surface-neutral-strong, #fff); + padding: 12px 16px; +} + +.jp-forms-filters-bar__controls { + display: flex; + gap: 8px; + justify-content: flex-end; +} + diff --git a/projects/packages/forms/src/dashboard/forms/views.ts b/projects/packages/forms/src/dashboard/forms/views.ts new file mode 100644 index 000000000000..88cfdc604927 --- /dev/null +++ b/projects/packages/forms/src/dashboard/forms/views.ts @@ -0,0 +1,70 @@ +import { useCallback, useEffect, useState } from '@wordpress/element'; +import { useSearchParams } from 'react-router'; +import type { View } from '@wordpress/dataviews/wp'; + +const LAYOUT_TABLE = 'table'; + +export const defaultView: View = { + type: LAYOUT_TABLE, + search: '', + filters: [], + page: 1, + perPage: 20, + fields: [ 'title', 'entries', 'status', 'modified' ], +}; + +export const defaultLayouts = { + [ LAYOUT_TABLE ]: {}, +}; + +/** + * Manage the DataViews view state for the Forms list and keep `search` in sync with the URL. + * + * @return {[typeof defaultView, (newView: typeof defaultView) => void]} The current DataViews view and a setter that updates the URL. + */ +export function useView() { + const [ searchParams, setSearchParams ] = useSearchParams(); + const urlSearch = searchParams.get( 'search' ); + + const [ view, setView ] = useState( () => ( { + ...defaultView, + search: urlSearch ?? '', + } ) ); + + const setViewWithUrlUpdate = useCallback( + newView => { + setView( newView ); + if ( newView.search !== urlSearch ) { + setSearchParams( previousSearchParams => { + const _searchParams = new URLSearchParams( previousSearchParams ); + if ( newView.search ) { + _searchParams.set( 'search', newView.search ); + } else { + _searchParams.delete( 'search' ); + } + return _searchParams; + } ); + } + }, + [ setSearchParams, urlSearch ] + ); + + const onUrlSearchChange = useCallback( () => { + setView( previousView => { + const newValue = urlSearch ?? ''; + if ( newValue === previousView.search ) { + return previousView; + } + return { + ...previousView, + search: newValue, + }; + } ); + }, [ urlSearch ] ); + + useEffect( () => { + onUrlSearchChange(); + }, [ onUrlSearchChange, urlSearch ] ); + + return [ view, setViewWithUrlUpdate ] as const; +} diff --git a/projects/packages/forms/src/dashboard/hooks/use-forms-data.ts b/projects/packages/forms/src/dashboard/hooks/use-forms-data.ts new file mode 100644 index 000000000000..20edf107cb5a --- /dev/null +++ b/projects/packages/forms/src/dashboard/hooks/use-forms-data.ts @@ -0,0 +1,87 @@ +import { useEntityRecords } from '@wordpress/core-data'; +import { useMemo } from '@wordpress/element'; +import { decodeEntities } from '@wordpress/html-entities'; + +export type FormListItem = { + id: number; + title: string; + status: string; + modified: string; + entriesCount: number; + editUrl?: string; +}; + +type JetpackFormRestItem = { + id: number; + title?: { rendered?: string }; + status: string; + modified: string; + entries_count?: number; + edit_url?: string; +}; + +type UseFormsDataReturn = { + records: FormListItem[]; + isLoading: boolean; + totalItems: number; + totalPages: number; +}; + +/** + * Fetch Forms list records for the Forms dashboard table. + * + * @param page - Current page number. + * @param perPage - Items per page. + * @param search - Search term. + * + * @return Forms list data for the current query. + */ +export default function useFormsData( + page: number, + perPage: number, + search: string +): UseFormsDataReturn { + const query = useMemo( () => { + const queryParams: Record< string, unknown > = { + context: 'edit', + jetpack_forms_context: 'dashboard', + order: 'desc', + orderby: 'modified', + page, + per_page: perPage, + status: 'publish,draft,pending,future,private', + }; + + if ( search ) { + queryParams.search = search; + } + + return queryParams; + }, [ page, perPage, search ] ); + + const { + records: rawRecords, + hasResolved, + totalItems, + totalPages, + } = useEntityRecords( 'postType', 'jetpack_form', query ); + + const records = ( rawRecords || [] ).map( item => { + const typedItem = item as JetpackFormRestItem; + return { + id: typedItem.id, + title: decodeEntities( typedItem.title?.rendered || '' ), + status: typedItem.status, + modified: typedItem.modified, + entriesCount: typedItem.entries_count ?? 0, + editUrl: typedItem.edit_url, + }; + } ); + + return { + records, + isLoading: ! hasResolved, + totalItems: totalItems ?? 0, + totalPages: totalPages ?? 0, + }; +} diff --git a/projects/packages/forms/src/dashboard/inbox/style.scss b/projects/packages/forms/src/dashboard/inbox/style.scss index 34fb385efa96..3e613b90ff6b 100644 --- a/projects/packages/forms/src/dashboard/inbox/style.scss +++ b/projects/packages/forms/src/dashboard/inbox/style.scss @@ -59,20 +59,19 @@ .jp-forms-filters-bar { border-bottom: 1px solid var(--wpds-color-stroke-surface-neutral-weak); - padding-inline: variables.$grid-unit * 2.5; display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: variables.$grid-unit * 1.25; background: var(--wpds-color-bg-surface-neutral-strong, #fff); + padding: 12px 16px; &__chips { display: flex; flex: 1 1 auto; min-width: 0; align-items: center; - padding: variables.$grid-unit * 1.5 0; gap: 8px; }