Skip to content

Commit

Permalink
Merge branch 'master' of github.com:elastic/kibana into refactor_cons…
Browse files Browse the repository at this point in the history
…ole_app_data_flow

* 'master' of github.com:elastic/kibana:
  [Console] Fix leaky mappings subscription (elastic#45646)
  TypeScriptify index_patterns/index_patterns/flatten_hit.js (elastic#45269)

# Conflicts:
#	src/legacy/core_plugins/console/np_ready/public/application/containers/main/main.tsx
#	src/legacy/core_plugins/console/public/quarantined/src/app.js
  • Loading branch information
jloleysens committed Sep 16, 2019
2 parents f10c383 + 8e18a5e commit 84feac0
Show file tree
Hide file tree
Showing 11 changed files with 137 additions and 23 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ function _Editor({ previousStateLocation = 'stored' }: EditorProps) {
return () => {
unsubscribeResizer();
unsubscribeAutoSave();
mappings.clearSubscriptions();
};
}, []);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,10 @@ export function useUIAceKeyboardMode(aceTextAreaElement: HTMLTextAreaElement | n
if (aceTextAreaElement) {
document.removeEventListener('keydown', documentKeyDownListener);
aceTextAreaElement.removeEventListener('keydown', aceKeydownListener);
document.removeChild(overlayMountNode.current!);
const textAreaContainer = aceTextAreaElement.parentElement;
if (textAreaContainer && textAreaContainer.contains(overlayMountNode.current!)) {
textAreaContainer.removeChild(overlayMountNode.current!);
}
}
};
}, [aceTextAreaElement]);
Expand Down
13 changes: 11 additions & 2 deletions src/legacy/core_plugins/console/np_ready/public/legacy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import 'ui/capabilities/route_setup';
/* eslint-enable @kbn/eslint/no-restricted-paths */

import template from '../../public/quarantined/index.html';
import { App } from '../../../../../core/public';
import { App, AppUnmount } from '../../../../../core/public';

