import { Form, Link, usePage } from '@inertiajs/react'; import { ChartBar, Clock3 } from 'lucide-react'; import type { KeyboardEvent } from 'react'; import { useEffect, useRef, useState } from 'react'; import CommitController from '@/actions/App/Http/Controllers/CommitController'; import ScheduledCommitController from '@/actions/App/Http/Controllers/ScheduledCommitController'; import { ActionTooltip } from '@/components/action-tooltip'; import { AuthorSwitcher, useAuthor } from '@/components/author-switcher'; import { BodyCounter } from '@/components/body-counter'; import { ImageDropOverlay, ImagePickerButton, ImagePickerPreviews, imageErrorFrom, } from '@/components/commit-image-picker'; import { CommitRulesDialog, useCommitRules } from '@/components/commit-rules'; import { ComposerPollPreview, ComposerPreviewBody, PreviewToggle, useComposerPreview, } from '@/components/composer-preview'; import { EmojiPickerButton } from '@/components/emoji-picker'; import { GraphRail, RailAvatar } from '@/components/graph-rail'; import InputError from '@/components/input-error'; import type { UseIssueCommandReturn } from '@/components/issue-command'; import { IssueCommandBadge, IssueCommandHint, IssueCommandSuggestions, useIssueCommand, } from '@/components/issue-command'; import { LinkCardPicker } from '@/components/link-card-picker'; import { MentionTextarea } from '@/components/mention-textarea'; import type { PollDraft } from '@/components/poll-editor'; import { emptyPollDraft, PollEditor } from '@/components/poll-editor'; import { isExistingLocalTime, SchedulePicker, } from '@/components/schedule-picker'; import { StashLabel } from '@/components/stash-label'; import { Button } from '@/components/ui/button'; import { useEmojiInsertion } from '@/hooks/use-emoji-insertion'; import { useImageAttachments } from '@/hooks/use-image-attachments'; import { useLinkCard } from '@/hooks/use-link-card'; import type { UseLinkCardReturn } from '@/hooks/use-link-card'; import type { UseStashReturn } from '@/hooks/use-stash'; import { discardSeriesStash, moveCaretToEnd, useStash, } from '@/hooks/use-stash'; import { useUser } from '@/hooks/use-user'; import { bodyCharacterCount, isSavedAs, maxBodyLength, maxRawBodyLength, minBodyLength, } from '@/lib/commit'; import type { IssueKind } from '@/lib/issue-commands'; import { hasModKey, useKeyLabels } from '@/lib/keyboard'; import { characterCount, cn, isRejectedSubmission, laneColor, organizationLaneColor, } from '@/lib/utils'; import { show } from '@/routes/user'; import type { OrganizationAuthor, User } from '@/types'; // The ring moves quickly while a post starts and slows toward the limit, yet only closes at the limit. function bodyProgress(count: number): number { return Math.log1p(count) / Math.log1p(maxBodyLength); } function focusBody(id: string): void { requestAnimationFrame(() => document.getElementById(id)?.focus()); } function useCommitSchedule() { const [isScheduling, setIsScheduling] = useState(false); const [scheduledAt, setScheduledAt] = useState(''); const [timezone, setTimezone] = useState(''); return { isScheduling, setIsScheduling, scheduledAt, setScheduledAt, timezone, setTimezone, }; } function CommitComposerBody({ id, isInDialog, user, author, onAuthorChange, stash, guildHandle, attachments, linkCard, schedule, poll, setPoll, commitRules, isSubmittable, processing, issue, errors, onKeyDown, drop, }: { id: string; isInDialog: boolean; user: User; author: OrganizationAuthor | null; onAuthorChange: (author: OrganizationAuthor | null) => void; stash: UseStashReturn; guildHandle?: string; attachments: ReturnType; linkCard: UseLinkCardReturn; schedule: ReturnType; poll: PollDraft | null; setPoll: (poll: PollDraft | null) => void; commitRules: ReturnType; isSubmittable: boolean; processing: boolean; issue: UseIssueCommandReturn; errors: Record; onKeyDown: (event: KeyboardEvent) => void; drop: () => void; }) { const keys = useKeyLabels(); const { body, isRestored, updateBody } = stash; const { auth } = usePage().props; const { isScheduling, scheduledAt, setScheduledAt, timezone, setTimezone, setIsScheduling, } = schedule; const hasImages = attachments.images.length > 0; const progress = bodyProgress( issue.command !== null ? characterCount(body) : bodyCharacterCount(body), ); const isFilled = hasImages || characterCount(body.trim()) >= minBodyLength; const error = errors.body ?? errors.link_preview_url ?? errors.author; const scheduleError = errors.scheduled_at ?? (scheduledAt && !isExistingLocalTime(scheduledAt) ? 'This time does not exist in your timezone. Choose another time.' : undefined); const textareaRef = useRef(null); const textBox = useRef(null); const preview = useComposerPreview({ body, guildHandle, textareaRef, isSubmittable, }); const isIssue = issue.command !== null; // When the dialog's text box shrinks, as the keyboard opens or an image is added, it keeps the caret in view. useEffect(() => { const box = textBox.current; const textarea = textareaRef.current; if (!isInDialog || box === null || textarea === null) { return; } const observer = new ResizeObserver(() => { if ( document.activeElement === textarea && textarea.selectionEnd === textarea.value.length ) { box.scrollTop = box.scrollHeight; } }); observer.observe(box); return () => observer.disconnect(); }, [isInDialog]); const ownNode = isInDialog ? ( ) : ( ); const insertEmoji = useEmojiInsertion({ body, updateBody, textareaRef, maxLength: isIssue ? maxBodyLength : maxRawBodyLength, }); return (
{attachments.isDraggingFiles && ( )} {author === null ? ( ) : ( )} } />
{issue.command && ( { issue.exit(); focusBody(id); }} /> )} {/* In the dialog only the text scrolls, so the images and actions below it always keep their room. */}
{issue.command && ( )} preview.handleShortcut(event) || onKeyDown(event) } onFocus={(event) => { issue.focus(); if (isRestored) { moveCaretToEnd(event); } }} onBlur={issue.blur} maxLength={ isIssue ? maxBodyLength : maxRawBodyLength } placeholder={ issue.command?.placeholder ?? (poll ? 'Ask a question' : guildHandle ? 'What do you want to share with the guild?' : 'What did you ship?') } autoComplete="off" aria-invalid={error ? true : undefined} aria-describedby={`${id}-count`} className={cn( 'col-start-1 row-start-1 block field-sizing-content max-h-[60dvh] min-h-10 w-full resize-none overflow-x-hidden overflow-y-auto bg-transparent py-1.5 pr-9 text-[17px] leading-relaxed outline-none placeholder:text-muted-foreground focus-visible:outline-none', { invisible: preview.isPreviewing, 'max-h-none': isInDialog, }, )} /> {!preview.isPreviewing && (
)} {preview.isPreviewing && ( )}
{guildHandle && (

Posted to this guild, not your profile log.

)} {issue.hint && ( { issue.start(kind, body); focusBody(id); }} onDismiss={issue.dismissHint} /> )} {issue.suggestions.length > 0 && ( { issue.start(kind, ''); focusBody(id); }} /> )} {!preview.isPreviewing && ( )} {poll && (
{ setPoll(null); focusBody(id); }} className={cn('col-start-1 row-start-1', { invisible: preview.isPreviewing, })} /> {preview.isPreviewing && ( )}
)} {isScheduling && (

{timezone} {scheduledAt && !Number.isNaN(new Date(scheduledAt).getTime()) ? ` (${new Intl.DateTimeFormat(undefined, { timeZoneName: 'shortOffset' }).formatToParts(new Date(scheduledAt)).find((part) => part.type === 'timeZoneName')?.value})` : ''} . Within 30 days. Private until submitted;{' '} {auth.isAdmin ? 'your commit will be approved automatically.' : 'then submitted for review, not published automatically.'}

Scheduled commits →
)}
{!isIssue && ( <> )} {isRestored && ( { drop(); focusBody(id); }} className="ml-2 text-[13px]" /> )}
{isIssue ? ( ) : ( )}
); } export function CommitComposer({ id = 'body', isInDialog = false, issue: initialIssue = null, guildHandle, onCommitted, }: { id?: string; isInDialog?: boolean; issue?: IssueKind | null; guildHandle?: string; onCommitted?: () => void; }) { const schedule = useCommitSchedule(); const { isScheduling, scheduledAt, setScheduledAt, setIsScheduling } = schedule; const { user } = useUser(); const { author, setAuthor } = useAuthor(); const stash = useStash( user.id, guildHandle ? `guild:${guildHandle}` : 'commit', ); const { body } = stash; const linkCard = useLinkCard(body); const [draftVersion, setDraftVersion] = useState(0); const drop = () => { stash.drop(); linkCard.reset(); setDraftVersion((version) => version + 1); }; const attachments = useImageAttachments( stash.images, stash.descriptions, stash.updateImages, stash.key, ); const [poll, setPoll] = useState(null); const commitRules = useCommitRules(); const isPosting = useRef(false); const hasImages = attachments.images.length > 0; const issue = useIssueCommand({ body, updateBody: stash.updateBody, enabled: !guildHandle && !attachments.reading && !hasImages && poll === null && !isScheduling, initialKind: initialIssue, onCreated: () => { drop(); focusBody(id); }, }); const isCommittable = !attachments.reading && (hasImages || characterCount(body.trim()) >= minBodyLength) && (issue.command !== null ? characterCount(body) : bodyCharacterCount(body)) <= maxBodyLength && (poll === null || poll.options.every((option) => option.trim().length > 0)); const isSubmittable = isCommittable && (!isScheduling || (scheduledAt !== '' && isExistingLocalTime(scheduledAt))); useEffect(() => discardSeriesStash(user.id), [user.id]); const { committed } = usePage().flash; // A deploy reloads the page before onSuccess can drop the draft, so the reloaded page names the commit it became. useEffect(() => { if ( committed !== undefined && (committed.guild_handle ?? null) === (guildHandle ?? null) && isSavedAs(body, committed.body) ) { drop(); } // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const onKeyDown = (event: KeyboardEvent) => { if ( issue.handleKeyDown( event, isCommittable && !attachments.isReading(), ) ) { return; } if ( event.key === 'Enter' && hasModKey(event) && isSubmittable && !attachments.isReading() ) { event.preventDefault(); event.currentTarget.form?.requestSubmit(); } }; return (
!isPosting.current && isSubmittable && !attachments.isReading() && issue.command === null && commitRules.beforeSubmit() } onStart={() => { isPosting.current = true; }} onFinish={() => { isPosting.current = false; }} transform={(data) => ({ ...data, body, ...(guildHandle && { guild_handle: guildHandle }), commit_rules_accepted: commitRules.hasAccepted(), human_verification_token: commitRules.humanVerificationToken(), ...(author !== null && { author: author.handle }), ...(hasImages && { images: attachments.images, image_descriptions: attachments.descriptions, }), ...(isScheduling && { scheduled_at: new Date(scheduledAt) .toISOString() .replace(/\.\d{3}Z$/, '+00:00'), }), })} options={{ preserveScroll: true }} onSuccess={(page) => { if (isRejectedSubmission(page.flash)) { return; } drop(); setAuthor(null); setScheduledAt(''); setIsScheduling(false); attachments.clear(); setPoll(null); if (onCommitted) { onCommitted(); } else { focusBody(id); } }} data-test="commit-composer" > {({ processing, errors }) => (
)}
); }