diff --git a/src/components/common/NamespaceDropdown.jsx b/src/components/common/NamespaceDropdown.jsx index e1214df..bf3fd98 100644 --- a/src/components/common/NamespaceDropdown.jsx +++ b/src/components/common/NamespaceDropdown.jsx @@ -25,7 +25,7 @@ const OwnerOption = ({ option, selected, ...rest }) => { } -const NamespaceDropdown = ({onChange, label, id, owner, backgroundColor, asOwner, personalOnly, size, disabled, sx}) => { +const NamespaceDropdown = ({onChange, label, id, owner, backgroundColor, asOwner, personalOnly, size, disabled, sx, helperText}) => { const { t } = useTranslation() const user = getCurrentUser() const [ownerOptions, setOwnerOptions] = React.useState([]) @@ -67,25 +67,30 @@ const NamespaceDropdown = ({onChange, label, id, owner, backgroundColor, asOwner renderOption={(props, option, { selected }) => } onChange={onChange} renderInput={ - params => ( - - {selectedOption.icon} - - ) - } - } : params.slotProps} - /> - ) + params => { + const slotProps = selectedOption?.icon ? { + ...params.slotProps, + input: { + ...params.slotProps?.input, + startAdornment: ( + + {selectedOption.icon} + + ) + } + } : params.slotProps + return ( + + ) + } } sx={sx} /> diff --git a/src/components/common/__integration__/capabilityNote.test.js b/src/components/common/__integration__/capabilityNote.test.js new file mode 100644 index 0000000..65ef35d --- /dev/null +++ b/src/components/common/__integration__/capabilityNote.test.js @@ -0,0 +1,80 @@ +/** + * The kept line under a form field follows the owner chosen now + * (OpenConceptLab/ocl_online#700): switching away and back shows the line + * kept for the earlier choice in no committed render, drops a late reply for + * another owner, and shows the fresh reply. + */ +import test from 'node:test' +import assert from 'node:assert/strict' +import React from 'react' +import ReactDOM from 'react-dom' +import { render, act, cleanup } from '@testing-library/react' + +import { toCapabilityNoteKey, useKeptCapabilityNote } from '../capabilityNote.js' + +const keyFor = owner => toCapabilityNoteKey({capability: 'example.capability', owner, lang: 'en'}) +const PERSONAL = keyFor('/users/someone/') +const ORG = keyFor('/orgs/Example/') + +// Records what every render showed. +const renderNotes = () => { + const shown = [] + let keep + const Note = ({noteKey}) => { + const [note, keepNote] = useKeptCapabilityNote(noteKey) + keep = keepNote + shown.push(note) + return React.createElement('span', {'data-testid': 'note'}, note || '') + } + return {Note, shown, keep: (...args) => act(() => keep(...args))} +} + +test('switching away and straight back never shows the earlier line', () => { + const { Note, shown, keep } = renderNotes() + const { rerender, getByTestId } = render(React.createElement(Note, {noteKey: PERSONAL})) + keep(PERSONAL, 'Personal line.') + assert.equal(getByTestId('note').textContent, 'Personal line.') + + shown.length = 0 + rerender(React.createElement(Note, {noteKey: ORG})) + rerender(React.createElement(Note, {noteKey: PERSONAL})) + assert.deepEqual(shown.filter(Boolean), [], 'no render after the switch showed a line') + assert.equal(getByTestId('note').textContent, '') + + // the organization's late reply is dropped; the fresh personal one shows + keep(ORG, 'Org line.') + assert.equal(getByTestId('note').textContent, '') + keep(PERSONAL, 'Personal line again.') + assert.equal(getByTestId('note').textContent, 'Personal line again.') + cleanup() +}) + +// Two quick choices, as two clicks are: each commits at once, before React gets +// to work it queued at a lower priority, as it does a passive effect's updates. +test('a quick switch away and back commits the earlier line in no render', () => { + const { Note, shown, keep } = renderNotes() + let choose + const Form = () => { + const [noteKey, setNoteKey] = React.useState(PERSONAL) + choose = setNoteKey + return React.createElement(Note, {noteKey}) + } + const { getByTestId } = render(React.createElement(Form)) + keep(PERSONAL, 'Personal line.') + assert.equal(getByTestId('note').textContent, 'Personal line.') + + shown.length = 0 + const committed = [] + act(() => { + for(const noteKey of [ORG, PERSONAL]) { + ReactDOM.flushSync(() => choose(noteKey)) + committed.push(getByTestId('note').textContent) + } + }) + assert.deepEqual(committed, ['', ''], 'no commit after a choice showed the earlier line') + assert.deepEqual(shown.filter(Boolean), [], 'no render after the switch showed a line') + + keep(PERSONAL, 'Personal line again.') + assert.equal(getByTestId('note').textContent, 'Personal line again.') + cleanup() +}) diff --git a/src/components/common/__tests__/capabilityNote.test.js b/src/components/common/__tests__/capabilityNote.test.js new file mode 100644 index 0000000..94805ef --- /dev/null +++ b/src/components/common/__tests__/capabilityNote.test.js @@ -0,0 +1,51 @@ +import test from 'node:test' +import assert from 'node:assert/strict' + +const { + capabilityNoteReducer, getCapabilityNoteRequest, toCapabilityNote, toCapabilityNoteKey, +} = await import('../capabilityNote.js') + +const REQUEST = {baseURL: 'https://api.example.org/', token: 'personal-token', capability: 'example.capability', owner: '/orgs/Example/', lang: 'pt-BR'} + +test('asks the API about the capability for the chosen owner, in the UI language, with the person\'s token', () => { + assert.deepEqual(getCapabilityNoteRequest(REQUEST), { + url: 'https://api.example.org/capabilities/example.capability/note/', + params: {owner: '/orgs/Example/', lang: 'pt-BR'}, + headers: {Authorization: 'Token personal-token'}, + }) +}) + +test('no API URL, token, capability or owner: no request', () => { + for(const field of ['baseURL', 'token', 'capability', 'owner']) + assert.equal(getCapabilityNoteRequest({...REQUEST, [field]: ''}), null, field) +}) + +test('shows only a non-empty string it is sent', () => { + assert.equal(toCapabilityNote({message: ' A line from the API. '}), 'A line from the API.') + for(const data of [undefined, null, {}, {message: null}, {message: ''}, {message: ' '}, {message: 3}, {message: {text: 'x'}}, 'text']) + assert.equal(toCapabilityNote(data), null, JSON.stringify(data)) +}) + +const keyFor = (owner, lang = 'en') => toCapabilityNoteKey({capability: 'example.capability', owner, lang}) +const ORG = keyFor('/orgs/Example/') +const PERSONAL = keyFor('/users/someone/') +const run = actions => actions.reduce(capabilityNoteReducer, {asked: null, note: null}) + +test('a line is kept once the reply to the latest ask arrives', () => { + assert.deepEqual(run([{type: 'ask', key: ORG}]), {asked: ORG, note: null}) + assert.deepEqual(run([{type: 'ask', key: ORG}, {type: 'reply', key: ORG, note: 'A line.'}]), {asked: ORG, note: 'A line.'}) +}) + +test('asking again drops the line, and a reply to an earlier ask is dropped', () => { + const asked = [{type: 'ask', key: PERSONAL}, {type: 'reply', key: PERSONAL, note: 'Personal line.'}, {type: 'ask', key: ORG}] + assert.deepEqual(run(asked), {asked: ORG, note: null}) + // back to the first owner before the organization replies; its new request fails (no reply), and the organization's + // late reply is dropped + assert.deepEqual(run([...asked, {type: 'ask', key: PERSONAL}, {type: 'reply', key: ORG, note: 'Org line.'}]), {asked: PERSONAL, note: null}) +}) + +test('nothing to ask about while disabled or with no owner', () => { + assert.equal(toCapabilityNoteKey({capability: 'example.capability', owner: '/orgs/Example/', lang: 'en', enabled: false}), null) + assert.equal(toCapabilityNoteKey({capability: 'example.capability', owner: '', lang: 'en'}), null) + assert.deepEqual(run([{type: 'ask', key: ORG}, {type: 'reply', key: ORG, note: 'x'}, {type: 'ask', key: null}, {type: 'reply', key: null, note: 'y'}]), {asked: null, note: null}) +}) diff --git a/src/components/common/capabilityNote.js b/src/components/common/capabilityNote.js new file mode 100644 index 0000000..f33670c --- /dev/null +++ b/src/components/common/capabilityNote.js @@ -0,0 +1,50 @@ +// A line the API may send to show beside a form, about a capability and the +// owner the form is for (OpenConceptLab/ocl_online#700). Open code shows only +// the text it's sent: an API without the route sends nothing, and nothing shows. +import React from 'react' + +export const getCapabilityNoteRequest = ({baseURL, token, capability, owner, lang}) => { + if(!baseURL || !token || !capability || !owner) + return null + return { + url: `${baseURL.replace(/\/+$/, '')}/capabilities/${capability}/note/`, + params: {owner, lang}, + headers: {Authorization: `Token ${token}`}, + } +} + +// Only a non-empty string becomes a line. +export const toCapabilityNote = data => + typeof data?.message === 'string' && data.message.trim() ? data.message.trim() : null + +// What a line is for: the capability, the owner and the language. None while +// there's nothing to ask about. +export const toCapabilityNoteKey = ({capability, owner, lang, enabled = true}) => + enabled && capability && owner ? JSON.stringify([capability, owner, lang]) : null + +// What the form has asked for (`asked`) and the line kept for it. Asking for +// anything drops the line, so a line shows only after a reply to the latest +// ask: never the last owner's, or an earlier one's when its new request +// fails. A reply to anything but the latest ask is dropped. +export const capabilityNoteReducer = (state, action) => { + if(action.type === 'ask') + return {asked: action.key, note: null} + if(action.type === 'reply' && action.key && action.key === state.asked) + return {...state, note: action.note} + return state +} + +// The line kept for `key`, and `keep(key, note)` for a reply. A new key asks +// again in an effect, not during render: React can drop a render-phase update +// when it replays queued ones, and then a reply to the new key would be lost. +// A layout effect, so the ask is done as the new key commits: a passive +// effect's ask can wait behind a quick switch back to the earlier key, which +// would then show the line kept for it before its fresh reply. +export const useKeptCapabilityNote = key => { + const [state, dispatch] = React.useReducer(capabilityNoteReducer, {asked: null, note: null}) + React.useLayoutEffect(() => { + dispatch({type: 'ask', key}) + }, [key]) + const keep = React.useCallback((replyKey, note) => dispatch({type: 'reply', key: replyKey, note}), []) + return [state.asked === key ? state.note : null, keep] +} diff --git a/src/components/common/useCapabilityNote.js b/src/components/common/useCapabilityNote.js new file mode 100644 index 0000000..d695037 --- /dev/null +++ b/src/components/common/useCapabilityNote.js @@ -0,0 +1,37 @@ +import React from 'react' +import axios from 'axios' +import { useTranslation } from 'react-i18next' + +import { currentUserToken, getAPIURL } from '../../common/utils' +import { getCapabilityNoteRequest, toCapabilityNote, toCapabilityNoteKey, useKeptCapabilityNote } from './capabilityNote' + +// The API's line about `capability` for `owner`, asked for again when the +// owner changes; null while `enabled` is false, until the reply arrives, and +// when the API sends none, fails or has no such route. axios directly, not +// APIService, so a missing route or a refusal skips its sign-out and +// throttling handling. +const useCapabilityNote = (capability, owner, enabled = true) => { + const { i18n } = useTranslation() + const key = toCapabilityNoteKey({capability, owner, lang: i18n.language, enabled}) + const [note, keep] = useKeptCapabilityNote(key) + + React.useEffect(() => { + const request = key ? + getCapabilityNoteRequest({baseURL: getAPIURL(), token: currentUserToken(), capability, owner, lang: i18n.language}) : + null + if(!request) + return undefined + // only this request's reply, while it's the latest + let current = true + axios.get(request.url, {params: request.params, headers: request.headers, timeout: 10000}) + .then(response => current && keep(key, toCapabilityNote(response.data))) + .catch(() => {}) + return () => { + current = false + } + }, [key]) + + return note +} + +export default useCapabilityNote diff --git a/src/components/map-projects/ConfigurationForm.jsx b/src/components/map-projects/ConfigurationForm.jsx index ba2f2ba..cf556e8 100644 --- a/src/components/map-projects/ConfigurationForm.jsx +++ b/src/components/map-projects/ConfigurationForm.jsx @@ -17,11 +17,13 @@ import SettingsIcon from '@mui/icons-material/Settings'; import SaveIcon from '@mui/icons-material/Save'; import OpenInNewIcon from '@mui/icons-material/OpenInNew'; +import Box from '@mui/material/Box' import Stack from '@mui/material/Stack' import Alert from '@mui/material/Alert' import Tooltip from '@mui/material/Tooltip' import InfoOutlinedIcon from '@mui/icons-material/InfoOutlined' +import { visuallyHidden } from '@mui/utils' import isEmpty from 'lodash/isEmpty' import omit from 'lodash/omit' import filter from 'lodash/filter' @@ -31,6 +33,7 @@ import { MATCHING_ALGORITHMS_DOC_LINK, MAPPER_DOCS_LINK } from '../../common/con import { COLORS } from '../../common/colors' import { getProjectConfigErrors } from './algorithms' import NamespaceDropdown from '../common/NamespaceDropdown' +import useCapabilityNote from '../common/useCapabilityNote' import RepoSearchAutocomplete from '../repos/RepoSearchAutocomplete' import RepoVersionSearchAutocomplete from '../repos/RepoVersionSearchAutocomplete' import CloseIconButton from '../common/CloseIconButton'; @@ -117,6 +120,9 @@ const ConfigurationForm = ({ project, handleFileUpload, file, owner, setOwner, n canUseCustomAlgorithms, }) const hasAccessErrors = accessErrors.length > 0 + // While the project is new, any line the API sends about the projects + // the chosen owner has (OpenConceptLab/ocl_online#700). + const projectsNote = useCapabilityNote('mapper.projects', owner, !project?.id) // Project-config validation. Currently flags custom algos with missing / // malformed canonical_url. Returned as a structured list so the banner @@ -161,7 +167,10 @@ const ConfigurationForm = ({ project, handleFileUpload, file, owner, setOwner, n asOwner personalOnly={!canUseOrgProjects} sx={{marginTop: '12px'}} + helperText={projectsNote} /> + {/* announces the line when it arrives: a live region is heard only when it's there before its text */} + {projectsNote || ''}