repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
manuel-hegner/conquery
frontend/src/js/external-forms/FormConfigSaver.tsx
<filename>frontend/src/js/external-forms/FormConfigSaver.tsx import styled from "@emotion/styled"; import { StateT } from "app-types"; import React, { FC, useState, useEffect } from "react"; import { useTranslation } from "react-i18next"; import { useSelector, useDispatch } from "react-redux"; import { usePatchFormConfig, useGetFormConfig, usePostFormConfig, } from "../api/api"; import IconButton from "../button/IconButton"; import { FORM_CONFIG } from "../common/constants/dndTypes"; import { usePrevious } from "../common/helpers/usePrevious"; import { useDatasetId } from "../dataset/selectors"; import FaIcon from "../icon/FaIcon"; import { setMessage } from "../snack-message/actions"; import WithTooltip from "../tooltip/WithTooltip"; import Dropzone from "../ui-components/Dropzone"; import EditableText from "../ui-components/EditableText"; import Label from "../ui-components/Label"; import { loadExternalFormValues, setExternalForm } from "./actions"; import { DragItemFormConfig } from "./form-configs/FormConfig"; import { useLoadFormConfigs } from "./form-configs/selectors"; import { selectActiveFormValues, useSelectActiveFormName, selectActiveFormType, } from "./stateSelectors"; const Root = styled("div")` display: flex; align-items: center; margin: 5px 0 20px; border-radius: ${({ theme }) => theme.borderRadius}; `; const SxLabel = styled(Label)` margin: 0; `; const SxEditableText = styled(EditableText)<{ editing: boolean }>` margin: ${({ editing }) => (editing ? "" : "5px 0 0px 8px")}; font-weight: 700; `; const Row = styled("div")` display: flex; align-items: center; `; const SpacedRow = styled(Row)` justify-content: space-between; width: 100%; `; const DirtyFlag = styled("div")` width: 7px; height: 7px; background-color: ${({ theme }) => theme.col.blueGrayDark}; border-radius: 50%; margin: 0 4px; flex-shrink: 0; `; const SxDropzone = styled(Dropzone)` color: #333; `; const LoadingText = styled("p")` font-weight: 400; margin: 3px 0 0px 8px; `; const SxFaIcon = styled(FaIcon)` margin-right: 5px; `; const hasChanged = (a: any, b: any) => { return JSON.stringify(a) !== JSON.stringify(b); }; const FormConfigSaver: FC = () => { const { t } = useTranslation(); const dispatch = useDispatch(); const datasetId = useDatasetId(); const [editing, setEditing] = useState<boolean>(false); const [formConfigId, setFormConfigId] = useState<string | null>(null); const [isDirty, setIsDirty] = useState<boolean>(true); const [isSaving, setIsSaving] = useState<boolean>(false); const [isLoading, setIsLoading] = useState<boolean>(false); const formValues = useSelector<StateT, Record<string, any>>((state) => selectActiveFormValues(state), ); const previousFormValues = usePrevious(formValues); const activeFormName = useSelectActiveFormName(); const activeFormType = useSelector<StateT, string | null>((state) => selectActiveFormType(state), ); const { loadFormConfigs } = useLoadFormConfigs(); const postFormConfig = usePostFormConfig(); const getFormConfig = useGetFormConfig(); const patchFormConfig = usePatchFormConfig(); function getUntitledName(name: string) { return `${name} ${new Date().toISOString().split("T")[0]}`; } const [configName, setConfigName] = useState<string>( getUntitledName(activeFormName), ); useEffect(() => { setConfigName(getUntitledName(activeFormName)); }, [activeFormName]); useEffect(() => { setIsDirty(true); setFormConfigId(null); }, [configName]); useEffect(() => { if (hasChanged(previousFormValues, formValues)) { setIsDirty(true); } }, [formValues, previousFormValues]); async function onSubmit() { if (!datasetId) return; setIsSaving(true); try { if (formConfigId) { await patchFormConfig(datasetId, formConfigId, { label: configName, values: formValues, }); setIsDirty(false); loadFormConfigs(datasetId); } else if (activeFormType) { const result = await postFormConfig(datasetId, { label: configName, formType: activeFormType, values: formValues, }); setFormConfigId(result.id); setIsDirty(false); loadFormConfigs(datasetId); } } catch (e) { dispatch(setMessage({ message: t("externalForms.config.saveError") })); } setIsSaving(false); } async function onLoad(dragItem: DragItemFormConfig) { if (!datasetId) return; setIsLoading(true); setIsDirty(false); try { const config = await getFormConfig(datasetId, dragItem.id); if (config.formType !== activeFormType) { dispatch(setExternalForm(config.formType)); } dispatch(loadExternalFormValues(config.formType, config.values)); setConfigName(config.label); setIsDirty(false); } catch (e) { dispatch(setMessage({ message: t("formConfig.loadError") })); } setIsLoading(false); } return ( <Root> <SxDropzone<FC<DropzoneProps<DragItemFormConfig>>> onDrop={onLoad} acceptedDropTypes={[FORM_CONFIG]} > {() => ( <SpacedRow> <div> <SxLabel>{t("externalForms.config.headline")}</SxLabel> <Row> {isLoading ? ( <LoadingText> <SxFaIcon icon="spinner" /> {t("common.loading")} </LoadingText> ) : ( <> <SxEditableText loading={false} editing={editing} onToggleEdit={() => setEditing(!editing)} text={configName || ""} saveOnClickoutside onSubmit={(txt: string) => { if (txt) { setConfigName(txt); } setEditing(false); }} /> {isDirty && <DirtyFlag />} </> )} </Row> </div> <WithTooltip lazy text={t("externalForms.config.saveDescription")}> <IconButton frame icon={isSaving ? "spinner" : "save"} onClick={onSubmit} > {t("externalForms.config.save")} </IconButton> </WithTooltip> </SpacedRow> )} </SxDropzone> </Root> ); }; export default React.memo(FormConfigSaver);
manuel-hegner/conquery
frontend/src/js/external-forms/reducer.ts
import { combineReducers, Reducer } from "redux"; import { reducer as reduxFormReducer, FormReducerMapObject, FormStateMap, } from "redux-form"; import type { QueryNodeEditorStateT } from "../query-node-editor/reducer"; import createQueryRunnerReducer, { QueryRunnerStateT, } from "../query-runner/reducer"; import { SET_EXTERNAL_FORM, LOAD_EXTERNAL_FORM_VALUES } from "./actionTypes"; import type { Form } from "./config-types"; import { createFormQueryNodeEditorReducer } from "./form-query-node-editor/reducer"; import { collectAllFormFields } from "./helper"; function collectConceptListFieldNames(config: Form) { const fieldNames = collectAllFormFields(config.fields) .filter((field) => field.type === "CONCEPT_LIST") .map((field) => field.name); return [...new Set(fieldNames)]; } export interface FormContextStateT { [conceptListFieldName: string]: QueryNodeEditorStateT; } function buildFormReducer(form: Form) { const conceptListFieldNames = collectConceptListFieldNames(form); if (conceptListFieldNames.length === 0) return () => null; return combineReducers( conceptListFieldNames.reduce((combined, name) => { combined[name] = createFormQueryNodeEditorReducer(form.type, name); return combined; }, {}), ); } export interface FormsStateT { activeForm: string | null; queryRunner: QueryRunnerStateT; reduxForm: FormStateMap; availableForms: { [formName: string]: Form; }; formsContext: { [formName: string]: null | FormContextStateT; }; } // Because this function is called multiple times, and the reducers are being replaced // we have to make sure that all reducers in here can deal with a changing default state, // meaning: return it when the default state changes changes, without expecting another @@INIT action const buildExternalFormsReducer = (availableForms: { [formName: string]: Form; }) => { const forms = Object.values(availableForms); const formReducers = forms.reduce<{ [formName: string]: Reducer<FormContextStateT>; }>((all, form) => { const reducer = buildFormReducer(form); if (!reducer) return all; all[form.type] = reducer; return all; }, {}); const defaultFormType = forms.length ? forms[0].type : null; const activeFormReducer = ( state: string | null = defaultFormType, action: any, ): string | null => { switch (action.type) { case SET_EXTERNAL_FORM: return action.payload.form; default: return state || defaultFormType; } }; const availableFormsReducer = () => availableForms; const reduxFormReducerPlugin: FormReducerMapObject = forms.reduce( (all, form) => ({ ...all, [form.type]: (state: any, action: any) => { switch (action.type) { case LOAD_EXTERNAL_FORM_VALUES: { if (action.payload.formType !== form.type) return state; const stateKeys = Object.keys(state.values); const filteredValues = Object.keys(action.payload.values) .filter((key) => stateKeys.includes(key)) .reduce<any>((all, key) => { all[key] = action.payload.values[key]; return all; }, {}); return { ...state, values: { ...state.values, ...filteredValues, }, }; } default: return state; } }, }), {}, ); return combineReducers({ activeForm: activeFormReducer, // Redux-Form reducer to keep the state of all forms: reduxForm: reduxFormReducer.plugin(reduxFormReducerPlugin), // Query Runner reducer that works with external forms queryRunner: createQueryRunnerReducer("externalForms"), availableForms: availableFormsReducer, formsContext: Object.keys(formReducers).length > 0 ? combineReducers(formReducers) : (state = {}) => state, }); }; export default buildExternalFormsReducer;
manuel-hegner/conquery
frontend/src/js/external-forms/form-query-dropzone/FormQueryDropzone.tsx
<gh_stars>10-100 import styled from "@emotion/styled"; import React, { FC } from "react"; import type { WrappedFieldProps } from "redux-form"; import { PREVIOUS_QUERY, PREVIOUS_SECONDARY_ID_QUERY, } from "../../common/constants/dndTypes"; import { exists } from "../../common/helpers/exists"; import type { DragItemQuery } from "../../standard-query-editor/types"; import InfoTooltip from "../../tooltip/InfoTooltip"; import Dropzone from "../../ui-components/Dropzone"; import Label from "../../ui-components/Label"; import Optional from "../../ui-components/Optional"; import FormQueryResult from "./FormQueryResult"; const SxDropzone = styled(Dropzone)<{ centered?: boolean }>` justify-content: ${({ centered }) => (centered ? "center" : "flex-start")}; `; interface PropsT extends WrappedFieldProps { label: string; tooltip?: string; optional?: boolean; dropzoneText: string; className?: string; } const FormQueryDropzone: FC<PropsT> = (props) => { const onDrop = (item: DragItemQuery) => { props.input.onChange(item); }; return ( <div className={props.className}> <Label> {props.optional && <Optional />} {props.label} {exists(props.tooltip) && <InfoTooltip text={props.tooltip} />} </Label> <SxDropzone<FC<DropzoneProps<DragItemQuery>>> onDrop={onDrop} acceptedDropTypes={[PREVIOUS_QUERY, PREVIOUS_SECONDARY_ID_QUERY]} centered={!props.input.value} > {() => !props.input.value ? ( props.dropzoneText ) : ( <FormQueryResult queryResult={props.input.value} onDelete={() => props.input.onChange(null)} /> ) } </SxDropzone> </div> ); }; export default FormQueryDropzone;
manuel-hegner/conquery
frontend/src/js/tooltip/InfoTooltip.tsx
import styled from "@emotion/styled"; import React, { FC, ReactElement } from "react"; import FaIcon from "../icon/FaIcon"; import WithTooltip from "./WithTooltip"; interface PropsT { text?: string; html?: ReactElement; className?: string; noIcon?: boolean; wide?: boolean; } const SxWithTooltip = styled(WithTooltip)` display: inline-block; padding: 0 7px; `; const InfoTooltip: FC<PropsT> = ({ className, text, html, noIcon, wide }) => { return ( <SxWithTooltip className={className} text={text} html={html} wide={wide}> {!noIcon && <FaIcon regular icon="question-circle" />} </SxWithTooltip> ); }; export default InfoTooltip;
manuel-hegner/conquery
frontend/src/js/localization/useActiveLang.ts
import { useTranslation } from "react-i18next"; export type Language = "de" | "en"; export const useActiveLang = () => { const { i18n } = useTranslation(); return (i18n.language as unknown) as Language; };
manuel-hegner/conquery
frontend/src/js/query-runner/QueryRunnerInfo.tsx
import styled from "@emotion/styled"; import React, { FC } from "react"; import { useTranslation } from "react-i18next"; import type { QueryRunnerStateT } from "./reducer"; const Status = styled("p")<{ success?: boolean; error?: boolean }>` font-weight: 400; margin: 0 10px; font-size: ${({ theme }) => theme.font.sm}; color: ${({ theme, success, error }) => success ? theme.col.green : error ? theme.col.red : "initial"}; `; interface PropsT { className?: string; queryRunner: QueryRunnerStateT; } const useMessage = (queryRunner: QueryRunnerStateT) => { const { t } = useTranslation(); if (queryRunner.startQuery.error) { return { type: "error", value: t("queryRunner.startError") }; } else if (queryRunner.stopQuery.error) { return { type: "error", value: t("queryRunner.stopError") }; } else if (!!queryRunner.queryResult && queryRunner.queryResult.error) { return { type: "error", value: queryRunner.queryResult.error, }; } else if (queryRunner.startQuery.success) { return { type: "success", value: t("queryRunner.startSuccess") }; } else if (queryRunner.stopQuery.success) { return { type: "success", value: t("queryRunner.stopSuccess") }; } return null; }; const QueryRunnerInfo: FC<PropsT> = ({ queryRunner, className }) => { const message = useMessage(queryRunner); const { queryResult } = queryRunner; const noQueryResultOrError = !queryResult || (!!queryResult && queryResult.error); if (!message || !noQueryResultOrError) { return null; } return ( <Status className={className} success={message.type === "success"} error={message.type === "error"} > {message.value} </Status> ); }; export default QueryRunnerInfo;
manuel-hegner/conquery
frontend/src/js/external-forms/form-query-dropzone/FormMultiQueryDropzone.tsx
import React, { FC, ReactNode } from "react"; import type { WrappedFieldProps } from "redux-form"; import { PREVIOUS_QUERY, PREVIOUS_SECONDARY_ID_QUERY, } from "../../common/constants/dndTypes"; import { PreviousQueryT } from "../../previous-queries/list/reducer"; import type { DragItemQuery } from "../../standard-query-editor/types"; import type { ChildArgs } from "../../ui-components/Dropzone"; import DropzoneList from "../form-components/DropzoneList"; import FormQueryResult from "./FormQueryResult"; interface PropsT extends WrappedFieldProps { dropzoneChildren: (args: ChildArgs) => ReactNode; label: string; tooltip?: string; optional?: boolean; } const FormMultiQueryDropzone: FC<PropsT> = ({ input, label, tooltip, optional, dropzoneChildren, }) => { const addValue = (newItem) => { input.onChange([...input.value, newItem]); }; const removeValue = (valueIdx: number) => { input.onChange([ ...input.value.slice(0, valueIdx), ...input.value.slice(valueIdx + 1), ]); }; return ( <DropzoneList<DragItemQuery> acceptedDropTypes={[PREVIOUS_QUERY, PREVIOUS_SECONDARY_ID_QUERY]} label={label} optional={optional} tooltip={tooltip} dropzoneChildren={dropzoneChildren} items={input.value.map((query: PreviousQueryT, i: number) => ( <FormQueryResult key={i} queryResult={query} /> ))} onDrop={(item) => { return input.onChange(addValue(item)); }} onDelete={(i: number) => removeValue(i)} ></DropzoneList> ); }; export default FormMultiQueryDropzone;
manuel-hegner/conquery
frontend/src/js/concept-trees/EmptyConceptTreeList.tsx
<filename>frontend/src/js/concept-trees/EmptyConceptTreeList.tsx import styled from "@emotion/styled"; import React from "react"; import { useTranslation } from "react-i18next"; const Root = styled("div")` position: relative; display: flex; width: 100%; flex-direction: column; margin-left: 10px; `; const MsgContainer = styled("div")` display: flex; width: 100%; height: 100%; flex-direction: column; align-items: flex-start; justify-content: center; `; const Msg = styled("div")` width: 400px; white-space: initial; `; const Message = styled("p")` font-size: ${({ theme }) => theme.font.lg}; margin: 10px 0 0; font-weight: 400; `; const SubMessage = styled("p")` font-size: ${({ theme }) => theme.font.md}; margin: 0 0 10px; `; const Preview = styled("div")` border-radius: ${({ theme }) => theme.borderRadius}; background-color: ${({ theme }) => theme.col.grayVeryLight}; height: 20px; margin: 3px 0; `; const Container = styled("div")` padding-left: 20px; display: flex; flex-direction: column; `; const EmptyConceptTreeList = () => { const { t } = useTranslation(); return ( <Root> <MsgContainer> <Msg> <Message>{t("conceptTreeList.noTrees")}</Message> <SubMessage>{t("conceptTreeList.noTreesExplanation")}</SubMessage> </Msg> </MsgContainer> <Preview style={{ width: `${200}px` }} /> <Preview style={{ width: `${100}px` }} /> <Container> <Preview style={{ width: `${250}px` }} /> <Preview style={{ width: `${150}px` }} /> <Preview style={{ width: `${300}px` }} /> <Container> <Preview style={{ width: `${200}px` }} /> <Preview style={{ width: `${50}px` }} /> </Container> </Container> <Preview style={{ width: `${350}px` }} /> <Preview style={{ width: `${200}px` }} /> <Preview style={{ width: `${300}px` }} /> <Preview style={{ width: `${250}px` }} /> </Root> ); }; export default EmptyConceptTreeList;
manuel-hegner/conquery
frontend/src/js/startup/actions.ts
import { useDispatch } from "react-redux"; import { ActionType, createAsyncAction } from "typesafe-actions"; import { useGetFrontendConfig } from "../api/api"; import { GetFrontendConfigResponseT } from "../api/types"; import { ErrorObject, errorPayload, successPayload } from "../common/actions"; export type StartupActions = ActionType<typeof loadConfig>; export const loadConfig = createAsyncAction( "startup/LOAD_CONFIG_START", "startup/LOAD_CONFIG_SUCCESS", "startup/LOAD_CONFIG_ERROR", )<undefined, { data: GetFrontendConfigResponseT }, ErrorObject>(); export const useLoadConfig = () => { const dispatch = useDispatch(); const getFrontendConfig = useGetFrontendConfig(); return async () => { dispatch(loadConfig.request()); try { const result = await getFrontendConfig(); dispatch(loadConfig.success(successPayload(result, {}))); } catch (error) { dispatch(loadConfig.failure(errorPayload(error, {}))); } }; };
manuel-hegner/conquery
frontend/src/js/search-bar/SearchBar.tsx
import styled from "@emotion/styled"; import { useEffect, useState } from "react"; import IconButton from "../button/IconButton"; import { exists } from "../common/helpers/exists"; import BaseInput from "../ui-components/BaseInput"; const InputContainer = styled("div")` flex-grow: 1; position: relative; `; const SxBaseInput = styled(BaseInput)` width: 100%; input { padding-right: 60px; height: 34px; width: 100%; &::placeholder { color: ${({ theme }) => theme.col.grayMediumLight}; opacity: 1; } } `; const Right = styled("div")` position: absolute; top: 0px; right: 30px; display: flex; flex-direction: row; align-items: center; height: 34px; `; const StyledIconButton = styled(IconButton)` padding: 8px 10px; color: ${({ theme }) => theme.col.gray}; `; interface Props { className?: string; searchTerm: string | null; placeholder: string; onSearch: (value: string) => void; onClear: () => void; } const SearchBar = ({ className, searchTerm, placeholder, onSearch, onClear, }: Props) => { const [localSearchTerm, setLocalSearchTerm] = useState<string | null>(null); useEffect(() => { setLocalSearchTerm(searchTerm); }, [searchTerm]); return ( <InputContainer className={className}> <SxBaseInput inputType="text" placeholder={placeholder} value={localSearchTerm || ""} onChange={(value) => { if (!exists(value)) onClear(); setLocalSearchTerm(value as string | null); }} inputProps={{ onKeyPress: (e) => { return e.key === "Enter" && exists(localSearchTerm) ? onSearch(localSearchTerm) : null; }, }} /> {exists(localSearchTerm) && ( <Right> <StyledIconButton icon="search" aria-hidden="true" onClick={() => onSearch(localSearchTerm)} /> </Right> )} </InputContainer> ); }; export default SearchBar;
manuel-hegner/conquery
frontend/src/js/ui-components/Label.tsx
<gh_stars>10-100 import styled from "@emotion/styled"; const Label = styled("span")<{ tiny?: boolean; large?: boolean; disabled?: boolean; fullWidth?: boolean; }>` font-size: ${({ theme, tiny, large }) => large ? theme.font.md : tiny ? theme.font.xs : theme.font.sm}; display: flex; align-items: center; margin: 6px 0 3px; color: ${({ theme, disabled }) => (disabled ? theme.col.gray : "initial")}; width: ${({ fullWidth }) => (fullWidth ? "100%" : "inherit")}; `; export default Label;
manuel-hegner/conquery
frontend/src/js/dataset/selectors.ts
import { StateT } from "app-types"; import { useSelector } from "react-redux"; import { DatasetIdT } from "../api/types"; export const useDatasetId = () => { const datasetId = useSelector<StateT, DatasetIdT | null>( (state) => state.datasets.selectedDatasetId, ); return datasetId; };
manuel-hegner/conquery
frontend/src/js/external-forms/form-tab-navigation/FormTabNavigation.tsx
import styled from "@emotion/styled"; import React, { FC } from "react"; import type { WrappedFieldProps } from "redux-form"; import SmallTabNavigation, { TabOption, } from "../../small-tab-navigation/SmallTabNavigation"; interface PropsT extends WrappedFieldProps { options: TabOption[]; } const SxSmallTabNavigation = styled(SmallTabNavigation)` padding-top: 3px; `; const FormTavNavigation: FC<PropsT> = ({ options, input }) => { return ( <SxSmallTabNavigation size="L" selectedTab={input.value} onSelectTab={input.onChange} options={options} /> ); }; export default FormTavNavigation;
manuel-hegner/conquery
frontend/src/js/ui-components/InputMultiSelect/InputMultiSelectTwo.tsx
<reponame>manuel-hegner/conquery import styled from "@emotion/styled"; import { useCombobox, useMultipleSelection } from "downshift"; import { useState, useMemo } from "react"; import { useTranslation } from "react-i18next"; import type { SelectOptionT } from "../../api/types"; import IconButton from "../../button/IconButton"; import InfoTooltip from "../../tooltip/InfoTooltip"; import InputMultiSelectDropzone from "../InputMultiSelectDropzone"; import Labeled from "../Labeled"; import EmptyPlaceholder from "./EmptyPlaceholder"; import ListOption from "./ListOption"; import MenuActionBar from "./MenuActionBar"; import SelectedItem from "./SelectedItem"; import { useResolvableSelect } from "./useResolvableSelect"; const Control = styled("div")` border: 1px solid ${({ theme }) => theme.col.gray}; border-radius: 4px; display: flex; align-items: center; overflow: hidden; padding: 3px 3px 3px 8px; background-color: white; &:focus { outline: 1px solid black; } `; const SelectContainer = styled("div")` width: 100%; position: relative; `; const ItemsInputContainer = styled("div")` display: flex; align-items: center; flex-wrap: wrap; gap: 3px; width: 100%; `; const Menu = styled("div")` position: absolute; width: 100%; border-radius: 4px; box-shadow: 0 0 0 1px hsl(0deg 0% 0% / 10%), 0 4px 11px hsl(0deg 0% 0% / 10%); background-color: ${({ theme }) => theme.col.bg}; z-index: 2; `; const List = styled("div")` padding: 3px; max-height: 300px; overflow-y: auto; --webkit-overflow-scrolling: touch; `; const Input = styled("input")` border: 0; height: 24px; outline: none; flex-grow: 1; flex-basis: 30px; `; const SxLabeled = styled(Labeled)` padding: 2px; `; const DropdownToggleButton = styled(IconButton)` padding: 5px 6px; `; const ResetButton = styled(IconButton)` padding: 5px 8px; `; const VerticalSeparator = styled("div")` width: 1px; margin: 3px 0; background-color: ${({ theme }) => theme.col.grayVeryLight}; align-self: stretch; flex-shrink: 0; `; const SxInputMultiSelectDropzone = styled(InputMultiSelectDropzone)` display: block; `; interface Props { label?: string; disabled?: boolean; options: SelectOptionT[]; tooltip?: string; indexPrefix?: number; creatable?: boolean; input: { value: SelectOptionT[]; defaultValue?: SelectOptionT[]; onChange: (value: SelectOptionT[]) => void; }; onResolve?: (csvFileLines: string[]) => void; // The assumption is that this will somehow update `options` } const InputMultiSelectTwo = ({ options, input, label, tooltip, indexPrefix, creatable, onResolve, }: Props) => { const { onDropFile } = useResolvableSelect({ defaultValue: input.defaultValue, onResolve, }); const [inputValue, setInputValue] = useState(""); const { t } = useTranslation(); const { getSelectedItemProps, getDropdownProps, addSelectedItem, removeSelectedItem, selectedItems, reset: resetMultiSelectState, setSelectedItems, activeIndex, } = useMultipleSelection<SelectOptionT>({ initialSelectedItems: input.defaultValue, onSelectedItemsChange: (changes) => { if (changes.selectedItems) { input.onChange(changes.selectedItems); } }, }); const filteredOptions = useMemo(() => { const creatableOption = creatable && inputValue.length > 0 ? [ { label: `${t("common.create")}: "${inputValue}"`, value: inputValue, }, ] : []; const regularOptions = options.filter( (option) => selectedItems.indexOf(option) < 0 && (option.label.toLowerCase().includes(inputValue.toLowerCase()) || String(option.value) .toLowerCase() .includes(inputValue.toLowerCase())), ); return [...creatableOption, ...regularOptions]; }, [options, selectedItems, inputValue, creatable, t]); const { isOpen, toggleMenu, getToggleButtonProps, getLabelProps, getMenuProps, getInputProps, getComboboxProps, getItemProps, highlightedIndex, setHighlightedIndex, reset: resetComboboxState, } = useCombobox({ inputValue, items: filteredOptions, stateReducer: (state, { type, changes }) => { // This modifies the action payload itself // in that way // - the default behavior may be adjusted // - including the `onStateChange` reactions that diverge from default behavior (see below) switch (type) { case useCombobox.stateChangeTypes.InputKeyDownEnter: case useCombobox.stateChangeTypes.InputBlur: case useCombobox.stateChangeTypes.ItemClick: const stayAlmostAtTheSamePositionIndex = state.highlightedIndex === filteredOptions.length - 1 ? state.highlightedIndex - 1 : state.highlightedIndex; const hasChosenCreatableItem = creatable && state.highlightedIndex === 0 && inputValue.length > 0; // The item that will be "chosen" const selectedItem = hasChosenCreatableItem ? { value: inputValue, label: inputValue } : changes.selectedItem; return { ...changes, selectedItem, isOpen: true, highlightedIndex: stayAlmostAtTheSamePositionIndex, }; default: return changes; } }, onStateChange: (action) => { // This only modifies the behavior of some of the actions, after the state has been changed switch (action.type) { case useCombobox.stateChangeTypes.InputChange: if (action.highlightedIndex !== 0) { setHighlightedIndex(0); } break; case useCombobox.stateChangeTypes.InputKeyDownEscape: if (action.isOpen) { // Sometimes closing the menu on esc didn't work, this fixes it toggleMenu(); } break; case useCombobox.stateChangeTypes.InputKeyDownEnter: case useCombobox.stateChangeTypes.InputBlur: case useCombobox.stateChangeTypes.ItemClick: if (action.selectedItem) { addSelectedItem(action.selectedItem); const wasNewItemCreated = creatable && action.selectedItem.value === inputValue && action.selectedItem.label === inputValue; if (wasNewItemCreated) { setInputValue(""); } } break; default: break; } }, }); const { ref: menuPropsRef, ...menuProps } = getMenuProps(); const inputProps = getInputProps(getDropdownProps()); const { ref: comboboxRef, ...comboboxProps } = getComboboxProps(); const Select = ( <SelectContainer> <Control {...comboboxProps} ref={(instance) => { comboboxRef(instance); }} > <ItemsInputContainer> {selectedItems.map((option, index) => { const selectedItemProps = getSelectedItemProps({ selectedItem: option, index, }); return ( <SelectedItem key={`${option.value}${index}`} option={option} active={index === activeIndex} {...selectedItemProps} onRemoveClick={() => removeSelectedItem(option)} /> ); })} <Input type="text" value={inputValue} {...inputProps} placeholder={ onResolve ? t("inputMultiSelect.dndPlaceholder") : t("inputSelect.placeholder") } onClick={(e) => { if (inputProps.onClick) { inputProps.onClick(e); } toggleMenu(); }} onChange={(e) => { if (inputProps.onChange) { inputProps.onChange(e); } setInputValue(e.target.value); }} /> </ItemsInputContainer> {(inputValue.length > 0 || selectedItems.length > 0) && ( <ResetButton icon="times" onClick={() => { setInputValue(""); resetMultiSelectState(); resetComboboxState(); }} /> )} <VerticalSeparator /> <DropdownToggleButton icon="chevron-down" {...getToggleButtonProps()} /> </Control> {isOpen ? ( <Menu {...menuProps} ref={(instance) => { menuPropsRef(instance); }} > <MenuActionBar optionsCount={filteredOptions.length} onInsertAllClick={() => { setSelectedItems(filteredOptions); }} /> <List> {!creatable && filteredOptions.length === 0 && <EmptyPlaceholder />} {filteredOptions.map((option, index) => { return ( <ListOption key={`${option.value}`} active={highlightedIndex === index} {...getItemProps({ index, item: filteredOptions[index] })} > {option.label} </ListOption> ); })} </List> </Menu> ) : ( <span ref={menuPropsRef} /> // To avoid a warning / error by downshift that ref is not applied )} </SelectContainer> ); return ( <SxLabeled {...getLabelProps({})} htmlFor="" // Important to override getLabelProps with this to avoid click events everywhere label={ <> {label} {tooltip && <InfoTooltip text={tooltip} />} </> } indexPrefix={indexPrefix} > {!onResolve && Select} {onResolve && onDropFile && ( <SxInputMultiSelectDropzone onDropFile={onDropFile}> {() => Select} </SxInputMultiSelectDropzone> )} </SxLabeled> ); }; export default InputMultiSelectTwo;
manuel-hegner/conquery
frontend/src/js/external-forms/index.ts
<gh_stars>10-100 import { TabT } from "../pane/types"; import FormsTab from "./FormsTab"; import buildExternalFormsReducer from "./reducer"; import { FormsStateT } from "./reducer"; export const tabDescription = { key: "externalForms", }; export type ExternalFormsStateT = FormsStateT | null; const Tab: TabT = { ...tabDescription, labelKey: "rightPane.externalForms", tooltipKey: "help.tabFormEditor", reducer: buildExternalFormsReducer({}), // Will be set when forms are loaded component: FormsTab, }; export default Tab;
manuel-hegner/conquery
frontend/src/js/concept-trees/ConceptTreesLoading.tsx
import styled from "@emotion/styled"; import React from "react"; import { useTranslation } from "react-i18next"; import FaIcon from "../icon/FaIcon"; const Container = styled("div")` display: flex; flex-direction: row; align-items: center; padding: 5px 12px; `; const StyledFaIcon = styled(FaIcon)` margin-right: 10px; `; const ConceptTreesLoading = () => { const { t } = useTranslation(); return ( <Container> <StyledFaIcon icon="spinner" /> <span>{t("conceptTreeList.loading")}</span> </Container> ); }; export default ConceptTreesLoading;
manuel-hegner/conquery
frontend/src/js/standard-query-editor/types.ts
import type { ConceptIdT, QueryIdT, RangeFilterT, MultiSelectFilterT, MultiSelectFilterValueT, SelectFilterT, SelectFilterValueT, SelectorT, TableT, DateRangeT, DateColumnT, QueryT, BigMultiSelectFilterT, InfoT, } from "../api/types"; export interface InfoType { key: string; value: string; } export type RangeFilterWithValueType = RangeFilterT; export interface MultiSelectFilterWithValueType extends MultiSelectFilterT { value?: MultiSelectFilterValueT; } export interface BigMultiSelectFilterWithValueType extends BigMultiSelectFilterT { value?: MultiSelectFilterValueT; } export interface SelectFilterWithValueType extends SelectFilterT { value?: SelectFilterValueT; } export type FilterWithValueType = | SelectFilterWithValueType | MultiSelectFilterWithValueType | BigMultiSelectFilterWithValueType | RangeFilterWithValueType; export interface SelectedSelectorT extends SelectorT { selected?: boolean; } export interface SelectedDateColumnT extends DateColumnT { value?: string; } export interface TableWithFilterValueT extends Omit<TableT, "filters" | "selects" | "dateColumn"> { filters: FilterWithValueType[] | null; selects?: SelectedSelectorT[]; dateColumn?: SelectedDateColumnT; } export interface DragItemQuery { // drag info; type: "PREVIOUS_QUERY" | "PREVIOUS_SECONDARY_ID_QUERY"; width: number; height: number; id: QueryIdT; label: string; excludeTimestamps?: boolean; loading?: boolean; error?: string; files?: void; isPreviousQuery: boolean; // true canExpand?: boolean; secondaryId?: string | null; availableSecondaryIds?: string[]; excludeFromSecondaryIdQuery?: boolean; tags: string[]; own?: boolean; shared?: boolean; } // ------------------ // A Query Node that is being dragged around within the standard editor. interface DragItemNodeConcept extends Omit<DragItemConceptTreeNode, "type"> { type: "QUERY_NODE"; moved: true; andIdx: number; orIdx: number; } interface DragItemNodeQuery extends Omit<DragItemQuery, "type"> { type: "QUERY_NODE"; moved: true; andIdx: number; orIdx: number; } export type DragItemNode = DragItemNodeConcept | DragItemNodeQuery; // ------------------ export interface DragItemConceptTreeNode extends ConceptQueryNodeType { type: "CONCEPT_TREE_NODE"; height: number; width: number; } export interface ConceptQueryNodeType { ids: ConceptIdT[]; tables: TableWithFilterValueT[]; selects: SelectedSelectorT[]; tree: ConceptIdT; description?: string; additionalInfos?: InfoT[]; matchingEntries?: number; matchingEntities?: number; dateRange?: DateRangeT; label: string; excludeTimestamps?: boolean; excludeFromSecondaryIdQuery?: boolean; loading?: boolean; error?: string; isEditing?: boolean; isPreviousQuery?: false; } export interface PreviousQueryQueryNodeType { id: QueryIdT; query?: QueryT; canExpand?: boolean; secondaryId?: string | null; availableSecondaryIds?: string[]; label: string; excludeTimestamps?: boolean; excludeFromSecondaryIdQuery?: boolean; loading?: boolean; error?: string; isEditing?: boolean; isPreviousQuery: true; } export type StandardQueryNodeT = | ConceptQueryNodeType | PreviousQueryQueryNodeType; export interface QueryGroupType { elements: StandardQueryNodeT[]; dateRange?: DateRangeT; exclude?: boolean; }
manuel-hegner/conquery
frontend/src/js/common/helpers/dateHelper.ts
import { format, parse, addQuarters, lastDayOfQuarter, addMonths, endOfMonth, isValid, differenceInCalendarDays, formatDistance, } from "date-fns"; import { de, enGB } from "date-fns/locale"; import { useTranslation } from "react-i18next"; // To save the date in this format in the state const DATE_FORMAT = "yyyy-MM-dd"; export const useDateLocale = () => { const { i18n } = useTranslation(); return i18n.language === "de" ? de : enGB; }; export const useFormatDateDistance = () => { const locale = useDateLocale(); return (d1: Date, d2: Date, withSuffix: boolean = false) => formatDistance(d1, d2, { locale: locale, addSuffix: withSuffix }); }; export const formatStdDate = (date: Date) => { return formatDate(date, DATE_FORMAT); }; export const formatDate = (date: Date, dateFormat: string) => { return date ? format(date, dateFormat) : ""; }; export const formatDateFromState = ( dateString: string, dateFormat: string, ): string => { const date = parseDate(dateString, DATE_FORMAT); return date !== null ? format(date, dateFormat) : dateString; }; export const parseDateToState = (date: Date) => { return format(date, DATE_FORMAT); }; export const parseDate = (dateString: string, dateFormat: string) => { // Otherwise 15.06.2 parses years as 15.06.0002 if (!dateString || dateString.length !== dateFormat.length) return null; const date = parse(dateString, dateFormat, new Date()); return isValid(date) ? date : null; }; export const parseStdDate = (dateString: string) => { return parseDate(dateString, DATE_FORMAT); }; const DATE_PATTERN = { raw: /(^\d{8})$/, year: /^[yj][.]*(\d{4})$/, quarter_year: /^[q]([1-4]).(\d{4})$/, month_year: /^[m](1[0-2]|[1-9]).(\d{4})$/, }; function handleRaw( what: "min" | "max", value: string, displayDateFormat: string, ) { const denseFormat = displayDateFormat.replace(/[-/.]/g, ""); // Assuming the format consists of 2 M, 2 d, and 2 y const dIdx = denseFormat.indexOf("d"); const d = value.substring(dIdx, dIdx + 2); const mIdx = denseFormat.indexOf("M"); const m = value.substring(mIdx, mIdx + 2); const yIdx = denseFormat.indexOf("y"); const y = value.substring(yIdx, yIdx + 4); let date: Date | null = new Date(parseInt(y), parseInt(m) - 1, parseInt(d)); date = isValid(date) ? date : null; if (what === "min") return { min: date, max: null }; else return { min: null, max: date }; } function handleYear(value: string) { const match = DATE_PATTERN.year.exec(value); if (!match) { throw new Error("Quarter.year should match at this point"); } const year = parseInt(match[1]); const min = new Date(year, 0, 1); const max = new Date(year, 11, 31); return { min, max }; } function handleQuarter(value: string) { const match = DATE_PATTERN.quarter_year.exec(value); if (!match) { throw new Error("Quarter.year should match at this point"); } const quarter = parseInt(match[1]); const year = parseInt(match[2]); const min = addQuarters(new Date(year, 0, 1), quarter - 1); const max = lastDayOfQuarter(addQuarters(new Date(year, 0, 1), quarter - 1)); return { min, max }; } function handleMonth(value: string) { const match = DATE_PATTERN.month_year.exec(value); if (!match) { throw new Error("Month.year should match at this point"); } const month = parseInt(match[1]); const year = parseInt(match[2]); const min = addMonths(new Date(year, 0, 1), month - 1); const max = endOfMonth(addMonths(new Date(year, 0, 1), month - 1)); return { min, max }; } export interface DateStringMinMax { min: string | null; // in DATE_FORMAT max: string | null; // in DATE_FORMAT } export const getDateStringFromShortcut = ( what: "min" | "max", value: string, displayDateFormat: string, ): DateStringMinMax => { const date = testRegexes(what, value, displayDateFormat); return { min: date.min ? format(date.min, DATE_FORMAT) : null, max: date.max ? format(date.max, DATE_FORMAT) : null, }; }; interface DateMinMax { min: Date | null; max: Date | null; } export const testRegexes = ( what: "min" | "max", value: string, displayDateFormat: string, ): DateMinMax => { switch (true) { case DATE_PATTERN.raw.test(value): return handleRaw(what, value, displayDateFormat); case DATE_PATTERN.year.test(value): return handleYear(value); case DATE_PATTERN.quarter_year.test(value): return handleQuarter(value); case DATE_PATTERN.month_year.test(value): return handleMonth(value); default: return { min: null, max: null }; } }; export function getDiffInDays(d1: Date, d2: Date) { return Math.abs(differenceInCalendarDays(d1, d2)) + 1; }
manuel-hegner/conquery
frontend/src/js/query-group-modal/actions.ts
<filename>frontend/src/js/query-group-modal/actions.ts import { ActionType, createAction } from "typesafe-actions"; import type { DateRangeT } from "../api/types"; export type QueryGroupModalActions = ActionType< typeof queryGroupModalSetDate | typeof queryGroupModalResetAllDates >; export const queryGroupModalSetDate = createAction( "query-group-modal/SET_DATE", )<{ andIdx: number; date: DateRangeT }>(); export const queryGroupModalResetAllDates = createAction( "query-group-modal/RESET_ALL_DATES", )<{ andIdx: number }>();
manuel-hegner/conquery
frontend/src/js/concept-trees/actions.ts
<gh_stars>10-100 import { useDispatch } from "react-redux"; import { useGetConcepts, useGetConcept } from "../api/api"; import type { DatasetIdT, ConceptIdT } from "../api/types"; import { defaultSuccess, defaultError, ErrorObject } from "../common/actions"; import { isEmpty } from "../common/helpers"; import { Sema } from "../common/helpers/rateLimitHelper"; import { getDatasetId } from "../dataset/globalDatasetHelper"; import { LOAD_TREES_START, LOAD_TREES_SUCCESS, LOAD_TREES_ERROR, LOAD_TREE_START, LOAD_TREE_SUCCESS, LOAD_TREE_ERROR, CLEAR_TREES, SEARCH_TREES_START, SEARCH_TREES_SUCCESS, SEARCH_TREES_ERROR, CLEAR_SEARCH_QUERY, TOGGLE_SHOW_MISMATCHES, } from "./actionTypes"; import { resetAllTrees, globalSearch } from "./globalTreeStoreHelper"; import type { TreesT } from "./reducer"; export const clearTrees = () => ({ type: CLEAR_TREES }); export const loadTreesStart = () => ({ type: LOAD_TREES_START }); export const loadTreesError = (err: ErrorObject) => defaultError(LOAD_TREES_ERROR, err); export const loadTreesSuccess = (res: any) => defaultSuccess(LOAD_TREES_SUCCESS, res); export const useLoadTrees = () => { const dispatch = useDispatch(); const getConcepts = useGetConcepts(); const loadTree = useLoadTree(); return async (datasetId: DatasetIdT) => { // CAREFUL: side effect! resetAllTrees(); dispatch(clearTrees()); dispatch(loadTreesStart()); try { const result = await getConcepts(datasetId); dispatch(loadTreesSuccess(result)); if (!result.concepts) return; for (const treeId of Object.keys(result.concepts)) { if (result.concepts[treeId].detailsAvailable) { loadTree(datasetId, treeId); } } } catch (e) { dispatch(loadTreesError(e)); } }; }; export const loadTreeStart = (treeId: ConceptIdT) => ({ type: LOAD_TREE_START, payload: { treeId }, }); export const loadTreeError = (treeId: ConceptIdT, err: any) => defaultError(LOAD_TREE_ERROR, err, { treeId }); export const loadTreeSuccess = (treeId: ConceptIdT, res: any) => defaultSuccess(LOAD_TREE_SUCCESS, res, { treeId }); const TREES_TO_LOAD_IN_PARALLEL = 5; const semaphore = new Sema(TREES_TO_LOAD_IN_PARALLEL); export const useLoadTree = () => { const dispatch = useDispatch(); const getConcept = useGetConcept(); return async (datasetId: DatasetIdT, treeId: ConceptIdT) => { await semaphore.acquire(); // If the datasetId changed in the mean time, don't load the tree if (datasetId !== getDatasetId()) { console.log(`${datasetId} not matching, not loading ${treeId}`); semaphore.release(); return; } dispatch(loadTreeStart(treeId)); try { const result = await getConcept(datasetId, treeId); semaphore.release(); dispatch(loadTreeSuccess(treeId, result)); } catch (e) { semaphore.release(); dispatch(loadTreeError(treeId, e)); } }; }; export const searchTreesStart = (query: string) => ({ type: SEARCH_TREES_START, payload: { query }, }); export const searchTreesSuccess = (query: string, result: Object) => ({ type: SEARCH_TREES_SUCCESS, payload: { query, result }, }); export const searchTreesError = (query: string, err: any) => defaultError(SEARCH_TREES_ERROR, err, { query }); export const useSearchTrees = () => { const dispatch = useDispatch(); return async (trees: TreesT, query: string) => { dispatch(searchTreesStart(query)); if (isEmpty(query)) return; try { const result = await globalSearch(trees, query); dispatch(searchTreesSuccess(query, result)); } catch (e) { dispatch(searchTreesError(query, e)); } }; }; export const clearSearchQuery = () => ({ type: CLEAR_SEARCH_QUERY }); export const toggleShowMismatches = () => ({ type: TOGGLE_SHOW_MISMATCHES });
manuel-hegner/conquery
frontend/src/js/ui-components/types.ts
<filename>frontend/src/js/ui-components/types.ts // // TODO: Get rid of redux-form, then refactor this. See README for more info. // // Residue struct of redux-form, which doesn't have great typescript types // Those are passed to a redux form field export interface InputProps<T> { input: { value: T; onChange: (value: T) => void; defaultValue?: T; }; }
manuel-hegner/conquery
frontend/src/js/timebased-query-editor/TimebasedQueryClearButton.tsx
<filename>frontend/src/js/timebased-query-editor/TimebasedQueryClearButton.tsx<gh_stars>10-100 import styled from "@emotion/styled"; import { StateT } from "app-types"; import React from "react"; import { useTranslation } from "react-i18next"; import { useDispatch, useSelector } from "react-redux"; import IconButton from "../button/IconButton"; import { clearTimebasedQuery } from "./actions"; import { anyConditionFilled } from "./helpers"; const Root = styled("div")` margin-bottom: 20px; padding: 0 20px 0 10px; `; const TimebasedQueryClearButton = () => { const { t } = useTranslation(); const isEnabled = useSelector<StateT, boolean>( (state) => state.timebasedQueryEditor.timebasedQuery.conditions.length > 1 || anyConditionFilled(state.timebasedQueryEditor.timebasedQuery), ); const dispatch = useDispatch(); const clearQuery = () => dispatch(clearTimebasedQuery()); return ( <Root> <IconButton frame onClick={clearQuery} regular icon="trash-alt" disabled={!isEnabled} > {t("common.clear")} </IconButton> </Root> ); }; export default TimebasedQueryClearButton;
manuel-hegner/conquery
frontend/src/js/user/actions.ts
<gh_stars>10-100 import { useDispatch } from "react-redux"; import { useGetMe } from "../api/api"; import { defaultError, defaultSuccess } from "../common/actions"; import { LOAD_ME_START, LOAD_ME_ERROR, LOAD_ME_SUCCESS } from "./actionTypes"; export const loadMeStart = () => ({ type: LOAD_ME_START }); export const loadMeError = (err: any) => defaultError(LOAD_ME_ERROR, err); export const loadMeSuccess = (res: any) => defaultSuccess(LOAD_ME_SUCCESS, res); export const useLoadMe = () => { const dispatch = useDispatch(); const getMe = useGetMe(); return () => { dispatch(loadMeStart()); return getMe().then( (r) => dispatch(loadMeSuccess(r)), (e) => dispatch(loadMeError(e)), ); }; };
manuel-hegner/conquery
frontend/src/js/concept-trees/reducer.ts
<reponame>manuel-hegner/conquery import type { ConceptT, ConceptIdT, SecondaryId } from "../api/types"; import { LOAD_TREES_START, LOAD_TREES_SUCCESS, LOAD_TREES_ERROR, LOAD_TREE_START, LOAD_TREE_SUCCESS, LOAD_TREE_ERROR, CLEAR_TREES, SEARCH_TREES_START, SEARCH_TREES_SUCCESS, SEARCH_TREES_ERROR, CLEAR_SEARCH_QUERY, TOGGLE_SHOW_MISMATCHES, } from "./actionTypes"; import { setTree } from "./globalTreeStoreHelper"; export interface TreesT { [treeId: string]: ConceptT; } export interface SearchT { allOpen: boolean; showMismatches: boolean; loading: boolean; query: string | null; words: string[] | null; result: null | Record<ConceptIdT, number>; resultCount: number; duration: number; } export interface ConceptTreesStateT { loading: boolean; version: string | null; trees: TreesT; search: SearchT; secondaryIds: SecondaryId[]; } const initialSearch = { allOpen: false, showMismatches: true, loading: false, query: null, words: null, result: null, resultCount: 0, duration: 0, }; const initialState: ConceptTreesStateT = { loading: false, version: null, trees: {}, search: initialSearch, secondaryIds: [], }; const setSearchTreesSuccess = ( state: ConceptTreesStateT, action: Object, ): ConceptTreesStateT => { const { query, result } = action.payload; // only create keys array once, then cache, // since the result might be > 100k entries const resultCount = Object.keys(result).length; const AUTO_UNFOLD_AT = 300; return { ...state, search: { ...state.search, query, result, resultCount, allOpen: resultCount < AUTO_UNFOLD_AT, showMismatches: resultCount >= AUTO_UNFOLD_AT, loading: false, words: query.split(" "), duration: Date.now() - state.search.duration, }, }; }; const setSearchTreesStart = ( state: ConceptTreesStateT, action: Object, ): ConceptTreesStateT => { const { query } = action.payload; return { ...state, search: { ...state.search, loading: query && query.length > 0, query, words: query ? query.split(" ") : [], result: {}, resultCount: 0, duration: Date.now(), }, }; }; const updateTree = ( state: ConceptTreesStateT, action: Object, attributes: Object, ): ConceptTreesStateT => { return { ...state, trees: { ...state.trees, [action.payload.treeId]: { ...state.trees[action.payload.treeId], ...attributes, }, }, }; }; const setTreeLoading = ( state: ConceptTreesStateT, action: Object, ): ConceptTreesStateT => { return updateTree(state, action, { loading: true }); }; const setTreeSuccess = ( state: ConceptTreesStateT, action: Object, ): ConceptTreesStateT => { // Side effect in a reducer. // Globally store the huge (1-5 MB) trees for read only // - keeps the redux store free from huge data const { treeId, data } = action.payload; const newState = updateTree(state, action, { loading: false }); const rootConcept = newState.trees[treeId]; setTree(rootConcept, treeId, data); return newState; }; const setTreeError = ( state: ConceptTreesStateT, action: Object, ): ConceptTreesStateT => { return updateTree(state, action, { loading: false, error: action.payload.message, }); }; const setLoadTreesSuccess = ( state: ConceptTreesStateT, action: Object, ): ConceptTreesStateT => { const { concepts, secondaryIds, version } = action.payload.data; // Assign default select filter values for (const concept of Object.values(concepts)) for (const table of concept.tables || []) for (const filter of table.filters || []) if (filter.defaultValue) filter.value = filter.defaultValue; return { ...state, loading: false, version: version, trees: concepts, secondaryIds, }; }; const conceptTrees = ( state: ConceptTreesStateT = initialState, action: Object, ): ConceptTreesStateT => { switch (action.type) { // All trees case LOAD_TREES_START: return { ...state, loading: true }; case LOAD_TREES_SUCCESS: return setLoadTreesSuccess(state, action); case LOAD_TREES_ERROR: return { ...state, loading: false, error: action.payload.message }; // Individual tree: case LOAD_TREE_START: return setTreeLoading(state, action); case LOAD_TREE_SUCCESS: return setTreeSuccess(state, action); case LOAD_TREE_ERROR: return setTreeError(state, action); case CLEAR_TREES: return initialState; case SEARCH_TREES_START: return setSearchTreesStart(state, action); case SEARCH_TREES_SUCCESS: return setSearchTreesSuccess(state, action); case SEARCH_TREES_ERROR: return { ...state, search: { ...state.search, loading: false, duration: 0 }, error: action.payload.message, }; case CLEAR_SEARCH_QUERY: return { ...state, search: initialSearch, }; case TOGGLE_SHOW_MISMATCHES: return { ...state, search: { ...state.search, allOpen: !state.search.showMismatches ? false : state.search.allOpen, showMismatches: !state.search.showMismatches, }, }; default: return state; } }; export default conceptTrees;
manuel-hegner/conquery
frontend/src/js/model/select.ts
<filename>frontend/src/js/model/select.ts import type { SelectorResultType, SelectorT } from "../api/types"; import type { ConceptQueryNodeType, SelectedSelectorT, TableWithFilterValueT, } from "../standard-query-editor/types"; export function objectHasSelectedSelects( obj: ConceptQueryNodeType | TableWithFilterValueT, ) { return ( obj && obj.selects && obj.selects.some( (select) => (select.selected && !select.default) || (!select.selected && !!select.default), ) ); } export function sortSelects(selects: SelectorT[]) { return selects .concat() // To avoid mutating the original array .sort((a, b) => (a.label < b.label ? -1 : 1)); } const withDefaultSelect = (select: SelectorT) => ({ ...select, selected: !!select.default, }); export const selectsWithDefaults = ( selects?: SelectorT[], ): SelectedSelectorT[] => (selects ? selects.map(withDefaultSelect) : []); function selectTypesMatch( resultType1: SelectorResultType, resultType2: SelectorResultType, ) { if ( resultType1.type === "LIST" && resultType2.type === "LIST" && !!resultType1.elementType && !!resultType2.elementType ) { return resultType1.elementType.type === resultType2.elementType.type; } return resultType1.type === resultType2.type; } export function selectIsWithinTypes( select: SelectorT, types: SelectorResultType[], ) { return types.some((selectType) => selectTypesMatch(selectType, select.resultType), ); } export const isSelectDisabled = ( select: SelectorT, blocklistedSelects?: SelectorResultType[], allowlistedSelects?: SelectorResultType[], ) => (!!allowlistedSelects && !selectIsWithinTypes(select, allowlistedSelects)) || (!!blocklistedSelects && selectIsWithinTypes(select, blocklistedSelects));
manuel-hegner/conquery
frontend/src/js/external-forms/common/FormField.tsx
import styled from "@emotion/styled"; import React from "react"; const TheFormField = styled("div")` margin: 0 0 10px; `; export default (Component) => (props) => ( <TheFormField> <Component {...props} /> </TheFormField> );
manuel-hegner/conquery
frontend/src/js/api/useApi.ts
import axios, { AxiosRequestConfig } from "axios"; import { useContext, useEffect, useRef } from "react"; import { useHistory } from "react-router-dom"; import { AuthTokenContext } from "../authorization/AuthTokenProvider"; import { isIDPEnabled, isLoginDisabled } from "../environment"; export const useApiUnauthorized = <T>( requestConfig: Partial<AxiosRequestConfig> = {}, ) => { return (finalRequestConfig: Partial<AxiosRequestConfig> = {}): Promise<T> => fetchJsonUnauthorized({ ...requestConfig, ...finalRequestConfig, }); }; export const useApi = <T>(requestConfig: Partial<AxiosRequestConfig> = {}) => { const history = useHistory(); const { authToken } = useContext(AuthTokenContext); // In order to always have the up to date token, // especially when polling for a long time within nested loops const authTokenRef = useRef<string>(authToken); useEffect( function updateRef() { authTokenRef.current = authToken; }, [authToken], ); return async ( finalRequestConfig: Partial<AxiosRequestConfig> = {}, ): Promise<T> => { try { const response = await fetchJson(authTokenRef.current, { ...requestConfig, ...finalRequestConfig, }); return response; } catch (error) { if ( !isIDPEnabled && !isLoginDisabled && error.status && error.status === 401 ) { history.push("/login"); } throw error; } }; }; export async function fetchJsonUnauthorized( request?: Partial<AxiosRequestConfig>, rawBody: boolean = false, ) { const finalRequest: AxiosRequestConfig = request ? { ...request, data: rawBody ? request.data : JSON.stringify(request.data), headers: { Accept: "application/json", "Content-Type": "application/json", ...request.headers, }, } : { method: "GET", headers: { Accept: "application/json", }, }; try { const response = await axios({ ...finalRequest, validateStatus: () => true, // Don't ever reject the promise for special status codes }); if ( response.status >= 200 && response.status < 300 && // Also handle empty responses (!response.data || (!!response.data && !response.data.error)) ) { return response.data; } else { // Reject other status try { return Promise.reject({ status: response.status, ...response.data }); } catch (e) { return Promise.reject({ status: response.status }); } } } catch (e) { return Promise.reject(e); // Network or connection failure } } function fetchJson(authToken: string, request?: Partial<AxiosRequestConfig>) { const finalRequest = { ...(request || {}), headers: { Authorization: `Bearer ${authToken}`, ...((request && request.headers) || {}), }, }; return fetchJsonUnauthorized(finalRequest); }
manuel-hegner/conquery
frontend/src/js/external-forms/form-query-node-editor/FormQueryNodeEditor.tsx
<filename>frontend/src/js/external-forms/form-query-node-editor/FormQueryNodeEditor.tsx import { StateT } from "app-types"; import React from "react"; import { useSelector } from "react-redux"; import { FormStateMap } from "redux-form"; import type { PostPrefixForSuggestionsParams } from "../../api/api"; import { ConceptIdT, CurrencyConfigT, DatasetIdT, SelectOptionT, SelectorResultType, } from "../../api/types"; import { toUpperCaseUnderscore } from "../../common/helpers"; import { tableIsEditable } from "../../model/table"; import QueryNodeEditor from "../../query-node-editor/QueryNodeEditor"; import { DragItemNode } from "../../standard-query-editor/types"; import { ModeT } from "../../ui-components/InputRange"; import { FormContextStateT } from "../reducer"; import { selectReduxFormState, selectEditedConceptPosition, selectEditedConcept, selectFormContextState, } from "../stateSelectors"; interface PropsT { formType: string; fieldName: string; blocklistedTables?: string[]; allowlistedTables?: string[]; allowlistedSelects?: SelectorResultType[]; blocklistedSelects?: SelectorResultType[]; onCloseModal: (andIdx: number, orIdx: number) => void; onUpdateLabel: (andIdx: number, orIdx: number, label: string) => void; onToggleTable: ( valueIdx: number, conceptIdx: number, tableIdx: number, isExcluded: boolean, ) => void; onDropConcept: ( valueIdx: number, conceptIdx: number, concept: DragItemNode, ) => void; onRemoveConcept: ( valueIdx: number, conceptIdx: number, conceptId: ConceptIdT, ) => void; onSetFilterValue: ( valueIdx: number, conceptIdx: number, tableIdx: number, filterIdx: number, filterValue: any, ) => void; onSwitchFilterMode: ( valueIdx: number, conceptIdx: number, tableIdx: number, filterIdx: number, mode: ModeT, ) => void; onResetAllFilters: (valueIdx: number, conceptIdx: number) => void; onSelectSelects: ( valueIdx: number, conceptIdx: number, selectedSelects: SelectOptionT[], ) => void; onSelectTableSelects: ( valueIdx: number, conceptIdx: number, tableIdx: number, selectedSelects: SelectOptionT[], ) => void; onLoadFilterSuggestions: ( andIdx: number, orIdx: number, params: PostPrefixForSuggestionsParams, tableIdx: number, filterIdx: number, ) => void; onSetDateColumn: ( valueIdx: number, conceptIdx: number, tableIdx: number, dateColumnValue: string | null, ) => void; } const FormQueryNodeEditor = (props: PropsT) => { const reduxFormState = useSelector<StateT, FormStateMap | null>( selectReduxFormState, ); const conceptPosition = selectEditedConceptPosition( reduxFormState, props.formType, props.fieldName, ); const datasetId = useSelector<StateT, DatasetIdT | null>( (state) => state.datasets.selectedDatasetId, ); const node = conceptPosition ? selectEditedConcept( reduxFormState, props.formType, props.fieldName, conceptPosition, props.blocklistedTables, props.allowlistedTables, ) : null; const { andIdx, orIdx } = conceptPosition || {}; const showTables = !!node && node.tables && node.tables.length > 1 && node.tables.some((table) => tableIsEditable(table)); const formState = useSelector<StateT, FormContextStateT | null>((state) => selectFormContextState(state, props.formType), ); const currencyConfig = useSelector<StateT, CurrencyConfigT>( (state) => state.startup.config.currency, ); const editorState = formState ? formState[props.fieldName] : null; if (!datasetId || !node || !editorState) { return null; } return ( <QueryNodeEditor datasetId={datasetId} name={`${props.formType}_${toUpperCaseUnderscore(props.fieldName)}`} onLoadFilterSuggestions={(...args) => props.onLoadFilterSuggestions(andIdx, orIdx, ...args) } node={node} editorState={editorState} showTables={showTables} blocklistedTables={props.blocklistedTables} allowlistedTables={props.allowlistedTables} blocklistedSelects={props.blocklistedSelects} allowlistedSelects={props.allowlistedSelects} currencyConfig={currencyConfig} onCloseModal={() => props.onCloseModal(andIdx, orIdx)} onUpdateLabel={(label) => props.onUpdateLabel(andIdx, orIdx, label)} onDropConcept={(node) => props.onDropConcept(andIdx, orIdx, node)} onRemoveConcept={(conceptId) => props.onRemoveConcept(andIdx, orIdx, conceptId) } onToggleTable={(...args) => props.onToggleTable(andIdx, orIdx, ...args)} onSelectSelects={(value) => { props.onSelectSelects(andIdx, orIdx, value); }} onSelectTableSelects={(...args) => props.onSelectTableSelects(andIdx, orIdx, ...args) } onSetFilterValue={(...args) => props.onSetFilterValue(andIdx, orIdx, ...args) } onSwitchFilterMode={(...args) => props.onSwitchFilterMode(andIdx, orIdx, ...args) } onResetAllFilters={() => props.onResetAllFilters(andIdx, orIdx)} onSetDateColumn={(...args) => props.onSetDateColumn(andIdx, orIdx, ...args) } /> ); }; export default FormQueryNodeEditor;
manuel-hegner/conquery
frontend/src/js/preview/StatsSubline.ts
import styled from "@emotion/styled"; const StatsSubline = styled("h4")` font-size: ${({ theme }) => theme.font.xs}; color: ${({ theme }) => theme.col.black}; font-weight: 400; margin: 0 0 12px; `; export default StatsSubline;
manuel-hegner/conquery
frontend/src/js/external-forms/form-configs/selectors.ts
<reponame>manuel-hegner/conquery import { StateT } from "app-types"; import { useCallback, useState } from "react"; import { useTranslation } from "react-i18next"; import { useDispatch, useSelector } from "react-redux"; import { useGetFormConfig, useGetFormConfigs } from "../../api/api"; import type { DatasetIdT } from "../../api/types"; import { setMessage } from "../../snack-message/actions"; import { useActiveFormType } from "../stateSelectors"; import { loadFormConfigsError, loadFormConfigsSuccess, patchFormConfigSuccess, } from "./actions"; import { FormConfigT } from "./reducer"; const configHasTag = (config: FormConfigT, searchTerm: string) => { return ( !!config.tags && config.tags.some((tag) => { return tag.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1; }) ); }; const configHasLabel = (config: FormConfigT, searchTerm: string) => { return ( config.label && config.label.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1 ); }; const configHasId = (config: FormConfigT, searchTerm: string) => { return config.id.toString() === searchTerm; }; const configHasFilterType = ( config: FormConfigT, filter: string, { activeFormType }: { activeFormType: string | null }, ) => { if (filter === "all") return true; if (filter === "activeForm") return !!activeFormType && config.formType === activeFormType; // Checks config.own, config.shared or config.system if (config[filter]) return true; // Special case for a "system"-config: // it's simply not shared and not self-created (own) if (filter === "system" && !config.shared && !config.own) return true; return false; }; export const useFilteredFormConfigs = () => { const formConfigs = useSelector<StateT, FormConfigT[]>( (state) => state.formConfigs.data, ); const search = useSelector<StateT, string[]>( (state) => state.formConfigsSearch, ); const filter = useSelector<StateT, string>( (state) => state.formConfigsFilter, ); const activeFormType = useActiveFormType(); if (search.length === 0 && filter === "all") return formConfigs; return formConfigs.filter((config) => { return ( configHasFilterType(config, filter, { activeFormType }) && search.every((searchTerm) => { return ( configHasId(config, searchTerm) || configHasLabel(config, searchTerm) || configHasTag(config, searchTerm) ); }) ); }); }; const labelContainsAnySearch = (label: string, searches: string[]) => searches.some( (search) => label.toLowerCase().indexOf(search.toLowerCase()) !== -1, ); export const useIsLabelHighlighted = (label: string) => { const formConfigsSearch = useSelector<StateT, string[]>( (state) => state.formConfigsSearch, ); return labelContainsAnySearch(label, formConfigsSearch); }; export const useLoadFormConfigs = () => { const [loading, setLoading] = useState<boolean>(false); const dispatch = useDispatch(); const getFormConfigs = useGetFormConfigs(); const loadFormConfigs = useCallback( async (datasetId: DatasetIdT) => { setLoading(true); try { const data = await getFormConfigs(datasetId); dispatch(loadFormConfigsSuccess(data)); } catch (e) { dispatch(loadFormConfigsError(e)); } setLoading(false); }, [dispatch], ); return { loading, loadFormConfigs, }; }; export const useLoadFormConfig = () => { const { t } = useTranslation(); const [loading, setLoading] = useState<boolean>(false); const dispatch = useDispatch(); const getFormConfig = useGetFormConfig(); const loadFormConfig = useCallback( async (datasetId: DatasetIdT, id: string) => { setLoading(true); try { const data = await getFormConfig(datasetId, id); dispatch(patchFormConfigSuccess(id, data)); } catch (e) { dispatch(setMessage({ message: t("formConfig.loadError") })); } setLoading(false); }, [t, dispatch], ); return { loading, loadFormConfig, }; };
manuel-hegner/conquery
frontend/src/js/query-node-editor/TableSelects.tsx
import React from "react"; import type { FilterSuggestion, SelectOptionT, SelectorResultType, } from "../api/types"; import { isSelectDisabled, sortSelects } from "../model/select"; import { SelectedSelectorT } from "../standard-query-editor/types"; import InputMultiSelect from "../ui-components/InputMultiSelect"; interface PropsT { selects: SelectedSelectorT[]; blocklistedSelects?: SelectorResultType[]; allowlistedSelects?: SelectorResultType[]; onSelectTableSelects: ( value: SelectOptionT[] | FilterSuggestion[] | null, ) => void; excludeTable?: boolean; } const TableSelects = ({ selects, blocklistedSelects, allowlistedSelects, onSelectTableSelects, excludeTable, }: PropsT) => { return ( <div> <InputMultiSelect input={{ onChange: onSelectTableSelects, value: selects .filter(({ selected }) => !!selected) .map(({ id, label }) => ({ value: id, label: label })), }} options={sortSelects(selects).map((select) => ({ value: select.id, label: select.label, disabled: isSelectDisabled( select, blocklistedSelects, allowlistedSelects, ), }))} disabled={excludeTable} /> </div> ); }; export default TableSelects;
manuel-hegner/conquery
frontend/src/js/ui-components/InputMultiSelect/InputMultiSelectTwo.stories.tsx
<filename>frontend/src/js/ui-components/InputMultiSelect/InputMultiSelectTwo.stories.tsx import { ComponentMeta, Story } from "@storybook/react"; import React, { ComponentProps, useState } from "react"; import wordslist from "../../../fixtures/words.json"; import { SelectOptionT } from "../../api/types"; import InputMultiSelectTwo from "./InputMultiSelectTwo"; const wl = wordslist.slice(0, 100); export default { title: "FormComponents/InputMultiSelectTwo", component: InputMultiSelectTwo, argTypes: { backgroundColor: { control: "#fafafa" }, }, } as ComponentMeta<typeof InputMultiSelectTwo>; const Template: Story<ComponentProps<typeof InputMultiSelectTwo>> = () => { const [options, setOptions] = useState<SelectOptionT[]>( wl.map((w) => ({ label: w, value: w })), ); const [value, setValue] = useState<SelectOptionT[] | null>([ { label: "lol", value: "yes", }, ]); const onLoad = (str: string) => { setOptions( wordslist .filter((w) => w.startsWith(str)) .map((w) => ({ label: w, value: w })), ); }; return ( <InputMultiSelectTwo label="This is a nice label" creatable onResolve={(csvLines) => { console.log(csvLines); }} tooltip="And here goes some tooltip that really helps the user understand what's going on" indexPrefix={5} input={{ defaultValue: [], value: value || [], onChange: (v) => setValue(v), }} options={options} /> ); }; export const Default = Template.bind({});
manuel-hegner/conquery
frontend/src/js/standard-query-editor/ExpandPreviousQueryModal.tsx
<filename>frontend/src/js/standard-query-editor/ExpandPreviousQueryModal.tsx import styled from "@emotion/styled"; import React, { FC } from "react"; import { useTranslation } from "react-i18next"; import PrimaryButton from "../button/PrimaryButton"; import TransparentButton from "../button/TransparentButton"; import Modal from "../modal/Modal"; const Description = styled.p` max-width: 400px; margin: 0 0 20px; `; const Buttons = styled.div` display: flex; align-items: center; justify-content: space-between; `; interface Props { className?: string; onClose: () => void; onAccept: () => void; } const ExpandPreviousQueryModal: FC<Props> = ({ onClose, onAccept, className, }) => { const { t } = useTranslation(); return ( <Modal className={className} onClose={onClose} headline={t("expandPreviousQueryModal.headline")} > <form onSubmit={(e) => { e.preventDefault(); onAccept(); }} > <Description>{t("expandPreviousQueryModal.description")}</Description> <Buttons> <TransparentButton onClick={onClose} type="button"> {t("common.cancel")} </TransparentButton> <PrimaryButton autoFocus onClick={onAccept} type="submit"> {t("expandPreviousQueryModal.submit")} </PrimaryButton> </Buttons> </form> </Modal> ); }; export default ExpandPreviousQueryModal;
manuel-hegner/conquery
frontend/src/js/external-forms/FormsNavigation.tsx
<filename>frontend/src/js/external-forms/FormsNavigation.tsx import styled from "@emotion/styled"; import type { StateT } from "app-types"; import React, { FC } from "react"; import { useTranslation } from "react-i18next"; import { useSelector, useDispatch } from "react-redux"; import { reset } from "redux-form"; import IconButton from "../button/IconButton"; import { useActiveLang } from "../localization/useActiveLang"; import WithTooltip from "../tooltip/WithTooltip"; import InputSelect from "../ui-components/InputSelect"; import { setExternalForm } from "./actions"; import { Form } from "./config-types"; import { selectActiveFormType, selectAvailableForms } from "./stateSelectors"; const Root = styled("div")` flex-shrink: 0; margin-bottom: 10px; padding: 0 20px 10px 10px; box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.2); box-sizing: border-box; display: flex; flex-direction: row; align-items: flex-end; `; const SxInputSelect = styled(InputSelect)` flex-grow: 1; `; const SxIconButton = styled(IconButton)` flex-shrink: 0; margin-left: 10px; padding: 6px 10px; `; const FormsNavigation: FC = () => { const language = useActiveLang(); const { t } = useTranslation(); const availableForms = useSelector< StateT, { [formName: string]: Form; } >((state) => selectAvailableForms(state)); const activeForm = useSelector<StateT, string | null>((state) => selectActiveFormType(state), ); const dispatch = useDispatch(); const onItemClick = (form: string) => dispatch(setExternalForm(form)); const options = Object.values(availableForms) .map((formType) => ({ label: formType.title[language]!, value: formType.type, })) .sort((a, b) => (a.label < b.label ? -1 : 1)); const activeFormType = useSelector<StateT, string | null>((state) => selectActiveFormType(state), ); const onClear = () => { if (activeFormType) { dispatch(reset(activeFormType)); } }; return ( <Root> <SxInputSelect label={t("externalForms.forms")} options={options} input={{ value: activeForm, onChange: (value: string) => onItemClick(value), }} selectProps={{ clearable: false, autosize: true, searchable: false, }} /> <WithTooltip text={t("externalForms.common.clear")}> <SxIconButton frame regular icon="trash-alt" onClick={onClear} /> </WithTooltip> </Root> ); }; export default FormsNavigation;
manuel-hegner/conquery
frontend/src/js/concept-trees/ConceptTreeSearchBox.tsx
<gh_stars>0 import styled from "@emotion/styled"; import { StateT } from "app-types"; import React, { FC } from "react"; import { useTranslation } from "react-i18next"; import { useSelector, useDispatch } from "react-redux"; import TransparentButton from "../button/TransparentButton"; import AnimatedDots from "../common/components/AnimatedDots"; import ConceptTreesOpenButtons from "../concept-trees-open/ConceptTreesOpenButtons"; import SearchBar from "../search-bar/SearchBar"; import { clearSearchQuery, toggleShowMismatches, useSearchTrees, } from "./actions"; import type { SearchT, TreesT } from "./reducer"; const Root = styled("div")` position: relative; `; const TinyText = styled("p")` margin: 3px 0; font-size: ${({ theme }) => theme.font.xs}; color: ${({ theme }) => theme.col.gray}; `; const Row = styled("div")` display: flex; flex-direction: row; align-items: center; justify-content: space-between; `; const Displaying = styled("span")` font-size: ${({ theme }) => theme.font.xs}; text-transform: uppercase; color: ${({ theme }) => theme.col.gray}; `; const StyledButton = styled(TransparentButton)` margin: 3px 0 3px 5px; `; const TopRow = styled("div")` display: flex; align-items: center; `; const SxConceptTreeOpenButtons = styled(ConceptTreesOpenButtons)` margin-right: 5px; `; interface PropsT { className?: string; } const ConceptTreeSearchBox: FC<PropsT> = ({ className }) => { const showMismatches = useSelector<StateT, boolean>( (state) => state.conceptTrees.search.showMismatches, ); const search = useSelector<StateT, SearchT>( (state) => state.conceptTrees.search, ); const trees = useSelector<StateT, TreesT>( (state) => state.conceptTrees.trees, ); const dispatch = useDispatch(); const { t } = useTranslation(); const searchTrees = useSearchTrees(); const onSearch = (trees: TreesT, searchString: string) => { if (searchString.length > 1) { searchTrees(trees, searchString); } }; const onClearQuery = () => dispatch(clearSearchQuery()); const onToggleShowMismatches = () => dispatch(toggleShowMismatches()); return ( <Root className={className}> <TopRow> <SxConceptTreeOpenButtons /> <SearchBar searchTerm={search.query} placeholder={t("conceptTreeList.searchPlaceholder")} onClear={onClearQuery} onSearch={(value) => onSearch(trees, value)} /> </TopRow> {search.loading ? ( <AnimatedDots /> ) : ( search.result && search.resultCount >= 0 && ( <Row> <TinyText> {t("search.resultLabel", { totalResults: search.resultCount, duration: (search.duration / 1000.0).toFixed(2), })} </TinyText> <div> <Displaying> {showMismatches ? t("conceptTreeList.showingMismatches") : t("conceptTreeList.showingMatchesOnly")} </Displaying> <StyledButton tiny onClick={onToggleShowMismatches}> {showMismatches ? t("conceptTreeList.showMatchesOnly") : t("conceptTreeList.showMismatches")} </StyledButton> </div> </Row> ) )} </Root> ); }; export default ConceptTreeSearchBox;
manuel-hegner/conquery
frontend/src/js/api/apiExternalFormsHelper.ts
// The query state contains the form values. // But small additions are made (properties allowlisted), empty things filtered out // to make it compatible with the backend API export const transformFormQueryToApi = ( query: { form: string; formName: string }, formQueryTransformation: Function, ): Object => { const { form, formName } = query; return { type: formName, ...formQueryTransformation(form, formName), }; };
manuel-hegner/conquery
frontend/src/js/timebased-query-editor/reducer.ts
import { ActionType, getType } from "typesafe-actions"; import { Action } from "../app/actions"; import { renameQuery } from "../previous-queries/list/actions"; import { addTimebasedCondition, clearTimebasedQuery, dropTimebasedNode, removeTimebasedCondition, removeTimebasedNode, setTimebasedConditionMaxDays, setTimebasedConditionMinDays, setTimebasedConditionMinDaysOrNoEvent, setTimebasedConditionOperator, setTimebasedIndexResult, setTimebasedNodeTimestamp, } from "./actions"; export type TimebasedTimestampType = "EARLIEST" | "LATEST" | "RANDOM"; export type TimebasedResultType = { id: string; label: string; timestamp: TimebasedTimestampType; }; export type TimebasedOperatorType = | "BEFORE" | "BEFORE_OR_SAME" | "SAME" | "DAYS_BEFORE" | "DAYS_OR_NO_EVENT_BEFORE"; export const TIMEBASED_OPERATOR_TYPES: TimebasedOperatorType[] = [ "BEFORE", "BEFORE_OR_SAME", "SAME", "DAYS_BEFORE", "DAYS_OR_NO_EVENT_BEFORE", ]; export interface TimebasedConditionT { operator: TimebasedOperatorType; result0: TimebasedResultType | null; result1: TimebasedResultType | null; minDays?: number | null; maxDays?: number | null; minDaysOrNoEvent?: number | null; } export interface ValidatedTimebasedConditionT extends TimebasedConditionT { result0: TimebasedResultType; result1: TimebasedResultType; } export interface TimebasedQueryStateT { indexResult: string | null; conditions: TimebasedConditionT[]; } const getEmptyNode = () => ({ operator: "BEFORE" as const, result0: null, result1: null, }); const setTimebasedConditionAttributes = ( state: TimebasedQueryStateT, conditionIdx: number, attributes: Partial<TimebasedConditionT>, ) => { return { ...state, conditions: [ ...state.conditions.slice(0, conditionIdx), { ...state.conditions[conditionIdx], ...attributes, }, ...state.conditions.slice(conditionIdx + 1), ], }; }; const setNode = ( state: TimebasedQueryStateT, resultIdx: number, conditionIdx: number, node: TimebasedResultType, ) => { const attributes = { [`result${resultIdx}`]: { ...node, timestamp: node.timestamp || "EARLIEST", }, }; return setTimebasedConditionAttributes(state, conditionIdx, attributes); }; const conditionResultsToArray = (conditions: TimebasedConditionT[]) => { return conditions.reduce<TimebasedResultType[]>((results, c) => { if (c.result0) results.push(c.result0); if (c.result1) results.push(c.result1); return results; }, []); }; const getPossibleIndexResults = (conditions: TimebasedConditionT[]) => { return conditions.reduce<TimebasedResultType[]>( (possibleResults, condition) => { if (condition.operator === "DAYS_OR_NO_EVENT_BEFORE" && condition.result1) possibleResults.push(condition.result1); if (condition.operator !== "DAYS_OR_NO_EVENT_BEFORE" && condition.result0) possibleResults.push(condition.result0); if (condition.operator !== "DAYS_OR_NO_EVENT_BEFORE" && condition.result1) possibleResults.push(condition.result1); return possibleResults; }, [], ); }; const ensureIndexResult = (state: TimebasedQueryStateT) => { // Return if there is already an indexResult if (state.indexResult) return state; // Ok, so there is none, let's ensure it const possibleResults = getPossibleIndexResults(state.conditions); // allResults includes results on the left side // of conditions with a DAYS_OR_NO_EVENT_BEFORE operator const allResults = conditionResultsToArray(state.conditions); // Best case if (possibleResults.length > 0) return { ...state, indexResult: possibleResults[0].id }; // Bad but ok case if (allResults.length > 0) return { ...state, indexResult: allResults[0].id }; // Well, couldn't find any result return { ...state, indexResult: null }; }; const onDropTimebasedNode = ( state: TimebasedQueryStateT, { node, resultIdx, conditionIdx, moved, }: ActionType<typeof dropTimebasedNode>["payload"], ) => { const stateWithNode = setNode(state, resultIdx, conditionIdx, node); return moved ? stateWithNode : ensureIndexResult(stateWithNode); }; const onRemoveTimebasedNode = ( state: TimebasedQueryStateT, { conditionIdx, resultIdx, moved, }: ActionType<typeof removeTimebasedNode>["payload"], ) => { const condition = state.conditions[conditionIdx]; const node = resultIdx === 0 ? condition.result0 : condition.result1; if (!node) return state; const attributes = { [`result${resultIdx}`]: null, }; const stateWithoutNode = setTimebasedConditionAttributes( state, conditionIdx, attributes, ); if (moved) return stateWithoutNode; // If item has not been moved and was indexResult, remove indexResult const nextState = node.id === state.indexResult ? { ...stateWithoutNode, indexResult: null } : stateWithoutNode; return ensureIndexResult(nextState); }; const onSetTimebasedNodeTimestamp = ( state: TimebasedQueryStateT, { conditionIdx, resultIdx, timestamp, }: ActionType<typeof setTimebasedNodeTimestamp>["payload"], ) => { const condition = state.conditions[conditionIdx]; const node = resultIdx === 0 ? condition.result0 : condition.result1; const attributes = { [`result${resultIdx}`]: { ...node, timestamp, }, }; return setTimebasedConditionAttributes(state, conditionIdx, attributes); }; const onSetTimebasedConditionOperator = ( state: TimebasedQueryStateT, { conditionIdx, operator, }: ActionType<typeof setTimebasedConditionOperator>["payload"], ) => { // Check if we're not switching to DAYS_OR_NO_EVENT_BEFORE. Then we're good. // But IF IN FACT we do, check if the indexResult is somewhere else than on the left result // Then we're also good. const nextState = setTimebasedConditionAttributes(state, conditionIdx, { operator, }); if ( operator !== "DAYS_OR_NO_EVENT_BEFORE" || !state.conditions[conditionIdx].result0 || state.conditions[conditionIdx].result0.id !== state.indexResult ) return nextState; // Now that this didn't work we're switching the operator to DAYS_OR_NO_EVENT_BEFORE // and the indexResult points to the first of both results of this condition. // This is not allowed with DAYS_OR_NO_EVENT_BEFORE. // Let's try to find a possible result to be the new indexResult const possibleResults = getPossibleIndexResults(nextState.conditions); // Now let's hope we found a possible result return possibleResults.length === 0 ? // Too bad, couldn't find a possible result nextState : // Nice, take the first result { ...nextState, indexResult: possibleResults[0].id, }; }; const onSetTimebasedConditionMinDays = ( state: TimebasedQueryStateT, { days, conditionIdx, }: ActionType<typeof setTimebasedConditionMinDays>["payload"], ) => { return setTimebasedConditionAttributes(state, conditionIdx, { minDays: days, }); }; const onSetTimebasedConditionMaxDays = ( state: TimebasedQueryStateT, { days, conditionIdx, }: ActionType<typeof setTimebasedConditionMaxDays>["payload"], ) => { return setTimebasedConditionAttributes(state, conditionIdx, { maxDays: days, }); }; const onSetTimebasedConditionMinDaysOrNoEvent = ( state: TimebasedQueryStateT, { days, conditionIdx, }: ActionType<typeof setTimebasedConditionMinDaysOrNoEvent>["payload"], ) => { return setTimebasedConditionAttributes(state, conditionIdx, { minDaysOrNoEvent: days, }); }; const onSetTimebasedIndexResult = ( state: TimebasedQueryStateT, { indexResult }: ActionType<typeof setTimebasedIndexResult>["payload"], ) => { return { ...state, indexResult, }; }; const onAddTimebasedCondition = (state: TimebasedQueryStateT) => { return { ...state, conditions: [...state.conditions, getEmptyNode()], }; }; const onRemoveTimebasedCondition = ( state: TimebasedQueryStateT, { conditionIdx }: ActionType<typeof removeTimebasedCondition>["payload"], ) => { const deletedCondition = state.conditions[conditionIdx]; const nextState = { ...state, conditions: [ ...state.conditions.slice(0, conditionIdx), ...state.conditions.slice(conditionIdx + 1), ], }; // if no node was indexed if ( !( deletedCondition.result0 && deletedCondition.result0.id === state.indexResult ) && !( deletedCondition.result1 && deletedCondition.result1.id === state.indexResult ) ) return nextState; return ensureIndexResult({ ...nextState, indexResult: null }); }; const renameQueries = ( state: TimebasedQueryStateT, { queryId, label }: ActionType<typeof renameQuery.success>["payload"], ) => { return { ...state, conditions: state.conditions.map((c) => { const result0 = c.result0 && c.result0.id === queryId ? { ...c.result0, label: label } : c.result0; const result1 = c.result1 && c.result1.id === queryId ? { ...c.result1, label: label } : c.result1; return { ...c, result0, result1, }; }), }; }; const initialState = { indexResult: null, conditions: [getEmptyNode()], }; // This state contains multiple and-conditions. // Every and-condition sets exactly two previous queries in a time-based relation. // To be more specific, the RESULTS of two previous queries are set in relation. // (The relation is measured in days) // // The result of this timebased query will look like those from any other query: // // A number of results with // id, // first date of occurrence, // last date of occurrence, // random dateof occurrence // // These dates will have to be taken from a single previous query // (result1 or result2 from within specific condition) the "indexResult". // // Example: // // { // indexResult: 2523, // conditions: [ // { // operator: 'BEFORE', // // operator: 'BEFORE_OR_SAME', // // operator: 'SAME', // result0: { // id: 2523, // timestamp: 'FIRST', // // timestamp: 'LAST', // // timestamp: 'RANDOM', // }, // result1: { // id: 2525, // timestamp: 'LAST' // }, // minDays: 5, // maxDays: 10 // }, // { // operator: 'SAME', // result0: { id: 6274, timestamp: "RANDOM" }, // result1: { id: 5274, timestamp: "RANDOM" }, // } // ] // } const timebasedQuery = ( state: TimebasedQueryStateT = initialState, action: Action, ): TimebasedQueryStateT => { switch (action.type) { case getType(dropTimebasedNode): return onDropTimebasedNode(state, action.payload); case getType(removeTimebasedNode): return onRemoveTimebasedNode(state, action.payload); case getType(setTimebasedNodeTimestamp): return onSetTimebasedNodeTimestamp(state, action.payload); case getType(setTimebasedConditionOperator): return onSetTimebasedConditionOperator(state, action.payload); case getType(setTimebasedConditionMinDays): return onSetTimebasedConditionMinDays(state, action.payload); case getType(setTimebasedConditionMaxDays): return onSetTimebasedConditionMaxDays(state, action.payload); case getType(setTimebasedConditionMinDaysOrNoEvent): return onSetTimebasedConditionMinDaysOrNoEvent(state, action.payload); case getType(setTimebasedIndexResult): return onSetTimebasedIndexResult(state, action.payload); case getType(addTimebasedCondition): return onAddTimebasedCondition(state); case getType(removeTimebasedCondition): return onRemoveTimebasedCondition(state, action.payload); case getType(renameQuery.success): return renameQueries(state, action.payload); case getType(clearTimebasedQuery): return initialState; default: return state; } }; export default timebasedQuery;
manuel-hegner/conquery
frontend/src/js/standard-query-editor/StandardQueryEditorTab.tsx
<gh_stars>10-100 import React from "react"; import { QueryEditor } from "./QueryEditor"; import StandardQueryRunner from "./StandardQueryRunner"; const StandardQueryEditorTab = () => ( <> <QueryEditor /> <StandardQueryRunner /> </> ); export default StandardQueryEditorTab;
manuel-hegner/conquery
frontend/src/js/previous-queries/upload/UploadQueryResultsModal.tsx
<gh_stars>10-100 import styled from "@emotion/styled"; import React, { FC, useState } from "react"; import { useTranslation } from "react-i18next"; import type { QueryUploadConfigT, UploadQueryResponseT } from "../../api/types"; import FaIcon from "../../icon/FaIcon"; import Modal from "../../modal/Modal"; import InfoTooltip from "../../tooltip/InfoTooltip"; import DropzoneWithFileInput from "../../ui-components/DropzoneWithFileInput"; import CSVColumnPicker, { QueryToUploadT } from "./CSVColumnPicker"; const Root = styled("div")``; const Success = styled("div")` margin: 25px 0; `; const StyledFaIcon = styled(FaIcon)` font-size: 40px; display: block; margin: 0 auto 10px; color: ${({ theme }) => theme.col.green}; `; const SuccessMsg = styled("p")` margin: 0; `; const SxDropzoneWithFileInput = styled(DropzoneWithFileInput)` padding: 180px 250px; width: 100%; cursor: pointer; `; interface PropsT { loading: boolean; config: QueryUploadConfigT; uploadResult: UploadQueryResponseT | null; onClearUploadResult: () => void; onClose: () => void; onUpload: (query: QueryToUploadT) => void; } const UploadQueryResultsModal: FC<PropsT> = ({ loading, config, uploadResult, onClearUploadResult, onClose, onUpload, }) => { const { t } = useTranslation(); const [file, setFile] = useState<File | null>(null); const fullUploadSuccess = uploadResult && uploadResult.resolved > 0 && uploadResult.unreadableDate.length === 0 && uploadResult.unresolvedId.length === 0; return ( <Modal onClose={onClose} closeIcon scrollable headline={ <> {t("uploadQueryResultsModal.headline")} <InfoTooltip wide text={t("uploadQueryResultsModal.formatInfo.text")} /> </> } > <Root> {fullUploadSuccess ? ( <Success> <StyledFaIcon icon="check-circle" /> <SuccessMsg> {t("uploadQueryResultsModal.uploadSucceeded", { count: uploadResult?.resolved || 0, })} </SuccessMsg> </Success> ) : ( <div> {file && ( <CSVColumnPicker file={file} uploadResult={uploadResult} config={config} loading={loading} onUpload={onUpload} onCancel={onClose} onReset={() => { setFile(null); onClearUploadResult(); }} /> )} {!file && ( <SxDropzoneWithFileInput onDrop={(item) => { if (item.files) { setFile(item.files[0]); } }} onSelectFile={setFile} > {() => t("uploadQueryResultsModal.dropzone")} </SxDropzoneWithFileInput> )} </div> )} </Root> </Modal> ); }; export default UploadQueryResultsModal;
manuel-hegner/conquery
frontend/src/js/timebased-query-editor/TimebasedCondition.tsx
import styled from "@emotion/styled"; import React from "react"; import { useTranslation } from "react-i18next"; import IconButton from "../button/IconButton"; import { isEmpty } from "../common/helpers"; import VerticalToggleButton from "../ui-components/VerticalToggleButton"; import TimebasedConditionDayRange from "./TimebasedConditionDayRange"; import TimebasedNode from "./TimebasedNode"; import TimebasedQueryEditorDropzone from "./TimebasedQueryEditorDropzone"; import type { TimebasedConditionT, TimebasedOperatorType, TimebasedResultType, } from "./reducer"; const StyledIconButton = styled(IconButton)` position: absolute; top: 0; right: 0; z-index: 1; display: inline; `; const Root = styled("div")` position: relative; padding: 30px 10px 10px; box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.12); border-radius: ${({ theme }) => theme.borderRadius}; border: 1px solid ${({ theme }) => theme.col.grayLight}; background-color: ${({ theme }) => theme.col.bg}; &:hover { border: 1px solid ${({ theme }) => theme.col.grayLight}; } `; const StyledVerticalToggleButton = styled(VerticalToggleButton)` max-width: 180px; `; const NodesContainer = styled("div")` margin-bottom: 10px; position: relative; `; const Nodes = styled("div")` position: relative; width: 100%; display: flex; flex-direction: row; align-items: center; justify-content: space-between; `; const HorizontalLine = styled("div")` position: absolute; top: 50%; right: 10%; width: 80%; border-bottom: 1px solid ${({ theme }) => theme.col.blueGray}; margin-top: -0.5px; `; const Operator = styled("div")` margin: 0 10px; `; type PropsType = { condition: TimebasedConditionT; conditionIdx: number; // indexResult: number | string | null; removable: boolean; onRemove: () => void; onSetOperator: (value: TimebasedOperatorType) => void; onRemoveTimebasedNode: (idx: number, moved: boolean) => void; onDropTimebasedNode: ( resultIdx: number, node: TimebasedResultType, moved: boolean, ) => void; onSetTimebasedNodeTimestamp: (idx: number, timestamp: string) => void; onSetTimebasedConditionMinDays: (value: number | null) => void; onSetTimebasedConditionMaxDays: (value: number | null) => void; onSetTimebasedConditionMinDaysOrNoEvent: (value: number | null) => void; }; const TimebasedCondition = ({ condition, conditionIdx, // indexResult, removable, onRemove, onSetOperator, onRemoveTimebasedNode, onDropTimebasedNode, onSetTimebasedNodeTimestamp, onSetTimebasedConditionMinDays, onSetTimebasedConditionMaxDays, onSetTimebasedConditionMinDaysOrNoEvent, }: PropsType) => { const { t } = useTranslation(); const minDays = !isEmpty(condition.minDays) ? condition.minDays : ""; const maxDays = !isEmpty(condition.maxDays) ? condition.maxDays : ""; const minDaysOrNoEvent = !isEmpty(condition.minDaysOrNoEvent) ? condition.minDaysOrNoEvent : ""; const createTimebasedResult = (idx: 0 | 1) => { const node = idx === 0 ? condition.result0 : condition.result1; return node ? ( <TimebasedNode node={node} conditionIdx={conditionIdx} resultIdx={idx} // isIndexResult={condition[`result${idx}`].id === indexResult} position={idx === 0 ? "left" : "right"} onRemove={() => onRemoveTimebasedNode(idx, false)} onSetTimebasedNodeTimestamp={(timestamp) => { onSetTimebasedNodeTimestamp(idx, timestamp); }} // onSetTimebasedIndexResult={() => { // onSetTimebasedIndexResult(condition[`result${idx}`].id); // }} // isIndexResultDisabled={ // idx === 0 && condition.operator === "DAYS_OR_NO_EVENT_BEFORE" // } /> ) : ( <TimebasedQueryEditorDropzone onDropNode={(node: TimebasedResultType, moved: boolean) => onDropTimebasedNode(idx, node, moved) } /> ); }; const result0 = createTimebasedResult(0); const result1 = createTimebasedResult(1); return ( <Root> {removable && <StyledIconButton icon="times" onClick={onRemove} />} <NodesContainer> <HorizontalLine /> <Nodes> {result0} <Operator> <StyledVerticalToggleButton onToggle={(value) => onSetOperator(value as TimebasedOperatorType) } activeValue={condition.operator} options={[ { label: t("timebasedQueryEditor.opBefore"), value: "BEFORE", }, { label: t("timebasedQueryEditor.opBeforeOrSame"), value: "BEFORE_OR_SAME", }, { label: t("timebasedQueryEditor.opDays"), value: "DAYS_BEFORE", }, { label: t("timebasedQueryEditor.opSame"), value: "SAME", }, { label: t("timebasedQueryEditor.opDaysOrNoEventBefore"), value: "DAYS_OR_NO_EVENT_BEFORE", }, ]} /> </Operator> {result1} </Nodes> </NodesContainer> {condition.operator === "DAYS_BEFORE" && ( <TimebasedConditionDayRange minDays={minDays} maxDays={maxDays} onSetTimebasedConditionMinDays={onSetTimebasedConditionMinDays} onSetTimebasedConditionMaxDays={onSetTimebasedConditionMaxDays} /> )} {condition.operator === "DAYS_OR_NO_EVENT_BEFORE" && ( <TimebasedConditionDayRange minDays={minDaysOrNoEvent} onSetTimebasedConditionMinDays={ onSetTimebasedConditionMinDaysOrNoEvent } /> )} </Root> ); }; export default TimebasedCondition;
manuel-hegner/conquery
frontend/src/js/ui-components/BaseInput.tsx
<filename>frontend/src/js/ui-components/BaseInput.tsx import styled from "@emotion/styled"; import * as React from "react"; import { useTranslation } from "react-i18next"; import type { CurrencyConfigT } from "../api/types"; import IconButton from "../button/IconButton"; import { isEmpty } from "../common/helpers"; import { exists } from "../common/helpers/exists"; import FaIcon from "../icon/FaIcon"; import WithTooltip from "../tooltip/WithTooltip"; import CurrencyInput from "./CurrencyInput"; const Root = styled("div")` position: relative; display: inline-block; `; const Input = styled("input")<{ large?: boolean }>` outline: 0; min-width: 170px; border: 1px solid ${({ theme }) => theme.col.grayMediumLight}; font-size: ${({ theme }) => theme.font.md}; padding: ${({ large }) => large ? "10px 30px 10px 14px" : "6px 30px 6px 10px"}; font-size: ${({ theme, large }) => (large ? theme.font.lg : theme.font.sm)}; border-radius: ${({ theme }) => theme.borderRadius}; `; const SignalIcon = styled(FaIcon)` position: absolute; top: 8px; right: 35px; opacity: 0.8; `; const GreenIcon = styled(SignalIcon)` color: ${({ theme }) => theme.col.green}; `; const RedIcon = styled(FaIcon)` color: ${({ theme }) => theme.col.red}; opacity: 0.8; `; const SxWithTooltip = styled(WithTooltip)` position: absolute; top: 5px; right: 35px; `; const ClearZoneIconButton = styled(IconButton)` position: absolute; top: ${({ large }) => (large ? "5px" : "0")}; right: 10px; cursor: pointer; height: 100%; display: flex; align-items: center; &:hover { color: ${({ theme }) => theme.col.red}; } `; interface InputProps { autoFocus?: boolean; pattern?: string; step?: number; min?: number; max?: number; onKeyPress?: (e: React.KeyboardEvent<HTMLInputElement>) => void; } interface Props { className?: string; inputType: string; money?: boolean; valid?: boolean; invalid?: boolean; invalidText?: string; placeholder?: string; value: number | string | null; large?: boolean; inputProps?: InputProps; currencyConfig?: CurrencyConfigT; onChange: (val: null | number | string) => void; onBlur?: (e: React.FocusEvent<HTMLInputElement>) => void; } const BaseInput = (props: Props) => { const { t } = useTranslation(); const inputProps = props.inputProps || {}; const { pattern } = props.inputProps || {}; const handleKeyPress = (event: React.KeyboardEvent<HTMLInputElement>) => { if (!pattern) return; const regex = new RegExp(pattern); const key = String.fromCharCode( !event.charCode ? event.which : event.charCode, ); if (!regex.test(key)) { event.preventDefault(); return false; } }; function safeOnChange(val: string | number | null) { if ( (typeof val === "string" && val.length === 0) || (typeof val === "number" && isNaN(val)) ) { props.onChange(null); } else { props.onChange(val); } } const isCurrencyInput = props.money && !!props.currencyConfig; return ( <Root className={props.className}> {isCurrencyInput ? ( <CurrencyInput currencyConfig={props.currencyConfig} placeholder={props.placeholder} large={props.large} value={props.value} onChange={safeOnChange} /> ) : ( <Input placeholder={props.placeholder} type={props.inputType} onChange={(e) => { let value: string | number | null = e.target.value; if (props.inputType === "number") { value = parseFloat(value); } safeOnChange(value); }} onKeyPress={(e) => handleKeyPress(e)} value={exists(props.value) ? props.value : ""} large={props.large} valid={props.valid} invalid={props.invalid} onBlur={props.onBlur} {...inputProps} /> )} {exists(props.value) && !isEmpty(props.value) && ( <> {props.valid && !props.invalid && ( <GreenIcon icon="check" large={props.large} /> )} {props.invalid && ( <SxWithTooltip text={props.invalidText}> <RedIcon icon="exclamation-triangle" large={props.large} /> </SxWithTooltip> )} <ClearZoneIconButton tiny icon="times" tabIndex={-1} large={props.large} title={t("common.clearValue")} aria-label={t("common.clearValue")} onClick={() => props.onChange(null)} /> </> )} </Root> ); }; export default BaseInput;
manuel-hegner/conquery
frontend/src/js/common/components/AnimatedDots.tsx
import { keyframes } from "@emotion/react"; import styled from "@emotion/styled"; import React from "react"; const blink = keyframes` 50% { color: transparent; } `; const Dot = styled.span` animation: 1s ${blink} infinite; &:nth-of-type(1) { animation-delay: 0ms; } &:nth-of-type(2) { animation-delay: 250ms; } &:nth-of-type(3) { animation-delay: 500ms; } `; const Root = styled("span")` font-weight: 700; `; export default function AnimatedDots() { return ( <Root> <Dot>.</Dot> <Dot>.</Dot> <Dot>.</Dot> </Root> ); }
manuel-hegner/conquery
frontend/src/js/external-forms/FormsTab.tsx
<reponame>manuel-hegner/conquery import { tabDescription } from "."; import { StateT } from "app-types"; import React, { useEffect } from "react"; import { useSelector, useStore } from "react-redux"; import { useGetForms } from "../api/api"; import { DatasetIdT } from "../api/types"; import StandardQueryEditorTab from "../standard-query-editor"; import { updateReducers } from "../store"; import TimebasedQueryEditorTab from "../timebased-query-editor"; import FormsContainer from "./FormsContainer"; import FormsNavigation from "./FormsNavigation"; import FormsQueryRunner from "./FormsQueryRunner"; import buildExternalFormsReducer from "./reducer"; const FormsTab = () => { const store = useStore(); const getForms = useGetForms(); const datasetId = useSelector<StateT, DatasetIdT | null>( (state) => state.datasets.selectedDatasetId, ); useEffect(() => { async function loadForms() { if (!datasetId) { return; } const configuredForms = await getForms(datasetId); const forms = configuredForms.reduce((all, form) => { all[form.type] = form; return all; }, {}); const externalFormsReducer = buildExternalFormsReducer(forms); const tabs = [ StandardQueryEditorTab, TimebasedQueryEditorTab, { ...tabDescription, reducer: externalFormsReducer, }, ]; updateReducers(store, tabs); } loadForms(); }, [store, datasetId]); return ( <> <FormsNavigation /> <FormsContainer /> <FormsQueryRunner /> </> ); }; export default FormsTab;
manuel-hegner/conquery
frontend/src/js/snack-message/reducer.ts
import { getType } from "typesafe-actions"; import { Action } from "../app/actions"; import { resetMessage, setMessage } from "./actions"; export interface SnackMessageStateT { message: string | null; } const initialState: SnackMessageStateT = { message: null, }; function reducer( state: SnackMessageStateT = initialState, action: Action, ): SnackMessageStateT { switch (action.type) { case getType(setMessage): return { ...state, message: action.payload.message }; case getType(resetMessage): return initialState; default: return state; } } export default reducer;
manuel-hegner/conquery
frontend/src/js/header/Header.tsx
<filename>frontend/src/js/header/Header.tsx import styled from "@emotion/styled"; import { StateT } from "app-types"; import preval from "preval.macro"; import React, { FC } from "react"; import { useTranslation } from "react-i18next"; import { useSelector } from "react-redux"; import DatasetSelector from "../dataset/DatasetSelector"; import { useHideLogoutButton } from "../user/selectors"; import LogoutButton from "./LogoutButton"; const Root = styled("header")` background-color: ${({ theme }) => theme.col.bg}; border-bottom: 1px solid ${({ theme }) => theme.col.grayMediumLight}; box-shadow: 0 0 3px 0 rgba(0, 0, 0, 0.3); padding: 0 20px; display: flex; flex-direction: row; justify-content: space-between; align-items: center; // Fix, so content can expand to 100% and scroll position: absolute; z-index: 3; width: 100%; top: 0; left: 0; `; const Right = styled("div")` display: flex; flex-direction: row; align-items: center; `; const OverflowHidden = styled("div")` overflow: hidden; flex-shrink: 0; display: flex; flex-direction: row; align-items: center; `; const Spacer = styled("span")` margin: 0 5px; height: 20px; `; const Logo = styled("div")` height: 40px; width: ${({ theme }) => theme.img.logoWidth}; background-image: url(${({ theme }) => theme.img.logo}); background-repeat: no-repeat; background-position-y: 50%; background-size: ${({ theme }) => theme.img.logoBackgroundSize}; `; const Headline = styled("h1")` margin: 0 auto 0 0; line-height: 2; font-size: ${({ theme }) => theme.font.md}; font-weight: 700; font-size: 12px; opacity: 0.3; text-transform: uppercase; color: ${({ theme }) => theme.col.blueGrayDark}; `; const SxLogoutButton = styled(LogoutButton)` margin-left: 5px; `; const useVersion = () => { const backendVersion = useSelector<StateT, string>( (state) => state.startup.config.version, ); const frontendDateTimeStamp = preval`module.exports = new Date().toISOString();`; // TODO: GET THIS TO WORK WHEN BUILDING INSIDE A DODCKER CONTAINER // const frontendGitCommit = preval` // const { execSync } = require('child_process'); // module.exports = execSync('git rev-parse --short HEAD').toString(); // `; // const frontendGitTag = preval` // const { execSync } = require('child_process'); // module.exports = execSync('git describe --all --exact-match \`git rev-parse HEAD\`').toString(); // `; return { backendVersion, frontendGitCommit: "", frontendDateTimeStamp, frontendGitTag: "", }; }; const Header: FC = () => { const { t } = useTranslation(); const { backendVersion, frontendDateTimeStamp, frontendGitTag, frontendGitCommit, } = useVersion(); const hideLogoutButton = useHideLogoutButton(); const versionString = `BE: ${backendVersion}, FE: ${frontendGitTag} ${frontendGitCommit} ${frontendDateTimeStamp}`; const copyVersionToClipboard = () => { navigator.clipboard.writeText( `${backendVersion} ${frontendGitTag} ${frontendGitCommit}`, ); }; return ( <Root> <OverflowHidden> <Logo title={versionString} onClick={copyVersionToClipboard} /> <Spacer /> <Headline>{t("headline")}</Headline> </OverflowHidden> <Right> <DatasetSelector /> {!hideLogoutButton && <SxLogoutButton />} </Right> </Root> ); }; export default Header;
manuel-hegner/conquery
frontend/src/js/highlightable-label/HighlightableLabel.tsx
import { css } from "@emotion/react"; import styled from "@emotion/styled"; import React, { FC } from "react"; interface PropsT { className?: string; isHighlighted?: boolean; } const Label = styled("span")<{ isHighlighted?: boolean }>` ${({ theme, isHighlighted }) => isHighlighted && css` background-color: ${theme.col.grayVeryLight}; border-radius: ${theme.borderRadius}; padding: 0 3px; `}; `; const HighlightableLabel: FC<PropsT> = ({ isHighlighted, className, children, }) => { return ( <Label className={className} isHighlighted={isHighlighted}> {children} </Label> ); }; export default HighlightableLabel;
manuel-hegner/conquery
frontend/src/js/standard-query-editor/queryReducer.ts
<gh_stars>10-100 import { ActionType, getType } from "typesafe-actions"; import type { TableT, OrNodeT, DateRestrictionNodeT, NegationNodeT, QueryConceptNodeT, SavedQueryNodeT, SelectorT, TableConfigT, FilterConfigT, RangeFilterValueT, FilterIdT, ConceptIdT, } from "../api/types"; import { Action } from "../app/actions"; import { isEmpty, objectWithoutKey } from "../common/helpers"; import { exists } from "../common/helpers/exists"; import { getConceptsByIdsWithTablesAndSelects } from "../concept-trees/globalTreeStoreHelper"; import type { TreesT } from "../concept-trees/reducer"; import { isMultiSelectFilter } from "../model/filter"; import { nodeIsConceptQueryNode } from "../model/node"; import { selectsWithDefaults } from "../model/select"; import { resetAllFiltersInTables, tableWithDefaults } from "../model/table"; import { loadQuery, renameQuery } from "../previous-queries/list/actions"; import { queryGroupModalResetAllDates, queryGroupModalSetDate, } from "../query-group-modal/actions"; import { acceptQueryUploadConceptListModal } from "../query-upload-concept-list-modal/actions"; import { dropAndNode, dropOrNode, resetTable, clearQuery, deleteGroup, deleteNode, toggleTable, updateNodeLabel, setFilterValue, toggleExcludeGroup, loadSavedQuery, toggleTimestamps, toggleSecondaryIdExclude, resetAllFilters, addConceptToNode, removeConceptFromNode, switchFilterMode, setDateColumn, setSelects, setTableSelects, expandPreviousQuery, loadFilterSuggestions, } from "./actions"; import type { StandardQueryNodeT, DragItemQuery, QueryGroupType, DragItemNode, DragItemConceptTreeNode, FilterWithValueType, } from "./types"; export type StandardQueryStateT = QueryGroupType[]; const initialState: StandardQueryStateT = []; const filterItem = ( item: DragItemNode | DragItemQuery | DragItemConceptTreeNode, ): StandardQueryNodeT => { // This sort of mapping might be a problem when adding new optional properties to // either Nodes or Queries: Flow won't complain when we omit those optional // properties here. But we can't use a spread operator either... const baseItem = { label: item.label, excludeTimestamps: item.excludeTimestamps, excludeFromSecondaryIdQuery: item.excludeFromSecondaryIdQuery, loading: item.loading, error: item.error, }; if (item.isPreviousQuery) { return { ...baseItem, id: item.id, // eslint-disable-next-line no-use-before-define query: item.query, isPreviousQuery: item.isPreviousQuery, canExpand: item.canExpand, availableSecondaryIds: item.availableSecondaryIds, }; } else { return { ...baseItem, ids: item.ids, description: item.description, tables: item.tables, selects: item.selects, tree: item.tree, additionalInfos: item.additionalInfos, matchingEntries: item.matchingEntries, matchingEntities: item.matchingEntities, dateRange: item.dateRange, isPreviousQuery: item.isPreviousQuery, }; } }; const setGroupProperties = ( node: StandardQueryStateT, andIdx: number, properties: Partial<QueryGroupType>, ) => { return [ ...node.slice(0, andIdx), { ...node[andIdx], ...properties, }, ...node.slice(andIdx + 1), ]; }; const setElementProperties = ( node: StandardQueryStateT, andIdx: number, orIdx: number, properties: Partial<StandardQueryNodeT>, ) => { const groupProperties = { elements: [ ...node[andIdx].elements.slice(0, orIdx), { ...node[andIdx].elements[orIdx], ...properties, }, ...node[andIdx].elements.slice(orIdx + 1), ], }; return setGroupProperties(node, andIdx, groupProperties); }; const onDropAndNode = ( state: StandardQueryStateT, { item }: ActionType<typeof dropAndNode>["payload"], ) => { const group = state[state.length - 1]; const dateRangeOfLastGroup = group ? group.dateRange : undefined; const nextState: StandardQueryStateT = [ ...state, { elements: [filterItem(item)], dateRange: dateRangeOfLastGroup, }, ]; return item.moved ? onDeleteNode(nextState, { andIdx: item.andIdx, orIdx: item.orIdx, }) : nextState; }; const onDropOrNode = ( state: StandardQueryStateT, { item, andIdx }: ActionType<typeof dropOrNode>["payload"], ) => { const nextState = [ ...state.slice(0, andIdx), { ...state[andIdx], elements: [filterItem(item), ...state[andIdx].elements], }, ...state.slice(andIdx + 1), ]; return item.moved ? item.andIdx === andIdx ? onDeleteNode(nextState, { andIdx: item.andIdx, orIdx: item.orIdx + 1, }) : onDeleteNode(nextState, { andIdx: item.andIdx, orIdx: item.orIdx, }) : nextState; }; // Delete a single Node (concept inside a group) const onDeleteNode = ( state: StandardQueryStateT, { andIdx, orIdx }: ActionType<typeof deleteNode>["payload"], ) => { return [ ...state.slice(0, andIdx), { ...state[andIdx], elements: [ ...state[andIdx].elements.slice(0, orIdx), ...state[andIdx].elements.slice(orIdx + 1), ], }, ...state.slice(andIdx + 1), ].filter((and) => !!and.elements && and.elements.length > 0); }; const onDeleteGroup = ( state: StandardQueryStateT, { andIdx }: ActionType<typeof deleteGroup>["payload"], ) => { return [...state.slice(0, andIdx), ...state.slice(andIdx + 1)]; }; const onToggleExcludeGroup = ( state: StandardQueryStateT, { andIdx }: ActionType<typeof toggleExcludeGroup>["payload"], ) => { return [ ...state.slice(0, andIdx), { ...state[andIdx], exclude: state[andIdx].exclude ? undefined : true, }, ...state.slice(andIdx + 1), ]; }; const updateNodeTable = ( state: StandardQueryStateT, andIdx: number, orIdx: number, tableIdx: number, table: TableT, ) => { const node = state[andIdx].elements[orIdx]; const tables = [ ...node.tables.slice(0, tableIdx), table, ...node.tables.slice(tableIdx + 1), ]; return updateNodeTables(state, andIdx, orIdx, tables); }; const updateNodeTables = ( state: StandardQueryStateT, andIdx: number, orIdx: number, tables, ) => { return setElementProperties(state, andIdx, orIdx, { tables }); }; const onToggleNodeTable = ( state: StandardQueryStateT, { andIdx, orIdx, tableIdx, isExcluded, }: ActionType<typeof toggleTable>["payload"], ) => { const node = state[andIdx].elements[orIdx]; const table = { ...node.tables[tableIdx], exclude: isExcluded, }; return updateNodeTable(state, andIdx, orIdx, tableIdx, table); }; const setNodeFilterProperties = ( state: StandardQueryStateT, { andIdx, orIdx, tableIdx, filterIdx, }: { andIdx: number; orIdx: number; tableIdx: number; filterIdx: number }, properties: Partial<FilterWithValueType>, ) => { const nodeFromState = state[andIdx].elements[orIdx]; if (!nodeIsConceptQueryNode(nodeFromState)) return state; const table = nodeFromState.tables[tableIdx]; const { filters } = table; if (!filters) return state; const filter = filters[filterIdx]; const newTable: TableT = { ...table, filters: [ ...filters.slice(0, filterIdx), { ...filter, ...properties, }, ...filters.slice(filterIdx + 1), ], }; return updateNodeTable(state, andIdx, orIdx, tableIdx, newTable); }; const setNodeFilterValue = ( state: StandardQueryStateT, payload: ActionType<typeof setFilterValue>["payload"], ) => { return setNodeFilterProperties(state, payload, { value: payload.value }); }; const setNodeTableSelects = ( state: StandardQueryStateT, { andIdx, orIdx, tableIdx, value, }: ActionType<typeof setTableSelects>["payload"], ) => { const table = state[andIdx].elements[orIdx].tables[tableIdx]; const { selects } = table; // value contains the selects that have now been selected const newTable = { ...table, selects: selects.map((select) => ({ ...select, selected: !!value && !!value.find((selectedValue) => selectedValue.value === select.id), })), }; return updateNodeTable(state, andIdx, orIdx, tableIdx, newTable); }; const setNodeTableDateColumn = ( state: StandardQueryStateT, { andIdx, orIdx, tableIdx, value, }: ActionType<typeof setDateColumn>["payload"], ) => { const table = state[andIdx].elements[orIdx].tables[tableIdx]; const { dateColumn } = table; // value contains the selects that have now been selected const newTable: TableT = { ...table, dateColumn: { ...dateColumn, value, }, }; return updateNodeTable(state, andIdx, orIdx, tableIdx, newTable); }; const setNodeSelects = ( state: StandardQueryStateT, { andIdx, orIdx, value }: ActionType<typeof setSelects>["payload"], ) => { const node = state[andIdx].elements[orIdx]; if (!nodeIsConceptQueryNode(node)) return state; return setElementProperties(state, andIdx, orIdx, { selects: node.selects.map((select) => ({ ...select, selected: !!value && !!value.find((selectedValue) => selectedValue.value === select.id), })), }); }; const switchNodeFilterMode = ( state: StandardQueryStateT, { andIdx, orIdx, tableIdx, filterIdx, mode, }: ActionType<typeof switchFilterMode>["payload"], ) => { return setNodeFilterProperties( state, { andIdx, orIdx, tableIdx, filterIdx }, { mode, value: null, }, ); }; const resetNodeAllFilters = ( state: StandardQueryStateT, { andIdx, orIdx }: ActionType<typeof resetAllFilters>["payload"], ) => { const node = state[andIdx].elements[orIdx]; const newState = setElementProperties(state, andIdx, orIdx, { excludeFromSecondaryIdQuery: false, excludeTimestamps: false, selects: nodeIsConceptQueryNode(node) ? selectsWithDefaults(node.selects) : [], }); if (!nodeIsConceptQueryNode(node)) return newState; const tables = resetAllFiltersInTables(node.tables); return updateNodeTables(newState, andIdx, orIdx, tables); }; const resetNodeTable = ( state: StandardQueryStateT, { andIdx, orIdx, tableIdx }: ActionType<typeof resetTable>["payload"], ) => { const node = state[andIdx].elements[orIdx]; if (!nodeIsConceptQueryNode(node)) return state; const table = node.tables[tableIdx]; if (!table) return state; return updateNodeTable( state, andIdx, orIdx, tableIdx, tableWithDefaults(table), ); }; const setGroupDate = ( state: StandardQueryStateT, { andIdx, date }: ActionType<typeof queryGroupModalSetDate>["payload"], ) => { return setGroupProperties(state, andIdx, { dateRange: date }); }; const resetGroupDates = ( state: StandardQueryStateT, { andIdx }: ActionType<typeof queryGroupModalResetAllDates>["payload"], ) => { return setGroupProperties(state, andIdx, { dateRange: null }); }; const isRangeFilterConfig = ( filter: FilterConfigT, ): filter is { filter: FilterIdT; value: RangeFilterValueT; type: "INTEGER_RANGE" | "REAL_RANGE" | "MONEY_RANGE"; } => filter.type === "INTEGER_RANGE" || filter.type === "REAL_RANGE" || filter.type === "MONEY_RANGE"; const isMultiSelectFilterConfig = ( filter: FilterConfigT, ): filter is { filter: FilterIdT; value: FilterIdT[]; type: "MULTI_SELECT" | "BIG_MULTI_SELECT"; } => (filter.type === "MULTI_SELECT" || filter.type === "BIG_MULTI_SELECT") && filter.value instanceof Array; // Merges filter values from `table` into declared filters from `savedTable` // // `savedTable` may define filters, but it won't have any filter values, // since `savedTables` comes from a `savedConcept` in a `conceptTree`. Such a // `savedConcept` is never modified and only declares possible filters. // Since `table` comes from a previous query, it may have set filter values // if so, we will need to merge them in. const mergeFiltersFromSavedConcept = ( savedTable: TableT, table?: TableConfigT, ) => { if (!table || !table.filters) return savedTable.filters || null; if (!savedTable.filters) return null; return savedTable.filters.map((savedFilter) => { // TODO: Improve the api and don't use `.filter`, but `.id` or `.filterId` const matchingFilter = table.filters!.find( (f) => f.filter === savedFilter.id, ); if (!matchingFilter) { return savedFilter; } if (isRangeFilterConfig(matchingFilter)) { const filterDetails = matchingFilter.value && !isEmpty(matchingFilter.value.min) && !isEmpty(matchingFilter.value.max) && matchingFilter.value.min === matchingFilter.value.max ? { mode: "exact", value: { exact: matchingFilter.value.min } } : { mode: "range", value: matchingFilter.value }; return { ...savedFilter, ...filterDetails }; } if (isMultiSelectFilterConfig(matchingFilter)) { const filterDetails = { ...matchingFilter, type: savedFilter.type, // matchingFilter.type is sometimes wrongly saying MULTI_SELECT value: matchingFilter.value .map((val) => { if (!isMultiSelectFilter(savedFilter)) { console.error( `Filter: ${savedFilter} is not a multi-select filter, even though its matching filter was: ${matchingFilter}`, ); return val; } else { // There is the possibility, that we have a BIG_MULTI_SELECT that loads options async. // Then filter.options would be empty and we wouldn't find it return savedFilter.options.find((op) => op.value === val) || val; } }) .filter(exists), // For BIG MULTI SELECT only, to be able to load all non-loaded options form the defaultValue later defaultValue: matchingFilter.value.filter((val) => { if (!isMultiSelectFilter(savedFilter)) { console.error( `Filter: ${savedFilter} is not a multi-select filter, even though its matching filter was: ${matchingFilter}`, ); return false; } return !exists(savedFilter.options.find((opt) => opt.value === val)); }), }; return { ...savedFilter, ...filterDetails }; } return { ...savedFilter, ...matchingFilter }; }); }; const mergeSelects = ( savedSelects?: SelectorT[], conceptOrTable?: QueryConceptNodeT | TableT, ) => { if (!conceptOrTable || !conceptOrTable.selects) { return savedSelects || null; } if (!savedSelects) return null; return savedSelects.map((select) => { const selectedSelect = conceptOrTable.selects.find( (id) => id === select.id, ); return { ...select, selected: !!selectedSelect }; }); }; const mergeDateColumn = (savedTable: TableT, table: TableT) => { if (!table || !table.dateColumn || !savedTable.dateColumn) return savedTable.dateColumn; return { ...savedTable.dateColumn, value: table.dateColumn.value, }; }; const mergeTables = (savedTables: TableT[], concept: QueryConceptNodeT) => { return savedTables ? savedTables.map((savedTable) => { // Find corresponding table in previous queryObject // TODO: Disentangle id / connectorId mixing const table = concept.tables.find( (t) => t.id === savedTable.connectorId, ); const filters = mergeFiltersFromSavedConcept(savedTable, table); const selects = mergeSelects(savedTable.selects, table); const dateColumn = mergeDateColumn(savedTable, table); return { ...savedTable, exclude: !table, filters, selects, dateColumn, }; }) : []; }; // Look for tables in the already savedConcept. If they were not included in the // respective query concept, exclude them. // Also, apply all necessary filters const mergeFromSavedConceptIntoNode = ( node: QueryConceptNodeT, { tables, selects }: { tables: TableT[]; selects: SelectorT[] }, ) => { return { selects: mergeSelects(selects, node), tables: mergeTables(tables, node), }; }; const expandNode = ( rootConcepts: TreesT, node: | NegationNodeT | DateRestrictionNodeT | OrNodeT | QueryConceptNodeT | SavedQueryNodeT, expandErrorMessage: string, ) => { switch (node.type) { case "OR": return { type: "OR", elements: node.children.map((c) => expandNode(rootConcepts, c, expandErrorMessage), ), }; case "SAVED_QUERY": return { ...node, id: node.query, isPreviousQuery: true, }; case "DATE_RESTRICTION": return { dateRange: node.dateRange, ...expandNode(rootConcepts, node.child, expandErrorMessage), }; case "NEGATION": return { exclude: true, ...expandNode(rootConcepts, node.child, expandErrorMessage), }; default: const lookupResult = getConceptsByIdsWithTablesAndSelects( rootConcepts, node.ids, ); if (!lookupResult) return { ...node, error: expandErrorMessage, }; const { tables, selects } = mergeFromSavedConceptIntoNode(node, { tables: lookupResult.tables, selects: lookupResult.selects, }); const label = node.label || lookupResult.concepts[0].label; const description = lookupResult.concepts[0].description; return { ...node, label, description, tables, selects, excludeTimestamps: node.excludeFromTimeAggregation, excludeFromSecondaryIdQuery: node.excludeFromSecondaryIdQuery, tree: lookupResult.root, }; } }; // Completely override all groups in the editor with the previous groups, but // a) merge elements with concept data from concept trees (esp. "tables") // b) load nested previous queries contained in that query, // so they can also be expanded const onExpandPreviousQuery = ({ rootConcepts, query, expandErrorMessage, }: ActionType<typeof expandPreviousQuery>["payload"]) => { return query.root.children.map((child) => expandNode(rootConcepts, child, expandErrorMessage), ); }; const findPreviousQueries = (state: StandardQueryStateT, action: any) => { // Find all nodes that are previous queries and have the correct id const queries = state .map((group, andIdx) => { return group.elements .map((concept, orIdx) => ({ ...concept, orIdx })) .filter( (concept) => concept.isPreviousQuery && concept.id === action.payload.queryId, ) .map((concept) => ({ andIdx, orIdx: concept.orIdx, node: objectWithoutKey("orIdx")(concept), })); }) .filter((group) => group.length > 0); return [].concat.apply([], queries); }; const updatePreviousQueries = ( state: StandardQueryStateT, action: any, attributes: any, ) => { const queries = findPreviousQueries(state, action); return queries.reduce((nextState, query) => { const { node, andIdx, orIdx } = query; return [ ...nextState.slice(0, andIdx), { ...nextState[andIdx], elements: [ ...nextState[andIdx].elements.slice(0, orIdx), { ...node, ...attributes, }, ...nextState[andIdx].elements.slice(orIdx + 1), ], }, ...nextState.slice(andIdx + 1), ]; }, state); }; const loadPreviousQueryStart = ( state: StandardQueryStateT, action: ActionType<typeof loadQuery.request>, ) => { return updatePreviousQueries(state, action, { loading: true }); }; const loadPreviousQuerySuccess = ( state: StandardQueryStateT, action: ActionType<typeof loadQuery.success>, ) => { const { data } = action.payload; const maybeLabel = data.label ? { label: data.label } : {}; return updatePreviousQueries(state, action, { ...maybeLabel, id: data.id, loading: false, query: data.query, canExpand: data.canExpand, availableSecondaryIds: data.availableSecondaryIds, }); }; const loadPreviousQueryError = ( state: StandardQueryStateT, action: ActionType<typeof loadQuery.failure>, ) => { return updatePreviousQueries(state, action, { loading: false, error: action.payload.message, }); }; const onRenamePreviousQuery = ( state: StandardQueryStateT, action: ActionType<typeof renameQuery.success>, ) => { return updatePreviousQueries(state, action, { loading: false, label: action.payload.label, }); }; const onToggleTimestamps = ( state: StandardQueryStateT, { andIdx, orIdx }: ActionType<typeof toggleTimestamps>["payload"], ) => { return setElementProperties(state, andIdx, orIdx, { excludeTimestamps: !state[andIdx].elements[orIdx].excludeTimestamps, }); }; const onToggleSecondaryIdExclude = ( state: StandardQueryStateT, { andIdx, orIdx }: ActionType<typeof toggleSecondaryIdExclude>["payload"], ) => { return setElementProperties(state, andIdx, orIdx, { excludeFromSecondaryIdQuery: !state[andIdx].elements[orIdx].excludeFromSecondaryIdQuery, }); }; const loadFilterSuggestionsStart = ( state: StandardQueryStateT, payload: ActionType<typeof loadFilterSuggestions.request>["payload"], ) => setNodeFilterProperties(state, payload, { isLoading: true }); const loadFilterSuggestionsSuccess = ( state: StandardQueryStateT, { data, ...rest }: ActionType<typeof loadFilterSuggestions.success>["payload"], ) => { // When [] comes back from the API, don't touch the current options if (!data || data.length === 0) { return setNodeFilterProperties(state, rest, { isLoading: false }); } return setNodeFilterProperties(state, rest, { isLoading: false, options: data, }); }; const loadFilterSuggestionsError = ( state: StandardQueryStateT, payload: ActionType<typeof loadFilterSuggestions.failure>["payload"], ) => setNodeFilterProperties(state, payload, { isLoading: false }); const createQueryNodeFromConceptListUploadResult = ( label: string, rootConcepts: TreesT, resolvedConcepts: ConceptIdT[], ): DragItemConceptTreeNode | null => { const lookupResult = getConceptsByIdsWithTablesAndSelects( rootConcepts, resolvedConcepts, ); return lookupResult ? { type: "CONCEPT_TREE_NODE", height: 0, width: 0, label, ids: resolvedConcepts, tables: lookupResult.tables, selects: lookupResult.selects, tree: lookupResult.root, } : null; }; const insertUploadedConceptList = ( state: StandardQueryStateT, { label, rootConcepts, resolvedConcepts, andIdx, }: ActionType<typeof acceptQueryUploadConceptListModal>["payload"], ) => { const queryElement = createQueryNodeFromConceptListUploadResult( label, rootConcepts, resolvedConcepts, ); if (!queryElement) return state; return andIdx === null ? onDropAndNode(state, { item: queryElement, }) : onDropOrNode(state, { andIdx, item: queryElement, }); }; const onUpdateNodeLabel = ( state: StandardQueryStateT, { andIdx, orIdx, label }: ActionType<typeof updateNodeLabel>["payload"], ) => { return setElementProperties(state, andIdx, orIdx, { label, }); }; const onAddConceptToNode = ( state: StandardQueryStateT, { andIdx, orIdx, concept }: ActionType<typeof addConceptToNode>["payload"], ) => { const node = state[andIdx].elements[orIdx]; if (!nodeIsConceptQueryNode(node)) return state; return setElementProperties(state, andIdx, orIdx, { ids: [...concept.ids, ...node.ids], }); }; const onRemoveConceptFromNode = ( state: StandardQueryStateT, { andIdx, orIdx, conceptId, }: ActionType<typeof removeConceptFromNode>["payload"], ) => { const node = state[andIdx].elements[orIdx]; if (!nodeIsConceptQueryNode(node)) return state; return setElementProperties(state, andIdx, orIdx, { ids: node.ids.filter((id) => id !== conceptId), }); }; // ----------------------------- // TODO: Figure out, whether we ever want to // include subnodes in the reguar query editor // => If we do, use this method, if we don't remove it // ----------------------------- // // const toggleIncludeSubnodes = (state: StateType, { andIdx, orIdx }: Object) => { // const { includeSubnodes } = action.payload; // const node = state[andIdx].elements[orIdx]; // const concept = getConceptById(node.ids); // const childIds = []; // const elements = concept.children.map(childId => { // const child = getConceptById(childId); // childIds.push(childId); // return { // ids: [childId], // label: child.label, // description: child.description, // tables: node.tables, // selects: node.selects, // tree: node.tree // }; // }); // const groupProps = { // elements: [ // ...state[andIdx].elements.slice(0, orIdx), // { // ...state[andIdx].elements[orIdx], // includeSubnodes // }, // ...state[andIdx].elements.slice(orIdx + 1) // ] // }; // if (includeSubnodes) { // groupProps.elements.push(...elements); // } else { // groupProps.elements = groupProps.elements.filter(element => { // return !(difference(element.ids, childIds).length === 0); // }); // } // return setGroupProperties(state, andIdx, groupProps); // }; // ----------------------------- // Query is an array of "groups" (a AND b and c) // where a, b, c are objects, that (can) have properites, // like `dateRange` or `exclude`. // But the main property is "elements" - an array of objects // that contain at least an ID. // An element may contain an array of tables that may // either be excluded, or contain an array of filters with values. // // Example: // [ // { // elements: [ // { id: 9, tables: [{ id: 1}] }, // { // id: 10, // tables: [ // { id: 213, exclude: true }, // { // id: 452, // filters: [ // { id: 52, type: 'INTEGER_RANGE', value: { min: 2, max: 3 } } // { id: 53, type: 'SELECT', value: "Some example filter value" } // ] // } // ] // } // ] // }, { // elements: [ // {id: 6, tables: []}, {id: 7, tables: []}, {id: 5, tables: []} // ] // } // ] const query = ( state: StandardQueryStateT = initialState, action: Action, ): StandardQueryStateT => { switch (action.type) { case getType(clearQuery): return initialState; case getType(dropAndNode): return onDropAndNode(state, action.payload); case getType(dropOrNode): return onDropOrNode(state, action.payload); case getType(deleteNode): return onDeleteNode(state, action.payload); case getType(deleteGroup): return onDeleteGroup(state, action.payload); case getType(toggleExcludeGroup): return onToggleExcludeGroup(state, action.payload); case getType(loadSavedQuery): return action.payload.query; case getType(updateNodeLabel): return onUpdateNodeLabel(state, action.payload); case getType(addConceptToNode): return onAddConceptToNode(state, action.payload); case getType(removeConceptFromNode): return onRemoveConceptFromNode(state, action.payload); case getType(toggleTable): return onToggleNodeTable(state, action.payload); case getType(setFilterValue): return setNodeFilterValue(state, action.payload); case getType(setTableSelects): return setNodeTableSelects(state, action.payload); case getType(setSelects): return setNodeSelects(state, action.payload); case getType(resetAllFilters): return resetNodeAllFilters(state, action.payload); case getType(resetTable): return resetNodeTable(state, action.payload); case getType(switchFilterMode): return switchNodeFilterMode(state, action.payload); case getType(toggleTimestamps): return onToggleTimestamps(state, action.payload); case getType(toggleSecondaryIdExclude): return onToggleSecondaryIdExclude(state, action.payload); case getType(queryGroupModalSetDate): return setGroupDate(state, action.payload); case getType(queryGroupModalResetAllDates): return resetGroupDates(state, action.payload); case getType(expandPreviousQuery): return onExpandPreviousQuery(action.payload); case getType(loadQuery.request): return loadPreviousQueryStart(state, action); case getType(loadQuery.success): return loadPreviousQuerySuccess(state, action); case getType(loadQuery.failure): return loadPreviousQueryError(state, action); case getType(renameQuery.success): return onRenamePreviousQuery(state, action); case getType(loadFilterSuggestions.request): return loadFilterSuggestionsStart(state, action.payload); case getType(loadFilterSuggestions.success): return loadFilterSuggestionsSuccess(state, action.payload); case getType(loadFilterSuggestions.failure): return loadFilterSuggestionsError(state, action.payload); case getType(acceptQueryUploadConceptListModal): return insertUploadedConceptList(state, action.payload); case getType(setDateColumn): return setNodeTableDateColumn(state, action.payload); default: return state; } }; export default query;
manuel-hegner/conquery
frontend/src/js/GlobalStyles.tsx
import type { Theme } from "@emotion/react"; import { css, Global, useTheme } from "@emotion/react"; const globalStyles = (theme: Theme) => css` * { box-sizing: border-box; } p { line-height: 1.5; } body { font-family: "Roboto", "Arial", sans-serif; font-weight: 300; background: ${theme.col.bg}; margin: 0; color: ${theme.col.black}; min-height: 100vh; height: 100%; overflow: hidden; } button, select, input { font-family: "Roboto", "Arial", sans-serif; } a, a:visited, a:active { color: ${theme.col.black}; text-decoration: none; } button { outline: none; cursor: pointer; } button::-moz-focus-inner { padding: 0; border: 0; } input::-ms-clear { display: none; } select { outline: 0; border-radius: 3px; padding: 8px 30px 8px 8px; border: 1px solid ${theme.col.gray}; appearance: none; font-size: ${theme.font.sm}; cursor: pointer; &:disabled { cursor: not-allowed; } &:hover { background-color: ${theme.col.grayVeryLight}; } } h3 { font-size: ${theme.font.sm}; margin: 0 0 10px 0; color: ${theme.col.blueGrayDark}; line-height: 25px; } `; const splitPaneStyles = (theme: Theme) => css` .SplitPane { .Pane1 { overflow: hidden; } .Pane2 { overflow: hidden; } } .SplitPane--tooltip-fixed { > .Pane1 { width: 30px !important; // Because SplitPane sets an element style after the first drag } } .Resizer { background: ${theme.col.grayMediumLight}; opacity: 0.8; z-index: 1; transition: all 0.5s ease-in-out; box-sizing: border-box; -moz-background-clip: padding; -webkit-background-clip: padding; background-clip: padding-box; &.vertical { width: 11px; margin: 0 -5px; border-left: 5px solid rgba(0, 0, 0, 0); border-right: 5px solid rgba(0, 0, 0, 0); cursor: col-resize; &:hover { &:not(.disabled) { border-left: 5px solid rgba(0, 0, 0, 0.1); border-right: 5px solid rgba(0, 0, 0, 0.1); } } } &.horizontal { height: 11px; margin: -5px 0; border-top: 5px solid rgba(0, 0, 0, 0); border-bottom: 5px solid rgba(0, 0, 0, 0); cursor: row-resize; &:hover { &:not(.disabled) { border-top: 5px solid rgba(0, 0, 0, 0.1); border-bottom: 5px solid rgba(0, 0, 0, 0.1); } } } &.disabled { cursor: not-allowed; } } `; const tippyStyleOverrides = css` .tippy-popper { max-width: initial; } `; const GlobalStyles = () => { const theme = useTheme(); return ( <> <Global styles={tippyStyleOverrides} /> <Global styles={globalStyles(theme)} /> <Global styles={splitPaneStyles(theme)} /> </> ); }; export default GlobalStyles;
manuel-hegner/conquery
frontend/src/js/ui-components/MultiSelectWithFileSupport.tsx
<filename>frontend/src/js/ui-components/MultiSelectWithFileSupport.tsx import React, { FC, useEffect } from "react"; import { getUniqueFileRows } from "../common/helpers/fileHelper"; import { usePrevious } from "../common/helpers/usePrevious"; import AsyncInputMultiSelect from "./AsyncInputMultiSelect"; import InputMultiSelect, { InputMultiSelectProps } from "./InputMultiSelect"; interface PropsT extends InputMultiSelectProps { onLoad?: (prefix: string) => void; onResolve: (rows: string[]) => void; } const MultiSelectWithFileSupport: FC<PropsT> = ({ input, onLoad, onResolve, ...props }) => { const previousDefaultValue = usePrevious(input.defaultValue); useEffect( function resolveDefault() { async function resolveDefaultValue() { const hasDefaultValueToLoad = input.defaultValue && input.defaultValue.length > 0 && JSON.stringify(input.defaultValue) !== JSON.stringify(previousDefaultValue); if (hasDefaultValueToLoad) { await onResolve(input.defaultValue as string[]); } } resolveDefaultValue(); }, [onResolve, previousDefaultValue, input], ); const onDropFile = async (file: File) => { const rows = await getUniqueFileRows(file); onResolve(rows); }; const commonProps = { input: input, onDropFile: onDropFile, }; // Can be both, an auto-completable (async) multi select or a regular one return onLoad ? ( <AsyncInputMultiSelect {...commonProps} {...props} onLoad={onLoad} /> ) : ( <InputMultiSelect {...commonProps} {...props} /> ); }; export default MultiSelectWithFileSupport;
manuel-hegner/conquery
frontend/src/js/tooltip/AdditionalInfoHoverable.tsx
<reponame>manuel-hegner/conquery import styled from "@emotion/styled"; import { FC } from "react"; import { useDispatch } from "react-redux"; import type { ConceptT, DateRangeT, InfoT } from "../api/types"; import { isEmpty } from "../common/helpers"; import { toggleAdditionalInfos, displayAdditionalInfos } from "./actions"; import { AdditionalInfosType } from "./reducer"; const Root = styled("div")` cursor: pointer; `; export type AdditionalInfoHoverableNodeType = { label: string; description?: string; children?: Array<string>; matchingEntries: number; matchingEntities: number; dateRange?: DateRangeT; additionalInfos: InfoT[]; }; // Allowlist the data we pass (especially: don't pass all children) const getAdditionalInfos = (node: ConceptT): AdditionalInfosType => ({ label: node.label, description: node.description, isFolder: !!node.children && node.children.length > 0, matchingEntries: node.matchingEntries, matchingEntities: node.matchingEntities, dateRange: node.dateRange, infos: node.additionalInfos, }); interface Props { node: ConceptT; className?: string; } const AdditionalInfoHoverable: FC<Props> = ({ node, className, children }) => { const dispatch = useDispatch(); const onDisplayAdditionalInfos = () => { if (!node.additionalInfos && isEmpty(node.matchingEntries)) return; dispatch( displayAdditionalInfos({ additionalInfos: getAdditionalInfos(node) }), ); }; const onToggleAdditionalInfos = () => { if (!node.additionalInfos && isEmpty(node.matchingEntries)) return; dispatch([ toggleAdditionalInfos(), displayAdditionalInfos({ additionalInfos: getAdditionalInfos(node) }), ]); }; return ( <Root className={className} onMouseEnter={onDisplayAdditionalInfos} onClick={onToggleAdditionalInfos} > {children} </Root> ); }; export default AdditionalInfoHoverable;
manuel-hegner/conquery
frontend/src/js/preview/actions.ts
<filename>frontend/src/js/preview/actions.ts<gh_stars>10-100 import type { ColumnDescription } from "../api/types"; import { defaultError } from "../common/actions"; import { loadCSV } from "../file/csv"; import { OPEN_PREVIEW, CLOSE_PREVIEW, LOAD_CSV_START, LOAD_CSV_ERROR, } from "./actionTypes"; export function closePreview() { return { type: CLOSE_PREVIEW, }; } const loadCSVStart = () => ({ type: LOAD_CSV_START }); const loadCSVError = (err: any) => defaultError(LOAD_CSV_ERROR, err); const loadCSVSuccess = ( parsed: { result: { data: string[][] } }, columns: ColumnDescription[], ) => ({ type: OPEN_PREVIEW, payload: { csv: parsed.result.data, columns, }, }); export function openPreview(url: string, columns: ColumnDescription[]) { return async (dispatch) => { dispatch(loadCSVStart()); try { const parsed = await loadCSV(url); dispatch(loadCSVSuccess(parsed, columns)); } catch (e) { dispatch(loadCSVError(e)); } }; }
manuel-hegner/conquery
frontend/src/js/authorization/helper.ts
// Putting localStorage into an own constant to type annotate it. const localStorage: Storage = window.localStorage; export const getStoredAuthToken = (): string | null => { return localStorage.getItem("authToken"); }; export const storeAuthToken = (token: string): void => { localStorage.setItem("authToken", token); }; export const deleteStoredAuthToken = (): void => { localStorage.removeItem("authToken"); };
manuel-hegner/conquery
frontend/src/js/standard-query-editor/index.ts
<reponame>manuel-hegner/conquery<filename>frontend/src/js/standard-query-editor/index.ts<gh_stars>10-100 import { combineReducers } from "redux"; import type { TabT } from "../pane/types"; import createQueryRunnerReducer from "../query-runner/reducer"; import type { QueryRunnerStateT } from "../query-runner/reducer"; import StandardQueryEditorTab from "./StandardQueryEditorTab"; import { default as queryReducer } from "./queryReducer"; import type { StandardQueryStateT } from "./queryReducer"; import selectedSecondaryIdsReducer from "./selectedSecondaryIdReducer"; import type { SelectedSecondaryIdStateT } from "./selectedSecondaryIdReducer"; const queryRunnerReducer = createQueryRunnerReducer("standard"); export interface StandardQueryEditorStateT { query: StandardQueryStateT; selectedSecondaryId: SelectedSecondaryIdStateT; queryRunner: QueryRunnerStateT; } const Tab: TabT = { key: "queryEditor", labelKey: "rightPane.queryEditor", tooltipKey: "help.tabQueryEditor", reducer: combineReducers({ query: queryReducer, selectedSecondaryId: selectedSecondaryIdsReducer, queryRunner: queryRunnerReducer, }), component: StandardQueryEditorTab, }; export default Tab;
manuel-hegner/conquery
frontend/src/js/model/query.ts
import type { StandardQueryStateT } from "../standard-query-editor/queryReducer"; import type { PreviousQueryQueryNodeType, StandardQueryNodeT, } from "../standard-query-editor/types"; import { TIMEBASED_OPERATOR_TYPES } from "../timebased-query-editor/reducer"; function isTimebasedQuery(node: PreviousQueryQueryNodeType) { const queryString = JSON.stringify(node.query); return TIMEBASED_OPERATOR_TYPES.some((op) => queryString.indexOf(op) !== -1); } // A little weird that it's nested so deeply, but well, you can't expand an external query function isExternalQuery(node: PreviousQueryQueryNodeType) { return ( node.query.type === "CONCEPT_QUERY" && node.query.root && node.query.root.type === "EXTERNAL_RESOLVED" ); } export function isQueryExpandable(node: StandardQueryNodeT) { if (!node.isPreviousQuery || !node.query || !node.canExpand) return false; return !isTimebasedQuery(node) && !isExternalQuery(node); } // Validation export function validateQueryLength(query: StandardQueryStateT) { return query.length > 0; } function elementHasValidDates(element) { return !element.excludeTimestamps; } function groupHasValidDates(group) { return !group.exclude && group.elements.some(elementHasValidDates); } export function validateQueryDates(query: StandardQueryStateT) { return !query || query.length === 0 || query.some(groupHasValidDates); }
manuel-hegner/conquery
frontend/src/js/external-forms/form-components/Description.tsx
<reponame>manuel-hegner/conquery import styled from "@emotion/styled"; export const Description = styled("p")` font-size: 14px; margin: 0 0 10px; `;
manuel-hegner/conquery
frontend/src/js/ui-components/ToggleButton.tsx
import { css } from "@emotion/react"; import styled from "@emotion/styled"; import React, { FC } from "react"; import WithTooltip from "../tooltip/WithTooltip"; const Root = styled("div")` margin: 0; display: flex; flex-wrap: wrap; align-items: center; `; const Option = styled("span")<{ active?: boolean; isFirst?: boolean; isLast?: boolean; }>` font-size: ${({ theme }) => theme.font.xs}; display: inline-block; padding: 4px 8px; cursor: pointer; transition: color ${({ theme }) => theme.transitionTime}, background-color ${({ theme }) => theme.transitionTime}; color: ${({ theme, active }) => (active ? theme.col.black : theme.col.gray)}; border: 1px solid ${({ theme }) => theme.col.gray}; background-color: ${({ theme, active }) => active ? "white" : theme.col.grayVeryLight}; margin-left: -1px; margin-bottom: 2px; &:hover { background-color: ${({ theme, active }) => active ? "white" : theme.col.bg}; } ${({ isFirst }) => isFirst && css` margin-left: 0; border-top-left-radius: 2px; border-bottom-left-radius: 2px; `} ${({ isLast }) => isLast && css` border-top-right-radius: 2px; border-bottom-right-radius: 2px; `} `; interface OptionsT { label: string; value: string; description?: string; } interface PropsT { className?: string; options: OptionsT[]; input: { value: any; onChange: (value: any) => void; }; } const ToggleButton: FC<PropsT> = ({ options, input, className }) => { return ( <Root className={className}> {options.map(({ value, label, description }, i) => ( <WithTooltip key={value} text={description}> <Option isFirst={i === 0} isLast={i === options.length - 1} active={input.value === value} onClick={() => { if (value !== input.value) input.onChange(value); }} > {label} </Option> </WithTooltip> ))} </Root> ); }; export default ToggleButton;
manuel-hegner/conquery
frontend/src/js/concept-trees-open/ConceptTreesOpenButtons.tsx
<reponame>manuel-hegner/conquery<gh_stars>10-100 import styled from "@emotion/styled"; import { StateT } from "app-types"; import React, { FC } from "react"; import { useTranslation } from "react-i18next"; import { useDispatch, useSelector } from "react-redux"; import IconButton from "../button/IconButton"; import { clearSearchQuery } from "../concept-trees/actions"; import { useRootConceptIds } from "../concept-trees/useRootConceptIds"; import WithTooltip from "../tooltip/WithTooltip"; import { closeAllConceptOpen, resetAllConceptOpen } from "./actions"; import { ConceptTreesOpenStateT } from "./reducer"; const SxWithTooltip = styled(WithTooltip)` margin-right: 5px; &:last-of-type { margin-right: 0; } `; const Row = styled("div")` display: flex; align-items: center; `; const SxIconButton = styled(IconButton)` padding: 8px 6px; `; interface PropsT { className?: string; } const ConceptTreesOpenButtons: FC<PropsT> = ({ className }) => { const dispatch = useDispatch(); const { t } = useTranslation(); const conceptTreesOpen = useSelector<StateT, ConceptTreesOpenStateT>( (state) => state.conceptTreesOpen, ); const rootConceptIds = useRootConceptIds(); const onCloseAllConceptOpen = () => dispatch(closeAllConceptOpen(rootConceptIds)); const onResetAllConceptOpen = () => { dispatch(resetAllConceptOpen()); dispatch(clearSearchQuery()); }; const areAllClosed = rootConceptIds.every( (id) => conceptTreesOpen[id] === false, ); const hasSearch = useSelector<StateT, boolean>( (state) => !!state.conceptTrees.search.result, ); const isCloseAllDisabled = areAllClosed || hasSearch; return ( <Row className={className}> <SxWithTooltip text={t("conceptTreesOpen.resetAll")}> <SxIconButton frame icon="home" onClick={onResetAllConceptOpen} /> </SxWithTooltip> <SxWithTooltip text={t("conceptTreesOpen.closeAll")}> <SxIconButton disabled={isCloseAllDisabled} frame icon="folder-minus" onClick={onCloseAllConceptOpen} /> </SxWithTooltip> </Row> ); }; export default ConceptTreesOpenButtons;
manuel-hegner/conquery
frontend/src/js/previous-queries/list/reducer.ts
<reponame>manuel-hegner/conquery<filename>frontend/src/js/previous-queries/list/reducer.ts<gh_stars>10-100 import { getType } from "typesafe-actions"; import type { QueryIdT, UserGroupIdT } from "../../api/types"; import { Action } from "../../app/actions"; import { deleteQuerySuccess, loadQueries, loadQuery, renameQuery, retagQuery, shareQuerySuccess, } from "./actions"; export type PreviousQueryIdT = string; export interface PreviousQueryT { id: PreviousQueryIdT; label: string; loading?: boolean; error?: string | null; numberOfResults: number | null; createdAt: string; tags: string[]; own: boolean; ownerName: string; system?: boolean; resultUrls: string[]; shared: boolean; isPristineLabel?: boolean; groups?: UserGroupIdT[]; queryType: "CONCEPT_QUERY" | "SECONDARY_ID_QUERY"; secondaryId?: string | null; } export interface PreviousQueriesStateT { queries: PreviousQueryT[]; loading: boolean; error: string | null; } const initialState: PreviousQueriesStateT = { queries: [], loading: false, error: null, }; const findQuery = (queries: PreviousQueryT[], queryId: string | number) => { const query = queries.find((q) => q.id === queryId); return { query, queryIdx: query ? queries.indexOf(query) : -1, }; }; const updatePreviousQuery = ( state: PreviousQueriesStateT, { payload: { queryId } }: { payload: { queryId: QueryIdT } }, attributes: Partial<PreviousQueryT>, ) => { const { query, queryIdx } = findQuery(state.queries, queryId); if (!query) return state; return { ...state, queries: [ ...state.queries.slice(0, queryIdx), { ...query, ...attributes, }, ...state.queries.slice(queryIdx + 1), ], }; }; const sortQueries = (queries: PreviousQueryT[]) => { return queries.sort((a, b) => { return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(); }); }; const deletePreviousQuery = ( state: PreviousQueriesStateT, { queryId }: { queryId: QueryIdT }, ) => { const { queryIdx } = findQuery(state.queries, queryId); return { ...state, queries: [ ...state.queries.slice(0, queryIdx), ...state.queries.slice(queryIdx + 1), ], }; }; const previousQueriesReducer = ( state: PreviousQueriesStateT = initialState, action: Action, ): PreviousQueriesStateT => { switch (action.type) { case getType(loadQueries.request): return { ...state, loading: true }; case getType(loadQueries.success): return { ...state, loading: false, queries: sortQueries(action.payload.data), }; case getType(loadQueries.failure): return { ...state, loading: false, error: action.payload.message || null, }; case getType(loadQuery.request): case getType(renameQuery.request): case getType(retagQuery.request): return updatePreviousQuery(state, action, { loading: true }); case getType(loadQuery.success): return updatePreviousQuery(state, action, { loading: false, error: null, ...action.payload.data, }); case getType(renameQuery.success): return updatePreviousQuery(state, action, { loading: false, error: null, label: action.payload.label, isPristineLabel: false, }); case getType(retagQuery.success): return updatePreviousQuery(state, action, { loading: false, error: null, tags: action.payload.tags, }); case getType(shareQuerySuccess): return updatePreviousQuery(state, action, { loading: false, error: null, groups: action.payload.groups, ...(!action.payload.groups || action.payload.groups.length === 0 ? { shared: false } : { shared: true }), }); case getType(deleteQuerySuccess): return deletePreviousQuery(state, action.payload); case getType(loadQuery.failure): case getType(renameQuery.failure): case getType(retagQuery.failure): return updatePreviousQuery(state, action, { loading: false, error: action.payload.message, }); default: return state; } }; export default previousQueriesReducer;
manuel-hegner/conquery
frontend/src/js/external-forms/actions.ts
import { SET_EXTERNAL_FORM, LOAD_EXTERNAL_FORM_VALUES } from "./actionTypes"; export const setExternalForm = (form: string) => ({ type: SET_EXTERNAL_FORM, payload: { form }, }); export const loadExternalFormValues = (formType: string, values: any) => ({ type: LOAD_EXTERNAL_FORM_VALUES, payload: { formType, values }, });
manuel-hegner/conquery
frontend/src/js/model/node.ts
<reponame>manuel-hegner/conquery import { ConceptElementT, ConceptT } from "../api/types"; import type { ConceptQueryNodeType, StandardQueryNodeT, } from "../standard-query-editor/types"; import { objectHasSelectedSelects } from "./select"; import { tablesHaveActiveFilter } from "./table"; export const nodeIsConceptQueryNode = ( node: StandardQueryNodeT, ): node is ConceptQueryNodeType => !node.isPreviousQuery; export const nodeHasActiveFilters = (node: StandardQueryNodeT) => node.excludeTimestamps || node.excludeFromSecondaryIdQuery || (nodeIsConceptQueryNode(node) && (node.includeSubnodes || // TODO REFACTOR / TYPE THIS ONE objectHasSelectedSelects(node) || nodeHasActiveTableFilters(node) || nodeHasExludedTable(node))); export const nodeHasActiveTableFilters = (node: ConceptQueryNodeType) => { if (!node.tables) return false; return tablesHaveActiveFilter(node.tables); }; export const nodeHasExludedTable = (node: ConceptQueryNodeType) => { if (!node.tables) return false; return node.tables.some((table) => table.exclude); }; export function nodeIsInvalid( node: ConceptQueryNodeType, blocklistedConceptIds?: string[], allowlistedConceptIds?: string[], ) { return ( (!!allowlistedConceptIds && !nodeIsAllowlisted(node, allowlistedConceptIds)) || (!!blocklistedConceptIds && nodeIsBlocklisted(node, blocklistedConceptIds)) ); } export function nodeIsBlocklisted( node: ConceptQueryNodeType, blocklistedConceptIds: string[], ) { return ( !!node.ids && blocklistedConceptIds.some((id) => node.ids.some((conceptId) => conceptId.indexOf(id.toLowerCase()) !== -1), ) ); } export function nodeIsAllowlisted( node: ConceptQueryNodeType, allowlistedConceptIds: string[], ) { return ( !!node.ids && allowlistedConceptIds.some((id) => node.ids.every((conceptId) => conceptId.indexOf(id.toLowerCase()) !== -1), ) ); } export function nodeIsElement(node: ConceptT): node is ConceptElementT { return "tables" in node; }
manuel-hegner/conquery
frontend/src/js/store.ts
<reponame>manuel-hegner/conquery import { applyMiddleware, compose, createStore, Store } from "redux"; import { composeWithDevTools } from "redux-devtools-extension"; import multi from "redux-multi"; import thunk from "redux-thunk"; import buildAppReducer from "./app/reducers"; import { TabT } from "./pane/types"; export function makeStore(initialState: Object, tabs: Object) { const middleware = applyMiddleware(thunk, multi); const enhancer = composeWithDevTools(middleware); const store = createStore(buildAppReducer(tabs), initialState, enhancer); if (module.hot) { // Enable Webpack hot module replacement for reducers module.hot.accept("./app/reducers", () => { const nextRootReducer = buildAppReducer(tabs); store.replaceReducer(nextRootReducer); }); } return store; } export function updateReducers(store: Store, tabs: TabT[]) { store.replaceReducer(buildAppReducer(tabs)); }
manuel-hegner/conquery
frontend/src/js/ui-components/EditableText.tsx
<gh_stars>10-100 import styled from "@emotion/styled"; import React from "react"; import Highlighter from "react-highlight-words"; import IconButton from "../button/IconButton"; import HighlightableLabel from "../highlightable-label/HighlightableLabel"; import WithTooltip from "../tooltip/WithTooltip"; import EditableTextForm from "./EditableTextForm"; interface PropsT { className?: string; loading: boolean; editing: boolean; text: string; tooltip?: string; large?: boolean; saveOnClickoutside?: boolean; isHighlighted?: boolean; highlightedWords?: string[]; selectTextOnMount?: boolean; onSubmit: (text: string) => void; onToggleEdit: () => void; } const SxIconButton = styled(IconButton)` margin-right: ${({ large }) => (large ? "10px" : "7px")}; padding: 2px 0; `; const Text = styled("div")` display: flex; flex-direction: row; align-items: flex-start; `; const SxHighlightableLabel = styled(HighlightableLabel)` text-overflow: ellipsis; overflow: hidden; white-space: nowrap; `; const EditableText: React.FC<PropsT> = (props) => { return props.editing ? ( <EditableTextForm className={props.className} loading={props.loading} text={props.text} selectTextOnMount={props.selectTextOnMount} saveOnClickoutside={props.saveOnClickoutside} onSubmit={props.onSubmit} onCancel={props.onToggleEdit} /> ) : ( <Text className={props.className}> <WithTooltip text={props.tooltip}> <SxIconButton large={props.large} bare icon="pen" onClick={props.onToggleEdit} /> </WithTooltip> <SxHighlightableLabel isHighlighted={props.isHighlighted}> {props.highlightedWords && props.highlightedWords.length > 0 ? ( <Highlighter searchWords={props.highlightedWords} autoEscape textToHighlight={props.text} /> ) : ( props.text )} </SxHighlightableLabel> </Text> ); }; export default EditableText;
manuel-hegner/conquery
frontend/src/js/query-runner/actionTypes.ts
export const START_QUERY_START = "query-runners/START_QUERY_START"; export const START_QUERY_SUCCESS = "query-runners/START_QUERY_SUCCESS"; export const START_QUERY_ERROR = "query-runners/START_QUERY_ERROR"; export const STOP_QUERY_START = "query-runners/STOP_QUERY_START"; export const STOP_QUERY_SUCCESS = "query-runners/STOP_QUERY_SUCCESS"; export const STOP_QUERY_ERROR = "query-runners/STOP_QUERY_ERROR"; export const QUERY_RESULT_START = "query-runners/QUERY_RESULT_START"; export const QUERY_RESULT_RESET = "query-runners/QUERY_RESULT_RESET"; export const QUERY_RESULT_RUNNING = "query-runners/QUERY_RESULT_RUNNING"; export const QUERY_RESULT_SUCCESS = "query-runners/QUERY_RESULT_SUCCESS"; export const QUERY_RESULT_ERROR = "query-runners/QUERY_RESULT_ERROR";
manuel-hegner/conquery
frontend/src/js/authorization/LoginPage.tsx
<gh_stars>10-100 import styled from "@emotion/styled"; import React, { useState } from "react"; import { useTranslation } from "react-i18next"; import { useHistory } from "react-router-dom"; import { usePostLogin } from "../api/api"; import PrimaryButton from "../button/PrimaryButton"; import ErrorMessage from "../error-message/ErrorMessage"; import FaIcon from "../icon/FaIcon"; import InputPlain from "../ui-components/InputPlain"; import { storeAuthToken } from "./helper"; const Root = styled("div")` display: flex; align-items: center; justify-content: center; height: 100vh; background-color: ${({ theme }) => theme.col.bgAlt}; `; const Wrap = styled("div")` max-width: 255px; display: flex; flex-direction: column; align-items: center; justify-content: center; `; const Logo = styled("div")` width: ${({ theme }) => theme.img.logoWidth}; height: 35px; background-image: url(${({ theme }) => theme.img.logo}); background-repeat: no-repeat; background-position-y: 50%; background-size: ${({ theme }) => theme.img.logoBackgroundSize}; `; const Headline = styled("h2")` line-height: 2; font-size: ${({ theme }) => theme.font.md}; text-transform: uppercase; font-weight: 300; color: ${({ theme }) => theme.col.gray}; margin: 0; `; const Form = styled("form")` margin: 15px auto 50px; display: flex; flex-direction: column; align-items: center; justify-content: center; `; const SxInputPlain = styled(InputPlain)` padding: 10px 0; `; const SxPrimaryButton = styled(PrimaryButton)` margin-top: 35px; width: 255px; display: flex; align-items: center; justify-content: center; `; const SxFaIcon = styled(FaIcon)` margin-right: 10px; `; const SxErrorMessage = styled(ErrorMessage)` margin: 20px 10px 0; `; const LoginPage = () => { const [user, setUser] = useState(""); const [password, setPassword] = useState(""); const [loading, setLoading] = useState(false); const [error, setError] = useState(false); const history = useHistory(); const postLogin = usePostLogin(); const { t } = useTranslation(); async function onSubmit(e: any) { e.preventDefault(); setLoading(true); try { const result = await postLogin(user, password); if (result.access_token) { storeAuthToken(result.access_token); history.push("/"); return; } } catch (e) { setError(true); } setLoading(false); } return ( <Root> <Wrap> <Logo /> <Headline>{t("login.headline")}</Headline> {!!error && <SxErrorMessage message={t("login.error")} />} <Form onSubmit={onSubmit}> <SxInputPlain label={t("login.username")} large input={{ value: user, onChange: setUser, }} inputProps={{ disabled: loading, }} /> <SxInputPlain inputType="password" label={t("login.password")} large input={{ value: password, onChange: setPassword, }} inputProps={{ disabled: loading, }} /> <SxPrimaryButton disabled={!user || !password} large type="submit"> <SxFaIcon large white icon={loading ? "spinner" : "check"} /> {t("login.submit")} </SxPrimaryButton> </Form> </Wrap> </Root> ); }; export default LoginPage;
manuel-hegner/conquery
frontend/src/js/previous-queries/list/PreviousQueriesFolder.tsx
<reponame>manuel-hegner/conquery<filename>frontend/src/js/previous-queries/list/PreviousQueriesFolder.tsx<gh_stars>10-100 import styled from "@emotion/styled"; import React, { FC } from "react"; import Highlighter from "react-highlight-words"; import { exists } from "../../common/helpers/exists"; import FaIcon from "../../icon/FaIcon"; const SxFaIcon = styled(FaIcon)` margin-right: 8px; `; const Folder = styled("div")<{ active?: boolean; special?: boolean }>` display: inline-flex; align-items: flex-start; padding: 2px 7px; border-radius: ${({ theme }) => theme.borderRadius}; font-size: ${({ theme }) => theme.font.sm}; cursor: pointer; font-style: ${({ special }) => (special ? "italic" : "inherit")}; background-color: ${({ theme, active }) => active ? theme.col.grayLight : "transparent"}; &:hover { background-color: ${({ theme }) => theme.col.blueGrayVeryLight}; } `; const Text = styled("div")` flex-shrink: 0; color: ${({ theme }) => theme.col.black}; `; const ResultCount = styled("span")` flex-shrink: 0; display: inline-flex; align-items: center; justify-content: center; line-height: 1; padding: 2px 0; margin-right: 5px; font-size: ${({ theme }) => theme.font.xs}; border-radius: ${({ theme }) => theme.borderRadius}; color: ${({ theme }) => theme.col.blueGrayDark}; font-weight: 700; `; interface Props { folder: string; resultCount: number | null; resultWords: string[]; className?: string; active?: boolean; special?: boolean; empty?: boolean; onClick: () => void; } const PreviousQueriesFolder: FC<Props> = ({ className, resultCount, resultWords, folder, active, special, empty, onClick, }) => { return ( <Folder key={folder} active={active} special={special} onClick={onClick} className={className} title={folder} > <SxFaIcon icon="folder" regular={special} active /> {exists(resultCount) && <ResultCount>{resultCount}</ResultCount>} <Text> {!empty && resultWords.length > 0 ? ( <Highlighter autoEscape searchWords={resultWords} textToHighlight={folder} /> ) : ( folder )} </Text> </Folder> ); }; export default PreviousQueriesFolder;
manuel-hegner/conquery
frontend/src/types/axios.d.ts
// https://github.com/axios/axios/issues/2296 declare module "axios/lib/adapters/http" { import { Adapter } from "axios"; const HttpAdapter: Adapter; export default HttpAdapter; }
manuel-hegner/conquery
frontend/src/js/ui-components/Optional.tsx
<filename>frontend/src/js/ui-components/Optional.tsx import styled from "@emotion/styled"; import React from "react"; import { useTranslation } from "react-i18next"; const Text = styled("div")` font-size: ${({ theme }) => theme.font.tiny}; text-transform: uppercase; color: ${({ theme }) => theme.col.gray}; padding-right: 6px; font-weight: 700; `; const Optional = () => { const { t } = useTranslation(); return <Text>({t("common.optional")})</Text>; }; export default Optional;
manuel-hegner/conquery
frontend/src/js/external-forms/FormsContainer.tsx
<reponame>manuel-hegner/conquery<filename>frontend/src/js/external-forms/FormsContainer.tsx import styled from "@emotion/styled"; import { StateT } from "app-types"; import React, { FC } from "react"; import { useSelector } from "react-redux"; import type { Form as FormType } from "./config-types"; import Form from "./form/Form"; import { selectFormConfig } from "./stateSelectors"; const Root = styled("div")` flex-grow: 1; overflow-y: auto; -webkit-overflow-scrolling: touch; padding: 0 20px 20px 10px; `; const FormsContainer: FC = () => { const formConfig = useSelector<StateT, FormType | null>((state) => selectFormConfig(state), ); return <Root>{!!formConfig && <Form config={formConfig} />}</Root>; }; export default React.memo(FormsContainer);
manuel-hegner/conquery
frontend/src/js/ui-components/InputMultiSelectDropzone.tsx
import styled from "@emotion/styled"; import React, { FC, ReactNode, useRef } from "react"; import { NativeTypes } from "react-dnd-html5-backend"; import { useTranslation } from "react-i18next"; import Dropzone from "./Dropzone"; import type { DragItemFile } from "./DropzoneWithFileInput"; const Root = styled("div")` position: relative; `; const SxDropzone = styled(Dropzone)` padding: 5px; `; const FileInput = styled("input")` display: none; `; const TopRight = styled("p")` margin: 0; font-size: ${({ theme }) => theme.font.tiny}; color: ${({ theme }) => theme.col.gray}; position: absolute; top: -15px; right: 0; cursor: pointer; &:hover { text-decoration: underline; } `; interface PropsT { className?: string; onDropFile: (file: File) => void; children: () => ReactNode; } const InputMultiSelectDropzone: FC<PropsT> = ({ className, onDropFile, children, }) => { const { t } = useTranslation(); const fileInputRef = useRef(null); function onOpenFileDialog() { fileInputRef.current.click(); } return ( <Root className={className}> <SxDropzone<DragItemFile> acceptedDropTypes={[NativeTypes.FILE]} onDrop={(item) => { onDropFile(item.files[0]); }} > {children} </SxDropzone> <TopRight onClick={onOpenFileDialog}> {t("inputMultiSelect.openFileDialog")} <FileInput ref={fileInputRef} type="file" onChange={(e) => { onDropFile(e.target.files[0]); fileInputRef.current.value = null; }} /> </TopRight> </Root> ); }; export default InputMultiSelectDropzone;
manuel-hegner/conquery
frontend/src/js/standard-query-editor/helper.ts
import { getConceptById } from "../concept-trees/globalTreeStoreHelper"; import type { ConceptQueryNodeType, StandardQueryNodeT } from "./types"; export function getRootNodeLabel(node: StandardQueryNodeT) { if (!node.ids || !node.tree) return null; const nodeIsRootNode = node.ids.indexOf(node.tree) !== -1; if (nodeIsRootNode) return null; const root = getConceptById(node.tree); return !!root ? root.label : null; } export function isLabelPristine(node: ConceptQueryNodeType) { if (node.ids.length === 0) { return false; } const storedConcept = getConceptById(node.ids[0]); return !!storedConcept && storedConcept.label === node.label; }
manuel-hegner/conquery
frontend/src/js/browserShimsAndPolyfills.ts
<reponame>manuel-hegner/conquery // @ts-nocheck /* eslint-disable */ import "core-js/features/array/find"; import "core-js/features/array/flat-map"; import "core-js/features/array/from"; import "core-js/features/array/includes"; import "core-js/features/array/iterator"; import "core-js/features/object/assign"; import "core-js/features/object/entries"; import "core-js/features/object/values"; import "core-js/features/promise"; import "core-js/features/set"; import "core-js/features/string/ends-with"; import "core-js/features/symbol"; import "core-js/web/url"; import "core-js/web/url-search-params"; // Remove fetch from window object so polyfill is used if (window.navigator.userAgent.indexOf("Edge") > -1) window.fetch = undefined; // -------------------- // -------------------- // CLASSLIST POLYFILL // -------------------- // -------------------- // 1. String.prototype.trim polyfill if (!"".trim) String.prototype.trim = function () { return this.replace(/^[\s]+|[\s]+$/g, ""); }; (function (window) { "use strict"; // prevent global namespace pollution if (!window.DOMException) (DOMException = function (reason) { this.message = reason; }).prototype = new Error(); var wsRE = /[\11\12\14\15\40]/, wsIndex = 0, checkIfValidClassListEntry = function (O, V) { if (V === "") throw new DOMException( "Failed to execute '" + O + "' on 'DOMTokenList': The token provided must not be empty.", ); if ((wsIndex = V.search(wsRE)) !== -1) throw new DOMException( "Failed to execute '" + O + "' on 'DOMTokenList': " + "The token provided ('" + V[wsIndex] + "') contains HTML space characters, which are not valid in tokens.", ); }; // 2. Implement the barebones DOMTokenList livelyness polyfill if (typeof DOMTokenList !== "function") (function (window) { var document = window.document, Object = window.Object, hasOwnProp = Object.prototype.hasOwnProperty; var defineProperty = Object.defineProperty, allowTokenListConstruction = 0, skipPropChange = 0; function DOMTokenList() { if (!allowTokenListConstruction) throw TypeError("Illegal constructor"); // internally let it through } DOMTokenList.prototype.toString = DOMTokenList.prototype.toLocaleString = function () { return this.value; }; DOMTokenList.prototype.add = function () { a: for ( var v = 0, argLen = arguments.length, val = "", ele = this[" uCL"], proto = ele[" uCLp"]; v !== argLen; ++v ) { (val = arguments[v] + ""), checkIfValidClassListEntry("add", val); for (var i = 0, Len = proto.length, resStr = val; i !== Len; ++i) if (this[i] === val) continue a; else resStr += " " + this[i]; (this[Len] = val), (proto.length += 1), (proto.value = resStr); } (skipPropChange = 1), (ele.className = proto.value), (skipPropChange = 0); }; DOMTokenList.prototype.remove = function () { for ( var v = 0, argLen = arguments.length, val = "", ele = this[" uCL"], proto = ele[" uCLp"]; v !== argLen; ++v ) { (val = arguments[v] + ""), checkIfValidClassListEntry("remove", val); for ( var i = 0, Len = proto.length, resStr = "", is = 0; i !== Len; ++i ) if (is) { this[i - 1] = this[i]; } else { if (this[i] !== val) { resStr += this[i] + " "; } else { is = 1; } } if (!is) continue; delete this[Len], (proto.length -= 1), (proto.value = resStr); } (skipPropChange = 1), (ele.className = proto.value), (skipPropChange = 0); }; window.DOMTokenList = DOMTokenList; function whenPropChanges() { var evt = window.event, prop = evt.propertyName; if ( !skipPropChange && (prop === "className" || (prop === "classList" && !defineProperty)) ) { var target = evt.srcElement, protoObjProto = target[" uCLp"], strval = "" + target[prop]; var tokens = strval.trim().split(wsRE), resTokenList = target[prop === "classList" ? " uCL" : "classList"]; var oldLen = protoObjProto.length; a: for ( var cI = 0, cLen = (protoObjProto.length = tokens.length), sub = 0; cI !== cLen; ++cI ) { for (var innerI = 0; innerI !== cI; ++innerI) if (tokens[innerI] === tokens[cI]) { sub++; continue a; } resTokenList[cI - sub] = tokens[cI]; } for (var i = cLen - sub; i < oldLen; ++i) delete resTokenList[i]; //remove trailing indexs if (prop !== "classList") return; (skipPropChange = 1), (target.classList = resTokenList), (target.className = strval); (skipPropChange = 0), (resTokenList.length = tokens.length - sub); } } function polyfillClassList(ele) { if (!ele || !("innerHTML" in ele)) throw TypeError("Illegal invocation"); ele.detachEvent("onpropertychange", whenPropChanges); // prevent duplicate handler infinite loop allowTokenListConstruction = 1; try { function protoObj() {} protoObj.prototype = new DOMTokenList(); } finally { allowTokenListConstruction = 0; } var protoObjProto = protoObj.prototype, resTokenList = new protoObj(); a: for ( var toks = ele.className.trim().split(wsRE), cI = 0, cLen = toks.length, sub = 0; cI !== cLen; ++cI ) { for (var innerI = 0; innerI !== cI; ++innerI) if (toks[innerI] === toks[cI]) { sub++; continue a; } this[cI - sub] = toks[cI]; } (protoObjProto.length = cLen - sub), (protoObjProto.value = ele.className), (protoObjProto[" uCL"] = ele); if (defineProperty) { defineProperty(ele, "classList", { // IE8 & IE9 allow defineProperty on the DOM enumerable: 1, get: function () { return resTokenList; }, configurable: 0, set: function (newVal) { (skipPropChange = 1), (ele.className = protoObjProto.value = newVal += ""), (skipPropChange = 0); var toks = newVal.trim().split(wsRE), oldLen = protoObjProto.length; a: for ( var cI = 0, cLen = (protoObjProto.length = toks.length), sub = 0; cI !== cLen; ++cI ) { for (var innerI = 0; innerI !== cI; ++innerI) if (toks[innerI] === toks[cI]) { sub++; continue a; } resTokenList[cI - sub] = toks[cI]; } for (var i = cLen - sub; i < oldLen; ++i) delete resTokenList[i]; //remove trailing indexs }, }); defineProperty(ele, " uCLp", { // for accessing the hidden prototype enumerable: 0, configurable: 0, writeable: 0, value: protoObj.prototype, }); defineProperty(protoObjProto, " uCL", { enumerable: 0, configurable: 0, writeable: 0, value: ele, }); } else { (ele.classList = resTokenList), (ele[" uCL"] = resTokenList), (ele[" uCLp"] = protoObj.prototype); } ele.attachEvent("onpropertychange", whenPropChanges); } try { // Much faster & cleaner version for IE8 & IE9: // Should work in IE8 because Element.prototype instanceof Node is true according to the specs window.Object.defineProperty(window.Element.prototype, "classList", { enumerable: 1, get: function (val) { if (!hasOwnProp.call(this, "classList")) polyfillClassList(this); return this.classList; }, configurable: 0, set: function (val) { this.className = val; }, }); } catch (e) { // Less performant fallback for older browsers (IE 6-8): window[" uCL"] = polyfillClassList; // the below code ensures polyfillClassList is applied to all current and future elements in the doc. document.documentElement.firstChild.appendChild( document.createElement("style"), ).styleSheet.cssText = '_*{x-uCLp:expression(!this.hasOwnProperty("classList")&&window[" uCL"](this))}' + // IE6 '[class]{x-uCLp/**/:expression(!this.hasOwnProperty("classList")&&window[" uCL"](this))}'; //IE7-8 } })(window); // 3. Patch in unsupported methods in DOMTokenList (function (DOMTokenListProto, testClass) { if (!DOMTokenListProto.item) DOMTokenListProto.item = function (i) { function NullCheck(n) { return n === void 0 ? null : n; } return NullCheck(this[i]); }; if (!DOMTokenListProto.toggle || testClass.toggle("a", 0) !== false) DOMTokenListProto.toggle = function (val) { if (arguments.length > 1) return this[arguments[1] ? "add" : "remove"](val), !!arguments[1]; var oldValue = this.value; return ( this.remove(oldValue), oldValue === this.value && (this.add(val), true) /*|| false*/ ); }; if ( !DOMTokenListProto.replace || typeof testClass.replace("a", "b") !== "boolean" ) DOMTokenListProto.replace = function (oldToken, newToken) { checkIfValidClassListEntry("replace", oldToken), checkIfValidClassListEntry("replace", newToken); var oldValue = this.value; return ( this.remove(oldToken), this.value !== oldValue && (this.add(newToken), true) ); }; if (!DOMTokenListProto.contains) DOMTokenListProto.contains = function (value) { for (var i = 0, Len = this.length; i !== Len; ++i) if (this[i] === value) return true; return false; }; if (!DOMTokenListProto.forEach) DOMTokenListProto.forEach = function (f) { if (arguments.length === 1) for (var i = 0, Len = this.length; i !== Len; ++i) f(this[i], i, this); else for ( var i = 0, Len = this.length, tArg = arguments[1]; i !== Len; ++i ) f.call(tArg, this[i], i, this); }; if (!DOMTokenListProto.entries) DOMTokenListProto.entries = function () { var nextIndex = 0, that = this; return { next: function () { return nextIndex < that.length ? { value: [nextIndex, that[nextIndex++]], done: false } : { done: true }; }, }; }; if (!DOMTokenListProto.values) DOMTokenListProto.values = function () { var nextIndex = 0, that = this; return { next: function () { return nextIndex < that.length ? { value: that[nextIndex++], done: false } : { done: true }; }, }; }; if (!DOMTokenListProto.keys) DOMTokenListProto.keys = function () { var nextIndex = 0, that = this; return { next: function () { return nextIndex < that.length ? { value: nextIndex++, done: false } : { done: true }; }, }; }; })( window.DOMTokenList.prototype, window.document.createElement("div").classList, ); })(window);
manuel-hegner/conquery
frontend/src/js/authorization/AuthTokenProvider.tsx
import { createContext, useState } from "react"; import { isIDPEnabled } from "../environment"; import { getStoredAuthToken } from "./helper"; export interface AuthTokenContextValue { authToken: string; setAuthToken: (token: string) => void; } export const AuthTokenContext = createContext<AuthTokenContextValue>({ authToken: "", setAuthToken: () => null, }); export const useAuthTokenContextValue = (): AuthTokenContextValue => { const [authToken, setAuthToken] = useState<string>( isIDPEnabled ? "" : getStoredAuthToken() || "", ); return { authToken, setAuthToken }; }; export const AuthTokenContextProvider = AuthTokenContext.Provider;
manuel-hegner/conquery
frontend/src/js/query-node-editor/ContentColumn.tsx
<filename>frontend/src/js/query-node-editor/ContentColumn.tsx<gh_stars>10-100 import styled from "@emotion/styled"; import React, { FC, useEffect, useRef } from "react"; import { useTranslation } from "react-i18next"; import type { PostPrefixForSuggestionsParams } from "../api/api"; import { CurrencyConfigT, DatasetIdT, SelectOptionT, SelectorResultType, } from "../api/types"; import { Heading3 } from "../headings/Headings"; import { nodeIsConceptQueryNode } from "../model/node"; import { sortSelects, isSelectDisabled } from "../model/select"; import { ConceptQueryNodeType, StandardQueryNodeT, } from "../standard-query-editor/types"; import InputCheckbox from "../ui-components/InputCheckbox"; import InputMultiSelect from "../ui-components/InputMultiSelect"; import type { ModeT } from "../ui-components/InputRange"; import ContentCell from "./ContentCell"; import TableView from "./TableView"; const Column = styled("div")` width: 100%; display: flex; flex-direction: column; `; const Row = styled("div")` max-width: 300px; margin-bottom: 10px; `; const SectionHeading = styled(Heading3)` margin: 10px 10px 0; `; const CommonSettingsContainer = styled("div")` margin: 15px 10px; `; const ContentCellGroup = styled(ContentCell)` padding-bottom: 10px; margin-bottom: 10px; border-bottom: 1px solid ${({ theme }) => theme.col.grayLight}; &:last-of-type { border-bottom: none; padding-bottom: 0; margin-bottom: 0; } `; interface PropsT { node: StandardQueryNodeT; datasetId: DatasetIdT; currencyConfig: CurrencyConfigT; selectedTableIdx: number | null; blocklistedSelects?: SelectorResultType[]; allowlistedSelects?: SelectorResultType[]; onShowDescription: (filterIdx: number) => void; onSelectSelects: (value: SelectOptionT[]) => void; onSelectTableSelects: (tableIdx: number, value: SelectOptionT[]) => void; onToggleTimestamps?: () => void; onToggleSecondaryIdExclude?: () => void; onSetFilterValue: (tableIdx: number, filterIdx: number, value: any) => void; onSwitchFilterMode: ( tableIdx: number, filterIdx: number, mode: ModeT, ) => void; onLoadFilterSuggestions: ( params: PostPrefixForSuggestionsParams, tableIdx: number, filterIdx: number, ) => void; onSetDateColumn: (tableIdx: number, value: string | null) => void; } const ContentColumn: FC<PropsT> = ({ node, datasetId, currencyConfig, selectedTableIdx, blocklistedSelects, allowlistedSelects, onLoadFilterSuggestions, onSetDateColumn, onSetFilterValue, onSwitchFilterMode, onShowDescription, onSelectSelects, onSelectTableSelects, onToggleTimestamps, onToggleSecondaryIdExclude, }) => { const { t } = useTranslation(); const tables = nodeIsConceptQueryNode(node) ? node.tables : []; const itemsRef = useRef<(HTMLDivElement | null)[]>(new Array(tables.length)); useEffect(() => { if ( selectedTableIdx !== null && itemsRef.current && itemsRef.current[selectedTableIdx] ) { itemsRef.current[selectedTableIdx]?.scrollIntoView({ block: "start", inline: "start", behavior: "smooth", }); } }, [selectedTableIdx]); return ( <Column> <ContentCellGroup> <SectionHeading>{t("queryNodeEditor.properties")}</SectionHeading> <CommonSettingsContainer> {onToggleTimestamps && ( <Row> <InputCheckbox label={t("queryNodeEditor.excludeTimestamps")} tooltip={t("help.excludeTimestamps")} tooltipLazy input={{ value: node.excludeTimestamps, onChange: () => onToggleTimestamps(), }} /> </Row> )} {onToggleSecondaryIdExclude && ( <Row> <InputCheckbox label={t("queryNodeEditor.excludeFromSecondaryIdQuery")} tooltip={t("help.excludeFromSecondaryIdQuery")} tooltipLazy input={{ value: node.excludeFromSecondaryIdQuery, onChange: () => onToggleSecondaryIdExclude(), }} /> </Row> )} </CommonSettingsContainer> {nodeIsConceptQueryNode(node) && node.selects && ( <ContentCell headline={t("queryNodeEditor.commonSelects")}> <InputMultiSelect input={{ onChange: onSelectSelects, value: node.selects .filter(({ selected }) => !!selected) .map(({ id, label }) => ({ value: id, label: label })), }} options={sortSelects(node.selects).map((select) => ({ value: select.id, label: select.label, disabled: isSelectDisabled( select, blocklistedSelects, allowlistedSelects, ), }))} /> </ContentCell> )} </ContentCellGroup> {tables.map((table, idx) => { if (table.exclude) { return null; } return ( <ContentCellGroup key={table.id} ref={(instance) => (itemsRef.current[idx] = instance)} > <SectionHeading>{table.label}</SectionHeading> <TableView node={ node as ConceptQueryNodeType /* otherwise there won't be tables */ } datasetId={datasetId} currencyConfig={currencyConfig} tableIdx={idx} allowlistedSelects={allowlistedSelects} blocklistedSelects={blocklistedSelects} onShowDescription={onShowDescription} onSelectTableSelects={onSelectTableSelects} onSetDateColumn={onSetDateColumn} onSetFilterValue={onSetFilterValue} onSwitchFilterMode={onSwitchFilterMode} onLoadFilterSuggestions={onLoadFilterSuggestions} /> </ContentCellGroup> ); })} </Column> ); }; export default ContentColumn;
manuel-hegner/conquery
frontend/src/js/timebased-query-editor/helpers.ts
import type { TimebasedQueryStateT } from "./reducer"; export const allConditionsFilled = (timebasedQuery: TimebasedQueryStateT) => timebasedQuery.conditions.every( (condition) => !!condition.result0 && !!condition.result1, ); export const anyConditionFilled = (timebasedQuery: TimebasedQueryStateT) => timebasedQuery.conditions.some( (condition) => condition.result0 || condition.result1, );
manuel-hegner/conquery
frontend/src/js/query-node-editor/TableView.tsx
import styled from "@emotion/styled"; import React, { FC } from "react"; import { useTranslation } from "react-i18next"; import type { PostPrefixForSuggestionsParams } from "../api/api"; import type { CurrencyConfigT, DatasetIdT, SelectOptionT, SelectorResultType, } from "../api/types"; import type { ConceptQueryNodeType } from "../standard-query-editor/types"; import type { ModeT } from "../ui-components/InputRange"; import ContentCell from "./ContentCell"; import DateColumnSelect from "./DateColumnSelect"; import TableFilters from "./TableFilters"; import TableSelects from "./TableSelects"; const Column = styled("div")` display: flex; flex-direction: column; flex-grow: 1; `; const MaximizedCell = styled(ContentCell)` flex-grow: 1; `; interface PropsT { node: ConceptQueryNodeType; tableIdx: number; datasetId: DatasetIdT; currencyConfig: CurrencyConfigT; blocklistedSelects?: SelectorResultType[]; allowlistedSelects?: SelectorResultType[]; onShowDescription: (filterIdx: number) => void; onSelectTableSelects: (tableIdx: number, value: SelectOptionT[]) => void; onSetDateColumn: (tableIdx: number, dateColumnValue: string | null) => void; onSetFilterValue: (tableIdx: number, filterIdx: number, value: any) => void; onSwitchFilterMode: ( tableIdx: number, filterIdx: number, mode: ModeT, ) => void; onLoadFilterSuggestions: ( params: PostPrefixForSuggestionsParams, tableIdx: number, filterIdx: number, ) => void; } const TableView: FC<PropsT> = ({ node, tableIdx, onShowDescription, datasetId, currencyConfig, allowlistedSelects, blocklistedSelects, onSelectTableSelects, onSetDateColumn, onSetFilterValue, onSwitchFilterMode, onLoadFilterSuggestions, }) => { const { t } = useTranslation(); const table = node.tables[tableIdx]; const displaySelects = !!table.selects && table.selects.length > 0; const displayDateColumnOptions = !!table.dateColumn && table.dateColumn.options.length > 0; const displayFilters = !!table.filters && table.filters.length > 0; return ( <Column> {displaySelects && ( <ContentCell headline={t("queryNodeEditor.selects")}> {table.selects && table.selects.length > 0 && ( <TableSelects selects={table.selects} allowlistedSelects={allowlistedSelects} blocklistedSelects={blocklistedSelects} onSelectTableSelects={(value) => onSelectTableSelects(tableIdx, value) } excludeTable={table.exclude} /> )} </ContentCell> )} {displayDateColumnOptions && ( <ContentCell headline={t("queryNodeEditor.selectValidityDate")}> <DateColumnSelect dateColumn={table.dateColumn!} onSelectDateColumn={(value) => onSetDateColumn(tableIdx, value)} /> </ContentCell> )} {displayFilters && ( <MaximizedCell headline={t("queryNodeEditor.filters")}> <TableFilters key={tableIdx} filters={table.filters} excludeTable={table.exclude} context={{ datasetId, treeId: node.tree, tableId: table.id, }} onSetFilterValue={(filterIdx: number, value: unknown) => onSetFilterValue(tableIdx, filterIdx, value) } onSwitchFilterMode={(filterIdx, mode) => onSwitchFilterMode(tableIdx, filterIdx, mode) } onLoadFilterSuggestions={(filterIdx, filterId, prefix) => onLoadFilterSuggestions( { datasetId: datasetId, conceptId: node.tree, tableId: table.id, filterId, prefix, }, tableIdx, filterIdx, ) } onShowDescription={onShowDescription} currencyConfig={currencyConfig} /> </MaximizedCell> )} </Column> ); }; export default TableView;
manuel-hegner/conquery
frontend/src/js/ui-components/ReactSelect.tsx
<reponame>manuel-hegner/conquery import { Theme, useTheme } from "@emotion/react"; import React from "react"; import Select, { Props } from "react-select"; import Creatable, { Props as CreatableProps } from "react-select/creatable"; import type { SelectOptionT } from "../api/types"; // Helps to have a common ground for styling selects const stylesFromTheme = (theme: Theme, changed?: boolean) => ({ control: (provided: any, state: any) => { return { ...provided, minHeight: "30px", // makes it a little bit smaller in height than usual fontSize: theme.font.sm, borderRadius: "3px", boxShadow: "none", backgroundColor: "white", borderColor: changed && state.hasValue ? theme.col.blueGrayDark : "#aaa", ":hover": { borderColor: changed && state.hasValue ? theme.col.blueGrayDark : "#aaa", }, }; }, dropdownIndicator: (provided: any, state: any) => { return { ...provided, padding: "3px", }; }, option: (provided: any, state: any) => { return { ...provided, cursor: "pointer", fontSize: "14px", color: state.isSelected ? "white" : theme.col.black, fontWeight: state.isSelected ? 400 : 300, backgroundColor: state.isSelected ? theme.col.blueGrayDark : state.isFocused ? theme.col.blueGrayVeryLight : "white", ":active": { backgroundColor: theme.col.blueGrayLight, color: "white", }, }; }, multiValueRemove: (provided: any) => ({ ...provided, cursor: "pointer", ":hover": { backgroundColor: theme.col.gray, }, }), }); interface SelectPropsT<IsMulti extends boolean> extends Props<SelectOptionT, IsMulti> { highlightChanged?: boolean; } interface CreatablePropsT<IsMulti extends boolean> extends CreatableProps<SelectOptionT, IsMulti> { creatable: true; highlightChanged?: boolean; } type PropsT<IsMulti extends boolean> = | CreatablePropsT<IsMulti> | SelectPropsT<IsMulti>; const ReactSelect = <IsMulti extends boolean>({ creatable, highlightChanged, ...props }: PropsT<IsMulti>) => { const theme = useTheme(); const hasChanged = JSON.stringify(props.value) !== JSON.stringify(props.defaultValue); const changed = hasChanged && highlightChanged; const styles = stylesFromTheme(theme, changed); return creatable ? ( <Creatable styles={styles} {...props} /> ) : ( <Select styles={styles} {...props} /> ); }; export default ReactSelect;
manuel-hegner/conquery
frontend/src/js/standard-query-editor/SecondaryIdSelector.tsx
import styled from "@emotion/styled"; import { StateT } from "app-types"; import React, { FC, useEffect } from "react"; import { useTranslation } from "react-i18next"; import { useDispatch, useSelector } from "react-redux"; import { SecondaryId } from "../api/types"; import { exists } from "../common/helpers/exists"; import FaIcon from "../icon/FaIcon"; import ToggleButton from "../ui-components/ToggleButton"; import { setSelectedSecondaryId } from "./actions"; import type { StandardQueryStateT } from "./queryReducer"; import type { SelectedSecondaryIdStateT } from "./selectedSecondaryIdReducer"; const Headline = styled.h3<{ active?: boolean }>` font-size: ${({ theme }) => theme.font.sm}; margin: 0; text-transform: uppercase; transition: color ${({ theme }) => theme.transitionTime}; color: ${({ theme, active }) => active ? theme.col.blueGrayDark : theme.col.gray}; `; const SxFaIcon = styled(FaIcon)<{ active?: boolean }>` transition: color ${({ theme }) => theme.transitionTime}; color: ${({ theme, active }) => active ? theme.col.blueGrayDark : theme.col.gray}; `; const SecondaryIdSelector: FC = () => { const { t } = useTranslation(); const query = useSelector<StateT, StandardQueryStateT>( (state) => state.queryEditor.query, ); const selectedSecondaryId = useSelector<StateT, SelectedSecondaryIdStateT>( (state) => state.queryEditor.selectedSecondaryId, ); const loadedSecondaryIds = useSelector<StateT, SecondaryId[]>( (state) => state.conceptTrees.secondaryIds, ); const dispatch = useDispatch(); const onSetSelectedSecondaryId = (id: string | null) => { dispatch( setSelectedSecondaryId({ secondaryId: id === "standard" ? null : id }), ); }; const availableSecondaryIds = Array.from( new Set( query.flatMap((group) => group.elements.flatMap((el) => { if (el.isPreviousQuery) { return el.availableSecondaryIds || []; } else { return el.tables .filter((table) => !table.exclude) .flatMap((table) => table.supportedSecondaryIds) .filter(exists); } }), ), ), ) .map((id) => loadedSecondaryIds.find((secId) => secId.id === id)) .filter(exists); useEffect(() => { if ( !!selectedSecondaryId && (availableSecondaryIds.length === 0 || !availableSecondaryIds.map((id) => id.id).includes(selectedSecondaryId)) ) { onSetSelectedSecondaryId(null); } }, [JSON.stringify(availableSecondaryIds)]); const options = [ { value: "standard", label: t("queryEditor.secondaryIdStandard") as string, }, ...availableSecondaryIds.map((id) => ({ label: id.label, value: id.id, description: id.description, })), ]; if (options.length < 2) { return null; } return ( <div> <Headline active={!!selectedSecondaryId}> <SxFaIcon active={!!selectedSecondaryId} left icon="microscope" /> {t("queryEditor.secondaryId")} </Headline> <ToggleButton input={{ value: selectedSecondaryId || "standard", onChange: onSetSelectedSecondaryId, }} options={options} /> </div> ); }; export default SecondaryIdSelector;
manuel-hegner/conquery
frontend/src/js/standard-query-editor/selectedSecondaryIdReducer.ts
<gh_stars>10-100 import { getType } from "typesafe-actions"; import { Action } from "../app/actions"; import { setSelectedSecondaryId } from "./actions"; export type SelectedSecondaryIdStateT = string | null; const reducer = (state: SelectedSecondaryIdStateT = null, action: Action) => { switch (action.type) { case getType(setSelectedSecondaryId): return action.payload.secondaryId; default: return state; } }; export default reducer;
manuel-hegner/conquery
frontend/src/js/ui-components/AsyncInputMultiSelect.tsx
<reponame>manuel-hegner/conquery<filename>frontend/src/js/ui-components/AsyncInputMultiSelect.tsx import InputMultiSelect, { InputMultiSelectProps } from "./InputMultiSelect"; interface PropsType extends InputMultiSelectProps { startLoadingThreshold?: number; onLoad: (prefix: string) => void; } const AsyncInputMultiSelect = ({ startLoadingThreshold = 2, onLoad, ...props }: PropsType) => ( <InputMultiSelect {...props} onInputChange={(value) => { if (value.length >= startLoadingThreshold) onLoad(value); return value; }} /> ); export default AsyncInputMultiSelect;
manuel-hegner/conquery
frontend/src/js/preview/ColumnStats.tsx
import styled from "@emotion/styled"; import React, { FC } from "react"; import { useTranslation } from "react-i18next"; import { ColumnDescriptionType } from "./Preview"; const Stats = styled("div")` padding: 0 10px 10px 0; `; const Stat = styled("code")` display: block; margin: 0; `; const Name = styled("code")` display: block; font-weight: 700; font-size: ${({ theme }) => theme.font.xs}; max-width: 130px; margin-bottom: 8px; `; const Label = styled("span")` font-style: italic; padding-right: 10px; `; const Values = styled("div")` font-size: ${({ theme }) => theme.font.xs}; `; const Value = styled("span")` font-weight: 700; `; interface Props { colName: string; columnType: ColumnDescriptionType; rawColumnData: string[]; } // Might come in handy at some point // function getVarianceFromAvg(arr: number[], avg: number) { // const diffs = arr.map((val) => Math.abs(avg - val)); // const sumDiffs = diffs.reduce((a, b) => a + b, 0); // return sumDiffs / arr.length; // } function getStdDeviationFromAvg(arr: number[], avg: number) { const squareDiffs = arr.map((val) => { const diff = Math.abs(avg - val); return diff * diff; }); const sumSquareDiffs = squareDiffs.reduce((a, b) => a + b, 0); return Math.sqrt(sumSquareDiffs / arr.length); } function getMedian(sortedArr: number[]) { if (sortedArr.length === 0) return 0; const half = Math.floor(sortedArr.length / 2); return sortedArr.length % 2 === 1 ? sortedArr[half] : (sortedArr[half - 1] + sortedArr[half]) / 2.0; } function toRoundedDecimalsString(num: number, decimals: number) { const factor = Math.pow(10, decimals); const rounded = Math.round(num * factor) / factor; return rounded.toFixed(decimals).replace(".", ","); } function toLocalizedNumberString(num: number) { return num.toString().replace(".", ","); } const ColumnStats: FC<Props> = ({ colName, columnType, rawColumnData }) => { const { t } = useTranslation(); switch (columnType) { case "NUMERIC": case "MONEY": case "INTEGER": { const cleanSortedData = rawColumnData .slice(1) .map((x) => { if (!x) return 0; switch (columnType) { case "INTEGER": return parseInt(x); case "NUMERIC": case "MONEY": default: return parseFloat(x); } }) .sort((a, b) => a - b); const sum = cleanSortedData.reduce((a, b) => a + b, 0); const median = getMedian(cleanSortedData); const avg = sum / cleanSortedData.length; const min = cleanSortedData[0]; const max = cleanSortedData[cleanSortedData.length - 1]; const std = getStdDeviationFromAvg(cleanSortedData, avg); const decimals = 2; // Might come in handy at some point // const variance = getVarianceFromAvg(cleanSortedData, avg); const toMoneyMaybe = (num: number) => { return columnType === "MONEY" ? num / 100 : num; }; return ( <Stats> <Name>{colName}</Name> <Values> <Stat> <Label>{t("common.average")}:</Label> <Value> {toRoundedDecimalsString(toMoneyMaybe(avg), decimals)} </Value> </Stat> <Stat> <Label>{t("common.median")}:</Label> <Value>{toLocalizedNumberString(toMoneyMaybe(median))}</Value> </Stat> <Stat> <Label>{t("common.min")}:</Label> <Value>{toLocalizedNumberString(toMoneyMaybe(min))}</Value> </Stat> <Stat> <Label>{t("common.max")}:</Label> <Value>{toLocalizedNumberString(toMoneyMaybe(max))}</Value> </Stat> <Stat> <Label>{t("common.std")}:</Label> <Value> {toRoundedDecimalsString(toMoneyMaybe(std), decimals)} </Value> </Stat> </Values> </Stats> ); } default: return null; } }; export default ColumnStats;
manuel-hegner/conquery
frontend/src/js/query-runner/reducer.ts
import type { ColumnDescription, DatasetIdT, GetQueryResponseDoneT, } from "../api/types"; import { QUERY_RESULT_ERROR, QUERY_RESULT_RESET, QUERY_RESULT_RUNNING, QUERY_RESULT_START, QUERY_RESULT_SUCCESS, START_QUERY_ERROR, START_QUERY_START, START_QUERY_SUCCESS, STOP_QUERY_ERROR, STOP_QUERY_START, STOP_QUERY_SUCCESS, } from "./actionTypes"; import { QueryTypeT } from "./actions"; interface APICallType { loading?: boolean; success?: boolean; error?: string | boolean | null; errorContext?: Record<string, string>; } interface QueryResultT extends APICallType { datasetId?: string; resultCount?: number | null; resultUrls?: string[]; resultColumns?: ColumnDescription[] | null; queryType?: "CONCEPT_QUERY" | "SECONDARY_ID_QUERY"; } export interface QueryRunnerStateT { runningQuery: string | null; progress?: number; queryRunning: boolean; startQuery: APICallType; stopQuery: APICallType; queryResult: QueryResultT | null; } export default function createQueryRunnerReducer(type: QueryTypeT) { const initialState: QueryRunnerStateT = { runningQuery: null, queryRunning: false, startQuery: {}, stopQuery: {}, queryResult: null, }; const getQueryResult = ( data: GetQueryResponseDoneT, datasetId: DatasetIdT, ) => { return { datasetId, loading: false, success: true, error: null, resultCount: data.numberOfResults, resultUrls: data.resultUrls, resultColumns: data.columnDescriptions, queryType: data.queryType, }; }; return ( state: QueryRunnerStateT = initialState, action: Object, ): QueryRunnerStateT => { if (!action.payload || action.payload.queryType !== type) { return state; } switch (action.type) { // To start a query case START_QUERY_START: return { ...state, stopQuery: {}, startQuery: { loading: true }, queryResult: null, }; case START_QUERY_SUCCESS: return { ...state, runningQuery: action.payload.data.id, queryRunning: true, stopQuery: {}, startQuery: { success: true }, }; case START_QUERY_ERROR: return { ...state, stopQuery: {}, startQuery: { error: action.payload.message || action.payload.status, }, }; // To cancel a query case STOP_QUERY_START: return { ...state, startQuery: {}, stopQuery: { loading: true } }; case STOP_QUERY_SUCCESS: return { ...state, runningQuery: null, progress: undefined, queryRunning: false, startQuery: {}, stopQuery: { success: true }, }; case STOP_QUERY_ERROR: return { ...state, startQuery: {}, stopQuery: { error: action.payload.message || action.payload.status }, }; // To check for query results case QUERY_RESULT_START: return { ...state, queryResult: { loading: true } }; case QUERY_RESULT_RUNNING: return { ...state, progress: action.payload.progress }; case QUERY_RESULT_RESET: return { ...state, queryResult: { loading: false } }; case QUERY_RESULT_SUCCESS: const queryResult = getQueryResult( action.payload.data, action.payload.datasetId, ); return { ...state, queryResult, runningQuery: null, progress: undefined, queryRunning: false, }; case QUERY_RESULT_ERROR: const { payload } = action; return { ...state, runningQuery: null, progress: undefined, queryRunning: false, queryResult: { loading: false, error: payload.error, }, }; default: return state; } }; }
manuel-hegner/conquery
frontend/src/js/query-runner/QueryRunningSpinner.tsx
import { keyframes } from "@emotion/react"; import styled from "@emotion/styled"; const spin = keyframes` 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } `; export const QueryRunningSpinner = styled("div")` height: 30px; width: 30px; background-image: url("${({ theme }) => theme.img.spinner}"); background-repeat: no-repeat; background-size: 30px; animation: ${spin} 1s linear 0s infinite; `;
manuel-hegner/conquery
frontend/src/js/environment/index.ts
<reponame>manuel-hegner/conquery import { TFunction } from "react-i18next"; // See index.html for an inject marker, that we use to inject env vars // at caontainer runtime function runtimeVar(variable: string): string | null { return window.env && window.env[variable] !== "null" ? window.env[variable] : null; } // Needs to be explicit because weback statically replaces process.env.XXX through DefinePlugin const isProductionEnv = runtimeVar("NODE_ENV") || process.env.NODE_ENV; const languageEnv = runtimeVar("REACT_APP_LANG") || process.env.REACT_APP_LANG; const apiUrlEnv = runtimeVar("REACT_APP_API_URL") || process.env.REACT_APP_API_URL; const disableLoginEnv = runtimeVar("REACT_APP_DISABLE_LOGIN") || process.env.REACT_APP_DISABLE_LOGIN; const enableIDPEnv = runtimeVar("REACT_APP_IDP_ENABLE") || process.env.REACT_APP_IDP_ENABLE; const basenameEnv = runtimeVar("REACT_APP_BASENAME") || process.env.REACT_APP_BASENAME; const idpUrlEnv = runtimeVar("REACT_APP_IDP_URL") || process.env.REACT_APP_IDP_URL; const idpRealmEnv = runtimeVar("REACT_APP_IDP_REALM") || process.env.REACT_APP_IDP_REALM; const idpClientIdEnv = runtimeVar("REACT_APP_IDP_CLIENT_ID") || process.env.REACT_APP_IDP_CLIENT_ID; export const isProduction = isProductionEnv === "production" || true; export const language = languageEnv === "de" ? "de" : "en"; export const apiUrl = apiUrlEnv || ""; export const isLoginDisabled = disableLoginEnv === "true"; export const isIDPEnabled = enableIDPEnv === "true"; export const basename = basenameEnv || ""; export const idpUrl = idpUrlEnv || ""; export const idpRealm = idpRealmEnv || ""; export const idpClientId = idpClientIdEnv || ""; export interface CustomEnvironment { getExternalSupportedErrorMessage?: ( t: TFunction, code: string, context?: Record<string, string>, ) => string | undefined; } let customEnvironment: CustomEnvironment | null = null; export const initializeEnvironment = (env: CustomEnvironment) => { customEnvironment = env; }; export const getExternalSupportedErrorMessage = ( t: TFunction, code: string, context?: Record<string, string>, ) => customEnvironment && customEnvironment.getExternalSupportedErrorMessage ? customEnvironment.getExternalSupportedErrorMessage(t, code, context) : undefined;
manuel-hegner/conquery
frontend/src/js/snack-message/actions.ts
import { ActionType, createAction } from "typesafe-actions"; export type SnackMessageActions = ActionType< typeof setMessage | typeof resetMessage >; export const setMessage = createAction("snack-message/SET")<{ message: string | null; }>(); export const resetMessage = createAction("snack-message/RESET")();
manuel-hegner/conquery
frontend/src/js/external-forms/validators.ts
import { TFunction } from "react-i18next"; import { isEmpty } from "../common/helpers"; export const validateRequired = (t: TFunction, value: any): string | null => { return isEmpty(value) ? t("externalForms.formValidation.isRequired") : null; }; export const validatePositive = (t: TFunction, value: any) => { return isEmpty(value) || value > 0 ? null : t("externalForms.formValidation.mustBePositiveNumber"); }; export const validateDateRange = ( t: TFunction, value: { min: string; max: string }, ) => { // May be empty if (!value || (!value.min && !value.max)) return null; // But if not, must be set fully and correctly if (!value.min || !value.max) return t("externalForms.formValidation.isRequired"); if (value.max < value.min) return t("externalForms.formValidation.invalidDateRange"); return null; }; export const validateDateRangeRequired = ( t: TFunction, value: { min: string; max: string; } | null, ): string | null => { if (!value || !value.min || !value.max) return t("externalForms.formValidation.isRequired"); return validateDateRange(t, value); }; export const validateConceptGroupFilled = ( t: TFunction, group: { concepts: [] }[], ): string | null => { if (!group || group.length === 0) return t("externalForms.formValidation.isRequired"); return group.some( (e) => e.concepts.length === 0 || e.concepts.some((c) => !c), ) ? t("externalForms.formValidation.isRequired") : null; };
manuel-hegner/conquery
frontend/src/js/query-upload-concept-list-modal/reducer.ts
import { getType } from "typesafe-actions"; import { Action } from "../app/actions"; import { closeQueryUploadConceptListModal, openQueryUploadConceptListModal, } from "./actions"; export interface QueryUploadConceptListModalStateT { isOpen: boolean; andIdx: number | null; } const initialState: QueryUploadConceptListModalStateT = { isOpen: false, andIdx: null, }; const reducer = ( state = initialState, action: Action, ): QueryUploadConceptListModalStateT => { switch (action.type) { case getType(openQueryUploadConceptListModal): const { andIdx } = action.payload; return { andIdx, isOpen: true }; case getType(closeQueryUploadConceptListModal): return initialState; default: return state; } }; export default reducer;
manuel-hegner/conquery
frontend/src/js/tags/Tag.tsx
<reponame>manuel-hegner/conquery<gh_stars>10-100 import { css } from "@emotion/react"; import styled from "@emotion/styled"; import React, { FC } from "react"; const Root = styled("p")<{ isClickable?: boolean; isSelected?: boolean }>` display: inline-block; padding: 4px 4px; margin: 0 3px 3px 0; font-size: ${({ theme }) => theme.font.xs}; line-height: ${({ theme }) => theme.font.xs}; border-radius: ${({ theme }) => theme.borderRadius}; border: 1px solid ${({ theme }) => theme.col.grayMediumLight}; white-space: nowrap; ${({ isClickable, theme, isSelected }) => isClickable && css` cursor: pointer; ${!isSelected && css` &:hover { border-color: ${theme.col.gray}; } `} `}; ${({ isSelected, theme }) => isSelected && css` background-color: ${theme.col.blueGrayLight}; color: white; font-weight: 700; border-color: ${theme.col.blueGrayLight}; `}; `; interface Props { className?: string; isSelected: boolean; onClick: () => void; } const Tag: FC<Props> = ({ children, className, onClick, isSelected }) => { return ( <Root className={className} isClickable={!!onClick} isSelected={!!isSelected} onClick={onClick} > {children} </Root> ); }; export default Tag;
manuel-hegner/conquery
frontend/src/js/concept-trees/ConceptTreeList.tsx
import styled from "@emotion/styled"; import React, { FC } from "react"; import { useSelector } from "react-redux"; import type { DatasetIdT } from "../api/types"; import type { StateT } from "../app/reducers"; import ConceptTreeListItem from "./ConceptTreeListItem"; import ConceptTreesLoading from "./ConceptTreesLoading"; import EmptyConceptTreeList from "./EmptyConceptTreeList"; import ProgressBar from "./ProgressBar"; import { useLoadTree } from "./actions"; import type { TreesT, SearchT } from "./reducer"; import { getAreTreesAvailable } from "./selectors"; import { useRootConceptIds } from "./useRootConceptIds"; const Root = styled("div")<{ show?: boolean }>` flex-grow: 1; flex-shrink: 0; flex-basis: 0; overflow-y: auto; -webkit-overflow-scrolling: touch; padding: 0 10px 0; white-space: nowrap; ${ "" // Only hide the Concept trees when the tab is not selected // Because mount / unmount would reset the open states // that are React states and not part of the Redux state // because if they were part of Redux state, the entire tree // would have to re-render when a single node would be opened // // Also: Can't set it to initial, because IE11 doesn't work then // => Empty string instead } display: ${({ show }) => (show ? "" : "none")}; `; interface PropsT { datasetId: DatasetIdT | null; } const ConceptTreeList: FC<PropsT> = ({ datasetId }) => { const trees = useSelector<StateT, TreesT>( (state) => state.conceptTrees.trees, ); const loading = useSelector<StateT, boolean>( (state) => state.conceptTrees.loading, ); const areTreesAvailable = useSelector<StateT, boolean>((state) => getAreTreesAvailable(state), ); const areDatasetsPristineOrLoading = useSelector<StateT, boolean>( (state) => state.datasets.pristine || state.datasets.loading, ); const activeTab = useSelector<StateT, string>( (state) => state.panes.left.activeTab, ); const search = useSelector<StateT, SearchT>( (state) => state.conceptTrees.search, ); const loadTree = useLoadTree(); const onLoadTree = (id: string) => { if (datasetId) { loadTree(datasetId, id); } }; const rootConceptIds = useRootConceptIds(); if (search.loading) return null; const anyTreeLoading = Object.keys(trees).some( (treeId) => trees[treeId].loading, ); return ( <Root show={activeTab === "conceptTrees"}> {loading && <ConceptTreesLoading />} {!loading && !areTreesAvailable && !areDatasetsPristineOrLoading && ( <EmptyConceptTreeList /> )} {!!anyTreeLoading && <ProgressBar trees={trees} />} {!anyTreeLoading && rootConceptIds.map((treeId, i) => ( <ConceptTreeListItem key={i} search={search} onLoadTree={onLoadTree} trees={trees} treeId={treeId} /> ))} </Root> ); }; export default ConceptTreeList;
manuel-hegner/conquery
frontend/src/js/tooltip/actions.ts
import { ActionType, createAction } from "typesafe-actions"; import type { AdditionalInfosType } from "./reducer"; export type TooltipActions = ActionType< | typeof displayAdditionalInfos | typeof toggleAdditionalInfos | typeof toggleDisplayTooltip >; export const displayAdditionalInfos = createAction( "tooltip/DISPLAY_ADDITIONAL_INFOS", )<{ additionalInfos: AdditionalInfosType }>(); export const toggleAdditionalInfos = createAction( "tooltip/TOGGLE_ADDITIONAL_INFOS", )(); export const toggleDisplayTooltip = createAction( "tooltip/TOGGLE_DISPLAY_TOOLTIP", )();
manuel-hegner/conquery
frontend/src/js/upload-concept-list-modal/UploadConceptListModal.tsx
import styled from "@emotion/styled"; import type { StateT } from "app-types"; import React, { useState, useEffect } from "react"; import { useTranslation } from "react-i18next"; import { useSelector } from "react-redux"; import type { ConceptIdT, ConceptT } from "../api/types"; import PrimaryButton from "../button/PrimaryButton"; import type { TreesT } from "../concept-trees/reducer"; import FaIcon from "../icon/FaIcon"; import Modal from "../modal/Modal"; import ScrollableList from "../scrollable-list/ScrollableList"; import InputPlain from "../ui-components/InputPlain"; import InputSelect from "../ui-components/InputSelect"; import { useSelectConceptRootNodeAndResolveCodes } from "./actions"; import { UploadConceptListModalStateT } from "./reducer"; const Root = styled("div")` padding: 0 0 10px; `; const Section = styled("div")` margin-top: 15px; padding: 15px; box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.1); display: grid; grid-gap: 20px; `; const Msg = styled("p")` margin: 0; `; const MsgRow = styled("div")` display: flex; align-items: flex-end; `; const BigIcon = styled(FaIcon)` font-size: 20px; margin-right: 10px; `; const ErrorIcon = styled(BigIcon)` color: ${({ theme }) => theme.col.red}; `; const SuccessIcon = styled(BigIcon)` color: ${({ theme }) => theme.col.green}; `; const CenteredIcon = styled(FaIcon)` text-align: center; `; const SxPrimaryButton = styled(PrimaryButton)` margin-left: 15px; flex-shrink: 0; `; const selectUnresolvedItemsCount = (state: StateT) => { const { resolved } = state.uploadConceptListModal; return resolved && resolved.unknownCodes && resolved.unknownCodes.length ? resolved.unknownCodes.length : 0; }; const selectResolvedItemsCount = (state: StateT) => { const { resolved } = state.uploadConceptListModal; return resolved && resolved.resolvedConcepts && resolved.resolvedConcepts.length ? resolved.resolvedConcepts.length : 0; }; const selectAvailableConceptRootNodes = (state: StateT) => { const { trees } = state.conceptTrees; if (!trees) return []; return Object.entries(trees) .map(([key, value]) => ({ key, value })) .filter(({ value }) => value.codeListResolvable) .sort((a, b) => a.value.label.toLowerCase().localeCompare(b.value.label.toLowerCase()), ); }; interface PropsT { onAccept: ( label: string, rootConcepts: TreesT, resolvedConcepts: ConceptIdT[], ) => void; onClose: () => void; } interface ConceptRootNodeByKey { key: string; value: ConceptT; } const UploadConceptListModal = ({ onAccept, onClose }: PropsT) => { const { t } = useTranslation(); const { filename, conceptCodesFromFile, selectedConceptRootNode, loading, resolved, error, } = useSelector<StateT, UploadConceptListModalStateT>( (state) => state.uploadConceptListModal, ); const availableConceptRootNodes = useSelector<StateT, ConceptRootNodeByKey[]>( (state) => selectAvailableConceptRootNodes(state), ); const rootConcepts = useSelector<StateT, TreesT>( (state) => state.conceptTrees.trees, ); const resolvedItemsCount = useSelector<StateT, number>((state) => selectResolvedItemsCount(state), ); const unresolvedItemsCount = useSelector<StateT, number>((state) => selectUnresolvedItemsCount(state), ); const [label, setLabel] = useState<string>(filename || ""); useEffect(() => { if (filename) { setLabel(filename); } }, [filename]); const selectConceptRootNodeAndResolveCode = useSelectConceptRootNodeAndResolveCodes(); if (!conceptCodesFromFile || conceptCodesFromFile.length === 0) { onClose(); } const hasUnresolvedItems = unresolvedItemsCount > 0; const hasResolvedItems = resolvedItemsCount > 0; const onSubmit = (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); if (label && resolved.resolvedConcepts) { onAccept(label, rootConcepts, resolved.resolvedConcepts); } onClose(); }; return ( <Modal closeIcon onClose={onClose} headline={t("uploadConceptListModal.headline")} > <Root> <InputSelect label={t("uploadConceptListModal.selectConceptRootNode")} input={{ value: selectedConceptRootNode, onChange: (value) => selectConceptRootNodeAndResolveCode(value, conceptCodesFromFile), }} options={availableConceptRootNodes.map((x) => ({ value: x.key, label: x.value.label, }))} selectProps={{ isSearchable: true, autoFocus: true, }} /> {!!resolved && !hasResolvedItems && !hasUnresolvedItems && ( <Section> <Msg>{t("uploadConceptListModal.nothingResolved")}</Msg> </Section> )} {(!!error || !!loading || (!!resolved && (hasResolvedItems || hasUnresolvedItems))) && ( <Section> {error && ( <p> <ErrorIcon icon="exclamation-circle" /> {t("uploadConceptListModal.error")} </p> )} {loading && <CenteredIcon icon="spinner" />} {resolved && ( <> {hasResolvedItems && ( <form onSubmit={onSubmit}> <Msg> <SuccessIcon icon="check-circle" /> {t("uploadConceptListModal.resolvedCodes", { count: resolvedItemsCount, })} </Msg> <MsgRow> <InputPlain label={t("uploadConceptListModal.label")} fullWidth inputProps={{ autoFocus: true, }} input={{ value: label, onChange: setLabel, }} /> <SxPrimaryButton type="submit"> {t("uploadConceptListModal.insertNode")} </SxPrimaryButton> </MsgRow> </form> )} {hasUnresolvedItems && ( <div> <Msg> <ErrorIcon icon="exclamation-circle" /> <span> {t("uploadConceptListModal.unknownCodes", { count: unresolvedItemsCount, })} </span> </Msg> <ScrollableList maxVisibleItems={3} fullWidth items={resolved.unknownCodes || []} /> </div> )} </> )} </Section> )} </Root> </Modal> ); }; export default UploadConceptListModal;
manuel-hegner/conquery
frontend/src/js/query-runner/actions.ts
import { TFunction, useTranslation } from "react-i18next"; import { useDispatch } from "react-redux"; import { useGetQuery, usePostFormQueries, usePostQueries, usePostQueryCancel, } from "../api/api"; import type { DatasetIdT, ErrorResponseT, GetQueryErrorResponseT, GetQueryResponseDoneT, QueryIdT, } from "../api/types"; import { defaultError, defaultSuccess, ErrorObject } from "../common/actions"; import { getExternalSupportedErrorMessage } from "../environment"; import { useLoadQueries } from "../previous-queries/list/actions"; import { StandardQueryStateT } from "../standard-query-editor/queryReducer"; import { TimebasedQueryStateT } from "../timebased-query-editor/reducer"; import { START_QUERY_START, START_QUERY_SUCCESS, START_QUERY_ERROR, STOP_QUERY_SUCCESS, STOP_QUERY_ERROR, STOP_QUERY_START, QUERY_RESULT_START, QUERY_RESULT_RESET, QUERY_RESULT_RUNNING, QUERY_RESULT_ERROR, QUERY_RESULT_SUCCESS, } from "./actionTypes"; import { QUERY_AGAIN_TIMEOUT } from "./constants"; /* This implements a polling mechanism, because queries are running sometimes longer than 10s. (we're using "long polling", where the backend delays the response) The polling works like: - Start the query (POST request) - From the response, get an ID when query was successfully started - Continuously poll (GET request) for the query results using that ID - Stop polling once the status is DONE, CANCELED or FAILED Also, there's a possibility to stop a query while it's running, by sending a DELETE request for that query ID */ export type QueryTypeT = "standard" | "timebased" | "externalForms"; const startQueryStart = (queryType: QueryTypeT) => ({ type: START_QUERY_START, payload: { queryType }, }); const startQueryError = (queryType: QueryTypeT, err: ErrorObject) => defaultError(START_QUERY_ERROR, err, { queryType }); const startQuerySuccess = (queryType: QueryTypeT, res: any) => defaultSuccess(START_QUERY_SUCCESS, res, { queryType }); export const useStartQuery = (queryType: QueryTypeT) => { const dispatch = useDispatch(); const queryResult = useQueryResult(queryType); const postQueries = usePostQueries(); const postFormQueries = usePostFormQueries(); return ( datasetId: DatasetIdT, query: StandardQueryStateT | TimebasedQueryStateT, { formQueryTransformation, selectedSecondaryId, }: { formQueryTransformation?: Function; selectedSecondaryId?: string | null; } = {}, ) => { dispatch(startQueryStart(queryType)); const apiMethod = formQueryTransformation ? () => postFormQueries(datasetId, query, { formQueryTransformation }) : () => postQueries(datasetId, query, { queryType, selectedSecondaryId, }); return apiMethod().then( (r) => { dispatch(startQuerySuccess(queryType, r)); const queryId = r.id; return queryResult(datasetId, queryId); }, (e) => dispatch(startQueryError(queryType, e)), ); }; }; const stopQueryStart = (queryType: QueryTypeT) => ({ type: STOP_QUERY_START, payload: { queryType }, }); const stopQueryError = (queryType: QueryTypeT, err: ErrorObject) => defaultError(STOP_QUERY_ERROR, err, { queryType }); const stopQuerySuccess = (queryType: QueryTypeT, res: any) => defaultSuccess(STOP_QUERY_SUCCESS, res, { queryType }); export const useStopQuery = (queryType: QueryTypeT) => { const dispatch = useDispatch(); const cancelQuery = usePostQueryCancel(); return (datasetId: DatasetIdT, queryId: QueryIdT) => { dispatch(stopQueryStart(queryType)); return cancelQuery(datasetId, queryId).then( (r) => dispatch(stopQuerySuccess(queryType, r)), (e) => dispatch(stopQueryError(queryType, e)), ); }; }; const queryResultStart = (queryType: QueryTypeT) => ({ type: QUERY_RESULT_START, payload: { queryType }, }); export const queryResultReset = (queryType: QueryTypeT) => ({ type: QUERY_RESULT_RESET, payload: { queryType }, }); export const queryResultRunning = ( queryType: QueryTypeT, progress?: number, ) => ({ type: QUERY_RESULT_RUNNING, payload: { queryType, progress }, }); const getQueryErrorMessage = ({ t, status, error, }: { t: TFunction; status: "CANCELED" | "FAILED"; error: ErrorResponseT | null; }): string => { if (status === "CANCELED") { return t("queryRunner.queryCanceled"); } return ( (error && error.code && getExternalSupportedErrorMessage(t, error.code, error.context)) || t("queryRunner.queryFailed") ); }; const queryResultError = ( t: TFunction, queryType: QueryTypeT, e: GetQueryErrorResponseT | Error, ) => { if (e instanceof Error) return defaultError(QUERY_RESULT_ERROR, e, { queryType }); // TODO: Refactor and get rid of defaultError, it's too generic return defaultError(QUERY_RESULT_ERROR, e, { error: getQueryErrorMessage({ t, status: e.status, error: e.error }), queryType, }); }; const queryResultSuccess = ( queryType: QueryTypeT, res: GetQueryResponseDoneT, datasetId: DatasetIdT, ) => defaultSuccess(QUERY_RESULT_SUCCESS, res, { datasetId, queryType }); const useQueryResult = (queryType: QueryTypeT) => { const { t } = useTranslation(); const dispatch = useDispatch(); const getQuery = useGetQuery(); const loadQueries = useLoadQueries(); const queryResult = (datasetId: DatasetIdT, queryId: QueryIdT) => { dispatch(queryResultStart(queryType)); return getQuery(datasetId, queryId).then( (r) => { // Indicate that looking for the result has stopped, // but not necessarily succeeded dispatch(queryResultReset(queryType)); switch (r.status) { case "DONE": dispatch(queryResultSuccess(queryType, r, datasetId)); // Now there should be a new result that can be queried loadQueries(datasetId); break; case "FAILED": dispatch(queryResultError(t, queryType, r)); break; case "RUNNING": dispatch(queryResultRunning(queryType, r.progress)); // Try again after a short time: // Use the "long polling" strategy, where we assume that the // backend blocks the request for a couple of seconds and waits // for the query comes back. // If it doesn't come back the request resolves and // we - the frontend - try again almost instantly. setTimeout( () => queryResult(datasetId, queryId), QUERY_AGAIN_TIMEOUT, ); break; case "NEW": default: break; } }, (e: Error) => dispatch(queryResultError(t, queryType, e)), ); }; return queryResult; };
manuel-hegner/conquery
frontend/src/js/query-node-editor/TableFilters.tsx
<reponame>manuel-hegner/conquery import styled from "@emotion/styled"; import React from "react"; import type { CurrencyConfigT, DatasetIdT, ConceptIdT, TableIdT, FilterIdT, } from "../api/types"; import type { FilterWithValueType } from "../standard-query-editor/types"; import InputPlain from "../ui-components/InputPlain"; import InputRange, { ModeT } from "../ui-components/InputRange"; import InputSelect from "../ui-components/InputSelect"; import FilterListMultiSelect from "./FilterListMultiSelect"; export interface FiltersContextT { datasetId: DatasetIdT; treeId: ConceptIdT; tableId: TableIdT; } interface PropsT { className?: string; context: FiltersContextT; filters: FilterWithValueType[] | null; excludeTable?: boolean; onSwitchFilterMode: (filterIdx: number, mode: ModeT) => void; onSetFilterValue: Function; onLoadFilterSuggestions: ( tableIdx: number, filterId: FilterIdT, prefix: string, ) => void; onShowDescription: (filterIdx: number) => void; currencyConfig: CurrencyConfigT; } const Row = styled("div")` margin-bottom: 10px; `; const TableFilters = (props: PropsT) => { if (!props.filters || props.filters.length === 0) return null; return ( <div> {props.filters .map((filter, filterIdx) => { switch (filter.type) { case "SELECT": return ( <InputSelect indexPrefix={filterIdx + 1} input={{ clearable: filter.value !== filter.defaultValue, defaultValue: filter.defaultValue, value: filter.value, onChange: (value) => props.onSetFilterValue(filterIdx, value), }} label={filter.label} options={filter.options} disabled={props.excludeTable} /> ); case "MULTI_SELECT": return ( <FilterListMultiSelect context={{ ...props.context, filterId: filter.id }} indexPrefix={filterIdx + 1} input={{ value: filter.value, defaultValue: filter.defaultValue, onChange: (value: string[]) => props.onSetFilterValue(filterIdx, value), }} label={filter.label} options={filter.options} disabled={props.excludeTable} allowDropFile={!!filter.allowDropFile} /> ); case "BIG_MULTI_SELECT": return ( <FilterListMultiSelect indexPrefix={filterIdx + 1} context={{ ...props.context, filterId: filter.id }} input={{ value: filter.value || [], defaultValue: filter.defaultValue || [], onChange: (value) => props.onSetFilterValue(filterIdx, value), }} label={filter.label} options={filter.options} disabled={!!props.excludeTable} allowDropFile={!!filter.allowDropFile} isLoading={filter.isLoading} onLoad={(prefix: string) => props.onLoadFilterSuggestions(filterIdx, filter.id, prefix) } /> ); case "INTEGER_RANGE": return ( <InputRange indexPrefix={filterIdx + 1} input={{ value: filter.value, defaultValue: filter.defaultValue, onChange: (value) => props.onSetFilterValue(filterIdx, value), }} limits={{ min: filter.min, max: filter.max }} unit={filter.unit} label={filter.label} mode={filter.mode || "range"} disabled={!!props.excludeTable} onSwitchMode={(mode) => props.onSwitchFilterMode(filterIdx, mode) } placeholder="-" pattern={filter.pattern} /> ); case "REAL_RANGE": return ( <InputRange indexPrefix={filterIdx + 1} input={{ value: filter.value, defaultValue: filter.defaultValue, onChange: (value) => props.onSetFilterValue(filterIdx, value), }} limits={{ min: filter.min, max: filter.max }} unit={filter.unit} label={filter.label} mode={filter.mode || "range"} stepSize={filter.precision || 0.1} disabled={!!props.excludeTable} onSwitchMode={(mode) => props.onSwitchFilterMode(filterIdx, mode) } placeholder="-" pattern={filter.pattern} /> ); case "MONEY_RANGE": return ( <InputRange indexPrefix={filterIdx + 1} moneyRange input={{ value: filter.value, defaultValue: filter.defaultValue, onChange: (value) => props.onSetFilterValue(filterIdx, value), }} unit={filter.unit} label={filter.label} mode={filter.mode || "range"} disabled={!!props.excludeTable} onSwitchMode={(mode) => props.onSwitchFilterMode(filterIdx, mode) } placeholder="-" currencyConfig={props.currencyConfig} /> ); case "STRING": return ( <InputPlain indexPrefix={filterIdx + 1} input={{ value: filter.value || "", defaultValue: filter.defaultValue, onChange: (value) => props.onSetFilterValue(filterIdx, value), }} placeholder="-" label={filter.label} /> ); default: // In the future, there might be other filter types supported return null; } }) .filter((input) => !!input) .map((input, filterIdx) => ( <Row key={filterIdx} onFocusCapture={() => props.onShowDescription(filterIdx)} > {input} </Row> ))} </div> ); }; export default TableFilters;
manuel-hegner/conquery
frontend/src/js/external-forms/transformers.ts
<reponame>manuel-hegner/conquery import type { SelectorT } from "../api/types"; import { tableIsDisabled } from "../model/table"; import type { ConceptQueryNodeType, TableWithFilterValueT, } from "../standard-query-editor/types"; import type { ConnectorDefault as ConnectorDefaultType } from "./config-types"; function setDefaultSelects(selects: SelectorT[], defaultSelects: string[]) { return selects.map((select) => ({ ...select, selected: defaultSelects.some( (s) => select.id.toLowerCase().indexOf(s.toLowerCase()) !== -1, ), })); } export const initTables = ({ blocklistedTables, allowlistedTables, }: { blocklistedTables?: string[]; allowlistedTables?: string[]; }) => (node: ConceptQueryNodeType) => { return !node.tables ? node : { ...node, tables: node.tables.map((table) => { const isDisabled = tableIsDisabled( table, blocklistedTables, allowlistedTables, ); return isDisabled ? { ...table, exclude: true } : table; }), }; }; export const initTablesWithDefaults = ( connectorDefaults?: ConnectorDefaultType[], ) => (node: ConceptQueryNodeType) => { return !node.tables ? node : { ...node, tables: node.tables.map((table) => { if (!table.selects || !connectorDefaults) return table; const connectorDefault = connectorDefaults.find( (c) => table.id.toLowerCase().indexOf(c.name.toLowerCase()) !== -1, ); if (!connectorDefault) return table; return initSelectsWithDefaults(connectorDefault.selects)(table); }), }; }; export const initSelectsWithDefaults = (defaultSelects: string[]) => ( node: ConceptQueryNodeType | TableWithFilterValueT, ) => { return !node.selects || !defaultSelects ? node : { ...node, selects: setDefaultSelects(node.selects, defaultSelects), }; };
manuel-hegner/conquery
frontend/src/js/external-forms/form-configs/DeleteFormConfigModal.tsx
import { StateT } from "app-types"; import React from "react"; import { useTranslation } from "react-i18next"; import { useDispatch, useSelector } from "react-redux"; import { useDeleteFormConfig } from "../../api/api"; import type { DatasetIdT } from "../../api/types"; import DeleteModal from "../../modal/DeleteModal"; import { setMessage } from "../../snack-message/actions"; interface PropsType { formConfigId: string; onClose: () => void; onDeleteSuccess: () => void; } const DeleteFormConfigModal = ({ formConfigId, onClose, onDeleteSuccess, }: PropsType) => { const { t } = useTranslation(); const datasetId = useSelector<StateT, DatasetIdT | null>( (state) => state.datasets.selectedDatasetId, ); const dispatch = useDispatch(); const deleteFormConfig = useDeleteFormConfig(); async function onDeleteFormConfig() { if (!datasetId) return; try { await deleteFormConfig(datasetId, formConfigId); onDeleteSuccess(); } catch (e) { dispatch(setMessage({ message: t("formConfig.deleteError") })); } } return ( <DeleteModal onClose={onClose} headline={t("deleteFormConfigModal.areYouSure")} onDelete={onDeleteFormConfig} /> ); }; export default DeleteFormConfigModal;
manuel-hegner/conquery
frontend/src/js/ui-components/InputMultiSelect/ListOption.tsx
import { css } from "@emotion/react"; import styled from "@emotion/styled"; import { forwardRef } from "react"; const Container = styled("div")<{ active?: boolean }>` padding: 3px 8px; cursor: pointer; color: ${({ theme }) => theme.col.black}; transition: background-color ${({ theme }) => theme.transitionTime}; ${({ active, theme }) => active && css` background-color: ${theme.col.blueGrayVeryLight}; `}; `; const ListOption = forwardRef<HTMLDivElement, { active?: boolean }>( (props, ref) => { return <Container {...props} ref={ref} />; }, ); export default ListOption;
manuel-hegner/conquery
frontend/src/js/ui-components/InputMultiSelect.tsx
import { css } from "@emotion/react"; import styled from "@emotion/styled"; import Mustache from "mustache"; import React, { FC } from "react"; import { useTranslation } from "react-i18next"; import Markdown from "react-markdown"; import { components, MenuListComponentProps } from "react-select"; import type { FilterSuggestion, SelectOptionT } from "../api/types"; import TransparentButton from "../button/TransparentButton"; import { exists } from "../common/helpers/exists"; import InfoTooltip from "../tooltip/InfoTooltip"; import InputMultiSelectDropzone from "./InputMultiSelectDropzone"; import Labeled from "./Labeled"; import ReactSelect from "./ReactSelect"; import TooManyValues from "./TooManyValues"; const SxInputMultiSelectDropzone = styled(InputMultiSelectDropzone)` display: block; `; const SxLabeled = styled(Labeled)` .fullwidth { width: 100%; } `; const disabledStyles = css` opacity: 0.4; `; const OptionLabel = styled("span")<{ disabled?: boolean }>` ${({ disabled }) => disabled && disabledStyles} `; const SxMarkdown = styled(Markdown)<{ disabled?: boolean }>` ${({ disabled }) => disabled && disabledStyles} p { margin: 0; } `; const Row = styled("div")` display: flex; align-items: center; justify-content: space-between; padding: 5px 10px; border-bottom: 1px solid #ccc; `; const InfoText = styled("p")` margin: 0; color: ${({ theme }) => theme.col.gray}; font-size: ${({ theme }) => theme.font.xs}; margin-right: 10px; `; // Arbitrary number that has been set in the backend as well // TODO: Unlimited here + paginated backend vs const OPTIONS_LIMIT = 500; const MultiValueLabel = (params: any) => { const label = params.data.optionLabel || params.data.label || params.data; const valueLabel = params.data.templateValues ? Mustache.render(label, params.data.templateValues) : label; return ( <components.MultiValueLabel {...params}> <span>{valueLabel}</span> </components.MultiValueLabel> ); }; const optionContainsStr = (str: string) => (option: SelectOptionT) => { return ( option.value.toString().toLowerCase().includes(str) || option.label.toLowerCase().includes(str) ); }; export interface MultiSelectInputProps { defaultValue?: string[]; value: SelectOptionT[] | FilterSuggestion[]; onChange: (value: SelectOptionT[] | FilterSuggestion[] | null) => void; } export interface InputMultiSelectProps { label?: string; indexPrefix?: number; options: SelectOptionT[]; disabled?: boolean; tooltip?: string; onInputChange?: (value: string) => void; isLoading?: boolean; className?: string; allowDropFile?: boolean | null; closeMenuOnSelect?: boolean; onDropFile?: (file: File) => void; input: MultiSelectInputProps; } const isFilterSuggestion = ( val: SelectOptionT | FilterSuggestion, ): val is FilterSuggestion => { return ( exists((val as any).optionValue) && exists((val as any).templateValues!) ); }; const InputMultiSelect: FC<InputMultiSelectProps> = (props) => { const { t } = useTranslation(); const allowDropFile = props.allowDropFile && !!props.onDropFile; const hasTooManyValues = props.input.value && props.input.value.length > OPTIONS_LIMIT; const options = props.options.slice(0, OPTIONS_LIMIT).map((option) => ({ ...option, label: isFilterSuggestion(option) ? Mustache.render(option.optionValue, option.templateValues) : option.label, value: String(option.value), optionLabel: option.label, })); const MenuList = ({ children, ...ownProps }: MenuListComponentProps<SelectOptionT, true>) => { return ( <> <Row> <InfoText> {!!props.options ? props.options.length : 0}{" "} {t("inputMultiSelect.options")} </InfoText> <TransparentButton tiny disabled={!props.options || props.options.length === 0} onClick={() => { const visibleOptions = props.options.filter( optionContainsStr(ownProps.selectProps.inputValue), ); ownProps.setValue(visibleOptions, "select-option"); }} > {t("inputMultiSelect.insertAll")} </TransparentButton> </Row> <components.MenuList {...ownProps}>{children}</components.MenuList> </> ); }; const Select = ( <ReactSelect<true> creatable highlightChanged isSearchable isMulti className="fullwidth" createOptionPosition="first" name="form-field" options={options} isOptionDisabled={(option) => !!option.disabled} components={{ MultiValueLabel, MenuList }} value={props.input.value} isDisabled={props.disabled} isLoading={!!props.isLoading} classNamePrefix={"react-select"} maxMenuHeight={300} closeMenuOnSelect={!!props.closeMenuOnSelect} placeholder={ allowDropFile ? t("inputMultiSelect.dndPlaceholder") : t("inputSelect.placeholder") } noOptionsMessage={() => t("inputSelect.empty")} onChange={props.input.onChange} onInputChange={ props.onInputChange || // To allow for async option loading function (value: string) { return value; } } formatCreateLabel={(inputValue: string) => t("common.create") + `: "${inputValue}"` } formatOptionLabel={({ label, disabled, optionValue, templateValues, highlight, }) => optionValue && templateValues ? ( <SxMarkdown disabled={disabled} source={Mustache.render(optionValue, templateValues)} /> ) : ( <OptionLabel disabled={disabled}>{label}</OptionLabel> ) } /> ); return ( <SxLabeled className={props.className} valueChanged={ exists(props.input.value) && JSON.stringify(props.input.value) !== JSON.stringify(props.input.defaultValue) } disabled={!!props.disabled} label={ <> {props.label} {props.tooltip && <InfoTooltip text={props.tooltip} />} </> } indexPrefix={props.indexPrefix} > {hasTooManyValues && ( <TooManyValues count={props.input.value.length} onClear={() => props.input.onChange(null)} /> )} {!hasTooManyValues && !allowDropFile && Select} {!hasTooManyValues && allowDropFile && props.onDropFile && ( <SxInputMultiSelectDropzone onDropFile={props.onDropFile}> {() => Select} </SxInputMultiSelectDropzone> )} </SxLabeled> ); }; export default InputMultiSelect;
manuel-hegner/conquery
frontend/src/js/upload-concept-list-modal/reducer.ts
<filename>frontend/src/js/upload-concept-list-modal/reducer.ts import { getType } from "typesafe-actions"; import type { PostConceptResolveResponseT } from "../api/types"; import { Action } from "../app/actions"; import { stripFilename } from "../common/helpers/fileHelper"; import { initUploadConceptListModal, resetUploadConceptListModal, resolveConcepts, selectConceptRootNode, } from "./actions"; export type UploadConceptListModalStateT = { filename: string | null; conceptCodesFromFile: string[]; selectedConceptRootNode: string; loading: boolean; resolved: PostConceptResolveResponseT; error: Error | null; }; const initialState: UploadConceptListModalStateT = { filename: null, conceptCodesFromFile: [], selectedConceptRootNode: "", loading: false, resolved: {}, error: null, }; const uploadConcepts = ( state: UploadConceptListModalStateT = initialState, action: Action, ) => { switch (action.type) { case getType(initUploadConceptListModal): const { filename, rows } = action.payload; return { ...state, filename: stripFilename(filename), conceptCodesFromFile: rows, selectedConceptRootNode: null, resolved: null, }; case getType(selectConceptRootNode): return { ...state, selectedConceptRootNode: action.payload.conceptId, resolved: null, }; case getType(resolveConcepts.request): return { ...state, loading: true, error: null, }; case getType(resolveConcepts.failure): return { ...state, loading: false, resolved: null, error: action.payload, }; case getType(resolveConcepts.success): return { ...state, loading: false, error: null, resolved: action.payload.data, }; case getType(resetUploadConceptListModal): return initialState; default: return state; } }; export default uploadConcepts;
manuel-hegner/conquery
frontend/src/js/AppRoot.tsx
<reponame>manuel-hegner/conquery import { StateT } from "app-types"; import React, { FC } from "react"; import { Provider } from "react-redux"; import { Store } from "redux"; import AppRouter from "./app/AppRouter"; import type { TabT } from "./pane/types"; interface PropsT { store: Store<StateT>; rightTabs: TabT[]; } const AppRoot: FC<PropsT> = ({ store, rightTabs }) => ( <Provider store={store}> <AppRouter rightTabs={rightTabs} /> </Provider> ); export default AppRoot;
manuel-hegner/conquery
frontend/src/js/ui-components/InputPlain.tsx
<reponame>manuel-hegner/conquery import { css } from "@emotion/react"; import styled from "@emotion/styled"; import React from "react"; import type { CurrencyConfigT } from "../api/types"; import BaseInput from "./BaseInput"; import Labeled from "./Labeled"; import { InputProps } from "./types"; const SxBaseInput = styled(BaseInput)<{ fullWidth?: boolean }>` ${({ fullWidth }) => fullWidth && css` width: 100%; `}; `; interface Props<T> extends InputProps<T> { label: string; indexPrefix?: number; optional?: boolean; inputType?: string; money?: boolean; className?: string; placeholder?: string; tinyLabel?: boolean; large?: boolean; inputProps?: Object; currencyConfig?: CurrencyConfigT; fullWidth?: boolean; tooltip?: string; } const InputPlain = <T extends string | number | null = string | null>( props: Props<T>, ) => { return ( <Labeled className={props.className} fullWidth={props.fullWidth} label={props.label} tinyLabel={props.tinyLabel} largeLabel={props.large} indexPrefix={props.indexPrefix} tooltip={props.tooltip} optional={props.optional} > <SxBaseInput large={props.large} fullWidth={props.fullWidth} inputType={props.inputType || "text"} money={props.money} placeholder={props.placeholder} value={props.input.value} onChange={props.input.onChange} currencyConfig={props.currencyConfig} inputProps={props.inputProps} /> </Labeled> ); }; export default InputPlain;
manuel-hegner/conquery
frontend/src/js/headings/Headings.tsx
import styled from "@emotion/styled"; export const Heading3 = styled("h3")` line-height: 1.3; font-weight: 700; font-size: ${({ theme }) => theme.font.md}; color: ${({ theme }) => theme.col.black}; `; export const Heading4 = styled("h4")` line-height: 1.2; font-weight: 400; font-size: ${({ theme }) => theme.font.sm}; color: ${({ theme }) => theme.col.gray}; text-transform: uppercase; `;