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63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
import { PatternRenderer, usePatternsRendererContext } from '@automattic/block-renderer';
import { Button } from '@automattic/components';
import { isMobile } from '@automattic/viewport';
import { useMobileBreakpoint } from '@automattic/viewport-react';
import { ResizableBox, Tooltip } from '@wordpress/components';
import { useResizeObserver } from '@wordpress/compose';
import { Icon, check, copy, lock } from '@wordpress/icons';
import clsx from 'clsx';
import { useRtl, useTranslate } from 'i18n-calypso';
import { useEffect, useRef, useState } from 'react';
import ClipboardButton from 'calypso/components/forms/clipboard-button';
import { recordTracksEvent } from 'calypso/lib/analytics/tracks';
import { PatternsGetAccessModal } from 'calypso/my-sites/patterns/components/get-access-modal';
import { patternFiltersClassName } from 'calypso/my-sites/patterns/components/pattern-library';
import { usePatternsContext } from 'calypso/my-sites/patterns/context';
import { useRecordPatternsEvent } from 'calypso/my-sites/patterns/hooks/use-record-patterns-event';
import { encodePatternId } from 'calypso/my-sites/patterns/lib/encode-pattern-id';
import { getTracksPatternType } from 'calypso/my-sites/patterns/lib/get-tracks-pattern-type';
import { useSelector } from 'calypso/state';
import { isUserLoggedIn } from 'calypso/state/current-user/selectors';
import getUserSetting from 'calypso/state/selectors/get-user-setting';
import type { Pattern, PatternGalleryProps } from 'calypso/my-sites/patterns/types';
import type { Dispatch, SetStateAction } from 'react';

import './style.scss';

export const GRID_VIEW_VIEWPORT_WIDTH = 1200;
export const ASPECT_RATIO = 7 / 4;

// This style is injected into pattern preview iframes to prevent users from navigating away from
// the pattern preview page and from submitting forms.
const noClickStyle = {
	css: 'a[href], button, input, textarea { pointer-events: none; }',
	isGlobalStyles: true,
};

// Firefox and Safari have trouble rendering elements in iframes with `writing-mode` styles. This
// hacky script is injected into pattern preview iframes to force rerender those elements.
function forceRedraw() {
	const elements = document.querySelectorAll< HTMLElement >( '[style*="writing-mode"]' );

	elements.forEach( ( element ) => {
		element.style.display = 'none';
	} );

	setTimeout( () => {
		elements.forEach( ( element ) => {
			element.style.removeProperty( 'display' );
		} );
	}, 200 );
}

const redrawScript = `
<script defer>
(${ forceRedraw.toString() })();
</script>
`;

// Abstraction for resetting `isPatternCopied` and `isPermalinkCopied` after a given delay
function useTimeoutToResetBoolean(
	value: boolean,
	setter: Dispatch< SetStateAction< boolean > >,
	timeout = 4500
) {
	useEffect( () => {
		if ( ! value ) {
			return;
		}

		const timeoutId = setTimeout( () => {
			setter( false );
		}, timeout );

		return () => {
			clearTimeout( timeoutId );
		};
	}, [ value ] );
}

type PatternPreviewProps = {
	canCopy?: boolean;
	className?: string;
	getPatternPermalink?: PatternGalleryProps[ 'getPatternPermalink' ];
	isResizable?: boolean;
	pattern: Pattern | null;
	viewportWidth?: number;
};

