Skip to content

Commit

Permalink
[Discover] move source field formatter to discover
Browse files Browse the repository at this point in the history
  • Loading branch information
dimaanj committed Oct 7, 2021
1 parent a5f4304 commit 4a49e61
Show file tree
Hide file tree
Showing 13 changed files with 168 additions and 175 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ import { ElasticSearchHit, DocViewFilterFn } from '../../../../../doc_views/doc_
import { getContextUrl } from '../../../../../helpers/get_context_url';
import { getSingleDocUrl } from '../../../../../helpers/get_single_doc_url';
import { TableRowDetails } from './table_row_details';
import { formatRow, formatTopLevelObject } from '../lib/row_formatter';
import { formatRow, formatTopLevelObject } from '../lib/formatters/row_formatter';
import { formatSource } from '../lib/formatters/source_formatter';

export type DocTableRow = ElasticSearchHit & {
isAnchor?: boolean;
Expand All @@ -32,6 +33,7 @@ export interface TableRowProps {
onRemoveColumn?: (column: string) => void;
useNewFieldsApi: boolean;
hideTimeColumn: boolean;
isShortDots: boolean;
filterManager: FilterManager;
addBasePath: (path: string) => string;
fieldsToShow: string[];
Expand All @@ -45,6 +47,7 @@ export const TableRow = ({
useNewFieldsApi,
fieldsToShow,
hideTimeColumn,
isShortDots,
onAddColumn,
onRemoveColumn,
filterManager,
Expand All @@ -63,18 +66,23 @@ export const TableRow = ({
// toggle display of the rows details, a full list of the fields from each row
const toggleRow = () => setOpen((prevOpen) => !prevOpen);

/**
* Fill an element with the value of a field
*/
const displayField = (fieldName: string) => {
const formatField = (fieldName: string) => {
if (fieldName === '_source') {
return formatSource({
hit: row,
indexPattern,
isShortDots,
});
}

const formattedField = indexPattern.formatField(row, fieldName);

// field formatters take care of escaping
// eslint-disable-next-line react/no-danger
const fieldElement = <span dangerouslySetInnerHTML={{ __html: formattedField }} />;

return <div className="truncate-by-height">{fieldElement}</div>;
const element = <span dangerouslySetInnerHTML={{ __html: formattedField }} />;
return <div className="truncate-by-height">{element}</div>;
};

const inlineFilter = useCallback(
(column: string, type: '+' | '-') => {
const field = indexPattern.fields.getByName(column);
Expand Down Expand Up @@ -116,7 +124,7 @@ export const TableRow = ({
<TableCell
key={indexPattern.timeFieldName}
timefield={true}
formatted={displayField(indexPattern.timeFieldName)}
formatted={formatField(indexPattern.timeFieldName)}
filterable={Boolean(mapping(indexPattern.timeFieldName)?.filterable && filter)}
column={indexPattern.timeFieldName}
inlineFilter={inlineFilter}
Expand Down Expand Up @@ -166,7 +174,7 @@ export const TableRow = ({
key={column}
timefield={false}
sourcefield={column === '_source'}
formatted={displayField(column)}
formatted={formatField(column)}
filterable={isFilterable}
column={column}
inlineFilter={inlineFilter}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,7 @@ export const DocTableWrapper = forwardRef(
row={current}
useNewFieldsApi={useNewFieldsApi}
hideTimeColumn={hideTimeColumn}
isShortDots={isShortDots}
onAddColumn={onAddColumn}
onRemoveColumn={onRemoveColumn}
filterManager={filterManager}
Expand All @@ -223,6 +224,7 @@ export const DocTableWrapper = forwardRef(
onRemoveColumn,
filterManager,
addBasePath,
isShortDots,
fieldsToShow,
]
);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { IndexPattern } from '../../../../../../../../../data/common';
import { stubbedSavedObjectIndexPattern } from '../../../../../../../../../data/common/stubs';
import { fieldFormatsMock } from '../../../../../../../../../field_formats/common/mocks';
import { DocTableRow } from '../../components/table_row';

export const hit = {
_id: 'a',
_type: 'doc',
_score: 1,
_source: {
foo: 'bar',
number: 42,
hello: '<h1>World</h1>',
also: 'with "quotes" or \'single quotes\'',
},
} as DocTableRow;

const createIndexPattern = () => {
const id = 'my-index';
const {
type,
version,
attributes: { timeFieldName, fields, title },
} = stubbedSavedObjectIndexPattern(id);

return new IndexPattern({
spec: { id, type, version, timeFieldName, fields: JSON.parse(fields), title },
fieldFormats: fieldFormatsMock,
shortDotsEnable: false,
metaFields: [],
});
};

export const indexPattern = createIndexPattern();
Original file line number Diff line number Diff line change
Expand Up @@ -8,43 +8,11 @@

import ReactDOM from 'react-dom/server';
import { formatRow, formatTopLevelObject } from './row_formatter';
import { IndexPattern } from '../../../../../../../../data/common';
import { fieldFormatsMock } from '../../../../../../../../field_formats/common/mocks';
import { setServices } from '../../../../../../kibana_services';
import { DiscoverServices } from '../../../../../../build_services';
import { stubbedSavedObjectIndexPattern } from '../../../../../../../../data/common/stubs';
import { setServices } from '../../../../../../../kibana_services';
import { DiscoverServices } from '../../../../../../../build_services';
import { indexPattern, hit } from './mocks';

describe('Row formatter', () => {
const hit = {
_id: 'a',
_type: 'doc',
_score: 1,
_source: {
foo: 'bar',
number: 42,
hello: '<h1>World</h1>',
also: 'with "quotes" or \'single quotes\'',
},
};

const createIndexPattern = () => {
const id = 'my-index';
const {
type,
version,
attributes: { timeFieldName, fields, title },
} = stubbedSavedObjectIndexPattern(id);

return new IndexPattern({
spec: { id, type, version, timeFieldName, fields: JSON.parse(fields), title },
fieldFormats: fieldFormatsMock,
shortDotsEnable: false,
metaFields: [],
});
};

const indexPattern = createIndexPattern();

const fieldsToShow = indexPattern.fields.getAll().map((fld) => fld.name);

// Realistic response with alphabetical insertion order
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@

import React, { Fragment } from 'react';
import type { IndexPattern } from 'src/plugins/data/common';
import { MAX_DOC_FIELDS_DISPLAYED } from '../../../../../../../common';
import { getServices } from '../../../../../../kibana_services';
import { MAX_DOC_FIELDS_DISPLAYED } from '../../../../../../../../common';
import { getServices } from '../../../../../../../kibana_services';

import './row_formatter.scss';

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { formatSource } from './source_formatter';
import { hit, indexPattern } from './mocks';

describe('_source formatter', () => {
it('should format properly', () => {
const element = formatSource({ hit, indexPattern, isShortDots: true });
expect(element).toMatchInlineSnapshot(`
<TemplateComponent
defPairs={
Array [
Array [
"also",
"with \\"quotes\\" or 'single quotes'",
],
Array [
"foo",
"bar",
],
Array [
"hello",
"<h1>World</h1>",
],
Array [
"number",
42,
],
]
}
/>
`);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import React, { Fragment } from 'react';
import { escape } from 'lodash';
import { DocTableRow } from '../../components/table_row';
import { shortenDottedString } from '../../../../../../../../../field_formats/common';
import { IndexPattern } from '../../../../../../../../../data/public';

interface Props {
defPairs: Array<[string, string]>;
}

const TemplateComponent = ({ defPairs }: Props) => {
return (
<dl className={'source truncate-by-height'}>
{defPairs.map((pair, idx) => (
<Fragment key={idx}>
<dt
dangerouslySetInnerHTML={{ __html: `${escape(pair[0])}:` }} // eslint-disable-line react/no-danger
/>
<dd
dangerouslySetInnerHTML={{ __html: `${pair[1]}` }} // eslint-disable-line react/no-danger
/>{' '}
</Fragment>
))}
</dl>
);
};

export const formatSource = ({
hit,
indexPattern,
isShortDots,
}: {
hit: DocTableRow;
indexPattern: IndexPattern;
isShortDots: boolean;
}) => {
const highlights: Record<string, string[]> = (hit && hit.highlight) || {};
// TODO: remove index pattern dependency
const formatted = hit ? indexPattern.formatHit(hit) : {};
const highlightPairs: Array<[string, string]> = [];
const sourcePairs: Array<[string, string]> = [];

Object.keys(formatted).forEach((key) => {
const pairs = highlights[key] ? highlightPairs : sourcePairs;
const newField = isShortDots ? shortenDottedString(key) : key;
const val = formatted![key];
pairs.push([newField as string, val]);
}, []);

return <TemplateComponent defPairs={highlightPairs.concat(sourcePairs)} />;
};
2 changes: 0 additions & 2 deletions src/plugins/field_formats/common/constants/base_formatters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import {
NumberFormat,
PercentFormat,
RelativeDateFormat,
SourceFormat,
StaticLookupFormat,
StringFormat,
TruncateFormat,
Expand All @@ -34,7 +33,6 @@ export const baseFormatters: FieldFormatInstanceType[] = [
NumberFormat,
PercentFormat,
RelativeDateFormat,
SourceFormat,
StaticLookupFormat,
StringFormat,
TruncateFormat,
Expand Down
1 change: 0 additions & 1 deletion src/plugins/field_formats/common/converters/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ export { IpFormat } from './ip';
export { NumberFormat } from './number';
export { PercentFormat } from './percent';
export { StringFormat } from './string';
export { SourceFormat } from './source';
export { ColorFormat } from './color';
export { TruncateFormat } from './truncate';
export { BoolFormat } from './boolean';
Expand Down
49 changes: 0 additions & 49 deletions src/plugins/field_formats/common/converters/source.test.ts

This file was deleted.

Loading

0 comments on commit 4a49e61

Please sign in to comment.