Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions src/components/map-projects/ConfigurationForm.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ const getSuggestedRepos = () => (window.REPO_SUGGESTIONS || process.env.REPO_SUG
.filter(([owner, id]) => owner && id)
.map(([owner, id]) => ({id, short_code: id, name: id, owner, ownerType: 'Organization', type: 'Source', url: `/orgs/${owner}/sources/${id}/`}))

const ConfigurationForm = ({ project, handleFileUpload, file, owner, setOwner, name, setName, description, setDescription, repo, onRepoChange, repoVersion, setRepoVersion, showTargetRepoVersionError, versions, mappedSources, targetSourcesFromRows, algosSelected, setAlgosSelected, sx, algos, validColumns, columns, isValidColumnValue, updateColumn, configure, setConfigure, columnVisibilityModel, setColumnVisibilityModel, onSave, isSaving, candidatesScore, onScoreChange, includeDefaultFilter, setIncludeDefaultFilter, filters, setFilters, locales, setAIAssistantColumns, AIAssistantColumns, inAIAssistantGroup, lookupConfig, setLookupConfig, encoderModel, setEncoderModel, isCoreUser, requestLimits, canSelectAIModel, canSetAIOutputLocale, canBridge, canScispacy, canUseOrgProjects=true, canUseCustomAlgorithms=true, promptTemplates, promptTemplate, onPromptTemplateChange, AIModels, AIModel, setAIModel, namespace, setNamespace, promptOutputLocale, setPromptOutputLocale, inputLocale, setInputLocale, oclLocales, useLexicalVariants, setUseLexicalVariants }) => {
const ConfigurationForm = ({ project, handleFileUpload, file, owner, setOwner, name, setName, description, setDescription, repo, onRepoChange, repoVersion, setRepoVersion, showRequiredErrors, versions, mappedSources, targetSourcesFromRows, algosSelected, setAlgosSelected, sx, algos, validColumns, columns, isValidColumnValue, updateColumn, configure, setConfigure, columnVisibilityModel, setColumnVisibilityModel, onSave, isSaving, candidatesScore, onScoreChange, includeDefaultFilter, setIncludeDefaultFilter, filters, setFilters, locales, setAIAssistantColumns, AIAssistantColumns, inAIAssistantGroup, lookupConfig, setLookupConfig, encoderModel, setEncoderModel, isCoreUser, requestLimits, canSelectAIModel, canSetAIOutputLocale, canBridge, canScispacy, canUseOrgProjects=true, canUseCustomAlgorithms=true, promptTemplates, promptTemplate, onPromptTemplateChange, AIModels, AIModel, setAIModel, namespace, setNamespace, promptOutputLocale, setPromptOutputLocale, inputLocale, setInputLocale, oclLocales, useLexicalVariants, setUseLexicalVariants }) => {
const { t } = useTranslation();
// A read-only project's settings are shown, not changed: every field that
// changes them is disabled (OpenConceptLab/ocl_online#424).
Expand Down Expand Up @@ -135,7 +135,7 @@ const ConfigurationForm = ({ project, handleFileUpload, file, owner, setOwner, n
const configErrors = getProjectConfigErrors(algosSelected)
const hasConfigErrors = configErrors.length > 0
const hasTargetRepoVersion = hasSelectedTargetRepoVersion(repoVersion)
const isTargetRepoVersionInError = Boolean(showTargetRepoVersionError && !hasTargetRepoVersion)
const isTargetRepoVersionInError = Boolean(showRequiredErrors && !hasTargetRepoVersion)
const getAlgos = () => getPreviewAlgorithmOptions({
algos,
algosSelected,
Expand Down Expand Up @@ -186,6 +186,7 @@ const ConfigurationForm = ({ project, handleFileUpload, file, owner, setOwner, n
disabled={locked}
sx={{marginTop: '12px'}}
label={t('common.name')}
error={Boolean(showRequiredErrors && !name?.trim())}
value={name}
onChange={event => setName(event.target.value || '')}
/>
Expand Down Expand Up @@ -221,10 +222,11 @@ const ConfigurationForm = ({ project, handleFileUpload, file, owner, setOwner, n
disabled={locked || Boolean(project?.id && project.input_file_name)}
>
{
file?.name ? file.name : t('map_project.upload_file')
file?.name ? file.name : <>{t('map_project.upload_file')}<span aria-hidden='true'>&nbsp;*</span></>
}
<VisuallyHiddenInput
type="file"
required
accept=".xlsx, .xls, .csv"
onChange={handleFileUpload}
/>
Expand Down Expand Up @@ -273,7 +275,7 @@ const ConfigurationForm = ({ project, handleFileUpload, file, owner, setOwner, n
</FormHelperText>

<LockedFields>
<RepoSearchAutocomplete label={t('map_project.repository')} size='small' onChange={(id, item) => onRepoChange(item)} value={repo} suggested={getSuggestedRepos()} sx={{marginTop: '12px'}} disabled={locked}/>
<RepoSearchAutocomplete label={t('map_project.repository')} size='small' onChange={(id, item) => onRepoChange(item)} value={repo} suggested={getSuggestedRepos()} sx={{marginTop: '12px'}} disabled={locked} error={isTargetRepoVersionInError && !repo?.url}/>
<RepoVersionSearchAutocomplete
versions={versions}
label={t('common.version')}
Expand Down Expand Up @@ -604,7 +606,7 @@ const ConfigurationForm = ({ project, handleFileUpload, file, owner, setOwner, n
sx={{textTransform: 'none', margin: '20px 5px 5px 0px'}}
startIcon={lock ? <LockMark /> : <SaveIcon />}
onClick={onSave}
disabled={locked || !name || !file?.name || !owner || hasConfigErrors || hasAccessErrors}
disabled={locked || hasConfigErrors || hasAccessErrors}
loading={isSaving}
loadingPosition="start"
>
Expand Down
160 changes: 104 additions & 56 deletions src/components/map-projects/MapProject.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ import chunk from 'lodash/chunk'
import get from 'lodash/get'
import omit from 'lodash/omit'
import omitBy from 'lodash/omitBy'
import reject from 'lodash/reject'
import uniq from 'lodash/uniq'
import compact from 'lodash/compact'
import keyBy from 'lodash/keyBy'
Expand Down Expand Up @@ -85,7 +84,7 @@ import { buildPanelPayload } from './openConceptPanel'
import LoaderDialog from '../common/LoaderDialog'
import Error403 from '../errors/Error403'
import { HEADERS, SEMANTIC_SEARCH_HEADERS, ROW_STATES, VIEWS, DECISION_TABS, ROW_STAGES, PROMPTS_KEY_DEFAULT, PROMPTS_ACTION_TYPE_DEFAULT, SCORES_COLOR } from './constants'
import { updateColumnState, resuggestColumns, applyTemplateColumns } from './columnSuggestions'
import { updateColumnState, resuggestColumns, applyTemplateColumns, getMissingColumns } from './columnSuggestions'
import MapProjectDeleteConfirmDialog from './MapProjectDeleteConfirmDialog';
import ConfigurationForm from './ConfigurationForm'
import Controls from './Controls'
Expand All @@ -95,6 +94,7 @@ import { aiOnByDefault, getMaxRunRows, getMapperSettings } from '@openconceptlab
import { createAutosaveScheduler, createLatestSender, isToldOnLeave, recordReadOnlyRefusal, saveOnLeave, sendAfter, trackSave, whenSaved, installUnloadGuard, SAVE_SKIPPED } from './autosave'
import { blockLeaving, continueLeaving, createEditTracker, createRunClosers, getRunLeaveMessageKey, isUnsavedNewProject, shouldAskBeforeLeaving, shouldWarnBeforeUnload } from './leaveGuard'
import { editProposed, getColumnsSnapshot } from './unsavedEdits'
import { getAlgosForRelease, toSelectedAlgo } from './selectedAlgos'
import MatchSummaryCard from './MatchSummaryCard'
import MappingDecisionResult from './MappingDecisionResult'
import DecisionSelector from './DecisionSelector'
Expand Down Expand Up @@ -233,6 +233,9 @@ const MapProject = () => {
const [appliedFacets, setAppliedFacets] = React.useState({});
const [searchResponse, setSearchResponse] = React.useState({});
const [algosSelected, setAlgosSelected] = React.useState([])
// Once the algorithms are someone's choice, OCL Semantic is no longer selected by
// default (OpenConceptLab/ocl_online#841). A saved or copied project's already are.
const algosChosenRef = React.useRef(Boolean(params.projectId || templateFromProjectURL))
const [notes, setNotes] = React.useState({})
const [mapTypes, setMapTypes] = React.useState({})
const [proposed, setProposed] = React.useState({})
Expand Down Expand Up @@ -548,8 +551,9 @@ const MapProject = () => {
// repo state
const [repo, setRepo] = React.useState(false)
const [repoVersion, setRepoVersion] = React.useState(false)
// Version shows its error only after a save without one.
const [showTargetRepoVersionError, setShowTargetRepoVersionError] = React.useState(false)
// A required field that's empty shows its error after a save it refused,
// until a save goes through.
const [showRequiredErrors, setShowRequiredErrors] = React.useState(false)
const [mappedSources, setMappedSources] = React.useState([])
const [bridgeMappedSources, setBridgeMappedSources] = React.useState({})
// One read of each version's list, shared by the target and the bridge probe.
Expand Down Expand Up @@ -1773,25 +1777,44 @@ const MapProject = () => {
})
}

// What's missing for a save, in the form's order, as the messages it's
// refused with (OpenConceptLab/ocl_online#841). A save needs the version, not
// the repository's details, so Repository counts only when the version is
// missing too.
const getMissingRequired = isVersionMissing => {
const fields = compact([
!owner && t('map_project.project_owner'),
!name?.trim() && t('common.name'),
!file?.name && t('map_project.upload_file'),
isVersionMissing && !repo?.url && t('map_project.repository'),
isVersionMissing && t('common.version')
])
const missingColumns = file?.name ? getMissingColumns(columns) : []
return compact([
fields.length && t('map_project.missing_required_field', {count: fields.length, names: fields.join(', ')}),
missingColumns.length && t('map_project.missing_required_column_mapping', {names: missingColumns.join(', ')})
])
}

const onSave = (options = {}) => {
const isAutoSave = options.source === 'auto'
if(isAutoSave && (!project?.id || readOnlyRef.current))
return
if(!isAutoSave)
autosaveSchedulerRef.current.cancel()
if(!repoVersion?.version_url || !selectedTargetRepoVersion) {
// Only a missing version refuses an autosave, and a saved project keeps its
// work whatever else its settings lack. A refusal names all that's missing.
const isVersionMissing = !repoVersion?.version_url || !selectedTargetRepoVersion
const errors = getMissingRequired(isVersionMissing)
if(isVersionMissing || (!isAutoSave && errors.length)) {
setConfigure(true)
setShowTargetRepoVersionError(true)
setAlert({
message: t(
'map_project.target_repo_version_required',
'Select a target repository version before saving.'
),
severity: 'error',
duration: 8
})
setShowRequiredErrors(true)
setAlert({message: errors.join(' '), severity: 'error', duration: 8, isRefusedSave: true})
return
}
// After the checks, so a refused save leaves a pending autosave to run.
if(!isAutoSave) {
autosaveSchedulerRef.current.cancel()
setAlert(prev => prev?.isRefusedSave ? false : prev)
}
const rowLogsForSave = options.logs || logsRef.current
const projectLogsForSave = options.projectLogs || projectLogsRef.current
const editsInSave = editTrackerRef.current.saving()
Expand Down Expand Up @@ -1882,6 +1905,7 @@ const MapProject = () => {
const status = response?.response?.status || response?.status
const errorData = response?.response?.data || (response?.data?.id ? null : response?.data)
if(response?.data?.id) {
setShowRequiredErrors(false)
const saveLog = {
action: isAutoSave ? 'Auto Saved' : (isUpdate ? 'Updated' : 'Created'),
description: isAutoSave ? t('map_project.auto_saved_changes') : undefined,
Expand Down Expand Up @@ -2325,30 +2349,34 @@ const MapProject = () => {
})
}

const onRepoVersionChange = version => {
const onRepoVersionChange = (version, isRestored=false) => {
setRepoVersion(version || false)
setShowTargetRepoVersionError(false)
// A slower read of an earlier version doesn't overwrite this one's list.
stopTargetMappedSourcesRef.current()
stopTargetMappedSourcesRef.current = () => {}
if(version?.version_url) {
setLocales(getDeclaredLocales(version))
stopTargetMappedSourcesRef.current = readMappedSources(version.version_url, setMappedSources)
updateAlgosByRepoVersion(version)
updateAlgosByRepoVersion(version, isRestored)
} else {
setMappedSources([])
setLocales([])
}
}

const updateAlgosByRepoVersion = version => {
const isLLMAlgoAllowed = version?.match_algorithms?.includes('llm')
const index = algos.findIndex(algo => algo.type === 'ocl-semantic')
if(index > -1) {
if(find(algosSelected, {type: 'ocl-semantic'}) && !isLLMAlgoAllowed) {
setAlgosSelected(reject(algosSelected, {type: 'ocl-semantic'}))
}
}
// The versions can load after the algorithms change, so this works on the
// list as it is then.
const updateAlgosByRepoVersion = (version, isRestored) => {
const defaultAlgo = algosChosenRef.current || projectIdRef.current ? null :
toSelectedAlgo(find(algos, {type: 'ocl-semantic'}), requestLimits)
setAlgosSelected(prev => getAlgosForRelease(prev, version, {defaultAlgo, isRestored}))
}

// The form's changes: only adding or removing an algorithm changes how many there are.
const onAlgosSelectedChange = next => {
if(Array.isArray(next) && next.length !== algosSelected.length)
algosChosenRef.current = true
setAlgosSelected(next)
}

const getFilters = () => {
Expand Down Expand Up @@ -3225,7 +3253,10 @@ const MapProject = () => {
setVersions(fetchedVersions || [])
setVersionsStatus(fetchedVersions ? null : 'failed')
noteTargetReadThrottle(response)
onRepoVersionChange(savedVersion === undefined ? getDefaultTargetRepoVersion(fetchedVersions) : getSavedTargetRepoVersion(fetchedVersions, savedVersion))
if(savedVersion === undefined)
onRepoVersionChange(getDefaultTargetRepoVersion(fetchedVersions))
else
onRepoVersionChange(getSavedTargetRepoVersion(fetchedVersions, savedVersion), true)
})
}

Expand Down Expand Up @@ -3338,6 +3369,11 @@ const MapProject = () => {
event.stopPropagation()
event.preventDefault()
setAutoMatchScope(getSelectedRowIndexes().length ? 'selected' : (rowStatuses.unmapped.length ? 'unmapped' : 'all'))
applyAutoMatchAIDefault()
setMatchDialog(true)
}

const applyAutoMatchAIDefault = () => {
if(inAIAssistantGroup) {
const { runAI, applied } = getAutoMatchAIOnOpen({
current: autoRunAIAnalysis,
Expand All @@ -3349,7 +3385,19 @@ const MapProject = () => {
autoMatchAIDefaultAppliedRef.current = applied
setAutoRunAIAnalysis(runAI)
}
setMatchDialog(true)
}

// The project's logs, and the user's access to the OCL AI Assistant, can load
// after the dialog opened. The box takes its default then, unless the user
// has already changed it.
React.useEffect(() => {
if(matchDialog && !autoMatchAIDefaultAppliedRef.current)
applyAutoMatchAIDefault()
}, [projectLogs, inAIAssistantGroup])

const onAutoRunAIAnalysisChange = runAI => {
autoMatchAIDefaultAppliedRef.current = true
setAutoRunAIAnalysis(runAI)
}

const onAutoMatchConfigure = () => {
Expand Down Expand Up @@ -6500,13 +6548,13 @@ const MapProject = () => {
onRepoChange={onRepoChange}
repoVersion={repoVersion}
setRepoVersion={onRepoVersionChange}
showTargetRepoVersionError={showTargetRepoVersionError}
showRequiredErrors={showRequiredErrors}
mappedSources={mappedSources}
targetSourcesFromRows={targetSourcesFromRows}
versions={versions}
algos={algos}
algosSelected={algosSelected}
setAlgosSelected={setAlgosSelected}
setAlgosSelected={onAlgosSelectedChange}
validColumns={headers}
columns={columns}
isValidColumnValue={isValidColumnValue}
Expand Down Expand Up @@ -6611,6 +6659,30 @@ const MapProject = () => {
loadingProject &&
<LoaderDialog open message={t('map_project.loading_project')}/>
}
<Snackbar
open={Boolean(alert?.message)}
autoHideDuration={alertDuration}
onClose={onAlertClose}
anchorOrigin={{vertical: 'top', horizontal: 'center'}}
>
<Alert
severity={alert?.severity || 'error'}
onClose={onAlertClose}
action={
<IconButton
aria-label="close"
color="inherit"
size="small"
onClick={() => setAlert(false)}
>
<CloseIcon fontSize="inherit" />
</IconButton>
}
sx={{ width: '100%' }}
>
{alert?.message}
</Alert>
</Snackbar>
<Split
sizes={getSplitWidths()}
minSize={isSplitView ? 200 : 1000}
Expand Down Expand Up @@ -6819,30 +6891,6 @@ const MapProject = () => {
onSearchTextChange={setSearchText}
searchValue={headerRowSearch}
/>
<Snackbar
open={Boolean(alert?.message)}
autoHideDuration={alertDuration}
onClose={onAlertClose}
anchorOrigin={{vertical: 'top', horizontal: 'center'}}
>
<Alert
severity={alert?.severity || 'error'}
onClose={onAlertClose}
action={
<IconButton
aria-label="close"
color="inherit"
size="small"
onClick={() => setAlert(false)}
>
<CloseIcon fontSize="inherit" />
</IconButton>
}
sx={{ width: '100%' }}
>
{alert?.message}
</Alert>
</Snackbar>
<div
style={{ width: '100%', height: `calc(var(--app-height) - ${getGridHeightFactor()}px)` }}
onPointerDownCapture={handleGridPointerDownCapture}
Expand Down Expand Up @@ -7013,7 +7061,7 @@ const MapProject = () => {
setAutoMatchScope,
selectedRowCount: selectedRowsCount,
autoRunAIAnalysis,
setAutoRunAIAnalysis,
setAutoRunAIAnalysis: onAutoRunAIAnalysisChange,
AIModels,
AIModel,
setAIModel,
Expand Down
11 changes: 2 additions & 9 deletions src/components/map-projects/MultiAlgoSelector.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ import { needsSessionToken, getTokenFlag, tokenInputValue, removeSavedToken } fr
import { getRequestLimits, getRequestSettings } from './requestLimits'
import { dropVersion } from '../../common/utils'
import { LockedFields, useEditLock } from '../common/NoticeLock'
import { patchSelected, customCheckReply } from './selectedAlgos'
import { patchSelected, customCheckReply, toSelectedAlgo } from './selectedAlgos'
import {
applyBridgeCanonical,
getDefaultBridgeRepoVersion,
Expand Down Expand Up @@ -357,14 +357,7 @@ export default function MultiAlgoSelector({
id = `${id}-1`
name = `${name}-1`
}
const defaults = {
...omit(algo, ['getIcon', 'disabled', 'description', 'url']),
id: id,
name: name,
batch_size: getRequestSettings(algo, requestLimits).batchSize,
concurrent_requests: getRequestSettings(algo, requestLimits).concurrentRequests,
__key: Math.random(100).toString()
};
const defaults = {...toSelectedAlgo(algo, requestLimits), id, name};

commitValue([...(latestValueRef.current || []), defaults]);
setExpanded((prev) => {
Expand Down
Loading
Loading