function PatternPreviewFragment( {
	canCopy = true,
	className,
	getPatternPermalink = () => '',
	pattern,
	viewportWidth: fixedViewportWidth,
}: PatternPreviewProps ) {
	const { category, patternTypeFilter, isGridView } = usePatternsContext();

	const { recordPatternsEvent } = useRecordPatternsEvent();
	const ref = useRef< HTMLDivElement >( null );
	const hasScrolledToAnchorRef = useRef< boolean >( false );

	const [ isPermalinkCopied, setIsPermalinkCopied ] = useState( false );
	const [ isPatternCopied, setIsPatternCopied ] = useState( false );

	const idAttr = `pattern-${ pattern?.ID }`;

	const { renderedPatterns } = usePatternsRendererContext();
	const patternId = encodePatternId( pattern?.ID ?? 0 );
	const renderedPattern = renderedPatterns[ patternId ];
	const [ resizeObserver, nodeSize ] = useResizeObserver();
	const [ isAuthModalOpen, setIsAuthModalOpen ] = useState( false );

	const isPreviewLarge = nodeSize?.width ? nodeSize.width > 960 : true;

	let viewportWidth: number | undefined = undefined;

	if ( fixedViewportWidth ) {
		viewportWidth = fixedViewportWidth;
	} else if ( nodeSize.width ) {
		viewportWidth = nodeSize.width * 1.16;
	}

	const translate = useTranslate();

	const titleTooltipText = isPermalinkCopied
		? translate( 'Copied link to pattern', {
				comment: 'Tooltip text in Pattern Library for when the user just clicked a button',
				textOnly: true,
		  } )
		: translate( 'Copy link to pattern', {
				comment: 'Tooltip text in Pattern Library',
				textOnly: true,
		  } );

	let copyButtonText = isPreviewLarge
		? translate( 'Copy pattern', {
				comment: 'Button label for copying a pattern',
				textOnly: true,
		  } )
		: translate( 'Copy', {
				comment: 'Button label for copying a pattern',
				textOnly: true,
		  } );

	if ( isPatternCopied ) {
		copyButtonText = isPreviewLarge
			? translate( 'Pattern copied', {
					comment: 'Button label for when a pattern was just copied',
					textOnly: true,
			  } )
			: translate( 'Copied', {
					comment: 'Button label for when a pattern was just copied',
					textOnly: true,
			  } );
	}

	const isDevAccount = useSelector( ( state ) => getUserSetting( state, 'is_dev_account' ) );
	const recordCopyEvent = ( tracksEventName: string ) => {
		recordTracksEvent( tracksEventName, {
			name: pattern?.name,
			category,
			type: getTracksPatternType( patternTypeFilter ),
			user_is_dev_account: isDevAccount ? '1' : '0',
			view: isGridView ? 'grid' : 'list',
		} );
	};

	useTimeoutToResetBoolean( isPermalinkCopied, setIsPermalinkCopied );
	useTimeoutToResetBoolean( isPatternCopied, setIsPatternCopied );

	useEffect( () => {
		ref.current?.dispatchEvent( new CustomEvent( 'patternPreviewResize', { bubbles: true } ) );
	}, [ nodeSize.width, nodeSize.height ] );

	// When a URL with a single-pattern hash is loaded, scroll to that pattern preview. We use
	// `window.scrollBy` instead of setting an ID attribute on the relevant pattern preview to avoid
	// a janky experience for users while the page is loading. This way, the browser doesn't scroll
	// down to the relevant patterns until patterns are mostly finished loading.
	useEffect( () => {
		if (
			window.location.hash !== `#${ idAttr }` ||
			hasScrolledToAnchorRef.current ||
			! ref.current
		) {
			return;
		}

		const element = ref.current;

		const timeoutId = setTimeout( function () {
			hasScrolledToAnchorRef.current = true;

			const masterbarHeightRaw = getComputedStyle( document.documentElement ).getPropertyValue(
				'--masterbar-height'
			);
			const masterbarHeight = /^\d+px$/.test( masterbarHeightRaw )
				? parseInt( masterbarHeightRaw )
				: 0;

			const stickyNav = document.querySelector( `.${ patternFiltersClassName }` );
			const stickyNavCoords = stickyNav?.getBoundingClientRect();
			const stickyNavHeight = stickyNavCoords && ! isMobile() ? stickyNavCoords.height : 0;

			const elementCoords = element.getBoundingClientRect();

			const EXTRA_VERTICAL_MARGIN = 16;

			// We deliberately avoid smooth scrolling, since this will trigger lazy loading on the
			// iframes above the target, potentially causing the layout to shift, which suddenly
			// makes the scroll target incorrect
			window.scrollBy( {
				top: elementCoords.top - stickyNavHeight - masterbarHeight - EXTRA_VERTICAL_MARGIN,
			} );
		}, 1000 );

		return () => {
			clearTimeout( timeoutId );
		};
	}, [ renderedPattern, idAttr ] );

	// When an iframe loses focus, browsers will scroll them back into view. This behavior can be
	// annoying and make for a glitchy impression. This callback continuously stores the latest
	// window scroll position and restores it just after this preview iframe loses focus
	useEffect( () => {
		const iframe = ref.current?.querySelector( 'iframe' );

		if ( ! iframe ) {
			return;
		}

		let lastScrollPosition = window.scrollY;

		function onWindowScroll() {
			lastScrollPosition = window.scrollY;
		}

		function onIframeBlur() {
			const storedLastScrollPosition = lastScrollPosition;

			requestAnimationFrame( () => {
				window.scrollTo( { top: storedLastScrollPosition } );
			} );
		}

		window.addEventListener( 'scroll', onWindowScroll, { passive: true } );
		iframe.contentWindow?.addEventListener( 'blur', onIframeBlur );

		return () => {
			window.removeEventListener( 'scroll', onWindowScroll );
			iframe.contentWindow?.removeEventListener( 'blur', onIframeBlur );
		};
	} );

	// This fetches forms and adds a listener that disables submission
	useEffect( () => {
		const iframe = ref.current?.querySelector( 'iframe' );

		if ( ! iframe?.contentDocument ) {
			return;
		}

		const forms = iframe.contentDocument.querySelectorAll( 'form' );

		if ( ! forms.length ) {
			return;
		}

		const onFormSubmit = ( event: SubmitEvent ) => event.preventDefault();

		forms.forEach( ( form ) => form.addEventListener( 'submit', onFormSubmit ) );

		return () => {
			forms.forEach( ( form ) => form.removeEventListener( 'submit', onFormSubmit ) );
		};
	} );

	if ( ! pattern ) {
		return null;
	}

	const recordGetAccessEvent = ( tracksEventName: string ) => {
		recordTracksEvent( tracksEventName, {
			name: pattern.name,
			category,
			type: getTracksPatternType( patternTypeFilter ),
			view: isGridView ? 'grid' : 'list',
		} );
	};

	return (
		<div
			className={ clsx( 'pattern-preview', className, {
				'is-loading': ! renderedPattern,
				// For some reason, the CSS `:target` selector has trouble with the transition from
				// SSR markup to client-side React code, which is why we need the `is-targeted` class
				'is-targeted': window.location.hash === `#${ idAttr }`,
			} ) }
			ref={ ref }
		>
			{ resizeObserver }

			<div className="pattern-preview__renderer">
				<PatternRenderer
					maxHeight="none"
					minHeight={ nodeSize.width ? nodeSize.width / ASPECT_RATIO : undefined }
					patternId={ patternId }
					scripts={ redrawScript }
					styles={ [ noClickStyle ] }
					viewportWidth={ viewportWidth }
				/>
			</div>

			<div className="pattern-preview__header">
				<Tooltip delay={ 300 } placement="top" text={ titleTooltipText }>
					<ClipboardButton
						borderless
						className="pattern-preview__title"
						onCopy={ () => {
							recordPatternsEvent( 'calypso_pattern_library_permalink_copy', {
								name: pattern.name,
							} );
							setIsPermalinkCopied( true );
						} }
						text={ getPatternPermalink( pattern ) }
						transparent
					>
						{ pattern.title }
					</ClipboardButton>
				</Tooltip>

				{ canCopy && (
					<ClipboardButton
						className="pattern-preview__copy"
						onCopy={ () => {
							recordCopyEvent( 'calypso_pattern_library_copy' );
							setIsPatternCopied( true );
						} }
						text={ pattern?.html ?? '' }
						primary
					>
						<Icon height={ 18 } icon={ isPatternCopied ? check : copy } width={ 18 } />{ ' ' }
						{ copyButtonText }
					</ClipboardButton>
				) }

				{ ! canCopy && (
					<Button
						className="pattern-preview__get-access"
						onClick={ () => {
							setIsAuthModalOpen( true );
							recordGetAccessEvent( 'calypso_pattern_library_get_access' );
						} }
						transparent
					>
						<Icon height={ 18 } icon={ lock } width={ 18 } />{ ' ' }
						{ translate( 'Get access', {
							comment:
								'Button label shown when logged-out users need to sign up to be able to use a pattern',
						} ) }
					</Button>
				) }
			</div>

			<PatternsGetAccessModal
				isOpen={ isAuthModalOpen }
				onClose={ () => setIsAuthModalOpen( false ) }
				pattern={ pattern }
				tracksEventHandler={ recordGetAccessEvent }
			/>
		</div>
	);
}

