Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

TweetSummary

By Alexandra Faller

Allows the user to tweet a summary into twitter.

TweetSummary.js

import React from 'react';
import {FormField} from '@sanity/base/components';
import {TextArea, Button, Stack, Text, Card, useToast} from '@sanity/ui';
import PatchEvent, {set, unset} from '@sanity/form-builder/PatchEvent';
import {useId} from '@reach/auto-id';
import {LaunchIcon} from '@sanity/icons';

const TweetSummary = React.forwardRef((props, ref) => {
	const {type, value, readOnly, placeholder, markers, presence, compareValue, onFocus, onBlur, onChange} = props;

	const inputId = useId();
	// For the toast notification
	const toast = useToast();

	//checks the max length of the validation rule
	const MaxValue = type.validation[0]._rules.filter((rule) => rule.flag == 'max')[0].constraint;

	const handleChange = React.useCallback(
		(event) => {
			const inputValue = event.currentTarget.value;
			onChange(PatchEvent.from(inputValue ? set(inputValue) : unset()));
		},
		[onChange]
	);

	//take value of input and put it in a new twitter tweet when button clicked.
	const handleClick = (event) => {
		const summary = props.value;
		if (summary === undefined || summary === '') {
			toast.push({
				status: 'Warning',
				title: 'Must contain a summary for the Tweet!',
			});
			return;
		} else {
			const twitterUrl = `https://twitter.com/intent/tweet?text=${summary}`;
			window.open(twitterUrl, '_blank');
		}
	};

	return (
		<Stack space={1}>
			<FormField
				description={type.description}
				title={type.title}
				__unstable_markers={markers}
				__unstable_presence={presence}
				compareValue={compareValue}
				inputId={inputId}
			>
				{' '}
				<Card flex={1} marginBottom={[2]}>
					<TextArea
						id={inputId}
						onChange={handleChange}
						value={value}
						readOnly={readOnly}
						placeholder={placeholder} // If placeholder is defined, display placeholder text
						onFocus={onFocus}
						onBlur={onBlur}
						ref={ref}
						fontSize={[2, 2, 3, 4]}
					/>
				</Card>
				<Card flex={1} marginBottom={[2]}>
					<Text muted size={1}>
						{value ? value.length : '0'} / {MaxValue}
					</Text>
				</Card>
				<Card flex={1} marginBottom={[2]}>
					<Button iconRight={LaunchIcon} onClick={handleClick} fontSize={[1]} mode='default' padding={[3]} text='Tweet Summary' marginLeft={[2, 2, 3, 4]} />
				</Card>
			</FormField>
		</Stack>
	);
});

export default TweetSummary;

Schema

	{
			name: 'summary',
			title: 'Summary to be tweeted',
			type: 'string',
			validation: (Rule) => Rule.max(160),
			inputComponent: TweetSummary,
		},

Allows the user to tweet a summary directly into twitter by opening a twitter page with the tweet pre-filled from the text area box.

Contributor