| 1 |
import { __ } from '@wordpress/i18n' |
| 2 |
import React, { useState } from 'react' |
| 3 |
import { useSnippetsAPI } from '../../../hooks/useSnippetsAPI' |
| 4 |
import { useSnippetsList } from '../../../hooks/useSnippetsList' |
| 5 |
import { handleUnknownError } from '../../../utils/errors' |
| 6 |
import type { Snippet } from '../../../types/Snippet' |
| 7 |
|
| 8 |
export interface SnippetPriorityInputProps { |
| 9 |
snippet: Snippet |
| 10 |
} |
| 11 |
|
| 12 |
/** |
| 13 |
* Inline number field for updating a snippet's priority, saving on blur or |
| 14 |
* form submission. Shared between the snippets list table, card kebab menu, |
| 15 |
* and preview modal. |
| 16 |
*/ |
| 17 |
export const SnippetPriorityInput: React.FC<SnippetPriorityInputProps> = ({ snippet }) => { |
| 18 |
const [value, setValue] = useState(snippet.priority) |
| 19 |
const snippetsAPI = useSnippetsAPI() |
| 20 |
const { refreshSnippetsList } = useSnippetsList() |
| 21 |
|
| 22 |
const handleUpdate = () => { |
| 23 |
// The kebab menu can focus this input on open, so a blur without a |
| 24 |
// real change must not trigger a write. |
| 25 |
if (Number.isNaN(value) || value === snippet.priority) { |
| 26 |
setValue(snippet.priority) |
| 27 |
return |
| 28 |
} |
| 29 |
|
| 30 |
snippetsAPI.update({ ...snippet, priority: value }) |
| 31 |
.then(response => { |
| 32 |
if (response.id === snippet.id) { |
| 33 |
setValue(response.priority) |
| 34 |
} |
| 35 |
}) |
| 36 |
.then(refreshSnippetsList) |
| 37 |
.catch(handleUnknownError) |
| 38 |
} |
| 39 |
|
| 40 |
return ( |
| 41 |
<form onSubmit={event => { |
| 42 |
event.preventDefault() |
| 43 |
handleUpdate() |
| 44 |
}}> |
| 45 |
<input |
| 46 |
id={`snippet-${snippet.id}-priority`} |
| 47 |
type="number" |
| 48 |
className="snippet-priority" |
| 49 |
value={value} |
| 50 |
step="1" |
| 51 |
onBlur={handleUpdate} |
| 52 |
aria-label={__('Snippet priority', 'code-snippets')} |
| 53 |
onChange={event => setValue(Number(event.target.value))} |
| 54 |
disabled={snippet.locked || snippet.trashed} |
| 55 |
/> |
| 56 |
</form> |
| 57 |
) |
| 58 |
} |
| 59 |
|