Skip to content
Draft
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
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ function CustomEditTables({
? formsText.configureDataEntryTables()
: formsText.configureInteractionTables()
}
isNoRestrictionMode={false}
showHiddenTables={false}
tables={tables}
onChange={handleChange}
onClose={handleClose}
Expand Down
136 changes: 136 additions & 0 deletions specifyweb/frontend/js_src/lib/components/DataViews/DataViewTables.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import React from 'react';
import { useBooleanState } from '../../hooks/useBooleanState';
import { commonText } from '../../localization/common';
import { schemaText } from '../../localization/schema';
import { GetSet, RA } from '../../utils/types';
import { Ul } from '../Atoms';
import { Button } from '../Atoms/Button';
import { DataEntry } from '../Atoms/DataEntry';
import { icons } from '../Atoms/Icons';
import { Link } from '../Atoms/Link';
import { SpecifyTable } from '../DataModel/specifyTable';
import { getTableById, strictGetTable } from '../DataModel/tables';
import { Tables } from '../DataModel/types';
import { Dialog, dialogClassNames } from '../Molecules/Dialog';
import { TableIcon } from '../Molecules/TableIcon';
import { userPreferences } from '../Preferences/userPreferences';
import { OverlayContext } from '../Router/Router';
import { tablesFilter } from '../SchemaConfig/Tables';
import { TablesListEdit } from '../Toolbar/QueryTablesEdit';
import { dataViewsText } from '../../localization/dataViews';

const defaultDataViewTablesConfig: RA<keyof Tables> = [
'Accession',
'AddressOfRecord',
'Agent',
'Appraisal',
'Author',
'Borrow',
'CollectingEvent',
'CollectingTrip',
'Collection',
'CollectionObject',
'CollectionObjectGroup',
'ConservDescription',
'Container',
'DNASequence',
'Deaccession',
'Determination',
'Discipline',
'Disposal',
'Division',
'ExchangeIn',
'ExchangeOut',
'Exsiccata',
'FieldNotebook',
'Geography',
'GeologicTimePeriod',
'Gift',
'InfoRequest',
'Institution',
'Journal',
'LithoStrat',
'Loan',
'Locality',
'MaterialSample',
'PaleoContext',
'Permit',
'Preparation',
'PrepType',
'ReferenceWork',
'RepositoryAgreement',
'Shipment',
'Storage',
'Taxon',
'TectonicUnit',
'TreatmentEvent',
];

export function DataViewTables(): JSX.Element {
const handleClose = React.useContext(OverlayContext);
const [tables, setTables] = useDataViewTables();
const [isEditing, handleEditing] = useBooleanState();
return isEditing ? (
<TablesListEdit
defaultTables={defaultDataViewTablesConfig}
header={dataViewsText.configureDataViews()}
tables={tables}
onChange={setTables}
onClose={handleClose}
/>
) : (
<Dialog
header={schemaText.tables()}
buttons={
<>
<span className="-ml-2 flex-1" />
<Button.Secondary onClick={handleClose}>
{commonText.close()}
</Button.Secondary>
</>
}
className={{
container: dialogClassNames.narrowContainer,
}}
headerButtons={<DataEntry.Edit onClick={handleEditing} />}
icon={icons.eye}
onClose={handleClose}
>
{/* REFACTOR: Generalize QueryTables component */}
<Ul className="flex flex-col gap-1">
{tables.map(({ name, label }, index) => (
<li className="contents" key={index}>
<Link.Default href={`/specify/dataviews/${name.toLowerCase()}`}>
<TableIcon label={false} name={name} />
{label}
</Link.Default>
</li>
))}
</Ul>
</Dialog>
);
}

function useDataViewTables(): GetSet<RA<SpecifyTable>> {
const [tables, setTables] = userPreferences.use(
'dataViews',
'general',
'shownTables'
);
const visibleTables =
tables.length === 0
? defaultDataViewTablesConfig.map(strictGetTable)
: tables.map(getTableById);

const allowedTables = visibleTables.filter((table) =>
tablesFilter(true, false, true, table)
);

const handleChange = React.useCallback(
(models: RA<SpecifyTable>) =>
setTables(models.map((model) => model.tableId)),
[setTables]
);

return [allowedTables, handleChange];
}
123 changes: 123 additions & 0 deletions specifyweb/frontend/js_src/lib/components/DataViews/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import React from 'react';
import { useParams } from 'react-router-dom';
import { DEFAULT_FETCH_LIMIT, fetchCollection } from '../DataModel/collection';
import { AnySchema, SerializedResource } from '../DataModel/helperTypes';
import { SpecifyTable } from '../DataModel/specifyTable';
import { getTable } from '../DataModel/tables';
import { ProtectedTable } from '../Permissions/PermissionDenied';
import { RecordSelectorFromIds } from '../FormSliders/RecordSelectorFromIds';
import { NotFoundView } from '../Router/NotFoundView';
import { f } from '../../utils/functools';
import { dataViewsText } from '../../localization/dataViews';
import { usePaginatedCollection } from '../../hooks/usePaginatedCollection';
import { Tables } from '../DataModel/types';
import { useAsyncState } from '../../hooks/useAsyncState';
import { RA } from '../../utils/types';

export function TableDataView(): JSX.Element {
const { tableName = '' } = useParams();

const table = getTable(tableName);

return table === undefined ? (
<NotFoundView />
) : (
<ProtectedTable tableName={table.name} action="read">
<DataViewFromTableWrapped table={table} />
</ProtectedTable>
);
}

function DataViewFromTableWrapped<SCHEMA extends AnySchema>({
table,
}: {
readonly table: SpecifyTable<SCHEMA>;
}): JSX.Element | null {
const handleFetchingCollection = React.useCallback(
(offset: number = 0) =>
fetchCollection(table.name, {
offset,
limit: DEFAULT_FETCH_LIMIT,
domainFilter: true,
orderBy:
table.getLiteralField('timestampCreated') === undefined
? '-id'
: '-timestampcreated',
}),
[table]
);
const [collection] = useAsyncState(handleFetchingCollection, true);

return collection === undefined ? null : (
<DataViewFromTable
table={table}
initialRecords={collection.records}
totalCount={collection.totalCount}
onFetchRecords={(index) =>
handleFetchingCollection(index).then(({ records }) => records)
}
/>
);
}

function DataViewFromTable<SCHEMA extends AnySchema>({
table,
totalCount: initialTotalCount,
initialRecords,
onFetchRecords: handleFetchRecords,
}: {
readonly table: SpecifyTable<SCHEMA>;
readonly totalCount: number;
readonly initialRecords: RA<SerializedResource<Tables[SCHEMA['tableName']]>>;
readonly onFetchRecords: (
index: number
) => Promise<RA<SerializedResource<Tables[SCHEMA['tableName']]>>>;
}): JSX.Element | null {
// FEATURE: Use useNavigator and keep current record/index in query
// parameter of page

const {
results: [collection],
totalCount: [totalCount],
onFetchMore: handleFetchMore,
} = usePaginatedCollection({
fetchMore: handleFetchRecords,
initialRecords,
totalCount: initialTotalCount,
});

return collection === undefined ? null : (
<RecordSelectorFromIds
canRemove={false}
defaultIndex={0}
// FEATURE: Add support for sorting on one or more fields, and specifying
// whether records should be scoped or not
// headerButtons={
// <>
// <span className="-ml-2 " />
// <OrderPicker
// table={table}
// order={'catalogNumber'}
// onChange={(order) => order}
// />
// </>
// }
dialog={false}
ids={collection.map(({ id }) => id)}
isDependent={false}
isInRecordSet={false}
newResource={undefined}
table={table}
title={dataViewsText.tableRecords({ tableLabel: table.label })}
totalCount={totalCount}
onAdd={undefined}
onClone={undefined}
onClose={() => undefined}
onDelete={undefined}
onSaved={f.void}
onSlide={(new_index) => {
handleFetchMore(new_index);
}}
/>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { treeText } from '../../localization/tree';
import { wbText } from '../../localization/workbench';
import { getCache } from '../../utils/cache';
import { f } from '../../utils/functools';
import type { IR } from '../../utils/types';
import { IR, localized } from '../../utils/types';
import { ensure } from '../../utils/types';
import { icons } from '../Atoms/Icons';
import {
Expand Down Expand Up @@ -76,6 +76,11 @@ const rawMenuItems = ensure<IR<Omit<MenuItem, 'name'>>>()({
hasToolPermission('queryBuilder', 'read') ||
hasPermission('/querybuilder/query', 'execute'),
},
dataViews: {
url: '/specify/overlay/dataviews/',
title: localized('Data Views'),
icon: icons.eye,
},
recordSets: {
url: '/specify/overlay/record-sets/',
title: commonText.recordSets(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ import type {
PreferencesVisibilityContext,
} from './types';
import { definePref } from './types';
import { dataViewsText } from '../../localization/dataViews';

const isLightMode = ({
isDarkMode,
Expand Down Expand Up @@ -1889,6 +1890,24 @@ export const userPreferenceDefinitions = {
},
},
},
dataViews: {
title: dataViewsText.dataViewsTitle(),
subCategories: {
general: {
title: preferencesText.general(),
items: {
shownTables: definePref<RA<number>>({
title: localized('_shownTables'),
requiresReload: false,
visible: false,
defaultValue: [],
renderer: f.never,
container: 'div',
}),
},
},
}
},
recordMerging: {
title: mergingText.recordMerging(),
subCategories: {
Expand Down
16 changes: 14 additions & 2 deletions specifyweb/frontend/js_src/lib/components/QueryBuilder/Results.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { LocalizedString } from 'typesafe-i18n';

import { useAsyncState } from '../../hooks/useAsyncState';
import { useInfiniteScroll } from '../../hooks/useInfiniteScroll';
import { usePaginatedCollection } from '../../hooks/usePaginatedCollection';
import { commonText } from '../../localization/common';
import { interactionsText } from '../../localization/interactions';
import { f } from '../../utils/functools';
Expand Down Expand Up @@ -31,7 +32,6 @@ import { CreateRecordSet } from './CreateRecordSet';
import type { QueryFieldSpec } from './fieldSpec';
import type { QueryField } from './helpers';
import { sortTypes } from './helpers';
import { useFetchQueryResults } from './hooks';
import { QueryResultsTable } from './ResultsTable';
import { QueryToForms } from './ToForms';
import { QueryToMap } from './ToMap';
Expand Down Expand Up @@ -119,7 +119,19 @@ export function QueryResults(props: QueryResultsProps): JSX.Element {
onFetchMore: handleFetchMore,
totalCount: [totalCount, setTotalCount],
canFetchMore,
} = useFetchQueryResults(props);
} = usePaginatedCollection<QueryResultRow | undefined>({
initialRecords: initialData,
fetchMore: fetchResults,
fetchSize: props.fetchSize,
totalCount: props.totalCount,
});

// const {
// results: [results, setResults],
// onFetchMore: handleFetchMore,
// totalCount: [totalCount, setTotalCount],
// canFetchMore,
// } = useFetchQueryResults(props);

const canMergeTable = canMerge(table);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@ import { treeText } from '../../localization/tree';
import { userText } from '../../localization/user';
import { welcomeText } from '../../localization/welcome';
import { wbText } from '../../localization/workbench';
import type { RA } from '../../utils/types';
import { RA } from '../../utils/types';
import { Redirect } from './Redirect';
import type { EnhancedRoute } from './RouterUtils';
import { dataViewsText } from '../../localization/dataViews';

/* eslint-disable @typescript-eslint/promise-function-async */
/**
Expand Down Expand Up @@ -141,6 +142,14 @@ export const overlayRoutes: RA<EnhancedRoute> = [
},
],
},
{
path: 'dataviews',
title: dataViewsText.dataViewsTitle(),
element: () =>
import('../DataViews/DataViewTables').then(
({ DataViewTables }) => DataViewTables
),
},
{
path: 'record-sets',
title: commonText.recordSets(),
Expand Down
Loading
Loading