Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reactify field formatters #48728

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import React, { useState } from 'react';
import { DocViewRenderProps } from 'ui/registry/doc_views';
import { DocViewTableRow } from './table_row';
import { arrayContainsObjects, trimAngularSpan } from './table_helper';
import { arrayContainsObjects } from './table_helper';

const COLLAPSE_LINE_LENGTH = 350;

Expand All @@ -33,7 +33,7 @@ export function DocViewTable({
}: DocViewRenderProps) {
const mapping = indexPattern.fields.getByName;
const flattened = indexPattern.flattenHit(hit);
const formatted = indexPattern.formatHit(hit, 'html');
const formatted = indexPattern.formatHit(hit, 'html', true);
const [fieldRowOpen, setFieldRowOpen] = useState({} as Record<string, boolean>);

function toggleValueCollapse(field: string) {
Expand All @@ -48,7 +48,7 @@ export function DocViewTable({
.sort()
.map(field => {
const valueRaw = flattened[field];
const value = trimAngularSpan(String(formatted[field]));
const value = formatted[field];

const isCollapsible = value.length > COLLAPSE_LINE_LENGTH;
const isCollapsed = isCollapsible && !fieldRowOpen[field];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,16 +93,9 @@ export function DocViewTableRow({
)}
{displayUnderscoreWarning && <DocViewTableRowIconUnderscore />}
{displayNoMappingWarning && <DocViewTableRowIconNoMapping />}
<div
className={valueClassName}
data-test-subj={`tableDocViewRow-${field}-value`}
/*
* Justification for dangerouslySetInnerHTML:
* We just use values encoded by our field formatters
*/
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{ __html: value as string }}
/>
<div className={valueClassName} data-test-subj={`tableDocViewRow-${field}-value`}>
{value}
</div>
</td>
</tr>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,24 @@
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
import { escape, isFunction } from 'lodash';
import { IFieldFormat, HtmlContextTypeConvert } from '../types';
import { asPrettyString, getHighlightHtml } from '../utils';
import { asPrettyString, getHighlight } from '../utils';

export const HTML_CONTEXT_TYPE = 'html';

const getConvertFn = (
format: IFieldFormat,
convert?: HtmlContextTypeConvert
): HtmlContextTypeConvert => {
const fallbackHtml: HtmlContextTypeConvert = (value, field, hit) => {
const formatted = escape(format.convert(value, 'text'));
const fallbackHtml: HtmlContextTypeConvert = (value, field, hit, meta, returnReact) => {
const formattedRaw = format.convert(value, 'text');
const formatted = returnReact ? formattedRaw : escape(String(formattedRaw));

return !field || !hit || !hit.highlight || !hit.highlight[field.name]
? formatted
: getHighlightHtml(formatted, hit.highlight[field.name]);
: getHighlight(formatted, hit.highlight[field.name], returnReact);
};

return (convert || fallbackHtml) as HtmlContextTypeConvert;
Expand All @@ -43,27 +45,40 @@ export const setup = (
): HtmlContextTypeConvert => {
const convert = getConvertFn(format, htmlContextTypeConvert);

const recurse: HtmlContextTypeConvert = (value, field, hit, meta) => {
const recurse: HtmlContextTypeConvert = (value, field, hit, meta, returnReact = false) => {
if (value == null) {
return asPrettyString(value);
}

if (!value || !isFunction(value.map)) {
return convert.call(format, value, field, hit, meta);
return convert.call(format, value, field, hit, meta, returnReact);
}

// arrays
const subValues = value.map((v: any) => {
return recurse(v, field, hit, meta);
return recurse(v, field, hit, meta, returnReact);
});

if (returnReact) {
return subValues.map((component: any, idx: number) => (
<span key={idx}>
{component}
{idx !== subValues.length ? ', ' : ''}
</span>
));
}
const useMultiLine = subValues.some((sub: string) => {
return sub.indexOf('\n') > -1;
});

return subValues.join(',' + (useMultiLine ? '\n' : ' '));
};

const wrap: HtmlContextTypeConvert = (value, field, hit, meta) => {
return `<span ng-non-bindable>${recurse(value, field, hit, meta)}</span>`;
const wrap: HtmlContextTypeConvert = (value, field, hit, meta, react = false) => {
if (react) {
return recurse(value, field, hit, meta, react);
}
return `<span ng-non-bindable>${recurse(value, field, hit, meta, react)}</span>`;
};

return wrap;
Expand Down
4 changes: 2 additions & 2 deletions src/plugins/data/common/field_formats/converters/custom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@
import { FieldFormat, IFieldFormatType } from '../field_format';
import { TextContextTypeConvert, FIELD_FORMAT_IDS } from '../types';

export const createCustomFieldFormat = (convert: TextContextTypeConvert): IFieldFormatType =>
export const createCustomFieldFormat = (textConvert: TextContextTypeConvert): IFieldFormatType =>
class CustomFieldFormat extends FieldFormat {
static id = FIELD_FORMAT_IDS.CUSTOM;

textConvert = convert;
textConvert = textConvert;
};
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,14 @@
* specific language governing permissions and limitations
* under the License.
*/

import React, { ReactElement } from 'react';
import { i18n } from '@kbn/i18n';
import { escape, memoize } from 'lodash';
import { getHighlightHtml } from '../utils';
import { KBN_FIELD_TYPES } from '../../kbn_field_types/types';
import { FieldFormat } from '../field_format';
import { TextContextTypeConvert, HtmlContextTypeConvert, FIELD_FORMAT_IDS } from '../types';
import { getHighlightReact } from '../utils/highlight/highlight_react';

const templateMatchRE = /{{([\s\S]+?)}}/g;
const whitelistUrlSchemes = ['http://', 'https://'];
Expand Down Expand Up @@ -123,23 +124,43 @@ export class UrlFormat extends FieldFormat {
};
}

private generateImgHtml(url: string, imageLabel: string): string {
private generateImgHtml(
url: string,
imageLabel: string,
returnReact: boolean = false
): string | ReactElement {
const isValidWidth = !isNaN(parseInt(this.param('width'), 10));
const isValidHeight = !isNaN(parseInt(this.param('height'), 10));
const maxWidth = isValidWidth ? `${this.param('width')}px` : 'none';
const maxHeight = isValidHeight ? `${this.param('height')}px` : 'none';

if (returnReact) {
return (
<img
src={url}
alt={imageLabel}
style={{ width: 'auto', height: 'auto', maxWidth, maxHeight }}
/>
);
}
return `<img src="${url}" alt="${imageLabel}" style="width:auto; height:auto; max-width:${maxWidth}; max-height:${maxHeight};">`;
}

textConvert: TextContextTypeConvert = value => this.formatLabel(value);

htmlConvert: HtmlContextTypeConvert = (rawValue, field, hit, parsedUrl) => {
htmlConvert: HtmlContextTypeConvert = (rawValue, field, hit, parsedUrl, returnReact) => {
const url = escape(this.formatUrl(rawValue));
const label = escape(this.formatLabel(rawValue, url));

switch (this.param('type')) {
case 'audio':
if (returnReact) {
return (
<audio controls preload="none" src={url}>
<track kind="captions" />
</audio>
);
}

return `<audio controls preload="none" src="${url}">`;

case 'img':
Expand All @@ -148,7 +169,7 @@ export class UrlFormat extends FieldFormat {
const imageLabel =
label === url ? `A dynamically-specified image located at ${url}` : label;

return this.generateImgHtml(url, imageLabel);
return this.generateImgHtml(url, imageLabel, returnReact);
default:
const inWhitelist = whitelistUrlSchemes.some(scheme => url.indexOf(scheme) === 0);
if (!inWhitelist && !parsedUrl) {
Expand Down Expand Up @@ -187,13 +208,21 @@ export class UrlFormat extends FieldFormat {
let linkLabel;

if (hit && hit.highlight && hit.highlight[field.name]) {
linkLabel = getHighlightHtml(label, hit.highlight[field.name]);
linkLabel = returnReact
? getHighlightReact(label, hit.highlight[field.name])
: getHighlightHtml(label, hit.highlight[field.name]);
} else {
linkLabel = label;
}

const linkTarget = this.param('openLinkInCurrentTab') ? '_self' : '_blank';

if (returnReact) {
return (
<a href={prefix + url} target={linkTarget} rel="noopener noreferrer">
{linkLabel}
</a>
);
}
return `<a href="${prefix}${url}" target="${linkTarget}" rel="noopener noreferrer">${linkLabel}</a>`;
}
};
Expand Down
10 changes: 5 additions & 5 deletions src/plugins/data/common/field_formats/field_format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/

import { ReactElement } from 'react';
import { transform, size, cloneDeep, get, defaults } from 'lodash';
import { createCustomFieldFormat } from './converters/custom';
import {
Expand Down Expand Up @@ -90,11 +90,11 @@ export abstract class FieldFormat {
* @param {string} [contentType=text] - optional content type, the only two contentTypes
* currently supported are "html" and "text", which helps
* formatters adjust to different contexts
* @return {string} - the formatted string, which is assumed to be html, safe for
* injecting into the DOM or a DOM attribute
* @return {string | ReactElement} - the formatted string, which is assumed to be html, safe for
* injecting into the DOM or a DOM attribute, or a ReactElement
* @public
*/
convert(value: any, contentType: ContentType = DEFAULT_CONTEXT_TYPE): string {
convert(value: any, contentType: ContentType = DEFAULT_CONTEXT_TYPE): string | ReactElement {
const converter = this.getConverterFor(contentType);

if (converter) {
Expand Down Expand Up @@ -184,7 +184,7 @@ export abstract class FieldFormat {
};
}

static from(convertFn: FieldFormatConvertFunction): IFieldFormatType {
static from(convertFn: TextContextTypeConvert): IFieldFormatType {
return createCustomFieldFormat(convertFn);
}

Expand Down
6 changes: 4 additions & 2 deletions src/plugins/data/common/field_formats/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
import { ReactElement } from 'react';

/** @public **/
export type ContentType = 'html' | 'text';
Expand All @@ -28,8 +29,9 @@ export type HtmlContextTypeConvert = (
value: any,
field?: any,
hit?: Record<string, any>,
meta?: any
) => string;
meta?: any,
react?: boolean
) => string | ReactElement;

/** @internal **/
export type TextContextTypeConvert = (value: any) => string;
Expand Down
29 changes: 29 additions & 0 deletions src/plugins/data/common/field_formats/utils/highlight/highlight.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import { getHighlightReact } from './highlight_react';
import { getHighlightHtml } from './highlight_html';

export function getHighlight(fieldValue: any, highlights: any, returnReact?: boolean) {
if (returnReact) {
return getHighlightReact(fieldValue, highlights);
} else {
return getHighlightHtml(fieldValue, highlights);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React, { ReactElement } from 'react';
import { htmlTags } from './html_tags';
import { getHighlightHtml } from './highlight_html';

export function replaceHighLightWithReactDom(
text: string,
tagLeft: string,
tagRight: string
): ReactElement {
return (
<>
{text.split(tagLeft).map((markedText, idx) => {
const sub = markedText.split(tagRight);
if (sub.length === 1) {
return markedText;
}
return (
<span key={idx}>
<mark>{sub[0]}</mark>
{sub[1]}
</span>
);
})}
</>
);
}

export function getHighlightReact(fieldValue: any, highlights: any) {
const html = getHighlightHtml(fieldValue, highlights);
return replaceHighLightWithReactDom(html, htmlTags.pre, htmlTags.post);
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,6 @@
* under the License.
*/

export { getHighlight } from './highlight';
export { getHighlightHtml } from './highlight_html';
export { getHighlightRequest } from './highlight_request';
2 changes: 1 addition & 1 deletion src/plugins/data/common/field_formats/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,4 @@
*/

export { asPrettyString } from './as_pretty_string';
export { getHighlightHtml, getHighlightRequest } from './highlight';
export { getHighlightHtml, getHighlightRequest, getHighlight } from './highlight';
Loading