export interface XPluginSet {
__LEGACY: {
Expand Down Expand Up @@ -64,12 +64,14 @@ uiRoutes.when('/dev_tools/console', {
throw new Error(message);
}

let unmount: AppUnmount | Promise<AppUnmount>;

const mockedSetupCore = {
...npSetup.core,
application: {
register(app: App): void {
try {
app.mount(anyObject, { element: targetElement, appBasePath: '' });
unmount = app.mount(anyObject, { element: targetElement, appBasePath: '' });
} catch (e) {
npSetup.core.fatalErrors.add(e);
}
Expand All @@ -87,6 +89,13 @@ uiRoutes.when('/dev_tools/console', {
},
});
pluginInstance.start(npStart.core);

$scope.$on('$destroy', async () => {
if (unmount) {
const fn = await unmount;
fn();
}
});
};
},
template,
Expand Down
94 changes: 94 additions & 0 deletions src/legacy/core_plugins/console/public/quarantined/src/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/*
* 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.
*/

const $ = require('jquery');

const DEFAULT_INPUT_VALUE = `GET _search
{
"query": {
"match_all": {}
}
}`;

export default function init(input, output, history, sourceLocation = 'stored') {
$(document.body).removeClass('fouc');

// set the value of the input and clear the output
function resetToValues(content) {
input.update(content != null ? content : DEFAULT_INPUT_VALUE);
output.update('');
}

function setupAutosave() {
let timer;
const saveDelay = 500;

input.getSession().on('change', function onChange() {
if (timer) {
timer = clearTimeout(timer);
}
timer = setTimeout(saveCurrentState, saveDelay);
});
}

function saveCurrentState() {
try {
const content = input.getValue();
history.updateCurrentState(content);
} catch (e) {
console.log('Ignoring saving error: ' + e);
}
}
function loadSavedState() {
const previousSaveState = history.getSavedEditorState();

if (sourceLocation === 'stored') {
if (previousSaveState) {
resetToValues(previousSaveState.content);
} else {
resetToValues();
}
} else if (/^https?:\/\//.test(sourceLocation)) {
const loadFrom = {
url: sourceLocation,
// Having dataType here is required as it doesn't allow jQuery to `eval` content
// coming from the external source thereby preventing XSS attack.
dataType: 'text',
kbnXsrfToken: false,
};

if (/https?:\/\/api.github.com/.test(sourceLocation)) {
loadFrom.headers = { Accept: 'application/vnd.github.v3.raw' };
}

$.ajax(loadFrom).done(data => {
resetToValues(data);
input.moveToNextRequestEdge(true);
input.highlightCurrentRequestsAndUpdateActionBar();
input.updateActionsBar();
});
} else {
resetToValues();
}
input.moveToNextRequestEdge(true);
}

setupAutosave();
loadSavedState();
}
Original file line number Diff line number Diff line change
Expand Up @@ -290,10 +290,16 @@ function retrieveSettings(settingsKey, settingsToRetrieve) {
// unchanged alone (both selected and unselected).
// 3. Poll: Use saved. Fetch selected. Ignore unselected.

function retrieveAutoCompleteInfo(settingsToRetrieve = legacyBackDoorToSettings().getAutocomplete()) {

function clearSubscriptions() {
if (pollTimeoutId) {
clearTimeout(pollTimeoutId);
}
}


function retrieveAutoCompleteInfo(settingsToRetrieve = legacyBackDoorToSettings().getAutocomplete()) {
clearSubscriptions();

const mappingPromise = retrieveSettings('fields', settingsToRetrieve);
const aliasesPromise = retrieveSettings('indices', settingsToRetrieve);
Expand Down Expand Up @@ -347,4 +353,5 @@ export default {
expandAliases,
clear,
retrieveAutoCompleteInfo,
clearSubscriptions
};
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,19 @@
*/

import _ from 'lodash';
import { IndexPattern } from './';

// Takes a hit, merges it with any stored/scripted fields, and with the metaFields
// returns a flattened version

function flattenHit(indexPattern, hit, deep) {
const flat = {};
function flattenHit(indexPattern: IndexPattern, hit: Record<string, any>, deep: boolean) {
const flat = {} as Record<string, any>;

// recursively merge _source
const fields = indexPattern.fields.byName;
(function flatten(obj, keyPrefix) {
(function flatten(obj, keyPrefix = '') {
keyPrefix = keyPrefix ? keyPrefix + '.' : '';
_.forOwn(obj, function (val, key) {
_.forOwn(obj, function(val, key) {
key = keyPrefix + key;

if (deep) {
Expand All @@ -52,28 +53,28 @@ function flattenHit(indexPattern, hit, deep) {
} else if (Array.isArray(flat[key])) {
flat[key].push(val);
} else {
flat[key] = [ flat[key], val ];
flat[key] = [flat[key], val];
}
return;
}

flatten(val, key);
});
}(hit._source));
})(hit._source);

return flat;
}

function decorateFlattenedWrapper(hit, metaFields) {
return function (flattened) {
function decorateFlattenedWrapper(hit: Record<string, any>, metaFields: Record<string, any>) {
return function(flattened: Record<string, any>) {
// assign the meta fields
_.each(metaFields, function (meta) {
_.each(metaFields, function(meta) {
if (meta === '_source') return;
flattened[meta] = hit[meta];
});

// unwrap computed fields
_.forOwn(hit.fields, function (val, key) {
_.forOwn(hit.fields, function(val, key: any) {
if (key[0] === '_' && !_.contains(metaFields, key)) return;
flattened[key] = Array.isArray(val) && val.length === 1 ? val[0] : val;
});
Expand All @@ -88,8 +89,12 @@ function decorateFlattenedWrapper(hit, metaFields) {
*
* @internal
*/
export function flattenHitWrapper(indexPattern, metaFields = {}, cache = new WeakMap()) {
return function cachedFlatten(hit, deep = false) {
export function flattenHitWrapper(
indexPattern: IndexPattern,
metaFields = {},
cache = new WeakMap()
) {
return function cachedFlatten(hit: Record<string, any>, deep = false) {
const decorateFlattened = decorateFlattenedWrapper(hit, metaFields);
const cached = cache.get(hit);
const flattened = cached || flattenHit(indexPattern, hit, deep);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
* under the License.
*/

// @ts-ignore
export * from './flatten_hit';
export * from './format_hit';
export * from './index_pattern';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ import { Field, FieldList, FieldType } from '../fields';
import { createFieldsFetcher } from './_fields_fetcher';
import { getRoutes } from '../utils';
import { formatHitProvider } from './format_hit';
// @ts-ignore
import { flattenHitWrapper } from './flatten_hit';
import { IndexPatternsApiClient } from './index_patterns_api_client';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@
*/

import { IndexPatternsService, IndexPatternsSetup } from '.';
// @ts-ignore
import { flattenHitWrapper } from './index_patterns/flatten_hit';
import { flattenHitWrapper } from './index_patterns';

type IndexPatternsServiceClientContract = PublicMethodsOf<IndexPatternsService>;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@

import { UiSettingsClientContract, SavedObjectsClientContract } from 'src/core/public';
import { Field, FieldList, FieldType } from './fields';
// @ts-ignore
import { createFlattenHitWrapper } from './index_patterns/flatten_hit';
import { createFlattenHitWrapper } from './index_patterns';
import { createIndexPatternSelect } from './components';
import {
formatHitProvider,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import { mount } from 'enzyme';
import { IndexPattern } from 'ui/index_patterns';
// @ts-ignore
import { findTestSubject } from '@elastic/eui/lib/test';
// @ts-ignore
import { flattenHitWrapper } from '../../../../data/public/index_patterns/index_patterns/flatten_hit';
import { DocViewTable } from './table';

Expand Down

0 comments on commit 84feac0

Please sign in to comment.