function PatternPreviewResizerHandle() {
	const translate = useTranslate();
	const tooltipText = translate( 'Resize', {
		comment: 'Tooltip text in Pattern Library for pattern preview resize handle',
		textOnly: true,
	} );

	return (
		<Tooltip delay={ 300 } placement="top" text={ tooltipText }>
			<div className="pattern-preview__resizer-handle" />
		</Tooltip>
	);
}

export function PatternPreview( props: PatternPreviewProps ) {
	const { isResizable, pattern } = props;
	const { category, patternTypeFilter } = usePatternsContext();

	const isMobile = useMobileBreakpoint();
	const isLoggedIn = useSelector( isUserLoggedIn );
	const isDevAccount = useSelector( ( state ) => getUserSetting( state, 'is_dev_account' ) );
	const isRtl = useRtl();

	if ( ! pattern ) {
		return null;
	}

	if ( ! isResizable || isMobile ) {
		return <PatternPreviewFragment { ...props } />;
	}

	const recordResizeEvent = ( tracksEventName: string ) => {
		recordTracksEvent( tracksEventName, {
			name: pattern?.name,
			category,
			type: getTracksPatternType( patternTypeFilter ),
			is_logged_in: isLoggedIn,
			user_is_dev_account: isDevAccount ? '1' : '0',
		} );
	};

	return (
		<ResizableBox
			enable={ {
				top: false,
				right: ! isRtl,
				bottom: false,
				left: isRtl,
				topRight: false,
				bottomRight: false,
				bottomLeft: false,
				topLeft: false,
			} }
			handleComponent={ {
				left: <PatternPreviewResizerHandle />,
				right: <PatternPreviewResizerHandle />,
			} }
			handleWrapperClass="pattern-preview__resizer"
			minWidth={ 335 }
			maxWidth="100%"
			onResizeStop={ () => {
				recordResizeEvent( 'calypso_pattern_library_resize' );
			} }
		>
			<PatternPreviewFragment { ...props } />
		</ResizableBox>
	);
}