Repository navigation
improvement(docs): collect reader feedback inline #9538
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| import { createLogger } from '@sim/logger' | ||
| import { z } from 'zod' | ||
| import { getPage } from '@/lib/content/catalog' | ||
| import { pagePathSchema } from '@/lib/http/pages' | ||
|
|
||
| const logger = createLogger('DocsFeedback') | ||
| const feedbackSchema = z | ||
| .object({ | ||
| submissionId: z.uuid(), | ||
| page: pagePathSchema, | ||
| helpful: z.boolean(), | ||
| comment: z.string().trim().max(2000), | ||
| }) | ||
| .strict() | ||
| const MAX_BODY_BYTES = 12_288 | ||
|
|
||
| export async function POST(request: Request) { | ||
| const headers = { 'Cache-Control': 'no-store' } | ||
| const fail = (error: string, status: number) => Response.json({ error }, { status, headers }) | ||
| const requestUrl = new URL(request.url) | ||
| const host = request.headers.get('host') | ||
| if (!host || request.headers.get('origin') !== `${requestUrl.protocol}//${host}`) { | ||
| return fail('Feedback must be submitted from this site.', 403) | ||
| } | ||
| if (request.headers.get('content-type')?.split(';')[0].trim() !== 'application/json') { | ||
| return fail('Expected JSON.', 415) | ||
| } | ||
| const reader = request.body?.getReader() | ||
| if (!reader) return fail('Feedback is required.', 400) | ||
| let text = '' | ||
| let bytes = 0 | ||
| const decoder = new TextDecoder() | ||
| try { | ||
| while (true) { | ||
| const chunk = await reader.read() | ||
| if (chunk.done) break | ||
| bytes += chunk.value.byteLength | ||
| if (bytes > MAX_BODY_BYTES) { | ||
| await reader.cancel() | ||
| return fail('Feedback is too long.', 413) | ||
| } | ||
| text += decoder.decode(chunk.value, { stream: true }) | ||
| } | ||
| text += decoder.decode() | ||
| } catch { | ||
| return fail('Could not read feedback.', 400) | ||
| } finally { | ||
| reader.releaseLock() | ||
| } | ||
| let input: z.infer<typeof feedbackSchema> | ||
| try { | ||
| input = feedbackSchema.parse(JSON.parse(text)) | ||
| } catch { | ||
| return fail('Check your feedback and try again.', 400) | ||
| } | ||
| const page = getPage(input.page.replace(/\/$/, '') || '/') | ||
| if (!page || page.url === '/') return fail('Documentation page not found.', 404) | ||
| const endpoint = process.env.DOCS_FEEDBACK_WEBHOOK_URL | ||
| const token = process.env.DOCS_FEEDBACK_WEBHOOK_TOKEN | ||
| if (!endpoint || !token) return fail('Feedback is temporarily unavailable.', 503) | ||
| try { | ||
| const url = new URL(endpoint) | ||
| if (url.protocol !== 'https:') throw new Error('Invalid feedback configuration') | ||
| const response = await fetch(url, { | ||
| method: 'POST', | ||
| headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` }, | ||
| body: JSON.stringify({ | ||
| submission_id: input.submissionId, | ||
| page: page.url, | ||
| helpful: input.helpful, | ||
| comment: input.comment, | ||
| received_at: new Date().toISOString(), | ||
| }), | ||
| signal: AbortSignal.timeout(15_000), | ||
| redirect: 'error', | ||
| }) | ||
| if (!response.ok) { | ||
| logger.warn('Feedback intake rejected submission', { status: response.status }) | ||
| return fail('Could not send feedback. Please try again.', 502) | ||
| } | ||
| const receipt: unknown = await response.json() | ||
|
waleedlatif1 marked this conversation as resolved.
Resolved
|
||
| if ( | ||
| !receipt || | ||
| typeof receipt !== 'object' || | ||
| !('message' in receipt) || | ||
| receipt.message !== 'Webhook processed' | ||
| ) { | ||
| return fail('Could not confirm feedback. Please try again.', 502) | ||
| } | ||
| return Response.json({ accepted: true }, { status: 202, headers }) | ||
| } catch { | ||
| logger.warn('Feedback intake unavailable') | ||
| return fail('Could not send feedback. Please try again.', 503) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,139 @@ | ||
| 'use client' | ||
|
|
||
| import { useRef, useState } from 'react' | ||
| import { ThumbsDown, ThumbsUp } from '@sim/emcn/icons' | ||
| import { generateId } from '@sim/utils/id' | ||
| import { QueryClient, QueryClientProvider, useMutation } from '@tanstack/react-query' | ||
| import { DocsButton } from '@/components/docs/primitives' | ||
|
|
||
| interface FeedbackProps { | ||
| page: string | ||
| } | ||
|
|
||
| export function Feedback({ page }: FeedbackProps) { | ||
| const [client] = useState(() => new QueryClient()) | ||
| return ( | ||
| <QueryClientProvider client={client}> | ||
| <FeedbackForm key={page} page={page} /> | ||
| </QueryClientProvider> | ||
| ) | ||
| } | ||
|
|
||
| function FeedbackForm({ page }: FeedbackProps) { | ||
| const [helpful, setHelpful] = useState<boolean | null>(null) | ||
| const [comment, setComment] = useState('') | ||
| const pendingSubmission = useRef<{ | ||
| submissionId: string | ||
| helpful: boolean | ||
| comment: string | ||
| } | null>(null) | ||
| const submission = useMutation({ | ||
| retry: false, | ||
| mutationFn: async (payload: { submissionId: string; helpful: boolean; comment: string }) => { | ||
| const response = await fetch('/api/feedback', { | ||
| method: 'POST', | ||
| headers: { 'Content-Type': 'application/json' }, | ||
| body: JSON.stringify({ ...payload, page }), | ||
| signal: AbortSignal.timeout(20_000), | ||
| }) | ||
| if (!response.ok) | ||
| throw new Error( | ||
| response.status === 429 | ||
| ? 'Too many submissions. Please try again in a minute.' | ||
| : 'Could not send feedback. Please try again.' | ||
| ) | ||
| const result: unknown = await response.json() | ||
| if ( | ||
| !result || | ||
| typeof result !== 'object' || | ||
| !('accepted' in result) || | ||
| result.accepted !== true | ||
| ) { | ||
| throw new Error('Could not confirm feedback. Please try again.') | ||
| } | ||
| }, | ||
| }) | ||
| function submit(vote: boolean) { | ||
| if (submission.isPending) return | ||
| const text = vote ? '' : comment.trim() | ||
| if ( | ||
| !pendingSubmission.current || | ||
| pendingSubmission.current.helpful !== vote || | ||
| pendingSubmission.current.comment !== text | ||
| ) { | ||
| pendingSubmission.current = { submissionId: generateId(), helpful: vote, comment: text } | ||
| } | ||
| submission.mutate(pendingSubmission.current) | ||
| } | ||
| if (submission.isSuccess) return <p role='status'>Thanks for your feedback.</p> | ||
| return ( | ||
| <form | ||
| className='min-w-0 space-y-3' | ||
| onSubmit={(event) => { | ||
| event.preventDefault() | ||
| if (helpful !== null && !submission.isPending) submit(helpful) | ||
| }} | ||
| > | ||
| <div className='flex items-center gap-2'> | ||
| <span>Was this helpful?</span> | ||
| <DocsButton | ||
| type='button' | ||
| aria-label='Yes, this was helpful' | ||
| aria-pressed={helpful === true} | ||
| disabled={submission.isPending} | ||
| iconOnly | ||
| className='size-11 aria-pressed:bg-[var(--docs-selected)]' | ||
| onClick={() => { | ||
| setHelpful(true) | ||
| submission.reset() | ||
| submit(true) | ||
| }} | ||
| > | ||
| <ThumbsUp className='size-4' /> | ||
| </DocsButton> | ||
| <DocsButton | ||
| type='button' | ||
| aria-label='No, this could be improved' | ||
| aria-pressed={helpful === false} | ||
| disabled={submission.isPending} | ||
| iconOnly | ||
| className='size-11 aria-pressed:bg-[var(--docs-selected)]' | ||
| onClick={() => { | ||
| setHelpful(false) | ||
| submission.reset() | ||
| }} | ||
| > | ||
| <ThumbsDown className='size-4' /> | ||
| </DocsButton> | ||
| </div> | ||
| {helpful === false && ( | ||
| <div className='space-y-2'> | ||
| <label className='block' htmlFor='docs-feedback-comment'> | ||
| What could be better? (optional) | ||
| </label> | ||
| <textarea | ||
| id='docs-feedback-comment' | ||
| aria-describedby='docs-feedback-privacy' | ||
| value={comment} | ||
| maxLength={2000} | ||
| rows={3} | ||
| disabled={submission.isPending} | ||
| onChange={(event) => setComment(event.target.value)} | ||
| className='w-full min-w-0 resize-y rounded-lg border border-[var(--docs-border)] bg-[var(--docs-canvas)] p-3 text-[var(--docs-heading)] text-docs-body focus-visible:outline-2 focus-visible:outline-[var(--docs-link)] focus-visible:outline-offset-2' | ||
| placeholder='Tell us what was missing or unclear.' | ||
| /> | ||
| <p id='docs-feedback-privacy'>Please don’t include private information.</p> | ||
| <DocsButton | ||
| type='submit' | ||
| disabled={submission.isPending} | ||
| className='h-11 border border-[var(--docs-border)]' | ||
| > | ||
| {submission.isPending ? 'Sending…' : 'Send feedback'} | ||
| </DocsButton> | ||
| </div> | ||
| )} | ||
| {submission.isPending && helpful === true && <p role='status'>Sending…</p>} | ||
| {submission.isError && <p role='alert'>{submission.error.message}</p>} | ||
| </form> | ||
| ) | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.