kibana/x-pack/plugins/runtime_fields
Spencer afb09ccf8a
Transpile packages on demand, validate all TS projects (#146212)
## Dearest Reviewers 👋 

I've been working on this branch with @mistic and @tylersmalley and
we're really confident in these changes. Additionally, this changes code
in nearly every package in the repo so we don't plan to wait for reviews
to get in before merging this. If you'd like to have a concern
addressed, please feel free to leave a review, but assuming that nobody
raises a blocker in the next 24 hours we plan to merge this EOD pacific
tomorrow, 12/22.

We'll be paying close attention to any issues this causes after merging
and work on getting those fixed ASAP. 🚀

---

The operations team is not confident that we'll have the time to achieve
what we originally set out to accomplish by moving to Bazel with the
time and resources we have available. We have also bought ourselves some
headroom with improvements to babel-register, optimizer caching, and
typescript project structure.

In order to make sure we deliver packages as quickly as possible (many
teams really want them), with a usable and familiar developer
experience, this PR removes Bazel for building packages in favor of
using the same JIT transpilation we use for plugins.

Additionally, packages now use `kbn_references` (again, just copying the
dx from plugins to packages).

Because of the complex relationships between packages/plugins and in
order to prepare ourselves for automatic dependency detection tools we
plan to use in the future, this PR also introduces a "TS Project Linter"
which will validate that every tsconfig.json file meets a few
requirements:

1. the chain of base config files extended by each config includes
`tsconfig.base.json` and not `tsconfig.json`
1. the `include` config is used, and not `files`
2. the `exclude` config includes `target/**/*`
3. the `outDir` compiler option is specified as `target/types`
1. none of these compiler options are specified: `declaration`,
`declarationMap`, `emitDeclarationOnly`, `skipLibCheck`, `target`,
`paths`

4. all references to other packages/plugins use their pkg id, ie:
	
	```js
    // valid
    {
      "kbn_references": ["@kbn/core"]
    }
    // not valid
    {
      "kbn_references": [{ "path": "../../../src/core/tsconfig.json" }]
    }
    ```

5. only packages/plugins which are imported somewhere in the ts code are
listed in `kbn_references`

This linter is not only validating all of the tsconfig.json files, but
it also will fix these config files to deal with just about any
violation that can be produced. Just run `node scripts/ts_project_linter
--fix` locally to apply these fixes, or let CI take care of
automatically fixing things and pushing the changes to your PR.

> **Example:** [`64e93e5`
(#146212)](64e93e5806)
When I merged main into my PR it included a change which removed the
`@kbn/core-injected-metadata-browser` package. After resolving the
conflicts I missed a few tsconfig files which included references to the
now removed package. The TS Project Linter identified that these
references were removed from the code and pushed a change to the PR to
remove them from the tsconfig.json files.

## No bazel? Does that mean no packages??
Nope! We're still doing packages but we're pretty sure now that we won't
be using Bazel to accomplish the 'distributed caching' and 'change-based
tasks' portions of the packages project.

This PR actually makes packages much easier to work with and will be
followed up with the bundling benefits described by the original
packages RFC. Then we'll work on documentation and advocacy for using
packages for any and all new code.

We're pretty confident that implementing distributed caching and
change-based tasks will be necessary in the future, but because of
recent improvements in the repo we think we can live without them for
**at least** a year.

## Wait, there are still BUILD.bazel files in the repo
Yes, there are still three webpack bundles which are built by Bazel: the
`@kbn/ui-shared-deps-npm` DLL, `@kbn/ui-shared-deps-src` externals, and
the `@kbn/monaco` workers. These three webpack bundles are still created
during bootstrap and remotely cached using bazel. The next phase of this
project is to figure out how to get the package bundling features
described in the RFC with the current optimizer, and we expect these
bundles to go away then. Until then any package that is used in those
three bundles still needs to have a BUILD.bazel file so that they can be
referenced by the remaining webpack builds.

Co-authored-by: kibanamachine <42973632+kibanamachine@users.noreply.github.com>
2022-12-22 19:00:29 -06:00
..
public [Form lib] Fix validate method returning wrong state when called from onChange handler (#146371) 2022-12-09 09:44:51 +05:00
jest.config.js [jest] update config files to get coverage per plugin (#111299) 2021-09-09 08:14:56 +02:00
kibana.json Adding owners to kibana plugins (#108407) 2021-08-17 10:21:06 -04:00
README.md add KibanaThemeProvider support for kibana-app-services (#122370) 2022-01-13 07:30:10 -07:00
tsconfig.json Transpile packages on demand, validate all TS projects (#146212) 2022-12-22 19:00:29 -06:00

Runtime fields

Welcome to the home of the runtime field editor and everything related to runtime fields!

The runtime field editor

Integration

The recommended way to integrate the runtime fields editor is by adding a plugin dependency to the "runtimeFields" x-pack plugin. This way you will be able to lazy load the editor when it is required and it will not increment the bundle size of your plugin.

// 1. Add the plugin as a dependency in your kibana.json
{
  ...
  "requiredBundles": [
    "runtimeFields",
    ...
  ]
}

// 2. Access it in your plugin setup()
export class MyPlugin {
  setup(core, { runtimeFields }) {
    // logic to provide it to your app, probably through context
  }
}

// 3. Load the editor and open it anywhere in your app
const MyComponent = () => {
  // Access the plugin through context
  const { runtimeFields } = useAppPlugins();

  // Ref of the handler to close the editor
  const closeRuntimeFieldEditor = useRef(() => {});

  const saveRuntimeField = (field: RuntimeField) => {
    // Do something with the field
    // See interface returned in @returns section below
  };

  const openRuntimeFieldsEditor = async() => {
    // Lazy load the editor
    const { openEditor } = await runtimeFields.loadEditor();

    closeRuntimeFieldEditor.current = openEditor({
      onSave: saveRuntimeField,
      /* defaultValue: optional field to edit */
      /* ctx: Context -- see section below */
    });
  };

  useEffect(() => {
    return () => {
      // Make sure to remove the editor when the component unmounts
      closeRuntimeFieldEditor.current();
    };
  }, []);

  return (
    <button onClick={openRuntimeFieldsEditor}>Add field</button>
  )
}

@returns

You get back a RuntimeField object with the following interface

interface RuntimeField {
  name: string;
  type: RuntimeType; // 'long' | 'boolean' ...
  script: {
    source: string;
  };
}

Context object

You can provide a context object to the runtime field editor. It has the following interface

interface Context {
  /** An array of field name not allowed. You would probably provide an array of existing runtime fields
   * to prevent the user creating a field with the same name.
   */
  namesNotAllowed?: string[];
  /**
   * An array of existing concrete fields. If the user gives a name to the runtime
   * field that matches one of the concrete fields, a callout will be displayed
   * to indicate that this runtime field will shadow the concrete field.
   * This array is also used to provide the list of field autocomplete suggestions to the code editor
   */
  existingConcreteFields?: Array<{
    name: string;
    type: string;
  }>;
}

Other type of integration

The runtime field editor is also exported as static React component that you can import into your components. The editor is exported in 2 flavours:

  • As the content of a <EuiFlyout /> (it contains a flyout header and footer)
  • As a standalone component that you can inline anywhere

Note: The runtime field editor uses the <CodeEditor /> that has a dependency on the Provider from the "kibana_react" plugin. If your app is not already wrapped by this provider you will need to add it at least around the runtime field editor. You can see an example in the "Using the core.overlays.openFlyout()" example below.

Content of a <EuiFlyout />

import React, { useState } from 'react';
import { EuiFlyoutBody, EuiButton } from '@elastic/eui';
import { RuntimeFieldEditorFlyoutContent, RuntimeField } from '../runtime_fields/public';

const MyComponent = () => {
  const { docLinksStart } = useCoreContext(); // access the core start service
  const [isFlyoutVisilbe, setIsFlyoutVisible] = useState(false);

  const saveRuntimeField = useCallback((field: RuntimeField) => {
    // Do something with the field
  }, []);

  return (
    <>
      <EuiButton onClick={() => setIsFlyoutVisible(true)}>Create field</EuiButton>

      {isFlyoutVisible && (
        <EuiFlyout onClose={() => setIsFlyoutVisible(false)}>
          <RuntimeFieldEditorFlyoutContent
            onSave={saveRuntimeField}
            onCancel={() => setIsFlyoutVisible(false)}
            docLinks={docLinksStart}
            defaultValue={/*optional runtime field to edit*/}
            ctx={/*optional context object -- see section above*/}
          />
        </EuiFlyout>
      )}
    </>
  )
}

Using the core.overlays.openFlyout()

As an alternative you can open the flyout with the openFlyout() helper from core.

import React, { useRef } from 'react';
import { EuiButton } from '@elastic/eui';
import { OverlayRef } from 'src/core/public';

import { createKibanaReactContext, toMountPoint } from '../../src/plugins/kibana_react/public';
import { RuntimeFieldEditorFlyoutContent, RuntimeField } from '../runtime_fields/public';

const MyComponent = () => {
  // Access the core start service
  const { docLinksStart, theme, overlays, uiSettings } = useCoreContext();
  const flyoutEditor = useRef<OverlayRef | null>(null);

  const { openFlyout } = overlays;

  const saveRuntimeField = useCallback((field: RuntimeField) => {
    // Do something with the field
  }, []);

  const openRuntimeFieldEditor = useCallback(() => {
    const { Provider: KibanaReactContextProvider } = createKibanaReactContext({ uiSettings });

    flyoutEditor.current = openFlyout(
      toMountPoint(
        <KibanaReactContextProvider>
          <RuntimeFieldEditorFlyoutContent
            onSave={saveRuntimeField}
            onCancel={() => flyoutEditor.current?.close()}
            docLinks={docLinksStart}
            defaultValue={defaultRuntimeField}
            ctx={/*optional context object -- see section above*/}
          />
        </KibanaReactContextProvider>,
        { theme$: theme.theme$ }
      )
    );
  }, [openFlyout, saveRuntimeField, uiSettings]);

  return (
    <>
      <EuiButton onClick={openRuntimeFieldEditor}>Create field</EuiButton>
    </>
  )
}

Standalone component

import React, { useState } from 'react';
import { EuiButton, EuiSpacer } from '@elastic/eui';
import { RuntimeFieldEditor, RuntimeField, RuntimeFieldFormState } from '../runtime_fields/public';

const MyComponent = () => {
  const { docLinksStart } = useCoreContext(); // access the core start service
  const [runtimeFieldFormState, setRuntimeFieldFormState] = useState<RuntimeFieldFormState>({
    isSubmitted: false,
    isValid: undefined,
    submit: async() => Promise.resolve({ isValid: false, data: {} as RuntimeField })
  });

  const { submit, isValid: isFormValid, isSubmitted } = runtimeFieldFormState;

  const saveRuntimeField = useCallback(async () => {
    const { isValid, data } = await submit();
    if (isValid) {
      // Do something with the field (data)
    }
  }, [submit]);

  return (
    <>
      <RuntimeFieldEditor
        onChange={setRuntimeFieldFormState}
        docLinks={docLinksStart}
        defaultValue={/*optional runtime field to edit*/}
        ctx={/*optional context object -- see section above*/}
      />

      <EuiSpacer />

      <EuiButton
        onClick={saveRuntimeField}
        disabled={isSubmitted && !isFormValid}>
        Save field
      </EuiButton>
    </>
  )
}