hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
listlengths 5
5
|
---|---|---|---|---|---|
{
"id": 1,
"code_window": [
" <Toolbar\n",
" key=\"toolbar\"\n",
" left={[\n",
" <TabBar key=\"tabs\" scroll={false}>\n",
" {tabsList.map(t => (\n",
" <S.UnstyledLink\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" {tabsList.map((t, index) => (\n"
],
"file_path": "lib/components/src/preview/preview.js",
"type": "replace",
"edit_start_line_idx": 90
} | {
"name": "@storybook/core-events",
"version": "4.0.0-alpha.25",
"description": "Event names used in storybook core",
"keywords": [
"storybook"
],
"homepage": "https://github.com/storybooks/storybook/tree/master/lib/core-events",
"publishConfig": {
"access": "public"
},
"bugs": {
"url": "https://github.com/storybooks/storybook/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/storybooks/storybook.git"
},
"license": "MIT",
"main": "index.js"
}
| lib/core-events/package.json | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.0001755854464136064,
0.0001739102735882625,
0.00017291416588705033,
0.00017323116480838507,
0.0000011915848290300346
]
|
{
"id": 1,
"code_window": [
" <Toolbar\n",
" key=\"toolbar\"\n",
" left={[\n",
" <TabBar key=\"tabs\" scroll={false}>\n",
" {tabsList.map(t => (\n",
" <S.UnstyledLink\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" {tabsList.map((t, index) => (\n"
],
"file_path": "lib/components/src/preview/preview.js",
"type": "replace",
"edit_start_line_idx": 90
} | {
"extends": "../src/tsconfig.app.json",
"exclude": [
"../src/test.ts",
"../src/**/*.spec.ts",
"../projects/**/*.spec.ts"
],
"include": [
"../src/**/*",
"../projects/**/*"
]
}
| lib/cli/generators/ANGULAR/template/.storybook/tsconfig.json | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.00017407744599040598,
0.00017376297910232097,
0.00017344851221423596,
0.00017376297910232097,
3.1446688808500767e-7
]
|
{
"id": 2,
"code_window": [
" <S.UnstyledLink\n",
" key={t.key}\n",
" to={location.replace(/^\\/(components|info)\\//, t.route)}\n",
" >\n",
" <TabButton>{t.title}</TabButton>\n",
" </S.UnstyledLink>\n",
" ))}\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" key={t.key || index}\n"
],
"file_path": "lib/components/src/preview/preview.js",
"type": "replace",
"edit_start_line_idx": 92
} | import { window } from 'global';
import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import Events from '@storybook/core-events';
import { types } from '@storybook/addons';
import { IconButton, Toolbar, Separator } from './toolbar';
import Icons from '../icon/icon';
import { Route } from '../router/router';
import { TabButton, TabBar } from '../tabs/tabs';
import Zoom from './tools/zoom';
import { Grid, Background } from './tools/background';
import * as S from './components';
class IFrame extends Component {
shouldComponentUpdate() {
// this component renders an iframe, which gets updates via post-messages
return false;
}
render() {
const { id, title, src, allowFullScreen, ...rest } = this.props;
return (
<iframe
id={id}
title={title}
src={src}
allowFullScreen={allowFullScreen}
{...rest}
style={{ border: '0 none' }}
/>
);
}
}
IFrame.propTypes = {
id: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
src: PropTypes.string.isRequired,
allowFullScreen: PropTypes.bool.isRequired,
};
// eslint-disable-next-line react/no-multi-comp
class Preview extends Component {
state = {
zoom: 1,
grid: false,
};
shouldComponentUpdate({ location, toolbar, options }, { zoom, grid }) {
const { props, state } = this;
return (
options.isFullscreen !== props.options.isFullscreen ||
location !== props.location ||
toolbar !== props.toolbar ||
zoom !== state.zoom ||
grid !== state.grid
);
}
componentDidUpdate(prevProps) {
const { channel, location } = this.props;
const { location: prevLocation } = prevProps;
if (location && this.getStoryPath(location) !== this.getStoryPath(prevLocation)) {
channel.emit(Events.SET_CURRENT_STORY, { location });
}
}
getStoryPath = location => location.replace(/\/?.+\/(.+)/, '$1');
render() {
const { id, toolbar = true, location = '/', getElements, actions, options } = this.props;
const { zoom, grid } = this.state;
const panels = getElements(types.PANEL);
const toolbarHeight = toolbar ? 40 : 0;
const panelList = Object.entries(panels).map(([key, value]) => ({ ...value, key }));
const tabsList = [{ route: '/components/', title: 'Canvas', key: 'canvas' }].concat(
getElements(types.TAB)
);
const toolList = getElements(types.TOOL);
return (
<Fragment>
{toolbar ? (
<Toolbar
key="toolbar"
left={[
<TabBar key="tabs" scroll={false}>
{tabsList.map(t => (
<S.UnstyledLink
key={t.key}
to={location.replace(/^\/(components|info)\//, t.route)}
>
<TabButton>{t.title}</TabButton>
</S.UnstyledLink>
))}
</TabBar>,
<Separator key="1" />,
<Zoom
key="zoom"
current={zoom}
set={v => this.setState({ zoom: zoom * v })}
reset={() => this.setState({ zoom: 1 })}
/>,
<Separator key="2" />,
<IconButton active={!!grid} key="grid" onClick={() => this.setState({ grid: !grid })}>
<Icons icon="grid" />
</IconButton>,
<Fragment>
{toolList.map(t => (
<Fragment>{t.render()}</Fragment>
))}
</Fragment>,
]}
right={[
<Separator key="1" />,
<IconButton key="full" onClick={actions.toggleFullscreen}>
<Icons icon={options.isFullscreen ? 'cross' : 'expand'} />
</IconButton>,
<Separator key="2" />,
<IconButton key="opener" onClick={() => window.open(`iframe.html?path=${location}`)}>
<Icons icon="share" />
</IconButton>,
]}
/>
) : null}
<S.FrameWrap key="frame" offset={toolbarHeight}>
<Route path="components" startsWith hideOnly>
<S.Frame
style={{
width: `${100 * zoom}%`,
height: `${100 * zoom}%`,
transform: `scale(${1 / zoom})`,
}}
>
<Background id="storybook-preview-background">{grid ? <Grid /> : null}</Background>
<IFrame
id="storybook-preview-iframe"
title={id || 'preview'}
src={`iframe.html?path=${location}`}
allowFullScreen
/>
</S.Frame>
</Route>
{panelList.map(panel => (
<Route path={panel.route} startsWith hideOnly key={panel.key}>
{panel.render({ active: true })}
</Route>
))}
</S.FrameWrap>
</Fragment>
);
}
}
Preview.propTypes = {
id: PropTypes.string.isRequired,
toolbar: PropTypes.bool.isRequired,
channel: PropTypes.shape({
on: PropTypes.func,
emit: PropTypes.func,
removeListener: PropTypes.func,
}).isRequired,
location: PropTypes.string.isRequired,
getElements: PropTypes.func.isRequired,
options: PropTypes.shape({
isFullscreen: PropTypes.bool,
}).isRequired,
actions: PropTypes.shape({}).isRequired,
};
export { Preview };
| lib/components/src/preview/preview.js | 1 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.9014546275138855,
0.05043422430753708,
0.00016018372843973339,
0.00018016312969848514,
0.20640330016613007
]
|
{
"id": 2,
"code_window": [
" <S.UnstyledLink\n",
" key={t.key}\n",
" to={location.replace(/^\\/(components|info)\\//, t.route)}\n",
" >\n",
" <TabButton>{t.title}</TabButton>\n",
" </S.UnstyledLink>\n",
" ))}\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" key={t.key || index}\n"
],
"file_path": "lib/components/src/preview/preview.js",
"type": "replace",
"edit_start_line_idx": 92
} | import React from 'react';
import { storiesOf, action, linkTo } from '@kadira/storybook';
import Button from './Button';
import Welcome from './Welcome';
storiesOf('Welcome', module)
.add('to Storybook', () => (
<Welcome showApp={linkTo('Button')}/>
));
storiesOf('Button', module)
.add('with text', () => (
<Button onClick={action('clicked')}>Hello Button</Button>
))
.add('with some emoji', () => (
<Button onClick={action('clicked')}>π π π π―</Button>
));
| lib/cli/test/fixtures/update_package_organisations/stories/index.js | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.00017290755931753665,
0.00017159471462946385,
0.00017028186994139105,
0.00017159471462946385,
0.0000013128446880728006
]
|
{
"id": 2,
"code_window": [
" <S.UnstyledLink\n",
" key={t.key}\n",
" to={location.replace(/^\\/(components|info)\\//, t.route)}\n",
" >\n",
" <TabButton>{t.title}</TabButton>\n",
" </S.UnstyledLink>\n",
" ))}\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" key={t.key || index}\n"
],
"file_path": "lib/components/src/preview/preview.js",
"type": "replace",
"edit_start_line_idx": 92
} | docs/src/components/Docs/style.css | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.00016828537627588958,
0.00016828537627588958,
0.00016828537627588958,
0.00016828537627588958,
0
]
|
|
{
"id": 2,
"code_window": [
" <S.UnstyledLink\n",
" key={t.key}\n",
" to={location.replace(/^\\/(components|info)\\//, t.route)}\n",
" >\n",
" <TabButton>{t.title}</TabButton>\n",
" </S.UnstyledLink>\n",
" ))}\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" key={t.key || index}\n"
],
"file_path": "lib/components/src/preview/preview.js",
"type": "replace",
"edit_start_line_idx": 92
} | [build]
publish = "netlify-build"
command = "bash scripts/netlify-build.sh"
[build.environment]
NODE_VERSION = "8"
YARN_VERSION = "1.3.2"
YARN_FLAGS = "--version"
| netlify.toml | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.00017070730973500758,
0.00017070730973500758,
0.00017070730973500758,
0.00017070730973500758,
0
]
|
{
"id": 3,
"code_window": [
" />,\n",
" <Separator key=\"2\" />,\n",
" <IconButton active={!!grid} key=\"grid\" onClick={() => this.setState({ grid: !grid })}>\n",
" <Icons icon=\"grid\" />\n",
" </IconButton>,\n",
" <Fragment>\n",
" {toolList.map(t => (\n",
" <Fragment>{t.render()}</Fragment>\n",
" ))}\n",
" </Fragment>,\n",
" ]}\n",
" right={[\n",
" <Separator key=\"1\" />,\n",
" <IconButton key=\"full\" onClick={actions.toggleFullscreen}>\n",
" <Icons icon={options.isFullscreen ? 'cross' : 'expand'} />\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ...toolList.map((t, index) => <Fragment key={`t${index}`}>{t.render()}</Fragment>),\n"
],
"file_path": "lib/components/src/preview/preview.js",
"type": "replace",
"edit_start_line_idx": 110
} | import addons from '@storybook/addons';
import { navigator, window, document } from 'global';
import createChannel from '@storybook/channel-postmessage';
import { handleKeyboardShortcuts } from '@storybook/ui/dist/libs/key_events';
import { logger } from '@storybook/client-logger';
import Events from '@storybook/core-events';
import StoryStore from './story_store';
import ClientApi from './client_api';
import ConfigApi from './config_api';
const classes = {
MAIN: 'sb-show-main',
NOPREVIEW: 'sb-show-nopreview',
ERROR: 'sb-show-errordisplay',
};
function showMain() {
document.body.classList.remove(classes.NOPREVIEW);
document.body.classList.remove(classes.ERROR);
document.body.classList.add(classes.MAIN);
}
function showNopreview() {
document.body.classList.remove(classes.MAIN);
document.body.classList.remove(classes.ERROR);
document.body.classList.add(classes.NOPREVIEW);
}
function showErrorDisplay({ message, stack }) {
document.getElementById('error-message').textContent = message;
document.getElementById('error-stack').textContent = stack;
document.body.classList.remove(classes.MAIN);
document.body.classList.remove(classes.NOPREVIEW);
document.body.classList.add(classes.ERROR);
}
// showError is used by the various app layers to inform the user they have done something
// wrong -- for instance returned the wrong thing from a story
function showError({ title, description }) {
addons.getChannel().emit(Events.STORY_ERRORED, { title, description });
showErrorDisplay({
message: title,
stack: description,
});
}
// showException is used if we fail to render the story and it is uncaught by the app layer
function showException(exception) {
addons.getChannel().emit(Events.STORY_THREW_EXCEPTION, exception);
showErrorDisplay(exception);
// Log the stack to the console. So, user could check the source code.
logger.error(exception.stack);
}
const isBrowser =
navigator &&
navigator.userAgent &&
navigator.userAgent !== 'storyshots' &&
!(navigator.userAgent.indexOf('Node.js') > -1) &&
!(navigator.userAgent.indexOf('jsdom') > -1);
const getContext = (() => {
let cache;
return decorateStory => {
if (cache) {
return cache;
}
let channel = null;
if (isBrowser) {
try {
channel = addons.getChannel();
} catch (e) {
channel = createChannel({ page: 'preview' });
addons.setChannel(channel);
}
}
const storyStore = new StoryStore({ channel });
const clientApi = new ClientApi({ storyStore, decorateStory });
const { clearDecorators } = clientApi;
const configApi = new ConfigApi({ clearDecorators, storyStore, channel, clientApi });
return {
configApi,
storyStore,
channel,
clientApi,
showMain,
showError,
showException,
};
};
})();
export default function start(render, { decorateStory } = {}) {
const context = getContext(decorateStory);
const { clientApi, channel, configApi, storyStore } = context;
// Provide access to external scripts if `window` is defined.
// NOTE this is different to isBrowser, primarily for the JSDOM use case
let previousKind = '';
let previousStory = '';
let previousRevision = -1;
const renderMain = forceRender => {
const revision = storyStore.getRevision();
const { kind, name, story } = storyStore.getSelection() || {};
if (story) {
// Render story only if selectedKind or selectedStory have changed.
// However, we DO want the story to re-render if the store itself has changed
// (which happens at the moment when HMR occurs)
if (
!forceRender &&
revision === previousRevision &&
kind === previousKind &&
previousStory === name
) {
return;
}
if (!forceRender) {
// Scroll to top of the page when changing story
document.documentElement.scrollTop = 0;
}
render({
...context,
story,
selectedKind: kind,
selectedStory: name,
forceRender,
});
addons.getChannel().emit(Events.STORY_RENDERED, storyStore.getSelection());
} else {
showNopreview();
addons.getChannel().emit(Events.STORY_MISSING, storyStore.getSelection());
}
previousRevision = revision;
previousKind = kind;
previousStory = name;
};
// initialize the UI
const renderUI = forceRender => {
if (isBrowser) {
try {
renderMain(forceRender);
} catch (ex) {
showException(ex);
}
}
};
const forceReRender = () => renderUI(true);
// channel can be null in NodeJS
if (isBrowser) {
channel.on(Events.FORCE_RE_RENDER, forceReRender);
channel.on(Events.SET_CURRENT_STORY, ({ location }) => {
if (!location) {
throw new Error('should have location');
}
const data = storyStore.fromPath(location);
console.log('here', location);
storyStore.setSelection(data);
storyStore.setPath(location);
});
// Handle keyboard shortcuts
window.onkeydown = handleKeyboardShortcuts(channel);
}
storyStore.on(Events.STORY_RENDER, renderUI);
if (typeof window !== 'undefined') {
window.__STORYBOOK_CLIENT_API__ = clientApi;
window.__STORYBOOK_ADDONS_CHANNEL__ = channel; // may not be defined
}
return { context, clientApi, configApi, forceReRender };
}
| lib/core/src/client/preview/start.js | 1 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.0001705747126834467,
0.00016672124911565334,
0.00016262395365629345,
0.00016718007100280374,
0.0000026299744604330044
]
|
{
"id": 3,
"code_window": [
" />,\n",
" <Separator key=\"2\" />,\n",
" <IconButton active={!!grid} key=\"grid\" onClick={() => this.setState({ grid: !grid })}>\n",
" <Icons icon=\"grid\" />\n",
" </IconButton>,\n",
" <Fragment>\n",
" {toolList.map(t => (\n",
" <Fragment>{t.render()}</Fragment>\n",
" ))}\n",
" </Fragment>,\n",
" ]}\n",
" right={[\n",
" <Separator key=\"1\" />,\n",
" <IconButton key=\"full\" onClick={actions.toggleFullscreen}>\n",
" <Icons icon={options.isFullscreen ? 'cross' : 'expand'} />\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ...toolList.map((t, index) => <Fragment key={`t${index}`}>{t.render()}</Fragment>),\n"
],
"file_path": "lib/components/src/preview/preview.js",
"type": "replace",
"edit_start_line_idx": 110
} | import React from 'react';
import { Text } from 'react-native';
import { storiesOf } from '@storybook/react-native';
import { action } from '@storybook/addon-actions';
import { linkTo } from '@storybook/addon-links';
import Button from './Button';
import CenterView from './CenterView';
import Welcome from './Welcome';
storiesOf('Welcome', module).add('to Storybook', () => <Welcome showApp={linkTo('Button')} />);
storiesOf('Button', module)
.addDecorator(getStory => <CenterView>{getStory()}</CenterView>)
.add('with text', () => (
<Button onPress={action('clicked-text')}>
<Text>Hello Button</Text>
</Button>
))
.add('with some emoji', () => (
<Button onPress={action('clicked-emoji')}>
<Text>π π π π―</Text>
</Button>
));
| lib/cli/generators/REACT_NATIVE/template/storybook/stories/index.js | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.00016851371037773788,
0.00016624898125883192,
0.0001644712610868737,
0.0001657619432080537,
0.0000016858718936418882
]
|
{
"id": 3,
"code_window": [
" />,\n",
" <Separator key=\"2\" />,\n",
" <IconButton active={!!grid} key=\"grid\" onClick={() => this.setState({ grid: !grid })}>\n",
" <Icons icon=\"grid\" />\n",
" </IconButton>,\n",
" <Fragment>\n",
" {toolList.map(t => (\n",
" <Fragment>{t.render()}</Fragment>\n",
" ))}\n",
" </Fragment>,\n",
" ]}\n",
" right={[\n",
" <Separator key=\"1\" />,\n",
" <IconButton key=\"full\" onClick={actions.toggleFullscreen}>\n",
" <Icons icon={options.isFullscreen ? 'cross' : 'expand'} />\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ...toolList.map((t, index) => <Fragment key={`t${index}`}>{t.render()}</Fragment>),\n"
],
"file_path": "lib/components/src/preview/preview.js",
"type": "replace",
"edit_start_line_idx": 110
} | import styles from './styles';
function getComponentSelector(component) {
// eslint-disable-next-line no-underscore-dangle
return component.__annotations__[0].selector;
}
function getTemplate(metadata) {
let tpl = '';
if (metadata.component) {
const selector = getComponentSelector(metadata.component);
tpl = `<${selector}></${selector}>`;
}
if (metadata.template) {
tpl = metadata.template;
}
return `
<div [ngStyle]="styles.style">
<div [ngStyle]="styles.innerStyle">
${tpl}
</div>
</div>`;
}
function getModuleMetadata(metadata) {
const { moduleMetadata, component } = metadata;
if (component && !moduleMetadata) {
return {
declarations: [metadata.component],
};
}
if (component && moduleMetadata) {
return {
...moduleMetadata,
declarations: [...moduleMetadata.declarations, metadata.component],
};
}
return moduleMetadata;
}
export default function(metadataFn) {
const metadata = metadataFn();
return {
...metadata,
template: getTemplate(metadata),
moduleMetadata: getModuleMetadata(metadata),
props: {
...metadata.props,
styles,
},
};
}
| addons/centered/src/angular.js | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.000168005601153709,
0.00016536707698833197,
0.00016241536650341004,
0.00016525070532225072,
0.0000017691336324787699
]
|
{
"id": 3,
"code_window": [
" />,\n",
" <Separator key=\"2\" />,\n",
" <IconButton active={!!grid} key=\"grid\" onClick={() => this.setState({ grid: !grid })}>\n",
" <Icons icon=\"grid\" />\n",
" </IconButton>,\n",
" <Fragment>\n",
" {toolList.map(t => (\n",
" <Fragment>{t.render()}</Fragment>\n",
" ))}\n",
" </Fragment>,\n",
" ]}\n",
" right={[\n",
" <Separator key=\"1\" />,\n",
" <IconButton key=\"full\" onClick={actions.toggleFullscreen}>\n",
" <Icons icon={options.isFullscreen ? 'cross' : 'expand'} />\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ...toolList.map((t, index) => <Fragment key={`t${index}`}>{t.render()}</Fragment>),\n"
],
"file_path": "lib/components/src/preview/preview.js",
"type": "replace",
"edit_start_line_idx": 110
} | !dist
| lib/cli/test/fixtures/ember-cli/.gitignore | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.000164406665135175,
0.000164406665135175,
0.000164406665135175,
0.000164406665135175,
0
]
|
{
"id": 4,
"code_window": [
" allowFullScreen\n",
" />\n",
" </S.Frame>\n",
" </Route>\n",
" {panelList.map(panel => (\n",
" <Route path={panel.route} startsWith hideOnly key={panel.key}>\n",
" {panel.render({ active: true })}\n",
" </Route>\n",
" ))}\n",
" </S.FrameWrap>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" {panelList.map((panel, index) => (\n",
" <Route path={panel.route || '/'} startsWith hideOnly key={panel.key || index}>\n"
],
"file_path": "lib/components/src/preview/preview.js",
"type": "replace",
"edit_start_line_idx": 146
} | import { window } from 'global';
import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import Events from '@storybook/core-events';
import { types } from '@storybook/addons';
import { IconButton, Toolbar, Separator } from './toolbar';
import Icons from '../icon/icon';
import { Route } from '../router/router';
import { TabButton, TabBar } from '../tabs/tabs';
import Zoom from './tools/zoom';
import { Grid, Background } from './tools/background';
import * as S from './components';
class IFrame extends Component {
shouldComponentUpdate() {
// this component renders an iframe, which gets updates via post-messages
return false;
}
render() {
const { id, title, src, allowFullScreen, ...rest } = this.props;
return (
<iframe
id={id}
title={title}
src={src}
allowFullScreen={allowFullScreen}
{...rest}
style={{ border: '0 none' }}
/>
);
}
}
IFrame.propTypes = {
id: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
src: PropTypes.string.isRequired,
allowFullScreen: PropTypes.bool.isRequired,
};
// eslint-disable-next-line react/no-multi-comp
class Preview extends Component {
state = {
zoom: 1,
grid: false,
};
shouldComponentUpdate({ location, toolbar, options }, { zoom, grid }) {
const { props, state } = this;
return (
options.isFullscreen !== props.options.isFullscreen ||
location !== props.location ||
toolbar !== props.toolbar ||
zoom !== state.zoom ||
grid !== state.grid
);
}
componentDidUpdate(prevProps) {
const { channel, location } = this.props;
const { location: prevLocation } = prevProps;
if (location && this.getStoryPath(location) !== this.getStoryPath(prevLocation)) {
channel.emit(Events.SET_CURRENT_STORY, { location });
}
}
getStoryPath = location => location.replace(/\/?.+\/(.+)/, '$1');
render() {
const { id, toolbar = true, location = '/', getElements, actions, options } = this.props;
const { zoom, grid } = this.state;
const panels = getElements(types.PANEL);
const toolbarHeight = toolbar ? 40 : 0;
const panelList = Object.entries(panels).map(([key, value]) => ({ ...value, key }));
const tabsList = [{ route: '/components/', title: 'Canvas', key: 'canvas' }].concat(
getElements(types.TAB)
);
const toolList = getElements(types.TOOL);
return (
<Fragment>
{toolbar ? (
<Toolbar
key="toolbar"
left={[
<TabBar key="tabs" scroll={false}>
{tabsList.map(t => (
<S.UnstyledLink
key={t.key}
to={location.replace(/^\/(components|info)\//, t.route)}
>
<TabButton>{t.title}</TabButton>
</S.UnstyledLink>
))}
</TabBar>,
<Separator key="1" />,
<Zoom
key="zoom"
current={zoom}
set={v => this.setState({ zoom: zoom * v })}
reset={() => this.setState({ zoom: 1 })}
/>,
<Separator key="2" />,
<IconButton active={!!grid} key="grid" onClick={() => this.setState({ grid: !grid })}>
<Icons icon="grid" />
</IconButton>,
<Fragment>
{toolList.map(t => (
<Fragment>{t.render()}</Fragment>
))}
</Fragment>,
]}
right={[
<Separator key="1" />,
<IconButton key="full" onClick={actions.toggleFullscreen}>
<Icons icon={options.isFullscreen ? 'cross' : 'expand'} />
</IconButton>,
<Separator key="2" />,
<IconButton key="opener" onClick={() => window.open(`iframe.html?path=${location}`)}>
<Icons icon="share" />
</IconButton>,
]}
/>
) : null}
<S.FrameWrap key="frame" offset={toolbarHeight}>
<Route path="components" startsWith hideOnly>
<S.Frame
style={{
width: `${100 * zoom}%`,
height: `${100 * zoom}%`,
transform: `scale(${1 / zoom})`,
}}
>
<Background id="storybook-preview-background">{grid ? <Grid /> : null}</Background>
<IFrame
id="storybook-preview-iframe"
title={id || 'preview'}
src={`iframe.html?path=${location}`}
allowFullScreen
/>
</S.Frame>
</Route>
{panelList.map(panel => (
<Route path={panel.route} startsWith hideOnly key={panel.key}>
{panel.render({ active: true })}
</Route>
))}
</S.FrameWrap>
</Fragment>
);
}
}
Preview.propTypes = {
id: PropTypes.string.isRequired,
toolbar: PropTypes.bool.isRequired,
channel: PropTypes.shape({
on: PropTypes.func,
emit: PropTypes.func,
removeListener: PropTypes.func,
}).isRequired,
location: PropTypes.string.isRequired,
getElements: PropTypes.func.isRequired,
options: PropTypes.shape({
isFullscreen: PropTypes.bool,
}).isRequired,
actions: PropTypes.shape({}).isRequired,
};
export { Preview };
| lib/components/src/preview/preview.js | 1 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.9857483506202698,
0.05521043390035629,
0.00016235202201642096,
0.00018369947792962193,
0.22568942606449127
]
|
{
"id": 4,
"code_window": [
" allowFullScreen\n",
" />\n",
" </S.Frame>\n",
" </Route>\n",
" {panelList.map(panel => (\n",
" <Route path={panel.route} startsWith hideOnly key={panel.key}>\n",
" {panel.render({ active: true })}\n",
" </Route>\n",
" ))}\n",
" </S.FrameWrap>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" {panelList.map((panel, index) => (\n",
" <Route path={panel.route || '/'} startsWith hideOnly key={panel.key || index}>\n"
],
"file_path": "lib/components/src/preview/preview.js",
"type": "replace",
"edit_start_line_idx": 146
} | import { document } from 'global';
/**
* Not all frameworks support an object for the style attribute but we want all to
* consume `styles.json`. Since `styles.json` uses standard style properties for keys,
* we can just set them on an element and then get the string result of that element's
* `style` attribute. This also means that invalid styles are filtered out.
*
* @param {Object} jsonStyles
* @returns {string}
* @see https://stackoverflow.com/questions/38533544/jsx-css-to-inline-styles
*/
export default function jsonToCss(jsonStyles) {
const frag = document.createElement('div');
Object.keys(jsonStyles).forEach(key => {
frag.style[key] = jsonStyles[key];
});
return frag.getAttribute('style');
}
| addons/centered/src/helpers/json2CSS.js | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.00017263360496144742,
0.00017057657532859594,
0.00016836289432831109,
0.00017073321214411408,
0.000001747025066833885
]
|
{
"id": 4,
"code_window": [
" allowFullScreen\n",
" />\n",
" </S.Frame>\n",
" </Route>\n",
" {panelList.map(panel => (\n",
" <Route path={panel.route} startsWith hideOnly key={panel.key}>\n",
" {panel.render({ active: true })}\n",
" </Route>\n",
" ))}\n",
" </S.FrameWrap>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" {panelList.map((panel, index) => (\n",
" <Route path={panel.route || '/'} startsWith hideOnly key={panel.key || index}>\n"
],
"file_path": "lib/components/src/preview/preview.js",
"type": "replace",
"edit_start_line_idx": 146
} | import { document } from 'global';
const riotForStorybook = require.requireActual('@storybook/riot');
function bootstrapADocumentAndReturnANode() {
const rootElement = document.createElement('div');
rootElement.id = 'root';
document.body = document.createElement('body');
document.body.appendChild(rootElement);
return rootElement;
}
function makeSureThatResultIsRenderedSomehow({ context, result, rootElement }) {
if (!rootElement.firstChild) {
riotForStorybook.render({
story: () => result,
selectedKind: context.kind,
selectedStory: context.story,
});
}
}
function getRenderedTree(story, context) {
const rootElement = bootstrapADocumentAndReturnANode();
const result = story.render(context);
makeSureThatResultIsRenderedSomehow({ context, result, rootElement });
return rootElement;
}
export default getRenderedTree;
| addons/storyshots/storyshots-core/src/frameworks/riot/renderTree.js | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.0001752651296555996,
0.00017338834004476666,
0.00017164109158329666,
0.00017332355491816998,
0.0000013969132623969926
]
|
{
"id": 4,
"code_window": [
" allowFullScreen\n",
" />\n",
" </S.Frame>\n",
" </Route>\n",
" {panelList.map(panel => (\n",
" <Route path={panel.route} startsWith hideOnly key={panel.key}>\n",
" {panel.render({ active: true })}\n",
" </Route>\n",
" ))}\n",
" </S.FrameWrap>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" {panelList.map((panel, index) => (\n",
" <Route path={panel.route || '/'} startsWith hideOnly key={panel.key || index}>\n"
],
"file_path": "lib/components/src/preview/preview.js",
"type": "replace",
"edit_start_line_idx": 146
} | import React from 'react';
import nestedObjectAssign from 'nested-object-assign';
import deprecate from 'util-deprecate';
import { makeDecorator } from '@storybook/addons';
import { logger } from '@storybook/client-logger';
import Story from './components/Story';
import PropTable from './components/PropTable';
import makeTableComponent from './components/makeTableComponent';
import { H1, H2, H3, H4, H5, H6, Code, P, UL, A, LI } from './components/markdown';
const defaultOptions = {
inline: false,
header: true,
source: true,
propTables: [],
TableComponent: PropTable,
maxPropsIntoLine: 3,
maxPropObjectKeys: 3,
maxPropArrayLength: 3,
maxPropStringLength: 50,
};
const defaultComponents = {
h1: H1,
h2: H2,
h3: H3,
h4: H4,
h5: H5,
h6: H6,
code: Code,
p: P,
a: A,
li: LI,
ul: UL,
};
let hasWarned = false;
function addInfo(storyFn, context, infoOptions) {
const options = {
...defaultOptions,
...infoOptions,
};
// props.propTables can only be either an array of components or null
// propTables option is allowed to be set to 'false' (a boolean)
// if the option is false, replace it with null to avoid react warnings
if (!options.propTables) {
options.propTables = null;
}
const components = { ...defaultComponents };
if (options && options.components) {
Object.assign(components, options.components);
}
if (options && options.marksyConf) {
if (!hasWarned) {
logger.warn('@storybook/addon-info: "marksyConf" option has been renamed to "components"');
hasWarned = true;
}
Object.assign(components, options.marksyConf);
}
const props = {
info: options.text,
context,
showInline: Boolean(options.inline),
showHeader: Boolean(options.header),
showSource: Boolean(options.source),
styles:
typeof options.styles === 'function'
? options.styles
: s => nestedObjectAssign({}, s, options.styles),
propTables: options.propTables,
propTablesExclude: options.propTablesExclude,
PropTable: makeTableComponent(options.TableComponent),
components,
maxPropObjectKeys: options.maxPropObjectKeys,
maxPropArrayLength: options.maxPropArrayLength,
maxPropsIntoLine: options.maxPropsIntoLine,
maxPropStringLength: options.maxPropStringLength,
excludedPropTypes: options.excludedPropTypes,
};
return <Story {...props}>{storyFn(context)}</Story>;
}
export const withInfo = makeDecorator({
name: 'withInfo',
parameterName: 'info',
allowDeprecatedUsage: true,
wrapper: (getStory, context, { options, parameters }) => {
const storyOptions = parameters || options;
const infoOptions = typeof storyOptions === 'string' ? { text: storyOptions } : storyOptions;
const mergedOptions =
typeof infoOptions === 'string' ? infoOptions : { ...options, ...infoOptions };
return addInfo(getStory, context, mergedOptions);
},
});
export { Story };
export function setDefaults(newDefaults) {
return deprecate(
() => Object.assign(defaultOptions, newDefaults),
'setDefaults is deprecated. Instead, you can pass options into withInfo(options) directly, or use the info parameter.'
)();
}
| addons/info/src/index.js | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.00017800735076889396,
0.00017253828991670161,
0.00016388061339966953,
0.0001740447769407183,
0.000004524917130765971
]
|
{
"id": 5,
"code_window": [
" selectedStory: name,\n",
" forceRender,\n",
" });\n",
" addons.getChannel().emit(Events.STORY_RENDERED, storyStore.getSelection());\n",
" } else {\n",
" showNopreview();\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" addons.getChannel().emit(Events.STORY_RENDERED, storyStore.getSelection().id);\n"
],
"file_path": "lib/core/src/client/preview/start.js",
"type": "replace",
"edit_start_line_idx": 138
} | import addons from '@storybook/addons';
import { navigator, window, document } from 'global';
import createChannel from '@storybook/channel-postmessage';
import { handleKeyboardShortcuts } from '@storybook/ui/dist/libs/key_events';
import { logger } from '@storybook/client-logger';
import Events from '@storybook/core-events';
import StoryStore from './story_store';
import ClientApi from './client_api';
import ConfigApi from './config_api';
const classes = {
MAIN: 'sb-show-main',
NOPREVIEW: 'sb-show-nopreview',
ERROR: 'sb-show-errordisplay',
};
function showMain() {
document.body.classList.remove(classes.NOPREVIEW);
document.body.classList.remove(classes.ERROR);
document.body.classList.add(classes.MAIN);
}
function showNopreview() {
document.body.classList.remove(classes.MAIN);
document.body.classList.remove(classes.ERROR);
document.body.classList.add(classes.NOPREVIEW);
}
function showErrorDisplay({ message, stack }) {
document.getElementById('error-message').textContent = message;
document.getElementById('error-stack').textContent = stack;
document.body.classList.remove(classes.MAIN);
document.body.classList.remove(classes.NOPREVIEW);
document.body.classList.add(classes.ERROR);
}
// showError is used by the various app layers to inform the user they have done something
// wrong -- for instance returned the wrong thing from a story
function showError({ title, description }) {
addons.getChannel().emit(Events.STORY_ERRORED, { title, description });
showErrorDisplay({
message: title,
stack: description,
});
}
// showException is used if we fail to render the story and it is uncaught by the app layer
function showException(exception) {
addons.getChannel().emit(Events.STORY_THREW_EXCEPTION, exception);
showErrorDisplay(exception);
// Log the stack to the console. So, user could check the source code.
logger.error(exception.stack);
}
const isBrowser =
navigator &&
navigator.userAgent &&
navigator.userAgent !== 'storyshots' &&
!(navigator.userAgent.indexOf('Node.js') > -1) &&
!(navigator.userAgent.indexOf('jsdom') > -1);
const getContext = (() => {
let cache;
return decorateStory => {
if (cache) {
return cache;
}
let channel = null;
if (isBrowser) {
try {
channel = addons.getChannel();
} catch (e) {
channel = createChannel({ page: 'preview' });
addons.setChannel(channel);
}
}
const storyStore = new StoryStore({ channel });
const clientApi = new ClientApi({ storyStore, decorateStory });
const { clearDecorators } = clientApi;
const configApi = new ConfigApi({ clearDecorators, storyStore, channel, clientApi });
return {
configApi,
storyStore,
channel,
clientApi,
showMain,
showError,
showException,
};
};
})();
export default function start(render, { decorateStory } = {}) {
const context = getContext(decorateStory);
const { clientApi, channel, configApi, storyStore } = context;
// Provide access to external scripts if `window` is defined.
// NOTE this is different to isBrowser, primarily for the JSDOM use case
let previousKind = '';
let previousStory = '';
let previousRevision = -1;
const renderMain = forceRender => {
const revision = storyStore.getRevision();
const { kind, name, story } = storyStore.getSelection() || {};
if (story) {
// Render story only if selectedKind or selectedStory have changed.
// However, we DO want the story to re-render if the store itself has changed
// (which happens at the moment when HMR occurs)
if (
!forceRender &&
revision === previousRevision &&
kind === previousKind &&
previousStory === name
) {
return;
}
if (!forceRender) {
// Scroll to top of the page when changing story
document.documentElement.scrollTop = 0;
}
render({
...context,
story,
selectedKind: kind,
selectedStory: name,
forceRender,
});
addons.getChannel().emit(Events.STORY_RENDERED, storyStore.getSelection());
} else {
showNopreview();
addons.getChannel().emit(Events.STORY_MISSING, storyStore.getSelection());
}
previousRevision = revision;
previousKind = kind;
previousStory = name;
};
// initialize the UI
const renderUI = forceRender => {
if (isBrowser) {
try {
renderMain(forceRender);
} catch (ex) {
showException(ex);
}
}
};
const forceReRender = () => renderUI(true);
// channel can be null in NodeJS
if (isBrowser) {
channel.on(Events.FORCE_RE_RENDER, forceReRender);
channel.on(Events.SET_CURRENT_STORY, ({ location }) => {
if (!location) {
throw new Error('should have location');
}
const data = storyStore.fromPath(location);
console.log('here', location);
storyStore.setSelection(data);
storyStore.setPath(location);
});
// Handle keyboard shortcuts
window.onkeydown = handleKeyboardShortcuts(channel);
}
storyStore.on(Events.STORY_RENDER, renderUI);
if (typeof window !== 'undefined') {
window.__STORYBOOK_CLIENT_API__ = clientApi;
window.__STORYBOOK_ADDONS_CHANNEL__ = channel; // may not be defined
}
return { context, clientApi, configApi, forceReRender };
}
| lib/core/src/client/preview/start.js | 1 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.7266218662261963,
0.042467642575502396,
0.0001613524364074692,
0.0006029744981788099,
0.16167399287223816
]
|
{
"id": 5,
"code_window": [
" selectedStory: name,\n",
" forceRender,\n",
" });\n",
" addons.getChannel().emit(Events.STORY_RENDERED, storyStore.getSelection());\n",
" } else {\n",
" showNopreview();\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" addons.getChannel().emit(Events.STORY_RENDERED, storyStore.getSelection().id);\n"
],
"file_path": "lib/core/src/client/preview/start.js",
"type": "replace",
"edit_start_line_idx": 138
} | import { location } from 'global';
import addons from '@storybook/addons';
import { ADDON_ID, EVENT_ID, REQUEST_HREF_EVENT_ID, RECEIVE_HREF_EVENT_ID } from '.';
export function register() {
addons.register(ADDON_ID, api => {
const channel = addons.getChannel();
channel.on(EVENT_ID, selection => {
if (selection.kind != null) {
api.selectStory(selection.kind, selection.story);
} else {
api.selectInCurrentKind(selection.story);
}
});
channel.on(REQUEST_HREF_EVENT_ID, selection => {
const params =
selection.kind != null
? {
selectedKind: selection.kind,
selectedStory: selection.story,
}
: {
selectedStory: selection.story,
};
const urlState = api.getUrlState(params);
channel.emit(RECEIVE_HREF_EVENT_ID, location.pathname + urlState.url);
});
});
}
| addons/links/src/manager.js | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.005241638049483299,
0.001560949720442295,
0.00017640234727878124,
0.000412879278883338,
0.0021335205528885126
]
|
{
"id": 5,
"code_window": [
" selectedStory: name,\n",
" forceRender,\n",
" });\n",
" addons.getChannel().emit(Events.STORY_RENDERED, storyStore.getSelection());\n",
" } else {\n",
" showNopreview();\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" addons.getChannel().emit(Events.STORY_RENDERED, storyStore.getSelection().id);\n"
],
"file_path": "lib/core/src/client/preview/start.js",
"type": "replace",
"edit_start_line_idx": 138
} | /* eslint-disable import/extensions */
import hbs from 'htmlbars-inline-precompile';
import { storiesOf } from '@storybook/ember';
import { action } from '@storybook/addon-actions';
import { linkTo } from '@storybook/addon-links';
storiesOf('Welcome', module).add('to Storybook', () => ({
template: hbs`
<div>
<h3> Welcome to Storybook! </h3>
<button {{action onClick}}> Checkout the button example </button>
</div>
`,
context: {
onClick: linkTo('Button'),
},
}));
storiesOf('Button', module)
.add('with text', () => ({
template: hbs`<button {{action onClick}}>Hello Button</button>`,
context: {
onClick: action('clicked'),
},
}))
.add('with some emoji', () => ({
template: hbs`
<button {{action onClick}}>
<span role="img" aria-label="so cool">
π π π π―
</span>
</button>
`,
context: {
onClick: action('clicked'),
},
}));
| lib/cli/generators/EMBER/template/stories/index.stories.js | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.00017558209947310388,
0.00017271985416300595,
0.00016672922356519848,
0.00017428406863473356,
0.000003499452532196301
]
|
{
"id": 5,
"code_window": [
" selectedStory: name,\n",
" forceRender,\n",
" });\n",
" addons.getChannel().emit(Events.STORY_RENDERED, storyStore.getSelection());\n",
" } else {\n",
" showNopreview();\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" addons.getChannel().emit(Events.STORY_RENDERED, storyStore.getSelection().id);\n"
],
"file_path": "lib/core/src/client/preview/start.js",
"type": "replace",
"edit_start_line_idx": 138
} | export {
storiesOf,
setAddon,
addDecorator,
addParameters,
configure,
getStorybook,
forceReRender,
} from './preview';
| app/marko/src/client/index.js | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.00017304957145825028,
0.00017304957145825028,
0.00017304957145825028,
0.00017304957145825028,
0
]
|
{
"id": 6,
"code_window": [
" } else {\n",
" showNopreview();\n",
" addons.getChannel().emit(Events.STORY_MISSING, storyStore.getSelection());\n",
" }\n",
" previousRevision = revision;\n",
" previousKind = kind;\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" addons.getChannel().emit(Events.STORY_MISSING);\n"
],
"file_path": "lib/core/src/client/preview/start.js",
"type": "replace",
"edit_start_line_idx": 141
} | import { inject } from 'mobx-react';
import AddonPanel from '../components/panel/panel';
export function mapper({ store, uiStore }) {
return {
panels: store.panels,
selectedPanel: store.selectedPanel,
panelPosition: uiStore.panelPosition,
actions: {
onSelect: panel => store.selectPanel(panel),
toggleVisibility: () => uiStore.togglePanel(),
togglePosition: () => uiStore.togglePanelPosition(),
},
};
}
export default inject(({ store, uiStore }) => mapper({ store, uiStore }))(AddonPanel);
| lib/ui/src/containers/panel.js | 1 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.00017604863387532532,
0.00017436392954550683,
0.00017267921066377312,
0.00017436392954550683,
0.0000016847116057761014
]
|
{
"id": 6,
"code_window": [
" } else {\n",
" showNopreview();\n",
" addons.getChannel().emit(Events.STORY_MISSING, storyStore.getSelection());\n",
" }\n",
" previousRevision = revision;\n",
" previousKind = kind;\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" addons.getChannel().emit(Events.STORY_MISSING);\n"
],
"file_path": "lib/core/src/client/preview/start.js",
"type": "replace",
"edit_start_line_idx": 141
} | import { configure } from '@storybook/react';
const req = require.context('../stories/required_with_context', true, /.stories.js$/);
function loadStories() {
req.keys().forEach(filename => req(filename));
require('../stories/directly_required');
}
configure(loadStories, module);
| addons/storyshots/storyshots-core/.storybook/config.js | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.00017684290651232004,
0.00017506256699562073,
0.00017328221292700619,
0.00017506256699562073,
0.0000017803467926569283
]
|
{
"id": 6,
"code_window": [
" } else {\n",
" showNopreview();\n",
" addons.getChannel().emit(Events.STORY_MISSING, storyStore.getSelection());\n",
" }\n",
" previousRevision = revision;\n",
" previousKind = kind;\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" addons.getChannel().emit(Events.STORY_MISSING);\n"
],
"file_path": "lib/core/src/client/preview/start.js",
"type": "replace",
"edit_start_line_idx": 141
} | // Icon paths
const icons = {
mobile:
'M648 64h-272c-66.274 0-120 53.726-120 120v656c0 66.274 53.726 120 120 120h272c66.274 0 120-53.726 120-120v-656c0-66.274-53.726-120-120-120zM376 144h272c22.056 0 40 17.944 40 40v495.968h-352v-495.968c0-22.056 17.946-40 40-40zM648 880h-272c-22.054 0-40-17.944-40-40v-80.032h352v80.032c0 22.056-17.944 40-40 40zM544.034 819.962c0 17.676-14.33 32.002-32.004 32.002-17.67 0-32-14.326-32-32.002 0-17.672 14.33-31.998 32-31.998 17.674-0 32.004 14.326 32.004 31.998z',
watch:
'M736.172 108.030c0-11.044-8.956-20-20-20h-408.282c-11.044 0-20 8.956-20 20 0 11.046 8.956 20 20 20h408.282c11.044 0 20-8.954 20-20zM736.172 50.37c0-11.044-8.956-20-20-20h-408.282c-11.044 0-20 8.956-20 20s8.956 20 20 20h408.282c11.044 0 20-8.956 20-20zM736.172 973.692c0-11.044-8.956-20-20-20h-408.282c-11.044 0-20 8.956-20 20s8.956 20 20 20h408.282c11.044 0 20-8.956 20-20zM736.172 916.030c0-11.044-8.956-20-20-20h-408.282c-11.044 0-20 8.956-20 20 0 11.046 8.956 20 20 20h408.282c11.044 0 20-8.954 20-20zM717.53 228c18.904 0 34.286 15.14 34.286 33.75v500.502c0 18.61-15.38 33.75-34.286 33.75h-411.43c-18.904 0-34.286-15.14-34.286-33.75v-500.502c0-18.61 15.38-33.75 34.286-33.75h411.43zM717.53 148h-411.43c-63.118 0-114.286 50.928-114.286 113.75v500.502c0 62.822 51.166 113.75 114.286 113.75h411.43c63.118 0 114.286-50.926 114.286-113.75v-500.502c-0.002-62.822-51.168-113.75-114.286-113.75v0zM680.036 511.53c0 22.090-17.91 40-40 40h-128.004c-5.384 0-10.508-1.078-15.196-3.006-0.124-0.048-0.254-0.086-0.376-0.132-0.61-0.262-1.188-0.57-1.782-0.86-0.572-0.276-1.16-0.528-1.718-0.828-0.204-0.112-0.39-0.246-0.594-0.364-0.918-0.514-1.832-1.050-2.704-1.64-0.086-0.058-0.164-0.128-0.254-0.188-10.492-7.21-17.382-19.284-17.382-32.98v-151.5c0-22.094 17.91-40 40.004-40 22.088 0 40 17.906 40 40v111.498h88c22.094-0.002 40.002 17.91 40.006 40z',
tablet:
'M200.022 927.988h624.018c1.38 0 2.746-0.072 4.090-0.208 20.168-2.050 35.91-19.080 35.91-39.792v-751.916c0-22.092-17.91-40-40-40h-624.018c-22.098 0-40 17.908-40 40v751.916c0 22.094 17.906 40 40 40zM512.002 878.206c-17.674 0-32.004-14.328-32.004-31.998 0-17.678 14.33-32.002 32.004-32.002 17.67 0 32 14.324 32 32.002 0 17.67-14.33 31.998-32 31.998zM240.022 176.078h544.018v591.902h-544.018v-591.902z',
browser:
'M920.004 128h-816.008c-1.38 0-2.746 0.070-4.090 0.208-20.168 2.048-35.91 19.080-35.91 39.792v688c0 22.090 17.91 40 40 40h816.008c22.098 0 40-17.91 40-40v-688c-0-22.094-17.906-40-40-40zM368 177.78c17.674 0 32.004 14.328 32.004 31.998 0 17.676-14.33 32.002-32.004 32.002-17.67 0-32-14.326-32-32.002 0-17.67 14.33-31.998 32-31.998zM272 177.78c17.674 0 32.004 14.328 32.004 31.998 0 17.676-14.33 32.002-32.004 32.002-17.67 0-32-14.326-32-32.002 0-17.67 14.33-31.998 32-31.998zM176 177.78c17.674 0 32.004 14.328 32.004 31.998 0 17.676-14.33 32.002-32.004 32.002-17.67 0-32-14.326-32-32.002 0-17.67 14.33-31.998 32-31.998zM880.004 815.996h-736.008v-527.988h736.008v527.988z',
sidebar:
'M920.032 127.858h-816c-22.092 0-40 17.908-40 40v688c0 22.092 17.908 40 40 40h316.578c1.13 0.096 2.266 0.172 3.422 0.172s2.292-0.078 3.424-0.172h492.576c22.092 0 40-17.908 40-40v-688c0-22.092-17.908-40-40-40zM144.032 207.858h240v608h-240v-608zM880.032 815.858h-416v-608h416v608zM198.734 288.030c0-17.674 14.328-32 32.002-32h66.396c17.672 0 32 14.326 32 32 0 17.676-14.324 32-32 32h-66.398c-17.674 0-32-14.326-32-32zM198.734 416.030c0-17.674 14.328-32 32.002-32h66.396c17.672 0 32 14.326 32 32 0 17.676-14.324 32-32 32h-66.398c-17.674 0-32-14.326-32-32zM198.734 544.030c0-17.674 14.328-32 32.002-32h66.396c17.672 0 32 14.326 32 32 0 17.676-14.324 32-32 32h-66.398c-17.674 0-32-14.326-32-32z',
sidebaralt:
'M64 167.944v688c0 22.092 17.908 40 40 40h816c22.092 0 40-17.908 40-40v-688c0-22.092-17.908-40-40-40h-816c-22.092 0-40 17.908-40 40zM880 815.944h-240v-608h240v608zM144 207.944h416v608h-416v-608zM793.296 320.118h-66.398c-17.676 0-32-14.324-32-32 0-17.674 14.328-32 32-32h66.396c17.674 0 32.002 14.326 32.002 32 0 17.672-14.324 32-32 32zM793.296 448.118h-66.398c-17.676 0-32-14.324-32-32 0-17.674 14.328-32 32-32h66.396c17.674 0 32.002 14.326 32.002 32 0 17.672-14.324 32-32 32zM793.296 576.118h-66.398c-17.676 0-32-14.324-32-32 0-17.674 14.328-32 32-32h66.396c17.674 0 32.002 14.326 32.002 32 0 17.672-14.324 32-32 32z',
bottombar:
'M85 121h854c24 0 42 18 42 41v700c0 23-18 41-42 41H608a44 44 0 0 1-7 0H85c-24 0-42-18-42-41V162c0-23 18-41 42-41zm41 535v165h772V656H126zm0-82h772V202H126v372zm185 197h-69c-19 0-34-14-34-32s15-33 34-33h69c19 0 34 15 34 33s-15 32-34 32zm236 0h-70c-18 0-33-14-33-32s15-33 33-33h70c18 0 33 15 33 33s-15 32-33 32zm235 0h-70c-18 0-33-14-33-32s15-33 33-33h70c18 0 33 15 33 33s-15 32-33 32z',
useralt:
'M532.716 960c115.572 0 227.634-22.612 333.076-67.208 18.116-7.66 35.888-15.94 53.336-24.774v-18.726c0-116.912-241.728-223.528-306.458-233.828-20.1-3.198-20.556-58.458-20.556-58.458s59.050-58.452 71.922-137.062c34.618 0 56.004-83.57 21.378-112.972 1.448-30.95 44.5-242.972-173.474-242.972-217.976 0-174.916 212.022-173.476 242.972-34.622 29.402-13.244 112.972 21.38 112.972 12.864 78.61 71.916 137.062 71.916 137.062s-0.458 55.262-20.554 58.458c-64.042 10.19-301.326 114.674-306.334 230.124 30.474 17.61 62.084 33.376 94.776 47.204 105.436 44.596 217.498 67.208 333.068 67.208z',
user:
'M512.062 65.062c-247.424 0-448 200.576-448 448s200.576 448 448 448 448-200.576 448-448-200.576-448-448-448zM776.324 769.132c-55.386-54.52-155.436-95.864-189.492-101.282-14.918-2.376-15.258-43.39-15.258-43.39s43.832-43.39 53.384-101.738c25.698 0 41.568-62.032 15.87-83.856 1.072-22.974 33.038-180.352-128.766-180.352s-129.836 157.376-128.768 180.352c-25.706 21.824-9.83 83.856 15.87 83.856 9.552 58.348 53.382 101.738 53.382 101.738s-0.34 41.020-15.256 43.39c-34.056 5.418-134.104 46.762-189.49 101.282-66.932-69.018-103.738-159.708-103.738-256.070 0-98.296 38.278-190.708 107.786-260.212 69.51-69.506 161.918-107.788 260.214-107.788s190.708 38.278 260.214 107.788c69.506 69.506 107.786 161.916 107.786 260.212-0 96.364-36.808 187.054-103.738 256.070z',
useradd:
'M123.302 833.14c-26.284-11.118-51.696-23.792-76.196-37.95 4.028-92.818 194.792-176.82 246.28-185.012 16.158-2.57 16.526-46.994 16.526-46.994s-47.476-46.996-57.818-110.196c-27.836 0-45.024-67.186-17.19-90.824-1.158-24.882-35.776-195.34 139.468-195.34 175.242 0 140.628 170.458 139.464 195.34 27.838 23.638 10.644 90.824-17.188 90.824-10.346 63.2-57.822 110.196-57.822 110.196s0.37 44.424 16.528 46.994c52.042 8.282 246.38 93.996 246.38 187.988v15.054c-14.028 7.102-28.316 13.76-42.88 19.918-84.77 35.852-174.864 54.032-267.78 54.032-92.912 0.002-183.004-18.178-267.772-54.030zM910.064 335h-80.008v-80.010c0.002-22.088-17.906-39.992-39.996-39.992-22.088 0-39.998 17.906-39.998 39.996v80.006h-80.002c-22.094 0-40 17.908-39.998 40-0.002 22.090 17.904 39.996 39.996 39.996h80.004v80.002c0 22.094 17.908 40 40 40 22.090 0 39.996-17.906 39.996-39.996v-80.006l80.010-0.002c22.090 0.002 39.994-17.906 39.994-39.996 0-22.088-17.908-39.998-39.998-39.998z',
users:
'M123.302 822.204c-26.284-11.118-51.696-23.792-76.196-37.95 4.028-92.818 194.792-176.82 246.28-185.012 16.158-2.57 16.526-46.998 16.526-46.998s-47.476-46.994-57.818-110.192c-27.836 0-45.024-67.186-17.19-90.822-1.158-24.884-35.776-195.342 139.468-195.342 175.242 0 140.628 170.458 139.464 195.342 27.838 23.636 10.644 90.822-17.188 90.822-10.346 63.2-57.822 110.192-57.822 110.192s0.37 44.426 16.528 46.998c52.042 8.282 246.38 93.996 246.38 187.988v15.054c-14.028 7.102-28.316 13.758-42.88 19.918-84.77 35.852-174.864 54.032-267.78 54.032-92.912 0-183.004-18.18-267.772-54.030zM977.018 652.224c0-64.612-133.592-123.532-169.364-129.222-11.106-1.768-11.36-32.306-11.36-32.306s32.634-32.304 39.744-75.746c19.132 0 30.954-46.188 11.818-62.436 0.798-17.106 24.592-134.276-95.874-134.276-120.462 0-96.666 117.17-95.87 134.276-19.134 16.248-7.32 62.436 11.816 62.436 7.11 43.442 39.742 75.746 39.742 75.746s-0.25 30.54-11.358 32.306c-23.154 3.684-87.282 29.672-129.644 65.068 21.022 10.038 42.072 21.39 61.066 33.186 14.278 8.866 27.392 17.866 39.338 26.986 35.696 27.262 60.956 55.638 75.646 84.934 2.784 0.032 5.562 0.102 8.352 0.102 77.788 0 153.58-12.792 225.944-37.976v-43.078z',
profile:
'M396.984 530.228c-12.040-5.090-23.676-10.896-34.898-17.38 1.846-42.512 89.218-80.984 112.798-84.736 7.402-1.178 7.568-21.526 7.568-21.526s-21.742-21.524-26.48-50.47c-12.748 0-20.622-30.77-7.874-41.596-0.532-11.398-16.384-89.468 63.878-89.468s64.408 78.070 63.876 89.468c12.75 10.826 4.876 41.596-7.872 41.596-4.738 28.948-26.482 50.47-26.482 50.47s0.168 20.348 7.568 21.526c23.836 3.792 112.846 43.050 112.846 86.102v6.894c-6.426 3.252-12.968 6.3-19.64 9.122-38.826 16.422-80.090 24.746-122.646 24.746-42.552-0.002-83.816-8.326-122.642-24.748zM800 145h-592.004v736h592.004c8.708 0 15.876-7.086 15.972-15.796v-704.246c-0.018-8.8-7.176-15.958-15.972-15.958zM800 65c52.944 0 95.872 42.858 95.992 95.772l0.012 0.014v705.334h-0.036c-0.602 52.502-43.324 94.88-95.968 94.88h-632.004c-22.090 0-40-17.906-40-40v-816c0-20.338 15.192-37.090 34.836-39.628 1.696-0.218 3.41-0.372 5.164-0.372h632.004zM736.282 792.998c0-11.044-8.956-20-20-20h-408.282c-11.044 0-20 8.956-20 20s8.956 20 20 20h408.282c11.044 0 20-8.956 20-20zM736.282 704.998c0-11.044-8.956-20-20-20h-408.282c-11.044 0-20 8.956-20 20s8.956 20 20 20h408.282c11.044 0 20-8.956 20-20zM736.282 616.998c0-11.044-8.956-20-20-20h-408.282c-11.044 0-20 8.956-20 20s8.956 20 20 20h408.282c11.044 0 20-8.956 20-20z',
bookmark:
'M772 1012L511 761l-260 251a49 49 0 0 1-52 10c-18-7-29-24-29-43V132c0-25 21-46 47-46h588c26 0 47 21 47 46v847c0 19-11 36-29 43a49 49 0 0 1-51-10z',
bookmarkhollow:
'M772 1012L511 761l-260 251a49 49 0 0 1-52 10c-18-7-29-24-29-43V132c0-25 21-46 47-46h588c26 0 47 21 47 46v847c0 19-11 36-29 43a49 49 0 0 1-51-10zM545 664l213 205V181H265v688l213-205c9-9 21-14 33-14s24 5 34 14z',
book:
'M896.054 159.774c-0.122-52.914-43.048-95.774-95.992-95.774h-632.004c-1.754 0-3.468 0.154-5.164 0.372-19.644 2.54-34.836 19.292-34.836 39.628v816c0 22.094 17.91 40 40 40h632.004c52.642 0 95.368-42.378 95.968-94.88h0.036v-705.332l-0.012-0.014zM368.062 144h80v271.922l-11.728-11.718c-15.62-15.606-40.924-15.606-56.542 0l-11.728 11.718v-271.922zM816.036 864.204c-0.1 8.712-7.268 15.796-15.972 15.796h-592.004v-736h80.004v368.426c0 16.176 9.742 30.758 24.684 36.954 14.944 6.192 32.146 2.778 43.586-8.656l51.728-51.68 51.728 51.68c7.652 7.644 17.876 11.708 28.28 11.708 5.156 0 10.356-1 15.306-3.050 14.944-6.196 24.684-20.778 24.684-36.954v-368.428h272c8.796 0 15.972 7.16 15.992 15.958l-0.016 704.246z',
repository:
'M856.020 159.804c-0.122-52.916-43.048-95.774-95.992-95.774h-591.968c-1.754 0-3.468 0.154-5.164 0.37-19.644 2.54-34.836 19.292-34.836 39.63v784.584c0 22.094 17.91 40 40 40h151.972v63.594c0 10.876 6.548 20.682 16.598 24.844 10.046 4.164 21.612 1.87 29.304-5.818l34.78-34.748 34.78 34.748c5.144 5.14 12.020 7.87 19.014 7.87 3.466 0 6.962-0.672 10.292-2.052 10.048-4.164 16.598-13.968 16.598-24.844v-63.594h278.63c52.642 0 95.368-42.38 95.968-94.882h0.036v-673.916l-0.012-0.012zM776.020 159.988l-0.014 504.628h-519.974v-520.584h503.996c8.796-0 15.972 7.158 15.992 15.956zM760.028 848.616h-278.63v-56h-161.366v56h-111.972v-104h567.944l-0.002 88.204c-0.102 8.71-7.27 15.796-15.974 15.796zM320.032 240.396c0-17.67 14.328-31.998 31.998-31.998s32.002 14.326 32.002 31.998c0 17.674-14.332 32-32.002 32-17.672-0.002-31.998-14.326-31.998-32zM320.032 349.79c0-17.67 14.328-31.998 31.998-31.998s32.002 14.328 32.002 31.998c0 17.676-14.332 32-32.002 32-17.672 0-31.998-14.324-31.998-32zM320.032 459.188c0-17.67 14.328-32 31.998-32s32.002 14.328 32.002 32c0 17.674-14.332 31.998-32.002 31.998-17.672 0-31.998-14.324-31.998-31.998zM384.032 568.582c0 17.674-14.332 31.998-32.002 31.998s-31.998-14.324-31.998-31.998c0-17.67 14.328-32 31.998-32 17.67 0.002 32.002 14.33 32.002 32z',
star:
'M763.972 919.5c-6.368 0-12.758-1.518-18.61-4.596l-233.358-122.688-233.37 122.688c-13.476 7.090-29.808 5.904-42.124-3.042-12.318-8.95-18.486-24.118-15.912-39.124l44.57-259.856-188.792-184.028c-10.904-10.626-14.828-26.524-10.124-41.004s17.222-25.034 32.292-27.222l260.906-37.912 116.686-236.42c6.738-13.652 20.644-22.296 35.87-22.296v0c15.226 0 29.13 8.644 35.87 22.298l116.674 236.418 260.906 37.912c15.068 2.19 27.586 12.742 32.292 27.222s0.782 30.376-10.124 41.004l-188.792 184.028 44.24 257.93c0.62 2.796 0.946 5.704 0.946 8.688 0 22.054-17.848 39.942-39.888 40-0.054 0-0.106 0-0.158 0z',
starhollow:
'M763.972 919.5c-6.368 0-12.758-1.518-18.61-4.596l-233.358-122.688-233.37 122.688c-13.476 7.090-29.808 5.904-42.124-3.042-12.318-8.95-18.486-24.118-15.912-39.124l44.57-259.856-188.792-184.028c-10.904-10.626-14.828-26.524-10.124-41.004s17.222-25.034 32.292-27.222l260.906-37.912 116.686-236.42c6.738-13.652 20.644-22.296 35.87-22.296v0c15.226 0 29.13 8.644 35.87 22.298l116.674 236.418 260.906 37.912c15.068 2.19 27.586 12.742 32.292 27.222s0.782 30.376-10.124 41.004l-188.792 184.028 44.24 257.93c0.62 2.796 0.946 5.704 0.946 8.688 0 22.054-17.848 39.942-39.888 40-0.054 0-0.106 0-0.158 0zM190.256 428.144l145.812 142.13c9.428 9.192 13.73 22.432 11.504 35.406l-34.424 200.7 180.244-94.758c11.654-6.13 25.576-6.126 37.226 0l180.232 94.756-34.422-200.698c-2.226-12.974 2.076-26.214 11.504-35.406l145.812-142.13-201.51-29.282c-13.030-1.892-24.292-10.076-30.118-21.882l-90.114-182.596-90.122 182.598c-5.826 11.804-17.090 19.988-30.118 21.88l-201.506 29.282z',
circle:
'M960 512c0 247.424-200.576 448-448 448s-448-200.576-448-448c0-247.424 200.576-448 448-448s448 200.576 448 448z',
circlehollow:
'M960 513c0-247.424-200.574-448-448-448-247.422 0-448 200.576-448 448s200.578 448 448 448c247.426 0 448-200.576 448-448zM251.786 773.216c-69.504-69.508-107.786-161.918-107.786-260.216 0-98.294 38.282-190.708 107.786-260.216 69.506-69.504 161.918-107.784 260.214-107.784s190.708 38.28 260.214 107.784c69.508 69.508 107.786 161.922 107.786 260.216 0 98.296-38.278 190.708-107.786 260.214-69.506 69.508-161.922 107.786-260.214 107.786-98.296 0-190.708-38.278-260.214-107.784z',
heart:
'M895.032 194.328c-20.906-21.070-46.492-37.316-76.682-48.938-30.104-11.71-63.986-17.39-101.474-17.39-19.55 0-38.744 2.882-57.584 9.094-18.472 6.062-36.584 14.242-54.072 24.246-17.476 9.828-34.056 21.276-49.916 33.898-16.038 12.8-30.456 25.572-43.346 38.664-13.52-13.092-28.026-25.864-43.616-38.664-15.684-12.624-32.080-24.070-49.382-33.898-17.214-10.004-35.414-18.184-54.704-24.246-19.104-6.21-38.568-9.094-58.034-9.094-37.126 0-70.56 5.68-100.48 17.39-29.732 11.622-55.328 27.868-76.328 48.938-20.994 21.094-37.214 46.962-48.478 77.328-11.174 30.544-16.942 64.5-16.942 101.812 0 21.628 3.068 43.078 9.19 64.53 6.308 21.096 14.416 41.986 24.876 61.642 10.446 19.656 22.702 38.488 36.584 56.59 13.88 18.124 28.388 34.516 43.344 49.58l305.766 305.112c8.466 7.558 18.11 11.444 28.204 11.444 10.726 0 19.914-3.884 27.308-11.444l305.934-304.226c14.78-14.772 29.382-31.368 43.166-49.378 14.058-18.212 26.314-37.222 37.042-57.23 10.9-19.924 19.192-40.638 25.406-62 6.218-21.188 9.198-42.61 9.198-64.618 0-37.312-5.592-71.268-16.582-101.812-11.264-30.366-27.22-56.236-48.398-77.33z',
hearthollow:
'M716.876 208c27.708 0 52.092 4.020 72.47 11.948l0.132 0.052 0.13 0.050c19.866 7.644 35.774 17.664 48.632 30.624l0.166 0.168 0.17 0.168c12.586 12.536 22.304 28.27 29.706 48.094 7.782 21.786 11.726 46.798 11.726 74.364 0 14.658-1.95 28.426-5.958 42.086l-0.028 0.092-0.026 0.092c-4.866 16.72-11.006 31.752-18.776 45.952l-0.162 0.298-0.16 0.296c-8.81 16.434-18.58 31.532-29.864 46.148l-0.204 0.264c-11.316 14.786-23.48 28.708-36.154 41.378l-277.122 275.574-276.94-276.35c-13.32-13.43-25.248-27.074-36.488-41.75-11.386-14.848-21.284-30.136-29.444-45.49-7.206-13.54-13.494-29.17-18.7-46.472-4.030-14.264-5.988-28.044-5.988-42.116 0-27.36 4.042-52.314 12.016-74.176 7.214-19.378 17.344-35.708 30.066-48.492 12.998-13.042 28.958-23.148 48.826-30.914 20.436-8 43.764-11.886 71.32-11.886 11.536 0 22.738 1.742 33.298 5.174l0.374 0.122 0.376 0.12c13.116 4.122 26.066 9.874 38.494 17.094l0.34 0.2 0.344 0.196c12.736 7.234 25.308 15.876 38.43 26.412 14.486 11.906 27.060 23.048 38.428 34.056l56.994 55.192 55.662-56.532c10.324-10.484 22.18-21.040 36.242-32.264 13.382-10.646 26.216-19.38 39.228-26.698l0.256-0.144 0.254-0.144c13.008-7.442 26.228-13.386 39.294-17.676l0.050-0.016 0.050-0.018c10.354-3.414 20.998-5.076 32.54-5.076zM716.876 128c-19.55 0-38.744 2.882-57.584 9.094-18.472 6.062-36.584 14.242-54.072 24.246-17.476 9.828-34.056 21.276-49.916 33.898-16.038 12.8-30.456 25.572-43.346 38.664-13.52-13.092-28.026-25.864-43.616-38.664-15.684-12.624-32.080-24.070-49.382-33.898-17.214-10.004-35.414-18.184-54.704-24.246-19.104-6.21-38.568-9.094-58.034-9.094-37.126 0-70.56 5.68-100.48 17.39-29.732 11.622-55.328 27.868-76.328 48.938-20.994 21.094-37.214 46.962-48.478 77.328-11.174 30.544-16.942 64.5-16.942 101.812 0 21.628 3.068 43.078 9.19 64.53 6.308 21.096 14.416 41.986 24.876 61.642 10.446 19.656 22.702 38.488 36.584 56.59 13.88 18.124 28.388 34.516 43.344 49.58l305.766 305.112c8.466 7.558 18.11 11.444 28.204 11.444 10.726 0 19.914-3.884 27.308-11.444l305.934-304.226c14.78-14.772 29.382-31.368 43.166-49.378 14.058-18.212 26.314-37.222 37.042-57.23 10.9-19.924 19.192-40.638 25.406-62 6.218-21.188 9.198-42.61 9.198-64.618 0-37.312-5.592-71.268-16.582-101.812-11.262-30.366-27.216-56.234-48.396-77.328-20.906-21.070-46.492-37.316-76.682-48.938-30.106-11.712-63.988-17.392-101.476-17.392v0z',
facehappy:
'M960 513c0-247.424-200.574-448-448-448-247.422 0-448 200.576-448 448s200.578 448 448 448c247.426 0 448-200.576 448-448zM251.786 773.214c-69.504-69.508-107.786-161.918-107.786-260.214 0-98.294 38.282-190.708 107.786-260.216 69.506-69.504 161.918-107.784 260.214-107.784s190.708 38.28 260.214 107.784c69.508 69.508 107.786 161.922 107.786 260.216 0 98.296-38.278 190.708-107.786 260.214-69.506 69.506-161.922 107.786-260.214 107.786-98.296 0-190.708-38.28-260.214-107.786zM416.5 384.998c0 35.346-28.654 64-64 64s-64-28.654-64-64 28.654-64 64-64 64 28.654 64 64zM736 384.998c0 35.346-28.654 64-64 64s-64-28.654-64-64 28.654-64 64-64 64 28.654 64 64zM763.62 636.976v0.094c-49.554 87.14-143.21 145.93-250.62 145.93-107.486 0-201.2-58.868-250.726-146.108v-0.092c-3.34-5.842-5.274-12.59-5.274-19.8s1.934-13.958 5.274-19.798v-0.198h0.122c6.918-11.946 19.808-20.004 34.606-20.004s27.69 8.058 34.61 20.004h0.098c35.756 63.222 103.614 105.996 181.29 105.996s145.54-42.774 181.3-105.996h0.090c6.918-11.946 19.81-20.004 34.606-20.004s27.69 8.058 34.61 20.004h0.014v0.024c3.402 5.88 5.38 12.69 5.38 19.972 0 7.286-1.978 14.094-5.38 19.976z',
facesad:
'M960 513c0-247.424-200.574-448-448-448-247.422 0-448 200.576-448 448s200.578 448 448 448c247.426 0 448-200.576 448-448zM251.786 773.214c-69.504-69.506-107.786-161.918-107.786-260.214 0-98.294 38.282-190.708 107.786-260.216 69.506-69.504 161.918-107.784 260.214-107.784s190.708 38.28 260.214 107.784c69.508 69.508 107.786 161.922 107.786 260.216 0 98.296-38.278 190.708-107.786 260.214-69.506 69.506-161.922 107.786-260.214 107.786-98.296 0-190.708-38.28-260.214-107.786zM416.5 384.998c0 35.346-28.654 64-64 64s-64-28.654-64-64 28.654-64 64-64 64 28.654 64 64zM736 384.998c0 35.346-28.654 64-64 64s-64-28.654-64-64 28.654-64 64-64 64 28.654 64 64zM262.38 684.024v-0.094c49.552-87.14 143.208-145.93 250.62-145.93 107.486 0 201.2 58.868 250.726 146.108v0.092c3.34 5.842 5.274 12.59 5.274 19.8s-1.934 13.958-5.274 19.798v0.198h-0.122c-6.918 11.946-19.808 20.004-34.606 20.004s-27.69-8.058-34.61-20.004h-0.098c-35.76-63.222-103.618-105.996-181.292-105.996s-145.54 42.774-181.3 105.996h-0.090c-6.918 11.946-19.808 20.004-34.606 20.004s-27.69-8.058-34.61-20.004h-0.014v-0.024c-3.402-5.88-5.38-12.69-5.38-19.972 0.002-7.286 1.98-14.094 5.382-19.976z',
faceneutral:
'M968 513c0-247.424-200.574-448-448-448-247.422 0-448 200.576-448 448s200.578 448 448 448c247.426 0 448-200.576 448-448zM259.786 773.214c-69.504-69.506-107.786-161.918-107.786-260.214 0-98.294 38.282-190.708 107.786-260.216 69.506-69.504 161.918-107.784 260.214-107.784s190.708 38.28 260.214 107.784c69.508 69.508 107.786 161.922 107.786 260.216 0 98.296-38.278 190.708-107.786 260.214-69.506 69.506-161.922 107.786-260.214 107.786-98.296 0-190.708-38.28-260.214-107.786zM424.5 384.998c0 35.346-28.654 64-64 64s-64-28.654-64-64 28.654-64 64-64 64 28.654 64 64zM744 384.998c0 35.346-28.654 64-64 64s-64-28.654-64-64 28.654-64 64-64 64 28.654 64 64zM777 641c0 22.094-17.906 40-40 40h-432c-22.090 0-40-17.906-40-40 0-22.090 17.91-40 40-40h432c22.094 0 40 17.91 40 40z',
lock:
'M896.032 915.53v-467.498c0-19.102-13.402-35.052-31.31-39.026-0.21-0.046-0.414-0.12-0.628-0.162-0.444-0.090-0.904-0.13-1.354-0.208-2.186-0.37-4.416-0.606-6.708-0.606h-55.902l0.002-55.85h0.020c0-159.14-129.010-288.15-288.15-288.15-159.128 0-288.13 128.992-288.15 288.118v55.884h-54.852c-20.71 0-37.746 15.742-39.792 35.91-0.136 1.344-0.208 2.708-0.208 4.090v463.332c-0.618 2.792-0.968 5.688-0.968 8.668 0 22.094 17.91 40 40 40h688.27c22.092 0 40-17.91 40-40-0.002-1.524-0.104-3.024-0.27-4.502zM209 488.032h607.032v392h-607.032v-392zM303.85 352.182c0-114.776 93.376-208.15 208.15-208.15 114.59 0 207.842 93.074 208.142 207.596 0 0.084-0.012 0.164-0.012 0.248v56.156h-416.284l0.004-55.85zM552.164 691.858l-0.002 58.188c0.004 22.088-17.906 39.996-39.996 39.998-22.094 0.002-40.004-17.906-40-40v-57.974c-14.704-11.726-24.134-29.782-24.134-50.048 0-35.346 28.654-64 64-64s64 28.654 64 64c0 20.142-9.318 38.104-23.868 49.836z',
unlock:
'M896.032 915.53v-467.498c0-1.988-0.194-3.926-0.472-5.834-0.11-0.744-0.192-1.498-0.34-2.226-1.524-7.44-5.136-14.1-10.164-19.408-0.252-0.266-0.48-0.554-0.738-0.814-0.496-0.494-1.036-0.944-1.554-1.412-0.43-0.386-0.84-0.8-1.288-1.17-0.292-0.24-0.608-0.446-0.904-0.676-2.506-1.954-5.244-3.616-8.176-4.934-0.744-0.334-1.504-0.632-2.27-0.922-4.39-1.656-9.124-2.604-14.094-2.604h-552.184l0.002-55.85c0-114.776 93.376-208.15 208.15-208.15 86.038 0 160.034 52.474 191.7 127.096 0.012 0.028 0.030 0.044 0.042 0.072 5.978 14.566 20.284 24.832 37.006 24.832 22.090 0 40-17.906 40-40 0-4.71-0.86-9.21-2.354-13.41-0.182-0.694-0.42-1.438-0.782-2.292-43.666-103.582-146.14-176.296-265.612-176.296-159.128 0-288.13 128.994-288.15 288.12v55.882h-54.85c-20.71 0-37.746 15.742-39.792 35.91-0.136 1.344-0.208 2.708-0.208 4.090v463.332c-0.618 2.794-0.968 5.688-0.968 8.668 0 22.094 17.91 40 40 40h688.27c22.092 0 40-17.91 40-40-0.002-1.528-0.104-3.028-0.27-4.506zM209 488.032h607.032v392h-607.032v-392zM552.164 691.86l-0.002 58.186c0.004 22.088-17.906 39.996-39.996 40-22.094 0-40.004-17.908-40-40v-57.976c-14.702-11.726-24.134-29.782-24.134-50.048 0-35.346 28.654-64 64-64s64 28.654 64 64c0 20.142-9.318 38.102-23.868 49.838z',
key:
'M768.032 320.032c0 35.346-28.654 64-64 64s-64-28.654-64-64 28.654-64 64-64 64 28.654 64 64zM960.032 353.092c0 159.062-128.946 288.010-288.008 288.010-35.306 0-69.124-6.368-100.38-17.996l-27.736 27.738-0.002 54.464c0 0.016 0.002 0.028 0.002 0.040 0 11.046-4.478 21.046-11.716 28.29-6.334 6.332-14.784 10.55-24.196 11.508-1.346 0.136-2.708 0.208-4.090 0.208h-71.748l-0.002 71.96c0 0.012 0.002 0.040 0.002 0.040 0 11.046-4.478 21.046-11.716 28.286-6.334 6.336-14.784 10.554-24.196 11.508-1.346 0.136-2.708 0.208-4.090 0.208h-71.996l-0.002 62.684c0 22.094-17.908 40-40 40-0.022 0-0.042 0-0.062 0-0.022 0-0.042 0-0.064 0h-175.996c-13.76 0-25.888-6.95-33.086-17.524-4.362-6.406-6.916-14.14-6.916-22.476v-112c0-0.664 0.066-1.308 0.1-1.964 0.032-0.618 0.034-1.234 0.092-1.852 0.11-1.148 0.288-2.278 0.492-3.398 0.024-0.128 0.034-0.258 0.058-0.386 1.614-8.378 5.848-15.808 11.808-21.446l325.456-325.458c-11.642-31.274-18.020-65.11-18.020-100.44 0-159.060 128.946-288.006 288.006-288.006 159.060-0.004 288.006 128.942 288.006 288.002zM880.032 353.092c0-114.696-93.312-208.006-208.008-208.006s-208.006 93.31-208.006 208.006c0 43.208 13.246 83.376 35.884 116.668l-57.36 57.362c-0.136-0.184-0.27-0.368-0.408-0.546l-298.102 298.106-0.002 55.356h96.124v-62.684c0-0.708 0.070-1.394 0.106-2.094 0.036-0.664 0.036-1.336 0.102-1.992 0.132-1.316 0.334-2.61 0.592-3.882 0.006-0.028 0.008-0.058 0.014-0.090 0.258-1.262 0.58-2.5 0.956-3.714 0.012-0.040 0.018-0.078 0.030-0.118 4.676-15.032 17.976-26.262 34.114-27.902 1.344-0.136 2.708-0.208 4.090-0.208h71.998v-67.64c-0.156-1.434-0.248-2.882-0.248-4.36 0-22.094 17.908-40 40-40h71.998v-30.692c0-0.148 0.020-0.29 0.022-0.438 0.008-10.226 3.912-20.45 11.714-28.254l55.99-55.988c1.982-1.984 4.124-3.71 6.38-5.188l18.68-18.684c33.030 22.090 72.702 34.992 115.332 34.992 114.694-0 208.008-93.314 208.008-208.010z',
arrowleftalt:
'M107.854 539.924l282.834 283.272c15.594 15.65 40.92 15.692 56.568 0.1 15.648-15.594 15.694-40.92 0.1-56.568l-214.838-215.040h655.412c22.092 0 40-17.908 40-40s-17.908-40-40-40h-655l214.75-214.61c15.64-15.602 15.672-40.928 0.070-56.568-7.814-7.834-18.066-11.752-28.32-11.75-10.22 0-20.442 3.892-28.25 11.68l-283.242 282.93c-15.634 15.594-15.672 40.91-0.084 56.554z',
arrowrightalt:
'M916.266 483.792l-282.834-283.272c-15.594-15.65-40.92-15.692-56.568-0.1-15.648 15.594-15.694 40.92-0.1 56.568l214.838 215.040h-655.412c-22.092 0-40 17.908-40 40s17.908 40 40 40h655l-214.748 214.61c-15.64 15.602-15.672 40.928-0.070 56.568 7.814 7.834 18.066 11.752 28.32 11.75 10.22 0 20.442-3.892 28.25-11.68l283.242-282.93c15.632-15.596 15.67-40.91 0.082-56.554z',
sync:
'M998.786 474.516l-91 90.988c-8.028 8.036-18.624 11.902-29.152 11.676-10.536 0.234-21.144-3.632-29.184-11.676l-92.3-92.296c-15.624-15.622-15.624-40.95 0-56.57 15.622-15.622 40.95-15.624 56.57 0l26.146 26.148c-13.774-61.416-44.624-117.806-90.216-163.394-63.46-63.464-147.84-98.414-237.586-98.414-89.75 0-174.128 34.95-237.59 98.414-27.012 27.012-48.836 57.824-65.024 91.214l-0.008-0.004c-6.722 12.632-20.008 21.242-35.32 21.242-22.090 0-40-17.906-40-40 0-5.464 1.102-10.668 3.086-15.414l-0.004-0.004c0.016-0.032 0.024-0.058 0.040-0.090 0.036-0.078 0.070-0.156 0.106-0.234 0.73-1.632 0.208-0.718 5.004-9.996 69.18-133.726 208.766-225.128 369.71-225.128 203.224 0 372.374 145.734 408.728 338.392l21.424-21.424c15.618-15.622 40.946-15.622 56.566 0s15.624 40.948 0.004 56.57zM889.992 682.11c0 5.464-1.106 10.672-3.090 15.414l0.008 0.004c-0.016 0.036-0.028 0.058-0.040 0.090-0.036 0.078-0.074 0.156-0.106 0.234-0.73 1.636-0.208 0.718-5.008 10-69.176 133.722-208.762 225.124-369.708 225.124-205.2 0-375.668-148.578-409.76-344.022l-19.478 19.478c-15.622 15.622-40.95 15.622-56.57 0-15.618-15.622-15.622-40.95 0-56.57l90.996-90.992c8.032-8.032 18.628-11.902 29.152-11.672 10.536-0.238 21.144 3.632 29.188 11.672l92.296 92.3c15.624 15.618 15.624 40.946 0 56.566-15.618 15.622-40.946 15.624-56.566 0.004l-29.292-29.292c12.466 65.568 44.214 125.882 92.448 174.116 63.46 63.46 147.84 98.41 237.586 98.41 89.75 0 174.124-34.95 237.59-98.41 27.012-27.012 48.836-57.824 65.020-91.218l0.008 0.004c6.726-12.632 20.012-21.242 35.324-21.242 22.092 0.002 40.002 17.912 40.002 40.002zM145.83 545.416l1.4 0.248-0.824-0.824-0.576 0.576z',
reply:
'M679.496 431.738c-0.414-0.062-0.834-0.102-1.266-0.102h-477.482l171.506-171.504c15.622-15.622 15.622-40.95-0.002-56.57-15.62-15.624-40.948-15.624-56.568 0l-239.734 239.732c-0.958 0.956-1.868 1.958-2.724 3.006-0.328 0.402-1.884 2.482-2.324 3.138-0.36 0.54-1.696 2.77-2.008 3.352-0.308 0.58-1.424 2.936-1.676 3.544-0.036 0.086-0.468 1.268-0.648 1.774-0.23 0.636-0.474 1.266-0.672 1.918-0.186 0.612-0.818 3.13-0.95 3.788-0.148 0.748-0.522 3.318-0.574 3.862-0.262 2.642-0.262 5.3 0 7.942 0.044 0.448 0.412 3.032 0.58 3.874 0.112 0.556 0.74 3.088 0.958 3.808 0.158 0.524 1.036 2.992 1.328 3.7 0.192 0.458 1.298 2.828 1.688 3.552 0.208 0.386 0.446 0.75 0.666 1.126 0.436 0.752 1.844 2.888 2.084 3.224 0.52 0.724 4.262 5.074 4.29 5.098l239.718 239.72c15.62 15.618 40.948 15.618 56.57 0 15.62-15.624 15.622-40.948 0-56.57l-171.516-171.514h471.296c114.52 0.084 207.688 93.124 207.988 207.594 0 0.084-0.012 0.164-0.012 0.248v95.876c-0.004 22.094 17.906 40.002 40 40 22.090-0.002 40-17.91 39.996-39.998l0.004-95.57h0.020c0-156.594-124.914-284.012-280.536-288.048z',
undo:
'M230 301h480a240 240 0 1 1 0 481H235c-23 0-42-20-42-43 0-24 19-43 42-43h475a155 155 0 0 0 0-310H228l3 3 65 65a45 45 0 0 1-65 64L90 376a45 45 0 0 1 0-64l142-142a45 45 0 1 1 64 65l-63 62-3 4z',
transfer:
'M916.25 348.726l-125 124.688c-7.808 7.79-18.032 11.68-28.25 11.68-10.254 0.002-20.506-3.918-28.32-11.75-15.602-15.64-15.57-40.966 0.070-56.568l56.508-56.368h-655.258c-22.092 0-40-17.908-40-40s17.908-40 40-40h655.672l-57.006-57.206c-15.594-15.646-15.548-40.972 0.1-56.566s40.972-15.55 56.568 0.098l125 125.438c15.588 15.644 15.548 40.958-0.084 56.554zM107.666 731.892l125 125.438c15.596 15.648 40.92 15.692 56.568 0.098s15.694-40.92 0.1-56.566l-57.006-57.206h655.672c22.092 0 40-17.908 40-40s-17.908-40-40-40h-655.258l56.508-56.368c15.64-15.602 15.672-40.928 0.070-56.568-7.814-7.832-18.066-11.752-28.32-11.75-10.218 0-20.442 3.89-28.25 11.68l-125 124.688c-15.632 15.596-15.672 40.91-0.084 56.554z',
redirect:
'M913.852 702.796c-15.594-15.648-40.922-15.694-56.57-0.1l-57.204 57.006v-451.424c0-0.372-0.028-0.736-0.074-1.098-0.458-99.016-80.86-179.15-179.988-179.15-99.412 0-180 80.592-180 180 0 0.084 0.004 0.166 0.004 0.248h-0.004v343.504h-0.006c0 0.082 0.006 0.164 0.006 0.248 0 55.14-44.86 100-100 100s-100-44.86-100-100c0-0.084 0.006-0.166 0.006-0.248h-0.002v-483.752c0-22.092-17.91-40-40-40s-40.004 17.908-40.004 40v483.752c0 0.018 0.002 0.036 0.002 0.054 0 0.064-0.002 0.128-0.002 0.194 0 99.408 80.59 180 180 180 99.412 0 180-80.592 180-180 0-0.084-0.004-0.166-0.004-0.248h0.004v-343.504h0.008c0-0.082-0.008-0.164-0.008-0.248 0-55.138 44.86-100 100-100s100 44.862 100 100c0 0.084-0.008 0.166-0.008 0.248h0.070v451.008l-56.368-56.506c-15.602-15.642-40.93-15.67-56.566-0.070-7.836 7.814-11.754 18.066-11.754 28.32 0 10.218 3.894 20.442 11.68 28.252l124.692 125c15.594 15.632 40.91 15.67 56.554 0.084l125.434-125c15.652-15.598 15.692-40.92 0.102-56.57z',
expand:
'M959.688 920.068l0.31-176c0.040-22.094-17.84-40.032-39.93-40.070-22.092-0.040-40.032 17.838-40.070 39.93l-0.142 79.672-235.734-235.732c-15.622-15.622-40.948-15.622-56.57 0s-15.622 40.948 0 56.568l235.442 235.442-78.946-0.1c-22.092-0.028-40.022 17.86-40.050 39.952-0.014 11.064 4.464 21.084 11.714 28.334 7.228 7.224 17.208 11.702 28.236 11.714l175.688 0.22c22.086 0.028 40.014-17.846 40.052-39.93zM920.178 64.228l-176-0.308c-22.094-0.040-40.032 17.84-40.070 39.93-0.040 22.092 17.838 40.032 39.93 40.070l79.672 0.14-235.732 235.734c-15.622 15.622-15.622 40.948 0 56.568s40.948 15.622 56.568 0l235.442-235.442-0.1 78.946c-0.028 22.092 17.86 40.022 39.952 40.050 11.064 0.014 21.084-4.464 28.334-11.714 7.224-7.228 11.702-17.208 11.714-28.236l0.22-175.688c0.026-22.082-17.846-40.010-39.93-40.050zM64.236 103.742l-0.308 176c-0.040 22.094 17.84 40.032 39.93 40.070 22.092 0.040 40.032-17.84 40.070-39.93l0.14-79.672 235.734 235.73c15.622 15.622 40.948 15.622 56.568 0s15.622-40.946 0-56.566l-235.442-235.442 78.946 0.098c22.092 0.028 40.022-17.86 40.050-39.95 0.014-11.066-4.464-21.086-11.714-28.336-7.228-7.222-17.208-11.7-28.236-11.714l-175.688-0.218c-22.084-0.026-40.012 17.844-40.050 39.93zM103.748 959.766l176 0.308c22.094 0.040 40.032-17.84 40.070-39.93 0.040-22.092-17.84-40.032-39.93-40.070l-79.672-0.14 235.73-235.734c15.622-15.622 15.622-40.948 0-56.568s-40.946-15.622-56.566 0l-235.442 235.442 0.098-78.946c0.028-22.092-17.86-40.022-39.95-40.050-11.066-0.014-21.086 4.464-28.336 11.714-7.222 7.228-11.7 17.208-11.714 28.236l-0.218 175.688c-0.026 22.082 17.844 40.010 39.93 40.050z',
expandalt:
'M512.008 959.964c-10.236 0-20.47-3.904-28.282-11.712l-239.898-239.838c-15.624-15.62-15.624-40.946-0.006-56.57 15.622-15.622 40.948-15.624 56.568-0.004l211.618 211.562 211.712-211.658c15.624-15.618 40.952-15.616 56.568 0.004 15.62 15.624 15.618 40.95-0.006 56.57l-239.994 239.934c-7.808 7.808-18.044 11.712-28.28 11.712zM483.824 75.744l-239.994 239.934c-15.624 15.62-15.624 40.948-0.006 56.57s40.944 15.622 56.568 0.004l211.712-211.658 211.618 211.562c15.622 15.62 40.948 15.616 56.568-0.006 15.62-15.624 15.618-40.95-0.006-56.57l-239.898-239.836c-7.81-7.81-18.044-11.714-28.282-11.714s-20.47 3.906-28.28 11.714z',
grow:
'M541.146 448.384c-1.694-0.216-3.408-0.37-5.162-0.37h-367.968c-1.754 0-3.468 0.152-5.162 0.37-19.646 2.538-34.838 19.292-34.838 39.63v368.032c0 22.094 17.91 40 40 40h367.968c13.808 0 25.98-6.996 33.168-17.636 0.102-0.148 0.184-0.308 0.282-0.458 0.612-0.924 1.2-1.862 1.722-2.838 0.046-0.082 0.080-0.172 0.124-0.254 2.994-5.61 4.704-12.008 4.704-18.808v-368.036c0-20.34-15.192-37.094-34.838-39.632zM208.016 816.046v-288.032h287.968v288.032h-287.968zM736.032 856.046c0 22.090-17.908 40-40 40-22.090 0-40-17.908-40-40v-487.902l-488.016 0.002c-22.090 0-40-17.91-40-40s17.908-40.002 40-40.002h528.016c1.754 0 3.468 0.152 5.162 0.37 19.646 2.538 34.838 19.292 34.838 39.63v527.902zM896.032 168.030v688.004c-0.002 22.088-17.91 39.996-40 39.996s-40.002-17.908-40.002-40c0 0 0.002-304.026 0.002-304.040v-343.96h-343.96c-0.014 0-304.040 0.002-304.040 0.002-22.090 0-40-17.91-40-40s17.908-40.002 40-40.002h688c1.754 0 3.468 0.152 5.162 0.37 19.646 2.536 34.838 19.29 34.838 39.63z',
arrowleft:
'M257.93 511.976c0-10.236 3.902-20.47 11.71-28.282l344.098-344.158c15.622-15.624 40.946-15.624 56.57-0.006 15.622 15.622 15.624 40.948 0.004 56.568l-315.82 315.876 315.868 315.922c15.618 15.624 15.618 40.952-0.004 56.568-15.622 15.62-40.95 15.618-56.57-0.006l-344.146-344.202c-7.808-7.81-11.71-18.044-11.71-28.28z',
arrowup:
'M512.024 256c10.236 0 20.47 3.904 28.282 11.712l344.154 344.098c15.624 15.62 15.624 40.946 0.006 56.57-15.622 15.622-40.948 15.624-56.568 0.004l-315.876-315.82-315.922 315.868c-15.624 15.618-40.952 15.618-56.568-0.004-15.62-15.624-15.618-40.95 0.006-56.57l344.204-344.144c7.81-7.81 18.046-11.714 28.282-11.714z',
arrowdown:
'M511.976 768.002c-10.236 0-20.47-3.904-28.282-11.712l-344.154-344.098c-15.624-15.62-15.624-40.946-0.006-56.57 15.622-15.622 40.948-15.624 56.568-0.004l315.876 315.82 315.922-315.868c15.624-15.618 40.952-15.616 56.568 0.004 15.62 15.624 15.618 40.95-0.006 56.57l-344.204 344.144c-7.81 7.81-18.046 11.714-28.282 11.714z',
arrowright:
'M768.072 514.022c0 10.236-3.904 20.47-11.712 28.282l-344.098 344.156c-15.62 15.624-40.946 15.624-56.568 0.006-15.622-15.622-15.624-40.948-0.006-56.568l315.82-315.876-315.868-315.922c-15.618-15.624-15.618-40.952 0.004-56.568 15.624-15.62 40.95-15.618 56.57 0.006l344.144 344.204c7.81 7.81 11.714 18.044 11.714 28.28z',
chevrondown:
'M511.976 833c-10.236 0-20.47-3.904-28.282-11.712l-471.934-471.874c-15.624-15.62-15.624-40.946-0.006-56.57 15.622-15.622 40.948-15.624 56.568-0.004l443.652 443.598 443.61-443.556c15.624-15.618 40.952-15.616 56.568 0.004 15.62 15.624 15.618 40.95-0.006 56.57l-471.89 471.832c-7.808 7.808-18.044 11.712-28.28 11.712z',
back:
'M512.030 880c-98.296 0-190.708-38.28-260.214-107.784-69.508-69.508-107.786-161.922-107.786-260.216 0-98.296 38.278-190.708 107.786-260.214s161.918-107.786 260.214-107.786c98.292 0 190.708 38.28 260.214 107.786 69.504 69.508 107.786 161.918 107.786 260.214 0 98.294-38.282 190.708-107.786 260.216-69.508 69.504-161.922 107.784-260.214 107.784zM512.030 960c247.422 0 448-200.576 448-448s-200.578-448-448-448c-247.426 0-448 200.576-448 448s200.574 448 448 448v0zM267.63 538.67l125 125.438c15.596 15.648 40.922 15.692 56.57 0.098s15.692-40.92 0.098-56.566l-57.004-57.206h335.672c22.090 0 40-17.908 40-40s-17.91-40-40-40h-335.26l56.508-56.368c15.64-15.602 15.672-40.928 0.070-56.568-7.814-7.832-18.064-11.752-28.318-11.75-10.22 0-20.444 3.89-28.25 11.68l-125 124.688c-15.634 15.596-15.672 40.91-0.086 56.554z',
download:
'M881 513.188c0 98.296-38.28 190.708-107.784 260.214-69.508 69.508-161.922 107.786-260.216 107.786-98.296 0-190.708-38.28-260.214-107.786s-107.786-161.916-107.786-260.214c0-98.294 38.28-190.708 107.786-260.216 69.508-69.504 161.918-107.784 260.214-107.784 98.294 0 190.708 38.28 260.216 107.784 69.504 69.508 107.784 161.922 107.784 260.216zM961 513.188c0-247.424-200.576-448-448-448s-448 200.576-448 448 200.576 448 448 448 448-200.576 448-448v0zM539.672 757.584l125.436-125c15.65-15.594 15.692-40.92 0.1-56.568-15.594-15.648-40.92-15.694-56.568-0.1l-57.204 57.004v-335.67c0-22.092-17.908-40-40-40s-40 17.908-40 40v335.258l-56.368-56.508c-15.602-15.64-40.928-15.672-56.568-0.070-7.834 7.814-11.752 18.066-11.75 28.32 0 10.22 3.892 20.442 11.68 28.25l124.688 125c15.594 15.634 40.91 15.672 56.554 0.084z',
upload:
'M143.996 511.998c0-98.296 38.28-190.708 107.784-260.214 69.508-69.508 161.922-107.786 260.216-107.786 98.296 0 190.708 38.278 260.214 107.786s107.786 161.918 107.786 260.214c0 98.292-38.28 190.708-107.786 260.214-69.508 69.504-161.918 107.786-260.214 107.786-98.294 0-190.708-38.282-260.216-107.786-69.504-69.508-107.784-161.922-107.784-260.214zM63.996 511.998c0 247.422 200.576 448 448 448s448-200.578 448-448c0-247.426-200.576-448-448-448s-448 200.574-448 448v0zM485.324 267.598l-125.438 125c-15.648 15.596-15.692 40.922-0.098 56.57s40.92 15.692 56.566 0.098l57.206-57.004v335.672c0 22.090 17.908 40 40 40s40-17.91 40-40v-335.26l56.368 56.508c15.602 15.64 40.928 15.672 56.568 0.070 7.832-7.814 11.752-18.064 11.75-28.318 0-10.22-3.89-20.444-11.68-28.25l-124.688-125c-15.594-15.634-40.91-15.672-56.554-0.086z',
proceed:
'M512 144c98.296 0 190.708 38.28 260.214 107.784 69.506 69.508 107.786 161.922 107.786 260.216 0 98.296-38.28 190.708-107.786 260.214-69.506 69.508-161.918 107.786-260.214 107.786-98.294 0-190.708-38.28-260.216-107.786-69.504-69.506-107.784-161.916-107.784-260.214 0-98.294 38.28-190.708 107.784-260.216 69.508-69.504 161.922-107.784 260.216-107.784zM512 64c-247.424 0-448 200.576-448 448s200.576 448 448 448 448-200.576 448-448-200.576-448-448-448v0zM756.396 484.14l-125-125.436c-15.594-15.65-40.92-15.692-56.568-0.1-15.648 15.594-15.694 40.92-0.1 56.568l57.004 57.204h-335.67c-22.092 0-40 17.908-40 40s17.908 40 40 40h335.258l-56.508 56.368c-15.64 15.602-15.672 40.928-0.070 56.568 7.814 7.834 18.066 11.752 28.32 11.75 10.22 0 20.442-3.892 28.25-11.68l125-124.688c15.634-15.594 15.672-40.91 0.084-56.554z',
info:
'M828.782 195.216c-174.954-174.958-458.614-174.958-633.566 0-174.958 174.954-174.958 458.612 0 633.568 174.954 174.954 458.614 174.954 633.566 0 174.956-174.952 174.956-458.614 0-633.568zM772.214 772.214c-69.508 69.506-161.918 107.784-260.214 107.784-98.3 0-190.71-38.278-260.218-107.784-69.504-69.506-107.782-161.92-107.786-260.214 0.004-98.296 38.282-190.708 107.786-260.214 69.508-69.506 161.922-107.786 260.218-107.788 98.292 0.002 190.708 38.282 260.214 107.79 69.504 69.504 107.782 161.916 107.786 260.212-0.004 98.294-38.282 190.708-107.786 260.214zM512.996 361.124c-22.090 0-40-17.906-40-40v0c0-22.088 17.91-40 40-40v0c22.090 0 40.004 17.912 40.004 40v0c0 22.092-17.914 40-40.004 40v0zM512.998 743.094c-22.090 0-40-17.906-40-40v-240.002c0-22.090 17.91-40 40-40v0c22.090 0 40.004 17.91 40.004 40v240.002c0 22.094-17.914 40-40.004 40v0z',
question:
'M828.782 195.218c-174.954-174.958-458.614-174.958-633.566 0-174.958 174.954-174.958 458.612 0 633.566 174.954 174.956 458.614 174.956 633.566 0 174.956-174.95 174.956-458.614 0-633.566zM772.214 772.216c-69.508 69.504-161.918 107.782-260.214 107.782-98.3 0-190.71-38.278-260.218-107.782-69.504-69.506-107.782-161.92-107.786-260.216 0.004-98.298 38.282-190.708 107.786-260.216 69.508-69.504 161.922-107.784 260.218-107.784 98.292 0 190.708 38.28 260.214 107.788 69.504 69.504 107.782 161.916 107.786 260.214-0.004 98.294-38.282 190.708-107.786 260.214zM512.996 784.784c-22.090 0-40-17.906-40-40v0c0-22.090 17.91-40 40-40v0c22.090 0 40.004 17.91 40.004 40v0c0 22.094-17.914 40-40.004 40v0zM552.996 572.27v52.898c0.004 22.088-17.906 39.996-39.996 40-22.094 0-40.004-17.908-40-40v-88c-0.004-21.752 17.372-39.416 38.996-39.952v-0.146c53.118 0 96.332-43.212 96.332-96.33 0-53.116-43.214-96.328-96.332-96.328-53.098 0-96.296 43.184-96.324 96.278 0 0.014 0 0.034 0 0.050 0 22.094-17.914 40-40.004 40s-40-17.906-40-40c0-97.382 78.946-176.328 176.328-176.328 97.386 0 176.332 78.946 176.332 176.328 0 83.268-57.722 153.048-135.332 171.53z',
support:
'M828.814 195.216c-174.956-174.956-458.614-174.956-633.566 0-174.958 174.956-174.956 458.612 0 633.568s458.614 174.956 633.566 0c174.958-174.956 174.956-458.612 0-633.568zM813.592 723.072l-92.714-92.712c41.542-73.186 41.548-163.544 0.016-236.734l92.7-92.698c43.176 61.41 66.44 134.45 66.44 211.074-0.004 76.62-23.266 149.662-66.442 211.070zM398.916 625.116c-62.382-62.384-62.382-163.89 0-226.274 30.216-30.216 70.398-46.86 113.146-46.864h0.010c42.724 0 82.898 16.642 113.12 46.866 62.382 62.38 62.382 163.886 0 226.272-30.22 30.22-70.4 46.864-113.136 46.864-42.74-0.002-82.92-16.644-113.14-46.864zM723.104 210.44l-92.696 92.698c-36.59-20.766-77.464-31.162-118.356-31.158-40.888 0.004-81.78 10.406-118.378 31.178l-92.714-92.716c61.408-43.176 134.452-66.438 211.070-66.44 76.622-0.004 149.668 23.262 211.074 66.438zM210.472 300.928l92.724 92.726c-41.512 73.176-41.506 163.506 0.016 236.678l-92.742 92.74c-43.176-61.408-66.438-134.454-66.44-211.072 0.004-76.624 23.264-149.664 66.442-211.072zM512.032 880c-76.624-0.002-149.666-23.264-211.072-66.44l92.74-92.742c36.59 20.766 77.464 31.16 118.356 31.16 40.868 0 81.738-10.392 118.322-31.144l92.726 92.726c-61.408 43.176-134.454 66.44-211.072 66.44z',
alert:
'M511.998 623.846c-22.090 0-40-17.906-40-40v-208c0-22.090 17.91-40 40-40v0c22.090 0 40.004 17.91 40.004 40v208c0 22.094-17.914 40-40.004 40v0zM511.998 743.846c22.090 0 40.004-17.906 40.004-40v0c0-22.090-17.914-40-40.004-40v0c-22.090 0-40 17.91-40 40v0c0 22.094 17.91 40 40 40v0zM512.142 211.808l-340.074 589.028h680.148l-340.074-589.028zM512.142 92.51c14.5 0 29 9.526 40 28.58l398.638 690.462c22 38.106 4 69.282-40 69.282h-797.278c-44 0-62-31.176-40-69.282l398.638-690.462c11.002-19.052 25.502-28.58 40.002-28.58v0z',
bell:
'M901.344 760.018l-57.644-77.648c-7.906-7.906-11.77-38.284-11.71-48.646h0.042v-200.588h-0.364c-6.878-148.106-114.428-269.902-255.792-298.528 0.208-2.1 0.318-4.228 0.318-6.384 0-35.452-28.738-64.194-64.194-64.194-35.458 0-64.194 28.742-64.194 64.194 0 2.19 0.112 4.352 0.326 6.486-141.128 28.802-248.446 150.488-255.316 298.426h-0.364v200.588h0.042c0.058 10.362-3.804 40.74-11.71 48.646l-57.644 77.648c-8.802 8.802-16.35 18.978-16.35 32.208 0 22.092 17.908 40 40 40h255.876c-0.814 5.412-1.28 10.936-1.28 16.576 0 61.43 49.794 111.23 111.23 111.23 61.432 0 111.228-49.8 111.228-111.23 0-5.638-0.464-11.164-1.282-16.576h255.128c22.092 0 40-17.908 40-40 0.004-13.23-7.542-23.404-16.346-32.208zM272.732 436.848c2.862-61.602 29.032-119.104 73.69-161.91 44.786-42.93 103.628-66.62 165.692-66.706h0.26c62.062 0.086 120.906 23.776 165.692 66.706 44.658 42.806 70.828 100.308 73.69 161.91l0.278 5.962v149.384h-479.58v-149.384l0.278-5.962zM543.846 848.8c0 17.22-14.010 31.23-31.228 31.23-17.22 0-31.23-14.010-31.23-31.23 0-6.096 1.784-11.768 4.82-16.576h52.818c3.038 4.81 4.82 10.482 4.82 16.576zM512.484 752.226h-283.922l14.572-19.63c12.064-14.542 20.078-33.27 24.982-58.158 0.146-0.742 0.276-1.496 0.416-2.244h487.42c0.138 0.748 0.268 1.5 0.414 2.244 4.904 24.888 12.918 43.616 24.982 58.158l14.572 19.63h-283.436z',
rss:
'M256.094 865.048c0 53.020-42.972 96-96 96-53.020 0-96-42.98-96-96 0-53.016 42.98-96 96-96s96 42.984 96 96zM510.020 918.352c-0.018-0.172-0.042-0.344-0.050-0.52-0.054-0.676-0.124-1.34-0.214-2.004-10.582-105.644-57.866-200.46-128.894-271.536v0c-71.074-71.054-165.906-118.352-271.564-128.934-0.664-0.090-1.33-0.16-2.006-0.214-0.174-0.016-0.348-0.040-0.52-0.054-0.254-0.024-0.5-0.024-0.742-0.008-0.64-0.032-1.278-0.098-1.922-0.098-22.098 0-40 17.908-40 40 0 20.582 15.542 37.516 35.536 39.738 0.042 0.004 0.066 0.036 0.106 0.040 84.82 8.098 163.514 45.024 224.542 106.042v0c61.036 61.036 97.964 139.738 106.070 224.574 0.004 0.040 0.036 0.070 0.042 0.106 2.222 19.988 19.156 35.536 39.736 35.536 22.092 0 40-17.902 40-40 0-0.644-0.066-1.282-0.098-1.922 0-0.246 0-0.492-0.022-0.746zM734.688 918.45c-0.004-0.090-0.018-0.186-0.024-0.276-0.040-0.544-0.058-1.102-0.124-1.638-10.972-167.816-83.558-318.804-195.33-430.616h0.002c-111.812-111.788-262.81-184.384-430.644-195.36-0.542-0.060-1.094-0.084-1.642-0.122-0.092-0.008-0.182-0.016-0.272-0.022-0.020-0.002-0.042 0.004-0.054 0.004-0.836-0.052-1.664-0.124-2.512-0.124-22.092 0-40 17.908-40 40 0 21.036 16.246 38.24 36.874 39.842 0.046 0.008 0.078 0.038 0.128 0.042 66.876 4.086 131.786 19.292 193.406 45.358 70.472 29.81 133.78 72.494 188.166 126.874v0c54.394 54.396 97.090 117.71 126.902 188.204 26.064 61.624 41.274 126.532 45.362 193.408 0.004 0.052 0.036 0.080 0.042 0.13 1.604 20.624 18.802 36.87 39.844 36.87 22.090 0 40-17.904 40-40 0-0.85-0.074-1.678-0.126-2.514-0.002-0.024 0.006-0.040 0.002-0.060zM959.126 920.556c-0.002-0.094 0.008-0.164 0.004-0.262-10.342-231.204-108.314-439.604-261.486-592.796v-0.002c-153.2-153.19-361.61-251.174-592.828-261.518-0.096-0.004-0.168 0.006-0.262 0.004-0.176-0.004-0.348-0.030-0.524-0.030-22.098 0-40 17.91-40 40 0 20.988 16.168 38.164 36.716 39.834 0.184 0.042 0.356 0.086 0.566 0.098 97.040 4.314 191.186 25.538 280.376 63.258 97.14 41.090 184.406 99.928 259.368 174.876v0c74.96 74.964 133.81 162.24 174.908 259.398 37.718 89.19 58.946 183.336 63.26 280.376 0.010 0.208 0.052 0.38 0.096 0.562 1.67 20.552 18.848 36.72 39.834 36.72 22.092 0 40-17.906 40-40-0-0.17-0.024-0.342-0.028-0.518z',
edit:
'M948.56 263.376c12.704-12.708 15.072-31.836 7.11-46.936-1.84-3.524-4.232-6.832-7.192-9.792-0.286-0.286-0.594-0.528-0.886-0.8l-129.318-128.634c-0.048-0.048-0.088-0.106-0.138-0.154-7.812-7.812-18.050-11.716-28.292-11.714-10.242-0.004-20.484 3.902-28.296 11.714-0.064 0.066-0.12 0.136-0.184 0.204l-636.168 636.168c-5.868 5.134-10.21 11.958-12.298 19.748l-47.606 177.664c-3.7 13.804 0.248 28.534 10.352 38.638 7.602 7.6 17.816 11.714 28.288 11.714 3.452 0 6.93-0.446 10.352-1.364l177.664-47.606c7.296-1.956 13.732-5.904 18.74-11.216l521.486-521.484c1.126-0.904 2.222-1.87 3.268-2.914 1.042-1.044 2.006-2.138 2.91-3.264l107.75-107.748c0.836-0.71 1.668-1.432 2.458-2.224zM806.9 291.66l-73.592-73.202 56.61-56.61 73.594 73.2-56.612 56.612zM281.566 816.996l-73.4-73.4 468.572-468.568 73.594 73.202-468.766 468.766zM160.496 864.628l11.742-43.822 32.080 32.080-43.822 11.742z',
paintbrush:
'M946.58 293.66c12.704-12.708 15.072-31.836 7.108-46.938-1.838-3.524-4.23-6.83-7.19-9.79-0.282-0.282-0.588-0.52-0.876-0.792l-129.338-128.654c-0.046-0.046-0.084-0.098-0.13-0.144-7.814-7.812-18.056-11.718-28.296-11.714-10.24 0-20.48 3.906-28.292 11.714-0.064 0.066-0.12 0.138-0.184 0.206l-557.048 557.048c-2.194 2.192-4.042 4.59-5.622 7.11-70.624 87.486-17.922 195.43-174.738 239.554 0 0 64.758 18.11 144.33 18.11 74.374 0 161.678-15.824 221.23-77.020 0.394-0.364 0.808-0.696 1.192-1.078l1.734-1.734c0.852-0.798 1.678-1.578 2.504-2.426 0.348-0.356 0.668-0.728 1.010-1.086l168.756-168.756c1.126-0.906 2.224-1.872 3.272-2.918 1.044-1.044 2.008-2.14 2.914-3.266l375.212-375.212c0.834-0.706 1.664-1.424 2.452-2.214zM537.462 589.402l-73.594-73.206 324.068-324.064 73.594 73.2-324.068 324.070zM388.178 667.684c-13.288-13.632-28.584-23.974-44.78-31.016l63.902-63.902 73.596 73.204-64.246 64.248c-6.498-15.23-15.964-29.698-28.472-42.534zM229.848 791.928c8.294-30.346 14.852-54.332 32.416-73.862 0.83-0.864 2.664-2.702 4.26-4.286 8.030-6.792 17.534-8.246 24.198-8.246 14.386 0 29.026 6.554 40.162 17.98 19.592 20.106 21.934 49.238 5.596 66.874l-1.712 1.712c-0.798 0.752-1.612 1.524-2.462 2.354l-0.86 0.84-0.834 0.864c-30.666 31.79-75.914 45.424-118.104 50.542 7.53-18.888 12.598-37.426 17.34-54.772z',
close:
'M693.022 637.866c15.62 15.622 15.618 40.95 0 56.566-15.622 15.622-40.946 15.624-56.562 0.002l-124.46-124.458-124.456 124.458c-15.622 15.622-40.944 15.622-56.562 0-15.624-15.622-15.624-40.946-0.002-56.568l124.454-124.456-124.452-124.45c-15.622-15.622-15.622-40.946 0-56.564 15.62-15.624 40.944-15.624 56.568-0.002l124.45 124.45 124.454-124.452c15.622-15.62 40.95-15.62 56.566 0 15.622 15.62 15.624 40.944 0.002 56.56l-124.456 124.458 124.456 124.456zM828.784 828.784c-174.956 174.956-458.614 174.956-633.566 0-174.958-174.956-174.958-458.614 0-633.566 174.954-174.958 458.612-174.958 633.566 0 174.954 174.952 174.954 458.612 0 633.566zM880 511.998c-0.002-98.296-38.28-190.708-107.786-260.212s-161.92-107.786-260.214-107.788c-98.296 0.002-190.71 38.282-260.216 107.786-69.506 69.508-107.782 161.918-107.786 260.214 0.002 98.296 38.282 190.71 107.786 260.216 69.508 69.506 161.918 107.784 260.216 107.784 98.296 0 190.708-38.278 260.214-107.784s107.784-161.92 107.786-260.216z',
trash:
'M919.5 225.208h-215.5v-120.080c0-20.344-15.192-37.096-34.836-39.632-1.696-0.216-3.41-0.372-5.164-0.372h-304.004c-1.754 0-3.468 0.152-5.164 0.372-19.644 2.54-34.836 19.292-34.836 39.628v120.084h-215.996c-22.090 0-40 17.912-40 40.002 0 22.092 17.91 40 40 40h27.216l53.916 615.914h0.214c0 22.092 17.91 40 40 40h573.372c22.094 0 40-17.91 40-40h0.148l53.916-615.914h26.716c22.090 0 40-17.91 40-40s-17.908-40.002-39.998-40.002zM399.996 145.126h224.004v80.082h-224.004v-80.082zM762.062 881.124h-500.124l-50.414-575.912h600.954l-50.416 575.912zM632.004 697.124v-240c-0.004-22.092 17.906-40.002 40-40.002 22.090 0.002 40 17.908 40 40.002l-0.004 240.002c0.004 22.088-17.906 39.996-39.996 39.998-22.094 0.002-40.004-17.906-40-40zM311.996 697.124v-240c-0.004-22.092 17.906-40.002 40-40.002 22.090 0.002 40 17.908 40 40.002l-0.004 240.002c0.004 22.088-17.906 39.996-39.996 39.998-22.094 0.002-40.004-17.906-40-40zM472 697.124v-240c-0.004-22.092 17.906-40.002 40-40.002 22.090 0.002 40 17.908 40 40.002l-0.004 240.002c0.004 22.088-17.906 39.996-39.996 39.998-22.094 0.002-40.004-17.906-40-40z',
cross:
'M1013.286 955.716l-443.72-443.716 443.718-443.718c15.622-15.622 15.62-40.948-0.004-56.566-15.618-15.622-40.942-15.622-56.562 0l-443.716 443.718-443.72-443.718c-15.62-15.624-40.946-15.622-56.566 0-15.622 15.62-15.622 40.944 0 56.566l443.722 443.718-443.722 443.722c-15.622 15.618-15.62 40.942 0 56.56s40.948 15.622 56.566 0l443.72-443.718 443.722 443.718c15.618 15.624 40.942 15.622 56.56 0 15.62-15.618 15.622-40.944 0.002-56.566z',
delete:
'M828.786 195.216c-174.958-174.956-458.612-174.958-633.568 0-174.954 174.954-174.956 458.612 0 633.566 174.954 174.956 458.614 174.956 633.568 0 174.954-174.954 174.952-458.612 0-633.566zM251.786 251.786c69.506-69.506 161.916-107.784 260.212-107.788 84.838 0 165.278 28.538 230.402 81.028l-517.372 517.374c-52.492-65.126-81.026-145.568-81.030-230.404 0.004-98.294 38.282-190.704 107.788-260.21zM772.214 772.214c-69.506 69.506-161.918 107.784-260.214 107.786-84.836-0.004-165.276-28.538-230.402-81.030l517.376-517.372c52.492 65.126 81.028 145.564 81.028 230.402-0.004 98.296-38.284 190.71-107.788 260.214z',
add:
'M512 144c98.296 0 190.708 38.28 260.214 107.784 69.506 69.508 107.786 161.922 107.786 260.216 0 98.296-38.28 190.708-107.786 260.214-69.508 69.506-161.918 107.786-260.214 107.786-98.294 0-190.708-38.28-260.216-107.786-69.504-69.508-107.784-161.918-107.784-260.214 0-98.294 38.28-190.708 107.784-260.216 69.508-69.504 161.922-107.784 260.216-107.784zM512 64c-247.424 0-448 200.576-448 448s200.576 448 448 448 448-200.576 448-448-200.576-448-448-448v0zM729.002 473h-176.008v-176.008c0.002-22.090-17.906-39.994-39.996-39.994-22.088 0-39.998 17.908-39.998 39.998v176.004h-176c-22.094 0-40 17.908-39.998 40-0.002 22.090 17.904 39.996 39.996 39.996h176.002v176.004c0 22.094 17.908 40 40 39.998 22.090 0.002 39.996-17.904 39.996-39.996v-176.006l176.012-0.002c22.090 0.002 39.994-17.906 39.994-39.996-0.002-22.088-17.91-39.998-40-39.998z',
subtract:
'M512 64a448 448 0 1 1 0 896 448 448 0 0 1 0-896zm3 83a366 366 0 0 0-368 368 366 366 0 0 0 368 368 366 366 0 0 0 369-368 366 366 0 0 0-369-368zM295 472h434a40 40 0 0 1 0 80H295a40 40 0 1 1 0-80z',
plus:
'M921.002 473h-368.008v-368.004c0.002-22.090-17.906-39.996-39.996-39.996-22.088 0-39.998 17.91-39.998 40v368h-368.002c-22.094 0-40 17.908-39.998 40-0.002 22.090 17.904 39.996 39.996 39.996l368.004-0.002v368.010c0 22.094 17.908 40 40 39.996 22.090 0.004 39.996-17.902 39.996-39.996v-368.010h368.010c22.090 0.002 39.994-17.906 39.994-39.996-0-22.088-17.908-39.998-39.998-39.998z',
document:
'M863.98 242.454c0.008-0.23-0.094-3.944-0.152-4.624-0.058-0.688-0.368-2.972-0.496-3.742-0.008-0.058-0.352-1.712-0.54-2.486-0.124-0.508-0.246-1.014-0.39-1.518-0.226-0.784-1.106-3.292-1.296-3.78-0.304-0.754-1.426-3.162-1.668-3.626-0.398-0.762-1.75-3.028-2.008-3.418-0.606-0.924-1.262-1.81-1.942-2.678-0.132-0.168-0.246-0.346-0.382-0.512-0.98-1.212-2.028-2.364-3.14-3.454l-104.020-104.9c-3.714-3.714-7.988-6.518-12.54-8.464-0.090-0.040-3.762-1.404-4.008-1.48-0.942-0.288-1.894-0.516-2.852-0.732-0.336-0.076-0.66-0.176-0.996-0.244-1-0.2-3.618-0.558-3.922-0.59-1.324-0.13-2.652-0.204-3.976-0.204h-519.652c-1.754 0-3.468 0.152-5.164 0.372-19.644 2.54-34.836 19.292-34.836 39.628v752c0 22.094 17.91 40 40 40h624c22.090 0 40-17.906 40-40l-0.020-645.548zM784 848h-544v-672l439.614 0.002v65.186c0 22.090 17.91 40 40 40h64.368l0.018 566.812zM664 336c22.090 0 40 17.908 40 40s-17.91 40-40 40h-304c-22.092 0-40-17.908-40-40s17.908-40 40-40h304zM704 528c0 22.092-17.91 40-40 40h-304c-22.092 0-40-17.908-40-40s17.908-40 40-40h304c22.090 0 40 17.908 40 40zM704 680c0 22.092-17.91 40-40 40h-304c-22.092 0-40-17.908-40-40s17.908-40 40-40h304c22.090 0 40 17.908 40 40z',
folder:
'M571 274h327c23 0 41 18 41 41v488c0 22-18 40-41 40H126c-23 0-41-18-41-40V242c0-34 27-61 61-61h317c18 0 35 7 47 21l61 72zm-119-8H170v492h684V359H531l-79-93z',
component:
'M171 469h298V171H246c-42 0-75 33-75 75v223zm0 86v223c0 42 33 75 75 75h223V555H171zm682-86V246c0-42-33-75-75-75H555v298h298zm0 86H555v298h223c42 0 75-33 75-75V555zM256 85h512c94 0 171 77 171 171v512c0 94-77 171-171 171H256c-94 0-171-77-171-171V256c0-94 77-171 171-171z',
calendar:
'M920.036 160.030h-112.004v-72c0-22.092-17.906-40.004-40-40.004-22.090 0-40 17.906-40 40v72.004h-432v-72c0-22.092-17.906-40.004-40-40.004-22.090 0-40 17.906-40 40v72.004h-112.004c-1.38 0-2.746 0.070-4.090 0.208-20.168 2.046-35.91 19.080-35.91 39.792v688c0 22.090 17.91 40 40 40h816.008c22.098 0 40-17.91 40-40v-688c0-22.094-17.908-40-40-40zM356.032 848.026h-212.004v-142.662h212.004v142.662zM356.032 665.364h-212.004v-162.664h212.004v162.664zM356.032 462.7h-212.004v-142.662h212.004v142.662zM628.032 848.026h-232v-142.662h232v142.662zM628.032 665.364h-232v-162.664h232v162.664zM628.032 462.7h-232v-142.662h232v142.662zM880.036 848.026h-212.004v-142.662h212.004v142.662zM880.036 665.364h-212.004v-162.664h212.004v162.664zM880.036 462.7h-212.004v-142.662h212.004v142.662z',
graphline:
'M820.536 489.23c-15.624 15.618-40.954 15.618-56.57 0l-42.006-42.002-169.898 169.9c-7.822 7.82-18.076 11.722-28.326 11.712-10.248 0.008-20.496-3.894-28.314-11.712l-96.178-96.182-140.67 140.674c-15.624 15.622-40.954 15.618-56.57-0.004-15.624-15.618-15.624-40.946 0-56.566l168.946-168.946c7.812-7.816 18.058-11.72 28.3-11.716 10.238-0.002 20.476 3.904 28.29 11.716l96.204 96.204 168.91-168.91c0.33-0.356 0.626-0.73 0.972-1.076 7.824-7.824 18.084-11.726 28.34-11.712 10.252-0.012 20.508 3.892 28.332 11.714 0.346 0.346 0.64 0.72 0.972 1.074l69.266 69.266c15.62 15.618 15.616 40.942 0 56.566zM880 144h-736v736h736v-736zM920 64c22.092 0 40 17.908 40 40v816c0 22.092-17.908 40-40 40h-816c-22.092 0-40-17.908-40-40v-816c0-22.092 17.908-40 40-40h816z',
docchart:
'M919.938 128h-816.008c-1.38 0-2.746 0.070-4.090 0.208-20.168 2.046-35.91 19.080-35.91 39.792v688c0 22.090 17.91 40 40 40h816.008c22.098 0 40-17.91 40-40v-688c0-22.094-17.906-40-40-40zM395.934 470.67h232v162.664h-232v-162.664zM355.934 633.334h-212.004v-162.664h212.004v162.664zM395.934 430.67v-142.662h232v142.662h-232zM667.934 470.67h212.004v162.664h-212.004v-162.664zM667.934 430.67v-142.662h212.004v142.662h-212.004zM355.934 288.008v142.662h-212.004v-142.662h212.004zM143.93 673.334h212.004v142.662h-212.004v-142.662zM395.934 673.334h232v142.662h-232v-142.662zM667.934 673.334h212.004v142.662h-212.004v-142.662z',
doclist:
'M919.938 128h-816.008c-1.38 0-2.746 0.070-4.090 0.208-20.168 2.046-35.91 19.080-35.91 39.792v688c0 22.090 17.91 40 40 40h816.008c22.098 0 40-17.91 40-40v-688c-0-22.094-17.906-40-40-40zM143.93 288.008h736.008v527.988h-736.008v-527.988zM248 400.004c0-22.090 17.91-40 40-40h448c22.094 0 40 17.906 40 40 0 22.090-17.906 40-40 40h-448c-22.090 0-40-17.91-40-40zM776 552.002c0 22.094-17.906 40-40 40h-448c-22.090 0-40-17.906-40-40 0-22.090 17.91-40 40-40h448c22.094 0 40 17.91 40 40zM776 704c0 22.094-17.906 40-40 40h-448c-22.090 0-40-17.906-40-40 0-22.090 17.91-40 40-40h448c22.094 0 40 17.91 40 40z',
category:
'M925.224 256.37c-1.694-0.216-3.408-0.37-5.162-0.37h-816c-1.754 0-3.468 0.152-5.162 0.37-19.646 2.538-34.838 19.292-34.838 39.63v624c0 22.094 17.91 40 40 40h816c13.808 0 25.98-6.996 33.168-17.636 0.102-0.148 0.184-0.308 0.282-0.458 0.612-0.924 1.2-1.862 1.722-2.838 0.046-0.082 0.080-0.172 0.124-0.254 2.994-5.61 4.704-12.008 4.704-18.808v-624.004c0-20.342-15.19-37.096-34.838-39.632zM144.062 880v-544h736v544h-736zM896.11 180c0 11.044-8.954 20-20 20h-728.032c-11.046 0-20-8.956-20-20v0c0-11.046 8.954-20 20-20h728.032c11.046 0 20 8.954 20 20v0zM832.094 84c0 11.044-8.954 20-20 20h-600c-11.046 0-20-8.956-20-20v0c0-11.046 8.954-20 20-20h600c11.046 0 20 8.954 20 20v0z',
grid:
'M437.162 552.368c-1.694-0.216-3.408-0.37-5.162-0.37h-263.978c-1.754 0-3.468 0.152-5.162 0.37-19.646 2.538-34.838 19.292-34.838 39.63v264.040c0 22.094 17.91 40 40 40h263.978c13.808 0 25.98-6.996 33.168-17.636 0.102-0.148 0.184-0.308 0.282-0.458 0.612-0.924 1.2-1.862 1.722-2.838 0.046-0.082 0.080-0.172 0.124-0.254 2.994-5.61 4.704-12.008 4.704-18.808v-264.044c0-20.34-15.19-37.094-34.838-39.632zM208.022 816.038v-184.040h183.978v184.040h-183.978zM437.162 128.4c-1.694-0.216-3.408-0.37-5.162-0.37h-263.978c-1.754 0-3.468 0.152-5.162 0.37-19.646 2.538-34.838 19.292-34.838 39.63v263.968c0 22.094 17.91 40 40 40h263.978c13.808 0 25.98-6.996 33.168-17.636 0.102-0.148 0.184-0.308 0.282-0.458 0.612-0.924 1.2-1.862 1.722-2.838 0.046-0.082 0.080-0.172 0.124-0.254 2.994-5.61 4.704-12.008 4.704-18.808v-263.972c0-20.342-15.19-37.096-34.838-39.632zM208.022 392v-183.968h183.978v183.968h-183.978zM861.212 552.368c-1.694-0.216-3.408-0.37-5.162-0.37h-264.050c-1.754 0-3.468 0.152-5.162 0.37-19.646 2.538-34.838 19.292-34.838 39.63v264.040c0 22.094 17.91 40 40 40h264.048c13.808 0 25.98-6.996 33.168-17.636 0.102-0.148 0.184-0.308 0.282-0.458 0.612-0.924 1.2-1.862 1.722-2.838 0.046-0.082 0.080-0.172 0.124-0.254 2.994-5.61 4.704-12.008 4.704-18.808v-264.044c0.002-20.34-15.19-37.094-34.836-39.632zM632 816.038v-184.040h184.048v184.040h-184.048zM861.212 128.4c-1.694-0.216-3.408-0.37-5.162-0.37h-264.050c-1.754 0-3.468 0.152-5.162 0.37-19.646 2.538-34.838 19.292-34.838 39.63v263.968c0 22.094 17.91 40 40 40h264.048c13.808 0 25.98-6.996 33.168-17.636 0.102-0.148 0.184-0.308 0.282-0.458 0.612-0.924 1.2-1.862 1.722-2.838 0.046-0.082 0.080-0.172 0.124-0.254 2.994-5.61 4.704-12.008 4.704-18.808v-263.972c0.002-20.342-15.19-37.096-34.836-39.632zM632 392v-183.968h184.048v183.968h-184.048z',
copy:
'M960.132 210.186c0-0.444-0.050-0.874-0.066-1.312-0.024-0.684-0.044-1.366-0.104-2.046-0.060-0.74-0.158-1.468-0.26-2.198-0.080-0.564-0.156-1.128-0.258-1.692-0.146-0.792-0.328-1.566-0.518-2.34-0.124-0.508-0.244-1.014-0.39-1.518-0.224-0.784-0.488-1.548-0.76-2.312-0.176-0.49-0.344-0.98-0.538-1.466-0.302-0.754-0.642-1.486-0.988-2.216-0.224-0.472-0.436-0.946-0.68-1.41-0.398-0.762-0.838-1.496-1.284-2.228-0.242-0.396-0.466-0.798-0.722-1.19-0.608-0.924-1.262-1.81-1.942-2.678-0.132-0.168-0.248-0.346-0.382-0.512-0.98-1.212-2.028-2.364-3.14-3.454l-104.020-104.9c-3.714-3.714-7.988-6.518-12.542-8.464-0.088-0.040-0.174-0.084-0.262-0.122-0.994-0.418-2.006-0.774-3.024-1.108-0.242-0.080-0.474-0.176-0.72-0.252-0.942-0.288-1.894-0.516-2.854-0.732-0.334-0.076-0.658-0.176-0.996-0.244-0.998-0.2-2.004-0.336-3.010-0.458-0.306-0.038-0.606-0.1-0.912-0.13-1.322-0.13-2.65-0.204-3.976-0.204h-391.784c-1.754 0-3.468 0.152-5.162 0.372-19.646 2.538-34.838 19.29-34.838 39.628v145.516h-279.874c-1.754 0-3.468 0.152-5.162 0.372-19.646 2.538-34.838 19.29-34.838 39.628v628.28c0 22.094 17.91 40 40 40h496.118c13.808 0 25.98-6.996 33.168-17.636 0.102-0.148 2.084-3.466 2.128-3.548 2.992-5.612 4.704-12.010 4.704-18.808 0 0 0 0 0-0.004v-145.518h279.874c13.808 0 25.98-6.996 33.168-17.636 0.102-0.148 2.084-3.466 2.128-3.548 2.992-5.612 4.704-12.010 4.704-18.808 0 0 0 0 0-0.004v-521.828c0.008-0.23-0.016-0.458-0.014-0.688 0.002-0.202 0.028-0.39 0.028-0.584zM144.124 878.792v-548.278h311.752v65.186c0 22.090 17.91 40 40 40h64.366v443.092h-416.118zM640.244 693.278v-296.31c0.006-0.23-0.018-0.458-0.014-0.688 0.004-0.196 0.030-0.382 0.030-0.578 0-0.444-0.052-0.874-0.066-1.312-0.024-0.684-0.044-1.366-0.104-2.046-0.062-0.74-0.16-1.468-0.262-2.198-0.078-0.564-0.152-1.128-0.258-1.692-0.144-0.792-0.324-1.566-0.516-2.34-0.124-0.508-0.246-1.014-0.39-1.518-0.226-0.784-0.488-1.548-0.76-2.312-0.174-0.49-0.342-0.98-0.538-1.466-0.302-0.754-0.64-1.486-0.988-2.216-0.222-0.472-0.438-0.946-0.68-1.41-0.398-0.762-0.838-1.496-1.284-2.228-0.242-0.396-0.466-0.798-0.724-1.19-0.606-0.924-1.262-1.81-1.942-2.678-0.13-0.168-0.246-0.346-0.382-0.512-0.978-1.212-2.028-2.364-3.138-3.454l-104.020-104.9c-3.714-3.714-7.988-6.518-12.542-8.464-0.088-0.040-0.172-0.084-0.262-0.122-0.994-0.418-2.004-0.774-3.024-1.108-0.242-0.080-0.476-0.176-0.72-0.252-0.942-0.288-1.896-0.516-2.854-0.732-0.334-0.076-0.658-0.176-0.996-0.244-0.998-0.2-2.004-0.336-3.012-0.458-0.304-0.038-0.602-0.1-0.91-0.13-1.322-0.13-2.648-0.204-3.976-0.204h-31.916v-105.516h311.752v65.186c0 22.090 17.91 40 40 40h64.366v443.092h-239.87z',
certificate:
'M832.032 384.032c0-176.728-143.266-320-320-320s-320 143.272-320 320c0 104.662 50.25 197.584 127.938 255.966v311.5c0 16.174 9.74 30.756 24.682 36.952 4.954 2.052 10.152 3.050 15.31 3.050 10.402 0 20.626-4.060 28.276-11.702l123.726-123.58 123.772 123.332c11.452 11.412 28.644 14.804 43.574 8.608 14.93-6.2 24.66-20.776 24.66-36.942v-311.124c77.756-58.376 128.062-151.342 128.062-256.060zM272.032 384.032c0-64.106 24.964-124.374 70.292-169.706 45.33-45.33 105.6-70.294 169.708-70.294s124.376 24.964 169.708 70.294c45.33 45.332 70.292 105.6 70.292 169.706s-24.964 124.376-70.292 169.704c-45.33 45.33-105.6 70.294-169.708 70.294s-124.376-24.964-169.708-70.294c-45.328-45.328-70.292-105.598-70.292-169.704zM623.968 854.89l-83.804-83.508c-15.622-15.564-40.898-15.552-56.502 0.034l-83.694 83.594v-171.17c34.878 13.042 72.632 20.192 112.062 20.192 39.382 0 77.094-7.13 111.938-20.142v171z',
print:
'M925.922 304.496c-1.698-0.218-3.41-0.37-5.166-0.37h-88.64v-93.548c0.006-0.21-0.016-0.422-0.014-0.634 0.004-0.212 0.036-0.416 0.036-0.63 0-0.478-0.054-0.942-0.074-1.416-0.024-0.636-0.042-1.27-0.094-1.906-0.066-0.776-0.168-1.54-0.276-2.302-0.074-0.534-0.146-1.066-0.242-1.596-0.15-0.82-0.338-1.624-0.538-2.424-0.12-0.48-0.23-0.958-0.37-1.436-0.234-0.812-0.506-1.608-0.792-2.398-0.164-0.462-0.322-0.924-0.504-1.38-0.318-0.788-0.668-1.552-1.036-2.316-0.208-0.436-0.406-0.88-0.628-1.312-0.424-0.802-0.88-1.574-1.352-2.344-0.218-0.358-0.422-0.724-0.656-1.078-0.636-0.972-1.324-1.91-2.042-2.82-0.098-0.124-0.182-0.252-0.282-0.376-0.988-1.224-2.048-2.388-3.172-3.488l-104.004-104.882c-3.696-3.696-7.948-6.486-12.466-8.432-0.122-0.050-0.224-0.11-0.344-0.16-0.974-0.41-1.966-0.756-2.962-1.084-0.262-0.086-0.512-0.19-0.78-0.272-0.926-0.284-1.87-0.506-2.812-0.722-0.346-0.080-0.684-0.182-1.034-0.252-0.988-0.198-1.988-0.334-2.988-0.456-0.31-0.040-0.618-0.102-0.93-0.134-1.324-0.132-2.652-0.204-3.978-0.204h-455.67c-1.754 0-3.468 0.152-5.162 0.37-19.646 2.538-34.838 19.29-34.838 39.63v200h-87.356c-1.754 0-3.468 0.152-5.164 0.37-19.644 2.538-34.836 19.29-34.836 39.63v320c0 22.094 17.91 40 40 40h87.368v216c0 22.094 17.91 40 40 40h560.006c13.81 0 25.982-6.996 33.17-17.636 0.102-0.146 0.184-0.306 0.282-0.458 0.612-0.922 1.2-1.86 1.722-2.836 0.046-0.082 0.080-0.17 0.124-0.254 2.994-5.612 4.704-12.008 4.704-18.808 0 0 0 0 0-0.004v-216h88.624c13.808 0 25.982-6.996 33.168-17.636 0.104-0.148 0.186-0.308 0.286-0.458 0.612-0.922 1.198-1.862 1.72-2.836 0.046-0.082 0.082-0.172 0.124-0.256 2.994-5.61 4.702-12.008 4.702-18.806 0 0 0 0 0-0.004v-320c0-20.344-15.186-37.096-34.834-39.636zM272.116 144.128h375.634v65.186c0 1.38 0.070 2.746 0.208 4.090 2.048 20.168 19.080 35.91 39.792 35.91h64.366v54.812h-480v-159.998zM272.124 880.126v-327.998h480.006v327.998zM880.756 384.128v239.998h-48.624v-111.998c0-20.34-15.19-37.092-34.836-39.63-1.694-0.218-565.17-0.372-565.17-0.372-1.754 0-3.468 0.152-5.162 0.372-19.646 2.538-34.838 19.29-34.838 39.628v112h-47.368v-239.998zM664.124 608.126c22.092 0 40 17.908 40 40s-17.908 40-40 40h-304c-22.092 0-40-17.908-40-40s17.908-40 40-40h304zM704.124 784.126c0 22.092-17.908 40-40 40h-304c-22.092 0-40-17.908-40-40s17.908-40 40-40h304c22.092 0 40 17.908 40 40z',
listunordered:
'M961 233c0 22.090-17.908 40-40 40h-607.996c-22.090 0-40-17.908-40-40v0c0-22.090 17.908-40.002 40-40.002h607.996c22.092 0 40 17.912 40 40.002v0zM961 793c0-22.090-17.908-40.002-40-40.002h-607.996c-22.092 0-40 17.912-40 40.002v0c0 22.092 17.91 40 40 40h607.996c22.092 0 40-17.91 40-40v0zM961 606.332c0-22.090-17.908-40-40-40h-607.996c-22.092 0-40 17.91-40 40v0c0 22.094 17.91 40 40 40h607.996c22.092 0 40-17.91 40-40v0zM961 419.668c0-22.090-17.908-40.004-40-40.004h-607.996c-22.092 0-40 17.914-40 40.004v0c0 22.090 17.91 40 40 40h607.996c22.092-0 40-17.91 40-40v0zM129 168.998c-35.346 0-64 28.654-64 64s28.654 64 64 64 64-28.654 64-64-28.654-64-64-64zM129 728.998c-35.346 0-64 28.654-64 64s28.654 64 64 64 64-28.654 64-64-28.654-64-64-64zM129 542.332c-35.346 0-64 28.652-64 64 0 35.344 28.654 64 64 64s64-28.656 64-64c0-35.348-28.654-64-64-64zM129 355.664c-35.346 0-64 28.656-64 64 0 35.348 28.654 64 64 64s64-28.652 64-64c0-35.344-28.654-64-64-64z',
graphbar:
'M324.832 513c22.090 0 40 17.91 40 40v304c0 22.090-17.906 40-40 40v0c-22.090 0-40-17.906-40-40v-304c0-22.090 17.91-40 40-40v0zM884.832 128.998c-22.090 0-40 17.906-40 40v688.002c0 22.094 17.91 40 40 40v0c22.094 0 40-17.91 40-40v-688.002c0-22.094-17.91-40-40-40v0zM698.164 256.998c-22.090 0-40 17.91-40 40v560.002c0 22.094 17.91 40 40 40v0c22.094 0 40-17.91 40-40v-560.002c0-22.090-17.91-40-40-40v0zM511.5 384.998c-22.090 0-40.004 17.91-40.004 40v432.002c0 22.094 17.914 40 40.004 40v0c22.090 0 40-17.91 40-40v-432.002c0-22.090-17.91-40-40-40v0zM139.168 641c-22.090 0-40 17.91-40 40v176c0 22.094 17.91 40 40 40v0c22.094 0 40-17.91 40-40v-176c0-22.090-17.91-40-40-40v0z',
menu:
'M960 232c0 22.092-17.908 40-40.002 40h-815.996c-22.092 0-40-17.908-40-40v0c0-22.090 17.908-40 40-40h815.998c22.092 0 40 17.91 40 40v0zM768 416c0 22.090-17.908 40-40 40h-624c-22.090 0-40-17.908-40-40v0c0-22.090 17.908-40.002 40-40.002h624c22.092 0.002 40 17.914 40 40.002v0zM832 608c0 22.092-17.906 40.002-40 40.002h-688c-22.090 0-40-17.91-40-40.002v0c0-22.090 17.908-40 40-40h688c22.094 0 40 17.912 40 40v0zM576 792c0 22.094-17.91 40-40.002 40h-431.998c-22.090 0-40-17.906-40-40v0c0-22.094 17.908-40.002 40-40.002h432c22.094 0.002 40 17.912 40 40.002v0z',
filter:
'M962.030 168.032c0 22.092-17.908 40-40.002 40h-815.996c-22.092 0-40-17.908-40-40v0c0-22.090 17.908-40 40-40h815.998c22.092 0 40 17.908 40 40v0zM770 544.034c0 22.090-17.908 40-40 40h-432c-22.090 0-40-17.908-40-40v0c0-22.090 17.908-40.002 40-40.002h432c22.090 0 40 17.912 40 40.002v0zM642.030 728.032c0 22.094-17.91 40-40.002 40h-175.998c-22.090 0-40-17.906-40-40v0c0-22.094 17.908-40.002 40-40.002h176c22.094 0.002 40 17.91 40 40.002v0zM866 352.030c0 22.092-17.906 40.002-40 40.002h-624c-22.090 0-40-17.91-40-40.002v0c0-22.090 17.908-40 40-40h624c22.092 0 40 17.91 40 40v0zM512.030 928.034c22.090 0 40.004-17.906 40.004-40v0c0-22.090-17.914-40-40.004-40v0c-22.090 0-40 17.91-40 40v0c0 22.092 17.91 40 40 40v0z',
ellipsis:
'M184 393c66.274 0 120 53.73 120 120s-53.726 120-120 120c-66.286 0-120-53.73-120-120s53.714-120 120-120zM512 393c66.272 0 120 53.73 120 120s-53.728 120-120 120c-66.286 0-120-53.73-120-120s53.714-120 120-120zM840 393c66.272 0 120 53.73 120 120s-53.728 120-120 120c-66.286 0-120-53.73-120-120s53.714-120 120-120z',
cog:
'M396.458 151.486l27.768 27.768c23.28 23.29 54.262 36.116 87.242 36.116 0.318 0 0.636 0 0.958-0.004 0.292 0.002 0.58 0.004 0.872 0.004 32.99 0 63.976-12.83 87.22-36.098l27.61-27.604c19.584 6.294 38.582 14.192 56.892 23.642v39.976c0 32.878 13.406 64.804 36.842 87.888 23.072 23.384 54.966 36.762 87.804 36.762l39.442 0.002c9.168 17.906 16.852 36.462 23.014 55.574l-27.676 27.676c-23.222 23.224-36.318 55.242-36.094 88.096-0.248 32.884 12.844 64.934 36.094 88.19l27.928 27.928c-6.298 19.704-14.212 38.812-23.704 57.23l-38.984 0.002c-0.008 0-0.012 0-0.022 0-32.84 0-64.74 13.38-87.814 36.776-23.43 23.080-36.83 55-36.83 87.876v39.116c-18.38 9.486-37.456 17.406-57.122 23.714l-27.348-27.346c-23.278-23.3-54.264-36.13-87.254-36.13-0.292 0-0.58 0.002-0.872 0.004-0.318-0.004-0.636-0.004-0.958-0.004-32.978 0-63.962 12.826-87.228 36.102l-27.552 27.554c-19.874-6.338-39.144-14.32-57.708-23.902l-0.002-38.13c0.012-32.854-13.368-64.764-36.772-87.846-23.082-23.43-55.004-36.834-87.878-36.834h-38.506c-9.776-18.846-17.898-38.42-24.328-58.624l27.49-27.49c23.246-23.248 36.338-55.296 36.088-88.182 0.224-32.854-12.872-64.872-36.092-88.094l-27.23-27.232c6.29-19.612 14.182-38.628 23.636-56.966h38.942c32.878 0 64.802-13.402 87.884-36.838 23.398-23.086 36.778-54.994 36.766-87.81l0.002-39.028c18.492-9.546 37.688-17.506 57.48-23.834zM421.486 60.208c-59.932 11.946-115.658 35.516-164.752 68.268l-0.004 85.866c0.004 11.676-4.886 22.194-12.706 29.68-7.486 7.83-18.012 12.728-29.702 12.728h-85.806c-32.624 48.946-56.132 104.484-68.088 164.204l60.39 60.394c8.256 8.256 12.234 19.15 11.998 29.968 0.246 10.83-3.734 21.738-11.998 30.004l-60.562 60.56c11.97 60.402 35.74 116.552 68.826 165.948h85.24c11.69 0 22.214 4.9 29.702 12.73 7.818 7.482 12.708 17.998 12.706 29.676l0.004 85.004c49.162 32.796 104.976 56.386 165.006 68.316l60.654-60.656c8.028-8.032 18.55-12.014 29.072-12.014 0.312 0 0.62 0.004 0.93 0.010 0.298-0.006 0.602-0.010 0.9-0.010 10.526 0 21.046 3.982 29.070 12.014l60.542 60.534c59.78-11.968 115.376-35.512 164.356-68.19v-85.956c0-11.69 4.9-22.214 12.73-29.702 7.486-7.818 18.002-12.708 29.678-12.706l85.876-0.004c32.668-49.032 56.182-104.674 68.104-164.504l-61.050-61.052c-8.266-8.266-12.244-19.174-12-30.004-0.236-10.818 3.742-21.712 12-29.968l60.882-60.888c-11.91-59.144-35.158-114.178-67.37-162.758l-86.444-0.004c-0.004 0-0.008 0-0.008 0-11.674 0-22.188-4.89-29.67-12.708-7.83-7.486-12.73-18.012-12.73-29.702v-86.816c-48.912-32.632-104.418-56.158-164.106-68.14l-60.792 60.784c-8.024 8.032-18.546 12.014-29.070 12.014-0.3 0-0.602-0.004-0.9-0.012-0.308 0.008-0.618 0.012-0.93 0.012-10.522 0-21.044-3.982-29.072-12.014l-60.906-60.906zM511.856 314.472c-109.014 0-197.386 88.372-197.386 197.384 0 109.010 88.374 197.382 197.386 197.382v0.134c0.746 0 1.492 0.012 2.24 0.004 14.806-0.16 29.214-1.942 43.056-5.182 1.022-0.238 1.932-0.496 2.794-0.762 17.328-4.988 29.94-21.012 29.738-39.916-0.242-22.71-18.846-40.926-41.556-40.686-2.996 0.032-5.902 0.402-8.708 1.042-0.090 0.016-0.178 0-0.266 0.022-8.18 1.99-16.708 3.096-25.472 3.224-0.586-0.074-1.19-0.124-1.826-0.124-63.486 0-115.142-51.65-115.142-115.138 0-63.49 51.656-115.142 115.142-115.142 63.488 0 115.14 51.652 115.14 115.142 0 8.924-1.028 17.616-2.964 25.958-0.020 0.090-0.008 0.178-0.020 0.268-0.61 2.812-0.948 5.724-0.948 8.72 0 22.71 18.408 41.122 41.122 41.122 18.906 0 34.792-12.778 39.596-30.158 0.262-0.866 0.508-1.78 0.736-2.804 3.092-13.876 4.722-28.3 4.722-43.106 0-109.012-88.372-197.384-197.384-197.384z',
wrench:
'M959.438 274.25c0-22.090-17.914-40-40.004-40-11.16 0-21.242 4.582-28.496 11.954l-60.152 60.148c-15.622 15.622-40.946 15.618-56.566-0.004l-56.57-56.566c-15.622-15.622-15.622-40.95 0-56.57l59.55-59.546c7.75-7.292 12.614-17.618 12.614-29.102 0-22.090-17.914-40-40.004-40-1.598 0-3.164 0.122-4.71 0.304-0.012 0-0.020-0.008-0.032-0.004-94.958 11.586-168.504 92.492-168.504 190.574 0 23.528 4.238 46.058 11.98 66.886l-503.078 503.074c-1.496 1.496-2.8 3.102-4.012 4.758-10.914 13.676-17.454 30.992-17.454 49.848 0 44.188 35.818 79.996 79.996 79.996 18.906 0 36.27-6.574 49.964-17.54 1.614-1.188 3.18-2.464 4.64-3.926l503.078-503.078c20.828 7.742 43.36 11.98 66.882 11.98 97.988 0 178.828-73.402 190.54-168.222v-0.012c0.2-1.628 0.338-3.272 0.338-4.952zM151.996 912c-22.090 0-40-17.906-40-40 0-22.090 17.91-40 40-40s40.004 17.91 40.004 40c0 22.094-17.914 40-40.004 40z',
nut:
'M512.034 144.030l318.696 184v368l-318.696 184-318.702-184v-368l318.702-184zM512.034 64.030c-13.812 0-27.624 3.574-40 10.718l-318.702 184c-24.752 14.29-40 40.7-40 69.282v368c0 28.582 15.248 54.994 40 69.28l318.702 184c12.376 7.146 26.19 10.72 40 10.72 13.814 0 27.624-3.572 40-10.72l318.696-184c24.752-14.288 40-40.698 40-69.28v-368c0-28.582-15.248-54.992-40-69.282l-318.696-184c-12.376-7.144-26.188-10.718-40-10.718v0zM511.63 314.25c-109.014 0-197.386 88.372-197.386 197.384 0 109.010 88.374 197.382 197.386 197.382v0.134c0.746 0 1.492 0.012 2.24 0.004 14.806-0.162 29.214-1.942 43.056-5.182 1.022-0.24 1.932-0.496 2.794-0.762 17.328-4.988 29.94-21.012 29.738-39.916-0.242-22.71-18.846-40.926-41.556-40.684-2.996 0.032-5.902 0.402-8.708 1.040-0.090 0.016-0.178 0-0.266 0.022-8.18 1.99-16.708 3.094-25.474 3.222-0.584-0.072-1.188-0.124-1.826-0.124-63.486 0-115.142-51.65-115.142-115.138 0-63.49 51.656-115.142 115.142-115.142 63.488 0 115.14 51.652 115.14 115.142 0 8.924-1.028 17.616-2.964 25.96-0.020 0.088-0.008 0.178-0.020 0.266-0.61 2.814-0.948 5.724-0.948 8.72 0 22.712 18.408 41.122 41.122 41.122 18.906 0 34.792-12.776 39.596-30.158 0.262-0.866 0.508-1.78 0.736-2.804 3.092-13.876 4.724-28.3 4.724-43.106 0-109.010-88.372-197.382-197.384-197.382z',
camera:
'M925.164 208.372c-1.694-0.218-3.408-0.372-5.162-0.372h-471.968v-39.962c0-20.344-15.192-37.096-34.836-39.63-1.696-0.218-3.41-0.374-5.164-0.374h-176.004c-1.754 0-3.468 0.152-5.164 0.374-19.644 2.538-34.836 19.29-34.836 39.626v39.966h-88.032c-1.754 0-3.468 0.152-5.162 0.372-19.646 2.536-34.838 19.29-34.838 39.628v528c0 22.094 17.91 40 40 40h816.004c13.808 0 25.98-6.996 33.168-17.636 0.102-0.148 0.184-0.308 0.282-0.46 0.612-0.922 1.2-1.86 1.722-2.836 0.046-0.082 0.080-0.172 0.124-0.254 2.994-5.61 4.704-12.008 4.704-18.808v-528.004c-0-20.342-15.192-37.096-34.838-39.63zM880.002 736h-736.004v-448h736.004v448zM512 402.522c60.368 0 109.478 49.112 109.478 109.478s-49.112 109.478-109.478 109.478-109.478-49.112-109.478-109.478 49.11-109.478 109.478-109.478zM512 322.522c-104.644 0-189.478 84.832-189.478 189.478 0 104.644 84.834 189.478 189.478 189.478 104.646 0 189.478-84.834 189.478-189.478 0-104.646-84.832-189.478-189.478-189.478v0z',
eye:
'M1008.714 490.522c-9.002-12.594-223.276-308.808-496.684-308.808-273.444 0-487.682 296.214-496.684 308.808l-15.316 21.49 15.316 21.466c9.002 12.618 223.24 308.808 496.684 308.808 273.408 0 487.682-296.19 496.684-308.808l15.316-21.466-15.316-21.49zM807.68 631.688c-46 39.142-92.558 70.064-138.382 91.904-53.874 25.676-106.786 38.694-157.266 38.694-50.49 0-103.406-13.018-157.282-38.696-45.826-21.838-92.382-52.758-138.378-91.902-53.708-45.706-94.302-92.122-116.61-119.672 22.36-27.602 63.028-74.094 116.612-119.696 45.996-39.146 92.554-70.068 138.378-91.908 53.876-25.678 106.792-38.698 157.28-38.698 50.48 0 103.39 13.020 157.264 38.696 45.824 21.842 92.382 52.764 138.382 91.91 53.602 45.614 94.264 92.098 116.624 119.696-22.306 27.544-62.898 73.954-116.622 119.672zM692.032 512.036c0 99.41-80.588 180-180 180s-180-80.59-180-180c0-99.406 80.588-179.998 180-179.998s180 80.59 180 179.998z',
eyeclose:
'M75.744 948.314c-15.62-15.62-15.62-40.948 0-56.564l816-816c15.626-15.624 40.95-15.624 56.57 0 15.624 15.62 15.626 40.946 0.004 56.57l-816 815.994c-15.62 15.62-40.95 15.62-56.572 0zM332.032 512.034c0 20.104 3.296 39.434 9.376 57.484l228.104-228.106c-18.050-6.080-37.38-9.376-57.48-9.376-99.412-0.004-180 80.588-180 179.996zM692.032 512.034c0-20.1-3.3-39.432-9.38-57.484l-228.106 228.11c18.052 6.080 37.384 9.376 57.488 9.376 99.412 0 180-80.59 180-180zM1008.716 490.522c-4.98-6.968-72.86-100.8-178.81-183.22l-57.040 57.040c11.624 8.8 23.24 18.128 34.814 27.98 53.6 45.614 94.264 92.1 116.624 119.696-22.304 27.544-62.896 73.954-116.62 119.672-46 39.14-92.56 70.064-138.384 91.904-53.872 25.676-106.786 38.694-157.266 38.694-37.448 0-76.234-7.18-115.76-21.36l-61.486 61.49c54.786 24.22 114.45 39.87 177.248 39.87 273.41 0 487.684-296.19 496.686-308.808l15.316-21.468-15.316-21.49zM216.372 631.69c-53.708-45.706-94.3-92.12-116.61-119.672 22.36-27.6 63.028-74.094 116.612-119.696 46-39.146 92.554-70.068 138.38-91.908 53.874-25.68 106.79-38.7 157.28-38.7 37.46 0 76.264 7.188 115.8 21.38l61.484-61.484c-54.796-24.236-114.474-39.896-177.286-39.896-273.446 0-487.684 296.214-496.686 308.808l-15.316 21.49 15.314 21.466c4.98 6.984 72.866 100.84 178.84 183.26l57.040-57.040c-11.64-8.806-23.264-18.144-34.854-28.008z',
photo:
'M920 64h-816c-22.092 0-40 17.91-40 40v816c0 22.094 17.908 40 40 40h816c22.092 0 40-17.906 40-40v-816c0-22.090-17.908-40-40-40zM880 144v449.782l-235.39-235.392c-7.502-7.5-17.676-11.714-28.286-11.714s-20.784 4.214-28.286 11.716l-169.804 169.804-40.958-40.958c-15.622-15.622-40.95-15.622-56.57 0l-176.708 176.708v-519.946h736.002zM144 880v-102.914l204.992-204.994 215.972 215.974c7.81 7.81 18.048 11.714 28.286 11.714s20.474-3.904 28.286-11.714c15.62-15.622 15.62-40.95 0-56.57l-146.732-146.73 141.522-141.524 263.676 263.68v173.078h-736.002zM356.174 400.542c52.466 0 95-42.536 95-95s-42.534-95-95-95-95 42.536-95 95 42.534 95 95 95zM356.174 250.542c30.326 0 55 24.672 55 55s-24.674 55-55 55-55-24.672-55-55 24.674-55 55-55z',
video:
'M926.050 273.364c-9.556 0-20.574 3.8-32.278 11.812l-189.738 129.894v-151.068c0-20.342-15.192-37.094-34.838-39.63-1.694-0.218-3.408-0.372-5.162-0.372h-560.002c-1.754 0-3.468 0.152-5.162 0.372-19.646 2.538-34.838 19.29-34.838 39.628v496.002c0 22.092 17.91 40 40 40h560.004c13.808 0 25.98-6.998 33.168-17.638 0.102-0.148 0.184-0.308 0.282-0.458 0.612-0.922 1.2-1.862 1.722-2.836 0.046-0.082 0.080-0.172 0.124-0.254 2.994-5.612 4.704-12.010 4.704-18.81v-151.066l189.738 129.886c11.706 8.012 22.718 11.812 32.278 11.812 20.092 0 33.736-16.806 33.736-46.622v-384.032c0-29.816-13.644-46.62-33.738-46.62zM624.036 720h-480.004v-415.998h480.004v415.998zM879.788 632.3l-175.728-120.296 175.728-120.302v240.598zM240.688 663.534c-22.090 0-40-17.906-40-40v0c0-22.090 17.91-40 40-40v0c22.090 0 40.004 17.91 40.004 40v0c0 22.092-17.914 40-40.004 40v0z',
speaker:
'M692.070 580.856c18.156-18.156 28.152-42.266 28.152-67.89-0.008-25.622-10.002-49.726-28.148-67.872-8.476-8.478-18.308-15.188-29-19.922-0.222-0.098-0.408-0.22-0.566-0.364-13.294-6.5-22.476-20.116-22.476-35.914 0-22.090 17.91-40 40-40 5.774 0 11.246 1.248 16.204 3.45 0.016 0.006 0.026 0.008 0.040 0.016 19.292 8.656 37.036 20.832 52.368 36.164 33.254 33.254 51.574 77.446 51.58 124.43 0.006 46.996-18.31 91.204-51.58 124.472-15.064 15.062-32.45 27.074-51.344 35.7-0.154 0.070-0.286 0.112-0.434 0.176-5.124 2.382-10.812 3.75-16.832 3.75-22.090 0-40-17.906-40-40 0-16.196 9.644-30.112 23.488-36.402 0.156-0.11 0.32-0.216 0.516-0.304 10.314-4.712 19.81-11.268 28.032-19.49zM861.778 275.386c-47.824-47.824-107.946-79.588-173.204-92.242-0.356-0.078-0.712-0.146-1.072-0.214-0.060-0.012-0.124-0.026-0.186-0.038-0.506-0.096-0.976-0.162-1.422-0.208-1.918-0.282-3.868-0.476-5.864-0.476-22.090 0-40 17.91-40 40 0 19.024 13.292 34.91 31.084 38.968 0.352 0.128 0.728 0.244 1.162 0.326 48.7 9.268 95.226 32.748 132.934 70.452 99.972 99.972 100.054 261.984-0.002 362.040-37.684 37.684-84.152 61.14-132.788 70.426-0.084 0.016-0.144 0.046-0.224 0.066-18.338 3.644-32.166 19.816-32.166 39.222 0 22.094 17.91 40 40 40 2.776 0 5.484-0.286 8.102-0.822 0.094-0.018 0.172-0.018 0.27-0.038 65.32-12.626 125.496-44.406 173.376-92.286 131.008-131.008 131.008-344.172 0-475.176zM525.988 159.516v704.968c0 22.090-17.906 40-40 40-12.73 0-24.046-5.966-31.374-15.234l-51.056-61.722v0.216l-122.14-147.666h-177.386c-22.090 0-40-17.906-40-40v0 0-256c0-5.22 1.030-10.194 2.85-14.766 0.104-0.266 0.184-0.542 0.294-0.804 0.39-0.924 0.844-1.812 1.3-2.702 0.134-0.26 0.242-0.538 0.382-0.794 0.246-0.456 0.54-0.878 0.804-1.324 6.972-11.726 19.734-19.61 34.368-19.61h177.386l173.13-209.238c7.324-9.316 18.67-15.324 31.44-15.324 22.092-0 40.002 17.91 40.002 40zM445.988 270.826l-126.708 153.252h-175.248v176h175.248l19.832 23.998h0.17l106.708 129.112v-482.362z',
phone:
'M742.52 960c-76.266 0-163.184-32.364-258.338-96.194-73.798-49.504-136.41-106.904-175.938-146.34-43.282-43.222-105.612-111.376-156.842-190.682-66.576-103.062-95.348-196.038-85.518-276.344 8.952-73.326 50.674-134.292 120.664-176.304 10.95-6.63 23.76-10.134 37.054-10.134 32.752 0 71.124 23.354 120.764 73.494 36.434 36.802 70.108 79.22 89.472 106.644 46.698 66.176 60.686 107.352 48.286 142.136-12.638 35.538-35.534 55.704-52.25 70.428-5.662 5.006-9.95 8.854-13.070 12.262 4.040 7.542 11.744 19.868 26.054 37.476 42.388 52.076 90.548 89.024 111.972 100.874 3.308-2.96 7.11-7.168 12.352-13.152 14.87-16.81 35.062-39.636 70.482-52.28 7.978-2.842 16.498-4.276 25.35-4.276 44.172 0 108.804 44.078 155.246 81.056 45.834 36.494 103.292 90.498 127.104 132.612 22.602 39.596 14.982 68.64 4.596 86.006-48.138 80.296-119.862 122.718-207.44 122.718zM224.758 144.53c-47.558 29.426-73.566 67.28-79.468 115.618-7.494 61.224 17.17 136.326 73.308 223.226 49.902 77.252 112.994 144.35 146.16 177.472 30.296 30.222 91.906 88.17 163.988 136.524 81.738 54.83 153.662 82.63 213.772 82.63 58.618 0 103.506-26.526 137.138-81.076-0.47-1.536-1.532-4.062-3.854-8.132-14.584-25.794-57.006-69.202-105.642-108.156-58.776-47.074-96.708-63.894-106.756-64.982-15.348 5.826-25.020 16.758-36.178 29.372-12.542 14.318-28.31 32.316-55.476 41.528l-6.25 2.12h-6.598c-8.704 0-31.826 0-86.73-43.378-32.196-25.438-64.65-57.534-91.38-90.374-35.712-43.942-51.41-77.764-46.674-100.548l0.55-2.642 0.9-2.546c9.19-26 26.284-41.118 41.364-54.458 12.726-11.208 23.698-20.874 29.494-36.378-0.606-4.398-5.076-23.488-37.948-70.072-15.882-22.494-45.746-60.376-77.614-93.084-39.93-40.986-60.106-50.546-66.106-52.664z',
flag:
'M168 960.060c-22.092 0-40-17.908-40-40v-816.36c0-22.092 17.908-40 40-40h687.698c16.178 0 30.764 9.746 36.956 24.694 6.192 14.946 2.77 32.15-8.67 43.59l-188.918 188.922 189.218 189.216c11.44 11.442 14.862 28.646 8.67 43.592-6.192 14.948-20.776 24.694-36.956 24.694h-647.998v341.654c0 22.090-17.908 39.998-40 39.998zM208 498.406h551.428l-149.218-149.216c-15.622-15.622-15.622-40.95 0-56.568l148.918-148.922h-551.128v354.706z',
pin:
'M512 959.916c-13.36 0-25.84-6.672-33.262-17.782l-242.080-362.324c-0.12-0.176-0.236-0.356-0.354-0.536-36.394-54.5-55.63-118.042-55.63-183.804 0-182.696 148.632-331.324 331.326-331.324 182.696 0 331.328 148.628 331.328 331.324 0 60.71-16.554 119.98-47.906 171.652-0.758 1.528-1.618 3.016-2.578 4.45l-5.786 8.664c-0.054 0.082-0.112 0.164-0.168 0.246-0.042 0.070-0.104 0.16-0.148 0.23l-241.484 361.426c-7.422 11.106-19.898 17.778-33.258 17.778zM303.458 535.784l0.026 0.040c0.038 0.054 0.158 0.238 0.194 0.292l208.324 311.796 212.374-317.86c0.376-0.696 0.778-1.382 1.198-2.062 24.7-39.708 37.758-85.532 37.758-132.52 0-138.582-112.746-251.324-251.328-251.324s-251.326 112.742-251.326 251.324c0 50.054 14.674 98.39 42.432 139.782 0.114 0.176 0.232 0.356 0.348 0.532zM512 304.4c49.98 0 90.64 40.66 90.64 90.64 0 49.976-40.66 90.636-90.64 90.636s-90.64-40.66-90.64-90.636c0-49.98 40.66-90.64 90.64-90.64zM512 224.4c-94.242 0-170.64 76.398-170.64 170.64s76.398 170.636 170.64 170.636 170.64-76.394 170.64-170.636-76.398-170.64-170.64-170.64v0z',
compass:
'M960 512c0-247.424-200.574-448-448-448-247.422 0-448 200.576-448 448s200.578 448 448 448c247.426 0 448-200.576 448-448zM251.786 772.214c-69.504-69.508-107.786-161.918-107.786-260.214 0-98.294 38.282-190.708 107.786-260.216 69.508-69.504 161.918-107.784 260.214-107.784s190.708 38.28 260.214 107.784c69.508 69.508 107.786 161.922 107.786 260.216 0 98.296-38.278 190.708-107.786 260.214s-161.922 107.786-260.214 107.786c-98.296 0-190.708-38.28-260.214-107.786zM565.742 565.74c-0.93 0.93-1.95 1.768-3.050 2.498l-237.586 158.392c-7.934 5.29-18.496 4.242-25.238-2.498-6.738-6.742-7.786-17.304-2.496-25.236l158.39-237.588c1.464-2.2 3.348-4.082 5.546-5.546l237.586-158.392c7.934-5.29 18.496-4.242 25.238 2.498 6.742 6.742 7.79 17.304 2.5 25.238l-158.394 237.586c-0.73 1.1-1.566 2.118-2.496 3.048zM386.122 637.878l151.054-100.704-50.352-50.352-100.702 151.056z',
globe:
'M530.878 65.424c-6.748-1.014-13.090-1.424-18.878-1.424s-12.13 0.41-18.878 1.424c-238.662 9.9-429.122 206.48-429.122 447.576 0 247.424 200.578 448 448 448 247.426 0 448-200.576 448-448 0-241.098-190.456-437.678-429.122-447.576zM877.84 472.998h-158.508c-3.16-92.542-17.532-179.266-41.262-247.494-6.442-18.52-13.534-35.536-21.228-50.988 42.548 18.214 81.66 44.556 115.374 78.268 59.988 59.99 96.69 137.046 105.624 220.214zM512 880c-65.872 0-120.112-143.058-127.206-327h254.41c-7.092 183.942-61.332 327-127.204 327zM384.714 472.998c6.426-175.362 55.69-314.010 117.15-327.852 3.372-0.092 6.748-0.146 10.134-0.146s6.764 0.054 10.136 0.146c61.46 13.842 110.722 152.49 117.148 327.852h-254.568zM251.786 252.784c33.714-33.71 72.826-60.052 115.374-78.268-7.694 15.452-14.788 32.468-21.226 50.988-23.732 68.228-38.104 154.952-41.264 247.494h-158.508c8.934-83.168 45.636-160.224 105.624-220.214zM146.16 553h158.578c3.298 91.792 17.632 177.762 41.194 245.498 6.798 19.55 14.33 37.416 22.526 53.542-43.050-18.232-82.616-44.772-116.672-78.826-59.988-59.99-96.69-137.044-105.626-220.214zM772.214 773.214c-34.054 34.054-73.622 60.592-116.672 78.824 8.196-16.126 15.726-33.99 22.528-53.542 23.558-67.736 37.892-153.704 41.192-245.498h158.578c-8.934 83.172-45.634 160.226-105.626 220.216z',
location:
'M960.002 512l-0.002-0.026c-0.006-114.646-43.746-229.288-131.216-316.758-174.954-174.958-458.614-174.958-633.566 0-174.958 174.954-174.958 458.612 0 633.568 87.45 87.45 202.056 131.186 316.674 131.214 0.022 0 0.042 0.002 0.064 0.002 0.014 0 0.026-0.002 0.042-0.002 114.654 0 229.308-43.738 316.788-131.214 87.472-87.47 131.21-202.114 131.216-316.76l0-0.024zM772.216 772.214c-60 59.998-137.072 96.702-220.258 105.626v-133.84c0-22.090-17.914-40-40.004-40s-40 17.91-40 40v133.83c-83.154-8.942-160.194-45.64-220.172-105.618-59.986-59.988-96.686-137.042-105.624-220.21h133.84c22.090 0 40-17.914 40-40.004s-17.91-40-40-40h-133.84c8.936-83.17 45.636-160.226 105.624-220.214 59.978-59.976 137.020-96.676 220.172-105.622v133.836c0 22.094 17.91 40 40 40s40.004-17.906 40.004-40v-133.844c83.184 8.926 160.258 45.63 220.258 105.63 59.986 59.986 96.688 137.042 105.624 220.212h-133.838c-22.094 0-40 17.91-40 40s17.906 40.004 40 40.004h133.838c-8.938 83.172-45.636 160.226-105.624 220.214z',
search:
'M218 670a318 318 0 0 1 0-451 316 316 0 0 1 451 0 318 318 0 0 1 0 451 316 316 0 0 1-451 0m750 240L756 698a402 402 0 1 0-59 60l212 212c16 16 42 16 59 0 16-17 16-43 0-60',
zoom:
'M220 670a316 316 0 0 1 0-450 316 316 0 0 1 450 0 316 316 0 0 1 0 450 316 316 0 0 1-450 0zm749 240L757 698a402 402 0 1 0-59 59l212 212a42 42 0 0 0 59-59zM487 604a42 42 0 0 1-84 0V487H286a42 42 0 1 1 0-84h117V286a42 42 0 1 1 84 0v117h117a42 42 0 0 1 0 84H487v117z',
zoomout:
'M757 698a402 402 0 1 0-59 59l212 212a42 42 0 0 0 59-59L757 698zM126 445a316 316 0 0 1 319-319 316 316 0 0 1 318 319 316 316 0 0 1-318 318 316 316 0 0 1-319-318zm160 42a42 42 0 1 1 0-84h318a42 42 0 0 1 0 84H286z',
zoomreset:
'M148 560a318 318 0 0 0 522 110 316 316 0 0 0 0-450 316 316 0 0 0-450 0c-11 11-21 22-30 34v4h47c25 0 46 21 46 46s-21 45-46 45H90c-13 0-25-6-33-14-9-9-14-20-14-33V156c0-25 20-45 45-45s45 20 45 45v32l1 1a401 401 0 0 1 623 509l212 212a42 42 0 0 1-59 59L698 757A401 401 0 0 1 65 570a42 42 0 0 1 83-10z',
timer:
'M576 540.658c0 35.344-28.654 64-64 64s-64-28.656-64-64c0-20.27 9.432-38.324 24.134-50.050v-193.418c-0.004-22.092 17.906-40.002 40-40 22.090 0 40 17.906 40 40l-0.004 193.626c14.552 11.732 23.87 29.692 23.87 49.842zM928.32 543.934c0 229.79-186.28 416.066-416.068 416.066-229.786 0-416.064-186.278-416.064-416.066 0-216.26 164.998-393.958 375.97-414.134l0.188-49.794h-16.348c-22.092 0-40.002-17.91-39.998-40 0-22.090 17.906-40.004 40-40.004l112 0.002c22.090-0.002 39.998 17.91 40 40 0 22.090-17.908 40-40 39.998h-15.656l-0.19 49.782c77.246 7.352 148.33 35.812 207.422 79.564l41.854-41.856c15.622-15.622 40.95-15.618 56.57 0.002s15.622 40.948 0 56.568l-38.9 38.9c67.822 74.028 109.22 172.66 109.22 280.972zM848.32 543.934c0-89.768-34.958-174.16-98.432-237.634s-147.87-98.432-237.636-98.432c-89.766 0-174.158 34.958-237.632 98.432s-98.432 147.868-98.432 237.634c0 89.766 34.958 174.16 98.432 237.636 63.474 63.472 147.868 98.43 237.632 98.43 89.768 0 174.162-34.958 237.636-98.43 63.476-63.476 98.432-147.87 98.432-237.636z',
time:
'M512 64c-247.424 0-448 200.578-448 448.004 0 247.422 200.576 448 448 448s448-200.578 448-448c0-247.424-200.576-448.004-448-448.004zM772.214 772.22c-69.508 69.504-161.918 107.786-260.214 107.786s-190.708-38.282-260.214-107.786c-69.508-69.508-107.786-161.918-107.786-260.214s38.278-190.708 107.786-260.214c69.508-69.504 161.918-107.786 260.214-107.786s190.708 38.278 260.214 107.786c69.504 69.508 107.786 161.918 107.786 260.214s-38.282 190.706-107.786 260.214zM768.004 517.004c0 22.090-17.91 40-40 40h-216c-5.384 0-10.508-1.078-15.196-3.008-0.124-0.046-0.254-0.086-0.376-0.132-0.61-0.262-1.188-0.57-1.782-0.86-0.572-0.278-1.16-0.528-1.718-0.828-0.204-0.114-0.39-0.246-0.594-0.364-0.918-0.516-1.832-1.050-2.704-1.64-0.086-0.058-0.164-0.128-0.254-0.188-10.492-7.21-17.382-19.286-17.382-32.98v-285c0-22.094 17.91-40 40.004-40 22.088 0 40 17.906 40 40v244.996h175.996c22.094 0 40.002 17.916 40.006 40.004z',
lightning:
'M320.022 1022.644c-7.408 0-14.852-2.052-21.44-6.238-15.292-9.714-22.144-28.494-16.706-45.774l115.186-365.908-214.552-52.57c-14.714-3.606-26.128-15.214-29.486-29.988-3.356-14.772 1.92-30.174 13.632-39.786l576-472.662c14.458-11.864 35.208-12.126 49.962-0.626 14.752 11.496 19.568 31.682 11.594 48.602l-171.202 363.256 208.648 51.756c14.29 3.544 25.476 14.652 29.124 28.914s-0.834 29.376-11.668 39.344l-512 471.112c-7.586 6.984-17.308 10.568-27.092 10.568zM279.236 493.49l178.314 43.69c10.74 2.632 19.912 9.59 25.336 19.226s6.62 21.086 3.298 31.636l-83.030 263.76 347.066-319.352-183.82-45.596c-11.63-2.884-21.356-10.832-26.498-21.656-5.144-10.822-5.164-23.382-0.054-34.22l116.31-246.788-376.922 309.3z',
dashboard:
'M567.594 674.956c-17.674 30.61-56.816 41.098-87.426 23.426-30.61-17.676-41.1-56.816-23.426-87.426 10.134-17.554 27.33-28.472 45.928-31.278l146.974-254.57c11.042-19.132 35.506-25.688 54.64-14.64 19.13 11.046 25.688 35.508 14.64 54.64l-147.084 254.75c6.736 17.434 5.826 37.648-4.246 55.098zM512.002 209.26c-98.296 0-190.708 38.28-260.214 107.786s-107.786 161.92-107.786 260.214c0 81.428 26.252 158.786 74.768 222.452 88.404-30.49 188.406-46.448 292.732-46.448 104.662 0 204.926 16.046 293.524 46.716 48.65-63.712 74.976-141.164 74.976-222.72 0-98.294-38.28-190.708-107.786-260.214s-161.918-107.786-260.214-107.786zM512.002 129.26c247.424 0 448 200.578 448 448 0 124.132-50.494 236.468-132.054 317.602-87.096-38.574-196.984-61.598-316.446-61.598-119.146 0-228.772 22.902-315.758 61.296-81.376-81.114-131.742-193.324-131.742-317.3 0-247.422 200.576-448 448-448v0z',
hourglass:
'M511.926 801.946c-22.090 0-40-17.906-40-40v0c0-22.090 17.91-40 40-40v0c22.090 0 40.004 17.91 40.004 40v0c0 22.094-17.914 40-40.004 40v0zM831.682 915.242c0.192 1.582 0.318 3.186 0.318 4.82 0 22.090-17.908 40-40 40h-560c-22.092 0-40-17.914-40-40 0-2.438 0.252-4.812 0.67-7.128 2.36-53.636 18.034-105.7 45.852-151.554 0.734-1.476 1.562-2.912 2.492-4.296l5.582-8.364c0.054-0.080 0.11-0.158 0.164-0.238 0.042-0.068 0.098-0.156 0.144-0.222l157.704-236.036-158.5-237.228c-0.116-0.17-0.23-0.342-0.34-0.516-32.842-49.178-51.11-105.994-53.368-165.044-0.238-1.762-0.402-3.546-0.402-5.374 0-22.090 17.908-40 40-40h560c22.092 0 40 17.914 40 40 0 2.056-0.204 4.064-0.504 6.038-2.194 54.020-17.886 106.48-45.894 152.648-0.734 1.472-1.562 2.91-2.492 4.294l-5.582 8.366c-0.054 0.078-0.11 0.156-0.164 0.236-0.042 0.068-0.098 0.154-0.144 0.222l-157.734 236.082 158.468 237.182c0.116 0.168 0.23 0.344 0.34 0.516 32.946 49.33 51.226 106.346 53.39 165.596zM749.958 144.060h-475.99c6.138 31.304 18.384 61.124 36.354 87.916 0.118 0.17 0.23 0.344 0.342 0.514l0.024 0.038c0.036 0.054 0.15 0.23 0.186 0.284l54.286 81.25h293.596l58.196-87.1c0.366-0.67 0.75-1.334 1.154-1.99 15.492-24.916 26.228-52.324 31.852-80.912zM497.528 512.178l-0.032 0.046 14.426 21.592 93.378-139.756h-186.692l78.92 118.118zM305.96 799.156c-15.498 24.91-26.234 52.318-31.856 80.906h476.052c-6.138-31.304-18.384-61.122-36.354-87.918-0.118-0.168-0.23-0.344-0.342-0.512l-0.024-0.040c-0.036-0.050-0.15-0.23-0.186-0.282l-140.242-209.902-28.98 43.374c-7.166 10.72-19.21 17.162-32.11 17.162-12.896 0-24.942-6.442-32.11-17.166l-28.76-43.044-143.938 215.428c-0.36 0.674-0.744 1.338-1.15 1.994z',
play:
'M878.78 477.856l-591.884-341.722c-9.464-5.464-18.426-8.050-26.386-8.048-19.516 0.002-33.002 15.546-33.002 42.338v683.446c0 26.792 13.482 42.338 33.002 42.338 7.96 0 16.924-2.586 26.386-8.048l591.884-341.722c32.664-18.864 32.664-49.724 0-68.582z',
stop:
'M960 512a448 448 0 1 0-896 0 448 448 0 0 0 896 0zM252 772a366 366 0 0 1 0-520 366 366 0 0 1 520 0 366 366 0 0 1 0 520 366 366 0 0 1-520 0zm412-68H360c-22 0-40-18-40-40V360c0-22 18-40 40-40h304c22 0 40 18 40 40v304c0 22-18 40-40 40z',
email:
'M960.032 268.004c0.748-10.040-2.246-20.364-9.226-28.684-5.984-7.132-13.938-11.62-22.394-13.394-0.13-0.026-0.268-0.066-0.396-0.092-1.082-0.22-2.172-0.376-3.272-0.5-0.25-0.032-0.492-0.080-0.742-0.102-1.028-0.096-2.052-0.136-3.090-0.156-0.292-0.002-0.582-0.042-0.876-0.042h-816.008c-21.416 0-38.848 16.844-39.898 38-0.034 0.628-0.092 1.256-0.096 1.89 0 0.034-0.006 0.074-0.006 0.114 0 0.050 0.008 0.102 0.008 0.152v495.692c0 0.054-0.008 0.106-0.008 0.156 0 22.090 17.91 40 40 40h816.004c13.808 0 25.98-6.996 33.17-17.636 0.1-0.148 0.182-0.312 0.28-0.458 0.606-0.93 1.196-1.868 1.722-2.84 0.046-0.082 0.080-0.172 0.124-0.258 2.992-5.604 4.704-12.008 4.704-18.804v0 0-493.038zM144.032 350.156l339.946 281.188c6.568 6.434 14.918 10.168 23.564 11.122 0.16 0.024 0.32 0.050 0.48 0.066 0.838 0.082 1.676 0.114 2.518 0.14 0.496 0.020 0.994 0.058 1.492 0.058s0.996-0.042 1.492-0.058c0.842-0.028 1.68-0.058 2.518-0.14 0.16-0.016 0.32-0.042 0.48-0.066 8.646-0.958 16.996-4.688 23.564-11.122l339.946-281.206v370.894h-736v-370.876zM215.066 305.030h593.91l-296.946 245.422-296.964-245.422z',
comment:
'M288 378.668h448c22.094 0 40 17.906 40 40 0 22.090-17.906 40-40 40h-448c-22.090 0-40-17.91-40-40s17.91-40 40-40zM736 565.334h-448c-22.090 0-40 17.91-40 40 0 22.094 17.91 40 40 40h448c22.094 0 40-17.906 40-40 0-22.090-17.906-40-40-40zM960 232.004v560c0 6.804-1.714 13.196-4.704 18.812-0.042 0.082-0.078 0.172-0.124 0.254-0.524 0.976-1.11 1.914-1.722 2.836-0.098 0.152-0.18 0.314-0.282 0.458-7.188 10.64-19.36 17.636-33.168 17.636h-519.766l-114.292 114.286c-8.036 8.046-18.644 11.91-29.18 11.67-0.292 0.008-0.582 0.046-0.876 0.046-22.090 0-40-17.91-40-40v-86.004h-111.886c-22.090 0-40-17.906-40-40v0-560c0-20.34 15.192-37.094 34.84-39.632 1.692-0.214 3.406-0.368 5.16-0.368h816c1.754 0 3.468 0.154 5.164 0.368 19.644 2.542 34.836 19.296 34.836 39.638zM880 272h-736v480h736v-480z',
requestchange:
'M925.164 193.396c-1.696-0.214-3.41-0.368-5.164-0.368h-816c-1.754 0-3.468 0.152-5.16 0.368-19.648 2.54-34.84 19.292-34.84 39.632v560c0 22.094 17.91 40 40 40h111.886v86.004c0 22.090 17.91 40 40 40 0.292 0 0.582-0.040 0.876-0.046 10.536 0.238 21.144-3.624 29.18-11.67l114.292-114.286h519.766c13.808 0 25.98-6.996 33.168-17.636 0.102-0.144 0.184-0.304 0.282-0.458 0.614-0.922 1.2-1.86 1.722-2.836 0.046-0.082 0.082-0.172 0.124-0.254 2.988-5.618 4.704-12.008 4.704-18.812v0-560c-0-20.346-15.192-37.098-34.836-39.638zM880 753.028h-736v-480h736v480zM756.334 484.17l-125-125.436c-15.594-15.65-40.92-15.692-56.568-0.1-15.648 15.594-15.694 40.92-0.1 56.568l57.004 57.204h-335.67c-22.092 0-40 17.908-40 40s17.908 40 40 40h335.258l-56.508 56.368c-15.64 15.602-15.672 40.928-0.070 56.57 7.814 7.832 18.066 11.752 28.32 11.75 10.22 0 20.442-3.892 28.25-11.68l125-124.688c15.634-15.596 15.672-40.912 0.084-56.556z',
link:
'M743.52 529.234c5.616-5.616 83.048-83.046 88.462-88.46 30.944-32.778 47.97-75.636 47.97-120.792 0-47.048-18.304-91.26-51.542-124.484-33.228-33.22-77.43-51.516-124.458-51.516-45.024 0-87.792 16.94-120.536 47.72l-104.458 104.456c-30.792 32.738-47.734 75.512-47.734 120.548 0 41.916 14.576 81.544 41.248 113.196 3.264 3.876 6.666 7.664 10.292 11.29 4.258 4.258 8.704 8.262 13.304 12.022 0.054 0.080 0.096 0.152 0.148 0.232 9.572 7.308 15.778 18.804 15.778 31.776 0 22.094-17.914 40-40.004 40-8.542 0-16.442-2.696-22.938-7.26-2.746-1.93-20.622-17.43-30.35-28.050-0.008-0.010-0.018-0.018-0.026-0.028-4.992-5.432-13.234-15.23-18.552-22.65s-16.556-25.872-17.036-26.736c-0.7-1.262-2.974-5.526-3.422-6.39-0.69-1.334-6.118-12.67-6.114-12.67-14.342-31.96-22.332-67.4-22.332-104.728 0-60.826 21.198-116.648 56.58-160.544 0.252-0.314 4.61-5.594 6.594-7.866 0.304-0.35 5.038-5.636 7.16-7.874 0.252-0.268 105.86-105.874 106.128-106.126 45.902-43.584 107.958-70.314 176.264-70.314 141.382 0 255.998 114.5 255.998 256 0 68.516-26.882 130.688-70.652 176.61-0.144 0.148-109.854 109.546-112.090 111.528-0.958 0.848-5.072 4.352-5.072 4.352-6.448 5.434-13.132 10.592-20.1 15.378 0.412-6.836 0.644-13.702 0.644-20.6 0-26.46-3.108-52.206-8.918-76.918l-0.236-1.102zM616.144 767.82c35.382-43.896 56.58-99.718 56.58-160.544 0-37.328-7.99-72.768-22.332-104.728 0.004 0 0.006-0.002 0.010-0.004-0.258-0.576-0.538-1.14-0.8-1.714-0.686-1.498-2.894-6.112-3.296-6.93-0.668-1.344-2.952-5.732-3.386-6.604-3.48-6.982-8.708-15.126-9.49-16.366-0.498-0.792-0.996-1.58-1.502-2.364-0.834-1.29-15.364-22.066-26.656-34.466-0.008-0.010-0.018-0.018-0.026-0.028-7.056-8.448-24.932-24.198-30.35-28.050-6.47-4.602-14.396-7.26-22.938-7.26-22.090 0-40.004 17.906-40.004 40 0 12.97 6.206 24.466 15.778 31.776 0.052 0.080 0.094 0.152 0.148 0.232 4.602 3.76 20.334 19.434 23.598 23.31 26.672 31.65 41.248 71.28 41.248 113.196 0 45.038-16.944 87.81-47.734 120.548l-104.458 104.456c-32.742 30.782-75.512 47.72-120.536 47.72-47.028 0-91.228-18.294-124.458-51.516-33.236-33.224-51.542-77.436-51.542-124.484 0-45.154 17.028-88.014 47.97-120.792 5.414-5.414 40.812-40.812 68.958-68.958 7.176-7.176 13.888-13.886 19.504-19.502v-0.002c-0.356-1.562-0.246-1.096-0.246-1.096-5.81-24.712-8.918-50.458-8.918-76.918 0-6.898 0.232-13.764 0.644-20.6-6.966 4.788-20.1 15.33-20.1 15.33-0.734 0.62-9.518 8.388-11.68 10.45-0.16 0.154-105.338 105.33-105.482 105.478-43.77 45.922-70.652 108.094-70.652 176.61 0 141.5 114.616 256 255.998 256 68.306 0 130.362-26.73 176.264-70.314 0.27-0.254 105.876-105.86 106.128-106.126 0.004-0.002 13.506-15.426 13.758-15.74z',
paperclip:
'M824.25 369.354c68.146-70.452 67.478-182.784-2.094-252.354-70.296-70.296-184.266-70.296-254.558 0-0.014 0.012-0.028 0.026-0.042 0.042-0.004 0.002-0.006 0.004-0.010 0.008l-433.144 433.142c-0.036 0.036-0.074 0.068-0.11 0.106-0.054 0.052-0.106 0.11-0.16 0.162l-2.668 2.67c-0.286 0.286-0.528 0.596-0.8 0.888-43.028 44.88-66.664 103.616-66.664 165.986 0 64.106 24.962 124.376 70.292 169.704 45.328 45.33 105.598 70.292 169.706 70.292 50.612 0 98.822-15.57 139.186-44.428 4.932-1.952 9.556-4.906 13.544-8.894l16.802-16.802c0.056-0.056 0.116-0.112 0.172-0.168 0.038-0.038 0.074-0.076 0.112-0.116l289.010-289.014c15.622-15.618 15.62-40.942 0-56.56s-40.948-15.62-56.566 0l-289.124 289.122c-62.482 62.484-163.792 62.484-226.274 0-62.484-62.482-62.484-163.79 0-226.272h-0.002l433.134-433.12c0.058-0.060 0.112-0.122 0.172-0.18 38.99-38.99 102.43-38.99 141.42 0 38.992 38.99 38.99 102.432 0 141.422-0.058 0.060-0.122 0.114-0.18 0.17l0.006 0.006-280.536 280.534c-0.002-0.002-0.002-0.004-0.004-0.006l-79.978 79.98c-0.010 0.010-0.016 0.020-0.028 0.028-0.008 0.012-0.018 0.018-0.028 0.028l-0.064 0.062c-15.622 15.624-40.944 15.624-56.562 0-15.624-15.62-15.624-40.944-0.002-56.566l0.062-0.062c0.010-0.010 0.018-0.020 0.028-0.028 0.008-0.012 0.020-0.018 0.028-0.028l79.98-79.978c-0.002-0.002-0.004-0.002-0.006-0.004l136.508-136.512c15.622-15.62 15.62-40.944-0.002-56.562-15.618-15.62-40.946-15.62-56.564 0l-219.342 219.344c-1.284 1.284-2.42 2.652-3.494 4.052-40.4 47.148-38.316 118.184 6.322 162.824 44.64 44.638 115.674 46.722 162.82 6.324 1.402-1.072 2.772-2.21 4.054-3.494l2.83-2.832c0.002 0 0.002 0 0.002 0s0 0 0 0l360.54-360.54c0.058-0.056 0.12-0.114 0.18-0.172 0.050-0.050 0.098-0.106 0.15-0.158l0.994-0.994c0.34-0.338 0.63-0.702 0.952-1.052z',
box:
'M960.016 408.080c0-0.672-0.046-1.342-0.078-2.014-0.032-0.594-0.044-1.19-0.102-1.782-0.068-0.726-0.186-1.448-0.294-2.17-0.080-0.54-0.144-1.080-0.248-1.616-0.138-0.724-0.326-1.442-0.506-2.16-0.134-0.534-0.252-1.070-0.408-1.6-0.196-0.662-0.436-1.314-0.668-1.968-0.204-0.582-0.396-1.166-0.628-1.74-0.226-0.56-0.494-1.11-0.75-1.662-0.3-0.656-0.598-1.312-0.934-1.954-0.242-0.454-0.514-0.894-0.774-1.342-0.414-0.716-0.83-1.43-1.292-2.124-0.256-0.382-0.538-0.752-0.806-1.128-0.514-0.716-1.036-1.428-1.602-2.116-0.090-0.11-0.162-0.226-0.254-0.336-0.244-0.292-0.516-0.542-0.768-0.826-0.534-0.6-1.068-1.198-1.644-1.772-0.48-0.478-0.982-0.924-1.48-1.376-0.354-0.316-0.674-0.658-1.040-0.964l-405.788-335.666c-6.568-6.436-14.918-10.166-23.564-11.124-0.16-0.022-0.32-0.050-0.48-0.066-0.838-0.082-1.676-0.11-2.518-0.14-0.496-0.020-0.994-0.058-1.492-0.058s-0.996 0.040-1.492 0.058c-0.842 0.028-1.68 0.058-2.518 0.14-0.16 0.016-0.32 0.044-0.48 0.066-8.646 0.956-16.996 4.688-23.564 11.124l-405.662 335.542c-7.13 5.982-11.616 13.93-13.392 22.382-0.032 0.14-0.070 0.278-0.1 0.42-0.212 1.072-0.37 2.152-0.494 3.238-0.032 0.258-0.078 0.51-0.106 0.77-0.086 0.89-0.114 1.786-0.138 2.68-0.014 0.39-0.052 0.78-0.054 1.17 0 0.040-0.006 0.074-0.006 0.114v204.856c-0.958 12.434 3.854 25.128 14.134 33.754l405.662 335.54c6.568 6.438 14.918 10.168 23.564 11.124 0.16 0.020 0.32 0.050 0.48 0.066 0.838 0.082 1.676 0.114 2.518 0.14 0.496 0.020 0.994 0.058 1.492 0.058 0.054 0 0.11-0.008 0.162-0.008 0.042 0 0.084 0.008 0.126 0.008 0.342 0 0.672-0.042 1.012-0.050 0.062-0.004 0.126-0.008 0.192-0.008 0.134-0.004 0.27-0.020 0.402-0.024 10.602-0.422 20.136-4.938 27.054-12.046l404.526-334.624c0.084-0.066 0.166-0.136 0.248-0.204l0.12-0.098c0.17-0.144 0.314-0.304 0.48-0.45 0.814-0.704 1.614-1.43 2.37-2.2 0.296-0.3 0.562-0.624 0.85-0.934 0.602-0.652 1.2-1.308 1.756-2 0.3-0.372 0.566-0.758 0.852-1.136 0.504-0.672 1.002-1.344 1.462-2.046 0.242-0.368 0.458-0.75 0.686-1.124 0.458-0.754 0.908-1.508 1.316-2.292 0.164-0.312 0.304-0.636 0.46-0.954 0.426-0.872 0.832-1.746 1.196-2.652 0.092-0.23 0.168-0.464 0.256-0.696 0.376-0.996 0.728-2 1.026-3.032 0.042-0.148 0.074-0.296 0.114-0.442 0.306-1.102 0.578-2.218 0.79-3.356 0.016-0.082 0.024-0.164 0.038-0.246 0.212-1.184 0.382-2.378 0.49-3.598v0c0.1-1.156 0.176-2.32 0.176-3.5v-204.86c0.024-0.318 0.022-0.638 0.040-0.958 0.026-0.668 0.074-1.338 0.074-2.008zM143.89 493.202l328.14 271.42v103.902l-328.14-271.18v-104.142zM552.032 764.402l327.868-271.212v103.88l-327.868 270.972v-103.64zM511.898 122.66l345.348 285.42-345.348 285.42-345.374-285.42 345.374-285.42z',
structure:
'M954.324 833.3c0.208-0.558 0.388-1.128 0.586-1.692 0.3-0.868 0.608-1.734 0.882-2.61 0.234-0.746 0.444-1.5 0.66-2.25 0.212-0.734 0.432-1.464 0.624-2.204 0.204-0.766 0.378-1.54 0.562-2.308 0.18-0.766 0.366-1.528 0.528-2.292 0.146-0.692 0.272-1.386 0.402-2.082 0.168-0.89 0.332-1.778 0.476-2.668 0.090-0.566 0.164-1.136 0.244-1.704 0.148-1.058 0.29-2.118 0.404-3.18 0.042-0.422 0.080-0.852 0.12-1.274 0.118-1.23 0.212-2.46 0.282-3.696 0.018-0.304 0.030-0.606 0.042-0.906 0.062-1.36 0.098-2.718 0.104-4.082 0-0.114 0.008-0.226 0.008-0.34 0-0.128-0.010-0.258-0.010-0.39-0.006-1.368-0.042-2.734-0.104-4.102-0.014-0.296-0.030-0.594-0.044-0.89-0.070-1.246-0.166-2.492-0.284-3.738-0.042-0.434-0.084-0.864-0.128-1.292-0.116-1.050-0.25-2.098-0.4-3.144-0.088-0.628-0.18-1.258-0.282-1.882-0.13-0.8-0.276-1.598-0.428-2.394-0.162-0.868-0.332-1.73-0.518-2.594-0.116-0.524-0.24-1.046-0.364-1.57-0.264-1.128-0.542-2.25-0.846-3.36-0.070-0.254-0.144-0.504-0.214-0.754-11.38-40.382-48.464-69.996-92.488-69.996-3.066 0-6.096 0.16-9.088 0.442l-264.576-458.262c21.080-29.698 24.3-70.13 4.9-103.732-12.596-21.816-32.458-36.812-54.764-43.724-0.062-0.020-0.124-0.036-0.186-0.054-1.394-0.43-2.798-0.83-4.21-1.196-0.296-0.076-0.596-0.142-0.894-0.216-1.208-0.3-2.422-0.586-3.642-0.84-0.384-0.082-0.774-0.148-1.16-0.224-1.168-0.228-2.338-0.444-3.514-0.626-0.384-0.060-0.776-0.112-1.162-0.168-1.208-0.174-2.416-0.332-3.63-0.46-0.35-0.038-0.7-0.066-1.048-0.1-1.27-0.12-2.54-0.218-3.814-0.29-0.32-0.018-0.642-0.032-0.964-0.044-1.294-0.058-2.594-0.094-3.892-0.1-0.166 0-0.328-0.012-0.492-0.012-0.19 0-0.376 0.014-0.564 0.014-1.21 0.008-2.42 0.040-3.63 0.092-0.494 0.022-0.986 0.046-1.478 0.074-0.992 0.060-1.986 0.136-2.978 0.226-0.722 0.064-1.442 0.134-2.16 0.214-0.696 0.080-1.392 0.17-2.090 0.266-1.014 0.136-2.026 0.286-3.032 0.452-0.352 0.060-0.704 0.124-1.054 0.19-44.97 8.028-79.122 47.302-79.122 94.582 0 20.756 6.602 39.958 17.79 55.67l-264.58 458.26c-2.954-0.274-5.94-0.434-8.962-0.434-53.078 0-96.11 43.032-96.11 96.11 0 53.082 43.032 96.11 96.11 96.11 38.8 0 72.208-23.004 87.386-56.11l529.202-0.004c0.138 0.304 0.292 0.606 0.436 0.91 0.226 0.48 0.456 0.958 0.69 1.434 0.474 0.968 0.966 1.93 1.476 2.882 0.214 0.402 0.432 0.8 0.65 1.2 0.314 0.566 0.604 1.14 0.93 1.708 0.284 0.488 0.59 0.958 0.88 1.442 0.122 0.2 0.244 0.398 0.37 0.602 27.086 44.372 84.766 59.278 130.040 33.136 18.864-10.89 32.624-27.214 40.478-45.852 0.054-0.132 0.104-0.266 0.158-0.398 0.518-1.248 1.020-2.506 1.486-3.776zM238.414 744.282l264.542-458.204c0.424 0.042 0.85 0.064 1.276 0.098 0.668 0.056 1.334 0.112 2.004 0.152 0.652 0.040 1.306 0.066 1.96 0.092 1.122 0.046 2.244 0.076 3.368 0.084 0.146 0.002 0.292 0.012 0.438 0.012 0.168 0 0.334-0.012 0.502-0.014 1.436-0.004 2.874-0.040 4.31-0.108 0.088-0.006 0.176-0.010 0.262-0.014 1.376-0.070 2.75-0.168 4.124-0.296l264.596 458.298c-3.48 4.894-6.514 10.122-9.042 15.636h-529.226c-2.546-5.55-5.602-10.814-9.114-15.736z',
cpu:
'M392.016 672.016h240.032c22.092 0 40-17.908 40-40v-240.032c0-22.092-17.908-40-40-40h-240.032c-22.092 0-40 17.908-40 40v240.032c0 22.092 17.908 40 40 40zM432.016 431.984h160.032v160.032h-160.032v-160.032zM864.032 424h71.98c22.094 0 40.004-17.906 40.004-40 0-22.092-17.906-40-40-40h-71.984v-143.968c0-22.092-17.908-40-40-40h-144v-72.012c0-22.094-17.906-40.004-40-40.004-22.090 0-40 17.906-40 40v72.016h-176v-72.012c0-22.094-17.906-40.004-40-40.004-22.090 0-40 17.906-40 40v72.016h-144c-22.092 0-40 17.908-40 40v143.968h-71.984c-22.094 0-40 17.908-40 40s17.91 40 40 40h71.984v176h-71.984c-22.094 0-40 17.908-40 40s17.91 40 40 40h71.984v144.030c0 22.092 17.908 40 40 40h144v71.954c0 22.094 17.906 40 40 40s40-17.91 40-40v-71.954h176v71.954c0 22.094 17.906 40 40 40s40-17.91 40-40v-71.954h144c22.092 0 40-17.908 40-40v-144.030h71.98c22.094 0 40.004-17.906 40.004-40 0-22.092-17.906-40-40-40h-71.984v-176zM784.032 784.032h-143.692c-0.104 0-0.204-0.016-0.308-0.016s-0.206 0.016-0.308 0.016h-127.382c-0.104 0-0.204-0.016-0.308-0.016s-0.206 0.016-0.308 0.016h-127.382c-0.104 0-0.204-0.016-0.308-0.016s-0.206 0.016-0.308 0.016h-143.696v-544h544v544z',
memory:
'M320.032 416.032v-152.968c0-22.094 17.91-40 40-40 22.094 0 40 17.91 40 40.004v152.964c0 22.090-17.906 40-40 40s-40-17.908-40-40zM512 456.032c22.094 0 40-17.91 40-40v-152.964c0-22.094-17.906-40.004-40-40.004-22.090 0-40 17.906-40 40v152.968c0 22.092 17.908 40 40 40zM664.032 456.032c22.094 0 40-17.91 40-40v-82.996c0-22.094-17.906-40.004-40-40.004-22.090 0-40 17.906-40 40v83c0 22.092 17.906 40 40 40zM864.018 316.616v603.418c0 0.004 0 0.004 0 0.004 0 6.798-1.71 13.198-4.704 18.808-0.044 0.084-0.078 0.172-0.124 0.254-0.524 0.976-1.112 1.914-1.722 2.836-0.098 0.15-0.18 0.312-0.282 0.46-7.188 10.638-19.36 17.634-33.168 17.634h-623.99c-22.090 0-40-17.908-40-40v-343.574c-0.002-0.142-0.022-0.282-0.022-0.426 0-0.142 0.020-0.282 0.022-0.426v-471.574c0-20.34 15.192-37.092 34.838-39.63 1.694-0.216 3.408-0.37 5.162-0.37l411.254 0.052c10.594-0.286 21.282 3.58 29.368 11.668l211.672 212.206c7.906 7.908 11.792 18.298 11.696 28.66zM240.026 144.034v391.998h543.99v-203.27l-188.252-188.728h-355.738zM784.016 880.032v-264h-543.99v264h543.99z',
database:
'M895.95 221.364c-3.414-87.32-173.972-157.672-383.918-157.672s-380.504 70.352-383.918 157.672h-0.082v578.328c0 88.552 171.918 160.338 384 160.338s384-71.786 384-160.338v-578.328h-0.082zM798.412 430.578c-15.6 11.386-37.69 22.346-63.882 31.696-60.984 21.77-140.002 33.758-222.498 33.758s-161.514-11.988-222.498-33.758c-26.192-9.348-48.282-20.308-63.88-31.696-8.706-6.352-13.646-11.608-16.122-14.874v-92.9c70.29 37.478 179.654 61.566 302.5 61.566s232.21-24.088 302.5-61.566v92.9c-2.476 3.266-7.416 8.522-16.12 14.874zM814.532 514.464v93.24c-2.474 3.266-7.416 8.522-16.12 14.874-15.6 11.386-37.69 22.346-63.882 31.696-60.984 21.77-140.002 33.758-222.498 33.758s-161.514-11.988-222.498-33.758c-26.192-9.348-48.282-20.308-63.88-31.696-8.706-6.352-13.646-11.608-16.122-14.874v-93.24c70.29 37.48 179.654 61.566 302.5 61.566s232.21-24.086 302.5-61.566zM225.652 209.146c15.6-11.386 37.69-22.346 63.88-31.696 60.984-21.77 140.002-33.758 222.498-33.758s161.514 11.988 222.498 33.758c26.192 9.348 48.282 20.308 63.882 31.696 8.704 6.352 13.646 11.608 16.12 14.874v0.026c-2.474 3.266-7.416 8.522-16.12 14.874-15.6 11.386-37.69 22.346-63.882 31.696-60.984 21.77-140.002 33.758-222.498 33.758s-161.514-11.988-222.498-33.758c-26.192-9.348-48.282-20.308-63.88-31.696-8.706-6.352-13.646-11.608-16.122-14.874v-0.026c2.476-3.268 7.418-8.524 16.122-14.874zM798.412 814.578c-15.6 11.386-37.69 22.346-63.882 31.696-60.984 21.77-140.002 33.758-222.498 33.758s-161.514-11.988-222.498-33.758c-26.192-9.348-48.282-20.308-63.88-31.696-8.714-6.36-13.66-11.62-16.13-14.886h0.010v-93.228c70.29 37.48 179.654 61.566 302.5 61.566s232.21-24.086 302.5-61.566v93.228h0.010c-2.474 3.266-7.42 8.526-16.132 14.886z',
power:
'M472 473.188v-368c-0.004-22.092 17.906-40.002 40-40 22.090 0 40 17.906 40 40l-0.004 368.002c0.004 22.088-17.906 39.996-39.996 39.998-22.094 0.002-40.004-17.906-40-40zM746.804 201.726v0.188c-13.138-9.004-26.808-17.292-40.978-24.768-1.994-1.050-3.492-1.84-4.668-2.458-1.75-0.892-3.518-1.756-5.28-2.624-0.004-0.002-0.008-0.004-0.012-0.006-0.080-0.032-0.158-0.074-0.234-0.108-0.032-0.012-0.056-0.024-0.090-0.042l-0.006 0.008c-4.724-2.022-9.924-3.168-15.386-3.212-22.090-0.178-40.14 17.588-40.32 39.678-0.122 15.112 8.166 28.298 20.47 35.208 31.9 15.71 61.418 36.616 87.492 62.292 2.796 2.754 5.52 5.562 8.208 8.394v-0.146c59.436 62.664 92.062 144.352 92.062 231.056 0 89.748-34.95 174.124-98.412 237.588s-147.84 98.412-237.588 98.412-174.124-34.95-237.588-98.412-98.412-147.84-98.412-237.588c0-81.652 28.962-158.834 81.972-219.886 5.814-6.69 11.902-13.192 18.288-19.474 26.064-25.652 55.564-46.538 87.446-62.238 12.342-6.892 20.66-20.106 20.542-35.238-0.17-22.088-18.218-39.86-40.306-39.69-5.468 0.044-10.664 1.186-15.392 3.208l-0.004-0.008c-0.036 0.016-0.058 0.028-0.088 0.042-0.042 0.018-0.084 0.038-0.126 0.056-1.862 0.918-3.728 1.828-5.574 2.774-0.458 0.238-0.948 0.496-1.512 0.792-1.096 0.566-2.18 1.148-3.27 1.722-15.704 8.294-30.804 17.572-45.232 27.736v-0.124c-106.896 75.288-176.742 199.646-176.742 340.33 0 229.75 186.25 416 416 416s416-186.25 416-416c-0.002-142.654-71.82-268.52-181.26-343.462z',
outbox:
'M960.062 616v304c0 1.382-0.070 2.746-0.208 4.090-2.046 20.172-19.080 35.91-39.792 35.91h-816c-22.090 0-40-17.906-40-40v-304c0-22.090 17.91-40 40-40s40 17.91 40 40v264h736v-264c0-22.090 17.91-40 40-40s40 17.912 40 40zM664.732 200.168l-124.41-124.41c-0.014-0.014-0.024-0.028-0.038-0.042-3.57-3.57-7.664-6.284-12.018-8.222-5.316-2.368-11.028-3.54-16.742-3.47-0.14-0.002-0.276-0.020-0.414-0.020-13.552 0-25.512 6.756-32.748 17.072l-119.1 119.092c-15.622 15.62-15.618 40.948 0.002 56.57 15.622 15.62 40.95 15.62 56.568 0l55.276-55.276v462.54c0 22.094 17.912 40 40.002 40 22.092 0 40-17.91 40-40v-464.314l57.052 57.052c15.622 15.624 40.948 15.62 56.568 0 15.628-15.624 15.628-40.952 0.002-56.572z',
share:
'M896.006 920c0 22.090-17.91 40-40 40h-688.006c-22.090 0-40-17.906-40-40v-549.922c-0.838-3.224-1.33-6.588-1.33-10.072 0-22.090 17.908-40.004 40-40.004h178.66c22.092 0.004 40 17.914 40 40.004 0 22.088-17.908 40-40 40h-137.33v479.996h607.998v-479.996h-138.658c-22.090 0-40-17.912-40-40 0-22.090 17.906-40.004 40-40.004h178.658c22.090 0 40 17.91 40 40v559.844c0 0.050 0.008 0.102 0.008 0.154zM665.622 200.168l-124.452-124.45c-8.042-8.042-18.65-11.912-29.186-11.674-1.612-0.034-3.222 0-4.828 0.16-0.558 0.054-1.098 0.16-1.648 0.238-0.742 0.104-1.484 0.192-2.218 0.338-0.656 0.13-1.29 0.31-1.934 0.472-0.622 0.154-1.244 0.292-1.86 0.476-0.64 0.196-1.258 0.436-1.886 0.66-0.602 0.216-1.208 0.414-1.802 0.66-0.598 0.248-1.17 0.54-1.754 0.814-0.598 0.282-1.202 0.546-1.788 0.86-0.578 0.312-1.13 0.664-1.694 1-0.552 0.332-1.116 0.644-1.654 1.006-0.67 0.448-1.3 0.942-1.942 1.426-0.394 0.302-0.806 0.576-1.196 0.894-1.046 0.858-2.052 1.768-3.008 2.726l-124.398 124.39c-15.622 15.62-15.618 40.948 0.002 56.57 15.622 15.62 40.95 15.62 56.568 0l56.164-56.166v439.426c0 22.094 17.912 40 40.002 40 22.092 0 40-17.91 40-40v-441.202l57.942 57.942c15.622 15.624 40.948 15.62 56.568 0 15.626-15.618 15.626-40.946 0.002-56.566z',
button:
'M644.634 802.32c-4.558 5.434-10.254 9.328-16.446 11.672l0.008 0.024-45.628 16.606 27.54 75.66c7.554 20.756-3.148 43.71-23.906 51.266s-43.714-3.146-51.27-23.906l-27.54-75.656-47.63 17.29c-6.020 1.956-12.586 2.518-19.254 1.342-21.75-3.836-36.282-24.582-32.45-46.34l30.57-173.328c2.55-14.476 12.61-25.714 25.458-30.508 0.292-0.118 0.586-0.23 0.878-0.34 0.238-0.084 0.476-0.168 0.718-0.246 12.942-4.624 27.91-2.492 39.196 6.98l134.824 113.13c16.932 14.2 19.144 39.432 4.932 56.354zM960.002 664v-368.082c0-22.092-17.908-40-40-40h-816c-22.092 0-40 17.908-40 40l-0.292 368.238c0 22.092 17.908 40 40 40h240.292c22.092 0 40-17.908 40-40s-17.908-40-40-40h-200.292l0.292-288.238h736v288.082h-200c-22.092 0-40 17.908-40 40s17.908 40 40 40h240c22.092 0 40-17.908 40-40z',
form:
'M948.362 178.828l-471.082 470.086c-0.24 0.25-0.45 0.52-0.698 0.77-7.82 7.82-18.070 11.722-28.32 11.712-10.25 0.010-20.504-3.892-28.324-11.712-0.262-0.262-0.48-0.546-0.734-0.812l-221.736-221.738c-15.624-15.622-15.624-40.95 0-56.566 15.618-15.622 40.946-15.624 56.57 0l194.224 194.222 443.53-442.528c15.622-15.618 40.95-15.618 56.57 0 15.62 15.62 15.62 40.946 0 56.566zM98.372 128.448c-18.926 0-34.266 15.342-34.266 34.268v699.032c0 18.926 15.34 34.266 34.266 34.266h699.032c18.926 0 34.266-15.34 34.266-34.266v-430.588c0 0 0.002-1.184 0.002-1.788 0-22.090-17.914-40-40.004-40s-40 17.91-40 40c0 0.288 0.002 386.64 0.002 386.64h-607.562v-607.564h600.002c22.090-0.002 40.002-17.906 40.002-40 0-22.090-17.914-40-40.004-40z',
check:
'M948.598 199.75c-15.622-15.618-40.95-15.618-56.57 0l-535.644 535.644-224.060-224.062c-15.624-15.624-40.954-15.62-56.57 0-15.624 15.62-15.624 40.948 0 56.568l251.574 251.574c0.252 0.266 0.472 0.55 0.734 0.812 7.82 7.82 18.072 11.724 28.322 11.714 10.25 0.010 20.502-3.894 28.322-11.714 0.248-0.248 0.456-0.518 0.698-0.77l563.196-563.202c15.618-15.618 15.618-40.94-0.002-56.564z',
batchaccept:
'M684 277L271 772l-1 1a40 40 0 0 1-56 5l-1-1L14 610a40 40 0 1 1 52-61l169 142 387-465a40 40 0 0 1 62 51zm340 234c0-22-18-40-40-40H808a40 40 0 0 0 0 80h176c22 0 40-18 40-40zm0-216c0-22-18-40-40-40H808a40 40 0 0 0 0 80h176c22 0 40-18 40-40zm0 432c0-22-18-40-40-40H808a40 40 0 0 0 0 80h176c22 0 40-18 40-40z',
batchdeny:
'M1024 512c0-22-18-40-40-40H808a40 40 0 0 0 0 80h176c22 0 40-18 40-40zm0-216c0-22-18-40-40-40H808a40 40 0 0 0 0 80h176c22 0 40-18 40-40zm0 432c0-22-18-40-40-40H808a40 40 0 0 0 0 80h176c22 0 40-18 40-40zM625 236c16 15 16 41 0 56L406 512l220 220a40 40 0 1 1-57 57L349 568 129 788a40 40 0 1 1-57-56l220-220L73 292a40 40 0 0 1 56-57l220 220 219-219c16-16 41-16 57 0z',
home:
'M948.12 483.624l-407.814-407.754c-7.812-7.808-18.046-11.712-28.282-11.712-10.238 0-20.472 3.904-28.282 11.712l-407.92 407.86c-15.624 15.622-15.624 40.948-0.006 56.57s40.944 15.622 56.568 0.004l19.616-19.612v366.708c0 22.090 17.91 40 40 40h190.696c0.416 0.014 0.82 0.062 1.238 0.062 11.054 0 21.060-4.484 28.3-11.734 7.266-7.244 11.766-17.262 11.766-28.332 0-0.418-0.050-0.822-0.062-1.238v-263.204h176.060v263.934c0 22.090 17.91 40 40 40l191.876 0.124c2.292 0 4.524-0.236 6.708-0.608 0.45-0.074 0.91-0.116 1.356-0.206 0.21-0.044 0.414-0.116 0.628-0.162 17.906-3.972 31.308-19.924 31.308-39.026v-366.492l19.682 19.68c15.622 15.62 40.948 15.616 56.568-0.006s15.618-40.948-0.004-56.568zM791.876 448.272v398.71l-111.874-0.074v-263.876c0-0.020-0.002-0.042-0.002-0.062 0-0.006 0-0.014 0-0.022 0-22.090-17.91-40-40-40h-254.002c-0.556 0-1.1 0.060-1.65 0.084-0.14-0.002-0.274-0.022-0.414-0.022-22.090 0-40 17.91-40 40v264.382h-111.934v-399.392c0-2.286-0.234-4.512-0.604-6.694l280.626-280.584 280.514 280.472c-0.412 2.302-0.66 4.658-0.66 7.078z',
admin:
'M919.596 847.534h-88.414v-467.716l88.75-0.044c13.688-0.132 26.958-7.25 34.294-19.96 11.044-19.13 4.49-43.596-14.642-54.64l-407.904-235.676c-0.44-0.254-0.894-0.45-1.34-0.684-0.542-0.29-1.084-0.578-1.638-0.84-0.696-0.328-1.4-0.62-2.108-0.904-0.478-0.194-0.954-0.388-1.44-0.56-0.78-0.282-1.564-0.524-2.352-0.754-0.442-0.126-0.878-0.256-1.324-0.37-0.808-0.206-1.618-0.376-2.43-0.528-0.468-0.088-0.934-0.174-1.404-0.246-0.768-0.116-1.534-0.204-2.302-0.274-0.554-0.052-1.108-0.096-1.664-0.124-0.672-0.034-1.34-0.044-2.012-0.044-0.67 0-1.338 0.012-2.010 0.044-0.556 0.030-1.11 0.072-1.664 0.124-0.77 0.070-1.536 0.158-2.302 0.274-0.468 0.072-0.938 0.158-1.402 0.246-0.814 0.152-1.624 0.322-2.432 0.528-0.444 0.114-0.882 0.242-1.322 0.37-0.79 0.23-1.574 0.472-2.356 0.754-0.484 0.172-0.958 0.368-1.438 0.56-0.708 0.286-1.41 0.576-2.11 0.904-0.554 0.262-1.094 0.55-1.636 0.84-0.446 0.234-0.9 0.43-1.34 0.684l-407.906 235.672c-19.128 11.044-25.686 35.51-14.64 54.64 7.34 12.71 20.606 19.828 34.292 19.96v0.044h89.842v467.716h-89.474c-22.090 0-40 17.91-40 40s17.91 40 40 40h128.276c0.402 0.012 0.794 0.060 1.2 0.060s0.796-0.048 1.2-0.060h183.602c0.402 0.012 0.794 0.060 1.2 0.060s0.796-0.048 1.2-0.060h183.602c0.402 0.012 0.794 0.060 1.2 0.060s0.796-0.048 1.2-0.060h313.154c22.098 0 40-17.91 40-40-0.006-22.090-17.914-39.996-40.006-39.996zM751.182 847.534h-105.94v-467.716h105.94v467.716zM252.93 299.816l258.736-149.486 258.738 149.486h-517.474zM565.242 379.816v467.716h-106v-467.716h106zM273.242 379.816h106v467.716h-106v-467.716z',
paragraph:
'M728.032 96.032h-116.98c-0.026 0-0.050-0.004-0.076-0.004s-0.050 0.004-0.076 0.004h-199.848c-0.026 0-0.050-0.004-0.076-0.004s-0.050 0.004-0.076 0.004h-31.924c-123.712 0-224 100.292-224 224 0 121.032 95.994 219.628 216 223.842v344.158c0 22.092 17.91 40 40 40 22.086 0 40-17.908 40-40v-712h120v712c0 22.092 17.91 40 40 40 22.086 0 40-17.908 40-40v-712h77.056c22.094 0 40-17.91 40-40 0-22.092-17.91-40-40-40z',
basket:
'M632.254 695.604v-112.016c-0.004-22.092 17.906-40.002 40-40.002 22.090 0.002 40 17.908 40 40.002l-0.004 112.018c0.004 22.088-17.906 39.996-39.996 39.998-22.094 0.002-40.004-17.904-40-40zM352.246 735.604c22.090-0.002 40-17.91 39.996-39.998l0.004-112.018c0-22.094-17.91-40-40-40.002-22.094 0-40.004 17.91-40 40.002v112.016c-0.004 22.096 17.906 40.002 40 40zM512.25 735.604c22.090-0.002 40-17.91 39.996-39.998l0.004-112.018c0-22.094-17.91-40-40-40.002-22.094 0-40.004 17.91-40 40.002v112.016c-0.004 22.096 17.906 40.002 40 40zM950.3 397.424c-7.596-8.686-18.574-13.67-30.114-13.67h-313.284c0.87 5.196 1.346 10.524 1.346 15.966 0 24.608-9.27 47.044-24.494 64.034h290.684l-47.318 351.376-629.908-0.030-47.502-351.346h291.034c-15.224-16.988-24.494-39.426-24.494-64.034 0-5.444 0.476-10.772 1.346-15.966h-313.66c-11.542 0-22.524 4.986-30.12 13.678-7.596 8.694-11.066 20.242-9.52 31.682l51.614 381.742 0.050 0.042c5.832 47.424 46.222 84.158 95.222 84.172l0.054 0.034 601.816-0.034c0.042 0 0.082 0.002 0.124 0.002 49.414 0 90.090-37.34 95.396-85.336l51.258-380.64c1.54-11.44-1.934-22.984-9.53-31.672zM805.492 105.34c-15.622-15.622-40.95-15.624-56.572 0.004l-230.684 230.684c-2.052-0.2-4.132-0.306-6.236-0.306-35.346 0-64 28.654-64 64s28.654 64 64 64 64-28.654 64-64c0-2.652-0.18-5.262-0.494-7.83l229.986-229.98c15.622-15.624 15.616-40.95-0-56.572z',
credit:
'M376.188 672.062h-112.124c-22.092 0-40-17.908-40-40s17.908-40 40-40h112.124c22.092 0 40 17.908 40 40s-17.908 40-40 40zM960 232.002v560c0 6.8-1.708 13.2-4.704 18.81-0.044 0.082-0.078 0.172-0.124 0.254-0.524 0.974-1.112 1.914-1.722 2.836-0.098 0.15-0.18 0.31-0.282 0.458-7.188 10.64-19.36 17.638-33.168 17.638h-816c-22.090 0-40-17.908-40-40v-559.998c0-20.34 15.192-37.092 34.838-39.628 1.694-0.218 3.408-0.372 5.162-0.372h816c1.754 0 3.468 0.152 5.162 0.372 19.646 2.536 34.838 19.288 34.838 39.63zM144 272.002v80.030h736v-80.030h-736zM880 751.998v-239.966h-736v239.966h736z',
shield:
'M875.146 148.994c-0.064-0.040-0.116-0.094-0.184-0.132-92.714-52.39-221.036-84.83-362.846-84.83-138.512 0-270.346 34.356-362.51 84.618-0.606 0.33-1.138 0.658-1.608 0.986-11.954 6.918-20.016 19.81-20.016 34.614v451.4c0 12.7 5.938 23.996 15.166 31.32l340.538 281.676c6.568 6.434 14.918 10.168 23.564 11.122 0.16 0.024 0.32 0.050 0.48 0.066 0.838 0.082 1.676 0.114 2.518 0.14 0.496 0.020 0.994 0.058 1.492 0.058s0.996-0.040 1.492-0.058c0.842-0.032 1.68-0.058 2.518-0.14 0.16-0.016 0.32-0.042 0.48-0.066 8.646-0.958 16.996-4.688 23.564-11.122l339.36-280.718c10.326-7.23 17.094-19.2 17.094-32.762v-450.918c0.002-15.254-8.54-28.506-21.102-35.254zM207.984 208.212c36.292-18.168 77.668-32.854 123.356-43.722 57.062-13.576 117.884-20.458 180.778-20.458s123.714 6.882 180.778 20.458c30.186 7.182 58.474 16.040 84.674 26.456l-490.846 490.848-78.738-65.070v-408.512zM511.742 867.75l-163.078-134.77 467.586-467.584v350.69l-304.508 251.664z',
beaker:
'M848.64 790.56l-208.638-361.374v-252.062h24c22.092 0 40-17.908 40-40s-17.908-40-40-40h-304.002c-22.092 0-40 17.908-40 40s17.908 40 40 40h24v252.066l-208.636 361.37c-44 76.208-8 138.564 80 138.564h513.278c87.998 0 123.998-62.354 79.998-138.564zM464 177.124h96.002l-0.070 273.376 63.872 110.628h-223.678c35.932-62.268 63.872-110.684 63.876-110.692v-273.312zM768.64 849.124h-513.278c-8.28 0-14.186-0.976-17.968-2 1.004-3.792 3.112-9.394 7.25-16.564 0 0 54.598-94.614 109.316-189.436l316.026-0.002 109.374 189.44c4.138 7.168 6.246 12.77 7.25 16.562-3.784 1.024-9.69 2-17.97 2z',
thumbsup:
'M256.972 768.004c0-8.67-3.156-16.158-9.484-22.534-6.332-6.34-13.836-9.484-22.504-9.458-8.682 0-16.188 3.172-22.516 9.458-6.33 6.344-9.488 13.84-9.488 22.534 0 8.692 3.158 16.186 9.488 22.532 6.328 6.286 13.834 9.458 22.516 9.458 8.668 0.028 16.172-3.118 22.504-9.458 6.328-6.376 9.484-13.868 9.484-22.532zM832.948 480.010c0-17.004-6.478-31.908-19.468-44.734-13.014-12.82-27.834-19.25-44.512-19.276h-175.97c0-19.328 7.98-45.904 24.004-79.724 15.968-33.826 23.978-60.568 23.978-80.256 0-32.646-5.332-56.808-15.994-72.48-10.664-15.664-31.988-23.484-63.98-23.484-8.696 8.64-15.012 22.828-19.032 42.486-4.020 19.69-9.102 40.606-15.254 62.752-6.168 22.172-16.080 40.382-29.762 54.738-7.344 7.68-20.168 22.832-38.5 45.496-1.326 1.67-5.164 6.65-11.512 15.010-6.342 8.342-11.594 15.178-15.762 20.508-4.156 5.308-9.91 12.386-17.252 21.218-7.328 8.862-14 16.186-19.988 22.038-5.986 5.794-12.412 11.73-19.26 17.744-6.852 5.984-13.508 10.5-19.99 13.48-6.478 3.010-12.4 4.484-17.756 4.512h-15.982v320.010h15.982c4.332 0 9.596 0.492 15.774 1.504 6.168 1.012 11.676 2.080 16.488 3.258 4.812 1.144 11.154 2.98 19.002 5.466 7.862 2.512 13.702 4.424 17.502 5.74 3.812 1.31 9.732 3.422 17.756 6.238 8.026 2.842 12.866 4.586 14.506 5.272 70.324 24.334 127.304 36.504 170.996 36.504h60.482c64.006 0 96.024-27.836 96.024-83.478 0-8.664-0.848-18.016-2.514-27.996 10.004-5.334 17.936-14.084 23.758-26.276 5.824-12.172 8.724-24.416 8.778-36.746 0-12.366-3.008-23.844-9.024-34.51 17.664-16.682 26.524-36.496 26.524-59.496 0-8.308-1.696-17.554-5.032-27.72-3.336-10.202-7.492-18.104-12.468-23.762 10.636-0.328 19.55-8.15 26.714-23.486 7.192-15.34 10.744-28.82 10.744-40.496v-0.054zM896.984 479.516c0 29.638-8.204 56.816-24.5 81.506 2.98 10.994 4.484 22.476 4.484 34.482 0 25.674-6.344 49.68-19.004 71.99 1.012 7 1.506 14.164 1.506 21.488 0 33.688-10.008 63.354-29.968 89.026 0.326 46.32-13.834 82.904-42.518 109.756-28.682 26.848-66.522 40.246-113.496 40.246h-64.528c-31.99 0-63.542-3.746-94.742-11.268-31.168-7.492-67.246-18.402-108.23-32.758-38.662-13.312-61.656-19.956-68.984-19.956h-143.996c-17.664 0-32.742-6.292-45.252-18.784-12.508-12.5-18.756-27.588-18.756-45.254v-319.982c0-17.666 6.248-32.728 18.756-45.226 12.51-12.52 27.588-18.784 45.252-18.784h136.998c12.002-8.010 34.818-33.822 68.478-77.484 19.33-24.99 37.168-46.344 53.508-64.008 7.996-8.314 13.918-22.586 17.744-42.766 3.828-20.178 8.912-41.232 15.256-63.24 6.36-21.984 16.68-40.002 30.994-53.998 13.002-12.362 28.012-18.514 45.018-18.514 27.998 0 53.152 5.414 75.464 16.242 22.31 10.828 39.316 27.748 50.964 50.77 11.704 23.002 17.5 53.978 17.5 92.962 0 31.008-7.984 63-23.98 96.028h88.014c34.67 0 64.634 12.628 89.956 37.98 25.346 25.346 38.008 55.144 38.008 89.49l0.054 0.056z',
mirror:
'M857 127.778h-688c-22.092 0-40 17.91-40 40v688c0 22.090 17.908 40 40 40h688c22.094 0 40-17.91 40-40v-688c0-22.092-17.906-40-40-40zM817 815.778h-608v-1.086l606.914-606.914h1.086v608z',
switchalt:
'M923.946 63.418h-631.232c-20.268 0-36.7 16.432-36.7 36.7v155.286h-155.284c-20.268 0-36.7 16.432-36.7 36.7v631.23c0 20.268 16.43 36.7 36.7 36.7h631.23c20.272 0 36.7-16.432 36.7-36.7v-155.286h155.286c20.272 0 36.7-16.432 36.7-36.7v-631.23c-0.002-20.268-16.43-36.7-36.7-36.7zM688.66 880.032h-544.628v-544.628h111.984v395.946c0 20.268 16.43 36.7 36.7 36.7h395.944v111.982zM688.66 688.046h-352.644v-352.644h352.644v352.644zM880.644 688.046h-111.984v-395.946c0-20.268-16.428-36.7-36.7-36.7h-395.944v-111.984h544.628v544.63z',
commit:
'M984.032 472h-186.808c-19.474-140.12-139.74-248-285.222-248s-265.748 107.88-285.222 248h-186.746c-22.092 0-40 17.912-40 40.002 0 22.092 17.91 40 40 40h186.746c19.476 140.122 139.74 247.998 285.222 247.998s265.746-107.876 285.222-247.998h186.808c22.092 0 40-17.91 40-40s-17.908-40.002-40-40.002zM512 720c-114.692 0-208-93.308-208-208s93.308-208 208-208 208 93.308 208 208-93.308 208-208 208z',
branch:
'M861.968 312.032c0-66.168-53.832-120-120-120s-120 53.832-120 120c0 50.55 31.436 93.87 75.77 111.516-5.384 20.352-15.71 39.68-29.844 54.92-28.828 31.092-72.202 46.858-128.91 46.858-77.162 0-129.12 26.162-162.984 55.12V297.15c46.556-16.512 80-60.974 80-113.12 0-66.168-53.832-120-120-120s-120 53.832-120 120c0 52.146 33.444 96.608 80 113.12v429.762c-46.556 16.512-80 60.974-80 113.12 0 66.168 53.832 120 120 120s120-53.832 120-120c0-50.926-31.902-94.514-76.758-111.908 5.222-26.17 16.578-51.154 32.558-70.432 28.8-34.746 71.592-52.364 127.184-52.364 99.498 0 156.922-39.408 187.574-72.466 27.402-29.554 45.708-67.194 52.48-106.716 48.078-15.66 82.93-60.882 82.93-114.114zM336 144.032c22.056 0 40 17.944 40 40s-17.944 40-40 40-40-17.944-40-40 17.944-40 40-40zm0 736c-22.056 0-40-17.944-40-40s17.944-40 40-40 40 17.944 40 40-17.944 40-40 40zm405.968-528c-22.056 0-40-17.944-40-40s17.944-40 40-40 40 17.944 40 40-17.942 40-40 40z',
merge:
'M776.306 456.032c-51.602 0-95.696 32.744-112.612 78.542-69.674-6.072-141.482-31.012-197.386-69.306-46.266-31.69-100.392-85.728-111.792-168.92 45.4-17.12 77.79-60.998 77.79-112.314 0-66.168-53.832-120-120-120s-120 53.832-120 120c0 52.146 33.444 96.608 80 113.12v429.762c-46.556 16.512-80 60.974-80 113.12 0 66.168 53.832 120 120 120s120-53.832 120-120c0-52.146-33.444-96.608-80-113.12V471.444c19.622 21.888 42.618 41.898 68.792 59.828 68.422 46.868 156.64 77.042 241.646 83.462 16.14 47.23 60.932 81.3 113.56 81.3 66.168 0 120-53.832 120-120s-53.83-120.002-119.998-120.002zm-464-312c22.056 0 40 17.944 40 40s-17.944 40-40 40-40-17.944-40-40 17.942-40 40-40zm0 736c-22.056 0-40-17.944-40-40s17.944-40 40-40 40 17.944 40 40-17.944 40-40 40zm464-264c-22.056 0-40-17.944-40-40s17.944-40 40-40 40 17.944 40 40-17.944 40-40 40z',
pullrequest:
'M631 157c104 1 171 52 171 166v397a123 123 0 1 1-82 0V323c0-63-27-83-90-84h-24l22 23a41 41 0 1 1-58 58l-93-93a41 41 0 0 1 1-58l93-93a41 41 0 1 1 58 58l-23 23h25zM222 314a123 123 0 1 1 82 0v406a123 123 0 1 1-82 0V314zm41 564a41 41 0 1 0 0-82 41 41 0 0 0 0 82zm0-639a41 41 0 1 0 0-83 41 41 0 0 0 0 83zm498 639a41 41 0 1 0 0-82 41 41 0 0 0 0 82z',
chroma:
'M511.714 956.324c-92.92 0-168.518-75.594-168.518-168.514v-334.082l131.54 75.954v215.936c0 13.172 7.082 25.446 18.48 32.030l139.33 80.43c8.33 4.814 17.014 9.168 25.872 12.966-29.646 52.72-85.44 85.28-146.704 85.28zM753.584 816.61c-29.36 0-58.43-7.812-84.064-22.59l-83.828-48.404 289.354-167.028c8.3-4.802 16.402-10.152 24.132-15.936 30.858 52.030 31.182 116.622 0.568 169.664-30.034 51.994-86.040 84.294-146.162 84.294zM270.334 816.576c-60.084 0-116.064-32.278-146.102-84.238-22.494-39.012-28.466-84.426-16.814-127.866 11.68-43.512 39.564-79.858 78.522-102.334l83.806-48.398 0.018 334.018c0 9.624 0.57 19.294 1.69 28.814-0.374 0.002-0.748 0.004-1.12 0.004zM548.73 529.73l186.996-107.966c11.416-6.588 18.506-18.864 18.506-32.040v-160.856c0.012-9.456-0.56-19.116-1.706-28.778 0.364-0.002 0.732-0.004 1.096-0.004 60.114 0 116.104 32.296 146.124 84.29 46.436 80.486 18.75 183.742-61.714 230.176l-289.302 167.040v-151.862zM325.248 357.624c-5.632-3.242-12.030-4.954-18.504-4.954-6.428 0-12.804 1.708-18.44 4.936l-139.344 80.452c-8.348 4.802-16.462 10.142-24.172 15.912-30.824-52-31.14-116.59-0.546-169.664 30.048-52 86.050-84.306 146.148-84.306 29.326 0 58.394 7.822 84.064 22.624l289.3 167.054-131.482 75.91-187.024-107.964zM390.964 158.644c-8.334-4.826-17.036-9.192-25.92-13.004 29.634-52.742 85.418-85.316 146.67-85.316 92.92 0 168.514 75.6 168.514 168.522v96.81l-289.264-167.012z',
twitter:
'M960 233.114c-32.946 14.616-68.41 24.5-105.598 28.942 37.954-22.762 67.098-58.774 80.856-101.688-35.52 21.054-74.894 36.368-116.726 44.598-33.542-35.724-81.316-58.038-134.204-58.038-101.496 0-183.796 82.292-183.796 183.814 0 14.424 1.628 28.45 4.758 41.89-152.75-7.668-288.22-80.872-378.876-192.072-15.822 27.15-24.898 58.706-24.898 92.42 0 63.776 32.458 120.034 81.782 153.010-30.116-0.944-58.458-9.212-83.262-22.982-0.028 0.75-0.028 1.546-0.028 2.324 0 89.070 63.356 163.334 147.438 180.256-15.426 4.186-31.664 6.426-48.442 6.426-11.836 0-23.35-1.146-34.574-3.28 23.406 73.006 91.286 126.16 171.726 127.632-62.914 49.324-142.18 78.696-228.314 78.696-14.828 0-29.448-0.876-43.842-2.568 81.33 52.138 177.96 82.574 281.786 82.574 338.11 0 523-280.104 523-523.014 0-7.986-0.164-15.914-0.542-23.778 35.952-25.96 67.124-58.318 91.756-95.162z',
google:
'M799.094 79.996c0 0-200.938 0-267.936 0-120.126 0-233.188 91.004-233.188 196.434 0 107.692 81.904 194.624 204.124 194.624 8.496 0 16.75-0.148 24.812-0.74-7.942 15.186-13.594 32.286-13.594 50.022 0 29.974 16.094 54.226 36.466 74.042-15.376 0-30.248 0.438-46.438 0.438-148.782 0.036-263.312 94.784-263.312 193.056 0 96.758 125.534 157.312 274.312 157.312 169.656 0 263.312-96.25 263.312-193.024 0-77.6-22.908-124.062-93.686-174.156-24.216-17.128-70.534-58.812-70.534-83.32 0-28.69 8.19-42.868 51.406-76.624 44.346-34.63 75.688-83.302 75.688-139.944 0-67.372-30-133.058-86.374-154.746h85l59.942-43.374zM701.504 735.438c2.092 8.992 3.276 18.226 3.276 27.624 0 78.226-50.374 139.304-194.934 139.304-102.874 0-177.124-65.078-177.124-143.304 0-76.622 92.122-140.434 194.934-139.32 24.004 0.254 46.376 4.136 66.69 10.702 55.812 38.834 95.874 60.808 107.158 104.994zM536.844 443.782c-69-2.094-134.624-77.212-146.564-167.876-11.874-90.664 34.378-160.030 103.442-157.97 68.996 2.060 134.594 74.818 146.53 165.432 11.906 90.696-34.408 162.508-103.408 160.414z',
gdrive:
'M465.926 641.356l-149.328 258.708h494.074l149.328-258.708h-494.074zM917.704 567.988l-256.33-444.048h-298.686l256.356 444.048h298.66zM320.236 197.442l-256.236 443.914 149.36 258.708 256.23-443.914-149.354-258.708z',
youtube:
'M704.010 511.988c0-12.332-5.038-21.358-15.042-26.992l-255.982-159.99c-10.344-6.666-21.178-6.998-32.51-1.008-10.988 5.984-16.492 15.312-16.492 28.002v320c0 12.69 5.504 22.018 16.492 28.002 5.332 2.678 10.516 3.996 15.506 3.996 6.668 0 12.334-1.644 17.004-4.98l255.982-160.014c10.004-5.69 15.042-14.684 15.042-26.992v-0.024zM960 511.988c0 31.99-0.164 56.98-0.488 75.032-0.334 17.99-1.754 40.738-4.27 68.25-2.516 27.504-6.262 52.058-11.27 73.742-5.332 24.338-16.84 44.85-34.504 61.496-17.64 16.63-38.306 26.308-61.96 28.988-73.992 8.342-185.824 12.526-335.508 12.526-149.668 0-261.5-4.184-335.5-12.526-23.662-2.656-44.414-12.302-62.242-28.988-17.834-16.678-29.412-37.182-34.744-61.496-4.672-21.684-8.258-46.238-10.756-73.742-2.508-27.512-3.928-50.26-4.254-68.25-0.342-18.050-0.504-43.042-0.504-75.032 0-31.998 0.162-57.010 0.504-75.008 0.326-18.022 1.746-40.768 4.254-68.28 2.498-27.474 6.262-52.082 11.252-73.744 5.34-24.336 16.842-44.842 34.504-61.496 17.648-16.654 38.324-26.332 61.986-29.010 74-8.312 185.832-12.472 335.5-12.472 149.684 0 261.516 4.16 335.508 12.472 23.654 2.678 44.406 12.356 62.232 29.010 17.826 16.678 29.422 37.16 34.73 61.496 4.702 21.662 8.256 46.27 10.772 73.744 2.516 27.512 3.936 50.258 4.27 68.28 0.324 17.998 0.488 43.010 0.488 75.008z',
facebook:
'M582.52 960h-167.88v-448h-112v-154.396l112-0.052-0.166-90.948c-0.036-125.974 34.12-202.604 182.484-202.604h123.542v154.424h-77.19c-57.782 0-60.566 21.56-60.566 61.85l-0.218 77.278h138.854l-16.376 154.394-122.36 0.052-0.124 448.002z',
medium:
'M0 0v1024h1024v-1024h-1024zM850.708 242.614l-54.918 52.655c-3.858 2.965-6.321 7.581-6.321 12.772 0 0.933 0.080 1.847 0.232 2.736l-0.014-0.095v386.883c-0.139 0.794-0.219 1.708-0.219 2.641 0 5.191 2.462 9.807 6.283 12.744l0.038 0.028 53.637 52.655v11.558h-269.774v-11.558l55.559-53.936c5.461-5.456 5.461-7.068 5.461-15.413v-312.719l-154.477 392.344h-20.874l-179.851-392.344v262.947c-0.209 1.465-0.329 3.156-0.329 4.875 0 9.848 3.924 18.78 10.293 25.317l-0.008-0.008 72.258 87.649v11.558h-204.895v-11.558l72.263-87.649c6.070-6.284 9.81-14.852 9.81-24.293 0-2.081-0.182-4.12-0.53-6.101l0.031 0.21v-304.044c0.086-0.804 0.135-1.737 0.135-2.682 0-7.844-3.389-14.896-8.782-19.773l-0.023-0.021-64.234-77.378v-11.558h199.438l154.157 338.083 135.53-338.083h190.123v11.558z',
graphql:
'M896.38 635.332c-7.286-4.206-14.934-7.196-22.714-9.074v-228.148c7.788-1.882 15.44-4.874 22.732-9.082 40.902-23.614 54.92-75.934 31.3-116.846-23.62-40.914-75.942-54.932-116.846-31.318-7.286 4.21-13.704 9.34-19.22 15.14l-197.586-114.076c2.266-7.68 3.502-15.802 3.502-24.212 0-47.232-38.3-85.53-85.544-85.53-47.242 0-85.544 38.298-85.544 85.53 0 8.42 1.238 16.552 3.508 24.24l-197.598 114.046c-5.518-5.802-11.936-10.93-19.218-15.138-40.902-23.614-93.22-9.596-116.846 31.318-23.62 40.91-9.6 93.228 31.3 116.846 7.29 4.208 14.94 7.202 22.728 9.082v228.15c-7.782 1.878-15.434 4.866-22.718 9.074-40.91 23.62-54.93 75.938-31.31 116.848 23.624 40.914 75.944 54.932 116.856 31.312 7.28-4.206 13.692-9.334 19.206-15.13l197.588 114.080c-2.262 7.68-3.498 15.792-3.498 24.2 0 47.244 38.302 85.544 85.546 85.544 47.242 0 85.542-38.302 85.542-85.544 0-9.362-1.524-18.36-4.308-26.79l196.558-113.484c5.914 6.624 12.946 12.446 21.046 17.126 40.912 23.618 93.23 9.602 116.856-31.314 23.618-40.914 9.598-93.232-31.318-116.85zM253.492 689.212c-1.88-7.73-4.856-15.33-9.038-22.568-4.142-7.18-9.194-13.516-14.892-18.98l258.558-447.814c7.58 2.198 15.586 3.402 23.878 3.402 8.262 0 16.242-1.196 23.802-3.38l258.574 447.85c-5.676 5.456-10.704 11.77-14.834 18.928-4.182 7.238-7.162 14.838-9.042 22.566l-517.006-0.004zM771.404 291.408c-6.156 21.512-3.936 45.396 8.138 66.306 12.066 20.91 31.638 34.772 53.348 40.2v228.538c-1.074 0.266-2.144 0.56-3.208 0.868l-258.56-447.826c0.804-0.768 1.596-1.556 2.372-2.354l197.91 114.268zM450.526 177.162c0.75 0.772 1.516 1.536 2.296 2.282l-258.578 447.856c-1.038-0.3-2.084-0.586-3.134-0.85v-228.536c21.708-5.428 41.276-19.29 53.348-40.202 12.074-20.91 14.294-44.794 8.134-66.306l197.934-114.244zM575.392 849.216c-15.65-17.262-38.256-28.108-63.39-28.108-24.152 0-45.946 10.026-61.5 26.112l-197.908-114.266c0.28-0.986 0.544-1.98 0.794-2.972h517.226c0.464 1.888 0.976 3.756 1.57 5.61l-196.792 113.624z',
redux:
'M359.016 943.608c-23.82 5.948-47.642 8.322-71.512 8.322-88.208 0-168.084-36.982-207.444-96.534-52.432-79.882-70.296-249.182 102.538-374.356 3.586 19.078 10.746 45.292 15.492 60.834-22.656 16.652-58.39 50.064-81.046 95.324-32.19 63.184-28.61 126.404 9.54 184.798 26.194 39.304 67.926 63.176 121.564 70.34 65.598 8.332 131.154-3.582 194.332-36.94 92.998-48.898 155.014-107.282 195.49-187.162-10.702-10.75-17.818-26.248-19.074-44.15-1.168-36.942 27.45-67.922 64.388-69.132h2.418c35.73 0 65.55 28.61 66.714 64.384 1.206 35.73-24.986 65.546-59.548 69.132-65.6 134.686-181.254 225.312-333.852 255.14zM902.646 540.622c-90.59-106.072-224.11-164.488-376.708-164.488h-19.072c-10.744-21.444-33.402-35.752-58.388-35.752h-2.418c-36.944 1.186-65.548 32.192-64.392 69.13 1.216 35.774 30.99 64.394 66.81 64.394h2.328c26.242-1.208 48.894-17.892 58.434-40.542h21.45c90.624 0 176.46 26.234 253.968 77.482 59.55 39.36 102.49 90.576 126.356 152.596 20.24 50.052 19.074 98.952-2.42 140.64-33.356 63.228-89.37 97.794-163.292 97.794-47.69 0-92.998-14.33-116.822-25.082-13.118 11.958-36.984 31.028-53.64 42.944 51.226 23.87 103.7 36.94 153.762 36.94 114.446 0 199.070-63.132 231.268-126.362 34.562-69.13 32.188-188.326-57.224-289.694zM297.046 708.706c1.21 35.828 30.984 64.394 66.764 64.394h2.368c36.992-1.168 65.556-32.15 64.39-69.132-1.162-35.732-30.984-64.394-66.758-64.394h-2.376c-2.418 0-5.958 0-8.332 1.208-48.89-81.090-69.132-169.27-62.014-264.648 4.792-71.528 28.616-133.516 70.346-184.766 34.568-44.106 101.326-65.57 146.598-66.758 126.402-2.396 180.044 154.968 183.576 218.144 15.542 3.584 41.734 11.936 59.644 17.892-14.328-193.118-133.526-293.266-247.97-293.266-107.28 0-206.236 77.484-245.552 191.932-54.848 152.596-19.070 299.212 47.644 414.826-5.912 8.374-9.494 21.498-8.328 34.568z',
github:
'M512.062 64.032c-247.426 0-448 200.576-448 448s200.574 448 448 448c247.422 0 448-200.576 448-448s-200.578-448-448-448zM251.846 772.246c-69.506-69.508-107.784-161.918-107.784-260.214 0-98.294 38.278-190.708 107.784-260.216 69.508-69.504 161.92-107.784 260.216-107.784s190.708 38.28 260.214 107.784c69.504 69.508 107.786 161.922 107.786 260.216 0 98.296-38.282 190.708-107.786 260.214-42.852 42.848-94.41 73.806-150.684 91.27v-65.104c0-34.584-11.86-60.022-35.578-76.31 14.864-1.43 28.512-3.43 40.942-6.002 12.434-2.572 25.578-6.292 39.442-11.146s26.292-10.644 37.3-17.364c11-6.712 21.574-15.434 31.718-26.15s18.648-22.866 25.508-36.444c6.864-13.57 12.292-29.866 16.292-48.874 4.004-19.006 6-39.944 6-62.802 0-44.3-14.434-82.032-43.296-113.182 13.14-34.294 11.714-71.594-4.29-111.894l-10.718-1.286c-7.43-0.858-20.79 2.286-40.082 9.434-19.29 7.144-40.942 18.864-64.95 35.152-34.016-9.432-69.308-14.148-105.894-14.148-36.87 0-72.024 4.716-105.46 14.148-15.144-10.29-29.51-18.79-43.086-25.508s-24.436-11.29-32.582-13.718c-8.144-2.43-15.718-3.93-22.722-4.5-7-0.574-11.5-0.714-13.504-0.43-2 0.286-3.43 0.572-4.288 0.86-16.004 40.582-17.436 77.88-4.288 111.894-28.868 31.152-43.3 68.878-43.3 113.178 0 22.866 2 43.798 6.002 62.804 4 19.010 9.432 35.296 16.292 48.876s15.364 25.722 25.508 36.442c10.146 10.718 20.72 19.438 31.724 26.152s23.436 12.504 37.298 17.362c13.862 4.858 27.008 8.574 39.442 11.146 12.434 2.57 26.080 4.574 40.942 6.002-23.438 16.004-35.152 41.444-35.152 76.31v66.404c-57.936-17.198-111.030-48.638-154.966-92.572z',
bitbucket:
'M512.157 32c-219.6 0-400.001 61.279-400.001 138.881 0 20.4 47.040 310.481 66.641 424.8 7.841 53.28 137.359 126.72 333.36 126.72 196.080 0 321.6-73.601 333.36-126.641 19.601-114.4 66.641-404.479 66.641-424.8-3.919-77.76-180.401-138.96-400.001-138.96v0zM512.157 628.4c-70.56 0-125.52-57.2-125.52-130.722s54.96-130.72 125.52-130.72c70.56 0 125.52 57.199 125.52 130.721 0 69.439-54.96 130.721-125.52 130.721zM512.157 211.76c-141.199 0-254.88-24.559-254.88-57.199 0-32.719 113.681-57.199 254.88-57.199s254.88 24.48 254.88 57.199c0 32.64-113.681 57.199-254.88 57.199zM801.597 706.081c7.84 0 11.76 8.16 7.84 16.32v4.002c-15.679 85.84-27.439 147.199-27.439 155.28-11.76 61.279-129.439 110.321-270.641 110.321-141.12 0-258.8-49.039-270.56-110.321 0-8.16-11.76-69.439-27.439-155.201v-4.081c0-12.24 7.841-16.319 15.679-16.319 4.409 0.751 8.359 2.145 11.962 4.1l-0.202-0.101c0 0 98.081 81.761 274.481 81.761 176.479 0 274.56-81.679 274.56-81.679s3.919-4.080 11.76-4.080l0.001-0.002zM512.157 558.961c-34.639 0-62.719-29.279-62.719-65.359s28.001-65.359 62.719-65.359c34.639 0 62.719 29.279 62.719 65.359s-28.001 65.359-62.719 65.359z',
gitlab:
'M511.989 937.076l-175.718-538.045h351.434l-175.717 538.045zM90.107 399.031l421.88 538.045-462.033-334.102c-9.156-6.631-15.047-17.289-15.047-29.321 0-3.985 0.645-7.821 1.839-11.406l-0.072 0.255 53.431-163.471zM90.107 399.031l105.75-324.083c2.508-7.304 9.319-12.457 17.334-12.457s14.825 5.153 17.294 12.329l0.042 0.128 105.749 324.082-246.165 0.001zM933.869 399.031l53.431 163.474c1.133 3.347 1.788 7.203 1.788 11.215 0 12.038-5.895 22.705-14.961 29.262l-0.104 0.072-462.034 334.022 421.88-538.046zM933.869 399.031h-246.162l105.75-324.083c2.543-7.242 9.325-12.341 17.292-12.341s14.748 5.096 17.256 12.212l0.042 0.127 105.825 324.083z',
};
export default icons;
| lib/components/src/icon/icons.js | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.004466954618692398,
0.0007569875451736152,
0.00016506151587236673,
0.00040369335329160094,
0.0009027795167639852
]
|
{
"id": 6,
"code_window": [
" } else {\n",
" showNopreview();\n",
" addons.getChannel().emit(Events.STORY_MISSING, storyStore.getSelection());\n",
" }\n",
" previousRevision = revision;\n",
" previousKind = kind;\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" addons.getChannel().emit(Events.STORY_MISSING);\n"
],
"file_path": "lib/core/src/client/preview/start.js",
"type": "replace",
"edit_start_line_idx": 141
} | // !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 46;
objects = {
/* Begin PBXBuildFile section */
00C302E51ABCBA2D00DB3ED1 /* libRCTActionSheet.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302AC1ABCB8CE00DB3ED1 /* libRCTActionSheet.a */; };
00C302E71ABCBA2D00DB3ED1 /* libRCTGeolocation.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302BA1ABCB90400DB3ED1 /* libRCTGeolocation.a */; };
00C302E81ABCBA2D00DB3ED1 /* libRCTImage.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302C01ABCB91800DB3ED1 /* libRCTImage.a */; };
00C302E91ABCBA2D00DB3ED1 /* libRCTNetwork.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302DC1ABCB9D200DB3ED1 /* libRCTNetwork.a */; };
00C302EA1ABCBA2D00DB3ED1 /* libRCTVibration.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302E41ABCB9EE00DB3ED1 /* libRCTVibration.a */; };
00E356F31AD99517003FC87E /* react_nativeTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 00E356F21AD99517003FC87E /* react_nativeTests.m */; };
133E29F31AD74F7200F7D852 /* libRCTLinking.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 78C398B91ACF4ADC00677621 /* libRCTLinking.a */; };
139105C61AF99C1200B5F7CC /* libRCTSettings.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 139105C11AF99BAD00B5F7CC /* libRCTSettings.a */; };
139FDEF61B0652A700C62182 /* libRCTWebSocket.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 139FDEF41B06529B00C62182 /* libRCTWebSocket.a */; };
13B07FBC1A68108700A75B9A /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB01A68108700A75B9A /* AppDelegate.m */; };
13B07FBD1A68108700A75B9A /* LaunchScreen.xib in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB11A68108700A75B9A /* LaunchScreen.xib */; };
13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB51A68108700A75B9A /* Images.xcassets */; };
13B07FC11A68108700A75B9A /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB71A68108700A75B9A /* main.m */; };
140ED2AC1D01E1AD002B40FF /* libReact.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 146834041AC3E56700842450 /* libReact.a */; };
146834051AC3E58100842450 /* libReact.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 146834041AC3E56700842450 /* libReact.a */; };
2D02E4BC1E0B4A80006451C7 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB01A68108700A75B9A /* AppDelegate.m */; };
2D02E4BD1E0B4A84006451C7 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB51A68108700A75B9A /* Images.xcassets */; };
2D02E4BF1E0B4AB3006451C7 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB71A68108700A75B9A /* main.m */; };
2D02E4C21E0B4AEC006451C7 /* libRCTAnimation-tvOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 5E9157351DD0AC6500FF2AA8 /* libRCTAnimation-tvOS.a */; };
2D02E4C31E0B4AEC006451C7 /* libRCTImage-tvOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 3DAD3E841DF850E9000B6D8A /* libRCTImage-tvOS.a */; };
2D02E4C41E0B4AEC006451C7 /* libRCTLinking-tvOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 3DAD3E881DF850E9000B6D8A /* libRCTLinking-tvOS.a */; };
2D02E4C51E0B4AEC006451C7 /* libRCTNetwork-tvOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 3DAD3E8C1DF850E9000B6D8A /* libRCTNetwork-tvOS.a */; };
2D02E4C61E0B4AEC006451C7 /* libRCTSettings-tvOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 3DAD3E901DF850E9000B6D8A /* libRCTSettings-tvOS.a */; };
2D02E4C71E0B4AEC006451C7 /* libRCTText-tvOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 3DAD3E941DF850E9000B6D8A /* libRCTText-tvOS.a */; };
2D02E4C81E0B4AEC006451C7 /* libRCTWebSocket-tvOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 3DAD3E991DF850E9000B6D8A /* libRCTWebSocket-tvOS.a */; };
2D02E4C91E0B4AEC006451C7 /* libReact.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 3DAD3EA31DF850E9000B6D8A /* libReact.a */; };
2DCD954D1E0B4F2C00145EB5 /* react_nativeTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 00E356F21AD99517003FC87E /* react_nativeTests.m */; };
5E9157361DD0AC6A00FF2AA8 /* libRCTAnimation.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 5E9157331DD0AC6500FF2AA8 /* libRCTAnimation.a */; };
832341BD1AAA6AB300B99B32 /* libRCTText.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 832341B51AAA6A8300B99B32 /* libRCTText.a */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
00C302AB1ABCB8CE00DB3ED1 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 00C302A71ABCB8CE00DB3ED1 /* RCTActionSheet.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 134814201AA4EA6300B7C361;
remoteInfo = RCTActionSheet;
};
00C302B91ABCB90400DB3ED1 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 00C302B51ABCB90400DB3ED1 /* RCTGeolocation.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 134814201AA4EA6300B7C361;
remoteInfo = RCTGeolocation;
};
00C302BF1ABCB91800DB3ED1 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 00C302BB1ABCB91800DB3ED1 /* RCTImage.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 58B5115D1A9E6B3D00147676;
remoteInfo = RCTImage;
};
00C302DB1ABCB9D200DB3ED1 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 00C302D31ABCB9D200DB3ED1 /* RCTNetwork.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 58B511DB1A9E6C8500147676;
remoteInfo = RCTNetwork;
};
00C302E31ABCB9EE00DB3ED1 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 00C302DF1ABCB9EE00DB3ED1 /* RCTVibration.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 832C81801AAF6DEF007FA2F7;
remoteInfo = RCTVibration;
};
00E356F41AD99517003FC87E /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 83CBB9F71A601CBA00E9B192 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 13B07F861A680F5B00A75B9A;
remoteInfo = react_native;
};
139105C01AF99BAD00B5F7CC /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 139105B61AF99BAD00B5F7CC /* RCTSettings.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 134814201AA4EA6300B7C361;
remoteInfo = RCTSettings;
};
139FDEF31B06529B00C62182 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 139FDEE61B06529A00C62182 /* RCTWebSocket.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 3C86DF461ADF2C930047B81A;
remoteInfo = RCTWebSocket;
};
146834031AC3E56700842450 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 83CBBA2E1A601D0E00E9B192;
remoteInfo = React;
};
2D02E4911E0B4A5D006451C7 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 83CBB9F71A601CBA00E9B192 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 2D02E47A1E0B4A5D006451C7;
remoteInfo = "react_native-tvOS";
};
3DAD3E831DF850E9000B6D8A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 00C302BB1ABCB91800DB3ED1 /* RCTImage.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 2D2A283A1D9B042B00D4039D;
remoteInfo = "RCTImage-tvOS";
};
3DAD3E871DF850E9000B6D8A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 78C398B01ACF4ADC00677621 /* RCTLinking.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 2D2A28471D9B043800D4039D;
remoteInfo = "RCTLinking-tvOS";
};
3DAD3E8B1DF850E9000B6D8A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 00C302D31ABCB9D200DB3ED1 /* RCTNetwork.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 2D2A28541D9B044C00D4039D;
remoteInfo = "RCTNetwork-tvOS";
};
3DAD3E8F1DF850E9000B6D8A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 139105B61AF99BAD00B5F7CC /* RCTSettings.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 2D2A28611D9B046600D4039D;
remoteInfo = "RCTSettings-tvOS";
};
3DAD3E931DF850E9000B6D8A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 832341B01AAA6A8300B99B32 /* RCTText.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 2D2A287B1D9B048500D4039D;
remoteInfo = "RCTText-tvOS";
};
3DAD3E981DF850E9000B6D8A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 139FDEE61B06529A00C62182 /* RCTWebSocket.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 2D2A28881D9B049200D4039D;
remoteInfo = "RCTWebSocket-tvOS";
};
3DAD3EA21DF850E9000B6D8A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 2D2A28131D9B038B00D4039D;
remoteInfo = "React-tvOS";
};
3DAD3EA41DF850E9000B6D8A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 3D3C059A1DE3340900C268FA;
remoteInfo = yoga;
};
3DAD3EA61DF850E9000B6D8A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 3D3C06751DE3340C00C268FA;
remoteInfo = "yoga-tvOS";
};
3DAD3EA81DF850E9000B6D8A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 3D3CD9251DE5FBEC00167DC4;
remoteInfo = cxxreact;
};
3DAD3EAA1DF850E9000B6D8A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 3D3CD9321DE5FBEE00167DC4;
remoteInfo = "cxxreact-tvOS";
};
3DAD3EAC1DF850E9000B6D8A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 3D3CD90B1DE5FBD600167DC4;
remoteInfo = jschelpers;
};
3DAD3EAE1DF850E9000B6D8A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 3D3CD9181DE5FBD800167DC4;
remoteInfo = "jschelpers-tvOS";
};
5E9157321DD0AC6500FF2AA8 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5E91572D1DD0AC6500FF2AA8 /* RCTAnimation.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 134814201AA4EA6300B7C361;
remoteInfo = RCTAnimation;
};
5E9157341DD0AC6500FF2AA8 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5E91572D1DD0AC6500FF2AA8 /* RCTAnimation.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 2D2A28201D9B03D100D4039D;
remoteInfo = "RCTAnimation-tvOS";
};
78C398B81ACF4ADC00677621 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 78C398B01ACF4ADC00677621 /* RCTLinking.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 134814201AA4EA6300B7C361;
remoteInfo = RCTLinking;
};
832341B41AAA6A8300B99B32 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 832341B01AAA6A8300B99B32 /* RCTText.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 58B5119B1A9E6C1200147676;
remoteInfo = RCTText;
};
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
008F07F21AC5B25A0029DE68 /* main.jsbundle */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = main.jsbundle; sourceTree = "<group>"; };
00C302A71ABCB8CE00DB3ED1 /* RCTActionSheet.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTActionSheet.xcodeproj; path = "../node_modules/react-native/Libraries/ActionSheetIOS/RCTActionSheet.xcodeproj"; sourceTree = "<group>"; };
00C302B51ABCB90400DB3ED1 /* RCTGeolocation.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTGeolocation.xcodeproj; path = "../node_modules/react-native/Libraries/Geolocation/RCTGeolocation.xcodeproj"; sourceTree = "<group>"; };
00C302BB1ABCB91800DB3ED1 /* RCTImage.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTImage.xcodeproj; path = "../node_modules/react-native/Libraries/Image/RCTImage.xcodeproj"; sourceTree = "<group>"; };
00C302D31ABCB9D200DB3ED1 /* RCTNetwork.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTNetwork.xcodeproj; path = "../node_modules/react-native/Libraries/Network/RCTNetwork.xcodeproj"; sourceTree = "<group>"; };
00C302DF1ABCB9EE00DB3ED1 /* RCTVibration.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTVibration.xcodeproj; path = "../node_modules/react-native/Libraries/Vibration/RCTVibration.xcodeproj"; sourceTree = "<group>"; };
00E356EE1AD99517003FC87E /* react_nativeTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = react_nativeTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
00E356F11AD99517003FC87E /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
00E356F21AD99517003FC87E /* react_nativeTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = react_nativeTests.m; sourceTree = "<group>"; };
139105B61AF99BAD00B5F7CC /* RCTSettings.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTSettings.xcodeproj; path = "../node_modules/react-native/Libraries/Settings/RCTSettings.xcodeproj"; sourceTree = "<group>"; };
139FDEE61B06529A00C62182 /* RCTWebSocket.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTWebSocket.xcodeproj; path = "../node_modules/react-native/Libraries/WebSocket/RCTWebSocket.xcodeproj"; sourceTree = "<group>"; };
13B07F961A680F5B00A75B9A /* react_native.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = react_native.app; sourceTree = BUILT_PRODUCTS_DIR; };
13B07FAF1A68108700A75B9A /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AppDelegate.h; path = react_native/AppDelegate.h; sourceTree = "<group>"; };
13B07FB01A68108700A75B9A /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AppDelegate.m; path = react_native/AppDelegate.m; sourceTree = "<group>"; };
13B07FB21A68108700A75B9A /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/LaunchScreen.xib; sourceTree = "<group>"; };
13B07FB51A68108700A75B9A /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = react_native/Images.xcassets; sourceTree = "<group>"; };
13B07FB61A68108700A75B9A /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = react_native/Info.plist; sourceTree = "<group>"; };
13B07FB71A68108700A75B9A /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = main.m; path = react_native/main.m; sourceTree = "<group>"; };
146833FF1AC3E56700842450 /* React.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = React.xcodeproj; path = "../node_modules/react-native/React/React.xcodeproj"; sourceTree = "<group>"; };
2D02E47B1E0B4A5D006451C7 /* react_native-tvOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "react_native-tvOS.app"; sourceTree = BUILT_PRODUCTS_DIR; };
2D02E4901E0B4A5D006451C7 /* react_native-tvOSTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "react_native-tvOSTests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
5E91572D1DD0AC6500FF2AA8 /* RCTAnimation.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTAnimation.xcodeproj; path = "../node_modules/react-native/Libraries/NativeAnimation/RCTAnimation.xcodeproj"; sourceTree = "<group>"; };
78C398B01ACF4ADC00677621 /* RCTLinking.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTLinking.xcodeproj; path = "../node_modules/react-native/Libraries/LinkingIOS/RCTLinking.xcodeproj"; sourceTree = "<group>"; };
832341B01AAA6A8300B99B32 /* RCTText.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTText.xcodeproj; path = "../node_modules/react-native/Libraries/Text/RCTText.xcodeproj"; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
00E356EB1AD99517003FC87E /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
140ED2AC1D01E1AD002B40FF /* libReact.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
13B07F8C1A680F5B00A75B9A /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
146834051AC3E58100842450 /* libReact.a in Frameworks */,
5E9157361DD0AC6A00FF2AA8 /* libRCTAnimation.a in Frameworks */,
00C302E51ABCBA2D00DB3ED1 /* libRCTActionSheet.a in Frameworks */,
00C302E71ABCBA2D00DB3ED1 /* libRCTGeolocation.a in Frameworks */,
00C302E81ABCBA2D00DB3ED1 /* libRCTImage.a in Frameworks */,
133E29F31AD74F7200F7D852 /* libRCTLinking.a in Frameworks */,
00C302E91ABCBA2D00DB3ED1 /* libRCTNetwork.a in Frameworks */,
139105C61AF99C1200B5F7CC /* libRCTSettings.a in Frameworks */,
832341BD1AAA6AB300B99B32 /* libRCTText.a in Frameworks */,
00C302EA1ABCBA2D00DB3ED1 /* libRCTVibration.a in Frameworks */,
139FDEF61B0652A700C62182 /* libRCTWebSocket.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
2D02E4781E0B4A5D006451C7 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
2D02E4C91E0B4AEC006451C7 /* libReact.a in Frameworks */,
2D02E4C21E0B4AEC006451C7 /* libRCTAnimation-tvOS.a in Frameworks */,
2D02E4C31E0B4AEC006451C7 /* libRCTImage-tvOS.a in Frameworks */,
2D02E4C41E0B4AEC006451C7 /* libRCTLinking-tvOS.a in Frameworks */,
2D02E4C51E0B4AEC006451C7 /* libRCTNetwork-tvOS.a in Frameworks */,
2D02E4C61E0B4AEC006451C7 /* libRCTSettings-tvOS.a in Frameworks */,
2D02E4C71E0B4AEC006451C7 /* libRCTText-tvOS.a in Frameworks */,
2D02E4C81E0B4AEC006451C7 /* libRCTWebSocket-tvOS.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
2D02E48D1E0B4A5D006451C7 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
00C302A81ABCB8CE00DB3ED1 /* Products */ = {
isa = PBXGroup;
children = (
00C302AC1ABCB8CE00DB3ED1 /* libRCTActionSheet.a */,
);
name = Products;
sourceTree = "<group>";
};
00C302B61ABCB90400DB3ED1 /* Products */ = {
isa = PBXGroup;
children = (
00C302BA1ABCB90400DB3ED1 /* libRCTGeolocation.a */,
);
name = Products;
sourceTree = "<group>";
};
00C302BC1ABCB91800DB3ED1 /* Products */ = {
isa = PBXGroup;
children = (
00C302C01ABCB91800DB3ED1 /* libRCTImage.a */,
3DAD3E841DF850E9000B6D8A /* libRCTImage-tvOS.a */,
);
name = Products;
sourceTree = "<group>";
};
00C302D41ABCB9D200DB3ED1 /* Products */ = {
isa = PBXGroup;
children = (
00C302DC1ABCB9D200DB3ED1 /* libRCTNetwork.a */,
3DAD3E8C1DF850E9000B6D8A /* libRCTNetwork-tvOS.a */,
);
name = Products;
sourceTree = "<group>";
};
00C302E01ABCB9EE00DB3ED1 /* Products */ = {
isa = PBXGroup;
children = (
00C302E41ABCB9EE00DB3ED1 /* libRCTVibration.a */,
);
name = Products;
sourceTree = "<group>";
};
00E356EF1AD99517003FC87E /* react_nativeTests */ = {
isa = PBXGroup;
children = (
00E356F21AD99517003FC87E /* react_nativeTests.m */,
00E356F01AD99517003FC87E /* Supporting Files */,
);
path = react_nativeTests;
sourceTree = "<group>";
};
00E356F01AD99517003FC87E /* Supporting Files */ = {
isa = PBXGroup;
children = (
00E356F11AD99517003FC87E /* Info.plist */,
);
name = "Supporting Files";
sourceTree = "<group>";
};
139105B71AF99BAD00B5F7CC /* Products */ = {
isa = PBXGroup;
children = (
139105C11AF99BAD00B5F7CC /* libRCTSettings.a */,
3DAD3E901DF850E9000B6D8A /* libRCTSettings-tvOS.a */,
);
name = Products;
sourceTree = "<group>";
};
139FDEE71B06529A00C62182 /* Products */ = {
isa = PBXGroup;
children = (
139FDEF41B06529B00C62182 /* libRCTWebSocket.a */,
3DAD3E991DF850E9000B6D8A /* libRCTWebSocket-tvOS.a */,
);
name = Products;
sourceTree = "<group>";
};
13B07FAE1A68108700A75B9A /* react_native */ = {
isa = PBXGroup;
children = (
008F07F21AC5B25A0029DE68 /* main.jsbundle */,
13B07FAF1A68108700A75B9A /* AppDelegate.h */,
13B07FB01A68108700A75B9A /* AppDelegate.m */,
13B07FB51A68108700A75B9A /* Images.xcassets */,
13B07FB61A68108700A75B9A /* Info.plist */,
13B07FB11A68108700A75B9A /* LaunchScreen.xib */,
13B07FB71A68108700A75B9A /* main.m */,
);
name = react_native;
sourceTree = "<group>";
};
146834001AC3E56700842450 /* Products */ = {
isa = PBXGroup;
children = (
146834041AC3E56700842450 /* libReact.a */,
3DAD3EA31DF850E9000B6D8A /* libReact.a */,
3DAD3EA51DF850E9000B6D8A /* libyoga.a */,
3DAD3EA71DF850E9000B6D8A /* libyoga.a */,
3DAD3EA91DF850E9000B6D8A /* libcxxreact.a */,
3DAD3EAB1DF850E9000B6D8A /* libcxxreact.a */,
3DAD3EAD1DF850E9000B6D8A /* libjschelpers.a */,
3DAD3EAF1DF850E9000B6D8A /* libjschelpers.a */,
);
name = Products;
sourceTree = "<group>";
};
5E91572E1DD0AC6500FF2AA8 /* Products */ = {
isa = PBXGroup;
children = (
5E9157331DD0AC6500FF2AA8 /* libRCTAnimation.a */,
5E9157351DD0AC6500FF2AA8 /* libRCTAnimation-tvOS.a */,
);
name = Products;
sourceTree = "<group>";
};
78C398B11ACF4ADC00677621 /* Products */ = {
isa = PBXGroup;
children = (
78C398B91ACF4ADC00677621 /* libRCTLinking.a */,
3DAD3E881DF850E9000B6D8A /* libRCTLinking-tvOS.a */,
);
name = Products;
sourceTree = "<group>";
};
832341AE1AAA6A7D00B99B32 /* Libraries */ = {
isa = PBXGroup;
children = (
5E91572D1DD0AC6500FF2AA8 /* RCTAnimation.xcodeproj */,
146833FF1AC3E56700842450 /* React.xcodeproj */,
00C302A71ABCB8CE00DB3ED1 /* RCTActionSheet.xcodeproj */,
00C302B51ABCB90400DB3ED1 /* RCTGeolocation.xcodeproj */,
00C302BB1ABCB91800DB3ED1 /* RCTImage.xcodeproj */,
78C398B01ACF4ADC00677621 /* RCTLinking.xcodeproj */,
00C302D31ABCB9D200DB3ED1 /* RCTNetwork.xcodeproj */,
139105B61AF99BAD00B5F7CC /* RCTSettings.xcodeproj */,
832341B01AAA6A8300B99B32 /* RCTText.xcodeproj */,
00C302DF1ABCB9EE00DB3ED1 /* RCTVibration.xcodeproj */,
139FDEE61B06529A00C62182 /* RCTWebSocket.xcodeproj */,
);
name = Libraries;
sourceTree = "<group>";
};
832341B11AAA6A8300B99B32 /* Products */ = {
isa = PBXGroup;
children = (
832341B51AAA6A8300B99B32 /* libRCTText.a */,
3DAD3E941DF850E9000B6D8A /* libRCTText-tvOS.a */,
);
name = Products;
sourceTree = "<group>";
};
83CBB9F61A601CBA00E9B192 = {
isa = PBXGroup;
children = (
13B07FAE1A68108700A75B9A /* react_native */,
832341AE1AAA6A7D00B99B32 /* Libraries */,
00E356EF1AD99517003FC87E /* react_nativeTests */,
83CBBA001A601CBA00E9B192 /* Products */,
);
indentWidth = 2;
sourceTree = "<group>";
tabWidth = 2;
};
83CBBA001A601CBA00E9B192 /* Products */ = {
isa = PBXGroup;
children = (
13B07F961A680F5B00A75B9A /* react_native.app */,
00E356EE1AD99517003FC87E /* react_nativeTests.xctest */,
2D02E47B1E0B4A5D006451C7 /* react_native-tvOS.app */,
2D02E4901E0B4A5D006451C7 /* react_native-tvOSTests.xctest */,
);
name = Products;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
00E356ED1AD99517003FC87E /* react_nativeTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 00E357021AD99517003FC87E /* Build configuration list for PBXNativeTarget "react_nativeTests" */;
buildPhases = (
00E356EA1AD99517003FC87E /* Sources */,
00E356EB1AD99517003FC87E /* Frameworks */,
00E356EC1AD99517003FC87E /* Resources */,
);
buildRules = (
);
dependencies = (
00E356F51AD99517003FC87E /* PBXTargetDependency */,
);
name = react_nativeTests;
productName = react_nativeTests;
productReference = 00E356EE1AD99517003FC87E /* react_nativeTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
13B07F861A680F5B00A75B9A /* react_native */ = {
isa = PBXNativeTarget;
buildConfigurationList = 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "react_native" */;
buildPhases = (
13B07F871A680F5B00A75B9A /* Sources */,
13B07F8C1A680F5B00A75B9A /* Frameworks */,
13B07F8E1A680F5B00A75B9A /* Resources */,
00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */,
);
buildRules = (
);
dependencies = (
);
name = react_native;
productName = "Hello World";
productReference = 13B07F961A680F5B00A75B9A /* react_native.app */;
productType = "com.apple.product-type.application";
};
2D02E47A1E0B4A5D006451C7 /* react_native-tvOS */ = {
isa = PBXNativeTarget;
buildConfigurationList = 2D02E4BA1E0B4A5E006451C7 /* Build configuration list for PBXNativeTarget "react_native-tvOS" */;
buildPhases = (
2D02E4771E0B4A5D006451C7 /* Sources */,
2D02E4781E0B4A5D006451C7 /* Frameworks */,
2D02E4791E0B4A5D006451C7 /* Resources */,
2D02E4CB1E0B4B27006451C7 /* Bundle React Native Code And Images */,
);
buildRules = (
);
dependencies = (
);
name = "react_native-tvOS";
productName = "react_native-tvOS";
productReference = 2D02E47B1E0B4A5D006451C7 /* react_native-tvOS.app */;
productType = "com.apple.product-type.application";
};
2D02E48F1E0B4A5D006451C7 /* react_native-tvOSTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 2D02E4BB1E0B4A5E006451C7 /* Build configuration list for PBXNativeTarget "react_native-tvOSTests" */;
buildPhases = (
2D02E48C1E0B4A5D006451C7 /* Sources */,
2D02E48D1E0B4A5D006451C7 /* Frameworks */,
2D02E48E1E0B4A5D006451C7 /* Resources */,
);
buildRules = (
);
dependencies = (
2D02E4921E0B4A5D006451C7 /* PBXTargetDependency */,
);
name = "react_native-tvOSTests";
productName = "react_native-tvOSTests";
productReference = 2D02E4901E0B4A5D006451C7 /* react_native-tvOSTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
83CBB9F71A601CBA00E9B192 /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 0610;
ORGANIZATIONNAME = Facebook;
TargetAttributes = {
00E356ED1AD99517003FC87E = {
CreatedOnToolsVersion = 6.2;
TestTargetID = 13B07F861A680F5B00A75B9A;
};
2D02E47A1E0B4A5D006451C7 = {
CreatedOnToolsVersion = 8.2.1;
ProvisioningStyle = Automatic;
};
2D02E48F1E0B4A5D006451C7 = {
CreatedOnToolsVersion = 8.2.1;
ProvisioningStyle = Automatic;
TestTargetID = 2D02E47A1E0B4A5D006451C7;
};
};
};
buildConfigurationList = 83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "react_native" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = English;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 83CBB9F61A601CBA00E9B192;
productRefGroup = 83CBBA001A601CBA00E9B192 /* Products */;
projectDirPath = "";
projectReferences = (
{
ProductGroup = 00C302A81ABCB8CE00DB3ED1 /* Products */;
ProjectRef = 00C302A71ABCB8CE00DB3ED1 /* RCTActionSheet.xcodeproj */;
},
{
ProductGroup = 5E91572E1DD0AC6500FF2AA8 /* Products */;
ProjectRef = 5E91572D1DD0AC6500FF2AA8 /* RCTAnimation.xcodeproj */;
},
{
ProductGroup = 00C302B61ABCB90400DB3ED1 /* Products */;
ProjectRef = 00C302B51ABCB90400DB3ED1 /* RCTGeolocation.xcodeproj */;
},
{
ProductGroup = 00C302BC1ABCB91800DB3ED1 /* Products */;
ProjectRef = 00C302BB1ABCB91800DB3ED1 /* RCTImage.xcodeproj */;
},
{
ProductGroup = 78C398B11ACF4ADC00677621 /* Products */;
ProjectRef = 78C398B01ACF4ADC00677621 /* RCTLinking.xcodeproj */;
},
{
ProductGroup = 00C302D41ABCB9D200DB3ED1 /* Products */;
ProjectRef = 00C302D31ABCB9D200DB3ED1 /* RCTNetwork.xcodeproj */;
},
{
ProductGroup = 139105B71AF99BAD00B5F7CC /* Products */;
ProjectRef = 139105B61AF99BAD00B5F7CC /* RCTSettings.xcodeproj */;
},
{
ProductGroup = 832341B11AAA6A8300B99B32 /* Products */;
ProjectRef = 832341B01AAA6A8300B99B32 /* RCTText.xcodeproj */;
},
{
ProductGroup = 00C302E01ABCB9EE00DB3ED1 /* Products */;
ProjectRef = 00C302DF1ABCB9EE00DB3ED1 /* RCTVibration.xcodeproj */;
},
{
ProductGroup = 139FDEE71B06529A00C62182 /* Products */;
ProjectRef = 139FDEE61B06529A00C62182 /* RCTWebSocket.xcodeproj */;
},
{
ProductGroup = 146834001AC3E56700842450 /* Products */;
ProjectRef = 146833FF1AC3E56700842450 /* React.xcodeproj */;
},
);
projectRoot = "";
targets = (
13B07F861A680F5B00A75B9A /* react_native */,
00E356ED1AD99517003FC87E /* react_nativeTests */,
2D02E47A1E0B4A5D006451C7 /* react_native-tvOS */,
2D02E48F1E0B4A5D006451C7 /* react_native-tvOSTests */,
);
};
/* End PBXProject section */
/* Begin PBXReferenceProxy section */
00C302AC1ABCB8CE00DB3ED1 /* libRCTActionSheet.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libRCTActionSheet.a;
remoteRef = 00C302AB1ABCB8CE00DB3ED1 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
00C302BA1ABCB90400DB3ED1 /* libRCTGeolocation.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libRCTGeolocation.a;
remoteRef = 00C302B91ABCB90400DB3ED1 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
00C302C01ABCB91800DB3ED1 /* libRCTImage.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libRCTImage.a;
remoteRef = 00C302BF1ABCB91800DB3ED1 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
00C302DC1ABCB9D200DB3ED1 /* libRCTNetwork.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libRCTNetwork.a;
remoteRef = 00C302DB1ABCB9D200DB3ED1 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
00C302E41ABCB9EE00DB3ED1 /* libRCTVibration.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libRCTVibration.a;
remoteRef = 00C302E31ABCB9EE00DB3ED1 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
139105C11AF99BAD00B5F7CC /* libRCTSettings.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libRCTSettings.a;
remoteRef = 139105C01AF99BAD00B5F7CC /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
139FDEF41B06529B00C62182 /* libRCTWebSocket.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libRCTWebSocket.a;
remoteRef = 139FDEF31B06529B00C62182 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
146834041AC3E56700842450 /* libReact.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libReact.a;
remoteRef = 146834031AC3E56700842450 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
3DAD3E841DF850E9000B6D8A /* libRCTImage-tvOS.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = "libRCTImage-tvOS.a";
remoteRef = 3DAD3E831DF850E9000B6D8A /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
3DAD3E881DF850E9000B6D8A /* libRCTLinking-tvOS.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = "libRCTLinking-tvOS.a";
remoteRef = 3DAD3E871DF850E9000B6D8A /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
3DAD3E8C1DF850E9000B6D8A /* libRCTNetwork-tvOS.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = "libRCTNetwork-tvOS.a";
remoteRef = 3DAD3E8B1DF850E9000B6D8A /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
3DAD3E901DF850E9000B6D8A /* libRCTSettings-tvOS.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = "libRCTSettings-tvOS.a";
remoteRef = 3DAD3E8F1DF850E9000B6D8A /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
3DAD3E941DF850E9000B6D8A /* libRCTText-tvOS.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = "libRCTText-tvOS.a";
remoteRef = 3DAD3E931DF850E9000B6D8A /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
3DAD3E991DF850E9000B6D8A /* libRCTWebSocket-tvOS.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = "libRCTWebSocket-tvOS.a";
remoteRef = 3DAD3E981DF850E9000B6D8A /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
3DAD3EA31DF850E9000B6D8A /* libReact.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libReact.a;
remoteRef = 3DAD3EA21DF850E9000B6D8A /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
3DAD3EA51DF850E9000B6D8A /* libyoga.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libyoga.a;
remoteRef = 3DAD3EA41DF850E9000B6D8A /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
3DAD3EA71DF850E9000B6D8A /* libyoga.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libyoga.a;
remoteRef = 3DAD3EA61DF850E9000B6D8A /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
3DAD3EA91DF850E9000B6D8A /* libcxxreact.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libcxxreact.a;
remoteRef = 3DAD3EA81DF850E9000B6D8A /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
3DAD3EAB1DF850E9000B6D8A /* libcxxreact.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libcxxreact.a;
remoteRef = 3DAD3EAA1DF850E9000B6D8A /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
3DAD3EAD1DF850E9000B6D8A /* libjschelpers.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libjschelpers.a;
remoteRef = 3DAD3EAC1DF850E9000B6D8A /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
3DAD3EAF1DF850E9000B6D8A /* libjschelpers.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libjschelpers.a;
remoteRef = 3DAD3EAE1DF850E9000B6D8A /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
5E9157331DD0AC6500FF2AA8 /* libRCTAnimation.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libRCTAnimation.a;
remoteRef = 5E9157321DD0AC6500FF2AA8 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
5E9157351DD0AC6500FF2AA8 /* libRCTAnimation-tvOS.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = "libRCTAnimation-tvOS.a";
remoteRef = 5E9157341DD0AC6500FF2AA8 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
78C398B91ACF4ADC00677621 /* libRCTLinking.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libRCTLinking.a;
remoteRef = 78C398B81ACF4ADC00677621 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
832341B51AAA6A8300B99B32 /* libRCTText.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libRCTText.a;
remoteRef = 832341B41AAA6A8300B99B32 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
/* End PBXReferenceProxy section */
/* Begin PBXResourcesBuildPhase section */
00E356EC1AD99517003FC87E /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
13B07F8E1A680F5B00A75B9A /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */,
13B07FBD1A68108700A75B9A /* LaunchScreen.xib in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
2D02E4791E0B4A5D006451C7 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
2D02E4BD1E0B4A84006451C7 /* Images.xcassets in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
2D02E48E1E0B4A5D006451C7 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "Bundle React Native code and images";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "export NODE_BINARY=node\n../node_modules/react-native/scripts/react-native-xcode.sh";
};
2D02E4CB1E0B4B27006451C7 /* Bundle React Native Code And Images */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "Bundle React Native Code And Images";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "export NODE_BINARY=node\n../node_modules/react-native/scripts/react-native-xcode.sh";
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
00E356EA1AD99517003FC87E /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
00E356F31AD99517003FC87E /* react_nativeTests.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
13B07F871A680F5B00A75B9A /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
13B07FBC1A68108700A75B9A /* AppDelegate.m in Sources */,
13B07FC11A68108700A75B9A /* main.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
2D02E4771E0B4A5D006451C7 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
2D02E4BF1E0B4AB3006451C7 /* main.m in Sources */,
2D02E4BC1E0B4A80006451C7 /* AppDelegate.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
2D02E48C1E0B4A5D006451C7 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
2DCD954D1E0B4F2C00145EB5 /* react_nativeTests.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
00E356F51AD99517003FC87E /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 13B07F861A680F5B00A75B9A /* react_native */;
targetProxy = 00E356F41AD99517003FC87E /* PBXContainerItemProxy */;
};
2D02E4921E0B4A5D006451C7 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 2D02E47A1E0B4A5D006451C7 /* react_native-tvOS */;
targetProxy = 2D02E4911E0B4A5D006451C7 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
13B07FB11A68108700A75B9A /* LaunchScreen.xib */ = {
isa = PBXVariantGroup;
children = (
13B07FB21A68108700A75B9A /* Base */,
);
name = LaunchScreen.xib;
path = react_native;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
00E356F61AD99517003FC87E /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
INFOPLIST_FILE = react_nativeTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
OTHER_LDFLAGS = (
"-ObjC",
"-lc++",
);
PRODUCT_NAME = "$(TARGET_NAME)";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/react_native.app/react_native";
};
name = Debug;
};
00E356F71AD99517003FC87E /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
COPY_PHASE_STRIP = NO;
INFOPLIST_FILE = react_nativeTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
OTHER_LDFLAGS = (
"-ObjC",
"-lc++",
);
PRODUCT_NAME = "$(TARGET_NAME)";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/react_native.app/react_native";
};
name = Release;
};
13B07F941A680F5B00A75B9A /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CURRENT_PROJECT_VERSION = 1;
DEAD_CODE_STRIPPING = NO;
INFOPLIST_FILE = react_native/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
OTHER_LDFLAGS = (
"$(inherited)",
"-ObjC",
"-lc++",
);
PRODUCT_NAME = react_native;
VERSIONING_SYSTEM = "apple-generic";
};
name = Debug;
};
13B07F951A680F5B00A75B9A /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CURRENT_PROJECT_VERSION = 1;
INFOPLIST_FILE = react_native/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
OTHER_LDFLAGS = (
"$(inherited)",
"-ObjC",
"-lc++",
);
PRODUCT_NAME = react_native;
VERSIONING_SYSTEM = "apple-generic";
};
name = Release;
};
2D02E4971E0B4A5E006451C7 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = "App Icon & Top Shelf Image";
ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;
CLANG_ANALYZER_NONNULL = YES;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_TESTABILITY = YES;
GCC_NO_COMMON_BLOCKS = YES;
INFOPLIST_FILE = "react_native-tvOS/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
OTHER_LDFLAGS = (
"-ObjC",
"-lc++",
);
PRODUCT_BUNDLE_IDENTIFIER = "com.facebook.REACT.react_native-tvOS";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = appletvos;
TARGETED_DEVICE_FAMILY = 3;
TVOS_DEPLOYMENT_TARGET = 9.2;
};
name = Debug;
};
2D02E4981E0B4A5E006451C7 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = "App Icon & Top Shelf Image";
ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;
CLANG_ANALYZER_NONNULL = YES;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
GCC_NO_COMMON_BLOCKS = YES;
INFOPLIST_FILE = "react_native-tvOS/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
OTHER_LDFLAGS = (
"-ObjC",
"-lc++",
);
PRODUCT_BUNDLE_IDENTIFIER = "com.facebook.REACT.react_native-tvOS";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = appletvos;
TARGETED_DEVICE_FAMILY = 3;
TVOS_DEPLOYMENT_TARGET = 9.2;
};
name = Release;
};
2D02E4991E0B4A5E006451C7 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CLANG_ANALYZER_NONNULL = YES;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_TESTABILITY = YES;
GCC_NO_COMMON_BLOCKS = YES;
INFOPLIST_FILE = "react_native-tvOSTests/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "com.facebook.REACT.react_native-tvOSTests";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = appletvos;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/react_native-tvOS.app/react_native-tvOS";
TVOS_DEPLOYMENT_TARGET = 10.1;
};
name = Debug;
};
2D02E49A1E0B4A5E006451C7 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CLANG_ANALYZER_NONNULL = YES;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
GCC_NO_COMMON_BLOCKS = YES;
INFOPLIST_FILE = "react_native-tvOSTests/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "com.facebook.REACT.react_native-tvOSTests";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = appletvos;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/react_native-tvOS.app/react_native-tvOS";
TVOS_DEPLOYMENT_TARGET = 10.1;
};
name = Release;
};
83CBBA201A601CBA00E9B192 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_SYMBOLS_PRIVATE_EXTERN = NO;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
};
name = Debug;
};
83CBBA211A601CBA00E9B192 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = YES;
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
VALIDATE_PRODUCT = YES;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
00E357021AD99517003FC87E /* Build configuration list for PBXNativeTarget "react_nativeTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
00E356F61AD99517003FC87E /* Debug */,
00E356F71AD99517003FC87E /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "react_native" */ = {
isa = XCConfigurationList;
buildConfigurations = (
13B07F941A680F5B00A75B9A /* Debug */,
13B07F951A680F5B00A75B9A /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
2D02E4BA1E0B4A5E006451C7 /* Build configuration list for PBXNativeTarget "react_native-tvOS" */ = {
isa = XCConfigurationList;
buildConfigurations = (
2D02E4971E0B4A5E006451C7 /* Debug */,
2D02E4981E0B4A5E006451C7 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
2D02E4BB1E0B4A5E006451C7 /* Build configuration list for PBXNativeTarget "react_native-tvOSTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
2D02E4991E0B4A5E006451C7 /* Debug */,
2D02E49A1E0B4A5E006451C7 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "react_native" */ = {
isa = XCConfigurationList;
buildConfigurations = (
83CBBA201A601CBA00E9B192 /* Debug */,
83CBBA211A601CBA00E9B192 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 83CBB9F71A601CBA00E9B192 /* Project object */;
}
| lib/cli/test/fixtures/react_native/ios/react_native.xcodeproj/project.pbxproj | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.0014676095452159643,
0.00019466501544229686,
0.00016474106814712286,
0.00017148166080005467,
0.00013896885502617806
]
|
{
"id": 7,
"code_window": [
" if (hasError) {\n",
" return <h1>Something went wrong.</h1>;\n",
" }\n",
" return (\n",
" <div id={id} title={title}>\n",
" {children}\n",
" </div>\n",
" );\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" {children()}\n"
],
"file_path": "lib/ui/src/components/panel/panel.js",
"type": "replace",
"edit_start_line_idx": 24
} | import addons from '@storybook/addons';
import { navigator, window, document } from 'global';
import createChannel from '@storybook/channel-postmessage';
import { handleKeyboardShortcuts } from '@storybook/ui/dist/libs/key_events';
import { logger } from '@storybook/client-logger';
import Events from '@storybook/core-events';
import StoryStore from './story_store';
import ClientApi from './client_api';
import ConfigApi from './config_api';
const classes = {
MAIN: 'sb-show-main',
NOPREVIEW: 'sb-show-nopreview',
ERROR: 'sb-show-errordisplay',
};
function showMain() {
document.body.classList.remove(classes.NOPREVIEW);
document.body.classList.remove(classes.ERROR);
document.body.classList.add(classes.MAIN);
}
function showNopreview() {
document.body.classList.remove(classes.MAIN);
document.body.classList.remove(classes.ERROR);
document.body.classList.add(classes.NOPREVIEW);
}
function showErrorDisplay({ message, stack }) {
document.getElementById('error-message').textContent = message;
document.getElementById('error-stack').textContent = stack;
document.body.classList.remove(classes.MAIN);
document.body.classList.remove(classes.NOPREVIEW);
document.body.classList.add(classes.ERROR);
}
// showError is used by the various app layers to inform the user they have done something
// wrong -- for instance returned the wrong thing from a story
function showError({ title, description }) {
addons.getChannel().emit(Events.STORY_ERRORED, { title, description });
showErrorDisplay({
message: title,
stack: description,
});
}
// showException is used if we fail to render the story and it is uncaught by the app layer
function showException(exception) {
addons.getChannel().emit(Events.STORY_THREW_EXCEPTION, exception);
showErrorDisplay(exception);
// Log the stack to the console. So, user could check the source code.
logger.error(exception.stack);
}
const isBrowser =
navigator &&
navigator.userAgent &&
navigator.userAgent !== 'storyshots' &&
!(navigator.userAgent.indexOf('Node.js') > -1) &&
!(navigator.userAgent.indexOf('jsdom') > -1);
const getContext = (() => {
let cache;
return decorateStory => {
if (cache) {
return cache;
}
let channel = null;
if (isBrowser) {
try {
channel = addons.getChannel();
} catch (e) {
channel = createChannel({ page: 'preview' });
addons.setChannel(channel);
}
}
const storyStore = new StoryStore({ channel });
const clientApi = new ClientApi({ storyStore, decorateStory });
const { clearDecorators } = clientApi;
const configApi = new ConfigApi({ clearDecorators, storyStore, channel, clientApi });
return {
configApi,
storyStore,
channel,
clientApi,
showMain,
showError,
showException,
};
};
})();
export default function start(render, { decorateStory } = {}) {
const context = getContext(decorateStory);
const { clientApi, channel, configApi, storyStore } = context;
// Provide access to external scripts if `window` is defined.
// NOTE this is different to isBrowser, primarily for the JSDOM use case
let previousKind = '';
let previousStory = '';
let previousRevision = -1;
const renderMain = forceRender => {
const revision = storyStore.getRevision();
const { kind, name, story } = storyStore.getSelection() || {};
if (story) {
// Render story only if selectedKind or selectedStory have changed.
// However, we DO want the story to re-render if the store itself has changed
// (which happens at the moment when HMR occurs)
if (
!forceRender &&
revision === previousRevision &&
kind === previousKind &&
previousStory === name
) {
return;
}
if (!forceRender) {
// Scroll to top of the page when changing story
document.documentElement.scrollTop = 0;
}
render({
...context,
story,
selectedKind: kind,
selectedStory: name,
forceRender,
});
addons.getChannel().emit(Events.STORY_RENDERED, storyStore.getSelection());
} else {
showNopreview();
addons.getChannel().emit(Events.STORY_MISSING, storyStore.getSelection());
}
previousRevision = revision;
previousKind = kind;
previousStory = name;
};
// initialize the UI
const renderUI = forceRender => {
if (isBrowser) {
try {
renderMain(forceRender);
} catch (ex) {
showException(ex);
}
}
};
const forceReRender = () => renderUI(true);
// channel can be null in NodeJS
if (isBrowser) {
channel.on(Events.FORCE_RE_RENDER, forceReRender);
channel.on(Events.SET_CURRENT_STORY, ({ location }) => {
if (!location) {
throw new Error('should have location');
}
const data = storyStore.fromPath(location);
console.log('here', location);
storyStore.setSelection(data);
storyStore.setPath(location);
});
// Handle keyboard shortcuts
window.onkeydown = handleKeyboardShortcuts(channel);
}
storyStore.on(Events.STORY_RENDER, renderUI);
if (typeof window !== 'undefined') {
window.__STORYBOOK_CLIENT_API__ = clientApi;
window.__STORYBOOK_ADDONS_CHANNEL__ = channel; // may not be defined
}
return { context, clientApi, configApi, forceReRender };
}
| lib/core/src/client/preview/start.js | 1 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.0003049445222131908,
0.00017941171245183796,
0.0001676094252616167,
0.00017269303498324007,
0.000029696695492020808
]
|
{
"id": 7,
"code_window": [
" if (hasError) {\n",
" return <h1>Something went wrong.</h1>;\n",
" }\n",
" return (\n",
" <div id={id} title={title}>\n",
" {children}\n",
" </div>\n",
" );\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" {children()}\n"
],
"file_path": "lib/ui/src/components/panel/panel.js",
"type": "replace",
"edit_start_line_idx": 24
} | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Storyshots Addon|Centered rounded 1`] = `
<div
style="position: fixed; top: 0px; left: 0px; bottom: 0px; right: 0px; display: flex; align-items: center; overflow: auto;"
>
<div
style="margin: auto; max-height: 100%;"
>
<div
style="position: fixed; top: 0px; left: 0px; bottom: 0px; right: 0px; display: flex; align-items: center; overflow: auto;"
>
<div
style="margin: auto; max-height: 100%;"
>
<button
class="button rounded"
style="color: rgb(66, 185, 131); border-color: #42b983;"
>
A Button with rounded edges!
</button>
</div>
</div>
</div>
</div>
`;
| examples/vue-kitchen-sink/src/stories/__snapshots__/addon-centered.stories.storyshot | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.00017505284631624818,
0.00017042072431650013,
0.00016664403665345162,
0.0001695652463240549,
0.0000034857694117818028
]
|
{
"id": 7,
"code_window": [
" if (hasError) {\n",
" return <h1>Something went wrong.</h1>;\n",
" }\n",
" return (\n",
" <div id={id} title={title}>\n",
" {children}\n",
" </div>\n",
" );\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" {children()}\n"
],
"file_path": "lib/ui/src/components/panel/panel.js",
"type": "replace",
"edit_start_line_idx": 24
} | import { configure } from '@storybook/svelte';
import { setOptions } from '@storybook/addon-options';
// Used with @storybook/addon-options/register
setOptions({ hierarchyRootSeparator: /\|/ });
function loadStories() {
require('../src/stories');
const req = require.context('../src/stories', true, /\.stories\.js$/);
req.keys().forEach(filename => req(filename));
}
configure(loadStories, module);
| examples/svelte-kitchen-sink/.storybook/config.js | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.0001756562851369381,
0.00017479801317676902,
0.00017393975576851517,
0.00017479801317676902,
8.582646842114627e-7
]
|
{
"id": 7,
"code_window": [
" if (hasError) {\n",
" return <h1>Something went wrong.</h1>;\n",
" }\n",
" return (\n",
" <div id={id} title={title}>\n",
" {children}\n",
" </div>\n",
" );\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" {children()}\n"
],
"file_path": "lib/ui/src/components/panel/panel.js",
"type": "replace",
"edit_start_line_idx": 24
} | .App {
text-align: center;
}
.App-logo {
animation: App-logo-spin infinite 20s linear;
height: 80px;
}
.App-header {
background-color: #222;
height: 150px;
padding: 20px;
color: white;
}
.App-intro {
font-size: large;
}
@keyframes App-logo-spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
| lib/cli/test/fixtures/react_scripts/src/App.css | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.0001771848474163562,
0.00017440615920349956,
0.00017272596596740186,
0.0001733076642267406,
0.0000019791284557868494
]
|
{
"id": 8,
"code_window": [
" </Tabs>\n",
");\n",
"AddonPanel.propTypes = {\n",
" selectedPanel: PropTypes.string,\n",
" actions: PropTypes.shape({}).isRequired,\n",
" panels: PropTypes.objectOf(\n",
" PropTypes.shape({\n",
" title: PropTypes.string,\n",
" render: PropTypes.func,\n",
" })\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" panels: PropTypes.arrayOf(\n"
],
"file_path": "lib/ui/src/components/panel/panel.js",
"type": "replace",
"edit_start_line_idx": 84
} | import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import styled from '@emotion/styled';
import { Tabs, Icons } from '@storybook/components';
class SafeTab extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error, info) {
this.setState({ hasError: true });
console.error(error, info);
}
render() {
const { hasError } = this.state;
const { children, title, id } = this.props;
if (hasError) {
return <h1>Something went wrong.</h1>;
}
return (
<div id={id} title={title}>
{children}
</div>
);
}
}
SafeTab.propTypes = {
children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired,
title: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
};
const ToolButton = styled.button({
background: 'none',
border: '0 none',
padding: 0,
color: 'inherit',
'&:hover, &:focus': {
color: '#300aaff',
outline: '0 none',
cursor: 'pointer',
},
});
export const Separator = styled.span({
width: 1,
height: 24,
background: '#eee',
});
const AddonPanel = ({ panels, actions, selectedPanel, panelPosition, ...rest }) => (
<Tabs
{...rest}
absolute
selected={selectedPanel}
actions={actions}
flex
tools={
<Fragment>
<Separator key="1" />
<ToolButton key="position" onClick={actions.togglePosition}>
<Icons icon={panelPosition === 'bottom' ? 'bottombar' : 'sidebaralt'} />
</ToolButton>
<ToolButton key="visibility" onClick={actions.toggleVisibility}>
<Icons icon="close" />
</ToolButton>
</Fragment>
}
id="storybook-panel-root"
>
{Object.entries(panels).map(([k, v]) => (
<SafeTab key={k} id={k} title={v.title}>
{v.render}
</SafeTab>
))}
</Tabs>
);
AddonPanel.propTypes = {
selectedPanel: PropTypes.string,
actions: PropTypes.shape({}).isRequired,
panels: PropTypes.objectOf(
PropTypes.shape({
title: PropTypes.string,
render: PropTypes.func,
})
).isRequired,
};
AddonPanel.defaultProps = {
selectedPanel: null,
};
export default AddonPanel;
| lib/ui/src/components/panel/panel.js | 1 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.9961463212966919,
0.1007457822561264,
0.0001750298251863569,
0.0009696530760265887,
0.298468679189682
]
|
{
"id": 8,
"code_window": [
" </Tabs>\n",
");\n",
"AddonPanel.propTypes = {\n",
" selectedPanel: PropTypes.string,\n",
" actions: PropTypes.shape({}).isRequired,\n",
" panels: PropTypes.objectOf(\n",
" PropTypes.shape({\n",
" title: PropTypes.string,\n",
" render: PropTypes.func,\n",
" })\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" panels: PropTypes.arrayOf(\n"
],
"file_path": "lib/ui/src/components/panel/panel.js",
"type": "replace",
"edit_start_line_idx": 84
} | import { mount, storiesOf, compileNow } from '@storybook/riot';
import { action } from '@storybook/addon-actions';
import ButtonRaw from './Button.txt';
compileNow(ButtonRaw);
storiesOf('Addon|Actions', module)
.add('Action only', () =>
mount('my-button', {
handleClick: action('button-click'),
content: 'Click me to log the action',
})
)
.add('Multiple actions', () =>
mount('my-button', {
handleDblClick: action('button-double-click'),
content: 'Double Click me to log the action',
})
);
| examples/riot-kitchen-sink/src/stories/addon-actions.stories.js | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.0001701763685559854,
0.00016975487233139575,
0.00016933339065872133,
0.00016975487233139575,
4.214889486320317e-7
]
|
{
"id": 8,
"code_window": [
" </Tabs>\n",
");\n",
"AddonPanel.propTypes = {\n",
" selectedPanel: PropTypes.string,\n",
" actions: PropTypes.shape({}).isRequired,\n",
" panels: PropTypes.objectOf(\n",
" PropTypes.shape({\n",
" title: PropTypes.string,\n",
" render: PropTypes.func,\n",
" })\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" panels: PropTypes.arrayOf(\n"
],
"file_path": "lib/ui/src/components/panel/panel.js",
"type": "replace",
"edit_start_line_idx": 84
} | # Polymer kitchen sink example
This project was generated with [Polymer CLI](https://github.com/Polymer/polymer-cli) version 1.5.2.
## Development server
Run `yarn start` for a dev server. Navigate to `http://127.0.0.1:8081/components/polymer-cli/`.
The app will automatically reload if you change any of the source files.
| examples/polymer-cli/README.md | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.00016934130690060556,
0.00016934130690060556,
0.00016934130690060556,
0.00016934130690060556,
0
]
|
{
"id": 8,
"code_window": [
" </Tabs>\n",
");\n",
"AddonPanel.propTypes = {\n",
" selectedPanel: PropTypes.string,\n",
" actions: PropTypes.shape({}).isRequired,\n",
" panels: PropTypes.objectOf(\n",
" PropTypes.shape({\n",
" title: PropTypes.string,\n",
" render: PropTypes.func,\n",
" })\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" panels: PropTypes.arrayOf(\n"
],
"file_path": "lib/ui/src/components/panel/panel.js",
"type": "replace",
"edit_start_line_idx": 84
} | import { configure } from '@storybook/polymer';
// automatically import all files ending in *.stories.js
const req = require.context('../src/stories', true, /.stories.js$/);
function loadStories() {
req.keys().forEach(filename => req(filename));
}
configure(loadStories, module);
| lib/cli/generators/POLYMER/template/.storybook/config.js | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.00017555012891534716,
0.00017555012891534716,
0.00017555012891534716,
0.00017555012891534716,
0
]
|
{
"id": 9,
"code_window": [
"import { inject } from 'mobx-react';\n",
"import AddonPanel from '../components/panel/panel';\n",
"\n",
"export function mapper({ store, uiStore }) {\n",
" return {\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { types } from '@storybook/addons';\n",
"\n"
],
"file_path": "lib/ui/src/containers/panel.js",
"type": "add",
"edit_start_line_idx": 1
} | import { window } from 'global';
import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import Events from '@storybook/core-events';
import { types } from '@storybook/addons';
import { IconButton, Toolbar, Separator } from './toolbar';
import Icons from '../icon/icon';
import { Route } from '../router/router';
import { TabButton, TabBar } from '../tabs/tabs';
import Zoom from './tools/zoom';
import { Grid, Background } from './tools/background';
import * as S from './components';
class IFrame extends Component {
shouldComponentUpdate() {
// this component renders an iframe, which gets updates via post-messages
return false;
}
render() {
const { id, title, src, allowFullScreen, ...rest } = this.props;
return (
<iframe
id={id}
title={title}
src={src}
allowFullScreen={allowFullScreen}
{...rest}
style={{ border: '0 none' }}
/>
);
}
}
IFrame.propTypes = {
id: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
src: PropTypes.string.isRequired,
allowFullScreen: PropTypes.bool.isRequired,
};
// eslint-disable-next-line react/no-multi-comp
class Preview extends Component {
state = {
zoom: 1,
grid: false,
};
shouldComponentUpdate({ location, toolbar, options }, { zoom, grid }) {
const { props, state } = this;
return (
options.isFullscreen !== props.options.isFullscreen ||
location !== props.location ||
toolbar !== props.toolbar ||
zoom !== state.zoom ||
grid !== state.grid
);
}
componentDidUpdate(prevProps) {
const { channel, location } = this.props;
const { location: prevLocation } = prevProps;
if (location && this.getStoryPath(location) !== this.getStoryPath(prevLocation)) {
channel.emit(Events.SET_CURRENT_STORY, { location });
}
}
getStoryPath = location => location.replace(/\/?.+\/(.+)/, '$1');
render() {
const { id, toolbar = true, location = '/', getElements, actions, options } = this.props;
const { zoom, grid } = this.state;
const panels = getElements(types.PANEL);
const toolbarHeight = toolbar ? 40 : 0;
const panelList = Object.entries(panels).map(([key, value]) => ({ ...value, key }));
const tabsList = [{ route: '/components/', title: 'Canvas', key: 'canvas' }].concat(
getElements(types.TAB)
);
const toolList = getElements(types.TOOL);
return (
<Fragment>
{toolbar ? (
<Toolbar
key="toolbar"
left={[
<TabBar key="tabs" scroll={false}>
{tabsList.map(t => (
<S.UnstyledLink
key={t.key}
to={location.replace(/^\/(components|info)\//, t.route)}
>
<TabButton>{t.title}</TabButton>
</S.UnstyledLink>
))}
</TabBar>,
<Separator key="1" />,
<Zoom
key="zoom"
current={zoom}
set={v => this.setState({ zoom: zoom * v })}
reset={() => this.setState({ zoom: 1 })}
/>,
<Separator key="2" />,
<IconButton active={!!grid} key="grid" onClick={() => this.setState({ grid: !grid })}>
<Icons icon="grid" />
</IconButton>,
<Fragment>
{toolList.map(t => (
<Fragment>{t.render()}</Fragment>
))}
</Fragment>,
]}
right={[
<Separator key="1" />,
<IconButton key="full" onClick={actions.toggleFullscreen}>
<Icons icon={options.isFullscreen ? 'cross' : 'expand'} />
</IconButton>,
<Separator key="2" />,
<IconButton key="opener" onClick={() => window.open(`iframe.html?path=${location}`)}>
<Icons icon="share" />
</IconButton>,
]}
/>
) : null}
<S.FrameWrap key="frame" offset={toolbarHeight}>
<Route path="components" startsWith hideOnly>
<S.Frame
style={{
width: `${100 * zoom}%`,
height: `${100 * zoom}%`,
transform: `scale(${1 / zoom})`,
}}
>
<Background id="storybook-preview-background">{grid ? <Grid /> : null}</Background>
<IFrame
id="storybook-preview-iframe"
title={id || 'preview'}
src={`iframe.html?path=${location}`}
allowFullScreen
/>
</S.Frame>
</Route>
{panelList.map(panel => (
<Route path={panel.route} startsWith hideOnly key={panel.key}>
{panel.render({ active: true })}
</Route>
))}
</S.FrameWrap>
</Fragment>
);
}
}
Preview.propTypes = {
id: PropTypes.string.isRequired,
toolbar: PropTypes.bool.isRequired,
channel: PropTypes.shape({
on: PropTypes.func,
emit: PropTypes.func,
removeListener: PropTypes.func,
}).isRequired,
location: PropTypes.string.isRequired,
getElements: PropTypes.func.isRequired,
options: PropTypes.shape({
isFullscreen: PropTypes.bool,
}).isRequired,
actions: PropTypes.shape({}).isRequired,
};
export { Preview };
| lib/components/src/preview/preview.js | 1 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.0003398679837118834,
0.00018295676272828132,
0.0001641253475099802,
0.00017076566291507334,
0.000040695478674024343
]
|
{
"id": 9,
"code_window": [
"import { inject } from 'mobx-react';\n",
"import AddonPanel from '../components/panel/panel';\n",
"\n",
"export function mapper({ store, uiStore }) {\n",
" return {\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { types } from '@storybook/addons';\n",
"\n"
],
"file_path": "lib/ui/src/containers/panel.js",
"type": "add",
"edit_start_line_idx": 1
} | import { buildDev } from '@storybook/core/server';
import options from './options';
buildDev(options);
| app/mithril/src/server/index.js | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.00017767785175237805,
0.00017767785175237805,
0.00017767785175237805,
0.00017767785175237805,
0
]
|
{
"id": 9,
"code_window": [
"import { inject } from 'mobx-react';\n",
"import AddonPanel from '../components/panel/panel';\n",
"\n",
"export function mapper({ store, uiStore }) {\n",
" return {\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { types } from '@storybook/addons';\n",
"\n"
],
"file_path": "lib/ui/src/containers/panel.js",
"type": "add",
"edit_start_line_idx": 1
} | export default {};
| addons/google-analytics/src/index.js | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.00016900447371881455,
0.00016900447371881455,
0.00016900447371881455,
0.00016900447371881455,
0
]
|
{
"id": 9,
"code_window": [
"import { inject } from 'mobx-react';\n",
"import AddonPanel from '../components/panel/panel';\n",
"\n",
"export function mapper({ store, uiStore }) {\n",
" return {\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { types } from '@storybook/addons';\n",
"\n"
],
"file_path": "lib/ui/src/containers/panel.js",
"type": "add",
"edit_start_line_idx": 1
} | import { storiesOf } from '@storybook/html';
import { withNotes } from '@storybook/addon-notes';
storiesOf('Addons|Notes', module)
.addDecorator(withNotes)
.add(
'Simple note',
() =>
`<p>
<strong>
This is a fragment of HTML
</strong>
</p>`,
{
notes: 'My notes on some bold text',
}
);
| examples/html-kitchen-sink/stories/addon-notes.stories.js | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.00017370737623423338,
0.00017230857338290662,
0.00017090977053157985,
0.00017230857338290662,
0.0000013988028513267636
]
|
{
"id": 10,
"code_window": [
"import AddonPanel from '../components/panel/panel';\n",
"\n",
"export function mapper({ store, uiStore }) {\n",
" return {\n",
" panels: store.panels,\n",
" selectedPanel: store.selectedPanel,\n",
" panelPosition: uiStore.panelPosition,\n",
" actions: {\n",
" onSelect: panel => store.selectPanel(panel),\n",
" toggleVisibility: () => uiStore.togglePanel(),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" panels: store.getElements(types.PANEL),\n"
],
"file_path": "lib/ui/src/containers/panel.js",
"type": "replace",
"edit_start_line_idx": 5
} | import { window } from 'global';
import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import Events from '@storybook/core-events';
import { types } from '@storybook/addons';
import { IconButton, Toolbar, Separator } from './toolbar';
import Icons from '../icon/icon';
import { Route } from '../router/router';
import { TabButton, TabBar } from '../tabs/tabs';
import Zoom from './tools/zoom';
import { Grid, Background } from './tools/background';
import * as S from './components';
class IFrame extends Component {
shouldComponentUpdate() {
// this component renders an iframe, which gets updates via post-messages
return false;
}
render() {
const { id, title, src, allowFullScreen, ...rest } = this.props;
return (
<iframe
id={id}
title={title}
src={src}
allowFullScreen={allowFullScreen}
{...rest}
style={{ border: '0 none' }}
/>
);
}
}
IFrame.propTypes = {
id: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
src: PropTypes.string.isRequired,
allowFullScreen: PropTypes.bool.isRequired,
};
// eslint-disable-next-line react/no-multi-comp
class Preview extends Component {
state = {
zoom: 1,
grid: false,
};
shouldComponentUpdate({ location, toolbar, options }, { zoom, grid }) {
const { props, state } = this;
return (
options.isFullscreen !== props.options.isFullscreen ||
location !== props.location ||
toolbar !== props.toolbar ||
zoom !== state.zoom ||
grid !== state.grid
);
}
componentDidUpdate(prevProps) {
const { channel, location } = this.props;
const { location: prevLocation } = prevProps;
if (location && this.getStoryPath(location) !== this.getStoryPath(prevLocation)) {
channel.emit(Events.SET_CURRENT_STORY, { location });
}
}
getStoryPath = location => location.replace(/\/?.+\/(.+)/, '$1');
render() {
const { id, toolbar = true, location = '/', getElements, actions, options } = this.props;
const { zoom, grid } = this.state;
const panels = getElements(types.PANEL);
const toolbarHeight = toolbar ? 40 : 0;
const panelList = Object.entries(panels).map(([key, value]) => ({ ...value, key }));
const tabsList = [{ route: '/components/', title: 'Canvas', key: 'canvas' }].concat(
getElements(types.TAB)
);
const toolList = getElements(types.TOOL);
return (
<Fragment>
{toolbar ? (
<Toolbar
key="toolbar"
left={[
<TabBar key="tabs" scroll={false}>
{tabsList.map(t => (
<S.UnstyledLink
key={t.key}
to={location.replace(/^\/(components|info)\//, t.route)}
>
<TabButton>{t.title}</TabButton>
</S.UnstyledLink>
))}
</TabBar>,
<Separator key="1" />,
<Zoom
key="zoom"
current={zoom}
set={v => this.setState({ zoom: zoom * v })}
reset={() => this.setState({ zoom: 1 })}
/>,
<Separator key="2" />,
<IconButton active={!!grid} key="grid" onClick={() => this.setState({ grid: !grid })}>
<Icons icon="grid" />
</IconButton>,
<Fragment>
{toolList.map(t => (
<Fragment>{t.render()}</Fragment>
))}
</Fragment>,
]}
right={[
<Separator key="1" />,
<IconButton key="full" onClick={actions.toggleFullscreen}>
<Icons icon={options.isFullscreen ? 'cross' : 'expand'} />
</IconButton>,
<Separator key="2" />,
<IconButton key="opener" onClick={() => window.open(`iframe.html?path=${location}`)}>
<Icons icon="share" />
</IconButton>,
]}
/>
) : null}
<S.FrameWrap key="frame" offset={toolbarHeight}>
<Route path="components" startsWith hideOnly>
<S.Frame
style={{
width: `${100 * zoom}%`,
height: `${100 * zoom}%`,
transform: `scale(${1 / zoom})`,
}}
>
<Background id="storybook-preview-background">{grid ? <Grid /> : null}</Background>
<IFrame
id="storybook-preview-iframe"
title={id || 'preview'}
src={`iframe.html?path=${location}`}
allowFullScreen
/>
</S.Frame>
</Route>
{panelList.map(panel => (
<Route path={panel.route} startsWith hideOnly key={panel.key}>
{panel.render({ active: true })}
</Route>
))}
</S.FrameWrap>
</Fragment>
);
}
}
Preview.propTypes = {
id: PropTypes.string.isRequired,
toolbar: PropTypes.bool.isRequired,
channel: PropTypes.shape({
on: PropTypes.func,
emit: PropTypes.func,
removeListener: PropTypes.func,
}).isRequired,
location: PropTypes.string.isRequired,
getElements: PropTypes.func.isRequired,
options: PropTypes.shape({
isFullscreen: PropTypes.bool,
}).isRequired,
actions: PropTypes.shape({}).isRequired,
};
export { Preview };
| lib/components/src/preview/preview.js | 1 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.008088445290923119,
0.0006216756883077323,
0.00016628736921120435,
0.00017143794684670866,
0.001811556052416563
]
|
{
"id": 10,
"code_window": [
"import AddonPanel from '../components/panel/panel';\n",
"\n",
"export function mapper({ store, uiStore }) {\n",
" return {\n",
" panels: store.panels,\n",
" selectedPanel: store.selectedPanel,\n",
" panelPosition: uiStore.panelPosition,\n",
" actions: {\n",
" onSelect: panel => store.selectPanel(panel),\n",
" toggleVisibility: () => uiStore.togglePanel(),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" panels: store.getElements(types.PANEL),\n"
],
"file_path": "lib/ui/src/containers/panel.js",
"type": "replace",
"edit_start_line_idx": 5
} | import React from 'react';
import PropTypes from 'prop-types';
/** BaseButton component description imported from comments inside the component file */
const BaseButton = ({ disabled, label, onClick, style }) => (
<button type="button" disabled={disabled} onClick={onClick} style={style}>
{label}
</button>
);
BaseButton.defaultProps = {
disabled: false,
onClick: () => {},
style: {},
};
BaseButton.propTypes = {
/** Boolean indicating whether the button should render as disabled */
disabled: PropTypes.bool,
/** button label. */
label: PropTypes.string.isRequired,
/** onClick handler */
onClick: PropTypes.func,
/** Custom styles */
style: PropTypes.shape({}),
};
export default BaseButton;
| examples/official-storybook/components/BaseButton.js | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.00017424550605937839,
0.00016970869910437614,
0.0001645718002691865,
0.00017030883464030921,
0.000003972006652475102
]
|
{
"id": 10,
"code_window": [
"import AddonPanel from '../components/panel/panel';\n",
"\n",
"export function mapper({ store, uiStore }) {\n",
" return {\n",
" panels: store.panels,\n",
" selectedPanel: store.selectedPanel,\n",
" panelPosition: uiStore.panelPosition,\n",
" actions: {\n",
" onSelect: panel => store.selectPanel(panel),\n",
" toggleVisibility: () => uiStore.togglePanel(),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" panels: store.getElements(types.PANEL),\n"
],
"file_path": "lib/ui/src/containers/panel.js",
"type": "replace",
"edit_start_line_idx": 5
} | <?xml version="1.0" encoding="UTF-8"?>
<svg width="80px" height="16px" viewBox="0 0 80 16" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 42 (36781) - http://www.bohemiancoding.com/sketch -->
<title>buffer-logo</title>
<desc>Created with Sketch.</desc>
<defs></defs>
<g id="buffer-web" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="buffer-logo" fill="#323B43">
<g id="Buffer-+-Logomark">
<g id="Buffer" transform="translate(21.643446, 0.000000)">
<path d="M2.93508416,15.5935101 L0.164977074,15.5935101 L0.164977074,0.0321392956 L2.93508416,0.0321392956 L2.93508416,6.07194618 C3.76393511,4.96373565 4.94177592,4.39832212 6.18505233,4.39832212 C8.86791195,4.39832212 10.8527918,6.56951009 10.8527918,10.1429236 C10.8527918,13.7841868 8.84610008,15.8649086 6.18505233,15.8649086 C4.91996405,15.8649086 3.76393511,15.2768785 2.93508416,14.1912845 L2.93508416,15.5935101 Z M2.93508416,12.0879462 C3.39313337,12.789059 4.41829111,13.3092394 5.31257765,13.3092394 C6.9266558,13.3092394 7.99543728,12.0427131 7.99543728,10.1429236 C7.99543728,8.24313415 6.9266558,6.95399129 5.31257765,6.95399129 C4.41829111,6.95399129 3.39313337,7.49678829 2.93508416,8.22051761 L2.93508416,12.0879462 Z M22.7127074,15.5935101 L19.9426004,15.5935101 L19.9426004,14.2139011 C19.2228087,15.0507131 17.9577205,15.8649086 16.234583,15.8649086 C13.9225251,15.8649086 12.8319318,14.5531492 12.8319318,12.4271943 L12.8319318,4.66972062 L15.6020388,4.66972062 L15.6020388,11.2963672 C15.6020388,12.8116755 16.3654542,13.3092394 17.543295,13.3092394 C18.6120765,13.3092394 19.4627393,12.6985928 19.9426004,12.0653296 L19.9426004,4.66972062 L22.7127074,4.66972062 L22.7127074,15.5935101 Z M28.9784532,15.5935101 L26.1865342,15.5935101 L26.1865342,7.18015671 L24.4415849,7.18015671 L24.4415849,4.66972062 L26.1865342,4.66972062 L26.1865342,4.08169054 C26.1865342,1.75218678 27.6261174,0.282111595 29.7418685,0.282111595 C30.7452144,0.282111595 31.8139959,0.553510091 32.4901638,1.29985596 L31.4431942,2.99609656 C31.1596399,2.70208152 30.7888381,2.54376573 30.2871652,2.54376573 C29.5237499,2.54376573 28.9784532,3.06394618 28.9784532,4.08169054 L28.9784532,4.66972062 L31.1160161,4.66972062 L31.1160161,7.18015671 L28.9784532,7.18015671 L28.9784532,15.5935101 Z M36.1109337,15.5935101 L33.3190147,15.5935101 L33.3190147,7.18015671 L31.5740654,7.18015671 L31.5740654,4.66972062 L33.3190147,4.66972062 L33.3190147,4.08169054 C33.3190147,1.75218678 34.7585979,0.282111595 36.874349,0.282111595 C37.8776949,0.282111595 38.9464764,0.553510091 39.6226442,1.29985596 L38.5756746,2.99609656 C38.2921203,2.70208152 37.9213186,2.54376573 37.4196457,2.54376573 C36.6562303,2.54376573 36.1109337,3.06394618 36.1109337,4.08169054 L36.1109337,4.66972062 L38.2484966,4.66972062 L38.2484966,7.18015671 L36.1109337,7.18015671 L36.1109337,15.5935101 Z M44.4694706,15.8649086 C41.2631262,15.8649086 38.842009,13.625871 38.842009,10.1203071 C38.842009,6.95399129 41.0886313,4.39832212 44.2949757,4.39832212 C47.4358845,4.39832212 49.5734475,6.84090859 49.5734475,10.4143221 L49.5734475,11.0475853 L41.7429873,11.0475853 C41.9174822,12.4271943 42.9862637,13.5806379 44.7748368,13.5806379 C45.6691233,13.5806379 46.9123997,13.1735402 47.5885676,12.4950439 L48.8100321,14.3496003 C47.7630625,15.3447281 46.1053607,15.8649086 44.4694706,15.8649086 Z M46.8905879,9.10256272 C46.8251523,8.06220182 46.1271725,6.6825928 44.2949757,6.6825928 C42.5718382,6.6825928 41.8302347,8.01696874 41.6993635,9.10256272 L46.8905879,9.10256272 Z M54.3502463,15.5935101 L51.5801392,15.5935101 L51.5801392,4.66972062 L54.3502463,4.66972062 L54.3502463,6.16241235 C55.0918498,5.18990107 56.4005618,4.39832212 57.7092738,4.39832212 L57.7092738,7.20277325 C57.512967,7.15754017 57.2512246,7.13492362 56.9458585,7.13492362 C56.0297601,7.13492362 54.8082955,7.67772062 54.3502463,8.3788334 L54.3502463,15.5935101 Z" id="buffer"></path>
</g>
<g id="Logomark" transform="translate(0.000000, 1.190344)">
<path d="M13.6751257,10.8759711 L12.1080077,10.1271144 C11.9736387,10.0628916 11.7537083,10.0628916 11.6192855,10.1271144 L7.13231903,12.2712406 C6.99795003,12.3354634 6.77796588,12.3354634 6.64359688,12.2712406 L2.1566304,10.1271144 C2.02220759,10.0628916 1.80227725,10.0628916 1.66790826,10.1271144 L0.100790197,10.8759711 C-0.033578795,10.9401939 -0.033578795,11.0452604 0.100790197,11.1094832 L6.64359688,14.2359782 C6.77796588,14.300201 6.99795003,14.300201 7.13231903,14.2359782 L13.6751257,11.1094832 C13.8094947,11.0452604 13.8094947,10.9401939 13.6751257,10.8759711" id="Fill-1"></path>
<path d="M13.6751257,7.02528176 L12.1080077,6.27648081 C11.9736387,6.21225801 11.7537083,6.21225801 11.6192855,6.27648081 L7.13231903,8.42055125 C6.99795003,8.48477404 6.77796588,8.48477404 6.64359688,8.42055125 L2.1566304,6.27648081 C2.02220759,6.21225801 1.80227725,6.21225801 1.66790826,6.27648081 L0.100790197,7.02528176 C-0.033578795,7.08950455 -0.033578795,7.19462683 0.100790197,7.25884962 L6.64359688,10.3852889 C6.77796588,10.4495117 6.99795003,10.4495117 7.13231903,10.3852889 L13.6751257,7.25884962 C13.8094947,7.19462683 13.8094947,7.08950455 13.6751257,7.02528176" id="Fill-2"></path>
<path d="M0.100790197,3.40816027 L6.64359688,6.53465532 C6.77796588,6.59887812 6.99795003,6.59887812 7.13231903,6.53465532 L13.6751257,3.40816027 C13.8094947,3.34393748 13.8094947,3.23887099 13.6751257,3.1746482 L7.13231903,0.048153146 C6.99795003,-0.0160696478 6.77796588,-0.0160696478 6.64359688,0.048153146 L0.100790197,3.1746482 C-0.033578795,3.23887099 -0.033578795,3.34393748 0.100790197,3.40816027" id="Fill-3"></path>
</g>
</g>
</g>
</g>
</svg> | docs/src/pages/logos/buffer.svg | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.0001838250464061275,
0.00017700204625725746,
0.00017326090892311186,
0.00017392018344253302,
0.000004832091235584812
]
|
{
"id": 10,
"code_window": [
"import AddonPanel from '../components/panel/panel';\n",
"\n",
"export function mapper({ store, uiStore }) {\n",
" return {\n",
" panels: store.panels,\n",
" selectedPanel: store.selectedPanel,\n",
" panelPosition: uiStore.panelPosition,\n",
" actions: {\n",
" onSelect: panel => store.selectPanel(panel),\n",
" toggleVisibility: () => uiStore.togglePanel(),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" panels: store.getElements(types.PANEL),\n"
],
"file_path": "lib/ui/src/containers/panel.js",
"type": "replace",
"edit_start_line_idx": 5
} | import PropTypes from 'prop-types';
import React from 'react';
import { Text, Modal, View, TouchableOpacity, TouchableWithoutFeedback } from 'react-native';
import { ColorPicker, fromHsv } from 'react-native-color-picker';
class ColorType extends React.Component {
constructor(props) {
super(props);
this.state = {
displayColorPicker: false,
};
}
openColorPicker = () => {
this.setState({
displayColorPicker: true,
});
};
closeColorPicker = () => {
this.setState({
displayColorPicker: false,
});
};
onChangeColor = color => {
const { onChange } = this.props;
onChange(fromHsv(color));
};
render() {
const { knob } = this.props;
const { displayColorPicker } = this.state;
const colorStyle = {
borderColor: 'rgb(247, 244, 244)',
width: 30,
height: 20,
borderRadius: 2,
margin: 10,
backgroundColor: knob.value,
};
return (
<View>
<TouchableOpacity style={colorStyle} onPress={this.openColorPicker} />
<Modal
supportedOrientations={['portrait', 'landscape']}
transparent
visible={displayColorPicker}
onRequestClose={this.closeColorPicker}
>
<TouchableWithoutFeedback onPress={this.closeColorPicker}>
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<TouchableWithoutFeedback>
<View
style={{
backgroundColor: 'white',
borderWidth: 1,
borderColor: 'rgb(247, 244, 244)',
width: 250,
height: 250,
padding: 10,
}}
>
<TouchableOpacity
onPress={this.closeColorPicker}
style={{ alignSelf: 'flex-end', padding: 5 }}
>
<Text style={{ fontSize: 18, fontWeight: 'bold' }}>X</Text>
</TouchableOpacity>
<ColorPicker
onColorSelected={this.onChangeColor}
defaultColor={knob.value}
style={{ flex: 1 }}
/>
</View>
</TouchableWithoutFeedback>
</View>
</TouchableWithoutFeedback>
</Modal>
</View>
);
}
}
ColorType.propTypes = {
knob: PropTypes.shape({
name: PropTypes.string,
value: PropTypes.string,
}),
onChange: PropTypes.func,
};
ColorType.defaultProps = {
knob: {},
onChange: value => value,
};
ColorType.serialize = value => value;
ColorType.deserialize = value => value;
export default ColorType;
| addons/ondevice-knobs/src/types/Color.js | 0 | https://github.com/storybookjs/storybook/commit/6c275121271ddcdb79639a3969eacaa718d65915 | [
0.0001750783994793892,
0.0001712086086627096,
0.0001650399499339983,
0.00017253585974685848,
0.0000032629316137899878
]
|
{
"id": 0,
"code_window": [
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"25\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"26\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"27\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"28\"],\n",
" [0, 0, 0, \"Do not use any type assertions.\", \"29\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"30\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"31\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"32\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"33\"],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" [0, 0, 0, \"Do not use any type assertions.\", \"28\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"29\"],\n"
],
"file_path": ".betterer.results",
"type": "replace",
"edit_start_line_idx": 1000
} | import { cloneDeep, defaults as _defaults, filter, indexOf, isEqual, map, maxBy, pull } from 'lodash';
import { Subscription } from 'rxjs';
import {
AnnotationQuery,
AppEvent,
DashboardCursorSync,
dateTime,
dateTimeFormat,
dateTimeFormatTimeAgo,
DateTimeInput,
EventBusExtended,
EventBusSrv,
PanelModel as IPanelModel,
TimeRange,
TimeZone,
UrlQueryValue,
} from '@grafana/data';
import { RefreshEvent, TimeRangeUpdatedEvent } from '@grafana/runtime';
import { Dashboard } from '@grafana/schema';
import { DEFAULT_ANNOTATION_COLOR } from '@grafana/ui';
import { GRID_CELL_HEIGHT, GRID_CELL_VMARGIN, GRID_COLUMN_COUNT, REPEAT_DIR_VERTICAL } from 'app/core/constants';
import { contextSrv } from 'app/core/services/context_srv';
import { sortedDeepCloneWithoutNulls } from 'app/core/utils/object';
import { variableAdapters } from 'app/features/variables/adapters';
import { onTimeRangeUpdated } from 'app/features/variables/state/actions';
import { GetVariables, getVariablesByKey } from 'app/features/variables/state/selectors';
import { CoreEvents, DashboardMeta, KioskMode } from 'app/types';
import { DashboardMetaChangedEvent, DashboardPanelsChangedEvent, RenderEvent } from 'app/types/events';
import { appEvents } from '../../../core/core';
import { dispatch } from '../../../store/store';
import {
VariablesChanged,
VariablesChangedEvent,
VariablesChangedInUrl,
VariablesTimeRangeProcessDone,
} from '../../variables/types';
import { isAllVariable } from '../../variables/utils';
import { getTimeSrv } from '../services/TimeSrv';
import { mergePanels, PanelMergeInfo } from '../utils/panelMerge';
import { DashboardMigrator } from './DashboardMigrator';
import { GridPos, PanelModel } from './PanelModel';
import { TimeModel } from './TimeModel';
import { deleteScopeVars, isOnTheSameGridRow } from './utils';
export interface CloneOptions {
saveVariables?: boolean;
saveTimerange?: boolean;
message?: string;
}
export type DashboardLinkType = 'link' | 'dashboards';
export interface DashboardLink {
icon: string;
title: string;
tooltip: string;
type: DashboardLinkType;
url: string;
asDropdown: boolean;
tags: any[];
searchHits?: any[];
targetBlank: boolean;
keepTime: boolean;
includeVars: boolean;
}
export class DashboardModel implements TimeModel {
id: any;
// TODO: use propert type and fix all the places where uid is set to null
uid: any;
title: string;
description: any;
tags: any;
style: any;
timezone: any;
weekStart: any;
editable: any;
graphTooltip: DashboardCursorSync;
time: any;
liveNow: boolean;
private originalTime: any;
timepicker: any;
templating: { list: any[] };
private originalTemplating: any;
annotations: { list: AnnotationQuery[] };
refresh: any;
snapshot: any;
schemaVersion: number;
version: number;
revision: number;
links: DashboardLink[];
gnetId: any;
panels: PanelModel[];
panelInEdit?: PanelModel;
panelInView?: PanelModel;
fiscalYearStartMonth?: number;
private panelsAffectedByVariableChange: number[] | null;
private appEventsSubscription: Subscription;
private lastRefresh: number;
// ------------------
// not persisted
// ------------------
// repeat process cycles
declare meta: DashboardMeta;
events: EventBusExtended;
static nonPersistedProperties: { [str: string]: boolean } = {
events: true,
meta: true,
panels: true, // needs special handling
templating: true, // needs special handling
originalTime: true,
originalTemplating: true,
originalLibraryPanels: true,
panelInEdit: true,
panelInView: true,
getVariablesFromState: true,
formatDate: true,
appEventsSubscription: true,
panelsAffectedByVariableChange: true,
lastRefresh: true,
};
constructor(data: Dashboard, meta?: DashboardMeta, private getVariablesFromState: GetVariables = getVariablesByKey) {
this.events = new EventBusSrv();
this.id = data.id || null;
// UID is not there for newly created dashboards
this.uid = data.uid || null;
this.revision = data.revision || 1;
this.title = data.title ?? 'No Title';
this.description = data.description;
this.tags = data.tags ?? [];
this.style = data.style ?? 'dark';
this.timezone = data.timezone ?? '';
this.weekStart = data.weekStart ?? '';
this.editable = data.editable !== false;
this.graphTooltip = data.graphTooltip || 0;
this.time = data.time ?? { from: 'now-6h', to: 'now' };
this.timepicker = data.timepicker ?? {};
this.liveNow = Boolean(data.liveNow);
this.templating = this.ensureListExist(data.templating);
this.annotations = this.ensureListExist(data.annotations);
this.refresh = data.refresh;
this.snapshot = data.snapshot;
this.schemaVersion = data.schemaVersion ?? 0;
this.fiscalYearStartMonth = data.fiscalYearStartMonth ?? 0;
this.version = data.version ?? 0;
this.links = data.links ?? [];
this.gnetId = data.gnetId || null;
this.panels = map(data.panels ?? [], (panelData: any) => new PanelModel(panelData));
this.ensurePanelsHaveIds();
this.formatDate = this.formatDate.bind(this);
this.resetOriginalVariables(true);
this.resetOriginalTime();
this.initMeta(meta);
this.updateSchema(data);
this.addBuiltInAnnotationQuery();
this.sortPanelsByGridPos();
this.panelsAffectedByVariableChange = null;
this.appEventsSubscription = new Subscription();
this.lastRefresh = Date.now();
this.appEventsSubscription.add(appEvents.subscribe(VariablesChanged, this.variablesChangedHandler.bind(this)));
this.appEventsSubscription.add(
appEvents.subscribe(VariablesTimeRangeProcessDone, this.variablesTimeRangeProcessDoneHandler.bind(this))
);
this.appEventsSubscription.add(
appEvents.subscribe(VariablesChangedInUrl, this.variablesChangedInUrlHandler.bind(this))
);
}
addBuiltInAnnotationQuery() {
const found = this.annotations.list.some((item) => item.builtIn === 1);
if (found) {
return;
}
this.annotations.list.unshift({
datasource: { uid: '-- Grafana --', type: 'grafana' },
name: 'Annotations & Alerts',
type: 'dashboard',
iconColor: DEFAULT_ANNOTATION_COLOR,
enable: true,
hide: true,
builtIn: 1,
});
}
private initMeta(meta?: DashboardMeta) {
meta = meta || {};
meta.canShare = meta.canShare !== false;
meta.canSave = meta.canSave !== false;
meta.canStar = meta.canStar !== false;
meta.canEdit = meta.canEdit !== false;
meta.canDelete = meta.canDelete !== false;
meta.showSettings = meta.canEdit;
meta.canMakeEditable = meta.canSave && !this.editable;
meta.hasUnsavedFolderChange = false;
if (!this.editable) {
meta.canEdit = false;
meta.canDelete = false;
meta.canSave = false;
}
this.meta = meta;
}
// cleans meta data and other non persistent state
getSaveModelClone(options?: CloneOptions): DashboardModel {
const defaults = _defaults(options || {}, {
saveVariables: true,
saveTimerange: true,
});
// make clone
let copy: any = {};
for (const property in this) {
if (DashboardModel.nonPersistedProperties[property] || !this.hasOwnProperty(property)) {
continue;
}
copy[property] = cloneDeep(this[property]);
}
this.updateTemplatingSaveModelClone(copy, defaults);
if (!defaults.saveTimerange) {
copy.time = this.originalTime;
}
// get panel save models
copy.panels = this.getPanelSaveModels();
// sort by keys
copy = sortedDeepCloneWithoutNulls(copy);
copy.getVariables = () => copy.templating.list;
return copy;
}
/**
* This will load a new dashboard, but keep existing panels unchanged
*
* This function can be used to implement:
* 1. potentially faster loading dashboard loading
* 2. dynamic dashboard behavior
* 3. "live" dashboard editing
*
* @internal and experimental
*/
updatePanels(panels: IPanelModel[]): PanelMergeInfo {
const info = mergePanels(this.panels, panels ?? []);
if (info.changed) {
this.panels = info.panels ?? [];
this.sortPanelsByGridPos();
this.events.publish(new DashboardPanelsChangedEvent());
}
return info;
}
private getPanelSaveModels() {
return this.panels
.filter(
(panel) =>
this.isSnapshotTruthy() || !(panel.type === 'add-panel' || panel.repeatPanelId || panel.repeatedByRow)
)
.map((panel) => {
// Clean libarary panels on save
if (panel.libraryPanel) {
const { id, title, libraryPanel, gridPos } = panel;
return {
id,
title,
gridPos,
libraryPanel: {
uid: libraryPanel.uid,
name: libraryPanel.name,
},
};
}
// If we save while editing we should include the panel in edit mode instead of the
// unmodified source panel
if (this.panelInEdit && this.panelInEdit.id === panel.id) {
return this.panelInEdit.getSaveModel();
}
return panel.getSaveModel();
})
.map((model: any) => {
if (this.isSnapshotTruthy()) {
return model;
}
// Clear any scopedVars from persisted mode. This cannot be part of getSaveModel as we need to be able to copy
// panel models with preserved scopedVars, for example when going into edit mode.
delete model.scopedVars;
// Clear any repeated panels from collapsed rows
if (model.type === 'row' && model.panels && model.panels.length > 0) {
model.panels = model.panels
.filter((rowPanel: PanelModel) => !rowPanel.repeatPanelId)
.map((model: PanelModel) => {
delete model.scopedVars;
return model;
});
}
return model;
});
}
private updateTemplatingSaveModelClone(
copy: any,
defaults: { saveTimerange: boolean; saveVariables: boolean } & CloneOptions
) {
const originalVariables = this.originalTemplating;
const currentVariables = this.getVariablesFromState(this.uid);
copy.templating = {
list: currentVariables.map((variable) =>
variableAdapters.get(variable.type).getSaveModel(variable, defaults.saveVariables)
),
};
if (!defaults.saveVariables) {
for (const current of copy.templating.list) {
const original = originalVariables.find(
({ name, type }: any) => name === current.name && type === current.type
);
if (!original) {
continue;
}
if (current.type === 'adhoc') {
current.filters = original.filters;
} else {
current.current = original.current;
}
}
}
}
timeRangeUpdated(timeRange: TimeRange) {
this.events.publish(new TimeRangeUpdatedEvent(timeRange));
dispatch(onTimeRangeUpdated(this.uid, timeRange));
}
startRefresh(event: VariablesChangedEvent = { refreshAll: true, panelIds: [] }) {
this.events.publish(new RefreshEvent());
this.lastRefresh = Date.now();
if (this.panelInEdit && (event.refreshAll || event.panelIds.includes(this.panelInEdit.id))) {
this.panelInEdit.refresh();
return;
}
for (const panel of this.panels) {
if (!this.otherPanelInFullscreen(panel) && (event.refreshAll || event.panelIds.includes(panel.id))) {
panel.refresh();
}
}
}
render() {
this.events.publish(new RenderEvent());
for (const panel of this.panels) {
panel.render();
}
}
panelInitialized(panel: PanelModel) {
const lastResult = panel.getQueryRunner().getLastResult();
if (!this.otherPanelInFullscreen(panel) && !lastResult) {
panel.refresh();
}
}
otherPanelInFullscreen(panel: PanelModel) {
return (this.panelInEdit || this.panelInView) && !(panel.isViewing || panel.isEditing);
}
initEditPanel(sourcePanel: PanelModel): PanelModel {
getTimeSrv().pauseAutoRefresh();
this.panelInEdit = sourcePanel.getEditClone();
return this.panelInEdit;
}
initViewPanel(panel: PanelModel) {
this.panelInView = panel;
panel.setIsViewing(true);
}
exitViewPanel(panel: PanelModel) {
this.panelInView = undefined;
panel.setIsViewing(false);
this.refreshIfPanelsAffectedByVariableChange();
}
exitPanelEditor() {
this.panelInEdit!.destroy();
this.panelInEdit = undefined;
getTimeSrv().resumeAutoRefresh();
this.refreshIfPanelsAffectedByVariableChange();
}
private refreshIfPanelsAffectedByVariableChange() {
if (!this.panelsAffectedByVariableChange) {
return;
}
this.startRefresh({ panelIds: this.panelsAffectedByVariableChange, refreshAll: false });
this.panelsAffectedByVariableChange = null;
}
private ensurePanelsHaveIds() {
let nextPanelId = this.getNextPanelId();
for (const panel of this.panelIterator()) {
panel.id ??= nextPanelId++;
}
}
private ensureListExist(data: any = {}) {
data.list ??= [];
return data;
}
getNextPanelId() {
let max = 0;
for (const panel of this.panelIterator()) {
if (panel.id > max) {
max = panel.id;
}
}
return max + 1;
}
*panelIterator() {
for (const panel of this.panels) {
yield panel;
const rowPanels = panel.panels ?? [];
for (const rowPanel of rowPanels) {
yield rowPanel;
}
}
}
forEachPanel(callback: (panel: PanelModel, index: number) => void) {
for (let i = 0; i < this.panels.length; i++) {
callback(this.panels[i], i);
}
}
getPanelById(id: number): PanelModel | null {
if (this.panelInEdit && this.panelInEdit.id === id) {
return this.panelInEdit;
}
return this.panels.find((p) => p.id === id) ?? null;
}
canEditPanel(panel?: PanelModel | null): boolean | undefined | null {
return Boolean(this.meta.canEdit && panel && !panel.repeatPanelId && panel.type !== 'row');
}
canEditPanelById(id: number): boolean | undefined | null {
return this.canEditPanel(this.getPanelById(id));
}
addPanel(panelData: any) {
panelData.id = this.getNextPanelId();
this.panels.unshift(new PanelModel(panelData));
this.sortPanelsByGridPos();
this.events.publish(new DashboardPanelsChangedEvent());
}
updateMeta(updates: Partial<DashboardMeta>) {
this.meta = { ...this.meta, ...updates };
this.events.publish(new DashboardMetaChangedEvent());
}
makeEditable() {
this.editable = true;
this.updateMeta({
canMakeEditable: false,
canEdit: true,
canSave: true,
});
}
sortPanelsByGridPos() {
this.panels.sort((panelA, panelB) => {
if (panelA.gridPos.y === panelB.gridPos.y) {
return panelA.gridPos.x - panelB.gridPos.x;
} else {
return panelA.gridPos.y - panelB.gridPos.y;
}
});
}
clearUnsavedChanges() {
for (const panel of this.panels) {
panel.configRev = 0;
}
if (this.panelInEdit) {
// Remember that we have a saved a change in panel editor so we apply it when leaving panel edit
this.panelInEdit.hasSavedPanelEditChange = this.panelInEdit.configRev > 0;
this.panelInEdit.configRev = 0;
}
}
hasUnsavedChanges() {
const changedPanel = this.panels.find((p) => p.hasChanged);
return Boolean(changedPanel);
}
cleanUpRepeats() {
if (this.isSnapshotTruthy() || !this.hasVariables()) {
return;
}
// cleanup scopedVars
deleteScopeVars(this.panels);
const panelsToRemove = this.panels.filter((p) => (!p.repeat || p.repeatedByRow) && p.repeatPanelId);
// remove panels
pull(this.panels, ...panelsToRemove);
panelsToRemove.map((p) => p.destroy());
this.sortPanelsByGridPos();
}
processRepeats() {
if (this.isSnapshotTruthy() || !this.hasVariables()) {
return;
}
this.cleanUpRepeats();
for (let i = 0; i < this.panels.length; i++) {
const panel = this.panels[i];
if (panel.repeat) {
this.repeatPanel(panel, i);
}
}
this.sortPanelsByGridPos();
this.events.publish(new DashboardPanelsChangedEvent());
}
cleanUpRowRepeats(rowPanels: PanelModel[]) {
const panelIds = rowPanels.map((row) => row.id);
// Remove repeated panels whose parent is in this row as these will be recreated later in processRowRepeats
const panelsToRemove = rowPanels.filter((p) => !p.repeat && p.repeatPanelId && panelIds.includes(p.repeatPanelId));
pull(rowPanels, ...panelsToRemove);
pull(this.panels, ...panelsToRemove);
}
processRowRepeats(row: PanelModel) {
if (this.isSnapshotTruthy() || !this.hasVariables()) {
return;
}
let rowPanels = row.panels ?? [];
if (!row.collapsed) {
const rowPanelIndex = this.panels.findIndex((p) => p.id === row.id);
rowPanels = this.getRowPanels(rowPanelIndex);
}
this.cleanUpRowRepeats(rowPanels);
for (const panel of rowPanels) {
if (panel.repeat) {
const panelIndex = this.panels.findIndex((p) => p.id === panel.id);
this.repeatPanel(panel, panelIndex);
}
}
}
getPanelRepeatClone(sourcePanel: PanelModel, valueIndex: number, sourcePanelIndex: number) {
// if first clone return source
if (valueIndex === 0) {
return sourcePanel;
}
const m = sourcePanel.getSaveModel();
m.id = this.getNextPanelId();
const clone = new PanelModel(m);
// insert after source panel + value index
this.panels.splice(sourcePanelIndex + valueIndex, 0, clone);
clone.repeatPanelId = sourcePanel.id;
clone.repeat = undefined;
if (this.panelInView?.id === clone.id) {
clone.setIsViewing(true);
this.panelInView = clone;
}
return clone;
}
getRowRepeatClone(sourceRowPanel: PanelModel, valueIndex: number, sourcePanelIndex: number) {
// if first clone return source
if (valueIndex === 0) {
if (!sourceRowPanel.collapsed) {
const rowPanels = this.getRowPanels(sourcePanelIndex);
sourceRowPanel.panels = rowPanels;
}
return sourceRowPanel;
}
const clone = new PanelModel(sourceRowPanel.getSaveModel());
// for row clones we need to figure out panels under row to clone and where to insert clone
let rowPanels: PanelModel[], insertPos: number;
if (sourceRowPanel.collapsed) {
rowPanels = cloneDeep(sourceRowPanel.panels) ?? [];
clone.panels = rowPanels;
// insert copied row after preceding row
insertPos = sourcePanelIndex + valueIndex;
} else {
rowPanels = this.getRowPanels(sourcePanelIndex);
clone.panels = rowPanels.map((panel) => panel.getSaveModel());
// insert copied row after preceding row's panels
insertPos = sourcePanelIndex + (rowPanels.length + 1) * valueIndex;
}
this.panels.splice(insertPos, 0, clone);
this.updateRepeatedPanelIds(clone);
return clone;
}
repeatPanel(panel: PanelModel, panelIndex: number) {
const variable = this.getPanelRepeatVariable(panel);
if (!variable) {
return;
}
if (panel.type === 'row') {
this.repeatRow(panel, panelIndex, variable);
return;
}
const selectedOptions = this.getSelectedVariableOptions(variable);
const maxPerRow = panel.maxPerRow || 4;
let xPos = 0;
let yPos = panel.gridPos.y;
for (let index = 0; index < selectedOptions.length; index++) {
const option = selectedOptions[index];
let copy;
copy = this.getPanelRepeatClone(panel, index, panelIndex);
copy.scopedVars ??= {};
copy.scopedVars[variable.name] = option;
if (panel.repeatDirection === REPEAT_DIR_VERTICAL) {
if (index > 0) {
yPos += copy.gridPos.h;
}
copy.gridPos.y = yPos;
} else {
// set width based on how many are selected
// assumed the repeated panels should take up full row width
copy.gridPos.w = Math.max(GRID_COLUMN_COUNT / selectedOptions.length, GRID_COLUMN_COUNT / maxPerRow);
copy.gridPos.x = xPos;
copy.gridPos.y = yPos;
xPos += copy.gridPos.w;
// handle overflow by pushing down one row
if (xPos + copy.gridPos.w > GRID_COLUMN_COUNT) {
xPos = 0;
yPos += copy.gridPos.h;
}
}
}
// Update gridPos for panels below
const yOffset = yPos - panel.gridPos.y;
if (yOffset > 0) {
const panelBelowIndex = panelIndex + selectedOptions.length;
for (const curPanel of this.panels.slice(panelBelowIndex)) {
if (isOnTheSameGridRow(panel, curPanel)) {
continue;
}
curPanel.gridPos.y += yOffset;
}
}
}
repeatRow(panel: PanelModel, panelIndex: number, variable: any) {
const selectedOptions = this.getSelectedVariableOptions(variable);
let yPos = panel.gridPos.y;
function setScopedVars(panel: PanelModel, variableOption: any) {
panel.scopedVars ??= {};
panel.scopedVars[variable.name] = variableOption;
}
for (let optionIndex = 0; optionIndex < selectedOptions.length; optionIndex++) {
const option = selectedOptions[optionIndex];
const rowCopy = this.getRowRepeatClone(panel, optionIndex, panelIndex);
setScopedVars(rowCopy, option);
const rowHeight = this.getRowHeight(rowCopy);
const rowPanels = rowCopy.panels || [];
let panelBelowIndex;
if (panel.collapsed) {
// For collapsed row just copy its panels and set scoped vars and proper IDs
for (const rowPanel of rowPanels) {
setScopedVars(rowPanel, option);
if (optionIndex > 0) {
this.updateRepeatedPanelIds(rowPanel, true);
}
}
rowCopy.gridPos.y += optionIndex;
yPos += optionIndex;
panelBelowIndex = panelIndex + optionIndex + 1;
} else {
// insert after 'row' panel
const insertPos = panelIndex + (rowPanels.length + 1) * optionIndex + 1;
rowPanels.forEach((rowPanel: PanelModel, i: number) => {
setScopedVars(rowPanel, option);
if (optionIndex > 0) {
const cloneRowPanel = new PanelModel(rowPanel);
this.updateRepeatedPanelIds(cloneRowPanel, true);
// For exposed row additionally set proper Y grid position and add it to dashboard panels
cloneRowPanel.gridPos.y += rowHeight * optionIndex;
this.panels.splice(insertPos + i, 0, cloneRowPanel);
}
});
rowCopy.panels = [];
rowCopy.gridPos.y += rowHeight * optionIndex;
yPos += rowHeight;
panelBelowIndex = insertPos + rowPanels.length;
}
// Update gridPos for panels below if we inserted more than 1 repeated row panel
if (selectedOptions.length > 1) {
for (const panel of this.panels.slice(panelBelowIndex)) {
panel.gridPos.y += yPos;
}
}
}
}
updateRepeatedPanelIds(panel: PanelModel, repeatedByRow?: boolean) {
panel.repeatPanelId = panel.id;
panel.id = this.getNextPanelId();
if (repeatedByRow) {
panel.repeatedByRow = true;
} else {
panel.repeat = undefined;
}
return panel;
}
getSelectedVariableOptions(variable: any) {
let selectedOptions: any[];
if (isAllVariable(variable)) {
selectedOptions = variable.options.slice(1, variable.options.length);
} else {
selectedOptions = filter(variable.options, { selected: true });
}
return selectedOptions;
}
getRowHeight(rowPanel: PanelModel): number {
if (!rowPanel.panels || rowPanel.panels.length === 0) {
return 0;
}
const rowYPos = rowPanel.gridPos.y;
const positions = map(rowPanel.panels, 'gridPos');
const maxPos = maxBy(positions, (pos: GridPos) => pos.y + pos.h);
return maxPos!.y + maxPos!.h - rowYPos;
}
removePanel(panel: PanelModel) {
this.panels = this.panels.filter((item) => item !== panel);
this.events.publish(new DashboardPanelsChangedEvent());
}
removeRow(row: PanelModel, removePanels: boolean) {
const needToggle = (!removePanels && row.collapsed) || (removePanels && !row.collapsed);
if (needToggle) {
this.toggleRow(row);
}
this.removePanel(row);
}
expandRows() {
const collapsedRows = this.panels.filter((p) => p.type === 'row' && p.collapsed);
for (const row of collapsedRows) {
this.toggleRow(row);
}
}
collapseRows() {
const collapsedRows = this.panels.filter((p) => p.type === 'row' && !p.collapsed);
for (const row of collapsedRows) {
this.toggleRow(row);
}
}
isSubMenuVisible() {
return (
this.links.length > 0 ||
this.getVariables().some((variable) => variable.hide !== 2) ||
this.annotations.list.some((annotation) => !annotation.hide)
);
}
getPanelInfoById(panelId: number) {
const panelIndex = this.panels.findIndex((p) => p.id === panelId);
return panelIndex >= 0 ? { panel: this.panels[panelIndex], index: panelIndex } : null;
}
duplicatePanel(panel: PanelModel) {
const newPanel = panel.getSaveModel();
newPanel.id = this.getNextPanelId();
delete newPanel.repeat;
delete newPanel.repeatIteration;
delete newPanel.repeatPanelId;
delete newPanel.scopedVars;
if (newPanel.alert) {
delete newPanel.thresholds;
}
delete newPanel.alert;
// does it fit to the right?
if (panel.gridPos.x + panel.gridPos.w * 2 <= GRID_COLUMN_COUNT) {
newPanel.gridPos.x += panel.gridPos.w;
} else {
// add below
newPanel.gridPos.y += panel.gridPos.h;
}
this.addPanel(newPanel);
return newPanel;
}
formatDate(date: DateTimeInput, format?: string) {
return dateTimeFormat(date, {
format,
timeZone: this.getTimezone(),
});
}
destroy() {
this.appEventsSubscription.unsubscribe();
this.events.removeAllListeners();
for (const panel of this.panels) {
panel.destroy();
}
}
toggleRow(row: PanelModel) {
const rowIndex = indexOf(this.panels, row);
if (!row.collapsed) {
const rowPanels = this.getRowPanels(rowIndex);
// remove panels
pull(this.panels, ...rowPanels);
// save panel models inside row panel
row.panels = rowPanels.map((panel: PanelModel) => panel.getSaveModel());
row.collapsed = true;
if (rowPanels.some((panel) => panel.hasChanged)) {
row.configRev++;
}
// emit change event
this.events.publish(new DashboardPanelsChangedEvent());
return;
}
row.collapsed = false;
const rowPanels = row.panels ?? [];
const hasRepeat = rowPanels.some((p: PanelModel) => p.repeat);
if (rowPanels.length > 0) {
// Use first panel to figure out if it was moved or pushed
// If the panel doesn't have gridPos.y, use the row gridPos.y instead.
// This can happen for some generated dashboards.
const firstPanelYPos = rowPanels[0].gridPos.y ?? row.gridPos.y;
const yDiff = firstPanelYPos - (row.gridPos.y + row.gridPos.h);
// start inserting after row
let insertPos = rowIndex + 1;
// y max will represent the bottom y pos after all panels have been added
// needed to know home much panels below should be pushed down
let yMax = row.gridPos.y;
for (const panel of rowPanels) {
// set the y gridPos if it wasn't already set
panel.gridPos.y ?? (panel.gridPos.y = row.gridPos.y); // (Safari 13.1 lacks ??= support)
// make sure y is adjusted (in case row moved while collapsed)
panel.gridPos.y -= yDiff;
// insert after row
this.panels.splice(insertPos, 0, new PanelModel(panel));
// update insert post and y max
insertPos += 1;
yMax = Math.max(yMax, panel.gridPos.y + panel.gridPos.h);
}
const pushDownAmount = yMax - row.gridPos.y - 1;
// push panels below down
for (const panel of this.panels.slice(insertPos)) {
panel.gridPos.y += pushDownAmount;
}
row.panels = [];
if (hasRepeat) {
this.processRowRepeats(row);
}
}
// sort panels
this.sortPanelsByGridPos();
// emit change event
this.events.publish(new DashboardPanelsChangedEvent());
}
/**
* Will return all panels after rowIndex until it encounters another row
*/
getRowPanels(rowIndex: number): PanelModel[] {
const panelsBelowRow = this.panels.slice(rowIndex + 1);
const nextRowIndex = panelsBelowRow.findIndex((p) => p.type === 'row');
// Take all panels up to next row, or all panels if there are no other rows
const rowPanels = panelsBelowRow.slice(0, nextRowIndex >= 0 ? nextRowIndex : this.panels.length);
return rowPanels;
}
/** @deprecated */
on<T>(event: AppEvent<T>, callback: (payload?: T) => void) {
console.log('DashboardModel.on is deprecated use events.subscribe');
this.events.on(event, callback);
}
/** @deprecated */
off<T>(event: AppEvent<T>, callback: (payload?: T) => void) {
console.log('DashboardModel.off is deprecated');
this.events.off(event, callback);
}
cycleGraphTooltip() {
this.graphTooltip = (this.graphTooltip + 1) % 3;
}
sharedTooltipModeEnabled() {
return this.graphTooltip > 0;
}
sharedCrosshairModeOnly() {
return this.graphTooltip === 1;
}
getRelativeTime(date: DateTimeInput) {
return dateTimeFormatTimeAgo(date, {
timeZone: this.getTimezone(),
});
}
isSnapshot() {
return this.snapshot !== undefined;
}
getTimezone(): TimeZone {
return (this.timezone ? this.timezone : contextSrv?.user?.timezone) as TimeZone;
}
private updateSchema(old: any) {
const migrator = new DashboardMigrator(this);
migrator.updateSchema(old);
}
resetOriginalTime() {
this.originalTime = cloneDeep(this.time);
}
hasTimeChanged() {
const { time, originalTime } = this;
// Compare moment values vs strings values
return !(
isEqual(time, originalTime) ||
(isEqual(dateTime(time?.from), dateTime(originalTime?.from)) &&
isEqual(dateTime(time?.to), dateTime(originalTime?.to)))
);
}
resetOriginalVariables(initial = false) {
if (initial) {
this.originalTemplating = this.cloneVariablesFrom(this.templating.list);
return;
}
this.originalTemplating = this.cloneVariablesFrom(this.getVariablesFromState(this.uid));
}
hasVariableValuesChanged() {
return this.hasVariablesChanged(this.originalTemplating, this.getVariablesFromState(this.uid));
}
autoFitPanels(viewHeight: number, kioskMode?: UrlQueryValue) {
const currentGridHeight = Math.max(...this.panels.map((panel) => panel.gridPos.h + panel.gridPos.y));
const navbarHeight = 55;
const margin = 20;
const submenuHeight = 50;
let visibleHeight = viewHeight - navbarHeight - margin;
// Remove submenu height if visible
if (this.meta.submenuEnabled && !kioskMode) {
visibleHeight -= submenuHeight;
}
// add back navbar height
if (kioskMode && kioskMode !== KioskMode.TV) {
visibleHeight += navbarHeight;
}
const visibleGridHeight = Math.floor(visibleHeight / (GRID_CELL_HEIGHT + GRID_CELL_VMARGIN));
const scaleFactor = currentGridHeight / visibleGridHeight;
for (const panel of this.panels) {
panel.gridPos.y = Math.round(panel.gridPos.y / scaleFactor) || 1;
panel.gridPos.h = Math.round(panel.gridPos.h / scaleFactor) || 1;
}
}
templateVariableValueUpdated() {
this.processRepeats();
this.events.emit(CoreEvents.templateVariableValueUpdated);
}
getPanelByUrlId(panelUrlId: string) {
const panelId = parseInt(panelUrlId ?? '0', 10);
// First try to find it in a collapsed row and exand it
const collapsedPanels = this.panels.filter((p) => p.collapsed);
for (const panel of collapsedPanels) {
const hasPanel = panel.panels?.some((rp: any) => rp.id === panelId);
hasPanel && this.toggleRow(panel);
}
return this.getPanelById(panelId);
}
toggleLegendsForAll() {
const panelsWithLegends = this.panels.filter(isPanelWithLegend);
// determine if more panels are displaying legends or not
const onCount = panelsWithLegends.filter((panel) => panel.legend.show).length;
const offCount = panelsWithLegends.length - onCount;
const panelLegendsOn = onCount >= offCount;
for (const panel of panelsWithLegends) {
panel.legend.show = !panelLegendsOn;
panel.render();
}
}
getVariables() {
return this.getVariablesFromState(this.uid);
}
canEditAnnotations(dashboardUID?: string) {
let canEdit = true;
// if RBAC is enabled there are additional conditions to check
if (contextSrv.accessControlEnabled()) {
// dashboardUID is falsy when it is an organizational annotation
if (!dashboardUID) {
canEdit = !!this.meta.annotationsPermissions?.organization.canEdit;
} else {
canEdit = !!this.meta.annotationsPermissions?.dashboard.canEdit;
}
}
return this.canEditDashboard() && canEdit;
}
canDeleteAnnotations(dashboardUID?: string) {
let canDelete = true;
if (contextSrv.accessControlEnabled()) {
// dashboardUID is falsy when it is an organizational annotation
if (!dashboardUID) {
canDelete = !!this.meta.annotationsPermissions?.organization.canDelete;
} else {
canDelete = !!this.meta.annotationsPermissions?.dashboard.canDelete;
}
}
return canDelete && this.canEditDashboard();
}
canAddAnnotations() {
// When the builtin annotations are disabled, we should not add any in the UI
const found = this.annotations.list.find((item) => item.builtIn === 1);
if (found?.enable === false || !this.canEditDashboard()) {
return false;
}
// If RBAC is enabled there are additional conditions to check.
return !contextSrv.accessControlEnabled() || Boolean(this.meta.annotationsPermissions?.dashboard.canAdd);
}
canEditDashboard() {
return Boolean(this.meta.canEdit || this.meta.canMakeEditable);
}
shouldUpdateDashboardPanelFromJSON(updatedPanel: PanelModel, panel: PanelModel) {
const shouldUpdateGridPositionLayout = !isEqual(updatedPanel?.gridPos, panel?.gridPos);
if (shouldUpdateGridPositionLayout) {
this.events.publish(new DashboardPanelsChangedEvent());
}
}
getDefaultTime() {
return this.originalTime;
}
private getPanelRepeatVariable(panel: PanelModel) {
return this.getVariablesFromState(this.uid).find((variable) => variable.name === panel.repeat);
}
private isSnapshotTruthy() {
return this.snapshot;
}
private hasVariables() {
return this.getVariablesFromState(this.uid).length > 0;
}
private hasVariablesChanged(originalVariables: any[], currentVariables: any[]): boolean {
if (originalVariables.length !== currentVariables.length) {
return false;
}
const updated = currentVariables.map((variable: any) => ({
name: variable.name,
type: variable.type,
current: cloneDeep(variable.current),
filters: cloneDeep(variable.filters),
}));
return !isEqual(updated, originalVariables);
}
private cloneVariablesFrom(variables: any[]): any[] {
return variables.map((variable) => ({
name: variable.name,
type: variable.type,
current: cloneDeep(variable.current),
filters: cloneDeep(variable.filters),
}));
}
private variablesTimeRangeProcessDoneHandler(event: VariablesTimeRangeProcessDone) {
const processRepeats = event.payload.variableIds.length > 0;
this.variablesChangedHandler(new VariablesChanged({ panelIds: [], refreshAll: true }), processRepeats);
}
private variablesChangedHandler(event: VariablesChanged, processRepeats = true) {
if (processRepeats) {
this.processRepeats();
}
if (event.payload.refreshAll || getTimeSrv().isRefreshOutsideThreshold(this.lastRefresh)) {
this.startRefresh({ refreshAll: true, panelIds: [] });
return;
}
if (this.panelInEdit || this.panelInView) {
this.panelsAffectedByVariableChange = event.payload.panelIds.filter(
(id) => id !== (this.panelInEdit?.id ?? this.panelInView?.id)
);
}
this.startRefresh(event.payload);
}
private variablesChangedInUrlHandler(event: VariablesChangedInUrl) {
this.templateVariableValueUpdated();
this.startRefresh(event.payload);
}
}
function isPanelWithLegend(panel: PanelModel): panel is PanelModel & Pick<Required<PanelModel>, 'legend'> {
return Boolean(panel.legend);
}
| public/app/features/dashboard/state/DashboardModel.ts | 1 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.00029811388230882585,
0.0001700951106613502,
0.00015926413470879197,
0.00016956047329586,
0.000012003323718090542
]
|
{
"id": 0,
"code_window": [
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"25\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"26\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"27\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"28\"],\n",
" [0, 0, 0, \"Do not use any type assertions.\", \"29\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"30\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"31\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"32\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"33\"],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" [0, 0, 0, \"Do not use any type assertions.\", \"28\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"29\"],\n"
],
"file_path": ".betterer.results",
"type": "replace",
"edit_start_line_idx": 1000
} | //
// Tooltips
// --------------------------------------------------
// Base class
.tooltip {
position: absolute;
z-index: $zindex-tooltip;
display: block;
visibility: visible;
line-height: 1.4;
font-weight: $font-weight-semi-bold;
@include opacity(0);
&.in {
@include opacity(100);
}
&.top {
margin-top: -3px;
padding: 5px 0;
}
&.right {
margin-left: 3px;
padding: 0 5px;
}
&.bottom {
margin-top: 3px;
padding: 5px 0;
}
&.left {
margin-left: -3px;
padding: 0 5px;
}
}
// Wrapper for the tooltip content
.tooltip-inner {
max-width: 400px;
padding: 8px 16px;
padding: 4px 8px;
color: $tooltipColor;
text-align: center;
text-decoration: none;
background-color: $tooltipBackground;
border-radius: 2px;
}
// Arrows
.tooltip-arrow {
position: absolute;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
}
.tooltip {
&.top .tooltip-arrow {
bottom: 0;
left: 50%;
margin-left: -$tooltipArrowWidth;
border-width: $tooltipArrowWidth $tooltipArrowWidth 0;
border-top-color: $tooltipArrowColor;
}
&.right .tooltip-arrow {
top: 50%;
left: 0;
margin-top: -$tooltipArrowWidth;
border-width: $tooltipArrowWidth $tooltipArrowWidth $tooltipArrowWidth 0;
border-right-color: $tooltipArrowColor;
}
&.left .tooltip-arrow {
top: 50%;
right: 0;
margin-top: -$tooltipArrowWidth;
border-width: $tooltipArrowWidth 0 $tooltipArrowWidth $tooltipArrowWidth;
border-left-color: $tooltipArrowColor;
}
&.bottom .tooltip-arrow {
top: 0;
left: 50%;
margin-left: -$tooltipArrowWidth;
border-width: 0 $tooltipArrowWidth $tooltipArrowWidth;
border-bottom-color: $tooltipArrowColor;
}
}
.grafana-tooltip {
position: absolute;
top: -1000;
left: 0;
color: $tooltipColor;
padding: 10px;
font-size: 11pt;
font-weight: 200;
background-color: $tooltipBackground;
border-radius: 5px;
z-index: 9999;
max-width: 800px;
max-height: 600px;
overflow: hidden;
line-height: 14px;
a {
color: $tooltipLinkColor;
}
a.external-link {
color: $tooltipExternalLinkColor;
}
}
.grafana-tip {
padding-left: 5px;
}
| public/sass/components/_tooltip.scss | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.00017635458789300174,
0.0001720619766274467,
0.00016247251187451184,
0.00017238834698218852,
0.0000030724966109119123
]
|
{
"id": 0,
"code_window": [
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"25\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"26\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"27\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"28\"],\n",
" [0, 0, 0, \"Do not use any type assertions.\", \"29\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"30\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"31\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"32\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"33\"],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" [0, 0, 0, \"Do not use any type assertions.\", \"28\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"29\"],\n"
],
"file_path": ".betterer.results",
"type": "replace",
"edit_start_line_idx": 1000
} | // Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed 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 { css } from '@emotion/css';
import cx from 'classnames';
import * as React from 'react';
import { GrafanaTheme2 } from '@grafana/data';
import { useStyles2 } from '@grafana/ui';
import { autoColor } from '../Theme';
import { TNil } from '../types';
import { formatDuration } from './utils';
const getStyles = (theme: GrafanaTheme2) => {
return {
Ticks: css`
label: Ticks;
pointer-events: none;
`,
TicksTick: css`
label: TicksTick;
position: absolute;
height: 100%;
width: 1px;
background: ${autoColor(theme, '#d8d8d8')};
&:last-child {
width: 0;
}
`,
TicksTickLabel: css`
label: TicksTickLabel;
left: 0.25rem;
position: absolute;
`,
TicksTickLabelEndAnchor: css`
label: TicksTickLabelEndAnchor;
left: initial;
right: 0.25rem;
`,
};
};
type TicksProps = {
endTime?: number | TNil;
numTicks: number;
showLabels?: boolean | TNil;
startTime?: number | TNil;
};
export default function Ticks(props: TicksProps) {
const { endTime, numTicks, showLabels, startTime } = props;
let labels: undefined | string[];
if (showLabels) {
labels = [];
const viewingDuration = (endTime || 0) - (startTime || 0);
for (let i = 0; i < numTicks; i++) {
const durationAtTick = (startTime || 0) + (i / (numTicks - 1)) * viewingDuration;
labels.push(formatDuration(durationAtTick));
}
}
const styles = useStyles2(getStyles);
const ticks: React.ReactNode[] = [];
for (let i = 0; i < numTicks; i++) {
const portion = i / (numTicks - 1);
ticks.push(
<div
data-testid="TicksID"
key={portion}
className={styles.TicksTick}
style={{
left: `${portion * 100}%`,
}}
>
{labels && (
<span className={cx(styles.TicksTickLabel, { [styles.TicksTickLabelEndAnchor]: portion >= 1 })}>
{labels[i]}
</span>
)}
</div>
);
}
return <div className={styles.Ticks}>{ticks}</div>;
}
Ticks.defaultProps = {
endTime: null,
showLabels: null,
startTime: null,
};
| packages/jaeger-ui-components/src/TraceTimelineViewer/Ticks.tsx | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.00017712489352561533,
0.00017226715863216668,
0.00016573096218053252,
0.0001737530983518809,
0.0000035466587178234477
]
|
{
"id": 0,
"code_window": [
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"25\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"26\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"27\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"28\"],\n",
" [0, 0, 0, \"Do not use any type assertions.\", \"29\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"30\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"31\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"32\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"33\"],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" [0, 0, 0, \"Do not use any type assertions.\", \"28\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"29\"],\n"
],
"file_path": ".betterer.results",
"type": "replace",
"edit_start_line_idx": 1000
} | import { RefObject, useEffect, useState } from 'react';
import { useEffectOnce } from 'react-use';
const modulo = (a: number, n: number) => ((a % n) + n) % n;
const UNFOCUSED = -1;
/** @internal */
export interface UseMenuFocusProps {
localRef: RefObject<HTMLDivElement>;
isMenuOpen?: boolean;
openedWithArrow?: boolean;
setOpenedWithArrow?: (openedWithArrow: boolean) => void;
close?: () => void;
onOpen?: (focusOnItem: (itemId: number) => void) => void;
onClose?: () => void;
onKeyDown?: React.KeyboardEventHandler;
}
/** @internal */
export type UseMenuFocusReturn = [(event: React.KeyboardEvent) => void, () => void];
/** @internal */
export const useMenuFocus = ({
localRef,
isMenuOpen,
openedWithArrow,
setOpenedWithArrow,
close,
onOpen,
onClose,
onKeyDown,
}: UseMenuFocusProps): UseMenuFocusReturn => {
const [focusedItem, setFocusedItem] = useState(UNFOCUSED);
useEffect(() => {
if (isMenuOpen && openedWithArrow) {
setFocusedItem(0);
setOpenedWithArrow?.(false);
}
}, [isMenuOpen, openedWithArrow, setOpenedWithArrow]);
useEffect(() => {
const menuItems = localRef?.current?.querySelectorAll<HTMLElement | HTMLButtonElement | HTMLAnchorElement>(
'[data-role="menuitem"]:not([data-disabled])'
);
menuItems?.[focusedItem]?.focus();
menuItems?.forEach((menuItem, i) => {
menuItem.tabIndex = i === focusedItem ? 0 : -1;
});
}, [localRef, focusedItem]);
useEffectOnce(() => {
const firstMenuItem = localRef?.current?.querySelector<HTMLElement | HTMLButtonElement | HTMLAnchorElement>(
'[data-role="menuitem"]:not([data-disabled])'
);
if (firstMenuItem) {
firstMenuItem.tabIndex = 0;
}
onOpen?.(setFocusedItem);
});
const handleKeys = (event: React.KeyboardEvent) => {
const menuItems = localRef?.current?.querySelectorAll<HTMLElement | HTMLButtonElement | HTMLAnchorElement>(
'[data-role="menuitem"]:not([data-disabled])'
);
const menuItemsCount = menuItems?.length ?? 0;
switch (event.key) {
case 'ArrowUp':
event.preventDefault();
event.stopPropagation();
setFocusedItem(modulo(focusedItem - 1, menuItemsCount));
break;
case 'ArrowDown':
event.preventDefault();
event.stopPropagation();
setFocusedItem(modulo(focusedItem + 1, menuItemsCount));
break;
case 'ArrowLeft':
event.preventDefault();
event.stopPropagation();
setFocusedItem(UNFOCUSED);
close?.();
break;
case 'Home':
event.preventDefault();
event.stopPropagation();
setFocusedItem(0);
break;
case 'End':
event.preventDefault();
event.stopPropagation();
setFocusedItem(menuItemsCount - 1);
break;
case 'Enter':
event.preventDefault();
event.stopPropagation();
menuItems?.[focusedItem]?.click();
break;
case 'Escape':
onClose?.();
break;
case 'Tab':
event.preventDefault();
onClose?.();
break;
default:
break;
}
// Forward event to parent
onKeyDown?.(event);
};
const handleFocus = () => {
if (focusedItem === UNFOCUSED) {
setFocusedItem(0);
}
};
return [handleKeys, handleFocus];
};
| packages/grafana-ui/src/components/Menu/hooks.ts | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.000174323286046274,
0.0001712611992843449,
0.00016517910989932716,
0.0001720474538160488,
0.0000025575566269253613
]
|
{
"id": 1,
"code_window": [
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"32\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"33\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"34\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"35\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"36\"]\n",
" ],\n",
" \"public/app/features/dashboard/state/PanelModel.test.ts:5381\": [\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"0\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"1\"],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"35\"]\n"
],
"file_path": ".betterer.results",
"type": "replace",
"edit_start_line_idx": 1007
} | package kind
import "strings"
name: "Dashboard"
maturity: "experimental"
lineage: seqs: [
{
schemas: [
// 0.0
{
@grafana(TSVeneer="type")
// Unique numeric identifier for the dashboard.
// TODO must isolate or remove identifiers local to a Grafana instance...?
id?: int64
// Unique dashboard identifier that can be generated by anyone. string (8-40)
uid?: string
// Title of dashboard.
title?: string
// Description of dashboard.
description?: string
// Version of the current dashboard data
revision: int64 | *-1 @grafanamaturity(NeedsExpertReview)
gnetId?: string @grafanamaturity(NeedsExpertReview)
// Tags associated with dashboard.
tags?: [...string] @grafanamaturity(NeedsExpertReview)
// Theme of dashboard.
style: "light" | *"dark" @grafanamaturity(NeedsExpertReview)
// Timezone of dashboard,
timezone?: *"browser" | "utc" | "" @grafanamaturity(NeedsExpertReview)
// Whether a dashboard is editable or not.
editable: bool | *true
// Configuration of dashboard cursor sync behavior.
graphTooltip: #DashboardCursorSync
// Time range for dashboard, e.g. last 6 hours, last 7 days, etc
time?: {
from: string | *"now-6h"
to: string | *"now"
} @grafanamaturity(NeedsExpertReview)
// TODO docs
// TODO this appears to be spread all over in the frontend. Concepts will likely need tidying in tandem with schema changes
timepicker?: {
// Whether timepicker is collapsed or not.
collapse: bool | *false
// Whether timepicker is enabled or not.
enable: bool | *true
// Whether timepicker is visible or not.
hidden: bool | *false
// Selectable intervals for auto-refresh.
refresh_intervals: [...string] | *["5s", "10s", "30s", "1m", "5m", "15m", "30m", "1h", "2h", "1d"]
// TODO docs
time_options: [...string] | *["5m", "15m", "1h", "6h", "12h", "24h", "2d", "7d", "30d"]
} @grafanamaturity(NeedsExpertReview)
// The month that the fiscal year starts on. 0 = January, 11 = December
fiscalYearStartMonth?: uint8 & <12 | *0
// TODO docs
liveNow?: bool @grafanamaturity(NeedsExpertReview)
// TODO docs
weekStart?: string @grafanamaturity(NeedsExpertReview)
// TODO docs
refresh?: string | false @grafanamaturity(NeedsExpertReview)
// Version of the JSON schema, incremented each time a Grafana update brings
// changes to said schema.
// TODO this is the existing schema numbering system. It will be replaced by Thema's themaVersion
schemaVersion: uint16 | *36
// Version of the dashboard, incremented each time the dashboard is updated.
version?: uint32 @grafanamaturity(NeedsExpertReview)
panels?: [...(#Panel | #RowPanel | #GraphPanel | #HeatmapPanel)] @grafanamaturity(NeedsExpertReview)
// TODO docs
templating?: {
list?: [...#VariableModel] @grafanamaturity(NeedsExpertReview)
}
// TODO docs
annotations?: {
list?: [...#AnnotationQuery] @grafanamaturity(NeedsExpertReview)
}
// TODO docs
links?: [...#DashboardLink] @grafanamaturity(NeedsExpertReview)
snapshot?: #Snapshot @grafanamaturity(NeedsExpertReview)
///////////////////////////////////////
// Definitions (referenced above) are declared below
// TODO docs
#AnnotationTarget: {
limit: int64
matchAny: bool
tags: [...string]
type: string
} @cuetsy(kind="interface") @grafanamaturity(NeedsExpertReview)
// TODO docs
// FROM: AnnotationQuery in grafana-data/src/types/annotations.ts
#AnnotationQuery: {
// Datasource to use for annotation.
datasource: {
type?: string
uid?: string
} @grafanamaturity(NeedsExpertReview)
// Whether annotation is enabled.
enable: bool | *true @grafanamaturity(NeedsExpertReview)
// Name of annotation.
name?: string @grafanamaturity(NeedsExpertReview)
builtIn: uint8 | *0 @grafanamaturity(NeedsExpertReview) // TODO should this be persisted at all?
// Whether to hide annotation.
hide?: bool | *false @grafanamaturity(NeedsExpertReview)
// Annotation icon color.
iconColor?: string @grafanamaturity(NeedsExpertReview)
type: string | *"dashboard" @grafanamaturity(NeedsExpertReview)
// Query for annotation data.
rawQuery?: string @grafanamaturity(NeedsExpertReview)
showIn: uint8 | *0 @grafanamaturity(NeedsExpertReview)
target?: #AnnotationTarget @grafanamaturity(NeedsExpertReview)
} @cuetsy(kind="interface")
// FROM: packages/grafana-data/src/types/templateVars.ts
// TODO docs
// TODO what about what's in public/app/features/types.ts?
// TODO there appear to be a lot of different kinds of [template] vars here? if so need a disjunction
#VariableModel: {
id: string | *"00000000-0000-0000-0000-000000000000"
type: #VariableType
name: string
label?: string
rootStateKey?: string
global: bool | *false
hide: #VariableHide
skipUrlSync: bool | *false
index: int32 | *-1
state: #LoadingState
error?: {...}
description?: string
// TODO: Move this into a separated QueryVariableModel type
query?: string | {...}
datasource?: #DataSourceRef
...
} @cuetsy(kind="interface") @grafana(TSVeneer="type") @grafanamaturity(NeedsExpertReview)
#VariableHide: 0 | 1 | 2 @cuetsy(kind="enum",memberNames="dontHide|hideLabel|hideVariable") @grafana(TSVeneer="type") @grafanamaturity(NeedsExpertReview)
#LoadingState: "NotStarted" | "Loading" | "Streaming" | "Done" | "Error" @cuetsy(kind="enum") @grafanamaturity(NeedsExpertReview)
// Ref to a DataSource instance
#DataSourceRef: {
// The plugin type-id
type?: string @grafanamaturity(NeedsExpertReview)
// Specific datasource instance
uid?: string @grafanamaturity(NeedsExpertReview)
} @cuetsy(kind="interface") @grafana(TSVeneer="type") @grafanamaturity(NeedsExpertReview)
// FROM public/app/features/dashboard/state/DashboardModels.ts - ish
// TODO docs
#DashboardLink: {
title: string @grafanamaturity(NeedsExpertReview)
type: #DashboardLinkType @grafanamaturity(NeedsExpertReview)
icon: string @grafanamaturity(NeedsExpertReview)
tooltip: string @grafanamaturity(NeedsExpertReview)
url: string @grafanamaturity(NeedsExpertReview)
tags: [...string] @grafanamaturity(NeedsExpertReview)
asDropdown: bool | *false @grafanamaturity(NeedsExpertReview)
targetBlank: bool | *false @grafanamaturity(NeedsExpertReview)
includeVars: bool | *false @grafanamaturity(NeedsExpertReview)
keepTime: bool | *false @grafanamaturity(NeedsExpertReview)
} @cuetsy(kind="interface")
// TODO docs
#DashboardLinkType: "link" | "dashboards" @cuetsy(kind="type") @grafanamaturity(NeedsExpertReview)
// FROM: packages/grafana-data/src/types/templateVars.ts
// TODO docs
// TODO this implies some wider pattern/discriminated union, probably?
#VariableType: "query" | "adhoc" | "constant" | "datasource" | "interval" | "textbox" | "custom" | "system" @cuetsy(kind="type") @grafanamaturity(NeedsExpertReview)
// TODO docs
#FieldColorModeId: "thresholds" | "palette-classic" | "palette-saturated" | "continuous-GrYlRd" | "fixed" @cuetsy(kind="enum",memberNames="Thresholds|PaletteClassic|PaletteSaturated|ContinuousGrYlRd|Fixed") @grafanamaturity(NeedsExpertReview)
// TODO docs
#FieldColorSeriesByMode: "min" | "max" | "last" @cuetsy(kind="type") @grafanamaturity(NeedsExpertReview)
// TODO docs
#FieldColor: {
// The main color scheme mode
mode: #FieldColorModeId | string
// Stores the fixed color value if mode is fixed
fixedColor?: string
// Some visualizations need to know how to assign a series color from by value color schemes
seriesBy?: #FieldColorSeriesByMode
} @cuetsy(kind="interface") @grafanamaturity(NeedsExpertReview)
#GridPos: {
// Panel
h: uint32 & >0 | *9 @grafanamaturity(NeedsExpertReview)
// Panel
w: uint32 & >0 & <=24 | *12 @grafanamaturity(NeedsExpertReview)
// Panel x
x: uint32 & >=0 & <24 | *0 @grafanamaturity(NeedsExpertReview)
// Panel y
y: uint32 & >=0 | *0 @grafanamaturity(NeedsExpertReview)
// true if fixed
static?: bool @grafanamaturity(NeedsExpertReview)
} @cuetsy(kind="interface")
// TODO docs
#Threshold: {
// TODO docs
// FIXME the corresponding typescript field is required/non-optional, but nulls currently appear here when serializing -Infinity to JSON
value?: number @grafanamaturity(NeedsExpertReview)
// TODO docs
color: string @grafanamaturity(NeedsExpertReview)
// TODO docs
// TODO are the values here enumerable into a disjunction?
// Some seem to be listed in typescript comment
state?: string @grafanamaturity(NeedsExpertReview)
} @cuetsy(kind="interface") @grafanamaturity(NeedsExpertReview)
#ThresholdsMode: "absolute" | "percentage" @cuetsy(kind="enum") @grafanamaturity(NeedsExpertReview)
#ThresholdsConfig: {
mode: #ThresholdsMode @grafanamaturity(NeedsExpertReview)
// Must be sorted by 'value', first value is always -Infinity
steps: [...#Threshold] @grafanamaturity(NeedsExpertReview)
} @cuetsy(kind="interface") @grafanamaturity(NeedsExpertReview)
// TODO docs
#ValueMapping: #ValueMap | #RangeMap | #RegexMap | #SpecialValueMap @cuetsy(kind="type") @grafanamaturity(NeedsExpertReview)
// TODO docs
#MappingType: "value" | "range" | "regex" | "special" @cuetsy(kind="enum",memberNames="ValueToText|RangeToText|RegexToText|SpecialValue") @grafanamaturity(NeedsExpertReview)
// TODO docs
#ValueMap: {
type: #MappingType & "value"
options: [string]: #ValueMappingResult
} @cuetsy(kind="interface")
// TODO docs
#RangeMap: {
type: #MappingType & "range"
options: {
// to and from are `number | null` in current ts, really not sure what to do
from: float64 @grafanamaturity(NeedsExpertReview)
to: float64 @grafanamaturity(NeedsExpertReview)
result: #ValueMappingResult
}
} @cuetsy(kind="interface") @grafanamaturity(NeedsExpertReview)
// TODO docs
#RegexMap: {
type: #MappingType & "regex"
options: {
pattern: string
result: #ValueMappingResult
}
} @cuetsy(kind="interface") @grafanamaturity(NeedsExpertReview)
// TODO docs
#SpecialValueMap: {
type: #MappingType & "special"
options: {
match: "true" | "false"
pattern: string
result: #ValueMappingResult
}
} @cuetsy(kind="interface") @grafanamaturity(NeedsExpertReview)
// TODO docs
#SpecialValueMatch: "true" | "false" | "null" | "nan" | "null+nan" | "empty" @cuetsy(kind="enum",memberNames="True|False|Null|NaN|NullAndNan|Empty")
// TODO docs
#ValueMappingResult: {
text?: string
color?: string
icon?: string
index?: int32
} @cuetsy(kind="interface")
// TODO docs
// FIXME this is extremely underspecfied; wasn't obvious which typescript types corresponded to it
#Transformation: {
id: string
options: {...}
} @cuetsy(kind="interface") @grafanamaturity(NeedsExpertReview)
// 0 for no shared crosshair or tooltip (default).
// 1 for shared crosshair.
// 2 for shared crosshair AND shared tooltip.
#DashboardCursorSync: *0 | 1 | 2 @cuetsy(kind="enum",memberNames="Off|Crosshair|Tooltip")
// Schema for panel targets is specified by datasource
// plugins. We use a placeholder definition, which the Go
// schema loader either left open/as-is with the Base
// variant of the Dashboard and Panel families, or filled
// with types derived from plugins in the Instance variant.
// When working directly from CUE, importers can extend this
// type directly to achieve the same effect.
#Target: {...} @grafanamaturity(NeedsExpertReview)
// TODO docs
#Snapshot: {
// TODO docs
created: string @grafanamaturity(NeedsExpertReview)
// TODO docs
expires: string @grafanamaturity(NeedsExpertReview)
// TODO docs
external: bool @grafanamaturity(NeedsExpertReview)
// TODO docs
externalUrl: string @grafanamaturity(NeedsExpertReview)
// TODO docs
id: uint32 @grafanamaturity(NeedsExpertReview)
// TODO docs
key: string @grafanamaturity(NeedsExpertReview)
// TODO docs
name: string @grafanamaturity(NeedsExpertReview)
// TODO docs
orgId: uint32 @grafanamaturity(NeedsExpertReview)
// TODO docs
updated: string @grafanamaturity(NeedsExpertReview)
// TODO docs
url?: string @grafanamaturity(NeedsExpertReview)
// TODO docs
userId: uint32 @grafanamaturity(NeedsExpertReview)
} @grafanamaturity(NeedsExpertReview)
// Dashboard panels. Panels are canonically defined inline
// because they share a version timeline with the dashboard
// schema; they do not evolve independently.
#Panel: {
// The panel plugin type id. May not be empty.
type: string & strings.MinRunes(1) @grafanamaturity(NeedsExpertReview)
// TODO docs
id?: uint32 @grafanamaturity(NeedsExpertReview)
// FIXME this almost certainly has to be changed in favor of scuemata versions
pluginVersion?: string @grafanamaturity(NeedsExpertReview)
// TODO docs
tags?: [...string] @grafanamaturity(NeedsExpertReview)
// TODO docs
targets?: [...#Target] @grafanamaturity(NeedsExpertReview)
// Panel title.
title?: string @grafanamaturity(NeedsExpertReview)
// Description.
description?: string @grafanamaturity(NeedsExpertReview)
// Whether to display the panel without a background.
transparent: bool | *false @grafanamaturity(NeedsExpertReview)
// The datasource used in all targets.
datasource?: {
type?: string
uid?: string
} @grafanamaturity(NeedsExpertReview)
// Grid position.
gridPos?: #GridPos
// Panel links.
// TODO fill this out - seems there are a couple variants?
links?: [...#DashboardLink] @grafanamaturity(NeedsExpertReview)
// Name of template variable to repeat for.
repeat?: string @grafanamaturity(NeedsExpertReview)
// Direction to repeat in if 'repeat' is set.
// "h" for horizontal, "v" for vertical.
// TODO this is probably optional
repeatDirection: *"h" | "v" @grafanamaturity(NeedsExpertReview)
// Id of the repeating panel.
repeatPanelId?: int64 @grafanamaturity(NeedsExpertReview)
// TODO docs
maxDataPoints?: number @grafanamaturity(NeedsExpertReview)
// TODO docs - seems to be an old field from old dashboard alerts?
thresholds?: [...] @grafanamaturity(NeedsExpertReview)
// TODO docs
timeRegions?: [...] @grafanamaturity(NeedsExpertReview)
transformations: [...#Transformation] @grafanamaturity(NeedsExpertReview)
// TODO docs
// TODO tighter constraint
interval?: string @grafanamaturity(NeedsExpertReview)
// TODO docs
// TODO tighter constraint
timeFrom?: string @grafanamaturity(NeedsExpertReview)
// TODO docs
// TODO tighter constraint
timeShift?: string @grafanamaturity(NeedsExpertReview)
// options is specified by the PanelOptions field in panel
// plugin schemas.
options: {...} @grafanamaturity(NeedsExpertReview)
fieldConfig: #FieldConfigSource
} @cuetsy(kind="interface") @grafana(TSVeneer="type") @grafanamaturity(NeedsExpertReview)
#FieldConfigSource: {
defaults: #FieldConfig
overrides: [...{
matcher: #MatcherConfig
properties: [...#DynamicConfigValue]
}] @grafanamaturity(NeedsExpertReview)
} @cuetsy(kind="interface") @grafana(TSVeneer="type") @grafanamaturity(NeedsExpertReview)
#MatcherConfig: {
id: string | *"" @grafanamaturity(NeedsExpertReview)
options?: _ @grafanamaturity(NeedsExpertReview)
} @cuetsy(kind="interface") @grafana(TSVeneer="type")
#DynamicConfigValue: {
id: string | *"" @grafanamaturity(NeedsExpertReview)
value?: _ @grafanamaturity(NeedsExpertReview)
}
#FieldConfig: {
// The display value for this field. This supports template variables blank is auto
displayName?: string @grafanamaturity(NeedsExpertReview)
// This can be used by data sources that return and explicit naming structure for values and labels
// When this property is configured, this value is used rather than the default naming strategy.
displayNameFromDS?: string @grafanamaturity(NeedsExpertReview)
// Human readable field metadata
description?: string @grafanamaturity(NeedsExpertReview)
// An explicit path to the field in the datasource. When the frame meta includes a path,
// This will default to `${frame.meta.path}/${field.name}
//
// When defined, this value can be used as an identifier within the datasource scope, and
// may be used to update the results
path?: string @grafanamaturity(NeedsExpertReview)
// True if data source can write a value to the path. Auth/authz are supported separately
writeable?: bool @grafanamaturity(NeedsExpertReview)
// True if data source field supports ad-hoc filters
filterable?: bool @grafanamaturity(NeedsExpertReview)
// Numeric Options
unit?: string @grafanamaturity(NeedsExpertReview)
// Significant digits (for display)
decimals?: number @grafanamaturity(NeedsExpertReview)
min?: number @grafanamaturity(NeedsExpertReview)
max?: number @grafanamaturity(NeedsExpertReview)
// Convert input values into a display string
mappings?: [...#ValueMapping] @grafanamaturity(NeedsExpertReview)
// Map numeric values to states
thresholds?: #ThresholdsConfig @grafanamaturity(NeedsExpertReview)
// Map values to a display color
color?: #FieldColor @grafanamaturity(NeedsExpertReview)
// Used when reducing field values
// nullValueMode?: NullValueMode
// The behavior when clicking on a result
links?: [...] @grafanamaturity(NeedsExpertReview)
// Alternative to empty string
noValue?: string @grafanamaturity(NeedsExpertReview)
// custom is specified by the PanelFieldConfig field
// in panel plugin schemas.
custom?: {...} @grafanamaturity(NeedsExpertReview)
} @cuetsy(kind="interface") @grafana(TSVeneer="type") @grafanamaturity(NeedsExpertReview)
// Row panel
#RowPanel: {
type: "row" @grafanamaturity(NeedsExpertReview)
collapsed: bool | *false @grafanamaturity(NeedsExpertReview)
title?: string @grafanamaturity(NeedsExpertReview)
// Name of default datasource.
datasource?: {
type?: string @grafanamaturity(NeedsExpertReview)
uid?: string @grafanamaturity(NeedsExpertReview)
} @grafanamaturity(NeedsExpertReview)
gridPos?: #GridPos
id: uint32 @grafanamaturity(NeedsExpertReview)
panels: [...(#Panel | #GraphPanel | #HeatmapPanel)] @grafanamaturity(NeedsExpertReview)
// Name of template variable to repeat for.
repeat?: string @grafanamaturity(NeedsExpertReview)
} @cuetsy(kind="interface") @grafanamaturity(NeedsExpertReview)
// Support for legacy graph and heatmap panels.
#GraphPanel: {
type: "graph" @grafanamaturity(NeedsExpertReview)
// @deprecated this is part of deprecated graph panel
legend?: {
show: bool | *true
sort?: string
sortDesc?: bool
}
...
} @cuetsy(kind="interface") @grafanamaturity(NeedsExpertReview)
#HeatmapPanel: {
type: "heatmap" @grafanamaturity(NeedsExpertReview)
...
} @cuetsy(kind="interface") @grafanamaturity(NeedsExpertReview)
},
]
},
]
| kinds/dashboard/dashboard_kind.cue | 1 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.0002258317545056343,
0.00017463747644796968,
0.00016572466120123863,
0.0001735400001052767,
0.000010370910786150489
]
|
{
"id": 1,
"code_window": [
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"32\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"33\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"34\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"35\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"36\"]\n",
" ],\n",
" \"public/app/features/dashboard/state/PanelModel.test.ts:5381\": [\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"0\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"1\"],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"35\"]\n"
],
"file_path": ".betterer.results",
"type": "replace",
"edit_start_line_idx": 1007
} | import config from '../../core/config';
// accessControlQueryParam adds an additional accesscontrol=true param to params when accesscontrol is enabled
export function accessControlQueryParam(params = {}) {
if (!config.rbacEnabled) {
return params;
}
return { ...params, accesscontrol: true };
}
| public/app/core/utils/accessControl.ts | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.00016959046479314566,
0.00016959046479314566,
0.00016959046479314566,
0.00016959046479314566,
0
]
|
{
"id": 1,
"code_window": [
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"32\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"33\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"34\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"35\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"36\"]\n",
" ],\n",
" \"public/app/features/dashboard/state/PanelModel.test.ts:5381\": [\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"0\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"1\"],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"35\"]\n"
],
"file_path": ".betterer.results",
"type": "replace",
"edit_start_line_idx": 1007
} | import { reducerTester } from '../../../../test/core/redux/reducerTester';
import { OrgRole, TeamPermissionLevel } from '../../../types';
import { getMockTeam } from '../../teams/__mocks__/teamMocks';
import {
initialUserState,
orgsLoaded,
sessionsLoaded,
setUpdating,
teamsLoaded,
updateTimeZone,
updateWeekStart,
userLoaded,
userReducer,
userSessionRevoked,
UserState,
} from './reducers';
describe('userReducer', () => {
let dateNow: any;
beforeAll(() => {
dateNow = jest.spyOn(Date, 'now').mockImplementation(() => 1609470000000); // 2021-01-01 04:00:00
});
afterAll(() => {
dateNow.mockRestore();
});
describe('when updateTimeZone is dispatched', () => {
it('then state should be correct', () => {
reducerTester<UserState>()
.givenReducer(userReducer, { ...initialUserState })
.whenActionIsDispatched(updateTimeZone({ timeZone: 'xyz' }))
.thenStateShouldEqual({ ...initialUserState, timeZone: 'xyz' });
});
});
describe('when updateWeekStart is dispatched', () => {
it('then state should be correct', () => {
reducerTester<UserState>()
.givenReducer(userReducer, { ...initialUserState })
.whenActionIsDispatched(updateWeekStart({ weekStart: 'xyz' }))
.thenStateShouldEqual({ ...initialUserState, weekStart: 'xyz' });
});
});
describe('when setUpdating is dispatched', () => {
it('then state should be correct', () => {
reducerTester<UserState>()
.givenReducer(userReducer, { ...initialUserState, isUpdating: false })
.whenActionIsDispatched(setUpdating({ updating: true }))
.thenStateShouldEqual({ ...initialUserState, isUpdating: true });
});
});
describe('when userLoaded is dispatched', () => {
it('then state should be correct', () => {
reducerTester<UserState>()
.givenReducer(userReducer, { ...initialUserState, user: null })
.whenActionIsDispatched(
userLoaded({
user: {
id: 2021,
email: '[email protected]',
isDisabled: true,
login: 'test',
name: 'Test Account',
isGrafanaAdmin: false,
},
})
)
.thenStateShouldEqual({
...initialUserState,
user: {
id: 2021,
email: '[email protected]',
isDisabled: true,
login: 'test',
name: 'Test Account',
isGrafanaAdmin: false,
},
});
});
});
describe('when teamsLoaded is dispatched', () => {
it('then state should be correct', () => {
reducerTester<UserState>()
.givenReducer(userReducer, { ...initialUserState, teamsAreLoading: true })
.whenActionIsDispatched(
teamsLoaded({
teams: [getMockTeam(1, { permission: TeamPermissionLevel.Admin })],
})
)
.thenStateShouldEqual({
...initialUserState,
teamsAreLoading: false,
teams: [getMockTeam(1, { permission: TeamPermissionLevel.Admin })],
});
});
});
describe('when orgsLoaded is dispatched', () => {
it('then state should be correct', () => {
reducerTester<UserState>()
.givenReducer(userReducer, { ...initialUserState, orgsAreLoading: true })
.whenActionIsDispatched(
orgsLoaded({
orgs: [{ orgId: 1, name: 'Main', role: OrgRole.Viewer }],
})
)
.thenStateShouldEqual({
...initialUserState,
orgsAreLoading: false,
orgs: [{ orgId: 1, name: 'Main', role: OrgRole.Viewer }],
});
});
});
describe('when sessionsLoaded is dispatched', () => {
it('then state should be correct', () => {
reducerTester<UserState>()
.givenReducer(userReducer, { ...initialUserState, sessionsAreLoading: true })
.whenActionIsDispatched(
sessionsLoaded({
sessions: [
{
id: 1,
browser: 'Chrome',
browserVersion: '90',
osVersion: '95',
clientIp: '192.168.1.1',
createdAt: '2021-01-01 04:00:00',
device: 'Computer',
os: 'Windows',
isActive: false,
seenAt: '1996-01-01 04:00:00',
},
],
})
)
.thenStateShouldEqual({
...initialUserState,
sessionsAreLoading: false,
sessions: [
{
id: 1,
browser: 'Chrome',
browserVersion: '90',
osVersion: '95',
clientIp: '192.168.1.1',
createdAt: '2021-01-01 04:00:00',
device: 'Computer',
os: 'Windows',
isActive: false,
seenAt: '25 years ago',
},
],
});
});
});
describe('when userSessionRevoked is dispatched', () => {
it('then state should be correct', () => {
reducerTester<UserState>()
.givenReducer(userReducer, {
...initialUserState,
sessions: [
{
id: 1,
browser: 'Chrome',
browserVersion: '90',
osVersion: '95',
clientIp: '192.168.1.1',
createdAt: '2021-01-01',
device: 'Computer',
os: 'Windows',
isActive: false,
seenAt: '1996-01-01',
},
],
})
.whenActionIsDispatched(userSessionRevoked({ tokenId: 1 }))
.thenStateShouldEqual({
...initialUserState,
sessions: [],
});
});
});
});
| public/app/features/profile/state/reducers.test.ts | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.0001771892566466704,
0.00017330283299088478,
0.0001677083782851696,
0.00017323596694041044,
0.000002532282906031469
]
|
{
"id": 1,
"code_window": [
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"32\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"33\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"34\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"35\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"36\"]\n",
" ],\n",
" \"public/app/features/dashboard/state/PanelModel.test.ts:5381\": [\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"0\"],\n",
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"1\"],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" [0, 0, 0, \"Unexpected any. Specify a different type.\", \"35\"]\n"
],
"file_path": ".betterer.results",
"type": "replace",
"edit_start_line_idx": 1007
} | package historian
import (
"context"
"encoding/json"
"fmt"
"sort"
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/ngalert/eval"
"github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/services/ngalert/state"
history_model "github.com/grafana/grafana/pkg/services/ngalert/state/historian/model"
)
const (
OrgIDLabel = "orgID"
RuleUIDLabel = "ruleUID"
GroupLabel = "group"
FolderUIDLabel = "folderUID"
)
type remoteLokiClient interface {
ping(context.Context) error
push(context.Context, []stream) error
}
type RemoteLokiBackend struct {
client remoteLokiClient
log log.Logger
}
func NewRemoteLokiBackend(cfg LokiConfig) *RemoteLokiBackend {
logger := log.New("ngalert.state.historian", "backend", "loki")
return &RemoteLokiBackend{
client: newLokiClient(cfg, logger),
log: logger,
}
}
func (h *RemoteLokiBackend) TestConnection(ctx context.Context) error {
return h.client.ping(ctx)
}
func (h *RemoteLokiBackend) RecordStatesAsync(ctx context.Context, rule history_model.RuleMeta, states []state.StateTransition) <-chan error {
logger := h.log.FromContext(ctx)
streams := h.statesToStreams(rule, states, logger)
return h.recordStreamsAsync(ctx, streams, logger)
}
func (h *RemoteLokiBackend) QueryStates(ctx context.Context, query models.HistoryQuery) (*data.Frame, error) {
return data.NewFrame("states"), nil
}
func (h *RemoteLokiBackend) statesToStreams(rule history_model.RuleMeta, states []state.StateTransition, logger log.Logger) []stream {
buckets := make(map[string][]row) // label repr -> entries
for _, state := range states {
if !shouldRecord(state) {
continue
}
labels := removePrivateLabels(state.State.Labels)
labels[OrgIDLabel] = fmt.Sprint(rule.OrgID)
labels[RuleUIDLabel] = fmt.Sprint(rule.UID)
labels[GroupLabel] = fmt.Sprint(rule.Group)
labels[FolderUIDLabel] = fmt.Sprint(rule.NamespaceUID)
repr := labels.String()
entry := lokiEntry{
SchemaVersion: 1,
Previous: state.PreviousFormatted(),
Current: state.Formatted(),
Values: valuesAsDataBlob(state.State),
}
jsn, err := json.Marshal(entry)
if err != nil {
logger.Error("Failed to construct history record for state, skipping", "error", err)
continue
}
line := string(jsn)
buckets[repr] = append(buckets[repr], row{
At: state.State.LastEvaluationTime,
Val: line,
})
}
result := make([]stream, 0, len(buckets))
for repr, rows := range buckets {
labels, err := data.LabelsFromString(repr)
if err != nil {
logger.Error("Failed to parse frame labels, skipping state history batch: %w", err)
continue
}
result = append(result, stream{
Stream: labels,
Values: rows,
})
}
return result
}
func (h *RemoteLokiBackend) recordStreamsAsync(ctx context.Context, streams []stream, logger log.Logger) <-chan error {
errCh := make(chan error, 1)
go func() {
defer close(errCh)
if err := h.recordStreams(ctx, streams, logger); err != nil {
logger.Error("Failed to save alert state history batch", "error", err)
errCh <- fmt.Errorf("failed to save alert state history batch: %w", err)
}
}()
return errCh
}
func (h *RemoteLokiBackend) recordStreams(ctx context.Context, streams []stream, logger log.Logger) error {
if err := h.client.push(ctx, streams); err != nil {
return err
}
logger.Debug("Done saving alert state history batch")
return nil
}
type lokiEntry struct {
SchemaVersion int `json:"schemaVersion"`
Previous string `json:"previous"`
Current string `json:"current"`
Values *simplejson.Json `json:"values"`
}
func valuesAsDataBlob(state *state.State) *simplejson.Json {
jsonData := simplejson.New()
switch state.State {
case eval.Error:
if state.Error == nil {
jsonData.Set("error", nil)
} else {
jsonData.Set("error", state.Error.Error())
}
case eval.NoData:
jsonData.Set("noData", true)
default:
keys := make([]string, 0, len(state.Values))
for k := range state.Values {
keys = append(keys, k)
}
sort.Strings(keys)
jsonData.Set("values", simplejson.NewFromAny(state.Values))
}
return jsonData
}
| pkg/services/ngalert/state/historian/loki.go | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.0001732359523884952,
0.00016880927432794124,
0.00016378844156861305,
0.00016952624719124287,
0.0000028387541988195153
]
|
{
"id": 2,
"code_window": [
"| `id` | integer | No | Unique numeric identifier for the dashboard.<br/>TODO must isolate or remove identifiers local to a Grafana instance...? |\n",
"| `links` | [DashboardLink](#dashboardlink)[] | No | TODO docs |\n",
"| `liveNow` | boolean | No | TODO docs |\n",
"| `panels` | [object](#panels)[] | No | |\n",
"| `refresh` | | No | TODO docs |\n",
"| `snapshot` | [Snapshot](#snapshot) | No | TODO docs |\n",
"| `tags` | string[] | No | Tags associated with dashboard. |\n",
"| `templating` | [object](#templating) | No | TODO docs |\n",
"| `time` | [object](#time) | No | Time range for dashboard, e.g. last 6 hours, last 7 days, etc |\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"| `refresh` | | No | Refresh rate of dashboard. Represented via interval string, e.g. \"5s\", \"1m\", \"1h\", \"1d\". |\n"
],
"file_path": "docs/sources/developers/kinds/core/dashboard/schema-reference.md",
"type": "replace",
"edit_start_line_idx": 30
} | // Code generated - EDITING IS FUTILE. DO NOT EDIT.
//
// Generated by:
// kinds/gen.go
// Using jennies:
// GoTypesJenny
// LatestJenny
//
// Run 'make gen-cue' from repository root to regenerate.
package dashboard
// Defines values for Style.
const (
StyleDark Style = "dark"
StyleLight Style = "light"
)
// Defines values for Timezone.
const (
TimezoneBrowser Timezone = "browser"
TimezoneEmpty Timezone = ""
TimezoneUtc Timezone = "utc"
)
// Defines values for CursorSync.
const (
CursorSyncN0 CursorSync = 0
CursorSyncN1 CursorSync = 1
CursorSyncN2 CursorSync = 2
)
// Defines values for LinkType.
const (
LinkTypeDashboards LinkType = "dashboards"
LinkTypeLink LinkType = "link"
)
// Defines values for FieldColorModeId.
const (
FieldColorModeIdContinuousGrYlRd FieldColorModeId = "continuous-GrYlRd"
FieldColorModeIdFixed FieldColorModeId = "fixed"
FieldColorModeIdPaletteClassic FieldColorModeId = "palette-classic"
FieldColorModeIdPaletteSaturated FieldColorModeId = "palette-saturated"
FieldColorModeIdThresholds FieldColorModeId = "thresholds"
)
// Defines values for FieldColorSeriesByMode.
const (
FieldColorSeriesByModeLast FieldColorSeriesByMode = "last"
FieldColorSeriesByModeMax FieldColorSeriesByMode = "max"
FieldColorSeriesByModeMin FieldColorSeriesByMode = "min"
)
// Defines values for GraphPanelType.
const (
GraphPanelTypeGraph GraphPanelType = "graph"
)
// Defines values for HeatmapPanelType.
const (
HeatmapPanelTypeHeatmap HeatmapPanelType = "heatmap"
)
// Defines values for LoadingState.
const (
LoadingStateDone LoadingState = "Done"
LoadingStateError LoadingState = "Error"
LoadingStateLoading LoadingState = "Loading"
LoadingStateNotStarted LoadingState = "NotStarted"
LoadingStateStreaming LoadingState = "Streaming"
)
// Defines values for MappingType.
const (
MappingTypeRange MappingType = "range"
MappingTypeRegex MappingType = "regex"
MappingTypeSpecial MappingType = "special"
MappingTypeValue MappingType = "value"
)
// Defines values for PanelRepeatDirection.
const (
PanelRepeatDirectionH PanelRepeatDirection = "h"
PanelRepeatDirectionV PanelRepeatDirection = "v"
)
// Defines values for RowPanelType.
const (
RowPanelTypeRow RowPanelType = "row"
)
// Defines values for SpecialValueMapOptionsMatch.
const (
SpecialValueMapOptionsMatchFalse SpecialValueMapOptionsMatch = "false"
SpecialValueMapOptionsMatchTrue SpecialValueMapOptionsMatch = "true"
)
// Defines values for SpecialValueMatch.
const (
SpecialValueMatchEmpty SpecialValueMatch = "empty"
SpecialValueMatchFalse SpecialValueMatch = "false"
SpecialValueMatchNan SpecialValueMatch = "nan"
SpecialValueMatchNull SpecialValueMatch = "null"
SpecialValueMatchNullNan SpecialValueMatch = "null+nan"
SpecialValueMatchTrue SpecialValueMatch = "true"
)
// Defines values for ThresholdsMode.
const (
ThresholdsModeAbsolute ThresholdsMode = "absolute"
ThresholdsModePercentage ThresholdsMode = "percentage"
)
// Defines values for VariableHide.
const (
VariableHideN0 VariableHide = 0
VariableHideN1 VariableHide = 1
VariableHideN2 VariableHide = 2
)
// Defines values for VariableType.
const (
VariableTypeAdhoc VariableType = "adhoc"
VariableTypeConstant VariableType = "constant"
VariableTypeCustom VariableType = "custom"
VariableTypeDatasource VariableType = "datasource"
VariableTypeInterval VariableType = "interval"
VariableTypeQuery VariableType = "query"
VariableTypeSystem VariableType = "system"
VariableTypeTextbox VariableType = "textbox"
)
// TODO docs
// FROM: AnnotationQuery in grafana-data/src/types/annotations.ts
type AnnotationQuery struct {
BuiltIn int `json:"builtIn"`
// Datasource to use for annotation.
Datasource struct {
Type *string `json:"type,omitempty"`
Uid *string `json:"uid,omitempty"`
} `json:"datasource"`
// Whether annotation is enabled.
Enable bool `json:"enable"`
// Whether to hide annotation.
Hide *bool `json:"hide,omitempty"`
// Annotation icon color.
IconColor *string `json:"iconColor,omitempty"`
// Name of annotation.
Name *string `json:"name,omitempty"`
// Query for annotation data.
RawQuery *string `json:"rawQuery,omitempty"`
ShowIn int `json:"showIn"`
// TODO docs
Target *AnnotationTarget `json:"target,omitempty"`
Type string `json:"type"`
}
// TODO docs
type AnnotationTarget struct {
Limit int64 `json:"limit"`
MatchAny bool `json:"matchAny"`
Tags []string `json:"tags"`
Type string `json:"type"`
}
// Dashboard defines model for Dashboard.
type Dashboard struct {
// TODO docs
Annotations *struct {
List *[]AnnotationQuery `json:"list,omitempty"`
} `json:"annotations,omitempty"`
// Description of dashboard.
Description *string `json:"description,omitempty"`
// Whether a dashboard is editable or not.
Editable bool `json:"editable"`
// The month that the fiscal year starts on. 0 = January, 11 = December
FiscalYearStartMonth *int `json:"fiscalYearStartMonth,omitempty"`
GnetId *string `json:"gnetId,omitempty"`
// 0 for no shared crosshair or tooltip (default).
// 1 for shared crosshair.
// 2 for shared crosshair AND shared tooltip.
GraphTooltip CursorSync `json:"graphTooltip"`
// Unique numeric identifier for the dashboard.
// TODO must isolate or remove identifiers local to a Grafana instance...?
Id *int64 `json:"id,omitempty"`
// TODO docs
Links *[]Link `json:"links,omitempty"`
// TODO docs
LiveNow *bool `json:"liveNow,omitempty"`
Panels *[]interface{} `json:"panels,omitempty"`
// TODO docs
Refresh *interface{} `json:"refresh,omitempty"`
// Version of the current dashboard data
Revision int `json:"revision"`
// Version of the JSON schema, incremented each time a Grafana update brings
// changes to said schema.
// TODO this is the existing schema numbering system. It will be replaced by Thema's themaVersion
SchemaVersion int `json:"schemaVersion"`
// TODO docs
Snapshot *Snapshot `json:"snapshot,omitempty"`
// Theme of dashboard.
Style Style `json:"style"`
// Tags associated with dashboard.
Tags *[]string `json:"tags,omitempty"`
// TODO docs
Templating *struct {
List *[]VariableModel `json:"list,omitempty"`
} `json:"templating,omitempty"`
// Time range for dashboard, e.g. last 6 hours, last 7 days, etc
Time *struct {
From string `json:"from"`
To string `json:"to"`
} `json:"time,omitempty"`
// TODO docs
// TODO this appears to be spread all over in the frontend. Concepts will likely need tidying in tandem with schema changes
Timepicker *struct {
// Whether timepicker is collapsed or not.
Collapse bool `json:"collapse"`
// Whether timepicker is enabled or not.
Enable bool `json:"enable"`
// Whether timepicker is visible or not.
Hidden bool `json:"hidden"`
// Selectable intervals for auto-refresh.
RefreshIntervals []string `json:"refresh_intervals"`
// TODO docs
TimeOptions []string `json:"time_options"`
} `json:"timepicker,omitempty"`
// Timezone of dashboard,
Timezone *Timezone `json:"timezone,omitempty"`
// Title of dashboard.
Title *string `json:"title,omitempty"`
// Unique dashboard identifier that can be generated by anyone. string (8-40)
Uid *string `json:"uid,omitempty"`
// Version of the dashboard, incremented each time the dashboard is updated.
Version *int `json:"version,omitempty"`
// TODO docs
WeekStart *string `json:"weekStart,omitempty"`
}
// Theme of dashboard.
type Style string
// Timezone of dashboard,
type Timezone string
// 0 for no shared crosshair or tooltip (default).
// 1 for shared crosshair.
// 2 for shared crosshair AND shared tooltip.
type CursorSync int
// FROM public/app/features/dashboard/state/Models.ts - ish
// TODO docs
type Link struct {
AsDropdown bool `json:"asDropdown"`
Icon string `json:"icon"`
IncludeVars bool `json:"includeVars"`
KeepTime bool `json:"keepTime"`
Tags []string `json:"tags"`
TargetBlank bool `json:"targetBlank"`
Title string `json:"title"`
Tooltip string `json:"tooltip"`
// TODO docs
Type LinkType `json:"type"`
Url string `json:"url"`
}
// TODO docs
type LinkType string
// Ref to a DataSource instance
type DataSourceRef struct {
// The plugin type-id
Type *string `json:"type,omitempty"`
// Specific datasource instance
Uid *string `json:"uid,omitempty"`
}
// DynamicConfigValue defines model for DynamicConfigValue.
type DynamicConfigValue struct {
Id string `json:"id"`
Value *interface{} `json:"value,omitempty"`
}
// TODO docs
type FieldColor struct {
// Stores the fixed color value if mode is fixed
FixedColor *string `json:"fixedColor,omitempty"`
// The main color scheme mode
Mode interface{} `json:"mode"`
// TODO docs
SeriesBy *FieldColorSeriesByMode `json:"seriesBy,omitempty"`
}
// TODO docs
type FieldColorModeId string
// TODO docs
type FieldColorSeriesByMode string
// FieldConfig defines model for FieldConfig.
type FieldConfig struct {
// TODO docs
Color *FieldColor `json:"color,omitempty"`
// custom is specified by the PanelFieldConfig field
// in panel plugin schemas.
Custom *map[string]interface{} `json:"custom,omitempty"`
// Significant digits (for display)
Decimals *float32 `json:"decimals,omitempty"`
// Human readable field metadata
Description *string `json:"description,omitempty"`
// The display value for this field. This supports template variables blank is auto
DisplayName *string `json:"displayName,omitempty"`
// This can be used by data sources that return and explicit naming structure for values and labels
// When this property is configured, this value is used rather than the default naming strategy.
DisplayNameFromDS *string `json:"displayNameFromDS,omitempty"`
// True if data source field supports ad-hoc filters
Filterable *bool `json:"filterable,omitempty"`
// The behavior when clicking on a result
Links *[]interface{} `json:"links,omitempty"`
// Convert input values into a display string
Mappings *[]ValueMapping `json:"mappings,omitempty"`
Max *float32 `json:"max,omitempty"`
Min *float32 `json:"min,omitempty"`
// Alternative to empty string
NoValue *string `json:"noValue,omitempty"`
// An explicit path to the field in the datasource. When the frame meta includes a path,
// This will default to `${frame.meta.path}/${field.name}
//
// When defined, this value can be used as an identifier within the datasource scope, and
// may be used to update the results
Path *string `json:"path,omitempty"`
Thresholds *ThresholdsConfig `json:"thresholds,omitempty"`
// Numeric Options
Unit *string `json:"unit,omitempty"`
// True if data source can write a value to the path. Auth/authz are supported separately
Writeable *bool `json:"writeable,omitempty"`
}
// FieldConfigSource defines model for FieldConfigSource.
type FieldConfigSource struct {
Defaults FieldConfig `json:"defaults"`
Overrides []struct {
Matcher MatcherConfig `json:"matcher"`
Properties []DynamicConfigValue `json:"properties"`
} `json:"overrides"`
}
// Support for legacy graph and heatmap panels.
type GraphPanel struct {
// @deprecated this is part of deprecated graph panel
Legend *struct {
Show bool `json:"show"`
Sort *string `json:"sort,omitempty"`
SortDesc *bool `json:"sortDesc,omitempty"`
} `json:"legend,omitempty"`
Type GraphPanelType `json:"type"`
}
// GraphPanelType defines model for GraphPanel.Type.
type GraphPanelType string
// GridPos defines model for GridPos.
type GridPos struct {
// Panel
H int `json:"h"`
// true if fixed
Static *bool `json:"static,omitempty"`
// Panel
W int `json:"w"`
// Panel x
X int `json:"x"`
// Panel y
Y int `json:"y"`
}
// HeatmapPanel defines model for HeatmapPanel.
type HeatmapPanel struct {
Type HeatmapPanelType `json:"type"`
}
// HeatmapPanelType defines model for HeatmapPanel.Type.
type HeatmapPanelType string
// LoadingState defines model for LoadingState.
type LoadingState string
// TODO docs
type MappingType string
// MatcherConfig defines model for MatcherConfig.
type MatcherConfig struct {
Id string `json:"id"`
Options *interface{} `json:"options,omitempty"`
}
// Dashboard panels. Panels are canonically defined inline
// because they share a version timeline with the dashboard
// schema; they do not evolve independently.
type Panel struct {
// The datasource used in all targets.
Datasource *struct {
Type *string `json:"type,omitempty"`
Uid *string `json:"uid,omitempty"`
} `json:"datasource,omitempty"`
// Description.
Description *string `json:"description,omitempty"`
FieldConfig FieldConfigSource `json:"fieldConfig"`
GridPos *GridPos `json:"gridPos,omitempty"`
// TODO docs
Id *int `json:"id,omitempty"`
// TODO docs
// TODO tighter constraint
Interval *string `json:"interval,omitempty"`
// Panel links.
// TODO fill this out - seems there are a couple variants?
Links *[]Link `json:"links,omitempty"`
// TODO docs
MaxDataPoints *float32 `json:"maxDataPoints,omitempty"`
// options is specified by the PanelOptions field in panel
// plugin schemas.
Options map[string]interface{} `json:"options"`
// FIXME this almost certainly has to be changed in favor of scuemata versions
PluginVersion *string `json:"pluginVersion,omitempty"`
// Name of template variable to repeat for.
Repeat *string `json:"repeat,omitempty"`
// Direction to repeat in if 'repeat' is set.
// "h" for horizontal, "v" for vertical.
// TODO this is probably optional
RepeatDirection PanelRepeatDirection `json:"repeatDirection"`
// Id of the repeating panel.
RepeatPanelId *int64 `json:"repeatPanelId,omitempty"`
// TODO docs
Tags *[]string `json:"tags,omitempty"`
// TODO docs
Targets *[]Target `json:"targets,omitempty"`
// TODO docs - seems to be an old field from old dashboard alerts?
Thresholds *[]interface{} `json:"thresholds,omitempty"`
// TODO docs
// TODO tighter constraint
TimeFrom *string `json:"timeFrom,omitempty"`
// TODO docs
TimeRegions *[]interface{} `json:"timeRegions,omitempty"`
// TODO docs
// TODO tighter constraint
TimeShift *string `json:"timeShift,omitempty"`
// Panel title.
Title *string `json:"title,omitempty"`
Transformations []Transformation `json:"transformations"`
// Whether to display the panel without a background.
Transparent bool `json:"transparent"`
// The panel plugin type id. May not be empty.
Type string `json:"type"`
}
// Direction to repeat in if 'repeat' is set.
// "h" for horizontal, "v" for vertical.
// TODO this is probably optional
type PanelRepeatDirection string
// TODO docs
type RangeMap struct {
Options struct {
// to and from are `number | null` in current ts, really not sure what to do
From float64 `json:"from"`
// TODO docs
Result ValueMappingResult `json:"result"`
To float64 `json:"to"`
} `json:"options"`
Type struct {
// Embedded struct due to allOf(#/components/schemas/MappingType)
MappingType `yaml:",inline"`
// Embedded fields due to inline allOf schema
} `json:"type"`
}
// TODO docs
type RegexMap struct {
Options struct {
Pattern string `json:"pattern"`
// TODO docs
Result ValueMappingResult `json:"result"`
} `json:"options"`
Type struct {
// Embedded struct due to allOf(#/components/schemas/MappingType)
MappingType `yaml:",inline"`
// Embedded fields due to inline allOf schema
} `json:"type"`
}
// Row panel
type RowPanel struct {
Collapsed bool `json:"collapsed"`
// Name of default datasource.
Datasource *struct {
Type *string `json:"type,omitempty"`
Uid *string `json:"uid,omitempty"`
} `json:"datasource,omitempty"`
GridPos *GridPos `json:"gridPos,omitempty"`
Id int `json:"id"`
Panels []interface{} `json:"panels"`
// Name of template variable to repeat for.
Repeat *string `json:"repeat,omitempty"`
Title *string `json:"title,omitempty"`
Type RowPanelType `json:"type"`
}
// RowPanelType defines model for RowPanel.Type.
type RowPanelType string
// TODO docs
type Snapshot struct {
// TODO docs
Created string `json:"created"`
// TODO docs
Expires string `json:"expires"`
// TODO docs
External bool `json:"external"`
// TODO docs
ExternalUrl string `json:"externalUrl"`
// TODO docs
Id int `json:"id"`
// TODO docs
Key string `json:"key"`
// TODO docs
Name string `json:"name"`
// TODO docs
OrgId int `json:"orgId"`
// TODO docs
Updated string `json:"updated"`
// TODO docs
Url *string `json:"url,omitempty"`
// TODO docs
UserId int `json:"userId"`
}
// TODO docs
type SpecialValueMap struct {
Options struct {
Match SpecialValueMapOptionsMatch `json:"match"`
Pattern string `json:"pattern"`
// TODO docs
Result ValueMappingResult `json:"result"`
} `json:"options"`
Type struct {
// Embedded struct due to allOf(#/components/schemas/MappingType)
MappingType `yaml:",inline"`
// Embedded fields due to inline allOf schema
} `json:"type"`
}
// SpecialValueMapOptionsMatch defines model for SpecialValueMap.Options.Match.
type SpecialValueMapOptionsMatch string
// TODO docs
type SpecialValueMatch string
// Schema for panel targets is specified by datasource
// plugins. We use a placeholder definition, which the Go
// schema loader either left open/as-is with the Base
// variant of the Dashboard and Panel families, or filled
// with types derived from plugins in the Instance variant.
// When working directly from CUE, importers can extend this
// type directly to achieve the same effect.
type Target map[string]interface{}
// TODO docs
type Threshold struct {
// TODO docs
Color string `json:"color"`
// TODO docs
// TODO are the values here enumerable into a disjunction?
// Some seem to be listed in typescript comment
State *string `json:"state,omitempty"`
// TODO docs
// FIXME the corresponding typescript field is required/non-optional, but nulls currently appear here when serializing -Infinity to JSON
Value *float32 `json:"value,omitempty"`
}
// ThresholdsConfig defines model for ThresholdsConfig.
type ThresholdsConfig struct {
Mode ThresholdsMode `json:"mode"`
// Must be sorted by 'value', first value is always -Infinity
Steps []Threshold `json:"steps"`
}
// ThresholdsMode defines model for ThresholdsMode.
type ThresholdsMode string
// TODO docs
// FIXME this is extremely underspecfied; wasn't obvious which typescript types corresponded to it
type Transformation struct {
Id string `json:"id"`
Options map[string]interface{} `json:"options"`
}
// TODO docs
type ValueMap struct {
Options map[string]ValueMappingResult `json:"options"`
Type struct {
// Embedded struct due to allOf(#/components/schemas/MappingType)
MappingType `yaml:",inline"`
// Embedded fields due to inline allOf schema
} `json:"type"`
}
// TODO docs
type ValueMapping interface{}
// TODO docs
type ValueMappingResult struct {
Color *string `json:"color,omitempty"`
Icon *string `json:"icon,omitempty"`
Index *int32 `json:"index,omitempty"`
Text *string `json:"text,omitempty"`
}
// VariableHide defines model for VariableHide.
type VariableHide int
// FROM: packages/grafana-data/src/types/templateVars.ts
// TODO docs
// TODO what about what's in public/app/features/types.ts?
// TODO there appear to be a lot of different kinds of [template] vars here? if so need a disjunction
type VariableModel struct {
// Ref to a DataSource instance
Datasource *DataSourceRef `json:"datasource,omitempty"`
Description *string `json:"description,omitempty"`
Error *map[string]interface{} `json:"error,omitempty"`
Global bool `json:"global"`
Hide VariableHide `json:"hide"`
Id string `json:"id"`
Index int `json:"index"`
Label *string `json:"label,omitempty"`
Name string `json:"name"`
// TODO: Move this into a separated QueryVariableModel type
Query *interface{} `json:"query,omitempty"`
RootStateKey *string `json:"rootStateKey,omitempty"`
SkipUrlSync bool `json:"skipUrlSync"`
State LoadingState `json:"state"`
// FROM: packages/grafana-data/src/types/templateVars.ts
// TODO docs
// TODO this implies some wider pattern/discriminated union, probably?
Type VariableType `json:"type"`
}
// FROM: packages/grafana-data/src/types/templateVars.ts
// TODO docs
// TODO this implies some wider pattern/discriminated union, probably?
type VariableType string
| pkg/kinds/dashboard/dashboard_types_gen.go | 1 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.011014771647751331,
0.011014771647751331,
0.011014771647751331,
0.011014771647751331,
0
]
|
{
"id": 2,
"code_window": [
"| `id` | integer | No | Unique numeric identifier for the dashboard.<br/>TODO must isolate or remove identifiers local to a Grafana instance...? |\n",
"| `links` | [DashboardLink](#dashboardlink)[] | No | TODO docs |\n",
"| `liveNow` | boolean | No | TODO docs |\n",
"| `panels` | [object](#panels)[] | No | |\n",
"| `refresh` | | No | TODO docs |\n",
"| `snapshot` | [Snapshot](#snapshot) | No | TODO docs |\n",
"| `tags` | string[] | No | Tags associated with dashboard. |\n",
"| `templating` | [object](#templating) | No | TODO docs |\n",
"| `time` | [object](#time) | No | Time range for dashboard, e.g. last 6 hours, last 7 days, etc |\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"| `refresh` | | No | Refresh rate of dashboard. Represented via interval string, e.g. \"5s\", \"1m\", \"1h\", \"1d\". |\n"
],
"file_path": "docs/sources/developers/kinds/core/dashboard/schema-reference.md",
"type": "replace",
"edit_start_line_idx": 30
} | import pluralize from 'pluralize';
import React, { FC, useMemo, useState } from 'react';
import { dateTime, dateTimeFormat } from '@grafana/data';
import { Stack } from '@grafana/experimental';
import { Button, ConfirmModal, Modal, useStyles2, Badge, Icon } from '@grafana/ui';
import { contextSrv } from 'app/core/services/context_srv';
import { AlertManagerCortexConfig } from 'app/plugins/datasource/alertmanager/types';
import { useDispatch, AccessControlAction, ContactPointsState, NotifiersState, ReceiversState } from 'app/types';
import { useGetContactPointsState } from '../../api/receiversApi';
import { Authorize } from '../../components/Authorize';
import { useUnifiedAlertingSelector } from '../../hooks/useUnifiedAlertingSelector';
import { deleteReceiverAction } from '../../state/actions';
import { getAlertTableStyles } from '../../styles/table';
import { SupportedPlugin } from '../../types/pluginBridges';
import { getNotificationsPermissions } from '../../utils/access-control';
import { isReceiverUsed } from '../../utils/alertmanager';
import { isVanillaPrometheusAlertManagerDataSource } from '../../utils/datasource';
import { makeAMLink } from '../../utils/misc';
import { extractNotifierTypeCounts } from '../../utils/receivers';
import { DynamicTable, DynamicTableColumnProps, DynamicTableItemProps } from '../DynamicTable';
import { ProvisioningBadge } from '../Provisioning';
import { ActionIcon } from '../rules/ActionIcon';
import { ReceiversSection } from './ReceiversSection';
import { GrafanaAppBadge } from './grafanaAppReceivers/GrafanaAppBadge';
import { useGetReceiversWithGrafanaAppTypes } from './grafanaAppReceivers/grafanaApp';
import { ReceiverWithTypes } from './grafanaAppReceivers/types';
interface UpdateActionProps extends ActionProps {
onClickDeleteReceiver: (receiverName: string) => void;
}
function UpdateActions({ permissions, alertManagerName, receiverName, onClickDeleteReceiver }: UpdateActionProps) {
return (
<>
<Authorize actions={[permissions.update]}>
<ActionIcon
aria-label="Edit"
data-testid="edit"
to={makeAMLink(
`/alerting/notifications/receivers/${encodeURIComponent(receiverName)}/edit`,
alertManagerName
)}
tooltip="Edit contact point"
icon="pen"
/>
</Authorize>
<Authorize actions={[permissions.delete]}>
<ActionIcon
onClick={() => onClickDeleteReceiver(receiverName)}
tooltip="Delete contact point"
icon="trash-alt"
/>
</Authorize>
</>
);
}
interface ActionProps {
permissions: {
read: AccessControlAction;
create: AccessControlAction;
update: AccessControlAction;
delete: AccessControlAction;
};
alertManagerName: string;
receiverName: string;
}
function ViewAction({ permissions, alertManagerName, receiverName }: ActionProps) {
return (
<Authorize actions={[permissions.update]}>
<ActionIcon
data-testid="view"
to={makeAMLink(`/alerting/notifications/receivers/${encodeURIComponent(receiverName)}/edit`, alertManagerName)}
tooltip="View contact point"
icon="file-alt"
/>
</Authorize>
);
}
interface ReceiverErrorProps {
errorCount: number;
errorDetail?: string;
showErrorCount: boolean;
}
function ReceiverError({ errorCount, errorDetail, showErrorCount }: ReceiverErrorProps) {
const text = showErrorCount ? `${errorCount} ${pluralize('error', errorCount)}` : 'Error';
return <Badge color="orange" icon="exclamation-triangle" text={text} tooltip={errorDetail ?? 'Error'} />;
}
interface NotifierHealthProps {
errorsByNotifier: number;
errorDetail?: string;
lastNotify: string;
}
function NotifierHealth({ errorsByNotifier, errorDetail, lastNotify }: NotifierHealthProps) {
const noErrorsColor = isLastNotifyNullDate(lastNotify) ? 'orange' : 'green';
const noErrorsText = isLastNotifyNullDate(lastNotify) ? 'No attempts' : 'OK';
return errorsByNotifier > 0 ? (
<ReceiverError errorCount={errorsByNotifier} errorDetail={errorDetail} showErrorCount={false} />
) : (
<Badge color={noErrorsColor} text={noErrorsText} tooltip="" />
);
}
interface ReceiverHealthProps {
errorsByReceiver: number;
someWithNoAttempt: boolean;
}
function ReceiverHealth({ errorsByReceiver, someWithNoAttempt }: ReceiverHealthProps) {
const noErrorsColor = someWithNoAttempt ? 'orange' : 'green';
const noErrorsText = someWithNoAttempt ? 'No attempts' : 'OK';
return errorsByReceiver > 0 ? (
<ReceiverError errorCount={errorsByReceiver} showErrorCount={true} />
) : (
<Badge color={noErrorsColor} text={noErrorsText} tooltip="" />
);
}
const useContactPointsState = (alertManagerName: string) => {
const contactPointsState = useGetContactPointsState(alertManagerName);
const receivers: ReceiversState = contactPointsState?.receivers ?? {};
const errorStateAvailable = Object.keys(receivers).length > 0;
return { contactPointsState, errorStateAvailable };
};
interface ReceiverItem {
name: string;
types: string[];
provisioned?: boolean;
grafanaAppReceiverType?: SupportedPlugin;
}
interface NotifierStatus {
lastError?: null | string;
lastNotify: string;
lastNotifyDuration: string;
type: string;
sendResolved?: boolean;
}
type RowTableColumnProps = DynamicTableColumnProps<ReceiverItem>;
type RowItemTableProps = DynamicTableItemProps<ReceiverItem>;
type NotifierTableColumnProps = DynamicTableColumnProps<NotifierStatus>;
type NotifierItemTableProps = DynamicTableItemProps<NotifierStatus>;
interface NotifiersTableProps {
notifiersState: NotifiersState;
}
const isLastNotifyNullDate = (lastNotify: string) => lastNotify === '0001-01-01T00:00:00.000Z';
function LastNotify({ lastNotifyDate }: { lastNotifyDate: string }) {
if (isLastNotifyNullDate(lastNotifyDate)) {
return <>{'-'}</>;
} else {
return (
<Stack alignItems="center">
<div>{`${dateTime(lastNotifyDate).locale('en').fromNow(true)} ago`}</div>
<Icon name="clock-nine" />
<div>{`${dateTimeFormat(lastNotifyDate, { format: 'YYYY-MM-DD HH:mm:ss' })}`}</div>
</Stack>
);
}
}
const possibleNullDurations = ['', '0', '0ms', '0s', '0m', '0h', '0d', '0w', '0y'];
const durationIsNull = (duration: string) => possibleNullDurations.includes(duration);
function NotifiersTable({ notifiersState }: NotifiersTableProps) {
function getNotifierColumns(): NotifierTableColumnProps[] {
return [
{
id: 'health',
label: 'Health',
renderCell: ({ data: { lastError, lastNotify } }) => {
return (
<NotifierHealth
errorsByNotifier={lastError ? 1 : 0}
errorDetail={lastError ?? undefined}
lastNotify={lastNotify}
/>
);
},
size: 0.5,
},
{
id: 'name',
label: 'Name',
renderCell: ({ data: { type }, id }) => <>{`${type}[${id}]`}</>,
size: 1,
},
{
id: 'lastNotify',
label: 'Last delivery attempt',
renderCell: ({ data: { lastNotify } }) => <LastNotify lastNotifyDate={lastNotify} />,
size: 3,
},
{
id: 'lastNotifyDuration',
label: 'Last duration',
renderCell: ({ data: { lastNotify, lastNotifyDuration } }) => (
<>{isLastNotifyNullDate(lastNotify) && durationIsNull(lastNotifyDuration) ? '-' : lastNotifyDuration}</>
),
size: 1,
},
{
id: 'sendResolved',
label: 'Send resolved',
renderCell: ({ data: { sendResolved } }) => <>{String(Boolean(sendResolved))}</>,
size: 1,
},
];
}
const notifierRows: NotifierItemTableProps[] = Object.entries(notifiersState).flatMap((typeState) =>
typeState[1].map((notifierStatus, index) => {
return {
id: index,
data: {
type: typeState[0],
lastError: notifierStatus.lastNotifyAttemptError,
lastNotify: notifierStatus.lastNotifyAttempt,
lastNotifyDuration: notifierStatus.lastNotifyAttemptDuration,
sendResolved: notifierStatus.sendResolved,
},
};
})
);
return <DynamicTable items={notifierRows} cols={getNotifierColumns()} />;
}
interface Props {
config: AlertManagerCortexConfig;
alertManagerName: string;
}
export const ReceiversTable: FC<Props> = ({ config, alertManagerName }) => {
const dispatch = useDispatch();
const isVanillaAM = isVanillaPrometheusAlertManagerDataSource(alertManagerName);
const permissions = getNotificationsPermissions(alertManagerName);
const grafanaNotifiers = useUnifiedAlertingSelector((state) => state.grafanaNotifiers);
const { contactPointsState, errorStateAvailable } = useContactPointsState(alertManagerName);
// receiver name slated for deletion. If this is set, a confirmation modal is shown. If user approves, this receiver is deleted
const [receiverToDelete, setReceiverToDelete] = useState<string>();
const [showCannotDeleteReceiverModal, setShowCannotDeleteReceiverModal] = useState(false);
const onClickDeleteReceiver = (receiverName: string): void => {
if (isReceiverUsed(receiverName, config)) {
setShowCannotDeleteReceiverModal(true);
} else {
setReceiverToDelete(receiverName);
}
};
const deleteReceiver = () => {
if (receiverToDelete) {
dispatch(deleteReceiverAction(receiverToDelete, alertManagerName));
}
setReceiverToDelete(undefined);
};
const receivers = useGetReceiversWithGrafanaAppTypes(config.alertmanager_config.receivers ?? []);
const rows: RowItemTableProps[] = useMemo(() => {
return (
receivers?.map((receiver: ReceiverWithTypes) => ({
id: receiver.name,
data: {
name: receiver.name,
types: Object.entries(extractNotifierTypeCounts(receiver, grafanaNotifiers.result ?? [])).map(
([type, count]) => {
if (count > 1) {
return `${type} (${count})`;
}
return type;
}
),
grafanaAppReceiverType: receiver.grafanaAppReceiverType,
provisioned: receiver.grafana_managed_receiver_configs?.some((receiver) => receiver.provenance),
},
})) ?? []
);
}, [grafanaNotifiers.result, receivers]);
const columns = useGetColumns(
alertManagerName,
errorStateAvailable,
contactPointsState,
onClickDeleteReceiver,
permissions,
isVanillaAM
);
return (
<ReceiversSection
title="Contact points"
description="Define where the notifications will be sent to, for example email or Slack."
showButton={!isVanillaAM && contextSrv.hasPermission(permissions.create)}
addButtonLabel={'New contact point'}
addButtonTo={makeAMLink('/alerting/notifications/receivers/new', alertManagerName)}
>
<DynamicTable
items={rows}
cols={columns}
isExpandable={errorStateAvailable}
renderExpandedContent={
errorStateAvailable
? ({ data: { name } }) => (
<NotifiersTable notifiersState={contactPointsState?.receivers[name]?.notifiers ?? {}} />
)
: undefined
}
/>
{!!showCannotDeleteReceiverModal && (
<Modal
isOpen={true}
title="Cannot delete contact point"
onDismiss={() => setShowCannotDeleteReceiverModal(false)}
>
<p>
Contact point cannot be deleted because it is used in more policies. Please update or delete these policies
first.
</p>
<Modal.ButtonRow>
<Button variant="secondary" onClick={() => setShowCannotDeleteReceiverModal(false)} fill="outline">
Close
</Button>
</Modal.ButtonRow>
</Modal>
)}
{!!receiverToDelete && (
<ConfirmModal
isOpen={true}
title="Delete contact point"
body={`Are you sure you want to delete contact point "${receiverToDelete}"?`}
confirmText="Yes, delete"
onConfirm={deleteReceiver}
onDismiss={() => setReceiverToDelete(undefined)}
/>
)}
</ReceiversSection>
);
};
const errorsByReceiver = (contactPointsState: ContactPointsState, receiverName: string) =>
contactPointsState?.receivers[receiverName]?.errorCount ?? 0;
const someNotifiersWithNoAttempt = (contactPointsState: ContactPointsState, receiverName: string) => {
const notifiers = Object.values(contactPointsState?.receivers[receiverName]?.notifiers ?? {});
const hasSomeWitNoAttempt =
notifiers.length === 0 || notifiers.flat().some((status) => isLastNotifyNullDate(status.lastNotifyAttempt));
return hasSomeWitNoAttempt;
};
function useGetColumns(
alertManagerName: string,
errorStateAvailable: boolean,
contactPointsState: ContactPointsState | undefined,
onClickDeleteReceiver: (receiverName: string) => void,
permissions: {
read: AccessControlAction;
create: AccessControlAction;
update: AccessControlAction;
delete: AccessControlAction;
},
isVanillaAM: boolean
): RowTableColumnProps[] {
const tableStyles = useStyles2(getAlertTableStyles);
const baseColumns: RowTableColumnProps[] = [
{
id: 'name',
label: 'Contact point name',
renderCell: ({ data: { name, provisioned } }) => (
<Stack alignItems="center">
<div>{name}</div>
{provisioned && <ProvisioningBadge />}
</Stack>
),
size: 1,
},
{
id: 'type',
label: 'Type',
renderCell: ({ data: { types, grafanaAppReceiverType } }) => (
<>{grafanaAppReceiverType ? <GrafanaAppBadge grafanaAppType={grafanaAppReceiverType} /> : types.join(', ')}</>
),
size: 1,
},
];
const healthColumn: RowTableColumnProps = {
id: 'health',
label: 'Health',
renderCell: ({ data: { name } }) => {
return (
contactPointsState && (
<ReceiverHealth
errorsByReceiver={errorsByReceiver(contactPointsState, name)}
someWithNoAttempt={someNotifiersWithNoAttempt(contactPointsState, name)}
/>
)
);
},
size: 1,
};
return [
...baseColumns,
...(errorStateAvailable ? [healthColumn] : []),
{
id: 'actions',
label: 'Actions',
renderCell: ({ data: { provisioned, name } }) => (
<Authorize actions={[permissions.update, permissions.delete]}>
<div className={tableStyles.actionsCell}>
{!isVanillaAM && !provisioned && (
<UpdateActions
permissions={permissions}
alertManagerName={alertManagerName}
receiverName={name}
onClickDeleteReceiver={onClickDeleteReceiver}
/>
)}
{(isVanillaAM || provisioned) && (
<ViewAction permissions={permissions} alertManagerName={alertManagerName} receiverName={name} />
)}
</div>
</Authorize>
),
size: '100px',
},
];
}
| public/app/features/alerting/unified/components/receivers/ReceiversTable.tsx | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.011014771647751331,
0.011014766059815884,
0.011014750227332115,
0.011014771647751331,
9.543216883400873e-9
]
|
{
"id": 2,
"code_window": [
"| `id` | integer | No | Unique numeric identifier for the dashboard.<br/>TODO must isolate or remove identifiers local to a Grafana instance...? |\n",
"| `links` | [DashboardLink](#dashboardlink)[] | No | TODO docs |\n",
"| `liveNow` | boolean | No | TODO docs |\n",
"| `panels` | [object](#panels)[] | No | |\n",
"| `refresh` | | No | TODO docs |\n",
"| `snapshot` | [Snapshot](#snapshot) | No | TODO docs |\n",
"| `tags` | string[] | No | Tags associated with dashboard. |\n",
"| `templating` | [object](#templating) | No | TODO docs |\n",
"| `time` | [object](#time) | No | Time range for dashboard, e.g. last 6 hours, last 7 days, etc |\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"| `refresh` | | No | Refresh rate of dashboard. Represented via interval string, e.g. \"5s\", \"1m\", \"1h\", \"1d\". |\n"
],
"file_path": "docs/sources/developers/kinds/core/dashboard/schema-reference.md",
"type": "replace",
"edit_start_line_idx": 30
} | import { ComponentType } from 'react';
import { KeyValue } from './data';
import { NavModel } from './navModel';
import { PluginMeta, GrafanaPlugin, PluginIncludeType } from './plugin';
/**
* @public
* The app container that is loading another plugin (panel or query editor)
* */
export enum CoreApp {
CloudAlerting = 'cloud-alerting',
UnifiedAlerting = 'unified-alerting',
Dashboard = 'dashboard',
Explore = 'explore',
Correlations = 'correlations',
Unknown = 'unknown',
PanelEditor = 'panel-editor',
PanelViewer = 'panel-viewer',
}
export interface AppRootProps<T extends KeyValue = KeyValue> {
meta: AppPluginMeta<T>;
/**
* base URL segment for an app, /app/pluginId
*/
basename: string; // The URL path to this page
/**
* Pass the nav model to the container... is there a better way?
* @deprecated Use PluginPage component exported from @grafana/runtime instead
*/
onNavChanged: (nav: NavModel) => void;
/**
* The URL query parameters
* @deprecated Use react-router instead
*/
query: KeyValue;
/**
* The URL path to this page
* @deprecated Use react-router instead
*/
path: string;
}
export interface AppPluginMeta<T extends KeyValue = KeyValue> extends PluginMeta<T> {
// TODO anything specific to apps?
}
export class AppPlugin<T extends KeyValue = KeyValue> extends GrafanaPlugin<AppPluginMeta<T>> {
// Content under: /a/${plugin-id}/*
root?: ComponentType<AppRootProps<T>>;
rootNav?: NavModel; // Initial navigation model
/**
* Called after the module has loaded, and before the app is used.
* This function may be called multiple times on the same instance.
* The first time, `this.meta` will be undefined
*/
init(meta: AppPluginMeta) {}
/**
* Set the component displayed under:
* /a/${plugin-id}/*
*
* If the NavModel is configured, the page will have a managed frame, otheriwse it has full control.
*
* NOTE: this structure will change in 7.2+ so that it is managed with a normal react router
*/
setRootPage(root: ComponentType<AppRootProps<T>>, rootNav?: NavModel) {
this.root = root;
this.rootNav = rootNav;
return this;
}
setComponentsFromLegacyExports(pluginExports: any) {
if (pluginExports.ConfigCtrl) {
this.angularConfigCtrl = pluginExports.ConfigCtrl;
}
if (this.meta && this.meta.includes) {
for (const include of this.meta.includes) {
if (include.type === PluginIncludeType.page && include.component) {
const exp = pluginExports[include.component];
if (!exp) {
console.warn('App Page uses unknown component: ', include.component, this.meta);
continue;
}
}
}
}
}
}
/**
* Defines life cycle of a feature
* @internal
*/
export enum FeatureState {
alpha = 'alpha',
beta = 'beta',
}
| packages/grafana-data/src/types/app.ts | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.011014771647751331,
0.011014772579073906,
0.011014771647751331,
0.011014771647751331,
9.313225746154785e-10
]
|
{
"id": 2,
"code_window": [
"| `id` | integer | No | Unique numeric identifier for the dashboard.<br/>TODO must isolate or remove identifiers local to a Grafana instance...? |\n",
"| `links` | [DashboardLink](#dashboardlink)[] | No | TODO docs |\n",
"| `liveNow` | boolean | No | TODO docs |\n",
"| `panels` | [object](#panels)[] | No | |\n",
"| `refresh` | | No | TODO docs |\n",
"| `snapshot` | [Snapshot](#snapshot) | No | TODO docs |\n",
"| `tags` | string[] | No | Tags associated with dashboard. |\n",
"| `templating` | [object](#templating) | No | TODO docs |\n",
"| `time` | [object](#time) | No | Time range for dashboard, e.g. last 6 hours, last 7 days, etc |\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"| `refresh` | | No | Refresh rate of dashboard. Represented via interval string, e.g. \"5s\", \"1m\", \"1h\", \"1d\". |\n"
],
"file_path": "docs/sources/developers/kinds/core/dashboard/schema-reference.md",
"type": "replace",
"edit_start_line_idx": 30
} | package metrics
import (
"fmt"
"strings"
)
// urlBuilder builds the URL for calling the Azure Monitor API
type urlBuilder struct {
ResourceURI string
// Following fields will be used to generate a ResourceURI
DefaultSubscription string
Subscription string
ResourceGroup string
MetricNamespace string
ResourceName string
}
func (params *urlBuilder) buildResourceURI() string {
if params.ResourceURI != "" {
return params.ResourceURI
}
subscription := params.Subscription
if params.Subscription == "" {
subscription = params.DefaultSubscription
}
metricNamespaceArray := strings.Split(params.MetricNamespace, "/")
resourceNameArray := strings.Split(params.ResourceName, "/")
provider := metricNamespaceArray[0]
metricNamespaceArray = metricNamespaceArray[1:]
if strings.HasPrefix(strings.ToLower(params.MetricNamespace), "microsoft.storage/storageaccounts/") &&
!strings.HasSuffix(params.ResourceName, "default") {
resourceNameArray = append(resourceNameArray, "default")
}
urlArray := []string{
"/subscriptions",
subscription,
"resourceGroups",
params.ResourceGroup,
"providers",
provider,
}
for i, namespace := range metricNamespaceArray {
urlArray = append(urlArray, namespace, resourceNameArray[i])
}
resourceURI := strings.Join(urlArray, "/")
return resourceURI
}
// BuildMetricsURL checks the metric properties to see which form of the url
// should be returned
func (params *urlBuilder) BuildMetricsURL() string {
resourceURI := params.ResourceURI
// Prior to Grafana 9, we had a legacy query object rather than a resourceURI, so we manually create the resource URI
if resourceURI == "" {
resourceURI = params.buildResourceURI()
}
return fmt.Sprintf("%s/providers/microsoft.insights/metrics", resourceURI)
}
// BuildSubscriptionMetricsURL returns a URL for querying metrics for all resources in a subscription
// It requires to set a $filter and a region parameter
func BuildSubscriptionMetricsURL(subscription string) string {
return fmt.Sprintf("/subscriptions/%s/providers/microsoft.insights/metrics", subscription)
}
| pkg/tsdb/azuremonitor/metrics/url-builder.go | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.011014760471880436,
0.011014760471880436,
0.011014760471880436,
0.011014760471880436,
0
]
|
{
"id": 3,
"code_window": [
"\t\t\t\t// TODO docs\n",
"\t\t\t\tliveNow?: bool @grafanamaturity(NeedsExpertReview)\n",
"\t\t\t\t// TODO docs\n",
"\t\t\t\tweekStart?: string @grafanamaturity(NeedsExpertReview)\n",
"\n",
"\t\t\t\t// TODO docs\n",
"\t\t\t\trefresh?: string | false @grafanamaturity(NeedsExpertReview)\n",
"\t\t\t\t// Version of the JSON schema, incremented each time a Grafana update brings\n",
"\t\t\t\t// changes to said schema.\n",
"\t\t\t\t// TODO this is the existing schema numbering system. It will be replaced by Thema's themaVersion\n",
"\t\t\t\tschemaVersion: uint16 | *36\n",
"\t\t\t\t// Version of the dashboard, incremented each time the dashboard is updated.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t// Refresh rate of dashboard. Represented via interval string, e.g. \"5s\", \"1m\", \"1h\", \"1d\".\n",
"\t\t\t\trefresh?: string | false\n"
],
"file_path": "kinds/dashboard/dashboard_kind.cue",
"type": "replace",
"edit_start_line_idx": 65
} | import { cloneDeep, defaults as _defaults, filter, indexOf, isEqual, map, maxBy, pull } from 'lodash';
import { Subscription } from 'rxjs';
import {
AnnotationQuery,
AppEvent,
DashboardCursorSync,
dateTime,
dateTimeFormat,
dateTimeFormatTimeAgo,
DateTimeInput,
EventBusExtended,
EventBusSrv,
PanelModel as IPanelModel,
TimeRange,
TimeZone,
UrlQueryValue,
} from '@grafana/data';
import { RefreshEvent, TimeRangeUpdatedEvent } from '@grafana/runtime';
import { Dashboard } from '@grafana/schema';
import { DEFAULT_ANNOTATION_COLOR } from '@grafana/ui';
import { GRID_CELL_HEIGHT, GRID_CELL_VMARGIN, GRID_COLUMN_COUNT, REPEAT_DIR_VERTICAL } from 'app/core/constants';
import { contextSrv } from 'app/core/services/context_srv';
import { sortedDeepCloneWithoutNulls } from 'app/core/utils/object';
import { variableAdapters } from 'app/features/variables/adapters';
import { onTimeRangeUpdated } from 'app/features/variables/state/actions';
import { GetVariables, getVariablesByKey } from 'app/features/variables/state/selectors';
import { CoreEvents, DashboardMeta, KioskMode } from 'app/types';
import { DashboardMetaChangedEvent, DashboardPanelsChangedEvent, RenderEvent } from 'app/types/events';
import { appEvents } from '../../../core/core';
import { dispatch } from '../../../store/store';
import {
VariablesChanged,
VariablesChangedEvent,
VariablesChangedInUrl,
VariablesTimeRangeProcessDone,
} from '../../variables/types';
import { isAllVariable } from '../../variables/utils';
import { getTimeSrv } from '../services/TimeSrv';
import { mergePanels, PanelMergeInfo } from '../utils/panelMerge';
import { DashboardMigrator } from './DashboardMigrator';
import { GridPos, PanelModel } from './PanelModel';
import { TimeModel } from './TimeModel';
import { deleteScopeVars, isOnTheSameGridRow } from './utils';
export interface CloneOptions {
saveVariables?: boolean;
saveTimerange?: boolean;
message?: string;
}
export type DashboardLinkType = 'link' | 'dashboards';
export interface DashboardLink {
icon: string;
title: string;
tooltip: string;
type: DashboardLinkType;
url: string;
asDropdown: boolean;
tags: any[];
searchHits?: any[];
targetBlank: boolean;
keepTime: boolean;
includeVars: boolean;
}
export class DashboardModel implements TimeModel {
id: any;
// TODO: use propert type and fix all the places where uid is set to null
uid: any;
title: string;
description: any;
tags: any;
style: any;
timezone: any;
weekStart: any;
editable: any;
graphTooltip: DashboardCursorSync;
time: any;
liveNow: boolean;
private originalTime: any;
timepicker: any;
templating: { list: any[] };
private originalTemplating: any;
annotations: { list: AnnotationQuery[] };
refresh: any;
snapshot: any;
schemaVersion: number;
version: number;
revision: number;
links: DashboardLink[];
gnetId: any;
panels: PanelModel[];
panelInEdit?: PanelModel;
panelInView?: PanelModel;
fiscalYearStartMonth?: number;
private panelsAffectedByVariableChange: number[] | null;
private appEventsSubscription: Subscription;
private lastRefresh: number;
// ------------------
// not persisted
// ------------------
// repeat process cycles
declare meta: DashboardMeta;
events: EventBusExtended;
static nonPersistedProperties: { [str: string]: boolean } = {
events: true,
meta: true,
panels: true, // needs special handling
templating: true, // needs special handling
originalTime: true,
originalTemplating: true,
originalLibraryPanels: true,
panelInEdit: true,
panelInView: true,
getVariablesFromState: true,
formatDate: true,
appEventsSubscription: true,
panelsAffectedByVariableChange: true,
lastRefresh: true,
};
constructor(data: Dashboard, meta?: DashboardMeta, private getVariablesFromState: GetVariables = getVariablesByKey) {
this.events = new EventBusSrv();
this.id = data.id || null;
// UID is not there for newly created dashboards
this.uid = data.uid || null;
this.revision = data.revision || 1;
this.title = data.title ?? 'No Title';
this.description = data.description;
this.tags = data.tags ?? [];
this.style = data.style ?? 'dark';
this.timezone = data.timezone ?? '';
this.weekStart = data.weekStart ?? '';
this.editable = data.editable !== false;
this.graphTooltip = data.graphTooltip || 0;
this.time = data.time ?? { from: 'now-6h', to: 'now' };
this.timepicker = data.timepicker ?? {};
this.liveNow = Boolean(data.liveNow);
this.templating = this.ensureListExist(data.templating);
this.annotations = this.ensureListExist(data.annotations);
this.refresh = data.refresh;
this.snapshot = data.snapshot;
this.schemaVersion = data.schemaVersion ?? 0;
this.fiscalYearStartMonth = data.fiscalYearStartMonth ?? 0;
this.version = data.version ?? 0;
this.links = data.links ?? [];
this.gnetId = data.gnetId || null;
this.panels = map(data.panels ?? [], (panelData: any) => new PanelModel(panelData));
this.ensurePanelsHaveIds();
this.formatDate = this.formatDate.bind(this);
this.resetOriginalVariables(true);
this.resetOriginalTime();
this.initMeta(meta);
this.updateSchema(data);
this.addBuiltInAnnotationQuery();
this.sortPanelsByGridPos();
this.panelsAffectedByVariableChange = null;
this.appEventsSubscription = new Subscription();
this.lastRefresh = Date.now();
this.appEventsSubscription.add(appEvents.subscribe(VariablesChanged, this.variablesChangedHandler.bind(this)));
this.appEventsSubscription.add(
appEvents.subscribe(VariablesTimeRangeProcessDone, this.variablesTimeRangeProcessDoneHandler.bind(this))
);
this.appEventsSubscription.add(
appEvents.subscribe(VariablesChangedInUrl, this.variablesChangedInUrlHandler.bind(this))
);
}
addBuiltInAnnotationQuery() {
const found = this.annotations.list.some((item) => item.builtIn === 1);
if (found) {
return;
}
this.annotations.list.unshift({
datasource: { uid: '-- Grafana --', type: 'grafana' },
name: 'Annotations & Alerts',
type: 'dashboard',
iconColor: DEFAULT_ANNOTATION_COLOR,
enable: true,
hide: true,
builtIn: 1,
});
}
private initMeta(meta?: DashboardMeta) {
meta = meta || {};
meta.canShare = meta.canShare !== false;
meta.canSave = meta.canSave !== false;
meta.canStar = meta.canStar !== false;
meta.canEdit = meta.canEdit !== false;
meta.canDelete = meta.canDelete !== false;
meta.showSettings = meta.canEdit;
meta.canMakeEditable = meta.canSave && !this.editable;
meta.hasUnsavedFolderChange = false;
if (!this.editable) {
meta.canEdit = false;
meta.canDelete = false;
meta.canSave = false;
}
this.meta = meta;
}
// cleans meta data and other non persistent state
getSaveModelClone(options?: CloneOptions): DashboardModel {
const defaults = _defaults(options || {}, {
saveVariables: true,
saveTimerange: true,
});
// make clone
let copy: any = {};
for (const property in this) {
if (DashboardModel.nonPersistedProperties[property] || !this.hasOwnProperty(property)) {
continue;
}
copy[property] = cloneDeep(this[property]);
}
this.updateTemplatingSaveModelClone(copy, defaults);
if (!defaults.saveTimerange) {
copy.time = this.originalTime;
}
// get panel save models
copy.panels = this.getPanelSaveModels();
// sort by keys
copy = sortedDeepCloneWithoutNulls(copy);
copy.getVariables = () => copy.templating.list;
return copy;
}
/**
* This will load a new dashboard, but keep existing panels unchanged
*
* This function can be used to implement:
* 1. potentially faster loading dashboard loading
* 2. dynamic dashboard behavior
* 3. "live" dashboard editing
*
* @internal and experimental
*/
updatePanels(panels: IPanelModel[]): PanelMergeInfo {
const info = mergePanels(this.panels, panels ?? []);
if (info.changed) {
this.panels = info.panels ?? [];
this.sortPanelsByGridPos();
this.events.publish(new DashboardPanelsChangedEvent());
}
return info;
}
private getPanelSaveModels() {
return this.panels
.filter(
(panel) =>
this.isSnapshotTruthy() || !(panel.type === 'add-panel' || panel.repeatPanelId || panel.repeatedByRow)
)
.map((panel) => {
// Clean libarary panels on save
if (panel.libraryPanel) {
const { id, title, libraryPanel, gridPos } = panel;
return {
id,
title,
gridPos,
libraryPanel: {
uid: libraryPanel.uid,
name: libraryPanel.name,
},
};
}
// If we save while editing we should include the panel in edit mode instead of the
// unmodified source panel
if (this.panelInEdit && this.panelInEdit.id === panel.id) {
return this.panelInEdit.getSaveModel();
}
return panel.getSaveModel();
})
.map((model: any) => {
if (this.isSnapshotTruthy()) {
return model;
}
// Clear any scopedVars from persisted mode. This cannot be part of getSaveModel as we need to be able to copy
// panel models with preserved scopedVars, for example when going into edit mode.
delete model.scopedVars;
// Clear any repeated panels from collapsed rows
if (model.type === 'row' && model.panels && model.panels.length > 0) {
model.panels = model.panels
.filter((rowPanel: PanelModel) => !rowPanel.repeatPanelId)
.map((model: PanelModel) => {
delete model.scopedVars;
return model;
});
}
return model;
});
}
private updateTemplatingSaveModelClone(
copy: any,
defaults: { saveTimerange: boolean; saveVariables: boolean } & CloneOptions
) {
const originalVariables = this.originalTemplating;
const currentVariables = this.getVariablesFromState(this.uid);
copy.templating = {
list: currentVariables.map((variable) =>
variableAdapters.get(variable.type).getSaveModel(variable, defaults.saveVariables)
),
};
if (!defaults.saveVariables) {
for (const current of copy.templating.list) {
const original = originalVariables.find(
({ name, type }: any) => name === current.name && type === current.type
);
if (!original) {
continue;
}
if (current.type === 'adhoc') {
current.filters = original.filters;
} else {
current.current = original.current;
}
}
}
}
timeRangeUpdated(timeRange: TimeRange) {
this.events.publish(new TimeRangeUpdatedEvent(timeRange));
dispatch(onTimeRangeUpdated(this.uid, timeRange));
}
startRefresh(event: VariablesChangedEvent = { refreshAll: true, panelIds: [] }) {
this.events.publish(new RefreshEvent());
this.lastRefresh = Date.now();
if (this.panelInEdit && (event.refreshAll || event.panelIds.includes(this.panelInEdit.id))) {
this.panelInEdit.refresh();
return;
}
for (const panel of this.panels) {
if (!this.otherPanelInFullscreen(panel) && (event.refreshAll || event.panelIds.includes(panel.id))) {
panel.refresh();
}
}
}
render() {
this.events.publish(new RenderEvent());
for (const panel of this.panels) {
panel.render();
}
}
panelInitialized(panel: PanelModel) {
const lastResult = panel.getQueryRunner().getLastResult();
if (!this.otherPanelInFullscreen(panel) && !lastResult) {
panel.refresh();
}
}
otherPanelInFullscreen(panel: PanelModel) {
return (this.panelInEdit || this.panelInView) && !(panel.isViewing || panel.isEditing);
}
initEditPanel(sourcePanel: PanelModel): PanelModel {
getTimeSrv().pauseAutoRefresh();
this.panelInEdit = sourcePanel.getEditClone();
return this.panelInEdit;
}
initViewPanel(panel: PanelModel) {
this.panelInView = panel;
panel.setIsViewing(true);
}
exitViewPanel(panel: PanelModel) {
this.panelInView = undefined;
panel.setIsViewing(false);
this.refreshIfPanelsAffectedByVariableChange();
}
exitPanelEditor() {
this.panelInEdit!.destroy();
this.panelInEdit = undefined;
getTimeSrv().resumeAutoRefresh();
this.refreshIfPanelsAffectedByVariableChange();
}
private refreshIfPanelsAffectedByVariableChange() {
if (!this.panelsAffectedByVariableChange) {
return;
}
this.startRefresh({ panelIds: this.panelsAffectedByVariableChange, refreshAll: false });
this.panelsAffectedByVariableChange = null;
}
private ensurePanelsHaveIds() {
let nextPanelId = this.getNextPanelId();
for (const panel of this.panelIterator()) {
panel.id ??= nextPanelId++;
}
}
private ensureListExist(data: any = {}) {
data.list ??= [];
return data;
}
getNextPanelId() {
let max = 0;
for (const panel of this.panelIterator()) {
if (panel.id > max) {
max = panel.id;
}
}
return max + 1;
}
*panelIterator() {
for (const panel of this.panels) {
yield panel;
const rowPanels = panel.panels ?? [];
for (const rowPanel of rowPanels) {
yield rowPanel;
}
}
}
forEachPanel(callback: (panel: PanelModel, index: number) => void) {
for (let i = 0; i < this.panels.length; i++) {
callback(this.panels[i], i);
}
}
getPanelById(id: number): PanelModel | null {
if (this.panelInEdit && this.panelInEdit.id === id) {
return this.panelInEdit;
}
return this.panels.find((p) => p.id === id) ?? null;
}
canEditPanel(panel?: PanelModel | null): boolean | undefined | null {
return Boolean(this.meta.canEdit && panel && !panel.repeatPanelId && panel.type !== 'row');
}
canEditPanelById(id: number): boolean | undefined | null {
return this.canEditPanel(this.getPanelById(id));
}
addPanel(panelData: any) {
panelData.id = this.getNextPanelId();
this.panels.unshift(new PanelModel(panelData));
this.sortPanelsByGridPos();
this.events.publish(new DashboardPanelsChangedEvent());
}
updateMeta(updates: Partial<DashboardMeta>) {
this.meta = { ...this.meta, ...updates };
this.events.publish(new DashboardMetaChangedEvent());
}
makeEditable() {
this.editable = true;
this.updateMeta({
canMakeEditable: false,
canEdit: true,
canSave: true,
});
}
sortPanelsByGridPos() {
this.panels.sort((panelA, panelB) => {
if (panelA.gridPos.y === panelB.gridPos.y) {
return panelA.gridPos.x - panelB.gridPos.x;
} else {
return panelA.gridPos.y - panelB.gridPos.y;
}
});
}
clearUnsavedChanges() {
for (const panel of this.panels) {
panel.configRev = 0;
}
if (this.panelInEdit) {
// Remember that we have a saved a change in panel editor so we apply it when leaving panel edit
this.panelInEdit.hasSavedPanelEditChange = this.panelInEdit.configRev > 0;
this.panelInEdit.configRev = 0;
}
}
hasUnsavedChanges() {
const changedPanel = this.panels.find((p) => p.hasChanged);
return Boolean(changedPanel);
}
cleanUpRepeats() {
if (this.isSnapshotTruthy() || !this.hasVariables()) {
return;
}
// cleanup scopedVars
deleteScopeVars(this.panels);
const panelsToRemove = this.panels.filter((p) => (!p.repeat || p.repeatedByRow) && p.repeatPanelId);
// remove panels
pull(this.panels, ...panelsToRemove);
panelsToRemove.map((p) => p.destroy());
this.sortPanelsByGridPos();
}
processRepeats() {
if (this.isSnapshotTruthy() || !this.hasVariables()) {
return;
}
this.cleanUpRepeats();
for (let i = 0; i < this.panels.length; i++) {
const panel = this.panels[i];
if (panel.repeat) {
this.repeatPanel(panel, i);
}
}
this.sortPanelsByGridPos();
this.events.publish(new DashboardPanelsChangedEvent());
}
cleanUpRowRepeats(rowPanels: PanelModel[]) {
const panelIds = rowPanels.map((row) => row.id);
// Remove repeated panels whose parent is in this row as these will be recreated later in processRowRepeats
const panelsToRemove = rowPanels.filter((p) => !p.repeat && p.repeatPanelId && panelIds.includes(p.repeatPanelId));
pull(rowPanels, ...panelsToRemove);
pull(this.panels, ...panelsToRemove);
}
processRowRepeats(row: PanelModel) {
if (this.isSnapshotTruthy() || !this.hasVariables()) {
return;
}
let rowPanels = row.panels ?? [];
if (!row.collapsed) {
const rowPanelIndex = this.panels.findIndex((p) => p.id === row.id);
rowPanels = this.getRowPanels(rowPanelIndex);
}
this.cleanUpRowRepeats(rowPanels);
for (const panel of rowPanels) {
if (panel.repeat) {
const panelIndex = this.panels.findIndex((p) => p.id === panel.id);
this.repeatPanel(panel, panelIndex);
}
}
}
getPanelRepeatClone(sourcePanel: PanelModel, valueIndex: number, sourcePanelIndex: number) {
// if first clone return source
if (valueIndex === 0) {
return sourcePanel;
}
const m = sourcePanel.getSaveModel();
m.id = this.getNextPanelId();
const clone = new PanelModel(m);
// insert after source panel + value index
this.panels.splice(sourcePanelIndex + valueIndex, 0, clone);
clone.repeatPanelId = sourcePanel.id;
clone.repeat = undefined;
if (this.panelInView?.id === clone.id) {
clone.setIsViewing(true);
this.panelInView = clone;
}
return clone;
}
getRowRepeatClone(sourceRowPanel: PanelModel, valueIndex: number, sourcePanelIndex: number) {
// if first clone return source
if (valueIndex === 0) {
if (!sourceRowPanel.collapsed) {
const rowPanels = this.getRowPanels(sourcePanelIndex);
sourceRowPanel.panels = rowPanels;
}
return sourceRowPanel;
}
const clone = new PanelModel(sourceRowPanel.getSaveModel());
// for row clones we need to figure out panels under row to clone and where to insert clone
let rowPanels: PanelModel[], insertPos: number;
if (sourceRowPanel.collapsed) {
rowPanels = cloneDeep(sourceRowPanel.panels) ?? [];
clone.panels = rowPanels;
// insert copied row after preceding row
insertPos = sourcePanelIndex + valueIndex;
} else {
rowPanels = this.getRowPanels(sourcePanelIndex);
clone.panels = rowPanels.map((panel) => panel.getSaveModel());
// insert copied row after preceding row's panels
insertPos = sourcePanelIndex + (rowPanels.length + 1) * valueIndex;
}
this.panels.splice(insertPos, 0, clone);
this.updateRepeatedPanelIds(clone);
return clone;
}
repeatPanel(panel: PanelModel, panelIndex: number) {
const variable = this.getPanelRepeatVariable(panel);
if (!variable) {
return;
}
if (panel.type === 'row') {
this.repeatRow(panel, panelIndex, variable);
return;
}
const selectedOptions = this.getSelectedVariableOptions(variable);
const maxPerRow = panel.maxPerRow || 4;
let xPos = 0;
let yPos = panel.gridPos.y;
for (let index = 0; index < selectedOptions.length; index++) {
const option = selectedOptions[index];
let copy;
copy = this.getPanelRepeatClone(panel, index, panelIndex);
copy.scopedVars ??= {};
copy.scopedVars[variable.name] = option;
if (panel.repeatDirection === REPEAT_DIR_VERTICAL) {
if (index > 0) {
yPos += copy.gridPos.h;
}
copy.gridPos.y = yPos;
} else {
// set width based on how many are selected
// assumed the repeated panels should take up full row width
copy.gridPos.w = Math.max(GRID_COLUMN_COUNT / selectedOptions.length, GRID_COLUMN_COUNT / maxPerRow);
copy.gridPos.x = xPos;
copy.gridPos.y = yPos;
xPos += copy.gridPos.w;
// handle overflow by pushing down one row
if (xPos + copy.gridPos.w > GRID_COLUMN_COUNT) {
xPos = 0;
yPos += copy.gridPos.h;
}
}
}
// Update gridPos for panels below
const yOffset = yPos - panel.gridPos.y;
if (yOffset > 0) {
const panelBelowIndex = panelIndex + selectedOptions.length;
for (const curPanel of this.panels.slice(panelBelowIndex)) {
if (isOnTheSameGridRow(panel, curPanel)) {
continue;
}
curPanel.gridPos.y += yOffset;
}
}
}
repeatRow(panel: PanelModel, panelIndex: number, variable: any) {
const selectedOptions = this.getSelectedVariableOptions(variable);
let yPos = panel.gridPos.y;
function setScopedVars(panel: PanelModel, variableOption: any) {
panel.scopedVars ??= {};
panel.scopedVars[variable.name] = variableOption;
}
for (let optionIndex = 0; optionIndex < selectedOptions.length; optionIndex++) {
const option = selectedOptions[optionIndex];
const rowCopy = this.getRowRepeatClone(panel, optionIndex, panelIndex);
setScopedVars(rowCopy, option);
const rowHeight = this.getRowHeight(rowCopy);
const rowPanels = rowCopy.panels || [];
let panelBelowIndex;
if (panel.collapsed) {
// For collapsed row just copy its panels and set scoped vars and proper IDs
for (const rowPanel of rowPanels) {
setScopedVars(rowPanel, option);
if (optionIndex > 0) {
this.updateRepeatedPanelIds(rowPanel, true);
}
}
rowCopy.gridPos.y += optionIndex;
yPos += optionIndex;
panelBelowIndex = panelIndex + optionIndex + 1;
} else {
// insert after 'row' panel
const insertPos = panelIndex + (rowPanels.length + 1) * optionIndex + 1;
rowPanels.forEach((rowPanel: PanelModel, i: number) => {
setScopedVars(rowPanel, option);
if (optionIndex > 0) {
const cloneRowPanel = new PanelModel(rowPanel);
this.updateRepeatedPanelIds(cloneRowPanel, true);
// For exposed row additionally set proper Y grid position and add it to dashboard panels
cloneRowPanel.gridPos.y += rowHeight * optionIndex;
this.panels.splice(insertPos + i, 0, cloneRowPanel);
}
});
rowCopy.panels = [];
rowCopy.gridPos.y += rowHeight * optionIndex;
yPos += rowHeight;
panelBelowIndex = insertPos + rowPanels.length;
}
// Update gridPos for panels below if we inserted more than 1 repeated row panel
if (selectedOptions.length > 1) {
for (const panel of this.panels.slice(panelBelowIndex)) {
panel.gridPos.y += yPos;
}
}
}
}
updateRepeatedPanelIds(panel: PanelModel, repeatedByRow?: boolean) {
panel.repeatPanelId = panel.id;
panel.id = this.getNextPanelId();
if (repeatedByRow) {
panel.repeatedByRow = true;
} else {
panel.repeat = undefined;
}
return panel;
}
getSelectedVariableOptions(variable: any) {
let selectedOptions: any[];
if (isAllVariable(variable)) {
selectedOptions = variable.options.slice(1, variable.options.length);
} else {
selectedOptions = filter(variable.options, { selected: true });
}
return selectedOptions;
}
getRowHeight(rowPanel: PanelModel): number {
if (!rowPanel.panels || rowPanel.panels.length === 0) {
return 0;
}
const rowYPos = rowPanel.gridPos.y;
const positions = map(rowPanel.panels, 'gridPos');
const maxPos = maxBy(positions, (pos: GridPos) => pos.y + pos.h);
return maxPos!.y + maxPos!.h - rowYPos;
}
removePanel(panel: PanelModel) {
this.panels = this.panels.filter((item) => item !== panel);
this.events.publish(new DashboardPanelsChangedEvent());
}
removeRow(row: PanelModel, removePanels: boolean) {
const needToggle = (!removePanels && row.collapsed) || (removePanels && !row.collapsed);
if (needToggle) {
this.toggleRow(row);
}
this.removePanel(row);
}
expandRows() {
const collapsedRows = this.panels.filter((p) => p.type === 'row' && p.collapsed);
for (const row of collapsedRows) {
this.toggleRow(row);
}
}
collapseRows() {
const collapsedRows = this.panels.filter((p) => p.type === 'row' && !p.collapsed);
for (const row of collapsedRows) {
this.toggleRow(row);
}
}
isSubMenuVisible() {
return (
this.links.length > 0 ||
this.getVariables().some((variable) => variable.hide !== 2) ||
this.annotations.list.some((annotation) => !annotation.hide)
);
}
getPanelInfoById(panelId: number) {
const panelIndex = this.panels.findIndex((p) => p.id === panelId);
return panelIndex >= 0 ? { panel: this.panels[panelIndex], index: panelIndex } : null;
}
duplicatePanel(panel: PanelModel) {
const newPanel = panel.getSaveModel();
newPanel.id = this.getNextPanelId();
delete newPanel.repeat;
delete newPanel.repeatIteration;
delete newPanel.repeatPanelId;
delete newPanel.scopedVars;
if (newPanel.alert) {
delete newPanel.thresholds;
}
delete newPanel.alert;
// does it fit to the right?
if (panel.gridPos.x + panel.gridPos.w * 2 <= GRID_COLUMN_COUNT) {
newPanel.gridPos.x += panel.gridPos.w;
} else {
// add below
newPanel.gridPos.y += panel.gridPos.h;
}
this.addPanel(newPanel);
return newPanel;
}
formatDate(date: DateTimeInput, format?: string) {
return dateTimeFormat(date, {
format,
timeZone: this.getTimezone(),
});
}
destroy() {
this.appEventsSubscription.unsubscribe();
this.events.removeAllListeners();
for (const panel of this.panels) {
panel.destroy();
}
}
toggleRow(row: PanelModel) {
const rowIndex = indexOf(this.panels, row);
if (!row.collapsed) {
const rowPanels = this.getRowPanels(rowIndex);
// remove panels
pull(this.panels, ...rowPanels);
// save panel models inside row panel
row.panels = rowPanels.map((panel: PanelModel) => panel.getSaveModel());
row.collapsed = true;
if (rowPanels.some((panel) => panel.hasChanged)) {
row.configRev++;
}
// emit change event
this.events.publish(new DashboardPanelsChangedEvent());
return;
}
row.collapsed = false;
const rowPanels = row.panels ?? [];
const hasRepeat = rowPanels.some((p: PanelModel) => p.repeat);
if (rowPanels.length > 0) {
// Use first panel to figure out if it was moved or pushed
// If the panel doesn't have gridPos.y, use the row gridPos.y instead.
// This can happen for some generated dashboards.
const firstPanelYPos = rowPanels[0].gridPos.y ?? row.gridPos.y;
const yDiff = firstPanelYPos - (row.gridPos.y + row.gridPos.h);
// start inserting after row
let insertPos = rowIndex + 1;
// y max will represent the bottom y pos after all panels have been added
// needed to know home much panels below should be pushed down
let yMax = row.gridPos.y;
for (const panel of rowPanels) {
// set the y gridPos if it wasn't already set
panel.gridPos.y ?? (panel.gridPos.y = row.gridPos.y); // (Safari 13.1 lacks ??= support)
// make sure y is adjusted (in case row moved while collapsed)
panel.gridPos.y -= yDiff;
// insert after row
this.panels.splice(insertPos, 0, new PanelModel(panel));
// update insert post and y max
insertPos += 1;
yMax = Math.max(yMax, panel.gridPos.y + panel.gridPos.h);
}
const pushDownAmount = yMax - row.gridPos.y - 1;
// push panels below down
for (const panel of this.panels.slice(insertPos)) {
panel.gridPos.y += pushDownAmount;
}
row.panels = [];
if (hasRepeat) {
this.processRowRepeats(row);
}
}
// sort panels
this.sortPanelsByGridPos();
// emit change event
this.events.publish(new DashboardPanelsChangedEvent());
}
/**
* Will return all panels after rowIndex until it encounters another row
*/
getRowPanels(rowIndex: number): PanelModel[] {
const panelsBelowRow = this.panels.slice(rowIndex + 1);
const nextRowIndex = panelsBelowRow.findIndex((p) => p.type === 'row');
// Take all panels up to next row, or all panels if there are no other rows
const rowPanels = panelsBelowRow.slice(0, nextRowIndex >= 0 ? nextRowIndex : this.panels.length);
return rowPanels;
}
/** @deprecated */
on<T>(event: AppEvent<T>, callback: (payload?: T) => void) {
console.log('DashboardModel.on is deprecated use events.subscribe');
this.events.on(event, callback);
}
/** @deprecated */
off<T>(event: AppEvent<T>, callback: (payload?: T) => void) {
console.log('DashboardModel.off is deprecated');
this.events.off(event, callback);
}
cycleGraphTooltip() {
this.graphTooltip = (this.graphTooltip + 1) % 3;
}
sharedTooltipModeEnabled() {
return this.graphTooltip > 0;
}
sharedCrosshairModeOnly() {
return this.graphTooltip === 1;
}
getRelativeTime(date: DateTimeInput) {
return dateTimeFormatTimeAgo(date, {
timeZone: this.getTimezone(),
});
}
isSnapshot() {
return this.snapshot !== undefined;
}
getTimezone(): TimeZone {
return (this.timezone ? this.timezone : contextSrv?.user?.timezone) as TimeZone;
}
private updateSchema(old: any) {
const migrator = new DashboardMigrator(this);
migrator.updateSchema(old);
}
resetOriginalTime() {
this.originalTime = cloneDeep(this.time);
}
hasTimeChanged() {
const { time, originalTime } = this;
// Compare moment values vs strings values
return !(
isEqual(time, originalTime) ||
(isEqual(dateTime(time?.from), dateTime(originalTime?.from)) &&
isEqual(dateTime(time?.to), dateTime(originalTime?.to)))
);
}
resetOriginalVariables(initial = false) {
if (initial) {
this.originalTemplating = this.cloneVariablesFrom(this.templating.list);
return;
}
this.originalTemplating = this.cloneVariablesFrom(this.getVariablesFromState(this.uid));
}
hasVariableValuesChanged() {
return this.hasVariablesChanged(this.originalTemplating, this.getVariablesFromState(this.uid));
}
autoFitPanels(viewHeight: number, kioskMode?: UrlQueryValue) {
const currentGridHeight = Math.max(...this.panels.map((panel) => panel.gridPos.h + panel.gridPos.y));
const navbarHeight = 55;
const margin = 20;
const submenuHeight = 50;
let visibleHeight = viewHeight - navbarHeight - margin;
// Remove submenu height if visible
if (this.meta.submenuEnabled && !kioskMode) {
visibleHeight -= submenuHeight;
}
// add back navbar height
if (kioskMode && kioskMode !== KioskMode.TV) {
visibleHeight += navbarHeight;
}
const visibleGridHeight = Math.floor(visibleHeight / (GRID_CELL_HEIGHT + GRID_CELL_VMARGIN));
const scaleFactor = currentGridHeight / visibleGridHeight;
for (const panel of this.panels) {
panel.gridPos.y = Math.round(panel.gridPos.y / scaleFactor) || 1;
panel.gridPos.h = Math.round(panel.gridPos.h / scaleFactor) || 1;
}
}
templateVariableValueUpdated() {
this.processRepeats();
this.events.emit(CoreEvents.templateVariableValueUpdated);
}
getPanelByUrlId(panelUrlId: string) {
const panelId = parseInt(panelUrlId ?? '0', 10);
// First try to find it in a collapsed row and exand it
const collapsedPanels = this.panels.filter((p) => p.collapsed);
for (const panel of collapsedPanels) {
const hasPanel = panel.panels?.some((rp: any) => rp.id === panelId);
hasPanel && this.toggleRow(panel);
}
return this.getPanelById(panelId);
}
toggleLegendsForAll() {
const panelsWithLegends = this.panels.filter(isPanelWithLegend);
// determine if more panels are displaying legends or not
const onCount = panelsWithLegends.filter((panel) => panel.legend.show).length;
const offCount = panelsWithLegends.length - onCount;
const panelLegendsOn = onCount >= offCount;
for (const panel of panelsWithLegends) {
panel.legend.show = !panelLegendsOn;
panel.render();
}
}
getVariables() {
return this.getVariablesFromState(this.uid);
}
canEditAnnotations(dashboardUID?: string) {
let canEdit = true;
// if RBAC is enabled there are additional conditions to check
if (contextSrv.accessControlEnabled()) {
// dashboardUID is falsy when it is an organizational annotation
if (!dashboardUID) {
canEdit = !!this.meta.annotationsPermissions?.organization.canEdit;
} else {
canEdit = !!this.meta.annotationsPermissions?.dashboard.canEdit;
}
}
return this.canEditDashboard() && canEdit;
}
canDeleteAnnotations(dashboardUID?: string) {
let canDelete = true;
if (contextSrv.accessControlEnabled()) {
// dashboardUID is falsy when it is an organizational annotation
if (!dashboardUID) {
canDelete = !!this.meta.annotationsPermissions?.organization.canDelete;
} else {
canDelete = !!this.meta.annotationsPermissions?.dashboard.canDelete;
}
}
return canDelete && this.canEditDashboard();
}
canAddAnnotations() {
// When the builtin annotations are disabled, we should not add any in the UI
const found = this.annotations.list.find((item) => item.builtIn === 1);
if (found?.enable === false || !this.canEditDashboard()) {
return false;
}
// If RBAC is enabled there are additional conditions to check.
return !contextSrv.accessControlEnabled() || Boolean(this.meta.annotationsPermissions?.dashboard.canAdd);
}
canEditDashboard() {
return Boolean(this.meta.canEdit || this.meta.canMakeEditable);
}
shouldUpdateDashboardPanelFromJSON(updatedPanel: PanelModel, panel: PanelModel) {
const shouldUpdateGridPositionLayout = !isEqual(updatedPanel?.gridPos, panel?.gridPos);
if (shouldUpdateGridPositionLayout) {
this.events.publish(new DashboardPanelsChangedEvent());
}
}
getDefaultTime() {
return this.originalTime;
}
private getPanelRepeatVariable(panel: PanelModel) {
return this.getVariablesFromState(this.uid).find((variable) => variable.name === panel.repeat);
}
private isSnapshotTruthy() {
return this.snapshot;
}
private hasVariables() {
return this.getVariablesFromState(this.uid).length > 0;
}
private hasVariablesChanged(originalVariables: any[], currentVariables: any[]): boolean {
if (originalVariables.length !== currentVariables.length) {
return false;
}
const updated = currentVariables.map((variable: any) => ({
name: variable.name,
type: variable.type,
current: cloneDeep(variable.current),
filters: cloneDeep(variable.filters),
}));
return !isEqual(updated, originalVariables);
}
private cloneVariablesFrom(variables: any[]): any[] {
return variables.map((variable) => ({
name: variable.name,
type: variable.type,
current: cloneDeep(variable.current),
filters: cloneDeep(variable.filters),
}));
}
private variablesTimeRangeProcessDoneHandler(event: VariablesTimeRangeProcessDone) {
const processRepeats = event.payload.variableIds.length > 0;
this.variablesChangedHandler(new VariablesChanged({ panelIds: [], refreshAll: true }), processRepeats);
}
private variablesChangedHandler(event: VariablesChanged, processRepeats = true) {
if (processRepeats) {
this.processRepeats();
}
if (event.payload.refreshAll || getTimeSrv().isRefreshOutsideThreshold(this.lastRefresh)) {
this.startRefresh({ refreshAll: true, panelIds: [] });
return;
}
if (this.panelInEdit || this.panelInView) {
this.panelsAffectedByVariableChange = event.payload.panelIds.filter(
(id) => id !== (this.panelInEdit?.id ?? this.panelInView?.id)
);
}
this.startRefresh(event.payload);
}
private variablesChangedInUrlHandler(event: VariablesChangedInUrl) {
this.templateVariableValueUpdated();
this.startRefresh(event.payload);
}
}
function isPanelWithLegend(panel: PanelModel): panel is PanelModel & Pick<Required<PanelModel>, 'legend'> {
return Boolean(panel.legend);
}
| public/app/features/dashboard/state/DashboardModel.ts | 1 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.0026995441876351833,
0.0002546400355640799,
0.0001637191162444651,
0.00017170782666653395,
0.0003312731278128922
]
|
{
"id": 3,
"code_window": [
"\t\t\t\t// TODO docs\n",
"\t\t\t\tliveNow?: bool @grafanamaturity(NeedsExpertReview)\n",
"\t\t\t\t// TODO docs\n",
"\t\t\t\tweekStart?: string @grafanamaturity(NeedsExpertReview)\n",
"\n",
"\t\t\t\t// TODO docs\n",
"\t\t\t\trefresh?: string | false @grafanamaturity(NeedsExpertReview)\n",
"\t\t\t\t// Version of the JSON schema, incremented each time a Grafana update brings\n",
"\t\t\t\t// changes to said schema.\n",
"\t\t\t\t// TODO this is the existing schema numbering system. It will be replaced by Thema's themaVersion\n",
"\t\t\t\tschemaVersion: uint16 | *36\n",
"\t\t\t\t// Version of the dashboard, incremented each time the dashboard is updated.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t// Refresh rate of dashboard. Represented via interval string, e.g. \"5s\", \"1m\", \"1h\", \"1d\".\n",
"\t\t\t\trefresh?: string | false\n"
],
"file_path": "kinds/dashboard/dashboard_kind.cue",
"type": "replace",
"edit_start_line_idx": 65
} | import { ComponentMeta, ComponentStory } from '@storybook/react';
import React from 'react';
import { FieldValidationMessage } from './FieldValidationMessage';
import mdx from './FieldValidationMessage.mdx';
const meta: ComponentMeta<typeof FieldValidationMessage> = {
title: 'Forms/FieldValidationMessage',
component: FieldValidationMessage,
parameters: {
docs: {
page: mdx,
},
controls: {
exclude: ['className'],
},
},
args: {
horizontal: false,
children: 'Invalid input message',
},
argTypes: {
children: { name: 'message' },
},
};
export const Basic: ComponentStory<typeof FieldValidationMessage> = (args) => {
return <FieldValidationMessage horizontal={args.horizontal}>{args.children}</FieldValidationMessage>;
};
export default meta;
| packages/grafana-ui/src/components/Forms/FieldValidationMessage.story.tsx | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.00017558361287228763,
0.0001727334747556597,
0.0001714253448881209,
0.00017196248518303037,
0.000001660529051150661
]
|
{
"id": 3,
"code_window": [
"\t\t\t\t// TODO docs\n",
"\t\t\t\tliveNow?: bool @grafanamaturity(NeedsExpertReview)\n",
"\t\t\t\t// TODO docs\n",
"\t\t\t\tweekStart?: string @grafanamaturity(NeedsExpertReview)\n",
"\n",
"\t\t\t\t// TODO docs\n",
"\t\t\t\trefresh?: string | false @grafanamaturity(NeedsExpertReview)\n",
"\t\t\t\t// Version of the JSON schema, incremented each time a Grafana update brings\n",
"\t\t\t\t// changes to said schema.\n",
"\t\t\t\t// TODO this is the existing schema numbering system. It will be replaced by Thema's themaVersion\n",
"\t\t\t\tschemaVersion: uint16 | *36\n",
"\t\t\t\t// Version of the dashboard, incremented each time the dashboard is updated.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t// Refresh rate of dashboard. Represented via interval string, e.g. \"5s\", \"1m\", \"1h\", \"1d\".\n",
"\t\t\t\trefresh?: string | false\n"
],
"file_path": "kinds/dashboard/dashboard_kind.cue",
"type": "replace",
"edit_start_line_idx": 65
} | // Copyright 2019 The Xorm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xorm
func trimQuote(s string) string {
if len(s) == 0 {
return s
}
if s[0] == '`' {
s = s[1:]
}
if len(s) > 0 && s[len(s)-1] == '`' {
return s[:len(s)-1]
}
return s
}
| pkg/util/xorm/statement_quote.go | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.00017586744797881693,
0.0001744842593325302,
0.00017310107068624347,
0.0001744842593325302,
0.000001383188646286726
]
|
{
"id": 3,
"code_window": [
"\t\t\t\t// TODO docs\n",
"\t\t\t\tliveNow?: bool @grafanamaturity(NeedsExpertReview)\n",
"\t\t\t\t// TODO docs\n",
"\t\t\t\tweekStart?: string @grafanamaturity(NeedsExpertReview)\n",
"\n",
"\t\t\t\t// TODO docs\n",
"\t\t\t\trefresh?: string | false @grafanamaturity(NeedsExpertReview)\n",
"\t\t\t\t// Version of the JSON schema, incremented each time a Grafana update brings\n",
"\t\t\t\t// changes to said schema.\n",
"\t\t\t\t// TODO this is the existing schema numbering system. It will be replaced by Thema's themaVersion\n",
"\t\t\t\tschemaVersion: uint16 | *36\n",
"\t\t\t\t// Version of the dashboard, incremented each time the dashboard is updated.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t// Refresh rate of dashboard. Represented via interval string, e.g. \"5s\", \"1m\", \"1h\", \"1d\".\n",
"\t\t\t\trefresh?: string | false\n"
],
"file_path": "kinds/dashboard/dashboard_kind.cue",
"type": "replace",
"edit_start_line_idx": 65
} | // Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed 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.
/**
* given a number and a desired precision for the floating
* side, return the number at the new precision.
*
* toFloatPrecision(3.55, 1) // 3.5
* toFloatPrecision(0.04422, 2) // 0.04
* toFloatPrecision(6.24e6, 2) // 6240000.00
*
* does not support numbers that use "e" notation on toString.
*
* @param {number} number
* @param {number} precision
* @returns {number} number at new floating precision
*/
export function toFloatPrecision(number: number, precision: number): number {
const log10Length = Math.floor(Math.log10(Math.abs(number))) + 1;
const targetPrecision = precision + log10Length;
if (targetPrecision <= 0) {
return Math.trunc(number);
}
return Number(number.toPrecision(targetPrecision));
}
| packages/jaeger-ui-components/src/utils/number.tsx | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.00017712489352561533,
0.00017196731641888618,
0.0001661144633544609,
0.0001723149762256071,
0.000004335824087320361
]
|
{
"id": 4,
"code_window": [
" */\n",
" liveNow?: boolean;\n",
" panels?: Array<(Panel | RowPanel | GraphPanel | HeatmapPanel)>;\n",
" /**\n",
" * TODO docs\n",
" */\n",
" refresh?: (string | false);\n",
" /**\n",
" * Version of the current dashboard data\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" * Refresh rate of dashboard. Represented via interval string, e.g. \"5s\", \"1m\", \"1h\", \"1d\".\n"
],
"file_path": "packages/grafana-schema/src/raw/dashboard/x/dashboard_types.gen.ts",
"type": "replace",
"edit_start_line_idx": 672
} | import { cloneDeep, defaults as _defaults, filter, indexOf, isEqual, map, maxBy, pull } from 'lodash';
import { Subscription } from 'rxjs';
import {
AnnotationQuery,
AppEvent,
DashboardCursorSync,
dateTime,
dateTimeFormat,
dateTimeFormatTimeAgo,
DateTimeInput,
EventBusExtended,
EventBusSrv,
PanelModel as IPanelModel,
TimeRange,
TimeZone,
UrlQueryValue,
} from '@grafana/data';
import { RefreshEvent, TimeRangeUpdatedEvent } from '@grafana/runtime';
import { Dashboard } from '@grafana/schema';
import { DEFAULT_ANNOTATION_COLOR } from '@grafana/ui';
import { GRID_CELL_HEIGHT, GRID_CELL_VMARGIN, GRID_COLUMN_COUNT, REPEAT_DIR_VERTICAL } from 'app/core/constants';
import { contextSrv } from 'app/core/services/context_srv';
import { sortedDeepCloneWithoutNulls } from 'app/core/utils/object';
import { variableAdapters } from 'app/features/variables/adapters';
import { onTimeRangeUpdated } from 'app/features/variables/state/actions';
import { GetVariables, getVariablesByKey } from 'app/features/variables/state/selectors';
import { CoreEvents, DashboardMeta, KioskMode } from 'app/types';
import { DashboardMetaChangedEvent, DashboardPanelsChangedEvent, RenderEvent } from 'app/types/events';
import { appEvents } from '../../../core/core';
import { dispatch } from '../../../store/store';
import {
VariablesChanged,
VariablesChangedEvent,
VariablesChangedInUrl,
VariablesTimeRangeProcessDone,
} from '../../variables/types';
import { isAllVariable } from '../../variables/utils';
import { getTimeSrv } from '../services/TimeSrv';
import { mergePanels, PanelMergeInfo } from '../utils/panelMerge';
import { DashboardMigrator } from './DashboardMigrator';
import { GridPos, PanelModel } from './PanelModel';
import { TimeModel } from './TimeModel';
import { deleteScopeVars, isOnTheSameGridRow } from './utils';
export interface CloneOptions {
saveVariables?: boolean;
saveTimerange?: boolean;
message?: string;
}
export type DashboardLinkType = 'link' | 'dashboards';
export interface DashboardLink {
icon: string;
title: string;
tooltip: string;
type: DashboardLinkType;
url: string;
asDropdown: boolean;
tags: any[];
searchHits?: any[];
targetBlank: boolean;
keepTime: boolean;
includeVars: boolean;
}
export class DashboardModel implements TimeModel {
id: any;
// TODO: use propert type and fix all the places where uid is set to null
uid: any;
title: string;
description: any;
tags: any;
style: any;
timezone: any;
weekStart: any;
editable: any;
graphTooltip: DashboardCursorSync;
time: any;
liveNow: boolean;
private originalTime: any;
timepicker: any;
templating: { list: any[] };
private originalTemplating: any;
annotations: { list: AnnotationQuery[] };
refresh: any;
snapshot: any;
schemaVersion: number;
version: number;
revision: number;
links: DashboardLink[];
gnetId: any;
panels: PanelModel[];
panelInEdit?: PanelModel;
panelInView?: PanelModel;
fiscalYearStartMonth?: number;
private panelsAffectedByVariableChange: number[] | null;
private appEventsSubscription: Subscription;
private lastRefresh: number;
// ------------------
// not persisted
// ------------------
// repeat process cycles
declare meta: DashboardMeta;
events: EventBusExtended;
static nonPersistedProperties: { [str: string]: boolean } = {
events: true,
meta: true,
panels: true, // needs special handling
templating: true, // needs special handling
originalTime: true,
originalTemplating: true,
originalLibraryPanels: true,
panelInEdit: true,
panelInView: true,
getVariablesFromState: true,
formatDate: true,
appEventsSubscription: true,
panelsAffectedByVariableChange: true,
lastRefresh: true,
};
constructor(data: Dashboard, meta?: DashboardMeta, private getVariablesFromState: GetVariables = getVariablesByKey) {
this.events = new EventBusSrv();
this.id = data.id || null;
// UID is not there for newly created dashboards
this.uid = data.uid || null;
this.revision = data.revision || 1;
this.title = data.title ?? 'No Title';
this.description = data.description;
this.tags = data.tags ?? [];
this.style = data.style ?? 'dark';
this.timezone = data.timezone ?? '';
this.weekStart = data.weekStart ?? '';
this.editable = data.editable !== false;
this.graphTooltip = data.graphTooltip || 0;
this.time = data.time ?? { from: 'now-6h', to: 'now' };
this.timepicker = data.timepicker ?? {};
this.liveNow = Boolean(data.liveNow);
this.templating = this.ensureListExist(data.templating);
this.annotations = this.ensureListExist(data.annotations);
this.refresh = data.refresh;
this.snapshot = data.snapshot;
this.schemaVersion = data.schemaVersion ?? 0;
this.fiscalYearStartMonth = data.fiscalYearStartMonth ?? 0;
this.version = data.version ?? 0;
this.links = data.links ?? [];
this.gnetId = data.gnetId || null;
this.panels = map(data.panels ?? [], (panelData: any) => new PanelModel(panelData));
this.ensurePanelsHaveIds();
this.formatDate = this.formatDate.bind(this);
this.resetOriginalVariables(true);
this.resetOriginalTime();
this.initMeta(meta);
this.updateSchema(data);
this.addBuiltInAnnotationQuery();
this.sortPanelsByGridPos();
this.panelsAffectedByVariableChange = null;
this.appEventsSubscription = new Subscription();
this.lastRefresh = Date.now();
this.appEventsSubscription.add(appEvents.subscribe(VariablesChanged, this.variablesChangedHandler.bind(this)));
this.appEventsSubscription.add(
appEvents.subscribe(VariablesTimeRangeProcessDone, this.variablesTimeRangeProcessDoneHandler.bind(this))
);
this.appEventsSubscription.add(
appEvents.subscribe(VariablesChangedInUrl, this.variablesChangedInUrlHandler.bind(this))
);
}
addBuiltInAnnotationQuery() {
const found = this.annotations.list.some((item) => item.builtIn === 1);
if (found) {
return;
}
this.annotations.list.unshift({
datasource: { uid: '-- Grafana --', type: 'grafana' },
name: 'Annotations & Alerts',
type: 'dashboard',
iconColor: DEFAULT_ANNOTATION_COLOR,
enable: true,
hide: true,
builtIn: 1,
});
}
private initMeta(meta?: DashboardMeta) {
meta = meta || {};
meta.canShare = meta.canShare !== false;
meta.canSave = meta.canSave !== false;
meta.canStar = meta.canStar !== false;
meta.canEdit = meta.canEdit !== false;
meta.canDelete = meta.canDelete !== false;
meta.showSettings = meta.canEdit;
meta.canMakeEditable = meta.canSave && !this.editable;
meta.hasUnsavedFolderChange = false;
if (!this.editable) {
meta.canEdit = false;
meta.canDelete = false;
meta.canSave = false;
}
this.meta = meta;
}
// cleans meta data and other non persistent state
getSaveModelClone(options?: CloneOptions): DashboardModel {
const defaults = _defaults(options || {}, {
saveVariables: true,
saveTimerange: true,
});
// make clone
let copy: any = {};
for (const property in this) {
if (DashboardModel.nonPersistedProperties[property] || !this.hasOwnProperty(property)) {
continue;
}
copy[property] = cloneDeep(this[property]);
}
this.updateTemplatingSaveModelClone(copy, defaults);
if (!defaults.saveTimerange) {
copy.time = this.originalTime;
}
// get panel save models
copy.panels = this.getPanelSaveModels();
// sort by keys
copy = sortedDeepCloneWithoutNulls(copy);
copy.getVariables = () => copy.templating.list;
return copy;
}
/**
* This will load a new dashboard, but keep existing panels unchanged
*
* This function can be used to implement:
* 1. potentially faster loading dashboard loading
* 2. dynamic dashboard behavior
* 3. "live" dashboard editing
*
* @internal and experimental
*/
updatePanels(panels: IPanelModel[]): PanelMergeInfo {
const info = mergePanels(this.panels, panels ?? []);
if (info.changed) {
this.panels = info.panels ?? [];
this.sortPanelsByGridPos();
this.events.publish(new DashboardPanelsChangedEvent());
}
return info;
}
private getPanelSaveModels() {
return this.panels
.filter(
(panel) =>
this.isSnapshotTruthy() || !(panel.type === 'add-panel' || panel.repeatPanelId || panel.repeatedByRow)
)
.map((panel) => {
// Clean libarary panels on save
if (panel.libraryPanel) {
const { id, title, libraryPanel, gridPos } = panel;
return {
id,
title,
gridPos,
libraryPanel: {
uid: libraryPanel.uid,
name: libraryPanel.name,
},
};
}
// If we save while editing we should include the panel in edit mode instead of the
// unmodified source panel
if (this.panelInEdit && this.panelInEdit.id === panel.id) {
return this.panelInEdit.getSaveModel();
}
return panel.getSaveModel();
})
.map((model: any) => {
if (this.isSnapshotTruthy()) {
return model;
}
// Clear any scopedVars from persisted mode. This cannot be part of getSaveModel as we need to be able to copy
// panel models with preserved scopedVars, for example when going into edit mode.
delete model.scopedVars;
// Clear any repeated panels from collapsed rows
if (model.type === 'row' && model.panels && model.panels.length > 0) {
model.panels = model.panels
.filter((rowPanel: PanelModel) => !rowPanel.repeatPanelId)
.map((model: PanelModel) => {
delete model.scopedVars;
return model;
});
}
return model;
});
}
private updateTemplatingSaveModelClone(
copy: any,
defaults: { saveTimerange: boolean; saveVariables: boolean } & CloneOptions
) {
const originalVariables = this.originalTemplating;
const currentVariables = this.getVariablesFromState(this.uid);
copy.templating = {
list: currentVariables.map((variable) =>
variableAdapters.get(variable.type).getSaveModel(variable, defaults.saveVariables)
),
};
if (!defaults.saveVariables) {
for (const current of copy.templating.list) {
const original = originalVariables.find(
({ name, type }: any) => name === current.name && type === current.type
);
if (!original) {
continue;
}
if (current.type === 'adhoc') {
current.filters = original.filters;
} else {
current.current = original.current;
}
}
}
}
timeRangeUpdated(timeRange: TimeRange) {
this.events.publish(new TimeRangeUpdatedEvent(timeRange));
dispatch(onTimeRangeUpdated(this.uid, timeRange));
}
startRefresh(event: VariablesChangedEvent = { refreshAll: true, panelIds: [] }) {
this.events.publish(new RefreshEvent());
this.lastRefresh = Date.now();
if (this.panelInEdit && (event.refreshAll || event.panelIds.includes(this.panelInEdit.id))) {
this.panelInEdit.refresh();
return;
}
for (const panel of this.panels) {
if (!this.otherPanelInFullscreen(panel) && (event.refreshAll || event.panelIds.includes(panel.id))) {
panel.refresh();
}
}
}
render() {
this.events.publish(new RenderEvent());
for (const panel of this.panels) {
panel.render();
}
}
panelInitialized(panel: PanelModel) {
const lastResult = panel.getQueryRunner().getLastResult();
if (!this.otherPanelInFullscreen(panel) && !lastResult) {
panel.refresh();
}
}
otherPanelInFullscreen(panel: PanelModel) {
return (this.panelInEdit || this.panelInView) && !(panel.isViewing || panel.isEditing);
}
initEditPanel(sourcePanel: PanelModel): PanelModel {
getTimeSrv().pauseAutoRefresh();
this.panelInEdit = sourcePanel.getEditClone();
return this.panelInEdit;
}
initViewPanel(panel: PanelModel) {
this.panelInView = panel;
panel.setIsViewing(true);
}
exitViewPanel(panel: PanelModel) {
this.panelInView = undefined;
panel.setIsViewing(false);
this.refreshIfPanelsAffectedByVariableChange();
}
exitPanelEditor() {
this.panelInEdit!.destroy();
this.panelInEdit = undefined;
getTimeSrv().resumeAutoRefresh();
this.refreshIfPanelsAffectedByVariableChange();
}
private refreshIfPanelsAffectedByVariableChange() {
if (!this.panelsAffectedByVariableChange) {
return;
}
this.startRefresh({ panelIds: this.panelsAffectedByVariableChange, refreshAll: false });
this.panelsAffectedByVariableChange = null;
}
private ensurePanelsHaveIds() {
let nextPanelId = this.getNextPanelId();
for (const panel of this.panelIterator()) {
panel.id ??= nextPanelId++;
}
}
private ensureListExist(data: any = {}) {
data.list ??= [];
return data;
}
getNextPanelId() {
let max = 0;
for (const panel of this.panelIterator()) {
if (panel.id > max) {
max = panel.id;
}
}
return max + 1;
}
*panelIterator() {
for (const panel of this.panels) {
yield panel;
const rowPanels = panel.panels ?? [];
for (const rowPanel of rowPanels) {
yield rowPanel;
}
}
}
forEachPanel(callback: (panel: PanelModel, index: number) => void) {
for (let i = 0; i < this.panels.length; i++) {
callback(this.panels[i], i);
}
}
getPanelById(id: number): PanelModel | null {
if (this.panelInEdit && this.panelInEdit.id === id) {
return this.panelInEdit;
}
return this.panels.find((p) => p.id === id) ?? null;
}
canEditPanel(panel?: PanelModel | null): boolean | undefined | null {
return Boolean(this.meta.canEdit && panel && !panel.repeatPanelId && panel.type !== 'row');
}
canEditPanelById(id: number): boolean | undefined | null {
return this.canEditPanel(this.getPanelById(id));
}
addPanel(panelData: any) {
panelData.id = this.getNextPanelId();
this.panels.unshift(new PanelModel(panelData));
this.sortPanelsByGridPos();
this.events.publish(new DashboardPanelsChangedEvent());
}
updateMeta(updates: Partial<DashboardMeta>) {
this.meta = { ...this.meta, ...updates };
this.events.publish(new DashboardMetaChangedEvent());
}
makeEditable() {
this.editable = true;
this.updateMeta({
canMakeEditable: false,
canEdit: true,
canSave: true,
});
}
sortPanelsByGridPos() {
this.panels.sort((panelA, panelB) => {
if (panelA.gridPos.y === panelB.gridPos.y) {
return panelA.gridPos.x - panelB.gridPos.x;
} else {
return panelA.gridPos.y - panelB.gridPos.y;
}
});
}
clearUnsavedChanges() {
for (const panel of this.panels) {
panel.configRev = 0;
}
if (this.panelInEdit) {
// Remember that we have a saved a change in panel editor so we apply it when leaving panel edit
this.panelInEdit.hasSavedPanelEditChange = this.panelInEdit.configRev > 0;
this.panelInEdit.configRev = 0;
}
}
hasUnsavedChanges() {
const changedPanel = this.panels.find((p) => p.hasChanged);
return Boolean(changedPanel);
}
cleanUpRepeats() {
if (this.isSnapshotTruthy() || !this.hasVariables()) {
return;
}
// cleanup scopedVars
deleteScopeVars(this.panels);
const panelsToRemove = this.panels.filter((p) => (!p.repeat || p.repeatedByRow) && p.repeatPanelId);
// remove panels
pull(this.panels, ...panelsToRemove);
panelsToRemove.map((p) => p.destroy());
this.sortPanelsByGridPos();
}
processRepeats() {
if (this.isSnapshotTruthy() || !this.hasVariables()) {
return;
}
this.cleanUpRepeats();
for (let i = 0; i < this.panels.length; i++) {
const panel = this.panels[i];
if (panel.repeat) {
this.repeatPanel(panel, i);
}
}
this.sortPanelsByGridPos();
this.events.publish(new DashboardPanelsChangedEvent());
}
cleanUpRowRepeats(rowPanels: PanelModel[]) {
const panelIds = rowPanels.map((row) => row.id);
// Remove repeated panels whose parent is in this row as these will be recreated later in processRowRepeats
const panelsToRemove = rowPanels.filter((p) => !p.repeat && p.repeatPanelId && panelIds.includes(p.repeatPanelId));
pull(rowPanels, ...panelsToRemove);
pull(this.panels, ...panelsToRemove);
}
processRowRepeats(row: PanelModel) {
if (this.isSnapshotTruthy() || !this.hasVariables()) {
return;
}
let rowPanels = row.panels ?? [];
if (!row.collapsed) {
const rowPanelIndex = this.panels.findIndex((p) => p.id === row.id);
rowPanels = this.getRowPanels(rowPanelIndex);
}
this.cleanUpRowRepeats(rowPanels);
for (const panel of rowPanels) {
if (panel.repeat) {
const panelIndex = this.panels.findIndex((p) => p.id === panel.id);
this.repeatPanel(panel, panelIndex);
}
}
}
getPanelRepeatClone(sourcePanel: PanelModel, valueIndex: number, sourcePanelIndex: number) {
// if first clone return source
if (valueIndex === 0) {
return sourcePanel;
}
const m = sourcePanel.getSaveModel();
m.id = this.getNextPanelId();
const clone = new PanelModel(m);
// insert after source panel + value index
this.panels.splice(sourcePanelIndex + valueIndex, 0, clone);
clone.repeatPanelId = sourcePanel.id;
clone.repeat = undefined;
if (this.panelInView?.id === clone.id) {
clone.setIsViewing(true);
this.panelInView = clone;
}
return clone;
}
getRowRepeatClone(sourceRowPanel: PanelModel, valueIndex: number, sourcePanelIndex: number) {
// if first clone return source
if (valueIndex === 0) {
if (!sourceRowPanel.collapsed) {
const rowPanels = this.getRowPanels(sourcePanelIndex);
sourceRowPanel.panels = rowPanels;
}
return sourceRowPanel;
}
const clone = new PanelModel(sourceRowPanel.getSaveModel());
// for row clones we need to figure out panels under row to clone and where to insert clone
let rowPanels: PanelModel[], insertPos: number;
if (sourceRowPanel.collapsed) {
rowPanels = cloneDeep(sourceRowPanel.panels) ?? [];
clone.panels = rowPanels;
// insert copied row after preceding row
insertPos = sourcePanelIndex + valueIndex;
} else {
rowPanels = this.getRowPanels(sourcePanelIndex);
clone.panels = rowPanels.map((panel) => panel.getSaveModel());
// insert copied row after preceding row's panels
insertPos = sourcePanelIndex + (rowPanels.length + 1) * valueIndex;
}
this.panels.splice(insertPos, 0, clone);
this.updateRepeatedPanelIds(clone);
return clone;
}
repeatPanel(panel: PanelModel, panelIndex: number) {
const variable = this.getPanelRepeatVariable(panel);
if (!variable) {
return;
}
if (panel.type === 'row') {
this.repeatRow(panel, panelIndex, variable);
return;
}
const selectedOptions = this.getSelectedVariableOptions(variable);
const maxPerRow = panel.maxPerRow || 4;
let xPos = 0;
let yPos = panel.gridPos.y;
for (let index = 0; index < selectedOptions.length; index++) {
const option = selectedOptions[index];
let copy;
copy = this.getPanelRepeatClone(panel, index, panelIndex);
copy.scopedVars ??= {};
copy.scopedVars[variable.name] = option;
if (panel.repeatDirection === REPEAT_DIR_VERTICAL) {
if (index > 0) {
yPos += copy.gridPos.h;
}
copy.gridPos.y = yPos;
} else {
// set width based on how many are selected
// assumed the repeated panels should take up full row width
copy.gridPos.w = Math.max(GRID_COLUMN_COUNT / selectedOptions.length, GRID_COLUMN_COUNT / maxPerRow);
copy.gridPos.x = xPos;
copy.gridPos.y = yPos;
xPos += copy.gridPos.w;
// handle overflow by pushing down one row
if (xPos + copy.gridPos.w > GRID_COLUMN_COUNT) {
xPos = 0;
yPos += copy.gridPos.h;
}
}
}
// Update gridPos for panels below
const yOffset = yPos - panel.gridPos.y;
if (yOffset > 0) {
const panelBelowIndex = panelIndex + selectedOptions.length;
for (const curPanel of this.panels.slice(panelBelowIndex)) {
if (isOnTheSameGridRow(panel, curPanel)) {
continue;
}
curPanel.gridPos.y += yOffset;
}
}
}
repeatRow(panel: PanelModel, panelIndex: number, variable: any) {
const selectedOptions = this.getSelectedVariableOptions(variable);
let yPos = panel.gridPos.y;
function setScopedVars(panel: PanelModel, variableOption: any) {
panel.scopedVars ??= {};
panel.scopedVars[variable.name] = variableOption;
}
for (let optionIndex = 0; optionIndex < selectedOptions.length; optionIndex++) {
const option = selectedOptions[optionIndex];
const rowCopy = this.getRowRepeatClone(panel, optionIndex, panelIndex);
setScopedVars(rowCopy, option);
const rowHeight = this.getRowHeight(rowCopy);
const rowPanels = rowCopy.panels || [];
let panelBelowIndex;
if (panel.collapsed) {
// For collapsed row just copy its panels and set scoped vars and proper IDs
for (const rowPanel of rowPanels) {
setScopedVars(rowPanel, option);
if (optionIndex > 0) {
this.updateRepeatedPanelIds(rowPanel, true);
}
}
rowCopy.gridPos.y += optionIndex;
yPos += optionIndex;
panelBelowIndex = panelIndex + optionIndex + 1;
} else {
// insert after 'row' panel
const insertPos = panelIndex + (rowPanels.length + 1) * optionIndex + 1;
rowPanels.forEach((rowPanel: PanelModel, i: number) => {
setScopedVars(rowPanel, option);
if (optionIndex > 0) {
const cloneRowPanel = new PanelModel(rowPanel);
this.updateRepeatedPanelIds(cloneRowPanel, true);
// For exposed row additionally set proper Y grid position and add it to dashboard panels
cloneRowPanel.gridPos.y += rowHeight * optionIndex;
this.panels.splice(insertPos + i, 0, cloneRowPanel);
}
});
rowCopy.panels = [];
rowCopy.gridPos.y += rowHeight * optionIndex;
yPos += rowHeight;
panelBelowIndex = insertPos + rowPanels.length;
}
// Update gridPos for panels below if we inserted more than 1 repeated row panel
if (selectedOptions.length > 1) {
for (const panel of this.panels.slice(panelBelowIndex)) {
panel.gridPos.y += yPos;
}
}
}
}
updateRepeatedPanelIds(panel: PanelModel, repeatedByRow?: boolean) {
panel.repeatPanelId = panel.id;
panel.id = this.getNextPanelId();
if (repeatedByRow) {
panel.repeatedByRow = true;
} else {
panel.repeat = undefined;
}
return panel;
}
getSelectedVariableOptions(variable: any) {
let selectedOptions: any[];
if (isAllVariable(variable)) {
selectedOptions = variable.options.slice(1, variable.options.length);
} else {
selectedOptions = filter(variable.options, { selected: true });
}
return selectedOptions;
}
getRowHeight(rowPanel: PanelModel): number {
if (!rowPanel.panels || rowPanel.panels.length === 0) {
return 0;
}
const rowYPos = rowPanel.gridPos.y;
const positions = map(rowPanel.panels, 'gridPos');
const maxPos = maxBy(positions, (pos: GridPos) => pos.y + pos.h);
return maxPos!.y + maxPos!.h - rowYPos;
}
removePanel(panel: PanelModel) {
this.panels = this.panels.filter((item) => item !== panel);
this.events.publish(new DashboardPanelsChangedEvent());
}
removeRow(row: PanelModel, removePanels: boolean) {
const needToggle = (!removePanels && row.collapsed) || (removePanels && !row.collapsed);
if (needToggle) {
this.toggleRow(row);
}
this.removePanel(row);
}
expandRows() {
const collapsedRows = this.panels.filter((p) => p.type === 'row' && p.collapsed);
for (const row of collapsedRows) {
this.toggleRow(row);
}
}
collapseRows() {
const collapsedRows = this.panels.filter((p) => p.type === 'row' && !p.collapsed);
for (const row of collapsedRows) {
this.toggleRow(row);
}
}
isSubMenuVisible() {
return (
this.links.length > 0 ||
this.getVariables().some((variable) => variable.hide !== 2) ||
this.annotations.list.some((annotation) => !annotation.hide)
);
}
getPanelInfoById(panelId: number) {
const panelIndex = this.panels.findIndex((p) => p.id === panelId);
return panelIndex >= 0 ? { panel: this.panels[panelIndex], index: panelIndex } : null;
}
duplicatePanel(panel: PanelModel) {
const newPanel = panel.getSaveModel();
newPanel.id = this.getNextPanelId();
delete newPanel.repeat;
delete newPanel.repeatIteration;
delete newPanel.repeatPanelId;
delete newPanel.scopedVars;
if (newPanel.alert) {
delete newPanel.thresholds;
}
delete newPanel.alert;
// does it fit to the right?
if (panel.gridPos.x + panel.gridPos.w * 2 <= GRID_COLUMN_COUNT) {
newPanel.gridPos.x += panel.gridPos.w;
} else {
// add below
newPanel.gridPos.y += panel.gridPos.h;
}
this.addPanel(newPanel);
return newPanel;
}
formatDate(date: DateTimeInput, format?: string) {
return dateTimeFormat(date, {
format,
timeZone: this.getTimezone(),
});
}
destroy() {
this.appEventsSubscription.unsubscribe();
this.events.removeAllListeners();
for (const panel of this.panels) {
panel.destroy();
}
}
toggleRow(row: PanelModel) {
const rowIndex = indexOf(this.panels, row);
if (!row.collapsed) {
const rowPanels = this.getRowPanels(rowIndex);
// remove panels
pull(this.panels, ...rowPanels);
// save panel models inside row panel
row.panels = rowPanels.map((panel: PanelModel) => panel.getSaveModel());
row.collapsed = true;
if (rowPanels.some((panel) => panel.hasChanged)) {
row.configRev++;
}
// emit change event
this.events.publish(new DashboardPanelsChangedEvent());
return;
}
row.collapsed = false;
const rowPanels = row.panels ?? [];
const hasRepeat = rowPanels.some((p: PanelModel) => p.repeat);
if (rowPanels.length > 0) {
// Use first panel to figure out if it was moved or pushed
// If the panel doesn't have gridPos.y, use the row gridPos.y instead.
// This can happen for some generated dashboards.
const firstPanelYPos = rowPanels[0].gridPos.y ?? row.gridPos.y;
const yDiff = firstPanelYPos - (row.gridPos.y + row.gridPos.h);
// start inserting after row
let insertPos = rowIndex + 1;
// y max will represent the bottom y pos after all panels have been added
// needed to know home much panels below should be pushed down
let yMax = row.gridPos.y;
for (const panel of rowPanels) {
// set the y gridPos if it wasn't already set
panel.gridPos.y ?? (panel.gridPos.y = row.gridPos.y); // (Safari 13.1 lacks ??= support)
// make sure y is adjusted (in case row moved while collapsed)
panel.gridPos.y -= yDiff;
// insert after row
this.panels.splice(insertPos, 0, new PanelModel(panel));
// update insert post and y max
insertPos += 1;
yMax = Math.max(yMax, panel.gridPos.y + panel.gridPos.h);
}
const pushDownAmount = yMax - row.gridPos.y - 1;
// push panels below down
for (const panel of this.panels.slice(insertPos)) {
panel.gridPos.y += pushDownAmount;
}
row.panels = [];
if (hasRepeat) {
this.processRowRepeats(row);
}
}
// sort panels
this.sortPanelsByGridPos();
// emit change event
this.events.publish(new DashboardPanelsChangedEvent());
}
/**
* Will return all panels after rowIndex until it encounters another row
*/
getRowPanels(rowIndex: number): PanelModel[] {
const panelsBelowRow = this.panels.slice(rowIndex + 1);
const nextRowIndex = panelsBelowRow.findIndex((p) => p.type === 'row');
// Take all panels up to next row, or all panels if there are no other rows
const rowPanels = panelsBelowRow.slice(0, nextRowIndex >= 0 ? nextRowIndex : this.panels.length);
return rowPanels;
}
/** @deprecated */
on<T>(event: AppEvent<T>, callback: (payload?: T) => void) {
console.log('DashboardModel.on is deprecated use events.subscribe');
this.events.on(event, callback);
}
/** @deprecated */
off<T>(event: AppEvent<T>, callback: (payload?: T) => void) {
console.log('DashboardModel.off is deprecated');
this.events.off(event, callback);
}
cycleGraphTooltip() {
this.graphTooltip = (this.graphTooltip + 1) % 3;
}
sharedTooltipModeEnabled() {
return this.graphTooltip > 0;
}
sharedCrosshairModeOnly() {
return this.graphTooltip === 1;
}
getRelativeTime(date: DateTimeInput) {
return dateTimeFormatTimeAgo(date, {
timeZone: this.getTimezone(),
});
}
isSnapshot() {
return this.snapshot !== undefined;
}
getTimezone(): TimeZone {
return (this.timezone ? this.timezone : contextSrv?.user?.timezone) as TimeZone;
}
private updateSchema(old: any) {
const migrator = new DashboardMigrator(this);
migrator.updateSchema(old);
}
resetOriginalTime() {
this.originalTime = cloneDeep(this.time);
}
hasTimeChanged() {
const { time, originalTime } = this;
// Compare moment values vs strings values
return !(
isEqual(time, originalTime) ||
(isEqual(dateTime(time?.from), dateTime(originalTime?.from)) &&
isEqual(dateTime(time?.to), dateTime(originalTime?.to)))
);
}
resetOriginalVariables(initial = false) {
if (initial) {
this.originalTemplating = this.cloneVariablesFrom(this.templating.list);
return;
}
this.originalTemplating = this.cloneVariablesFrom(this.getVariablesFromState(this.uid));
}
hasVariableValuesChanged() {
return this.hasVariablesChanged(this.originalTemplating, this.getVariablesFromState(this.uid));
}
autoFitPanels(viewHeight: number, kioskMode?: UrlQueryValue) {
const currentGridHeight = Math.max(...this.panels.map((panel) => panel.gridPos.h + panel.gridPos.y));
const navbarHeight = 55;
const margin = 20;
const submenuHeight = 50;
let visibleHeight = viewHeight - navbarHeight - margin;
// Remove submenu height if visible
if (this.meta.submenuEnabled && !kioskMode) {
visibleHeight -= submenuHeight;
}
// add back navbar height
if (kioskMode && kioskMode !== KioskMode.TV) {
visibleHeight += navbarHeight;
}
const visibleGridHeight = Math.floor(visibleHeight / (GRID_CELL_HEIGHT + GRID_CELL_VMARGIN));
const scaleFactor = currentGridHeight / visibleGridHeight;
for (const panel of this.panels) {
panel.gridPos.y = Math.round(panel.gridPos.y / scaleFactor) || 1;
panel.gridPos.h = Math.round(panel.gridPos.h / scaleFactor) || 1;
}
}
templateVariableValueUpdated() {
this.processRepeats();
this.events.emit(CoreEvents.templateVariableValueUpdated);
}
getPanelByUrlId(panelUrlId: string) {
const panelId = parseInt(panelUrlId ?? '0', 10);
// First try to find it in a collapsed row and exand it
const collapsedPanels = this.panels.filter((p) => p.collapsed);
for (const panel of collapsedPanels) {
const hasPanel = panel.panels?.some((rp: any) => rp.id === panelId);
hasPanel && this.toggleRow(panel);
}
return this.getPanelById(panelId);
}
toggleLegendsForAll() {
const panelsWithLegends = this.panels.filter(isPanelWithLegend);
// determine if more panels are displaying legends or not
const onCount = panelsWithLegends.filter((panel) => panel.legend.show).length;
const offCount = panelsWithLegends.length - onCount;
const panelLegendsOn = onCount >= offCount;
for (const panel of panelsWithLegends) {
panel.legend.show = !panelLegendsOn;
panel.render();
}
}
getVariables() {
return this.getVariablesFromState(this.uid);
}
canEditAnnotations(dashboardUID?: string) {
let canEdit = true;
// if RBAC is enabled there are additional conditions to check
if (contextSrv.accessControlEnabled()) {
// dashboardUID is falsy when it is an organizational annotation
if (!dashboardUID) {
canEdit = !!this.meta.annotationsPermissions?.organization.canEdit;
} else {
canEdit = !!this.meta.annotationsPermissions?.dashboard.canEdit;
}
}
return this.canEditDashboard() && canEdit;
}
canDeleteAnnotations(dashboardUID?: string) {
let canDelete = true;
if (contextSrv.accessControlEnabled()) {
// dashboardUID is falsy when it is an organizational annotation
if (!dashboardUID) {
canDelete = !!this.meta.annotationsPermissions?.organization.canDelete;
} else {
canDelete = !!this.meta.annotationsPermissions?.dashboard.canDelete;
}
}
return canDelete && this.canEditDashboard();
}
canAddAnnotations() {
// When the builtin annotations are disabled, we should not add any in the UI
const found = this.annotations.list.find((item) => item.builtIn === 1);
if (found?.enable === false || !this.canEditDashboard()) {
return false;
}
// If RBAC is enabled there are additional conditions to check.
return !contextSrv.accessControlEnabled() || Boolean(this.meta.annotationsPermissions?.dashboard.canAdd);
}
canEditDashboard() {
return Boolean(this.meta.canEdit || this.meta.canMakeEditable);
}
shouldUpdateDashboardPanelFromJSON(updatedPanel: PanelModel, panel: PanelModel) {
const shouldUpdateGridPositionLayout = !isEqual(updatedPanel?.gridPos, panel?.gridPos);
if (shouldUpdateGridPositionLayout) {
this.events.publish(new DashboardPanelsChangedEvent());
}
}
getDefaultTime() {
return this.originalTime;
}
private getPanelRepeatVariable(panel: PanelModel) {
return this.getVariablesFromState(this.uid).find((variable) => variable.name === panel.repeat);
}
private isSnapshotTruthy() {
return this.snapshot;
}
private hasVariables() {
return this.getVariablesFromState(this.uid).length > 0;
}
private hasVariablesChanged(originalVariables: any[], currentVariables: any[]): boolean {
if (originalVariables.length !== currentVariables.length) {
return false;
}
const updated = currentVariables.map((variable: any) => ({
name: variable.name,
type: variable.type,
current: cloneDeep(variable.current),
filters: cloneDeep(variable.filters),
}));
return !isEqual(updated, originalVariables);
}
private cloneVariablesFrom(variables: any[]): any[] {
return variables.map((variable) => ({
name: variable.name,
type: variable.type,
current: cloneDeep(variable.current),
filters: cloneDeep(variable.filters),
}));
}
private variablesTimeRangeProcessDoneHandler(event: VariablesTimeRangeProcessDone) {
const processRepeats = event.payload.variableIds.length > 0;
this.variablesChangedHandler(new VariablesChanged({ panelIds: [], refreshAll: true }), processRepeats);
}
private variablesChangedHandler(event: VariablesChanged, processRepeats = true) {
if (processRepeats) {
this.processRepeats();
}
if (event.payload.refreshAll || getTimeSrv().isRefreshOutsideThreshold(this.lastRefresh)) {
this.startRefresh({ refreshAll: true, panelIds: [] });
return;
}
if (this.panelInEdit || this.panelInView) {
this.panelsAffectedByVariableChange = event.payload.panelIds.filter(
(id) => id !== (this.panelInEdit?.id ?? this.panelInView?.id)
);
}
this.startRefresh(event.payload);
}
private variablesChangedInUrlHandler(event: VariablesChangedInUrl) {
this.templateVariableValueUpdated();
this.startRefresh(event.payload);
}
}
function isPanelWithLegend(panel: PanelModel): panel is PanelModel & Pick<Required<PanelModel>, 'legend'> {
return Boolean(panel.legend);
}
| public/app/features/dashboard/state/DashboardModel.ts | 1 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.997525155544281,
0.08186324685811996,
0.0001656728272791952,
0.0002215461281593889,
0.25639188289642334
]
|
{
"id": 4,
"code_window": [
" */\n",
" liveNow?: boolean;\n",
" panels?: Array<(Panel | RowPanel | GraphPanel | HeatmapPanel)>;\n",
" /**\n",
" * TODO docs\n",
" */\n",
" refresh?: (string | false);\n",
" /**\n",
" * Version of the current dashboard data\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" * Refresh rate of dashboard. Represented via interval string, e.g. \"5s\", \"1m\", \"1h\", \"1d\".\n"
],
"file_path": "packages/grafana-schema/src/raw/dashboard/x/dashboard_types.gen.ts",
"type": "replace",
"edit_start_line_idx": 672
} | <div class="gf-form-group">
<div class="gf-form">
<h6>TLS/SSL Auth Details</h6>
<info-popover mode="header">TLS/SSL certificates are encrypted and stored in the Grafana database.</info-popover>
</div>
<div ng-if="current.jsonData.tlsAuthWithCACert">
<div class="gf-form-inline">
<div class="gf-form gf-form--v-stretch"><label class="gf-form-label width-7">CA Cert</label></div>
<div class="gf-form gf-form--grow" ng-if="!current.secureJsonFields.tlsCACert">
<textarea
rows="7"
class="gf-form-input gf-form-textarea"
ng-model="current.secureJsonData.tlsCACert"
placeholder="Begins with -----BEGIN CERTIFICATE-----"
></textarea>
</div>
<div class="gf-form" ng-if="current.secureJsonFields.tlsCACert">
<input type="text" class="gf-form-input max-width-12" disabled="disabled" value="configured" />
<button
type="reset"
aria-label="Reset CA Cert"
class="btn btn-secondary gf-form-btn"
ng-click="current.secureJsonFields.tlsCACert = false"
>
reset
</button>
</div>
</div>
</div>
<div ng-if="current.jsonData.tlsAuth">
<div class="gf-form-inline">
<div class="gf-form gf-form--v-stretch"><label class="gf-form-label width-7">Client Cert</label></div>
<div class="gf-form gf-form--grow" ng-if="!current.secureJsonFields.tlsClientCert">
<textarea
rows="7"
class="gf-form-input gf-form-textarea"
ng-model="current.secureJsonData.tlsClientCert"
placeholder="Begins with -----BEGIN CERTIFICATE-----"
required
></textarea>
</div>
<div class="gf-form" ng-if="current.secureJsonFields.tlsClientCert">
<input type="text" class="gf-form-input max-width-12" disabled="disabled" value="configured" />
<button
class="btn btn-secondary gf-form-btn"
aria-label="Reset Client Cert"
type="reset"
ng-click="current.secureJsonFields.tlsClientCert = false"
>
reset
</button>
</div>
</div>
<div class="gf-form-inline">
<div class="gf-form gf-form--v-stretch"><label class="gf-form-label width-7">Client Key</label></div>
<div class="gf-form gf-form--grow" ng-if="!current.secureJsonFields.tlsClientKey">
<textarea
rows="7"
class="gf-form-input gf-form-textarea"
ng-model="current.secureJsonData.tlsClientKey"
placeholder="Begins with -----BEGIN RSA PRIVATE KEY-----"
required
></textarea>
</div>
<div class="gf-form" ng-if="current.secureJsonFields.tlsClientKey">
<input type="text" class="gf-form-input max-width-12" disabled="disabled" value="configured" />
<button
class="btn btn-secondary gf-form-btn"
type="reset"
aria-label="Reset Client Key"
ng-click="current.secureJsonFields.tlsClientKey = false"
>
reset
</button>
</div>
</div>
</div>
</div>
| public/app/angular/partials/tls_auth_settings.html | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.00017649150686338544,
0.00017418999050278217,
0.0001696330145932734,
0.0001746102498145774,
0.0000021021378415753134
]
|
{
"id": 4,
"code_window": [
" */\n",
" liveNow?: boolean;\n",
" panels?: Array<(Panel | RowPanel | GraphPanel | HeatmapPanel)>;\n",
" /**\n",
" * TODO docs\n",
" */\n",
" refresh?: (string | false);\n",
" /**\n",
" * Version of the current dashboard data\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" * Refresh rate of dashboard. Represented via interval string, e.g. \"5s\", \"1m\", \"1h\", \"1d\".\n"
],
"file_path": "packages/grafana-schema/src/raw/dashboard/x/dashboard_types.gen.ts",
"type": "replace",
"edit_start_line_idx": 672
} | <svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" viewBox="0 0 24 24"><path d="M16,8V5c0-0.6-0.4-1-1-1h-1V3h1c0.6,0,1-0.4,1-1s-0.4-1-1-1h-4.8C8.5,1,6.9,2,6.1,3.6C5.9,4,6.1,4.6,6.6,4.9c0.5,0.2,1.1,0,1.3-0.4C8.3,3.6,9.2,3,10.2,3H12v1h-1c-0.6,0-1,0.4-1,1v3c-1.7,0-3,1.3-3,3v9c0,1.7,1.3,3,3,3h6c1.7,0,3-1.3,3-3v-9C19,9.3,17.7,8,16,8z M12,6h2v2h-2V6z M14,17h-2c-0.6,0-1-0.4-1-1s0.4-1,1-1h2c0.6,0,1,0.4,1,1S14.6,17,14,17z"/></svg> | public/img/icons/solid/sanitizer-alt.svg | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.00016588496509939432,
0.00016588496509939432,
0.00016588496509939432,
0.00016588496509939432,
0
]
|
{
"id": 4,
"code_window": [
" */\n",
" liveNow?: boolean;\n",
" panels?: Array<(Panel | RowPanel | GraphPanel | HeatmapPanel)>;\n",
" /**\n",
" * TODO docs\n",
" */\n",
" refresh?: (string | false);\n",
" /**\n",
" * Version of the current dashboard data\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" * Refresh rate of dashboard. Represented via interval string, e.g. \"5s\", \"1m\", \"1h\", \"1d\".\n"
],
"file_path": "packages/grafana-schema/src/raw/dashboard/x/dashboard_types.gen.ts",
"type": "replace",
"edit_start_line_idx": 672
} | // π This was machine generated. Do not edit. π
//
// Frame[0] {
// "custom": {
// "resultType": "exemplar"
// },
// "executedQueryString": "Expr: histogram_quantile(0.99, sum(rate(traces_spanmetrics_duration_seconds_bucket[15s])) by (le))\nStep: 15s"
// }
// Name: exemplar
// Dimensions: 14 Fields by 62 Rows
// +-----------------------------------+-----------------+--------------------------------------------+----------------+-------------------+-------------------+----------------+----------------+--------------------+----------------+------------------+-----------------+-------------------+----------------------------------+
// | Name: Time | Name: Value | Name: __name__ | Name: group | Name: http_method | Name: http_target | Name: instance | Name: le | Name: service | Name: source | Name: span_kind | Name: span_name | Name: span_status | Name: traceID |
// | Labels: | Labels: | Labels: | Labels: | Labels: | Labels: | Labels: | Labels: | Labels: | Labels: | Labels: | Labels: | Labels: | Labels: |
// | Type: []time.Time | Type: []float64 | Type: []string | Type: []string | Type: []string | Type: []string | Type: []string | Type: []string | Type: []string | Type: []string | Type: []string | Type: []string | Type: []string | Type: []string |
// +-----------------------------------+-----------------+--------------------------------------------+----------------+-------------------+-------------------+----------------+----------------+--------------------+----------------+------------------+-----------------+-------------------+----------------------------------+
// | 2022-06-01 12:28:31.809 +0000 UTC | 0.001162 | traces_spanmetrics_duration_seconds_bucket | mythical | | | f1c32fe505c3 | 0.002 | mythical-server | tempo | SPAN_KIND_CLIENT | pg.query:INSERT | STATUS_CODE_ERROR | 94809f37ec6cc984f2eb2b14a9f8036e |
// | 2022-06-01 12:28:36.81 +0000 UTC | 0.134971 | traces_spanmetrics_duration_seconds_bucket | mythical | | | f1c32fe505c3 | 0.256 | mythical-requester | tempo | SPAN_KIND_CLIENT | requester | STATUS_CODE_OK | 46e15ae41852149068aeb26c64643c29 |
// | 2022-06-01 12:28:36.81 +0000 UTC | 0.090381 | traces_spanmetrics_duration_seconds_bucket | mythical | POST | /loki/api/v1/push | f1c32fe505c3 | 0.128 | mythical-server | tempo | SPAN_KIND_CLIENT | HTTP POST | STATUS_CODE_OK | 46e15ae41852149068aeb26c64643c29 |
// | 2022-06-01 12:28:36.81 +0000 UTC | 0.029188 | traces_spanmetrics_duration_seconds_bucket | mythical | GET | /manticore | f1c32fe505c3 | 0.032 | mythical-server | tempo | SPAN_KIND_SERVER | GET /:endpoint | STATUS_CODE_OK | 1e58dc2083eceb454846f9ab343a79ff |
// | 2022-06-01 12:28:41.809 +0000 UTC | 0.05719 | traces_spanmetrics_duration_seconds_bucket | mythical | | | f1c32fe505c3 | 0.064 | mythical-requester | tempo | SPAN_KIND_CLIENT | requester | STATUS_CODE_OK | d6ff032e85e6e5719a1f6b923042765f |
// | 2022-06-01 12:28:46.809 +0000 UTC | 0.071953 | traces_spanmetrics_duration_seconds_bucket | mythical | | | f1c32fe505c3 | 0.128 | mythical-requester | tempo | SPAN_KIND_CLIENT | requester | STATUS_CODE_OK | b12280a11924d98f7001f9b03779c6bc |
// | 2022-06-01 12:28:46.809 +0000 UTC | 0.041812 | traces_spanmetrics_duration_seconds_bucket | mythical | GET | /unicorn | f1c32fe505c3 | 0.064 | mythical-server | tempo | SPAN_KIND_SERVER | GET /:endpoint | STATUS_CODE_OK | b12280a11924d98f7001f9b03779c6bc |
// | 2022-06-01 12:28:56.809 +0000 UTC | 0.013244 | traces_spanmetrics_duration_seconds_bucket | mythical | | | f1c32fe505c3 | 0.016 | mythical-requester | tempo | SPAN_KIND_CLIENT | log_to_loki | STATUS_CODE_OK | 43cd491719146ad9c706d73b4870512c |
// | 2022-06-01 12:29:06.809 +0000 UTC | 0.070504 | traces_spanmetrics_duration_seconds_bucket | mythical | | | f1c32fe505c3 | 0.128 | mythical-requester | tempo | SPAN_KIND_CLIENT | requester | STATUS_CODE_OK | e08c737b2dc96959a8dda2cb76c91de7 |
// | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
// +-----------------------------------+-----------------+--------------------------------------------+----------------+-------------------+-------------------+----------------+----------------+--------------------+----------------+------------------+-----------------+-------------------+----------------------------------+
//
//
// π This was machine generated. Do not edit. π
{
"status": 200,
"frames": [
{
"schema": {
"name": "exemplar",
"meta": {
"custom": {
"resultType": "exemplar"
},
"executedQueryString": "Expr: histogram_quantile(0.99, sum(rate(traces_spanmetrics_duration_seconds_bucket[15s])) by (le))\nStep: 15s"
},
"fields": [
{
"name": "Time",
"type": "time",
"typeInfo": {
"frame": "time.Time"
}
},
{
"name": "Value",
"type": "number",
"typeInfo": {
"frame": "float64"
}
},
{
"name": "__name__",
"type": "string",
"typeInfo": {
"frame": "string"
}
},
{
"name": "group",
"type": "string",
"typeInfo": {
"frame": "string"
}
},
{
"name": "http_method",
"type": "string",
"typeInfo": {
"frame": "string"
}
},
{
"name": "http_target",
"type": "string",
"typeInfo": {
"frame": "string"
}
},
{
"name": "instance",
"type": "string",
"typeInfo": {
"frame": "string"
}
},
{
"name": "le",
"type": "string",
"typeInfo": {
"frame": "string"
}
},
{
"name": "service",
"type": "string",
"typeInfo": {
"frame": "string"
}
},
{
"name": "source",
"type": "string",
"typeInfo": {
"frame": "string"
}
},
{
"name": "span_kind",
"type": "string",
"typeInfo": {
"frame": "string"
}
},
{
"name": "span_name",
"type": "string",
"typeInfo": {
"frame": "string"
}
},
{
"name": "span_status",
"type": "string",
"typeInfo": {
"frame": "string"
}
},
{
"name": "traceID",
"type": "string",
"typeInfo": {
"frame": "string"
}
}
]
},
"data": {
"values": [
[
1654086511809,
1654086516810,
1654086516810,
1654086516810,
1654086521809,
1654086526809,
1654086526809,
1654086536809,
1654086546809,
1654086546809,
1654086546809,
1654086561810,
1654086566809,
1654086566809,
1654086571809,
1654086576810,
1654086576810,
1654086586809,
1654086591809,
1654086591809,
1654086601809,
1654086606809,
1654086616810,
1654086621809,
1654086626810,
1654086631809,
1654086636809,
1654086641809,
1654086646809,
1654086651809,
1654086651809,
1654086661809,
1654086666809,
1654086666809,
1654086676809,
1654086676809,
1654086686809,
1654086696809,
1654086701809,
1654086701809,
1654086706809,
1654086716809,
1654086716809,
1654086721809,
1654086721809,
1654086731809,
1654086731809,
1654086741809,
1654086741809,
1654086746809,
1654086751809,
1654086761809,
1654086761809,
1654086766809,
1654086766809,
1654086776809,
1654086786809,
1654086786809,
1654086791809,
1654086796809,
1654086801809,
1654086801809
],
[
0.001162,
0.134971,
0.090381,
0.029188,
0.05719,
0.071953,
0.041812,
0.013244,
0.070504,
0.038753,
0.010491,
0.01785,
0.074616,
0.046192,
0.067413,
0.038985,
0.010387,
0.055778,
0.090068,
0.026474,
0.020916,
0.051105,
0.010103,
0.038904,
0.069116,
0.036012,
0.06704,
0.007759,
0.046809,
0.076668,
0.01864,
0.037142,
0.066299,
0.008877,
0.072569,
0.038946,
0.010457,
0.021391,
0.089991,
0.049446,
0.011579,
0.068599,
0.039792,
0.067805,
0.010759,
0.099291,
0.039441,
0.06673,
0.03671,
0.008554,
0.039395,
0.071128,
0.010549,
0.043282,
0.014027,
0.072983,
0.070787,
0.009928,
0.037937,
0.010333,
0.067877,
0.038846
],
[
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket"
],
[
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical"
],
[
"",
"",
"POST",
"GET",
"",
"",
"GET",
"",
"",
"GET",
"",
"",
"",
"",
"",
"GET",
"",
"",
"",
"GET",
"",
"",
"",
"GET",
"",
"GET",
"",
"",
"GET",
"",
"",
"",
"",
"",
"",
"POST",
"",
"POST",
"",
"",
"POST",
"",
"GET",
"",
"",
"",
"",
"",
"GET",
"POST",
"GET",
"",
"",
"POST",
"",
"",
"",
"",
"GET",
"",
"",
""
],
[
"",
"",
"/loki/api/v1/push",
"/manticore",
"",
"",
"/unicorn",
"",
"",
"/manticore",
"",
"",
"",
"",
"",
"/manticore",
"",
"",
"",
"/manticore",
"",
"",
"",
"/manticore",
"",
"/unicorn",
"",
"",
"/unicorn",
"",
"",
"",
"",
"",
"",
"/loki/api/v1/push",
"",
"/loki/api/v1/push",
"",
"",
"/beholder",
"",
"/manticore",
"",
"",
"",
"",
"",
"/manticore",
"/loki/api/v1/push",
"/manticore",
"",
"",
"/loki/api/v1/push",
"",
"",
"",
"",
"/manticore",
"",
"",
""
],
[
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3"
],
[
"0.002",
"0.256",
"0.128",
"0.032",
"0.064",
"0.128",
"0.064",
"0.016",
"0.128",
"0.064",
"0.016",
"0.032",
"0.128",
"0.064",
"0.128",
"0.064",
"0.016",
"0.064",
"0.128",
"0.032",
"0.032",
"0.064",
"0.016",
"0.064",
"0.128",
"0.064",
"0.128",
"0.008",
"0.064",
"0.128",
"0.032",
"0.064",
"0.128",
"0.016",
"0.128",
"0.064",
"0.016",
"0.032",
"0.128",
"0.064",
"0.016",
"0.128",
"0.064",
"0.128",
"0.016",
"0.128",
"0.064",
"0.128",
"0.064",
"0.016",
"0.064",
"0.128",
"0.016",
"0.064",
"0.016",
"0.128",
"0.128",
"0.016",
"0.064",
"0.016",
"0.128",
"0.064"
],
[
"mythical-server",
"mythical-requester",
"mythical-server",
"mythical-server",
"mythical-requester",
"mythical-requester",
"mythical-server",
"mythical-requester",
"mythical-requester",
"mythical-server",
"mythical-server",
"mythical-requester",
"mythical-requester",
"mythical-server",
"mythical-requester",
"mythical-server",
"mythical-server",
"mythical-requester",
"mythical-requester",
"mythical-server",
"mythical-requester",
"mythical-requester",
"mythical-requester",
"mythical-server",
"mythical-requester",
"mythical-server",
"mythical-requester",
"mythical-requester",
"mythical-server",
"mythical-requester",
"mythical-server",
"mythical-server",
"mythical-requester",
"mythical-server",
"mythical-requester",
"mythical-server",
"mythical-server",
"mythical-server",
"mythical-requester",
"mythical-requester",
"mythical-server",
"mythical-requester",
"mythical-server",
"mythical-requester",
"mythical-requester",
"mythical-requester",
"mythical-server",
"mythical-requester",
"mythical-server",
"mythical-server",
"mythical-server",
"mythical-requester",
"mythical-requester",
"mythical-server",
"mythical-requester",
"mythical-requester",
"mythical-requester",
"mythical-server",
"mythical-server",
"mythical-server",
"mythical-requester",
"mythical-server"
],
[
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo"
],
[
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_SERVER",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_SERVER",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_SERVER",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_SERVER",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_SERVER",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_SERVER",
"SPAN_KIND_CLIENT",
"SPAN_KIND_SERVER",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_SERVER",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_UNSPECIFIED",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_SERVER",
"SPAN_KIND_CLIENT",
"SPAN_KIND_SERVER",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_SERVER",
"SPAN_KIND_CLIENT",
"SPAN_KIND_SERVER",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_SERVER",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_UNSPECIFIED"
],
[
"pg.query:INSERT",
"requester",
"HTTP POST",
"GET /:endpoint",
"requester",
"requester",
"GET /:endpoint",
"log_to_loki",
"requester",
"GET /:endpoint",
"pg.query:INSERT",
"log_to_loki",
"requester",
"dns.lookup",
"requester",
"GET /:endpoint",
"pg.query:DELETE",
"requester",
"requester",
"GET /:endpoint",
"requester",
"requester",
"log_to_loki",
"GET /:endpoint",
"requester",
"GET /:endpoint",
"requester",
"log_to_loki",
"GET /:endpoint",
"requester",
"dns.lookup",
"pg.query:INSERT",
"requester",
"tcp.connect",
"requester",
"HTTP POST",
"pg.query:INSERT",
"HTTP POST",
"requester",
"requester",
"POST /:endpoint",
"requester",
"GET /:endpoint",
"requester",
"requester",
"requester",
"pg.query:SELECT",
"requester",
"GET /:endpoint",
"HTTP POST",
"GET /:endpoint",
"requester",
"requester",
"HTTP POST",
"log_to_loki",
"requester",
"requester",
"pg.query:SELECT",
"GET /:endpoint",
"pg.query:DELETE",
"requester",
"tcp.connect"
],
[
"STATUS_CODE_ERROR",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_UNSET",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_UNSET",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_UNSET",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_UNSET",
"STATUS_CODE_UNSET",
"STATUS_CODE_OK",
"STATUS_CODE_UNSET",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_UNSET",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_UNSET",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_UNSET",
"STATUS_CODE_OK",
"STATUS_CODE_UNSET",
"STATUS_CODE_OK",
"STATUS_CODE_UNSET"
],
[
"94809f37ec6cc984f2eb2b14a9f8036e",
"46e15ae41852149068aeb26c64643c29",
"46e15ae41852149068aeb26c64643c29",
"1e58dc2083eceb454846f9ab343a79ff",
"d6ff032e85e6e5719a1f6b923042765f",
"b12280a11924d98f7001f9b03779c6bc",
"b12280a11924d98f7001f9b03779c6bc",
"43cd491719146ad9c706d73b4870512c",
"e08c737b2dc96959a8dda2cb76c91de7",
"654d578991bcc53c7de88912a8660488",
"8dec2e77ca64f1cc665afc43b3b1623f",
"e5f765faeb401c335355e0bb79e33b83",
"68d98aae947863f11a7863cd92421038",
"61386de633427db6bb2e5fd216518b3c",
"a17f9f61386f57e7ef85acedc120f82",
"3b4e33abe16c115448759924138cc775",
"ccfb65171f9957871c792f9e7ba4caf0",
"62110ace7888d4e116a0d6182e3ef880",
"1c5d32e0675734a7d86c6146cfef54e1",
"ee885d6d0fa1949978667532d7b50b40",
"45128087f18fb412c24394ed10826446",
"3855df04789862c55b23ca3726fd700a",
"ff6a99aa5fd60f6fbcf0f838164f87ea",
"ca2f23783ee1c390e446f02f7a27cf4",
"2699255777b784b20c8e42bb7889f607",
"72c7ff318a7bb17b6e38aa0f4e94c955",
"78b31a3856158fb296920170f15b2663",
"e81a28f6ee9b468cdac757b825b17623",
"a5277cb54e46140aa3ae489109e1ebc8",
"9ed79aa36a4c6b4c53c7f54e77e6489c",
"9ed79aa36a4c6b4c53c7f54e77e6489c",
"5ec0bc7cc644f654c04190b1cc16d39",
"2d6bde392e5b69cb55588219ce605cbc",
"7c42490bd4361a83bb8ee827b89387ae",
"1b9024f2c2042d52b82d22c36597ec3f",
"1b9024f2c2042d52b82d22c36597ec3f",
"da0d4ef26ef65b5d9c446a51b8662895",
"b1a28a72cc2a4991b2cec793530d605",
"c642d0d7df516be0390080402991b79f",
"a05d1517c61ea0c4ab76b39ab645c9b6",
"2dc68b746bbd6c6958f25c3dbb1ea110",
"ec7dc9dd4096d36ebf564427bf30abc8",
"da805bfda5683c80b9a5538c17346217",
"3835f629b97ac7869de9a839b1e2bf2a",
"1f2e6add2566d120c876e5e4f4602432",
"efa3c8aa7380ae77e734f6f655d9c782",
"312e6ef8f9d9b4ffbb4470e772f43660",
"135989a5bb785b94d339caf672590634",
"a58a30a5caee0a451e7b1ae24bc1e33e",
"d4c096aa222e1016b67de881f80978d8",
"3eefbe3d5fb80a96325688a69c5597e3",
"5384591d9cd576d73f86cbe1803d2a46",
"4f1660168b2dcf5a40474d08a587e8dd",
"bd11e06766d5a045d69b201a9c442258",
"60d05233bc4ccb745055ef19af359686",
"a3374ca45cd256cc5bdb6f482c0a2856",
"a30c5021f274710636e84eca64343b4",
"54b4e0377ac7c101278b68134853562a",
"32dfe6e357ffbb98e7148104e2d660a4",
"a11a727138a3de7ca030687340bd19b0",
"a11c1d3d300f07b1e5d688e96069f76b",
"83bf586cc62842c3187106bb40a6793d"
]
]
}
}
]
} | pkg/tsdb/prometheus/testdata/exemplar.result.golden.jsonc | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.00017741411284077913,
0.000171276435139589,
0.00016485074593219906,
0.00017148404731415212,
0.000002354512389501906
]
|
{
"id": 5,
"code_window": [
"\n",
"\t// TODO docs\n",
"\tLiveNow *bool `json:\"liveNow,omitempty\"`\n",
"\tPanels *[]interface{} `json:\"panels,omitempty\"`\n",
"\n",
"\t// TODO docs\n",
"\tRefresh *interface{} `json:\"refresh,omitempty\"`\n",
"\n",
"\t// Version of the current dashboard data\n",
"\tRevision int `json:\"revision\"`\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// Refresh rate of dashboard. Represented via interval string, e.g. \"5s\", \"1m\", \"1h\", \"1d\".\n"
],
"file_path": "pkg/kinds/dashboard/dashboard_types_gen.go",
"type": "replace",
"edit_start_line_idx": 242
} | import { getPanelPlugin } from '@grafana/data/test/__mocks__/pluginMocks';
import { setContextSrv } from '../../../../core/services/context_srv';
import { PanelModel } from '../../state/PanelModel';
import { createDashboardModelFixture, createPanelJSONFixture } from '../../state/__fixtures__/dashboardFixtures';
import { hasChanges, ignoreChanges } from './DashboardPrompt';
function getDefaultDashboardModel() {
return createDashboardModelFixture({
refresh: false,
panels: [
createPanelJSONFixture({
id: 1,
type: 'graph',
gridPos: { x: 0, y: 0, w: 24, h: 6 },
legend: { show: true, sortDesc: false }, // TODO legend is marked as a non-persisted field
}),
{
id: 2,
type: 'row',
gridPos: { x: 0, y: 6, w: 24, h: 2 },
collapsed: true,
panels: [
{ id: 3, type: 'graph', gridPos: { x: 0, y: 6, w: 12, h: 2 } },
{ id: 4, type: 'graph', gridPos: { x: 12, y: 6, w: 12, h: 2 } },
],
},
{ id: 5, type: 'row', gridPos: { x: 0, y: 6, w: 1, h: 1 }, collapsed: false, panels: [] },
],
});
}
function getTestContext() {
const contextSrv: any = { isSignedIn: true, isEditor: true };
setContextSrv(contextSrv);
const dash = getDefaultDashboardModel();
const original = dash.getSaveModelClone();
return { dash, original, contextSrv };
}
describe('DashboardPrompt', () => {
it('No changes should not have changes', () => {
const { original, dash } = getTestContext();
expect(hasChanges(dash, original)).toBe(false);
});
it('Simple change should be registered', () => {
const { original, dash } = getTestContext();
dash.title = 'google';
expect(hasChanges(dash, original)).toBe(true);
});
it('Should ignore a lot of changes', () => {
const { original, dash } = getTestContext();
dash.time = { from: '1h' };
dash.refresh = true;
dash.schemaVersion = 10;
expect(hasChanges(dash, original)).toBe(false);
});
it('Should ignore row collapse change', () => {
const { original, dash } = getTestContext();
dash.toggleRow(dash.panels[1]);
expect(hasChanges(dash, original)).toBe(false);
});
it('Should ignore panel legend changes', () => {
const { original, dash } = getTestContext();
dash.panels[0]!.legend!.sortDesc = true;
dash.panels[0]!.legend!.sort = 'avg';
expect(hasChanges(dash, original)).toBe(false);
});
it('Should ignore panel repeats', () => {
const { original, dash } = getTestContext();
dash.panels.push(new PanelModel({ repeatPanelId: 10 }));
expect(hasChanges(dash, original)).toBe(false);
});
describe('ignoreChanges', () => {
describe('when called without original dashboard', () => {
it('then it should return true', () => {
const { dash } = getTestContext();
expect(ignoreChanges(dash, null)).toBe(true);
});
});
describe('when called without current dashboard', () => {
it('then it should return true', () => {
const { original } = getTestContext();
expect(ignoreChanges(null, original)).toBe(true);
});
});
describe('when called for a viewer without save permissions', () => {
it('then it should return true', () => {
const { contextSrv } = getTestContext();
const dash = createDashboardModelFixture({}, { canSave: false });
const original = dash.getSaveModelClone();
contextSrv.isEditor = false;
expect(ignoreChanges(dash, original)).toBe(true);
});
});
describe('when called for a viewer with save permissions', () => {
it('then it should return undefined', () => {
const { contextSrv } = getTestContext();
const dash = createDashboardModelFixture({}, { canSave: true });
const original = dash.getSaveModelClone();
contextSrv.isEditor = false;
expect(ignoreChanges(dash, original)).toBe(undefined);
});
});
describe('when called for an user that is not signed in', () => {
it('then it should return true', () => {
const { contextSrv } = getTestContext();
const dash = createDashboardModelFixture({}, { canSave: true });
const original = dash.getSaveModelClone();
contextSrv.isSignedIn = false;
expect(ignoreChanges(dash, original)).toBe(true);
});
});
describe('when called with fromScript', () => {
it('then it should return true', () => {
const dash = createDashboardModelFixture({}, { canSave: true, fromScript: true, fromFile: undefined });
const original = dash.getSaveModelClone();
expect(ignoreChanges(dash, original)).toBe(true);
});
});
it('Should ignore panel schema migrations', () => {
const { original, dash } = getTestContext();
const plugin = getPanelPlugin({}).setMigrationHandler((panel) => {
delete (panel as any).legend;
return { option1: 'Aasd' };
});
dash.panels[0].pluginLoaded(plugin);
expect(hasChanges(dash, original)).toBe(false);
});
describe('when called with fromFile', () => {
it('then it should return true', () => {
const dash = createDashboardModelFixture({}, { canSave: true, fromScript: undefined, fromFile: true });
const original = dash.getSaveModelClone();
expect(ignoreChanges(dash, original)).toBe(true);
});
});
describe('when called with canSave but without fromScript and fromFile', () => {
it('then it should return false', () => {
const dash = createDashboardModelFixture({}, { canSave: true, fromScript: undefined, fromFile: undefined });
const original = dash.getSaveModelClone();
expect(ignoreChanges(dash, original)).toBe(undefined);
});
});
});
});
| public/app/features/dashboard/components/DashboardPrompt/DashboardPrompt.test.tsx | 1 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.0014899373054504395,
0.00041512702591717243,
0.00016891089035198092,
0.00028849035152234137,
0.0003221111837774515
]
|
{
"id": 5,
"code_window": [
"\n",
"\t// TODO docs\n",
"\tLiveNow *bool `json:\"liveNow,omitempty\"`\n",
"\tPanels *[]interface{} `json:\"panels,omitempty\"`\n",
"\n",
"\t// TODO docs\n",
"\tRefresh *interface{} `json:\"refresh,omitempty\"`\n",
"\n",
"\t// Version of the current dashboard data\n",
"\tRevision int `json:\"revision\"`\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// Refresh rate of dashboard. Represented via interval string, e.g. \"5s\", \"1m\", \"1h\", \"1d\".\n"
],
"file_path": "pkg/kinds/dashboard/dashboard_types_gen.go",
"type": "replace",
"edit_start_line_idx": 242
} | import { Observable } from 'rxjs';
import {
DataQuery,
DataQueryRequest,
DataSourceApi,
DataSourceRef,
getDefaultTimeRange,
LoadingState,
PanelData,
DataTopic,
} from '@grafana/data';
import { getDashboardSrv } from 'app/features/dashboard/services/DashboardSrv';
import { QueryRunnerOptions } from 'app/features/query/state/PanelQueryRunner';
import { DashboardQuery, SHARED_DASHBOARD_QUERY } from './types';
export function isSharedDashboardQuery(datasource: string | DataSourceRef | DataSourceApi | null) {
if (!datasource) {
// default datasource
return false;
}
if (typeof datasource === 'string') {
return datasource === SHARED_DASHBOARD_QUERY;
}
if ('meta' in datasource) {
return datasource.meta.name === SHARED_DASHBOARD_QUERY || datasource.uid === SHARED_DASHBOARD_QUERY;
}
return datasource.uid === SHARED_DASHBOARD_QUERY;
}
export function runSharedRequest(options: QueryRunnerOptions, query: DashboardQuery): Observable<PanelData> {
return new Observable<PanelData>((subscriber) => {
const dashboard = getDashboardSrv().getCurrent();
const listenToPanelId = getPanelIdFromQuery(options.queries);
if (!listenToPanelId) {
subscriber.next(getQueryError('Missing panel reference ID'));
return undefined;
}
const listenToPanel = dashboard?.getPanelById(listenToPanelId);
if (!listenToPanel) {
subscriber.next(getQueryError('Unknown Panel: ' + listenToPanelId));
return undefined;
}
const listenToRunner = listenToPanel.getQueryRunner();
const subscription = listenToRunner
.getData({
withTransforms: Boolean(query?.withTransforms),
withFieldConfig: false,
})
.subscribe({
next: (data: PanelData) => {
// Use annotation data for series
if (query?.topic === DataTopic.Annotations) {
data = {
...data,
series: data.annotations ?? [],
annotations: undefined, // remove annotations
};
}
subscriber.next(data);
},
});
// If we are in fullscreen the other panel will not execute any queries
// So we have to trigger it from here
if (!listenToPanel.isInView) {
const { datasource, targets } = listenToPanel;
const modified = {
...options,
datasource,
panelId: listenToPanelId,
queries: targets,
};
listenToRunner.run(modified);
}
return () => {
subscription.unsubscribe();
};
});
}
function getPanelIdFromQuery(queries: DataQuery[]): number | undefined {
if (!queries || !queries.length) {
return undefined;
}
return (queries[0] as DashboardQuery).panelId;
}
function getQueryError(msg: string): PanelData {
return {
state: LoadingState.Error,
series: [],
request: {} as DataQueryRequest,
error: { message: msg },
timeRange: getDefaultTimeRange(),
};
}
| public/app/plugins/datasource/dashboard/runSharedRequest.ts | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.0012374776415526867,
0.0003951934922952205,
0.00017024289991240948,
0.00017211504746228456,
0.0003779972321353853
]
|
{
"id": 5,
"code_window": [
"\n",
"\t// TODO docs\n",
"\tLiveNow *bool `json:\"liveNow,omitempty\"`\n",
"\tPanels *[]interface{} `json:\"panels,omitempty\"`\n",
"\n",
"\t// TODO docs\n",
"\tRefresh *interface{} `json:\"refresh,omitempty\"`\n",
"\n",
"\t// Version of the current dashboard data\n",
"\tRevision int `json:\"revision\"`\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// Refresh rate of dashboard. Represented via interval string, e.g. \"5s\", \"1m\", \"1h\", \"1d\".\n"
],
"file_path": "pkg/kinds/dashboard/dashboard_types_gen.go",
"type": "replace",
"edit_start_line_idx": 242
} | import angular from 'angular';
const coreModule = angular.module('grafana.core', ['ngRoute']);
// legacy modules
const angularModules = [
coreModule,
angular.module('grafana.controllers', []),
angular.module('grafana.directives', []),
angular.module('grafana.factories', []),
angular.module('grafana.services', []),
angular.module('grafana.filters', []),
angular.module('grafana.routes', []),
];
export { angularModules, coreModule };
export default coreModule;
| public/app/angular/core_module.ts | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.00017444600234739482,
0.0001711260701995343,
0.00016780612349975854,
0.0001711260701995343,
0.0000033199394238181412
]
|
{
"id": 5,
"code_window": [
"\n",
"\t// TODO docs\n",
"\tLiveNow *bool `json:\"liveNow,omitempty\"`\n",
"\tPanels *[]interface{} `json:\"panels,omitempty\"`\n",
"\n",
"\t// TODO docs\n",
"\tRefresh *interface{} `json:\"refresh,omitempty\"`\n",
"\n",
"\t// Version of the current dashboard data\n",
"\tRevision int `json:\"revision\"`\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// Refresh rate of dashboard. Represented via interval string, e.g. \"5s\", \"1m\", \"1h\", \"1d\".\n"
],
"file_path": "pkg/kinds/dashboard/dashboard_types_gen.go",
"type": "replace",
"edit_start_line_idx": 242
} | package grafanaplugin
composableKinds: PanelCfg: lineage: {
seqs: [
{
schemas: [
{
PanelOptions: {
foo: string
} @cuetsy(kind="interface")
},
]
},
]
}
| pkg/plugins/manager/testdata/valid-model-panel/composable.cue | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.0001723456080071628,
0.00017009129805956036,
0.0001678369881119579,
0.00017009129805956036,
0.000002254309947602451
]
|
{
"id": 6,
"code_window": [
" ],\n",
" \"currentVersion\": [\n",
" 0,\n",
" 0\n",
" ],\n",
" \"grafanaMaturityCount\": 141,\n",
" \"lineageIsGroup\": false,\n",
" \"links\": {\n",
" \"docs\": \"https://grafana.com/docs/grafana/next/developers/kinds/core/dashboard/schema-reference\",\n",
" \"go\": \"https://github.com/grafana/grafana/tree/main/pkg/kinds/dashboard\",\n",
" \"schema\": \"https://github.com/grafana/grafana/tree/main/kinds/dashboard/dashboard_kind.cue\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"grafanaMaturityCount\": 140,\n"
],
"file_path": "pkg/kindsys/report.json",
"type": "replace",
"edit_start_line_idx": 285
} | // Code generated - EDITING IS FUTILE. DO NOT EDIT.
//
// Generated by:
// kinds/gen.go
// Using jennies:
// GoTypesJenny
// LatestJenny
//
// Run 'make gen-cue' from repository root to regenerate.
package dashboard
// Defines values for Style.
const (
StyleDark Style = "dark"
StyleLight Style = "light"
)
// Defines values for Timezone.
const (
TimezoneBrowser Timezone = "browser"
TimezoneEmpty Timezone = ""
TimezoneUtc Timezone = "utc"
)
// Defines values for CursorSync.
const (
CursorSyncN0 CursorSync = 0
CursorSyncN1 CursorSync = 1
CursorSyncN2 CursorSync = 2
)
// Defines values for LinkType.
const (
LinkTypeDashboards LinkType = "dashboards"
LinkTypeLink LinkType = "link"
)
// Defines values for FieldColorModeId.
const (
FieldColorModeIdContinuousGrYlRd FieldColorModeId = "continuous-GrYlRd"
FieldColorModeIdFixed FieldColorModeId = "fixed"
FieldColorModeIdPaletteClassic FieldColorModeId = "palette-classic"
FieldColorModeIdPaletteSaturated FieldColorModeId = "palette-saturated"
FieldColorModeIdThresholds FieldColorModeId = "thresholds"
)
// Defines values for FieldColorSeriesByMode.
const (
FieldColorSeriesByModeLast FieldColorSeriesByMode = "last"
FieldColorSeriesByModeMax FieldColorSeriesByMode = "max"
FieldColorSeriesByModeMin FieldColorSeriesByMode = "min"
)
// Defines values for GraphPanelType.
const (
GraphPanelTypeGraph GraphPanelType = "graph"
)
// Defines values for HeatmapPanelType.
const (
HeatmapPanelTypeHeatmap HeatmapPanelType = "heatmap"
)
// Defines values for LoadingState.
const (
LoadingStateDone LoadingState = "Done"
LoadingStateError LoadingState = "Error"
LoadingStateLoading LoadingState = "Loading"
LoadingStateNotStarted LoadingState = "NotStarted"
LoadingStateStreaming LoadingState = "Streaming"
)
// Defines values for MappingType.
const (
MappingTypeRange MappingType = "range"
MappingTypeRegex MappingType = "regex"
MappingTypeSpecial MappingType = "special"
MappingTypeValue MappingType = "value"
)
// Defines values for PanelRepeatDirection.
const (
PanelRepeatDirectionH PanelRepeatDirection = "h"
PanelRepeatDirectionV PanelRepeatDirection = "v"
)
// Defines values for RowPanelType.
const (
RowPanelTypeRow RowPanelType = "row"
)
// Defines values for SpecialValueMapOptionsMatch.
const (
SpecialValueMapOptionsMatchFalse SpecialValueMapOptionsMatch = "false"
SpecialValueMapOptionsMatchTrue SpecialValueMapOptionsMatch = "true"
)
// Defines values for SpecialValueMatch.
const (
SpecialValueMatchEmpty SpecialValueMatch = "empty"
SpecialValueMatchFalse SpecialValueMatch = "false"
SpecialValueMatchNan SpecialValueMatch = "nan"
SpecialValueMatchNull SpecialValueMatch = "null"
SpecialValueMatchNullNan SpecialValueMatch = "null+nan"
SpecialValueMatchTrue SpecialValueMatch = "true"
)
// Defines values for ThresholdsMode.
const (
ThresholdsModeAbsolute ThresholdsMode = "absolute"
ThresholdsModePercentage ThresholdsMode = "percentage"
)
// Defines values for VariableHide.
const (
VariableHideN0 VariableHide = 0
VariableHideN1 VariableHide = 1
VariableHideN2 VariableHide = 2
)
// Defines values for VariableType.
const (
VariableTypeAdhoc VariableType = "adhoc"
VariableTypeConstant VariableType = "constant"
VariableTypeCustom VariableType = "custom"
VariableTypeDatasource VariableType = "datasource"
VariableTypeInterval VariableType = "interval"
VariableTypeQuery VariableType = "query"
VariableTypeSystem VariableType = "system"
VariableTypeTextbox VariableType = "textbox"
)
// TODO docs
// FROM: AnnotationQuery in grafana-data/src/types/annotations.ts
type AnnotationQuery struct {
BuiltIn int `json:"builtIn"`
// Datasource to use for annotation.
Datasource struct {
Type *string `json:"type,omitempty"`
Uid *string `json:"uid,omitempty"`
} `json:"datasource"`
// Whether annotation is enabled.
Enable bool `json:"enable"`
// Whether to hide annotation.
Hide *bool `json:"hide,omitempty"`
// Annotation icon color.
IconColor *string `json:"iconColor,omitempty"`
// Name of annotation.
Name *string `json:"name,omitempty"`
// Query for annotation data.
RawQuery *string `json:"rawQuery,omitempty"`
ShowIn int `json:"showIn"`
// TODO docs
Target *AnnotationTarget `json:"target,omitempty"`
Type string `json:"type"`
}
// TODO docs
type AnnotationTarget struct {
Limit int64 `json:"limit"`
MatchAny bool `json:"matchAny"`
Tags []string `json:"tags"`
Type string `json:"type"`
}
// Dashboard defines model for Dashboard.
type Dashboard struct {
// TODO docs
Annotations *struct {
List *[]AnnotationQuery `json:"list,omitempty"`
} `json:"annotations,omitempty"`
// Description of dashboard.
Description *string `json:"description,omitempty"`
// Whether a dashboard is editable or not.
Editable bool `json:"editable"`
// The month that the fiscal year starts on. 0 = January, 11 = December
FiscalYearStartMonth *int `json:"fiscalYearStartMonth,omitempty"`
GnetId *string `json:"gnetId,omitempty"`
// 0 for no shared crosshair or tooltip (default).
// 1 for shared crosshair.
// 2 for shared crosshair AND shared tooltip.
GraphTooltip CursorSync `json:"graphTooltip"`
// Unique numeric identifier for the dashboard.
// TODO must isolate or remove identifiers local to a Grafana instance...?
Id *int64 `json:"id,omitempty"`
// TODO docs
Links *[]Link `json:"links,omitempty"`
// TODO docs
LiveNow *bool `json:"liveNow,omitempty"`
Panels *[]interface{} `json:"panels,omitempty"`
// TODO docs
Refresh *interface{} `json:"refresh,omitempty"`
// Version of the current dashboard data
Revision int `json:"revision"`
// Version of the JSON schema, incremented each time a Grafana update brings
// changes to said schema.
// TODO this is the existing schema numbering system. It will be replaced by Thema's themaVersion
SchemaVersion int `json:"schemaVersion"`
// TODO docs
Snapshot *Snapshot `json:"snapshot,omitempty"`
// Theme of dashboard.
Style Style `json:"style"`
// Tags associated with dashboard.
Tags *[]string `json:"tags,omitempty"`
// TODO docs
Templating *struct {
List *[]VariableModel `json:"list,omitempty"`
} `json:"templating,omitempty"`
// Time range for dashboard, e.g. last 6 hours, last 7 days, etc
Time *struct {
From string `json:"from"`
To string `json:"to"`
} `json:"time,omitempty"`
// TODO docs
// TODO this appears to be spread all over in the frontend. Concepts will likely need tidying in tandem with schema changes
Timepicker *struct {
// Whether timepicker is collapsed or not.
Collapse bool `json:"collapse"`
// Whether timepicker is enabled or not.
Enable bool `json:"enable"`
// Whether timepicker is visible or not.
Hidden bool `json:"hidden"`
// Selectable intervals for auto-refresh.
RefreshIntervals []string `json:"refresh_intervals"`
// TODO docs
TimeOptions []string `json:"time_options"`
} `json:"timepicker,omitempty"`
// Timezone of dashboard,
Timezone *Timezone `json:"timezone,omitempty"`
// Title of dashboard.
Title *string `json:"title,omitempty"`
// Unique dashboard identifier that can be generated by anyone. string (8-40)
Uid *string `json:"uid,omitempty"`
// Version of the dashboard, incremented each time the dashboard is updated.
Version *int `json:"version,omitempty"`
// TODO docs
WeekStart *string `json:"weekStart,omitempty"`
}
// Theme of dashboard.
type Style string
// Timezone of dashboard,
type Timezone string
// 0 for no shared crosshair or tooltip (default).
// 1 for shared crosshair.
// 2 for shared crosshair AND shared tooltip.
type CursorSync int
// FROM public/app/features/dashboard/state/Models.ts - ish
// TODO docs
type Link struct {
AsDropdown bool `json:"asDropdown"`
Icon string `json:"icon"`
IncludeVars bool `json:"includeVars"`
KeepTime bool `json:"keepTime"`
Tags []string `json:"tags"`
TargetBlank bool `json:"targetBlank"`
Title string `json:"title"`
Tooltip string `json:"tooltip"`
// TODO docs
Type LinkType `json:"type"`
Url string `json:"url"`
}
// TODO docs
type LinkType string
// Ref to a DataSource instance
type DataSourceRef struct {
// The plugin type-id
Type *string `json:"type,omitempty"`
// Specific datasource instance
Uid *string `json:"uid,omitempty"`
}
// DynamicConfigValue defines model for DynamicConfigValue.
type DynamicConfigValue struct {
Id string `json:"id"`
Value *interface{} `json:"value,omitempty"`
}
// TODO docs
type FieldColor struct {
// Stores the fixed color value if mode is fixed
FixedColor *string `json:"fixedColor,omitempty"`
// The main color scheme mode
Mode interface{} `json:"mode"`
// TODO docs
SeriesBy *FieldColorSeriesByMode `json:"seriesBy,omitempty"`
}
// TODO docs
type FieldColorModeId string
// TODO docs
type FieldColorSeriesByMode string
// FieldConfig defines model for FieldConfig.
type FieldConfig struct {
// TODO docs
Color *FieldColor `json:"color,omitempty"`
// custom is specified by the PanelFieldConfig field
// in panel plugin schemas.
Custom *map[string]interface{} `json:"custom,omitempty"`
// Significant digits (for display)
Decimals *float32 `json:"decimals,omitempty"`
// Human readable field metadata
Description *string `json:"description,omitempty"`
// The display value for this field. This supports template variables blank is auto
DisplayName *string `json:"displayName,omitempty"`
// This can be used by data sources that return and explicit naming structure for values and labels
// When this property is configured, this value is used rather than the default naming strategy.
DisplayNameFromDS *string `json:"displayNameFromDS,omitempty"`
// True if data source field supports ad-hoc filters
Filterable *bool `json:"filterable,omitempty"`
// The behavior when clicking on a result
Links *[]interface{} `json:"links,omitempty"`
// Convert input values into a display string
Mappings *[]ValueMapping `json:"mappings,omitempty"`
Max *float32 `json:"max,omitempty"`
Min *float32 `json:"min,omitempty"`
// Alternative to empty string
NoValue *string `json:"noValue,omitempty"`
// An explicit path to the field in the datasource. When the frame meta includes a path,
// This will default to `${frame.meta.path}/${field.name}
//
// When defined, this value can be used as an identifier within the datasource scope, and
// may be used to update the results
Path *string `json:"path,omitempty"`
Thresholds *ThresholdsConfig `json:"thresholds,omitempty"`
// Numeric Options
Unit *string `json:"unit,omitempty"`
// True if data source can write a value to the path. Auth/authz are supported separately
Writeable *bool `json:"writeable,omitempty"`
}
// FieldConfigSource defines model for FieldConfigSource.
type FieldConfigSource struct {
Defaults FieldConfig `json:"defaults"`
Overrides []struct {
Matcher MatcherConfig `json:"matcher"`
Properties []DynamicConfigValue `json:"properties"`
} `json:"overrides"`
}
// Support for legacy graph and heatmap panels.
type GraphPanel struct {
// @deprecated this is part of deprecated graph panel
Legend *struct {
Show bool `json:"show"`
Sort *string `json:"sort,omitempty"`
SortDesc *bool `json:"sortDesc,omitempty"`
} `json:"legend,omitempty"`
Type GraphPanelType `json:"type"`
}
// GraphPanelType defines model for GraphPanel.Type.
type GraphPanelType string
// GridPos defines model for GridPos.
type GridPos struct {
// Panel
H int `json:"h"`
// true if fixed
Static *bool `json:"static,omitempty"`
// Panel
W int `json:"w"`
// Panel x
X int `json:"x"`
// Panel y
Y int `json:"y"`
}
// HeatmapPanel defines model for HeatmapPanel.
type HeatmapPanel struct {
Type HeatmapPanelType `json:"type"`
}
// HeatmapPanelType defines model for HeatmapPanel.Type.
type HeatmapPanelType string
// LoadingState defines model for LoadingState.
type LoadingState string
// TODO docs
type MappingType string
// MatcherConfig defines model for MatcherConfig.
type MatcherConfig struct {
Id string `json:"id"`
Options *interface{} `json:"options,omitempty"`
}
// Dashboard panels. Panels are canonically defined inline
// because they share a version timeline with the dashboard
// schema; they do not evolve independently.
type Panel struct {
// The datasource used in all targets.
Datasource *struct {
Type *string `json:"type,omitempty"`
Uid *string `json:"uid,omitempty"`
} `json:"datasource,omitempty"`
// Description.
Description *string `json:"description,omitempty"`
FieldConfig FieldConfigSource `json:"fieldConfig"`
GridPos *GridPos `json:"gridPos,omitempty"`
// TODO docs
Id *int `json:"id,omitempty"`
// TODO docs
// TODO tighter constraint
Interval *string `json:"interval,omitempty"`
// Panel links.
// TODO fill this out - seems there are a couple variants?
Links *[]Link `json:"links,omitempty"`
// TODO docs
MaxDataPoints *float32 `json:"maxDataPoints,omitempty"`
// options is specified by the PanelOptions field in panel
// plugin schemas.
Options map[string]interface{} `json:"options"`
// FIXME this almost certainly has to be changed in favor of scuemata versions
PluginVersion *string `json:"pluginVersion,omitempty"`
// Name of template variable to repeat for.
Repeat *string `json:"repeat,omitempty"`
// Direction to repeat in if 'repeat' is set.
// "h" for horizontal, "v" for vertical.
// TODO this is probably optional
RepeatDirection PanelRepeatDirection `json:"repeatDirection"`
// Id of the repeating panel.
RepeatPanelId *int64 `json:"repeatPanelId,omitempty"`
// TODO docs
Tags *[]string `json:"tags,omitempty"`
// TODO docs
Targets *[]Target `json:"targets,omitempty"`
// TODO docs - seems to be an old field from old dashboard alerts?
Thresholds *[]interface{} `json:"thresholds,omitempty"`
// TODO docs
// TODO tighter constraint
TimeFrom *string `json:"timeFrom,omitempty"`
// TODO docs
TimeRegions *[]interface{} `json:"timeRegions,omitempty"`
// TODO docs
// TODO tighter constraint
TimeShift *string `json:"timeShift,omitempty"`
// Panel title.
Title *string `json:"title,omitempty"`
Transformations []Transformation `json:"transformations"`
// Whether to display the panel without a background.
Transparent bool `json:"transparent"`
// The panel plugin type id. May not be empty.
Type string `json:"type"`
}
// Direction to repeat in if 'repeat' is set.
// "h" for horizontal, "v" for vertical.
// TODO this is probably optional
type PanelRepeatDirection string
// TODO docs
type RangeMap struct {
Options struct {
// to and from are `number | null` in current ts, really not sure what to do
From float64 `json:"from"`
// TODO docs
Result ValueMappingResult `json:"result"`
To float64 `json:"to"`
} `json:"options"`
Type struct {
// Embedded struct due to allOf(#/components/schemas/MappingType)
MappingType `yaml:",inline"`
// Embedded fields due to inline allOf schema
} `json:"type"`
}
// TODO docs
type RegexMap struct {
Options struct {
Pattern string `json:"pattern"`
// TODO docs
Result ValueMappingResult `json:"result"`
} `json:"options"`
Type struct {
// Embedded struct due to allOf(#/components/schemas/MappingType)
MappingType `yaml:",inline"`
// Embedded fields due to inline allOf schema
} `json:"type"`
}
// Row panel
type RowPanel struct {
Collapsed bool `json:"collapsed"`
// Name of default datasource.
Datasource *struct {
Type *string `json:"type,omitempty"`
Uid *string `json:"uid,omitempty"`
} `json:"datasource,omitempty"`
GridPos *GridPos `json:"gridPos,omitempty"`
Id int `json:"id"`
Panels []interface{} `json:"panels"`
// Name of template variable to repeat for.
Repeat *string `json:"repeat,omitempty"`
Title *string `json:"title,omitempty"`
Type RowPanelType `json:"type"`
}
// RowPanelType defines model for RowPanel.Type.
type RowPanelType string
// TODO docs
type Snapshot struct {
// TODO docs
Created string `json:"created"`
// TODO docs
Expires string `json:"expires"`
// TODO docs
External bool `json:"external"`
// TODO docs
ExternalUrl string `json:"externalUrl"`
// TODO docs
Id int `json:"id"`
// TODO docs
Key string `json:"key"`
// TODO docs
Name string `json:"name"`
// TODO docs
OrgId int `json:"orgId"`
// TODO docs
Updated string `json:"updated"`
// TODO docs
Url *string `json:"url,omitempty"`
// TODO docs
UserId int `json:"userId"`
}
// TODO docs
type SpecialValueMap struct {
Options struct {
Match SpecialValueMapOptionsMatch `json:"match"`
Pattern string `json:"pattern"`
// TODO docs
Result ValueMappingResult `json:"result"`
} `json:"options"`
Type struct {
// Embedded struct due to allOf(#/components/schemas/MappingType)
MappingType `yaml:",inline"`
// Embedded fields due to inline allOf schema
} `json:"type"`
}
// SpecialValueMapOptionsMatch defines model for SpecialValueMap.Options.Match.
type SpecialValueMapOptionsMatch string
// TODO docs
type SpecialValueMatch string
// Schema for panel targets is specified by datasource
// plugins. We use a placeholder definition, which the Go
// schema loader either left open/as-is with the Base
// variant of the Dashboard and Panel families, or filled
// with types derived from plugins in the Instance variant.
// When working directly from CUE, importers can extend this
// type directly to achieve the same effect.
type Target map[string]interface{}
// TODO docs
type Threshold struct {
// TODO docs
Color string `json:"color"`
// TODO docs
// TODO are the values here enumerable into a disjunction?
// Some seem to be listed in typescript comment
State *string `json:"state,omitempty"`
// TODO docs
// FIXME the corresponding typescript field is required/non-optional, but nulls currently appear here when serializing -Infinity to JSON
Value *float32 `json:"value,omitempty"`
}
// ThresholdsConfig defines model for ThresholdsConfig.
type ThresholdsConfig struct {
Mode ThresholdsMode `json:"mode"`
// Must be sorted by 'value', first value is always -Infinity
Steps []Threshold `json:"steps"`
}
// ThresholdsMode defines model for ThresholdsMode.
type ThresholdsMode string
// TODO docs
// FIXME this is extremely underspecfied; wasn't obvious which typescript types corresponded to it
type Transformation struct {
Id string `json:"id"`
Options map[string]interface{} `json:"options"`
}
// TODO docs
type ValueMap struct {
Options map[string]ValueMappingResult `json:"options"`
Type struct {
// Embedded struct due to allOf(#/components/schemas/MappingType)
MappingType `yaml:",inline"`
// Embedded fields due to inline allOf schema
} `json:"type"`
}
// TODO docs
type ValueMapping interface{}
// TODO docs
type ValueMappingResult struct {
Color *string `json:"color,omitempty"`
Icon *string `json:"icon,omitempty"`
Index *int32 `json:"index,omitempty"`
Text *string `json:"text,omitempty"`
}
// VariableHide defines model for VariableHide.
type VariableHide int
// FROM: packages/grafana-data/src/types/templateVars.ts
// TODO docs
// TODO what about what's in public/app/features/types.ts?
// TODO there appear to be a lot of different kinds of [template] vars here? if so need a disjunction
type VariableModel struct {
// Ref to a DataSource instance
Datasource *DataSourceRef `json:"datasource,omitempty"`
Description *string `json:"description,omitempty"`
Error *map[string]interface{} `json:"error,omitempty"`
Global bool `json:"global"`
Hide VariableHide `json:"hide"`
Id string `json:"id"`
Index int `json:"index"`
Label *string `json:"label,omitempty"`
Name string `json:"name"`
// TODO: Move this into a separated QueryVariableModel type
Query *interface{} `json:"query,omitempty"`
RootStateKey *string `json:"rootStateKey,omitempty"`
SkipUrlSync bool `json:"skipUrlSync"`
State LoadingState `json:"state"`
// FROM: packages/grafana-data/src/types/templateVars.ts
// TODO docs
// TODO this implies some wider pattern/discriminated union, probably?
Type VariableType `json:"type"`
}
// FROM: packages/grafana-data/src/types/templateVars.ts
// TODO docs
// TODO this implies some wider pattern/discriminated union, probably?
type VariableType string
| pkg/kinds/dashboard/dashboard_types_gen.go | 1 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.004798158071935177,
0.0003098889719694853,
0.00016080719069577754,
0.0001677647087490186,
0.0006477512652054429
]
|
{
"id": 6,
"code_window": [
" ],\n",
" \"currentVersion\": [\n",
" 0,\n",
" 0\n",
" ],\n",
" \"grafanaMaturityCount\": 141,\n",
" \"lineageIsGroup\": false,\n",
" \"links\": {\n",
" \"docs\": \"https://grafana.com/docs/grafana/next/developers/kinds/core/dashboard/schema-reference\",\n",
" \"go\": \"https://github.com/grafana/grafana/tree/main/pkg/kinds/dashboard\",\n",
" \"schema\": \"https://github.com/grafana/grafana/tree/main/kinds/dashboard/dashboard_kind.cue\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"grafanaMaturityCount\": 140,\n"
],
"file_path": "pkg/kindsys/report.json",
"type": "replace",
"edit_start_line_idx": 285
} | package common
// TODO docs
DataSourceJsonData: {
authType?: string
defaultRegion?: string
profile?: string
manageAlerts?: bool
alertmanagerUid?: string
} @cuetsy(kind="interface")
| packages/grafana-schema/src/common/data_source.cue | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.0001703224697848782,
0.00016957407933659852,
0.00016882570344023407,
0.00016957407933659852,
7.483831723220646e-7
]
|
{
"id": 6,
"code_window": [
" ],\n",
" \"currentVersion\": [\n",
" 0,\n",
" 0\n",
" ],\n",
" \"grafanaMaturityCount\": 141,\n",
" \"lineageIsGroup\": false,\n",
" \"links\": {\n",
" \"docs\": \"https://grafana.com/docs/grafana/next/developers/kinds/core/dashboard/schema-reference\",\n",
" \"go\": \"https://github.com/grafana/grafana/tree/main/pkg/kinds/dashboard\",\n",
" \"schema\": \"https://github.com/grafana/grafana/tree/main/kinds/dashboard/dashboard_kind.cue\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"grafanaMaturityCount\": 140,\n"
],
"file_path": "pkg/kindsys/report.json",
"type": "replace",
"edit_start_line_idx": 285
} | package plugindef
import (
"strings"
"regexp"
"github.com/grafana/thema"
)
thema.#Lineage
name: "plugindef"
seqs: [
{
schemas: [
{
// Unique name of the plugin. If the plugin is published on
// grafana.com, then the plugin id has to follow the naming
// conventions.
id: string & strings.MinRunes(1)
id: =~"^([0-9a-z]+\\-([0-9a-z]+\\-)?(\(strings.Join([ for t in _types {t}], "|"))))|(alertGroups|alertlist|annolist|barchart|bargauge|candlestick|canvas|dashlist|debug|gauge|geomap|gettingstarted|graph|heatmap|histogram|icon|live|logs|news|nodeGraph|piechart|pluginlist|stat|state-timeline|status-history|table|table-old|text|timeseries|traces|welcome|xychart|alertmanager|cloudwatch|dashboard|elasticsearch|grafana|grafana-azure-monitor-datasource|graphite|influxdb|jaeger|loki|mixed|mssql|mysql|opentsdb|postgres|prometheus|stackdriver|tempo|testdata|zipkin|phlare|parca)$"
// The set of all plugin types. This hidden field exists solely
// so that the set can be string-interpolated into other fields.
_types: ["app", "datasource", "panel", "renderer", "secretsmanager"]
// type indicates which type of Grafana plugin this is, of the defined
// set of Grafana plugin types.
type: or(_types)
// IncludeType is a string identifier of a plugin include type, which is
// a superset of plugin types.
#IncludeType: type | "dashboard" | "page"
// Human-readable name of the plugin that is shown to the user in
// the UI.
name: string
// FIXME there appears to be a bug in thema that prevents this from working. Maybe it'd
// help to refer to it with an alias, but thema can't support using current list syntax.
// syntax (fixed by grafana/thema#82). Either way, for now, pascalName gets populated in Go.
let sani = (strings.ToTitle(regexp.ReplaceAllLiteral("[^a-zA-Z]+", name, "")))
// The PascalCase name for the plugin. Used for creating machine-friendly
// identifiers, typically in code generation.
//
// If not provided, defaults to name, but title-cased and sanitized (only
// alphabetical characters allowed).
pascalName: string & =~"^([A-Z][a-zA-Z]{1,62})$" | *sani
// Plugin category used on the Add data source page.
category?: "tsdb" | "logging" | "cloud" | "tracing" | "sql" | "enterprise" | "profiling" | "other"
// For data source plugins, if the plugin supports annotation
// queries.
annotations?: bool
// For data source plugins, if the plugin supports alerting.
alerting?: bool
// If the plugin has a backend component.
backend?: bool
// builtin indicates whether the plugin is developed and shipped as part
// of Grafana. Also known as a "core plugin."
builtIn: bool | *false
// hideFromList excludes the plugin from listings in Grafana's UI. Only
// allowed for builtin plugins.
hideFromList: bool | *false
// The first part of the file name of the backend component
// executable. There can be multiple executables built for
// different operating system and architecture. Grafana will
// check for executables named `<executable>_<$GOOS>_<lower case
// $GOARCH><.exe for Windows>`, e.g. `plugin_linux_amd64`.
// Combination of $GOOS and $GOARCH can be found here:
// https://golang.org/doc/install/source#environment.
executable?: string
// Initialize plugin on startup. By default, the plugin
// initializes on first use.
preload?: bool
// Marks a plugin as a pre-release.
state?: #ReleaseState
// ReleaseState indicates release maturity state of a plugin.
#ReleaseState: "alpha" | "beta" | "deprecated" | *"stable"
// Resources to include in plugin.
includes?: [...#Include]
// A resource to be included in a plugin.
#Include: {
// Unique identifier of the included resource
uid?: string
type: #IncludeType
name?: string
// (Legacy) The Angular component to use for a page.
component?: string
role?: "Admin" | "Editor" | "Viewer"
// RBAC action the user must have to access the route
action?: string
// Used for app plugins.
path?: string
// Add the include to the side menu.
addToNav?: bool
// Page or dashboard when user clicks the icon in the side menu.
defaultNav?: bool
// Icon to use in the side menu. For information on available
// icon, refer to [Icons
// Overview](https://developers.grafana.com/ui/latest/index.html?path=/story/docs-overview-icon--icons-overview).
icon?: string
...
}
// For data source plugins, if the plugin supports logs.
logs?: bool
// For panel plugins. Hides the query editor.
skipDataQuery?: bool
// For data source plugins, if the plugin supports metric queries.
// Used in Explore.
metrics?: bool
// For data source plugins, if the plugin supports streaming.
streaming?: bool
// This is an undocumented feature.
tables?: bool
// For data source plugins, if the plugin supports tracing.
tracing?: bool
// For data source plugins, include hidden queries in the data
// request.
hiddenQueries?: bool
// Set to true for app plugins that should be enabled by default
// in all orgs
autoEnabled?: bool
// Optional list of RBAC RoleRegistrations.
// Describes and organizes the default permissions associated with any of the Grafana basic roles,
// which characterizes what viewers, editors, admins, or grafana admins can do on the plugin.
// The Admin basic role inherits its default permissions from the Editor basic role which in turn
// inherits them from the Viewer basic role.
roles?: [...#RoleRegistration]
// RoleRegistration describes an RBAC role and its assignments to basic roles.
// It organizes related RBAC permissions on the plugin into a role and defines which basic roles
// will get them by default.
// Example: the role 'Schedules Reader' bundles permissions to view all schedules of the plugin
// which will be granted to Admins by default.
#RoleRegistration: {
// RBAC role definition to bundle related RBAC permissions on the plugin.
role: #Role
// Default assignment of the role to Grafana basic roles (Viewer, Editor, Admin, Grafana Admin)
// The Admin basic role inherits its default permissions from the Editor basic role which in turn
// inherits them from the Viewer basic role.
grants: [...#BasicRole]
}
// Role describes an RBAC role which allows grouping multiple related permissions on the plugin,
// each of which has an action and an optional scope.
// Example: the role 'Schedules Reader' bundles permissions to view all schedules of the plugin.
#Role: {
name: string,
name: =~"^([A-Z][0-9A-Za-z ]+)$"
description: string,
permissions: [...#Permission]
}
// Permission describes an RBAC permission on the plugin. A permission has an action and an optional
// scope.
// Example: action: 'test-app.schedules:read', scope: 'test-app.schedules:*'
#Permission: {
action: string
scope?: string
}
// BasicRole is a Grafana basic role, which can be 'Viewer', 'Editor', 'Admin' or 'Grafana Admin'.
// With RBAC, the Admin basic role inherits its default permissions from the Editor basic role which
// in turn inherits them from the Viewer basic role.
#BasicRole: "Grafana Admin" | "Admin" | "Editor" | "Viewer"
// Dependencies needed by the plugin.
dependencies: #Dependencies
#Dependencies: {
// (Deprecated) Required Grafana version for this plugin, e.g.
// `6.x.x 7.x.x` to denote plugin requires Grafana v6.x.x or
// v7.x.x.
grafanaVersion?: =~"^([0-9]+)(\\.[0-9x]+)?(\\.[0-9x])?$"
// Required Grafana version for this plugin. Validated using
// https://github.com/npm/node-semver.
grafanaDependency: =~"^(<=|>=|<|>|=|~|\\^)?([0-9]+)(\\.[0-9x\\*]+)(\\.[0-9x\\*]+)?(\\s(<=|>=|<|=>)?([0-9]+)(\\.[0-9x]+)(\\.[0-9x]+))?$"
// An array of required plugins on which this plugin depends.
plugins?: [...#Dependency]
}
// Dependency describes another plugin on which a plugin depends.
// The id refers to the plugin package identifier, as given on
// the grafana.com plugin marketplace.
#Dependency: {
id: =~"^[0-9a-z]+\\-([0-9a-z]+\\-)?(app|panel|datasource)$"
type: "app" | "datasource" | "panel"
name: string
version: string
...
}
// Metadata about the plugin.
info: #Info
// Metadata about a Grafana plugin. Some fields are used on the plugins
// page in Grafana and others on grafana.com, if the plugin is published.
#Info: {
// Information about the plugin author.
author?: {
// Author's name.
name?: string
// Author's name.
email?: string
// Link to author's website.
url?: string
}
// Build information
build?: #BuildInfo
// Description of plugin. Used on the plugins page in Grafana and
// for search on grafana.com.
description?: string
// Array of plugin keywords. Used for search on grafana.com.
keywords: [...string]
// should be this, but CUE to openapi converter screws this up
// by inserting a non-concrete default.
// keywords: [string, ...string]
// An array of link objects to be displayed on this plugin's
// project page in the form `{name: 'foo', url:
// 'http://example.com'}`
links?: [...{
name?: string
url?: string
}]
// SVG images that are used as plugin icons.
logos?: {
// Link to the "small" version of the plugin logo, which must be
// an SVG image. "Large" and "small" logos can be the same image.
small: string
// Link to the "large" version of the plugin logo, which must be
// an SVG image. "Large" and "small" logos can be the same image.
large: string
}
// An array of screenshot objects in the form `{name: 'bar', path:
// 'img/screenshot.png'}`
screenshots?: [...{
name?: string
path?: string
}]
// Date when this plugin was built.
updated?: =~"^(\\d{4}-\\d{2}-\\d{2}|\\%TODAY\\%)$"
// Project version of this commit, e.g. `6.7.x`.
version?: =~"^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)|(\\%VERSION\\%)$"
}
#BuildInfo: {
// Time when the plugin was built, as a Unix timestamp.
time?: int64
repo?: string
// Git branch the plugin was built from.
branch?: string
// Git hash of the commit the plugin was built from
hash?: string
"number"?: int64
// GitHub pull request the plugin was built from
pr?: int32
}
// For data source plugins. There is a query options section in
// the plugin's query editor and these options can be turned on
// if needed.
queryOptions?: {
// For data source plugins. If the `max data points` option should
// be shown in the query options section in the query editor.
maxDataPoints?: bool
// For data source plugins. If the `min interval` option should be
// shown in the query options section in the query editor.
minInterval?: bool
// For data source plugins. If the `cache timeout` option should
// be shown in the query options section in the query editor.
cacheTimeout?: bool
}
// Routes is a list of proxy routes, if any. For datasource plugins only.
routes?: [...#Route]
// Header describes an HTTP header that is forwarded with a proxied request for
// a plugin route.
#Header: {
name: string
content: string
}
// URLParam describes query string parameters for
// a url in a plugin route
#URLParam: {
name: string
content: string
}
// A proxy route used in datasource plugins for plugin authentication
// and adding headers to HTTP requests made by the plugin.
// For more information, refer to [Authentication for data source
// plugins](https://grafana.com/docs/grafana/latest/developers/plugins/authentication/).
#Route: {
// For data source plugins. The route path that is replaced by the
// route URL field when proxying the call.
path?: string
// For data source plugins. Route method matches the HTTP verb
// like GET or POST. Multiple methods can be provided as a
// comma-separated list.
method?: string
// For data source plugins. Route URL is where the request is
// proxied to.
url?: string
urlParams?: [...#URLParam]
reqSignedIn?: bool
reqRole?: string
// For data source plugins. Route headers adds HTTP headers to the
// proxied request.
headers?: [...#Header]
// For data source plugins. Route headers set the body content and
// length to the proxied request.
body?: {
...
}
// For data source plugins. Token authentication section used with
// an OAuth API.
tokenAuth?: #TokenAuth
// For data source plugins. Token authentication section used with
// an JWT OAuth API.
jwtTokenAuth?: #JWTTokenAuth
}
// TODO docs
#TokenAuth: {
// URL to fetch the authentication token.
url?: string
// The list of scopes that your application should be granted
// access to.
scopes?: [...string]
// Parameters for the token authentication request.
params: [string]: string
}
// TODO docs
// TODO should this really be separate from TokenAuth?
#JWTTokenAuth: {
// URL to fetch the JWT token.
url: string
// The list of scopes that your application should be granted
// access to.
scopes: [...string]
// Parameters for the JWT token authentication request.
params: [string]: string
}
// Grafana Enerprise specific features.
enterpriseFeatures?: {
// Enable/Disable health diagnostics errors. Requires Grafana
// >=7.5.5.
healthDiagnosticsErrors?: bool | *false
...
}
},
]
},
]
| pkg/plugins/plugindef/plugindef.cue | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.0008564904564991593,
0.0002061814011540264,
0.0001624944998184219,
0.00017023688997142017,
0.00013238842075224966
]
|
{
"id": 6,
"code_window": [
" ],\n",
" \"currentVersion\": [\n",
" 0,\n",
" 0\n",
" ],\n",
" \"grafanaMaturityCount\": 141,\n",
" \"lineageIsGroup\": false,\n",
" \"links\": {\n",
" \"docs\": \"https://grafana.com/docs/grafana/next/developers/kinds/core/dashboard/schema-reference\",\n",
" \"go\": \"https://github.com/grafana/grafana/tree/main/pkg/kinds/dashboard\",\n",
" \"schema\": \"https://github.com/grafana/grafana/tree/main/kinds/dashboard/dashboard_kind.cue\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"grafanaMaturityCount\": 140,\n"
],
"file_path": "pkg/kindsys/report.json",
"type": "replace",
"edit_start_line_idx": 285
} | class LogReporter {
constructor(globalConfig, reporterOptions, reporterContext) {
this._globalConfig = globalConfig;
this._options = reporterOptions;
this._context = reporterContext;
}
onRunComplete(testContexts, results) {
if (!this._options.enable) {
return;
}
this.logStats(results);
this.logTestFailures(results);
}
logTestFailures(results) {
results.testResults.forEach(printTestFailures);
}
logStats(results) {
const stats = {
suites: results.numTotalTestSuites,
tests: results.numTotalTests,
passes: results.numPassedTests,
pending: results.numPendingTests,
failures: results.numFailedTests,
duration: Date.now() - results.startTime,
};
// JestStats suites=1 tests=94 passes=93 pending=0 failures=1 duration=3973
console.log(`JestStats ${objToLogAttributes(stats)}`);
}
}
function printTestFailures(result) {
if (result.status === 'pending') {
return;
}
if (result.numFailingTests > 0) {
const testInfo = {
file: result.testFilePath,
failures: result.numFailingTests,
duration: result.perfStats.end - result.perfStats.start,
errorMessage: result.failureMessage,
};
// JestFailure file=<...>/public/app/features/dashboard/state/DashboardMigrator.test.ts
// failures=1 duration=3251 errorMessage="formatted error message"
console.log(`JestFailure ${objToLogAttributes(testInfo)}`);
}
}
/**
* Stringify object to be log friendly
* @param {Object} obj
* @returns {String}
*/
function objToLogAttributes(obj) {
return Object.entries(obj)
.map(([key, value]) => `${key}=${formatValue(value)}`)
.join(' ');
}
/**
* Escape double quotes
* @param {String} str
* @returns
*/
function escapeQuotes(str) {
return String(str).replaceAll('"', '\\"');
}
/**
* Wrap the value within double quote if needed
* @param {*} value
* @returns
*/
function formatValue(value) {
const hasWhiteSpaces = /\s/g.test(value);
return hasWhiteSpaces ? `"${escapeQuotes(value)}"` : value;
}
module.exports = LogReporter;
| public/test/log-reporter.js | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.0002364235115237534,
0.00017578474944457412,
0.0001632744970265776,
0.00016824253543745726,
0.000021653309886460193
]
|
{
"id": 7,
"code_window": [
"import { hasChanges, ignoreChanges } from './DashboardPrompt';\n",
"\n",
"function getDefaultDashboardModel() {\n",
" return createDashboardModelFixture({\n",
" refresh: false,\n",
" panels: [\n",
" createPanelJSONFixture({\n",
" id: 1,\n",
" type: 'graph',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/dashboard/components/DashboardPrompt/DashboardPrompt.test.tsx",
"type": "replace",
"edit_start_line_idx": 10
} | import { getPanelPlugin } from '@grafana/data/test/__mocks__/pluginMocks';
import { setContextSrv } from '../../../../core/services/context_srv';
import { PanelModel } from '../../state/PanelModel';
import { createDashboardModelFixture, createPanelJSONFixture } from '../../state/__fixtures__/dashboardFixtures';
import { hasChanges, ignoreChanges } from './DashboardPrompt';
function getDefaultDashboardModel() {
return createDashboardModelFixture({
refresh: false,
panels: [
createPanelJSONFixture({
id: 1,
type: 'graph',
gridPos: { x: 0, y: 0, w: 24, h: 6 },
legend: { show: true, sortDesc: false }, // TODO legend is marked as a non-persisted field
}),
{
id: 2,
type: 'row',
gridPos: { x: 0, y: 6, w: 24, h: 2 },
collapsed: true,
panels: [
{ id: 3, type: 'graph', gridPos: { x: 0, y: 6, w: 12, h: 2 } },
{ id: 4, type: 'graph', gridPos: { x: 12, y: 6, w: 12, h: 2 } },
],
},
{ id: 5, type: 'row', gridPos: { x: 0, y: 6, w: 1, h: 1 }, collapsed: false, panels: [] },
],
});
}
function getTestContext() {
const contextSrv: any = { isSignedIn: true, isEditor: true };
setContextSrv(contextSrv);
const dash = getDefaultDashboardModel();
const original = dash.getSaveModelClone();
return { dash, original, contextSrv };
}
describe('DashboardPrompt', () => {
it('No changes should not have changes', () => {
const { original, dash } = getTestContext();
expect(hasChanges(dash, original)).toBe(false);
});
it('Simple change should be registered', () => {
const { original, dash } = getTestContext();
dash.title = 'google';
expect(hasChanges(dash, original)).toBe(true);
});
it('Should ignore a lot of changes', () => {
const { original, dash } = getTestContext();
dash.time = { from: '1h' };
dash.refresh = true;
dash.schemaVersion = 10;
expect(hasChanges(dash, original)).toBe(false);
});
it('Should ignore row collapse change', () => {
const { original, dash } = getTestContext();
dash.toggleRow(dash.panels[1]);
expect(hasChanges(dash, original)).toBe(false);
});
it('Should ignore panel legend changes', () => {
const { original, dash } = getTestContext();
dash.panels[0]!.legend!.sortDesc = true;
dash.panels[0]!.legend!.sort = 'avg';
expect(hasChanges(dash, original)).toBe(false);
});
it('Should ignore panel repeats', () => {
const { original, dash } = getTestContext();
dash.panels.push(new PanelModel({ repeatPanelId: 10 }));
expect(hasChanges(dash, original)).toBe(false);
});
describe('ignoreChanges', () => {
describe('when called without original dashboard', () => {
it('then it should return true', () => {
const { dash } = getTestContext();
expect(ignoreChanges(dash, null)).toBe(true);
});
});
describe('when called without current dashboard', () => {
it('then it should return true', () => {
const { original } = getTestContext();
expect(ignoreChanges(null, original)).toBe(true);
});
});
describe('when called for a viewer without save permissions', () => {
it('then it should return true', () => {
const { contextSrv } = getTestContext();
const dash = createDashboardModelFixture({}, { canSave: false });
const original = dash.getSaveModelClone();
contextSrv.isEditor = false;
expect(ignoreChanges(dash, original)).toBe(true);
});
});
describe('when called for a viewer with save permissions', () => {
it('then it should return undefined', () => {
const { contextSrv } = getTestContext();
const dash = createDashboardModelFixture({}, { canSave: true });
const original = dash.getSaveModelClone();
contextSrv.isEditor = false;
expect(ignoreChanges(dash, original)).toBe(undefined);
});
});
describe('when called for an user that is not signed in', () => {
it('then it should return true', () => {
const { contextSrv } = getTestContext();
const dash = createDashboardModelFixture({}, { canSave: true });
const original = dash.getSaveModelClone();
contextSrv.isSignedIn = false;
expect(ignoreChanges(dash, original)).toBe(true);
});
});
describe('when called with fromScript', () => {
it('then it should return true', () => {
const dash = createDashboardModelFixture({}, { canSave: true, fromScript: true, fromFile: undefined });
const original = dash.getSaveModelClone();
expect(ignoreChanges(dash, original)).toBe(true);
});
});
it('Should ignore panel schema migrations', () => {
const { original, dash } = getTestContext();
const plugin = getPanelPlugin({}).setMigrationHandler((panel) => {
delete (panel as any).legend;
return { option1: 'Aasd' };
});
dash.panels[0].pluginLoaded(plugin);
expect(hasChanges(dash, original)).toBe(false);
});
describe('when called with fromFile', () => {
it('then it should return true', () => {
const dash = createDashboardModelFixture({}, { canSave: true, fromScript: undefined, fromFile: true });
const original = dash.getSaveModelClone();
expect(ignoreChanges(dash, original)).toBe(true);
});
});
describe('when called with canSave but without fromScript and fromFile', () => {
it('then it should return false', () => {
const dash = createDashboardModelFixture({}, { canSave: true, fromScript: undefined, fromFile: undefined });
const original = dash.getSaveModelClone();
expect(ignoreChanges(dash, original)).toBe(undefined);
});
});
});
});
| public/app/features/dashboard/components/DashboardPrompt/DashboardPrompt.test.tsx | 1 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.9992761015892029,
0.16249480843544006,
0.0001672770013101399,
0.002858527470380068,
0.3133741617202759
]
|
{
"id": 7,
"code_window": [
"import { hasChanges, ignoreChanges } from './DashboardPrompt';\n",
"\n",
"function getDefaultDashboardModel() {\n",
" return createDashboardModelFixture({\n",
" refresh: false,\n",
" panels: [\n",
" createPanelJSONFixture({\n",
" id: 1,\n",
" type: 'graph',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/dashboard/components/DashboardPrompt/DashboardPrompt.test.tsx",
"type": "replace",
"edit_start_line_idx": 10
} | import React, { FunctionComponent, PropsWithChildren, ReactElement, useMemo } from 'react';
import { selectors } from '@grafana/e2e-selectors';
import { Tooltip } from '@grafana/ui';
import { variableAdapters } from '../adapters';
import { VariableHide, VariableModel } from '../types';
interface Props {
variable: VariableModel;
readOnly?: boolean;
}
export const PickerRenderer: FunctionComponent<Props> = (props) => {
const PickerToRender = useMemo(() => variableAdapters.get(props.variable.type).picker, [props.variable]);
if (!props.variable) {
return <div>Couldn't load variable</div>;
}
return (
<div className="gf-form">
<PickerLabel variable={props.variable} />
{props.variable.hide !== VariableHide.hideVariable && PickerToRender && (
<PickerToRender variable={props.variable} readOnly={props.readOnly ?? false} />
)}
</div>
);
};
function PickerLabel({ variable }: PropsWithChildren<Props>): ReactElement | null {
const labelOrName = useMemo(() => variable.label || variable.name, [variable]);
if (variable.hide !== VariableHide.dontHide) {
return null;
}
const elementId = `var-${variable.id}`;
if (variable.description) {
return (
<Tooltip content={variable.description} placement={'bottom'}>
<label
className="gf-form-label gf-form-label--variable"
data-testid={selectors.pages.Dashboard.SubMenu.submenuItemLabels(labelOrName)}
htmlFor={elementId}
>
{labelOrName}
</label>
</Tooltip>
);
}
return (
<label
className="gf-form-label gf-form-label--variable"
data-testid={selectors.pages.Dashboard.SubMenu.submenuItemLabels(labelOrName)}
htmlFor={elementId}
>
{labelOrName}
</label>
);
}
| public/app/features/variables/pickers/PickerRenderer.tsx | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.000178275557118468,
0.00017259120068047196,
0.00016412143304478377,
0.00017308983660768718,
0.0000042040765038109384
]
|
{
"id": 7,
"code_window": [
"import { hasChanges, ignoreChanges } from './DashboardPrompt';\n",
"\n",
"function getDefaultDashboardModel() {\n",
" return createDashboardModelFixture({\n",
" refresh: false,\n",
" panels: [\n",
" createPanelJSONFixture({\n",
" id: 1,\n",
" type: 'graph',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/dashboard/components/DashboardPrompt/DashboardPrompt.test.tsx",
"type": "replace",
"edit_start_line_idx": 10
} | package notifier
import (
"bytes"
"context"
"errors"
"io/fs"
"os"
"path/filepath"
"testing"
"time"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/ngalert/metrics"
"github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/services/ngalert/provisioning"
"github.com/grafana/grafana/pkg/services/secrets/fakes"
secretsManager "github.com/grafana/grafana/pkg/services/secrets/manager"
"github.com/grafana/grafana/pkg/setting"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/stretchr/testify/require"
)
func TestMultiOrgAlertmanager_SyncAlertmanagersForOrgs(t *testing.T) {
configStore := &FakeConfigStore{
configs: map[int64]*models.AlertConfiguration{},
}
orgStore := &FakeOrgStore{
orgs: []int64{1, 2, 3},
}
tmpDir := t.TempDir()
kvStore := NewFakeKVStore(t)
provStore := provisioning.NewFakeProvisioningStore()
secretsService := secretsManager.SetupTestService(t, fakes.NewFakeSecretsStore())
decryptFn := secretsService.GetDecryptedValue
reg := prometheus.NewPedanticRegistry()
m := metrics.NewNGAlert(reg)
cfg := &setting.Cfg{
DataPath: tmpDir,
UnifiedAlerting: setting.UnifiedAlertingSettings{
AlertmanagerConfigPollInterval: 3 * time.Minute,
DefaultConfiguration: setting.GetAlertmanagerDefaultConfiguration(),
DisabledOrgs: map[int64]struct{}{5: {}},
}, // do not poll in tests.
}
mam, err := NewMultiOrgAlertmanager(cfg, configStore, orgStore, kvStore, provStore, decryptFn, m.GetMultiOrgAlertmanagerMetrics(), nil, log.New("testlogger"), secretsService)
require.NoError(t, err)
ctx := context.Background()
// Ensure that one Alertmanager is created per org.
{
require.NoError(t, mam.LoadAndSyncAlertmanagersForOrgs(ctx))
require.Len(t, mam.alertmanagers, 3)
require.NoError(t, testutil.GatherAndCompare(reg, bytes.NewBufferString(`
# HELP grafana_alerting_active_configurations The number of active Alertmanager configurations.
# TYPE grafana_alerting_active_configurations gauge
grafana_alerting_active_configurations 3
# HELP grafana_alerting_discovered_configurations The number of organizations we've discovered that require an Alertmanager configuration.
# TYPE grafana_alerting_discovered_configurations gauge
grafana_alerting_discovered_configurations 3
`), "grafana_alerting_discovered_configurations", "grafana_alerting_active_configurations"))
}
// When an org is removed, it should detect it.
{
orgStore.orgs = []int64{1, 3}
require.NoError(t, mam.LoadAndSyncAlertmanagersForOrgs(ctx))
require.Len(t, mam.alertmanagers, 2)
require.NoError(t, testutil.GatherAndCompare(reg, bytes.NewBufferString(`
# HELP grafana_alerting_active_configurations The number of active Alertmanager configurations.
# TYPE grafana_alerting_active_configurations gauge
grafana_alerting_active_configurations 2
# HELP grafana_alerting_discovered_configurations The number of organizations we've discovered that require an Alertmanager configuration.
# TYPE grafana_alerting_discovered_configurations gauge
grafana_alerting_discovered_configurations 2
`), "grafana_alerting_discovered_configurations", "grafana_alerting_active_configurations"))
}
// if the org comes back, it should detect it.
{
orgStore.orgs = []int64{1, 2, 3, 4}
require.NoError(t, mam.LoadAndSyncAlertmanagersForOrgs(ctx))
require.Len(t, mam.alertmanagers, 4)
require.NoError(t, testutil.GatherAndCompare(reg, bytes.NewBufferString(`
# HELP grafana_alerting_active_configurations The number of active Alertmanager configurations.
# TYPE grafana_alerting_active_configurations gauge
grafana_alerting_active_configurations 4
# HELP grafana_alerting_discovered_configurations The number of organizations we've discovered that require an Alertmanager configuration.
# TYPE grafana_alerting_discovered_configurations gauge
grafana_alerting_discovered_configurations 4
`), "grafana_alerting_discovered_configurations", "grafana_alerting_active_configurations"))
}
// if the disabled org comes back, it should not detect it.
{
orgStore.orgs = []int64{1, 2, 3, 4, 5}
require.NoError(t, mam.LoadAndSyncAlertmanagersForOrgs(ctx))
require.Len(t, mam.alertmanagers, 4)
}
// Orphaned state should be removed.
{
orgID := int64(6)
// First we create a directory and two files for an ograniztation that
// is not existing in the current state.
orphanDir := filepath.Join(tmpDir, "alerting", "6")
err := os.Mkdir(orphanDir, 0750)
require.NoError(t, err)
silencesPath := filepath.Join(orphanDir, silencesFilename)
err = os.WriteFile(silencesPath, []byte("file_1"), 0644)
require.NoError(t, err)
notificationPath := filepath.Join(orphanDir, notificationLogFilename)
err = os.WriteFile(notificationPath, []byte("file_2"), 0644)
require.NoError(t, err)
// We make sure that both files are on disk.
info, err := os.Stat(silencesPath)
require.NoError(t, err)
require.Equal(t, info.Name(), silencesFilename)
info, err = os.Stat(notificationPath)
require.NoError(t, err)
require.Equal(t, info.Name(), notificationLogFilename)
// We also populate the kvstore with orphaned records.
err = kvStore.Set(ctx, orgID, KVNamespace, silencesFilename, "file_1")
require.NoError(t, err)
err = kvStore.Set(ctx, orgID, KVNamespace, notificationLogFilename, "file_1")
require.NoError(t, err)
// Now re run the sync job once.
require.NoError(t, mam.LoadAndSyncAlertmanagersForOrgs(ctx))
// The organization directory should be gone by now.
_, err = os.Stat(orphanDir)
require.True(t, errors.Is(err, fs.ErrNotExist))
// The organization kvstore records should be gone by now.
_, exists, _ := kvStore.Get(ctx, orgID, KVNamespace, silencesFilename)
require.False(t, exists)
_, exists, _ = kvStore.Get(ctx, orgID, KVNamespace, notificationLogFilename)
require.False(t, exists)
}
}
func TestMultiOrgAlertmanager_SyncAlertmanagersForOrgsWithFailures(t *testing.T) {
// Include a broken configuration for organization 2.
configStore := &FakeConfigStore{
configs: map[int64]*models.AlertConfiguration{
2: {AlertmanagerConfiguration: brokenConfig, OrgID: 2},
},
}
orgStore := &FakeOrgStore{
orgs: []int64{1, 2, 3},
}
tmpDir := t.TempDir()
kvStore := NewFakeKVStore(t)
provStore := provisioning.NewFakeProvisioningStore()
secretsService := secretsManager.SetupTestService(t, fakes.NewFakeSecretsStore())
decryptFn := secretsService.GetDecryptedValue
reg := prometheus.NewPedanticRegistry()
m := metrics.NewNGAlert(reg)
cfg := &setting.Cfg{
DataPath: tmpDir,
UnifiedAlerting: setting.UnifiedAlertingSettings{
AlertmanagerConfigPollInterval: 10 * time.Minute,
DefaultConfiguration: setting.GetAlertmanagerDefaultConfiguration(),
}, // do not poll in tests.
}
mam, err := NewMultiOrgAlertmanager(cfg, configStore, orgStore, kvStore, provStore, decryptFn, m.GetMultiOrgAlertmanagerMetrics(), nil, log.New("testlogger"), secretsService)
require.NoError(t, err)
ctx := context.Background()
// When you sync the first time, the alertmanager is created but is doesn't become ready until you have a configuration applied.
{
require.NoError(t, mam.LoadAndSyncAlertmanagersForOrgs(ctx))
require.Len(t, mam.alertmanagers, 3)
require.True(t, mam.alertmanagers[1].Ready())
require.False(t, mam.alertmanagers[2].Ready())
require.True(t, mam.alertmanagers[3].Ready())
}
// On the next sync, it never panics and alertmanager is still not ready.
{
require.NoError(t, mam.LoadAndSyncAlertmanagersForOrgs(ctx))
require.Len(t, mam.alertmanagers, 3)
require.True(t, mam.alertmanagers[1].Ready())
require.False(t, mam.alertmanagers[2].Ready())
require.True(t, mam.alertmanagers[3].Ready())
}
// If we fix the configuration, it becomes ready.
{
configStore.configs = map[int64]*models.AlertConfiguration{} // It'll apply the default config.
require.NoError(t, mam.LoadAndSyncAlertmanagersForOrgs(ctx))
require.Len(t, mam.alertmanagers, 3)
require.True(t, mam.alertmanagers[1].Ready())
require.True(t, mam.alertmanagers[2].Ready())
require.True(t, mam.alertmanagers[3].Ready())
}
}
func TestMultiOrgAlertmanager_AlertmanagerFor(t *testing.T) {
configStore := &FakeConfigStore{
configs: map[int64]*models.AlertConfiguration{},
}
orgStore := &FakeOrgStore{
orgs: []int64{1, 2, 3},
}
tmpDir := t.TempDir()
cfg := &setting.Cfg{
DataPath: tmpDir,
UnifiedAlerting: setting.UnifiedAlertingSettings{AlertmanagerConfigPollInterval: 3 * time.Minute, DefaultConfiguration: setting.GetAlertmanagerDefaultConfiguration()}, // do not poll in tests.
}
kvStore := NewFakeKVStore(t)
provStore := provisioning.NewFakeProvisioningStore()
secretsService := secretsManager.SetupTestService(t, fakes.NewFakeSecretsStore())
decryptFn := secretsService.GetDecryptedValue
reg := prometheus.NewPedanticRegistry()
m := metrics.NewNGAlert(reg)
mam, err := NewMultiOrgAlertmanager(cfg, configStore, orgStore, kvStore, provStore, decryptFn, m.GetMultiOrgAlertmanagerMetrics(), nil, log.New("testlogger"), secretsService)
require.NoError(t, err)
ctx := context.Background()
// Ensure that one Alertmanagers is created per org.
{
require.NoError(t, mam.LoadAndSyncAlertmanagersForOrgs(ctx))
require.Len(t, mam.alertmanagers, 3)
}
// First, let's try to request an Alertmanager from an org that doesn't exist.
{
_, err := mam.AlertmanagerFor(5)
require.EqualError(t, err, ErrNoAlertmanagerForOrg.Error())
}
// With an Alertmanager that exists, it responds correctly.
{
am, err := mam.AlertmanagerFor(2)
require.NoError(t, err)
require.Equal(t, *am.GetStatus().VersionInfo.Version, "N/A")
require.Equal(t, am.orgID, int64(2))
require.NotNil(t, am.Base.ConfigHash())
}
// Let's now remove the previous queried organization.
orgStore.orgs = []int64{1, 3}
require.NoError(t, mam.LoadAndSyncAlertmanagersForOrgs(ctx))
{
_, err := mam.AlertmanagerFor(2)
require.EqualError(t, err, ErrNoAlertmanagerForOrg.Error())
}
}
var brokenConfig = `
"alertmanager_config": {
"route": {
"receiver": "grafana-default-email"
},
"receivers": [{
"name": "grafana-default-email",
"grafana_managed_receiver_configs": [{
"uid": "",
"name": "slack receiver",
"type": "slack",
"isDefault": true,
"settings": {
"addresses": "<[email protected]>"
"url": "οΏ½r_οΏ½οΏ½q/bοΏ½οΏ½οΏ½οΏ½οΏ½p@β±Θ =οΏ½οΏ½@ΣΉtd>RΓΊοΏ½HοΏ½οΏ½ οΏ½;οΏ½@UfοΏ½οΏ½0οΏ½\k2*jhοΏ½}ΓuοΏ½)"2οΏ½F6]οΏ½}rοΏ½οΏ½RοΏ½bοΏ½dοΏ½J;οΏ½οΏ½Sν§οΏ½οΏ½$οΏ½οΏ½",
"recipient": "#graphana-metrics",
}
}]
}]
}
}`
| pkg/services/ngalert/notifier/multiorg_alertmanager_test.go | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.0001924218813655898,
0.00017475469212513417,
0.00016891217092052102,
0.00017441518139094114,
0.000004220938080834458
]
|
{
"id": 7,
"code_window": [
"import { hasChanges, ignoreChanges } from './DashboardPrompt';\n",
"\n",
"function getDefaultDashboardModel() {\n",
" return createDashboardModelFixture({\n",
" refresh: false,\n",
" panels: [\n",
" createPanelJSONFixture({\n",
" id: 1,\n",
" type: 'graph',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/dashboard/components/DashboardPrompt/DashboardPrompt.test.tsx",
"type": "replace",
"edit_start_line_idx": 10
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M13,15.28V10.5a1,1,0,0,0-2,0v4.78A2,2,0,0,0,10,17a2,2,0,0,0,4,0A2,2,0,0,0,13,15.28ZM16.5,13V5.5a4.5,4.5,0,0,0-9,0V13a6,6,0,0,0,3.21,9.83A7,7,0,0,0,12,23,6,6,0,0,0,16.5,13Zm-2,7.07a4,4,0,0,1-5.32-6,1,1,0,0,0,.3-.71V5.5a2.5,2.5,0,0,1,5,0v7.94a1,1,0,0,0,.3.71,4,4,0,0,1-.28,6Z"/></svg> | public/img/icons/unicons/temperature-half.svg | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.0001745421759551391,
0.0001745421759551391,
0.0001745421759551391,
0.0001745421759551391,
0
]
|
{
"id": 8,
"code_window": [
"\n",
" it('Should ignore a lot of changes', () => {\n",
" const { original, dash } = getTestContext();\n",
" dash.time = { from: '1h' };\n",
" dash.refresh = true;\n",
" dash.schemaVersion = 10;\n",
" expect(hasChanges(dash, original)).toBe(false);\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" dash.refresh = '30s';\n"
],
"file_path": "public/app/features/dashboard/components/DashboardPrompt/DashboardPrompt.test.tsx",
"type": "replace",
"edit_start_line_idx": 58
} | // Code generated - EDITING IS FUTILE. DO NOT EDIT.
//
// Generated by:
// kinds/gen.go
// Using jennies:
// GoTypesJenny
// LatestJenny
//
// Run 'make gen-cue' from repository root to regenerate.
package dashboard
// Defines values for Style.
const (
StyleDark Style = "dark"
StyleLight Style = "light"
)
// Defines values for Timezone.
const (
TimezoneBrowser Timezone = "browser"
TimezoneEmpty Timezone = ""
TimezoneUtc Timezone = "utc"
)
// Defines values for CursorSync.
const (
CursorSyncN0 CursorSync = 0
CursorSyncN1 CursorSync = 1
CursorSyncN2 CursorSync = 2
)
// Defines values for LinkType.
const (
LinkTypeDashboards LinkType = "dashboards"
LinkTypeLink LinkType = "link"
)
// Defines values for FieldColorModeId.
const (
FieldColorModeIdContinuousGrYlRd FieldColorModeId = "continuous-GrYlRd"
FieldColorModeIdFixed FieldColorModeId = "fixed"
FieldColorModeIdPaletteClassic FieldColorModeId = "palette-classic"
FieldColorModeIdPaletteSaturated FieldColorModeId = "palette-saturated"
FieldColorModeIdThresholds FieldColorModeId = "thresholds"
)
// Defines values for FieldColorSeriesByMode.
const (
FieldColorSeriesByModeLast FieldColorSeriesByMode = "last"
FieldColorSeriesByModeMax FieldColorSeriesByMode = "max"
FieldColorSeriesByModeMin FieldColorSeriesByMode = "min"
)
// Defines values for GraphPanelType.
const (
GraphPanelTypeGraph GraphPanelType = "graph"
)
// Defines values for HeatmapPanelType.
const (
HeatmapPanelTypeHeatmap HeatmapPanelType = "heatmap"
)
// Defines values for LoadingState.
const (
LoadingStateDone LoadingState = "Done"
LoadingStateError LoadingState = "Error"
LoadingStateLoading LoadingState = "Loading"
LoadingStateNotStarted LoadingState = "NotStarted"
LoadingStateStreaming LoadingState = "Streaming"
)
// Defines values for MappingType.
const (
MappingTypeRange MappingType = "range"
MappingTypeRegex MappingType = "regex"
MappingTypeSpecial MappingType = "special"
MappingTypeValue MappingType = "value"
)
// Defines values for PanelRepeatDirection.
const (
PanelRepeatDirectionH PanelRepeatDirection = "h"
PanelRepeatDirectionV PanelRepeatDirection = "v"
)
// Defines values for RowPanelType.
const (
RowPanelTypeRow RowPanelType = "row"
)
// Defines values for SpecialValueMapOptionsMatch.
const (
SpecialValueMapOptionsMatchFalse SpecialValueMapOptionsMatch = "false"
SpecialValueMapOptionsMatchTrue SpecialValueMapOptionsMatch = "true"
)
// Defines values for SpecialValueMatch.
const (
SpecialValueMatchEmpty SpecialValueMatch = "empty"
SpecialValueMatchFalse SpecialValueMatch = "false"
SpecialValueMatchNan SpecialValueMatch = "nan"
SpecialValueMatchNull SpecialValueMatch = "null"
SpecialValueMatchNullNan SpecialValueMatch = "null+nan"
SpecialValueMatchTrue SpecialValueMatch = "true"
)
// Defines values for ThresholdsMode.
const (
ThresholdsModeAbsolute ThresholdsMode = "absolute"
ThresholdsModePercentage ThresholdsMode = "percentage"
)
// Defines values for VariableHide.
const (
VariableHideN0 VariableHide = 0
VariableHideN1 VariableHide = 1
VariableHideN2 VariableHide = 2
)
// Defines values for VariableType.
const (
VariableTypeAdhoc VariableType = "adhoc"
VariableTypeConstant VariableType = "constant"
VariableTypeCustom VariableType = "custom"
VariableTypeDatasource VariableType = "datasource"
VariableTypeInterval VariableType = "interval"
VariableTypeQuery VariableType = "query"
VariableTypeSystem VariableType = "system"
VariableTypeTextbox VariableType = "textbox"
)
// TODO docs
// FROM: AnnotationQuery in grafana-data/src/types/annotations.ts
type AnnotationQuery struct {
BuiltIn int `json:"builtIn"`
// Datasource to use for annotation.
Datasource struct {
Type *string `json:"type,omitempty"`
Uid *string `json:"uid,omitempty"`
} `json:"datasource"`
// Whether annotation is enabled.
Enable bool `json:"enable"`
// Whether to hide annotation.
Hide *bool `json:"hide,omitempty"`
// Annotation icon color.
IconColor *string `json:"iconColor,omitempty"`
// Name of annotation.
Name *string `json:"name,omitempty"`
// Query for annotation data.
RawQuery *string `json:"rawQuery,omitempty"`
ShowIn int `json:"showIn"`
// TODO docs
Target *AnnotationTarget `json:"target,omitempty"`
Type string `json:"type"`
}
// TODO docs
type AnnotationTarget struct {
Limit int64 `json:"limit"`
MatchAny bool `json:"matchAny"`
Tags []string `json:"tags"`
Type string `json:"type"`
}
// Dashboard defines model for Dashboard.
type Dashboard struct {
// TODO docs
Annotations *struct {
List *[]AnnotationQuery `json:"list,omitempty"`
} `json:"annotations,omitempty"`
// Description of dashboard.
Description *string `json:"description,omitempty"`
// Whether a dashboard is editable or not.
Editable bool `json:"editable"`
// The month that the fiscal year starts on. 0 = January, 11 = December
FiscalYearStartMonth *int `json:"fiscalYearStartMonth,omitempty"`
GnetId *string `json:"gnetId,omitempty"`
// 0 for no shared crosshair or tooltip (default).
// 1 for shared crosshair.
// 2 for shared crosshair AND shared tooltip.
GraphTooltip CursorSync `json:"graphTooltip"`
// Unique numeric identifier for the dashboard.
// TODO must isolate or remove identifiers local to a Grafana instance...?
Id *int64 `json:"id,omitempty"`
// TODO docs
Links *[]Link `json:"links,omitempty"`
// TODO docs
LiveNow *bool `json:"liveNow,omitempty"`
Panels *[]interface{} `json:"panels,omitempty"`
// TODO docs
Refresh *interface{} `json:"refresh,omitempty"`
// Version of the current dashboard data
Revision int `json:"revision"`
// Version of the JSON schema, incremented each time a Grafana update brings
// changes to said schema.
// TODO this is the existing schema numbering system. It will be replaced by Thema's themaVersion
SchemaVersion int `json:"schemaVersion"`
// TODO docs
Snapshot *Snapshot `json:"snapshot,omitempty"`
// Theme of dashboard.
Style Style `json:"style"`
// Tags associated with dashboard.
Tags *[]string `json:"tags,omitempty"`
// TODO docs
Templating *struct {
List *[]VariableModel `json:"list,omitempty"`
} `json:"templating,omitempty"`
// Time range for dashboard, e.g. last 6 hours, last 7 days, etc
Time *struct {
From string `json:"from"`
To string `json:"to"`
} `json:"time,omitempty"`
// TODO docs
// TODO this appears to be spread all over in the frontend. Concepts will likely need tidying in tandem with schema changes
Timepicker *struct {
// Whether timepicker is collapsed or not.
Collapse bool `json:"collapse"`
// Whether timepicker is enabled or not.
Enable bool `json:"enable"`
// Whether timepicker is visible or not.
Hidden bool `json:"hidden"`
// Selectable intervals for auto-refresh.
RefreshIntervals []string `json:"refresh_intervals"`
// TODO docs
TimeOptions []string `json:"time_options"`
} `json:"timepicker,omitempty"`
// Timezone of dashboard,
Timezone *Timezone `json:"timezone,omitempty"`
// Title of dashboard.
Title *string `json:"title,omitempty"`
// Unique dashboard identifier that can be generated by anyone. string (8-40)
Uid *string `json:"uid,omitempty"`
// Version of the dashboard, incremented each time the dashboard is updated.
Version *int `json:"version,omitempty"`
// TODO docs
WeekStart *string `json:"weekStart,omitempty"`
}
// Theme of dashboard.
type Style string
// Timezone of dashboard,
type Timezone string
// 0 for no shared crosshair or tooltip (default).
// 1 for shared crosshair.
// 2 for shared crosshair AND shared tooltip.
type CursorSync int
// FROM public/app/features/dashboard/state/Models.ts - ish
// TODO docs
type Link struct {
AsDropdown bool `json:"asDropdown"`
Icon string `json:"icon"`
IncludeVars bool `json:"includeVars"`
KeepTime bool `json:"keepTime"`
Tags []string `json:"tags"`
TargetBlank bool `json:"targetBlank"`
Title string `json:"title"`
Tooltip string `json:"tooltip"`
// TODO docs
Type LinkType `json:"type"`
Url string `json:"url"`
}
// TODO docs
type LinkType string
// Ref to a DataSource instance
type DataSourceRef struct {
// The plugin type-id
Type *string `json:"type,omitempty"`
// Specific datasource instance
Uid *string `json:"uid,omitempty"`
}
// DynamicConfigValue defines model for DynamicConfigValue.
type DynamicConfigValue struct {
Id string `json:"id"`
Value *interface{} `json:"value,omitempty"`
}
// TODO docs
type FieldColor struct {
// Stores the fixed color value if mode is fixed
FixedColor *string `json:"fixedColor,omitempty"`
// The main color scheme mode
Mode interface{} `json:"mode"`
// TODO docs
SeriesBy *FieldColorSeriesByMode `json:"seriesBy,omitempty"`
}
// TODO docs
type FieldColorModeId string
// TODO docs
type FieldColorSeriesByMode string
// FieldConfig defines model for FieldConfig.
type FieldConfig struct {
// TODO docs
Color *FieldColor `json:"color,omitempty"`
// custom is specified by the PanelFieldConfig field
// in panel plugin schemas.
Custom *map[string]interface{} `json:"custom,omitempty"`
// Significant digits (for display)
Decimals *float32 `json:"decimals,omitempty"`
// Human readable field metadata
Description *string `json:"description,omitempty"`
// The display value for this field. This supports template variables blank is auto
DisplayName *string `json:"displayName,omitempty"`
// This can be used by data sources that return and explicit naming structure for values and labels
// When this property is configured, this value is used rather than the default naming strategy.
DisplayNameFromDS *string `json:"displayNameFromDS,omitempty"`
// True if data source field supports ad-hoc filters
Filterable *bool `json:"filterable,omitempty"`
// The behavior when clicking on a result
Links *[]interface{} `json:"links,omitempty"`
// Convert input values into a display string
Mappings *[]ValueMapping `json:"mappings,omitempty"`
Max *float32 `json:"max,omitempty"`
Min *float32 `json:"min,omitempty"`
// Alternative to empty string
NoValue *string `json:"noValue,omitempty"`
// An explicit path to the field in the datasource. When the frame meta includes a path,
// This will default to `${frame.meta.path}/${field.name}
//
// When defined, this value can be used as an identifier within the datasource scope, and
// may be used to update the results
Path *string `json:"path,omitempty"`
Thresholds *ThresholdsConfig `json:"thresholds,omitempty"`
// Numeric Options
Unit *string `json:"unit,omitempty"`
// True if data source can write a value to the path. Auth/authz are supported separately
Writeable *bool `json:"writeable,omitempty"`
}
// FieldConfigSource defines model for FieldConfigSource.
type FieldConfigSource struct {
Defaults FieldConfig `json:"defaults"`
Overrides []struct {
Matcher MatcherConfig `json:"matcher"`
Properties []DynamicConfigValue `json:"properties"`
} `json:"overrides"`
}
// Support for legacy graph and heatmap panels.
type GraphPanel struct {
// @deprecated this is part of deprecated graph panel
Legend *struct {
Show bool `json:"show"`
Sort *string `json:"sort,omitempty"`
SortDesc *bool `json:"sortDesc,omitempty"`
} `json:"legend,omitempty"`
Type GraphPanelType `json:"type"`
}
// GraphPanelType defines model for GraphPanel.Type.
type GraphPanelType string
// GridPos defines model for GridPos.
type GridPos struct {
// Panel
H int `json:"h"`
// true if fixed
Static *bool `json:"static,omitempty"`
// Panel
W int `json:"w"`
// Panel x
X int `json:"x"`
// Panel y
Y int `json:"y"`
}
// HeatmapPanel defines model for HeatmapPanel.
type HeatmapPanel struct {
Type HeatmapPanelType `json:"type"`
}
// HeatmapPanelType defines model for HeatmapPanel.Type.
type HeatmapPanelType string
// LoadingState defines model for LoadingState.
type LoadingState string
// TODO docs
type MappingType string
// MatcherConfig defines model for MatcherConfig.
type MatcherConfig struct {
Id string `json:"id"`
Options *interface{} `json:"options,omitempty"`
}
// Dashboard panels. Panels are canonically defined inline
// because they share a version timeline with the dashboard
// schema; they do not evolve independently.
type Panel struct {
// The datasource used in all targets.
Datasource *struct {
Type *string `json:"type,omitempty"`
Uid *string `json:"uid,omitempty"`
} `json:"datasource,omitempty"`
// Description.
Description *string `json:"description,omitempty"`
FieldConfig FieldConfigSource `json:"fieldConfig"`
GridPos *GridPos `json:"gridPos,omitempty"`
// TODO docs
Id *int `json:"id,omitempty"`
// TODO docs
// TODO tighter constraint
Interval *string `json:"interval,omitempty"`
// Panel links.
// TODO fill this out - seems there are a couple variants?
Links *[]Link `json:"links,omitempty"`
// TODO docs
MaxDataPoints *float32 `json:"maxDataPoints,omitempty"`
// options is specified by the PanelOptions field in panel
// plugin schemas.
Options map[string]interface{} `json:"options"`
// FIXME this almost certainly has to be changed in favor of scuemata versions
PluginVersion *string `json:"pluginVersion,omitempty"`
// Name of template variable to repeat for.
Repeat *string `json:"repeat,omitempty"`
// Direction to repeat in if 'repeat' is set.
// "h" for horizontal, "v" for vertical.
// TODO this is probably optional
RepeatDirection PanelRepeatDirection `json:"repeatDirection"`
// Id of the repeating panel.
RepeatPanelId *int64 `json:"repeatPanelId,omitempty"`
// TODO docs
Tags *[]string `json:"tags,omitempty"`
// TODO docs
Targets *[]Target `json:"targets,omitempty"`
// TODO docs - seems to be an old field from old dashboard alerts?
Thresholds *[]interface{} `json:"thresholds,omitempty"`
// TODO docs
// TODO tighter constraint
TimeFrom *string `json:"timeFrom,omitempty"`
// TODO docs
TimeRegions *[]interface{} `json:"timeRegions,omitempty"`
// TODO docs
// TODO tighter constraint
TimeShift *string `json:"timeShift,omitempty"`
// Panel title.
Title *string `json:"title,omitempty"`
Transformations []Transformation `json:"transformations"`
// Whether to display the panel without a background.
Transparent bool `json:"transparent"`
// The panel plugin type id. May not be empty.
Type string `json:"type"`
}
// Direction to repeat in if 'repeat' is set.
// "h" for horizontal, "v" for vertical.
// TODO this is probably optional
type PanelRepeatDirection string
// TODO docs
type RangeMap struct {
Options struct {
// to and from are `number | null` in current ts, really not sure what to do
From float64 `json:"from"`
// TODO docs
Result ValueMappingResult `json:"result"`
To float64 `json:"to"`
} `json:"options"`
Type struct {
// Embedded struct due to allOf(#/components/schemas/MappingType)
MappingType `yaml:",inline"`
// Embedded fields due to inline allOf schema
} `json:"type"`
}
// TODO docs
type RegexMap struct {
Options struct {
Pattern string `json:"pattern"`
// TODO docs
Result ValueMappingResult `json:"result"`
} `json:"options"`
Type struct {
// Embedded struct due to allOf(#/components/schemas/MappingType)
MappingType `yaml:",inline"`
// Embedded fields due to inline allOf schema
} `json:"type"`
}
// Row panel
type RowPanel struct {
Collapsed bool `json:"collapsed"`
// Name of default datasource.
Datasource *struct {
Type *string `json:"type,omitempty"`
Uid *string `json:"uid,omitempty"`
} `json:"datasource,omitempty"`
GridPos *GridPos `json:"gridPos,omitempty"`
Id int `json:"id"`
Panels []interface{} `json:"panels"`
// Name of template variable to repeat for.
Repeat *string `json:"repeat,omitempty"`
Title *string `json:"title,omitempty"`
Type RowPanelType `json:"type"`
}
// RowPanelType defines model for RowPanel.Type.
type RowPanelType string
// TODO docs
type Snapshot struct {
// TODO docs
Created string `json:"created"`
// TODO docs
Expires string `json:"expires"`
// TODO docs
External bool `json:"external"`
// TODO docs
ExternalUrl string `json:"externalUrl"`
// TODO docs
Id int `json:"id"`
// TODO docs
Key string `json:"key"`
// TODO docs
Name string `json:"name"`
// TODO docs
OrgId int `json:"orgId"`
// TODO docs
Updated string `json:"updated"`
// TODO docs
Url *string `json:"url,omitempty"`
// TODO docs
UserId int `json:"userId"`
}
// TODO docs
type SpecialValueMap struct {
Options struct {
Match SpecialValueMapOptionsMatch `json:"match"`
Pattern string `json:"pattern"`
// TODO docs
Result ValueMappingResult `json:"result"`
} `json:"options"`
Type struct {
// Embedded struct due to allOf(#/components/schemas/MappingType)
MappingType `yaml:",inline"`
// Embedded fields due to inline allOf schema
} `json:"type"`
}
// SpecialValueMapOptionsMatch defines model for SpecialValueMap.Options.Match.
type SpecialValueMapOptionsMatch string
// TODO docs
type SpecialValueMatch string
// Schema for panel targets is specified by datasource
// plugins. We use a placeholder definition, which the Go
// schema loader either left open/as-is with the Base
// variant of the Dashboard and Panel families, or filled
// with types derived from plugins in the Instance variant.
// When working directly from CUE, importers can extend this
// type directly to achieve the same effect.
type Target map[string]interface{}
// TODO docs
type Threshold struct {
// TODO docs
Color string `json:"color"`
// TODO docs
// TODO are the values here enumerable into a disjunction?
// Some seem to be listed in typescript comment
State *string `json:"state,omitempty"`
// TODO docs
// FIXME the corresponding typescript field is required/non-optional, but nulls currently appear here when serializing -Infinity to JSON
Value *float32 `json:"value,omitempty"`
}
// ThresholdsConfig defines model for ThresholdsConfig.
type ThresholdsConfig struct {
Mode ThresholdsMode `json:"mode"`
// Must be sorted by 'value', first value is always -Infinity
Steps []Threshold `json:"steps"`
}
// ThresholdsMode defines model for ThresholdsMode.
type ThresholdsMode string
// TODO docs
// FIXME this is extremely underspecfied; wasn't obvious which typescript types corresponded to it
type Transformation struct {
Id string `json:"id"`
Options map[string]interface{} `json:"options"`
}
// TODO docs
type ValueMap struct {
Options map[string]ValueMappingResult `json:"options"`
Type struct {
// Embedded struct due to allOf(#/components/schemas/MappingType)
MappingType `yaml:",inline"`
// Embedded fields due to inline allOf schema
} `json:"type"`
}
// TODO docs
type ValueMapping interface{}
// TODO docs
type ValueMappingResult struct {
Color *string `json:"color,omitempty"`
Icon *string `json:"icon,omitempty"`
Index *int32 `json:"index,omitempty"`
Text *string `json:"text,omitempty"`
}
// VariableHide defines model for VariableHide.
type VariableHide int
// FROM: packages/grafana-data/src/types/templateVars.ts
// TODO docs
// TODO what about what's in public/app/features/types.ts?
// TODO there appear to be a lot of different kinds of [template] vars here? if so need a disjunction
type VariableModel struct {
// Ref to a DataSource instance
Datasource *DataSourceRef `json:"datasource,omitempty"`
Description *string `json:"description,omitempty"`
Error *map[string]interface{} `json:"error,omitempty"`
Global bool `json:"global"`
Hide VariableHide `json:"hide"`
Id string `json:"id"`
Index int `json:"index"`
Label *string `json:"label,omitempty"`
Name string `json:"name"`
// TODO: Move this into a separated QueryVariableModel type
Query *interface{} `json:"query,omitempty"`
RootStateKey *string `json:"rootStateKey,omitempty"`
SkipUrlSync bool `json:"skipUrlSync"`
State LoadingState `json:"state"`
// FROM: packages/grafana-data/src/types/templateVars.ts
// TODO docs
// TODO this implies some wider pattern/discriminated union, probably?
Type VariableType `json:"type"`
}
// FROM: packages/grafana-data/src/types/templateVars.ts
// TODO docs
// TODO this implies some wider pattern/discriminated union, probably?
type VariableType string
| pkg/kinds/dashboard/dashboard_types_gen.go | 1 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.0014955321094021201,
0.00021732834284193814,
0.0001593171473359689,
0.00016934759332798421,
0.00020652108651120216
]
|
{
"id": 8,
"code_window": [
"\n",
" it('Should ignore a lot of changes', () => {\n",
" const { original, dash } = getTestContext();\n",
" dash.time = { from: '1h' };\n",
" dash.refresh = true;\n",
" dash.schemaVersion = 10;\n",
" expect(hasChanges(dash, original)).toBe(false);\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" dash.refresh = '30s';\n"
],
"file_path": "public/app/features/dashboard/components/DashboardPrompt/DashboardPrompt.test.tsx",
"type": "replace",
"edit_start_line_idx": 58
} | package notifiers
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"os"
"strconv"
"strings"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/alerting/models"
"github.com/grafana/grafana/pkg/services/notifications"
"github.com/grafana/grafana/pkg/setting"
)
func init() {
alerting.RegisterNotifier(&alerting.NotifierPlugin{
Type: "discord",
Name: "Discord",
Description: "Sends notifications to Discord",
Factory: newDiscordNotifier,
Heading: "Discord settings",
Options: []alerting.NotifierOption{
{
Label: "Avatar URL",
Element: alerting.ElementTypeInput,
InputType: alerting.InputTypeText,
Description: "Provide a URL to an image to use as the avatar for the bot's message",
PropertyName: "avatar_url",
},
{
Label: "Message Content",
Description: "Mention a group using <@&ID> or a user using <@ID> when notifying in a channel",
Element: alerting.ElementTypeInput,
InputType: alerting.InputTypeText,
PropertyName: "content",
},
{
Label: "Webhook URL",
Element: alerting.ElementTypeInput,
InputType: alerting.InputTypeText,
Placeholder: "Discord webhook URL",
PropertyName: "url",
Required: true,
},
{
Label: "Use Discord's Webhook Username",
Description: "Use the username configured in Discord's webhook settings. Otherwise, the username will be 'Grafana'",
Element: alerting.ElementTypeCheckbox,
PropertyName: "use_discord_username",
},
},
})
}
func newDiscordNotifier(model *models.AlertNotification, _ alerting.GetDecryptedValueFn, ns notifications.Service) (alerting.Notifier, error) {
avatar := model.Settings.Get("avatar_url").MustString()
content := model.Settings.Get("content").MustString()
url := model.Settings.Get("url").MustString()
if url == "" {
return nil, alerting.ValidationError{Reason: "Could not find webhook url property in settings"}
}
useDiscordUsername := model.Settings.Get("use_discord_username").MustBool(false)
return &DiscordNotifier{
NotifierBase: NewNotifierBase(model, ns),
Content: content,
AvatarURL: avatar,
WebhookURL: url,
log: log.New("alerting.notifier.discord"),
UseDiscordUsername: useDiscordUsername,
}, nil
}
// DiscordNotifier is responsible for sending alert
// notifications to discord.
type DiscordNotifier struct {
NotifierBase
Content string
AvatarURL string
WebhookURL string
log log.Logger
UseDiscordUsername bool
}
// Notify send an alert notification to Discord.
func (dn *DiscordNotifier) Notify(evalContext *alerting.EvalContext) error {
dn.log.Info("Sending alert notification to", "webhook_url", dn.WebhookURL)
ruleURL, err := evalContext.GetRuleURL()
if err != nil {
dn.log.Error("Failed get rule link", "error", err)
return err
}
bodyJSON := simplejson.New()
if !dn.UseDiscordUsername {
bodyJSON.Set("username", "Grafana")
}
if dn.Content != "" {
bodyJSON.Set("content", dn.Content)
}
if dn.AvatarURL != "" {
bodyJSON.Set("avatar_url", dn.AvatarURL)
}
fields := make([]map[string]interface{}, 0)
for _, evt := range evalContext.EvalMatches {
fields = append(fields, map[string]interface{}{
// Discord uniquely does not send the alert if the metric field is empty,
// which it can be in some cases
"name": notEmpty(evt.Metric),
"value": evt.Value.FullString(),
"inline": true,
})
}
footer := map[string]interface{}{
"text": "Grafana v" + setting.BuildVersion,
"icon_url": "https://grafana.com/static/assets/img/fav32.png",
}
color, _ := strconv.ParseInt(strings.TrimLeft(evalContext.GetStateModel().Color, "#"), 16, 0)
embed := simplejson.New()
embed.Set("title", evalContext.GetNotificationTitle())
// Discord takes integer for color
embed.Set("color", color)
embed.Set("url", ruleURL)
embed.Set("description", evalContext.Rule.Message)
embed.Set("type", "rich")
embed.Set("fields", fields)
embed.Set("footer", footer)
var image map[string]interface{}
var embeddedImage = false
if dn.NeedsImage() {
if evalContext.ImagePublicURL != "" {
image = map[string]interface{}{
"url": evalContext.ImagePublicURL,
}
embed.Set("image", image)
} else {
image = map[string]interface{}{
"url": "attachment://graph.png",
}
embed.Set("image", image)
embeddedImage = true
}
}
bodyJSON.Set("embeds", []interface{}{embed})
json, _ := bodyJSON.MarshalJSON()
cmd := ¬ifications.SendWebhookSync{
Url: dn.WebhookURL,
HttpMethod: "POST",
ContentType: "application/json",
}
if !embeddedImage {
cmd.Body = string(json)
} else {
err := dn.embedImage(cmd, evalContext.ImageOnDiskPath, json)
if err != nil {
dn.log.Error("failed to embed image", "error", err)
return err
}
}
if err := dn.NotificationService.SendWebhookSync(evalContext.Ctx, cmd); err != nil {
dn.log.Error("Failed to send notification to Discord", "error", err)
return err
}
return nil
}
func (dn *DiscordNotifier) embedImage(cmd *notifications.SendWebhookSync, imagePath string, existingJSONBody []byte) error {
// nolint:gosec
// We can ignore the gosec G304 warning on this one because `imagePath` comes
// from the alert `evalContext` that generates the images.
f, err := os.Open(imagePath)
if err != nil {
if os.IsNotExist(err) {
cmd.Body = string(existingJSONBody)
return nil
}
if !os.IsNotExist(err) {
return err
}
}
defer func() {
if err := f.Close(); err != nil {
dn.log.Warn("Failed to close file", "path", imagePath, "err", err)
}
}()
var b bytes.Buffer
w := multipart.NewWriter(&b)
defer func() {
if err := w.Close(); err != nil {
// Should be OK since we already close it on non-error path
dn.log.Warn("Failed to close multipart writer", "err", err)
}
}()
fw, err := w.CreateFormField("payload_json")
if err != nil {
return err
}
if _, err = fw.Write([]byte(string(existingJSONBody))); err != nil {
return err
}
fw, err = w.CreateFormFile("file", "graph.png")
if err != nil {
return err
}
if _, err = io.Copy(fw, f); err != nil {
return err
}
if err := w.Close(); err != nil {
return fmt.Errorf("failed to close multipart writer: %w", err)
}
cmd.Body = b.String()
cmd.ContentType = w.FormDataContentType()
return nil
}
func notEmpty(metric string) string {
if metric == "" {
return "<NO_METRIC_NAME>"
}
return metric
}
| pkg/services/alerting/notifiers/discord.go | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.00018113806436304003,
0.0001753125397954136,
0.0001644511939957738,
0.0001764133630786091,
0.000004257678938301979
]
|
{
"id": 8,
"code_window": [
"\n",
" it('Should ignore a lot of changes', () => {\n",
" const { original, dash } = getTestContext();\n",
" dash.time = { from: '1h' };\n",
" dash.refresh = true;\n",
" dash.schemaVersion = 10;\n",
" expect(hasChanges(dash, original)).toBe(false);\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" dash.refresh = '30s';\n"
],
"file_path": "public/app/features/dashboard/components/DashboardPrompt/DashboardPrompt.test.tsx",
"type": "replace",
"edit_start_line_idx": 58
} | package testdatasource
import (
"encoding/json"
"fmt"
"io"
"net/http"
"sort"
"strconv"
"time"
"github.com/grafana/grafana/pkg/infra/log"
)
func (s *Service) registerRoutes() *http.ServeMux {
mux := http.NewServeMux()
mux.HandleFunc("/", s.testGetHandler)
mux.HandleFunc("/scenarios", s.getScenariosHandler)
mux.HandleFunc("/stream", s.testStreamHandler)
mux.Handle("/test", createJSONHandler(s.logger))
mux.Handle("/test/json", createJSONHandler(s.logger))
mux.HandleFunc("/boom", s.testPanicHandler)
mux.HandleFunc("/sims", s.sims.GetSimulationHandler)
mux.HandleFunc("/sim/", s.sims.GetSimulationHandler)
return mux
}
func (s *Service) testGetHandler(rw http.ResponseWriter, req *http.Request) {
s.logger.Debug("Received resource call", "url", req.URL.String(), "method", req.Method)
if req.Method != http.MethodGet {
return
}
if _, err := rw.Write([]byte("Hello world from test datasource!")); err != nil {
s.logger.Error("Failed to write response", "error", err)
return
}
rw.WriteHeader(http.StatusOK)
}
func (s *Service) getScenariosHandler(rw http.ResponseWriter, req *http.Request) {
result := make([]interface{}, 0)
scenarioIds := make([]string, 0)
for id := range s.scenarios {
scenarioIds = append(scenarioIds, id)
}
sort.Strings(scenarioIds)
for _, scenarioID := range scenarioIds {
scenario := s.scenarios[scenarioID]
result = append(result, map[string]interface{}{
"id": scenario.ID,
"name": scenario.Name,
"description": scenario.Description,
"stringInput": scenario.StringInput,
})
}
bytes, err := json.Marshal(&result)
if err != nil {
s.logger.Error("Failed to marshal response body to JSON", "error", err)
}
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(http.StatusOK)
if _, err := rw.Write(bytes); err != nil {
s.logger.Error("Failed to write response", "error", err)
}
}
func (s *Service) testStreamHandler(rw http.ResponseWriter, req *http.Request) {
s.logger.Debug("Received resource call", "url", req.URL.String(), "method", req.Method)
if req.Method != http.MethodGet {
return
}
count := 10
countstr := req.URL.Query().Get("count")
if countstr != "" {
if i, err := strconv.Atoi(countstr); err == nil {
count = i
}
}
sleep := req.URL.Query().Get("sleep")
sleepDuration, err := time.ParseDuration(sleep)
if err != nil {
sleepDuration = time.Millisecond
}
rw.Header().Set("Content-Type", "text/plain")
rw.WriteHeader(http.StatusOK)
for i := 1; i <= count; i++ {
if _, err := io.WriteString(rw, fmt.Sprintf("Message #%d", i)); err != nil {
s.logger.Error("Failed to write response", "error", err)
return
}
rw.(http.Flusher).Flush()
time.Sleep(sleepDuration)
}
}
func createJSONHandler(logger log.Logger) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
logger.Debug("Received resource call", "url", req.URL.String(), "method", req.Method)
var reqData map[string]interface{}
if req.Body != nil {
defer func() {
if err := req.Body.Close(); err != nil {
logger.Warn("Failed to close response body", "err", err)
}
}()
b, err := io.ReadAll(req.Body)
if err != nil {
logger.Error("Failed to read request body to bytes", "error", err)
} else {
err := json.Unmarshal(b, &reqData)
if err != nil {
logger.Error("Failed to unmarshal request body to JSON", "error", err)
}
logger.Debug("Received resource call body", "body", reqData)
}
}
data := map[string]interface{}{
"message": "Hello world from test datasource!",
"request": map[string]interface{}{
"method": req.Method,
"url": req.URL,
"headers": req.Header,
"body": reqData,
},
}
bytes, err := json.Marshal(&data)
if err != nil {
logger.Error("Failed to marshal response body to JSON", "error", err)
}
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(http.StatusOK)
if _, err := rw.Write(bytes); err != nil {
logger.Error("Failed to write response", "error", err)
}
})
}
func (s *Service) testPanicHandler(rw http.ResponseWriter, req *http.Request) {
panic("BOOM")
}
| pkg/tsdb/testdatasource/resource_handler.go | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.00017890201706904918,
0.00017460680101066828,
0.00017162472067866474,
0.00017387258412782103,
0.0000022012459339748602
]
|
{
"id": 8,
"code_window": [
"\n",
" it('Should ignore a lot of changes', () => {\n",
" const { original, dash } = getTestContext();\n",
" dash.time = { from: '1h' };\n",
" dash.refresh = true;\n",
" dash.schemaVersion = 10;\n",
" expect(hasChanges(dash, original)).toBe(false);\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" dash.refresh = '30s';\n"
],
"file_path": "public/app/features/dashboard/components/DashboardPrompt/DashboardPrompt.test.tsx",
"type": "replace",
"edit_start_line_idx": 58
} | // Package cuectx provides a single, central ["cuelang.org/go/cue".Context] and
// ["github.com/grafana/thema".Runtime] that can be used uniformly across
// Grafana, and related helper functions for loading Thema lineages.
package cuectx
import (
"fmt"
"io/fs"
"path/filepath"
"testing/fstest"
"cuelang.org/go/cue"
"cuelang.org/go/cue/build"
"cuelang.org/go/cue/cuecontext"
"github.com/grafana/grafana"
"github.com/grafana/thema"
"github.com/grafana/thema/load"
"github.com/grafana/thema/vmux"
"github.com/yalue/merged_fs"
)
var ctx = cuecontext.New()
var rt = thema.NewRuntime(ctx)
// GrafanaCUEContext returns Grafana's singleton instance of [cue.Context].
//
// All code within grafana/grafana that needs a *cue.Context should get it
// from this function, when one was not otherwise provided.
func GrafanaCUEContext() *cue.Context {
return ctx
}
// GrafanaThemaRuntime returns Grafana's singleton instance of [thema.Runtime].
//
// All code within grafana/grafana that needs a *thema.Runtime should get it
// from this function, when one was not otherwise provided.
func GrafanaThemaRuntime() *thema.Runtime {
return rt
}
// JSONtoCUE attempts to decode the given []byte into a cue.Value, relying on
// the central Grafana cue.Context provided in this package.
//
// The provided path argument determines the name given to the input bytes if
// later CUE operations (e.g. Thema validation) produce errors related to the
// returned cue.Value.
//
// This is a convenience function for one-off JSON decoding. It's wasteful to
// call it repeatedly. Most use cases should probably prefer making
// their own Thema/CUE decoders.
func JSONtoCUE(path string, b []byte) (cue.Value, error) {
return vmux.NewJSONCodec(path).Decode(ctx, b)
}
// LoadGrafanaInstancesWithThema loads CUE files containing a lineage
// representing some Grafana core model schema. It is expected to be used when
// implementing a thema.LineageFactory.
//
// This function primarily juggles paths to make CUE's loader happy. Provide the
// path from the grafana root to the directory containing the lineage.cue. The
// lineage.cue file must be the sole contents of the provided fs.FS.
//
// More details on underlying behavior can be found in the docs for github.com/grafana/thema/load.InstanceWithThema.
//
// TODO this approach is complicated and confusing, refactor to something understandable
func LoadGrafanaInstancesWithThema(path string, cueFS fs.FS, rt *thema.Runtime, opts ...thema.BindOption) (thema.Lineage, error) {
prefix := filepath.FromSlash(path)
fs, err := prefixWithGrafanaCUE(prefix, cueFS)
if err != nil {
return nil, err
}
inst, err := load.InstanceWithThema(fs, prefix)
// Need to trick loading by creating the embedded file and
// making it look like a module in the root dir.
if err != nil {
return nil, err
}
val := rt.Context().BuildInstance(inst)
lin, err := thema.BindLineage(val, rt, opts...)
if err != nil {
return nil, err
}
return lin, nil
}
// prefixWithGrafanaCUE constructs an fs.FS that merges the provided fs.FS with
// the embedded FS containing Grafana's core CUE files, [grafana.CueSchemaFS].
// The provided prefix should be the relative path from the grafana repository
// root to the directory root of the provided inputfs.
//
// The returned fs.FS is suitable for passing to a CUE loader, such as [load.InstanceWithThema].
func prefixWithGrafanaCUE(prefix string, inputfs fs.FS) (fs.FS, error) {
m, err := prefixFS(prefix, inputfs)
if err != nil {
return nil, err
}
return merged_fs.NewMergedFS(m, grafana.CueSchemaFS), nil
}
// TODO such a waste, replace with stateless impl that just transforms paths on the fly
func prefixFS(prefix string, fsys fs.FS) (fs.FS, error) {
m := make(fstest.MapFS)
prefix = filepath.FromSlash(prefix)
err := fs.WalkDir(fsys, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
b, err := fs.ReadFile(fsys, path)
if err != nil {
return err
}
// fstest can recognize only forward slashes.
m[filepath.ToSlash(filepath.Join(prefix, path))] = &fstest.MapFile{Data: b}
return nil
})
return m, err
}
// LoadGrafanaInstance wraps [load.InstanceWithThema] to load a
// [*build.Instance] corresponding to a particular path within the
// github.com/grafana/grafana CUE module.
//
// This allows resolution of imports within the grafana or thema CUE modules to
// work correctly and consistently by relying on the embedded FS at
// [grafana.CueSchemaFS] and [thema.CueFS].
//
// relpath should be a relative path path within [grafana.CueSchemaFS] to be
// loaded. Optionally, the caller may provide an additional fs.FS via the
// overlay parameter, which will be merged with [grafana.CueSchemaFS] at
// relpath, and loaded.
//
// pkg, if non-empty, is set as the value of
// ["cuelang.org/go/cue/load".Config.Package]. If the CUE package to be loaded
// is the same as the parent directory name, it should be omitted.
//
// NOTE this function will be deprecated in favor of a more generic loader
func LoadGrafanaInstance(relpath string, pkg string, overlay fs.FS) (*build.Instance, error) {
// notes about how this crap needs to work
//
// Within grafana/grafana, need:
// - pass in an fs.FS that, in its root, contains the .cue files to load
// - has no cue.mod
// - gets prefixed with the appropriate path within grafana/grafana
// - and merged with all the other .cue files from grafana/grafana
// notes about how this crap needs to work
//
// Need a prefixing instance loader that:
// - can take multiple fs.FS, each one representing a CUE module (nesting?)
// - reconcile at most one of the provided fs with cwd
// - behavior must differ depending on whether cwd is in a cue module
// - behavior should(?) be controllable depending on
relpath = filepath.ToSlash(relpath)
var f fs.FS = grafana.CueSchemaFS
var err error
if overlay != nil {
f, err = prefixWithGrafanaCUE(relpath, overlay)
if err != nil {
return nil, err
}
}
if pkg != "" {
return load.InstanceWithThema(f, relpath, load.Package(pkg))
}
return load.InstanceWithThema(f, relpath)
}
// BuildGrafanaInstance wraps [LoadGrafanaInstance], additionally building
// the returned [*build.Instance] into a [cue.Value].
//
// An error is returned if:
// - The underlying call to [LoadGrafanaInstance] returns an error
// - The built [cue.Value] has an error ([cue.Value.Err] returns non-nil)
//
// NOTE this function will be deprecated in favor of a more generic builder
func BuildGrafanaInstance(ctx *cue.Context, relpath string, pkg string, overlay fs.FS) (cue.Value, error) {
bi, err := LoadGrafanaInstance(relpath, pkg, overlay)
if err != nil {
return cue.Value{}, err
}
if ctx == nil {
ctx = GrafanaCUEContext()
}
v := ctx.BuildInstance(bi)
if v.Err() != nil {
return v, fmt.Errorf("%s not a valid CUE instance: %w", relpath, v.Err())
}
return v, nil
}
// LoadInstanceWithGrafana loads a [*build.Instance] from .cue files
// in the provided modFS as ["cuelang.org/go/cue/load".Instances], but
// fulfilling any imports of CUE packages under:
//
// - github.com/grafana/grafana
// - github.com/grafana/thema
//
// This function is modeled after [load.InstanceWithThema]. It has the same
// signature and expectations for the modFS.
//
// Attempting to use this func to load files within the
// github.com/grafana/grafana CUE module will result in an error. Use
// [LoadGrafanaInstance] instead.
//
// NOTE This function will be deprecated in favor of a more generic loader
func LoadInstanceWithGrafana(fsys fs.FS, dir string, opts ...load.Option) (*build.Instance, error) {
if modf, err := fs.ReadFile(fsys, filepath.Join("cue.mod", "module.cue")); err != nil {
// delegate error handling
return load.InstanceWithThema(fsys, dir, opts...)
} else if modname, err := cuecontext.New().CompileBytes(modf).LookupPath(cue.MakePath(cue.Str("module"))).String(); err != nil {
// delegate error handling
return load.InstanceWithThema(fsys, dir, opts...)
} else if modname == "github.com/grafana/grafana" {
return nil, fmt.Errorf("use cuectx.LoadGrafanaInstance to load .cue files within github.com/grafana/grafana CUE module")
}
// TODO wasteful, doing this every time - make that stateless prefixfs!
depFS, err := prefixFS("cue.mod/pkg/github.com/grafana/grafana", grafana.CueSchemaFS)
if err != nil {
panic(err)
}
// FIXME remove grafana from cue.mod/pkg if it exists, otherwise external thing can inject files to be loaded
return load.InstanceWithThema(merged_fs.NewMergedFS(depFS, fsys), dir, opts...)
}
| pkg/cuectx/ctx.go | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.00041397675522603095,
0.000187445359188132,
0.00016285468882415444,
0.0001744121836964041,
0.0000494563028041739
]
|
{
"id": 9,
"code_window": [
" const dash = model.getSaveModelClone();\n",
"\n",
" // ignore time and refresh\n",
" dash.time = 0;\n",
" dash.refresh = 0;\n",
" dash.schemaVersion = 0;\n",
" dash.timezone = 0;\n",
"\n",
" dash.panels = [];\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" dash.refresh = '';\n"
],
"file_path": "public/app/features/dashboard/components/DashboardPrompt/DashboardPrompt.tsx",
"type": "replace",
"edit_start_line_idx": 180
} | import { getPanelPlugin } from '@grafana/data/test/__mocks__/pluginMocks';
import { setContextSrv } from '../../../../core/services/context_srv';
import { PanelModel } from '../../state/PanelModel';
import { createDashboardModelFixture, createPanelJSONFixture } from '../../state/__fixtures__/dashboardFixtures';
import { hasChanges, ignoreChanges } from './DashboardPrompt';
function getDefaultDashboardModel() {
return createDashboardModelFixture({
refresh: false,
panels: [
createPanelJSONFixture({
id: 1,
type: 'graph',
gridPos: { x: 0, y: 0, w: 24, h: 6 },
legend: { show: true, sortDesc: false }, // TODO legend is marked as a non-persisted field
}),
{
id: 2,
type: 'row',
gridPos: { x: 0, y: 6, w: 24, h: 2 },
collapsed: true,
panels: [
{ id: 3, type: 'graph', gridPos: { x: 0, y: 6, w: 12, h: 2 } },
{ id: 4, type: 'graph', gridPos: { x: 12, y: 6, w: 12, h: 2 } },
],
},
{ id: 5, type: 'row', gridPos: { x: 0, y: 6, w: 1, h: 1 }, collapsed: false, panels: [] },
],
});
}
function getTestContext() {
const contextSrv: any = { isSignedIn: true, isEditor: true };
setContextSrv(contextSrv);
const dash = getDefaultDashboardModel();
const original = dash.getSaveModelClone();
return { dash, original, contextSrv };
}
describe('DashboardPrompt', () => {
it('No changes should not have changes', () => {
const { original, dash } = getTestContext();
expect(hasChanges(dash, original)).toBe(false);
});
it('Simple change should be registered', () => {
const { original, dash } = getTestContext();
dash.title = 'google';
expect(hasChanges(dash, original)).toBe(true);
});
it('Should ignore a lot of changes', () => {
const { original, dash } = getTestContext();
dash.time = { from: '1h' };
dash.refresh = true;
dash.schemaVersion = 10;
expect(hasChanges(dash, original)).toBe(false);
});
it('Should ignore row collapse change', () => {
const { original, dash } = getTestContext();
dash.toggleRow(dash.panels[1]);
expect(hasChanges(dash, original)).toBe(false);
});
it('Should ignore panel legend changes', () => {
const { original, dash } = getTestContext();
dash.panels[0]!.legend!.sortDesc = true;
dash.panels[0]!.legend!.sort = 'avg';
expect(hasChanges(dash, original)).toBe(false);
});
it('Should ignore panel repeats', () => {
const { original, dash } = getTestContext();
dash.panels.push(new PanelModel({ repeatPanelId: 10 }));
expect(hasChanges(dash, original)).toBe(false);
});
describe('ignoreChanges', () => {
describe('when called without original dashboard', () => {
it('then it should return true', () => {
const { dash } = getTestContext();
expect(ignoreChanges(dash, null)).toBe(true);
});
});
describe('when called without current dashboard', () => {
it('then it should return true', () => {
const { original } = getTestContext();
expect(ignoreChanges(null, original)).toBe(true);
});
});
describe('when called for a viewer without save permissions', () => {
it('then it should return true', () => {
const { contextSrv } = getTestContext();
const dash = createDashboardModelFixture({}, { canSave: false });
const original = dash.getSaveModelClone();
contextSrv.isEditor = false;
expect(ignoreChanges(dash, original)).toBe(true);
});
});
describe('when called for a viewer with save permissions', () => {
it('then it should return undefined', () => {
const { contextSrv } = getTestContext();
const dash = createDashboardModelFixture({}, { canSave: true });
const original = dash.getSaveModelClone();
contextSrv.isEditor = false;
expect(ignoreChanges(dash, original)).toBe(undefined);
});
});
describe('when called for an user that is not signed in', () => {
it('then it should return true', () => {
const { contextSrv } = getTestContext();
const dash = createDashboardModelFixture({}, { canSave: true });
const original = dash.getSaveModelClone();
contextSrv.isSignedIn = false;
expect(ignoreChanges(dash, original)).toBe(true);
});
});
describe('when called with fromScript', () => {
it('then it should return true', () => {
const dash = createDashboardModelFixture({}, { canSave: true, fromScript: true, fromFile: undefined });
const original = dash.getSaveModelClone();
expect(ignoreChanges(dash, original)).toBe(true);
});
});
it('Should ignore panel schema migrations', () => {
const { original, dash } = getTestContext();
const plugin = getPanelPlugin({}).setMigrationHandler((panel) => {
delete (panel as any).legend;
return { option1: 'Aasd' };
});
dash.panels[0].pluginLoaded(plugin);
expect(hasChanges(dash, original)).toBe(false);
});
describe('when called with fromFile', () => {
it('then it should return true', () => {
const dash = createDashboardModelFixture({}, { canSave: true, fromScript: undefined, fromFile: true });
const original = dash.getSaveModelClone();
expect(ignoreChanges(dash, original)).toBe(true);
});
});
describe('when called with canSave but without fromScript and fromFile', () => {
it('then it should return false', () => {
const dash = createDashboardModelFixture({}, { canSave: true, fromScript: undefined, fromFile: undefined });
const original = dash.getSaveModelClone();
expect(ignoreChanges(dash, original)).toBe(undefined);
});
});
});
});
| public/app/features/dashboard/components/DashboardPrompt/DashboardPrompt.test.tsx | 1 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.9948791265487671,
0.6525442004203796,
0.00016866240184754133,
0.9285070300102234,
0.43635478615760803
]
|
{
"id": 9,
"code_window": [
" const dash = model.getSaveModelClone();\n",
"\n",
" // ignore time and refresh\n",
" dash.time = 0;\n",
" dash.refresh = 0;\n",
" dash.schemaVersion = 0;\n",
" dash.timezone = 0;\n",
"\n",
" dash.panels = [];\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" dash.refresh = '';\n"
],
"file_path": "public/app/features/dashboard/components/DashboardPrompt/DashboardPrompt.tsx",
"type": "replace",
"edit_start_line_idx": 180
} | // This component is based on logic from the flamebearer project
// https://github.com/mapbox/flamebearer
// ISC License
// Copyright (c) 2018, Mapbox
// Permission to use, copy, modify, and/or distribute this software for any purpose
// with or without fee is hereby granted, provided that the above copyright notice
// and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
// OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
// THIS SOFTWARE.
import { css } from '@emotion/css';
import uFuzzy from '@leeoniya/ufuzzy';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useMeasure } from 'react-use';
import { CoreApp, createTheme, DataFrame, FieldType, getDisplayProcessor } from '@grafana/data';
import { PIXELS_PER_LEVEL } from '../../constants';
import { TooltipData, SelectedView } from '../types';
import FlameGraphTooltip, { getTooltipData } from './FlameGraphTooltip';
import { ItemWithStart } from './dataTransform';
import { getBarX, getRectDimensionsForLevel, renderRect } from './rendering';
type Props = {
data: DataFrame;
app: CoreApp;
flameGraphHeight?: number;
levels: ItemWithStart[][];
topLevelIndex: number;
rangeMin: number;
rangeMax: number;
search: string;
setTopLevelIndex: (level: number) => void;
setRangeMin: (range: number) => void;
setRangeMax: (range: number) => void;
selectedView: SelectedView;
style?: React.CSSProperties;
};
const FlameGraph = ({
data,
app,
flameGraphHeight,
levels,
topLevelIndex,
rangeMin,
rangeMax,
search,
setTopLevelIndex,
setRangeMin,
setRangeMax,
selectedView,
}: Props) => {
const styles = getStyles(selectedView, app, flameGraphHeight);
const totalTicks = data.fields[1].values.get(0);
const valueField =
data.fields.find((f) => f.name === 'value') ?? data.fields.find((f) => f.type === FieldType.number);
if (!valueField) {
throw new Error('Malformed dataFrame: value field of type number is not in the query response');
}
const [sizeRef, { width: wrapperWidth }] = useMeasure<HTMLDivElement>();
const graphRef = useRef<HTMLCanvasElement>(null);
const tooltipRef = useRef<HTMLDivElement>(null);
const [tooltipData, setTooltipData] = useState<TooltipData>();
const [showTooltip, setShowTooltip] = useState(false);
// Convert pixel coordinates to bar coordinates in the levels array so that we can add mouse events like clicks to
// the canvas.
const convertPixelCoordinatesToBarCoordinates = useCallback(
(x: number, y: number, pixelsPerTick: number) => {
const levelIndex = Math.floor(y / (PIXELS_PER_LEVEL / window.devicePixelRatio));
const barIndex = getBarIndex(x, levels[levelIndex], pixelsPerTick, totalTicks, rangeMin);
return { levelIndex, barIndex };
},
[levels, totalTicks, rangeMin]
);
const render = useCallback(
(pixelsPerTick: number) => {
if (!levels.length) {
return;
}
const ctx = graphRef.current?.getContext('2d')!;
const graph = graphRef.current!;
const height = PIXELS_PER_LEVEL * levels.length;
graph.width = Math.round(wrapperWidth * window.devicePixelRatio);
graph.height = Math.round(height * window.devicePixelRatio);
graph.style.width = `${wrapperWidth}px`;
graph.style.height = `${height}px`;
ctx.textBaseline = 'middle';
ctx.font = 12 * window.devicePixelRatio + 'px monospace';
ctx.strokeStyle = 'white';
const processor = getDisplayProcessor({
field: valueField,
theme: createTheme() /* theme does not matter for us here */,
});
const ufuzzy = new uFuzzy({
intraMode: 0,
intraIns: 0,
});
for (let levelIndex = 0; levelIndex < levels.length; levelIndex++) {
const level = levels[levelIndex];
// Get all the dimensions of the rectangles for the level. We do this by level instead of per rectangle, because
// sometimes we collapse multiple bars into single rect.
const dimensions = getRectDimensionsForLevel(level, levelIndex, totalTicks, rangeMin, pixelsPerTick, processor);
for (const rect of dimensions) {
// Render each rectangle based on the computed dimensions
renderRect(ctx, rect, totalTicks, rangeMin, rangeMax, search, levelIndex, topLevelIndex, ufuzzy);
}
}
},
[levels, wrapperWidth, valueField, totalTicks, rangeMin, rangeMax, search, topLevelIndex]
);
useEffect(() => {
if (graphRef.current) {
const pixelsPerTick = (wrapperWidth * window.devicePixelRatio) / totalTicks / (rangeMax - rangeMin);
render(pixelsPerTick);
// Clicking allows user to "zoom" into the flamegraph. Zooming means the x axis gets smaller so that the clicked
// bar takes 100% of the x axis.
graphRef.current.onclick = (e) => {
const pixelsPerTick = graphRef.current!.clientWidth / totalTicks / (rangeMax - rangeMin);
const { levelIndex, barIndex } = convertPixelCoordinatesToBarCoordinates(e.offsetX, e.offsetY, pixelsPerTick);
if (barIndex !== -1 && !isNaN(levelIndex) && !isNaN(barIndex)) {
setTopLevelIndex(levelIndex);
setRangeMin(levels[levelIndex][barIndex].start / totalTicks);
setRangeMax((levels[levelIndex][barIndex].start + levels[levelIndex][barIndex].value) / totalTicks);
}
};
graphRef.current!.onmousemove = (e) => {
if (tooltipRef.current) {
setShowTooltip(false);
const pixelsPerTick = graphRef.current!.clientWidth / totalTicks / (rangeMax - rangeMin);
const { levelIndex, barIndex } = convertPixelCoordinatesToBarCoordinates(e.offsetX, e.offsetY, pixelsPerTick);
if (barIndex !== -1 && !isNaN(levelIndex) && !isNaN(barIndex)) {
tooltipRef.current.style.left = e.clientX + 10 + 'px';
tooltipRef.current.style.top = e.clientY + 'px';
const bar = levels[levelIndex][barIndex];
const tooltipData = getTooltipData(valueField, bar.label, bar.value, bar.self, totalTicks);
setTooltipData(tooltipData);
setShowTooltip(true);
}
}
};
graphRef.current!.onmouseleave = () => {
setShowTooltip(false);
};
}
}, [
render,
convertPixelCoordinatesToBarCoordinates,
levels,
rangeMin,
rangeMax,
topLevelIndex,
totalTicks,
wrapperWidth,
setTopLevelIndex,
setRangeMin,
setRangeMax,
selectedView,
valueField,
]);
return (
<div className={styles.graph} ref={sizeRef}>
<canvas ref={graphRef} data-testid="flameGraph" />
<FlameGraphTooltip tooltipRef={tooltipRef} tooltipData={tooltipData!} showTooltip={showTooltip} />
</div>
);
};
const getStyles = (selectedView: SelectedView, app: CoreApp, flameGraphHeight: number | undefined) => ({
graph: css`
cursor: pointer;
float: left;
overflow: scroll;
width: ${selectedView === SelectedView.FlameGraph ? '100%' : '50%'};
${app !== CoreApp.Explore
? `height: calc(${flameGraphHeight}px - 44px)`
: ''}; // 44px to adjust for header pushing content down
`,
});
/**
* Binary search for a bar in a level, based on the X pixel coordinate. Useful for detecting which bar did user click
* on.
*/
const getBarIndex = (
x: number,
level: ItemWithStart[],
pixelsPerTick: number,
totalTicks: number,
rangeMin: number
) => {
if (level) {
let start = 0;
let end = level.length - 1;
while (start <= end) {
const midIndex = (start + end) >> 1;
const startOfBar = getBarX(level[midIndex].start, totalTicks, rangeMin, pixelsPerTick);
const startOfNextBar = getBarX(
level[midIndex].start + level[midIndex].value,
totalTicks,
rangeMin,
pixelsPerTick
);
if (startOfBar <= x && startOfNextBar >= x) {
return midIndex;
}
if (startOfBar > x) {
end = midIndex - 1;
} else {
start = midIndex + 1;
}
}
}
return -1;
};
export default FlameGraph;
| public/app/plugins/panel/flamegraph/components/FlameGraph/FlameGraph.tsx | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.0001786001812433824,
0.000174334563780576,
0.00016617878281977028,
0.00017530022887513041,
0.000002691371037144563
]
|
{
"id": 9,
"code_window": [
" const dash = model.getSaveModelClone();\n",
"\n",
" // ignore time and refresh\n",
" dash.time = 0;\n",
" dash.refresh = 0;\n",
" dash.schemaVersion = 0;\n",
" dash.timezone = 0;\n",
"\n",
" dash.panels = [];\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" dash.refresh = '';\n"
],
"file_path": "public/app/features/dashboard/components/DashboardPrompt/DashboardPrompt.tsx",
"type": "replace",
"edit_start_line_idx": 180
} | package influxdb
import (
"fmt"
"strconv"
"time"
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana/pkg/components/simplejson"
)
type InfluxdbQueryParser struct{}
func (qp *InfluxdbQueryParser) Parse(query backend.DataQuery) (*Query, error) {
model, err := simplejson.NewJson(query.JSON)
if err != nil {
return nil, fmt.Errorf("couldn't unmarshal query")
}
policy := model.Get("policy").MustString("default")
rawQuery := model.Get("query").MustString("")
useRawQuery := model.Get("rawQuery").MustBool(false)
alias := model.Get("alias").MustString("")
tz := model.Get("tz").MustString("")
limit := model.Get("limit").MustString("")
slimit := model.Get("slimit").MustString("")
orderByTime := model.Get("orderByTime").MustString("")
measurement := model.Get("measurement").MustString("")
tags, err := qp.parseTags(model)
if err != nil {
return nil, err
}
groupBys, err := qp.parseGroupBy(model)
if err != nil {
return nil, err
}
selects, err := qp.parseSelects(model)
if err != nil {
return nil, err
}
interval := query.Interval
// we make sure it is at least 1 millisecond
minInterval := time.Millisecond
if interval < minInterval {
interval = minInterval
}
return &Query{
Measurement: measurement,
Policy: policy,
GroupBy: groupBys,
Tags: tags,
Selects: selects,
RawQuery: rawQuery,
Interval: interval,
Alias: alias,
UseRawQuery: useRawQuery,
Tz: tz,
Limit: limit,
Slimit: slimit,
OrderByTime: orderByTime,
}, nil
}
func (qp *InfluxdbQueryParser) parseSelects(model *simplejson.Json) ([]*Select, error) {
selectObjs := model.Get("select").MustArray()
result := make([]*Select, 0, len(selectObjs))
for _, selectObj := range selectObjs {
selectJson := simplejson.NewFromAny(selectObj)
var parts Select
for _, partObj := range selectJson.MustArray() {
part := simplejson.NewFromAny(partObj)
queryPart, err := qp.parseQueryPart(part)
if err != nil {
return nil, err
}
parts = append(parts, *queryPart)
}
result = append(result, &parts)
}
return result, nil
}
func (*InfluxdbQueryParser) parseTags(model *simplejson.Json) ([]*Tag, error) {
tags := model.Get("tags").MustArray()
result := make([]*Tag, 0, len(tags))
for _, t := range tags {
tagJson := simplejson.NewFromAny(t)
tag := &Tag{}
var err error
tag.Key, err = tagJson.Get("key").String()
if err != nil {
return nil, err
}
tag.Value, err = tagJson.Get("value").String()
if err != nil {
return nil, err
}
operator, err := tagJson.Get("operator").String()
if err == nil {
tag.Operator = operator
}
condition, err := tagJson.Get("condition").String()
if err == nil {
tag.Condition = condition
}
result = append(result, tag)
}
return result, nil
}
func (*InfluxdbQueryParser) parseQueryPart(model *simplejson.Json) (*QueryPart, error) {
typ, err := model.Get("type").String()
if err != nil {
return nil, err
}
var params []string
for _, paramObj := range model.Get("params").MustArray() {
param := simplejson.NewFromAny(paramObj)
stringParam, err := param.String()
if err == nil {
params = append(params, stringParam)
continue
}
intParam, err := param.Int()
if err == nil {
params = append(params, strconv.Itoa(intParam))
continue
}
return nil, err
}
qp, err := NewQueryPart(typ, params)
if err != nil {
return nil, err
}
return qp, nil
}
func (qp *InfluxdbQueryParser) parseGroupBy(model *simplejson.Json) ([]*QueryPart, error) {
groupBy := model.Get("groupBy").MustArray()
result := make([]*QueryPart, 0, len(groupBy))
for _, groupObj := range groupBy {
groupJson := simplejson.NewFromAny(groupObj)
queryPart, err := qp.parseQueryPart(groupJson)
if err != nil {
return nil, err
}
result = append(result, queryPart)
}
return result, nil
}
| pkg/tsdb/influxdb/model_parser.go | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.001702932408079505,
0.0002593061653897166,
0.00016404179041273892,
0.00017577075050212443,
0.00035020848736166954
]
|
{
"id": 9,
"code_window": [
" const dash = model.getSaveModelClone();\n",
"\n",
" // ignore time and refresh\n",
" dash.time = 0;\n",
" dash.refresh = 0;\n",
" dash.schemaVersion = 0;\n",
" dash.timezone = 0;\n",
"\n",
" dash.panels = [];\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" dash.refresh = '';\n"
],
"file_path": "public/app/features/dashboard/components/DashboardPrompt/DashboardPrompt.tsx",
"type": "replace",
"edit_start_line_idx": 180
} | <svg xmlns="http://www.w3.org/2000/svg" data-name="Layer 1" viewBox="0 0 24 24"><path d="M22,5.8a8.49,8.49,0,0,1-2.36.64,4.13,4.13,0,0,0,1.81-2.27,8.21,8.21,0,0,1-2.61,1,4.1,4.1,0,0,0-7,3.74A11.64,11.64,0,0,1,3.39,4.62a4.16,4.16,0,0,0-.55,2.07A4.09,4.09,0,0,0,4.66,10.1,4.05,4.05,0,0,1,2.8,9.59v.05a4.1,4.1,0,0,0,3.3,4A3.93,3.93,0,0,1,5,13.81a4.9,4.9,0,0,1-.77-.07,4.11,4.11,0,0,0,3.83,2.84A8.22,8.22,0,0,1,3,18.34a7.93,7.93,0,0,1-1-.06,11.57,11.57,0,0,0,6.29,1.85A11.59,11.59,0,0,0,20,8.45c0-.17,0-.35,0-.53A8.43,8.43,0,0,0,22,5.8Z"/></svg> | public/img/icons/unicons/twitter.svg | 0 | https://github.com/grafana/grafana/commit/b9a1d8e5f994d49fb5b864be25f464f69f3aa412 | [
0.0001700813154457137,
0.0001700813154457137,
0.0001700813154457137,
0.0001700813154457137,
0
]
|
{
"id": 0,
"code_window": [
"\n",
"describe('SSR hydration', () => {\n",
" mockWarn()\n",
"\n",
" test('text', async () => {\n",
" const msg = ref('foo')\n",
" const { vnode, container } = mountWithHydration('foo', () => msg.value)\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" beforeEach(() => {\n",
" document.body.innerHTML = ''\n",
" })\n",
"\n"
],
"file_path": "packages/runtime-core/__tests__/hydration.spec.ts",
"type": "add",
"edit_start_line_idx": 39
} | import { ComponentInternalInstance } from '../component'
import { SuspenseBoundary } from './Suspense'
import {
RendererInternals,
MoveType,
RendererElement,
RendererNode,
RendererOptions
} from '../renderer'
import { VNode, VNodeArrayChildren, VNodeProps } from '../vnode'
import { isString, ShapeFlags } from '@vue/shared'
import { warn } from '../warning'
export interface TeleportProps {
to: string | RendererElement
disabled?: boolean
}
export const isTeleport = (type: any): boolean => type.__isTeleport
const isTeleportDisabled = (props: VNode['props']): boolean =>
props && (props.disabled || props.disabled === '')
const resolveTarget = <T = RendererElement>(
props: TeleportProps | null,
select: RendererOptions['querySelector']
): T | null => {
const targetSelector = props && props.to
if (isString(targetSelector)) {
if (!select) {
__DEV__ &&
warn(
`Current renderer does not support string target for Teleports. ` +
`(missing querySelector renderer option)`
)
return null
} else {
const target = select(targetSelector)
if (!target) {
__DEV__ &&
warn(
`Failed to locate Teleport target with selector "${targetSelector}".`
)
}
return target as any
}
} else {
if (__DEV__ && !targetSelector) {
warn(`Invalid Teleport target: ${targetSelector}`)
}
return targetSelector as any
}
}
export const TeleportImpl = {
__isTeleport: true,
process(
n1: VNode | null,
n2: VNode,
container: RendererElement,
anchor: RendererNode | null,
parentComponent: ComponentInternalInstance | null,
parentSuspense: SuspenseBoundary | null,
isSVG: boolean,
optimized: boolean,
internals: RendererInternals
) {
const {
mc: mountChildren,
pc: patchChildren,
pbc: patchBlockChildren,
o: { insert, querySelector, createText, createComment }
} = internals
const disabled = isTeleportDisabled(n2.props)
const { shapeFlag, children } = n2
if (n1 == null) {
// insert anchors in the main view
const placeholder = (n2.el = __DEV__
? createComment('teleport start')
: createText(''))
const mainAnchor = (n2.anchor = __DEV__
? createComment('teleport end')
: createText(''))
insert(placeholder, container, anchor)
insert(mainAnchor, container, anchor)
const target = (n2.target = resolveTarget(
n2.props as TeleportProps,
querySelector
))
const targetAnchor = (n2.targetAnchor = createText(''))
if (target) {
insert(targetAnchor, target)
} else if (__DEV__) {
warn('Invalid Teleport target on mount:', target, `(${typeof target})`)
}
const mount = (container: RendererElement, anchor: RendererNode) => {
// Teleport *always* has Array children. This is enforced in both the
// compiler and vnode children normalization.
if (shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
mountChildren(
children as VNodeArrayChildren,
container,
anchor,
parentComponent,
parentSuspense,
isSVG,
optimized
)
}
}
if (disabled) {
mount(container, mainAnchor)
} else if (target) {
mount(target, targetAnchor)
}
} else {
// update content
n2.el = n1.el
const mainAnchor = (n2.anchor = n1.anchor)!
const target = (n2.target = n1.target)!
const targetAnchor = (n2.targetAnchor = n1.targetAnchor)!
const wasDisabled = isTeleportDisabled(n1.props)
const currentContainer = wasDisabled ? container : target
const currentAnchor = wasDisabled ? mainAnchor : targetAnchor
if (n2.dynamicChildren) {
// fast path when the teleport happens to be a block root
patchBlockChildren(
n1.dynamicChildren!,
n2.dynamicChildren,
currentContainer,
parentComponent,
parentSuspense,
isSVG
)
} else if (!optimized) {
patchChildren(
n1,
n2,
currentContainer,
currentAnchor,
parentComponent,
parentSuspense,
isSVG
)
}
if (disabled) {
if (!wasDisabled) {
// enabled -> disabled
// move into main container
moveTeleport(
n2,
container,
mainAnchor,
internals,
TeleportMoveTypes.TOGGLE
)
}
} else {
// target changed
if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) {
const nextTarget = (n2.target = resolveTarget(
n2.props as TeleportProps,
querySelector
))
if (nextTarget) {
moveTeleport(
n2,
nextTarget,
null,
internals,
TeleportMoveTypes.TARGET_CHANGE
)
} else if (__DEV__) {
warn(
'Invalid Teleport target on update:',
target,
`(${typeof target})`
)
}
} else if (wasDisabled) {
// disabled -> enabled
// move into teleport target
moveTeleport(
n2,
target,
targetAnchor,
internals,
TeleportMoveTypes.TOGGLE
)
}
}
}
},
remove(
vnode: VNode,
{ r: remove, o: { remove: hostRemove } }: RendererInternals
) {
const { shapeFlag, children, anchor } = vnode
hostRemove(anchor!)
if (shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
for (let i = 0; i < (children as VNode[]).length; i++) {
remove((children as VNode[])[i])
}
}
},
move: moveTeleport,
hydrate: hydrateTeleport
}
export const enum TeleportMoveTypes {
TARGET_CHANGE,
TOGGLE, // enable / disable
REORDER // moved in the main view
}
function moveTeleport(
vnode: VNode,
container: RendererElement,
parentAnchor: RendererNode | null,
{ o: { insert }, m: move }: RendererInternals,
moveType: TeleportMoveTypes = TeleportMoveTypes.REORDER
) {
// move target anchor if this is a target change.
if (moveType === TeleportMoveTypes.TARGET_CHANGE) {
insert(vnode.targetAnchor!, container, parentAnchor)
}
const { el, anchor, shapeFlag, children, props } = vnode
const isReorder = moveType === TeleportMoveTypes.REORDER
// move main view anchor if this is a re-order.
if (isReorder) {
insert(el!, container, parentAnchor)
}
// if this is a re-order and teleport is enabled (content is in target)
// do not move children. So the opposite is: only move children if this
// is not a reorder, or the teleport is disabled
if (!isReorder || isTeleportDisabled(props)) {
// Teleport has either Array children or no children.
if (shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
for (let i = 0; i < (children as VNode[]).length; i++) {
move(
(children as VNode[])[i],
container,
parentAnchor,
MoveType.REORDER
)
}
}
}
// move main view anchor if this is a re-order.
if (isReorder) {
insert(anchor!, container, parentAnchor)
}
}
interface TeleportTargetElement extends Element {
// last teleport target
_lpa?: Node | null
}
function hydrateTeleport(
node: Node,
vnode: VNode,
parentComponent: ComponentInternalInstance | null,
parentSuspense: SuspenseBoundary | null,
optimized: boolean,
{
o: { nextSibling, parentNode, querySelector }
}: RendererInternals<Node, Element>,
hydrateChildren: (
node: Node | null,
vnode: VNode,
container: Element,
parentComponent: ComponentInternalInstance | null,
parentSuspense: SuspenseBoundary | null,
optimized: boolean
) => Node | null
): Node | null {
const target = (vnode.target = resolveTarget<Element>(
vnode.props as TeleportProps,
querySelector
))
if (target) {
// if multiple teleports rendered to the same target element, we need to
// pick up from where the last teleport finished instead of the first node
const targetNode =
(target as TeleportTargetElement)._lpa || target.firstChild
if (vnode.shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
if (isTeleportDisabled(vnode.props)) {
vnode.anchor = hydrateChildren(
nextSibling(node),
vnode,
parentNode(node)!,
parentComponent,
parentSuspense,
optimized
)
vnode.targetAnchor = targetNode
} else {
vnode.anchor = nextSibling(node)
vnode.targetAnchor = hydrateChildren(
targetNode,
vnode,
target,
parentComponent,
parentSuspense,
optimized
)
}
;(target as TeleportTargetElement)._lpa = nextSibling(
vnode.targetAnchor as Node
)
}
}
return vnode.anchor && nextSibling(vnode.anchor as Node)
}
// Force-casted public typing for h and TSX props inference
export const Teleport = (TeleportImpl as any) as {
__isTeleport: true
new (): { $props: VNodeProps & TeleportProps }
}
| packages/runtime-core/src/components/Teleport.ts | 1 | https://github.com/vuejs/core/commit/c463a71bb31f01da55927424533e2ece3a3c4efe | [
0.9972476363182068,
0.18344397842884064,
0.00016325566684827209,
0.0002629703958518803,
0.3810480535030365
]
|
{
"id": 0,
"code_window": [
"\n",
"describe('SSR hydration', () => {\n",
" mockWarn()\n",
"\n",
" test('text', async () => {\n",
" const msg = ref('foo')\n",
" const { vnode, container } = mountWithHydration('foo', () => msg.value)\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" beforeEach(() => {\n",
" document.body.innerHTML = ''\n",
" })\n",
"\n"
],
"file_path": "packages/runtime-core/__tests__/hydration.spec.ts",
"type": "add",
"edit_start_line_idx": 39
} | import { baseCompile as compile } from '../src'
import { SourceMapConsumer, RawSourceMap } from 'source-map'
describe('compiler: integration tests', () => {
const source = `
<div id="foo" :class="bar.baz">
{{ world.burn() }}
<div v-if="ok">yes</div>
<template v-else>no</template>
<div v-for="(value, index) in list"><span>{{ value + index }}</span></div>
</div>
`.trim()
interface Pos {
line: number
column: number
name?: string
}
function getPositionInCode(
code: string,
token: string,
expectName: string | boolean = false
): Pos {
const generatedOffset = code.indexOf(token)
let line = 1
let lastNewLinePos = -1
for (let i = 0; i < generatedOffset; i++) {
if (code.charCodeAt(i) === 10 /* newline char code */) {
line++
lastNewLinePos = i
}
}
const res: Pos = {
line,
column:
lastNewLinePos === -1
? generatedOffset
: generatedOffset - lastNewLinePos - 1
}
if (expectName) {
res.name = typeof expectName === 'string' ? expectName : token
}
return res
}
test('function mode', () => {
const { code, map } = compile(source, {
sourceMap: true,
filename: `foo.vue`
})
expect(code).toMatchSnapshot()
expect(map!.sources).toEqual([`foo.vue`])
expect(map!.sourcesContent).toEqual([source])
const consumer = new SourceMapConsumer(map as RawSourceMap)
expect(
consumer.originalPositionFor(getPositionInCode(code, `id`))
).toMatchObject(getPositionInCode(source, `id`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `"foo"`))
).toMatchObject(getPositionInCode(source, `"foo"`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `class:`))
).toMatchObject(getPositionInCode(source, `class=`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `bar`))
).toMatchObject(getPositionInCode(source, `bar`))
// without prefixIdentifiers: true, identifiers inside compound expressions
// are mapped to closest parent expression.
expect(
consumer.originalPositionFor(getPositionInCode(code, `baz`))
).toMatchObject(getPositionInCode(source, `bar`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `world`))
).toMatchObject(getPositionInCode(source, `world`))
// without prefixIdentifiers: true, identifiers inside compound expressions
// are mapped to closest parent expression.
expect(
consumer.originalPositionFor(getPositionInCode(code, `burn()`))
).toMatchObject(getPositionInCode(source, `world`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `ok`))
).toMatchObject(getPositionInCode(source, `ok`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `list`))
).toMatchObject(getPositionInCode(source, `list`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `value`))
).toMatchObject(getPositionInCode(source, `value`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `index`))
).toMatchObject(getPositionInCode(source, `index`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `value + index`))
).toMatchObject(getPositionInCode(source, `value + index`))
})
test('function mode w/ prefixIdentifiers: true', () => {
const { code, map } = compile(source, {
sourceMap: true,
filename: `foo.vue`,
prefixIdentifiers: true
})
expect(code).toMatchSnapshot()
expect(map!.sources).toEqual([`foo.vue`])
expect(map!.sourcesContent).toEqual([source])
const consumer = new SourceMapConsumer(map as RawSourceMap)
expect(
consumer.originalPositionFor(getPositionInCode(code, `id`))
).toMatchObject(getPositionInCode(source, `id`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `"foo"`))
).toMatchObject(getPositionInCode(source, `"foo"`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `class:`))
).toMatchObject(getPositionInCode(source, `class=`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `bar`))
).toMatchObject(getPositionInCode(source, `bar`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `_ctx.bar`, `bar`))
).toMatchObject(getPositionInCode(source, `bar`, true))
expect(
consumer.originalPositionFor(getPositionInCode(code, `baz`))
).toMatchObject(getPositionInCode(source, `baz`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `world`, true))
).toMatchObject(getPositionInCode(source, `world`, `world`))
expect(
consumer.originalPositionFor(
getPositionInCode(code, `_ctx.world`, `world`)
)
).toMatchObject(getPositionInCode(source, `world`, `world`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `burn()`))
).toMatchObject(getPositionInCode(source, `burn()`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `ok`))
).toMatchObject(getPositionInCode(source, `ok`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `_ctx.ok`, `ok`))
).toMatchObject(getPositionInCode(source, `ok`, true))
expect(
consumer.originalPositionFor(getPositionInCode(code, `list`))
).toMatchObject(getPositionInCode(source, `list`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `_ctx.list`, `list`))
).toMatchObject(getPositionInCode(source, `list`, true))
expect(
consumer.originalPositionFor(getPositionInCode(code, `value`))
).toMatchObject(getPositionInCode(source, `value`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `index`))
).toMatchObject(getPositionInCode(source, `index`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `value + index`))
).toMatchObject(getPositionInCode(source, `value + index`))
})
test('module mode', () => {
const { code, map } = compile(source, {
mode: 'module',
sourceMap: true,
filename: `foo.vue`
})
expect(code).toMatchSnapshot()
expect(map!.sources).toEqual([`foo.vue`])
expect(map!.sourcesContent).toEqual([source])
const consumer = new SourceMapConsumer(map as RawSourceMap)
expect(
consumer.originalPositionFor(getPositionInCode(code, `id`))
).toMatchObject(getPositionInCode(source, `id`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `"foo"`))
).toMatchObject(getPositionInCode(source, `"foo"`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `class:`))
).toMatchObject(getPositionInCode(source, `class=`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `bar`))
).toMatchObject(getPositionInCode(source, `bar`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `_ctx.bar`, `bar`))
).toMatchObject(getPositionInCode(source, `bar`, true))
expect(
consumer.originalPositionFor(getPositionInCode(code, `baz`))
).toMatchObject(getPositionInCode(source, `baz`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `world`, true))
).toMatchObject(getPositionInCode(source, `world`, `world`))
expect(
consumer.originalPositionFor(
getPositionInCode(code, `_ctx.world`, `world`)
)
).toMatchObject(getPositionInCode(source, `world`, `world`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `burn()`))
).toMatchObject(getPositionInCode(source, `burn()`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `ok`))
).toMatchObject(getPositionInCode(source, `ok`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `_ctx.ok`, `ok`))
).toMatchObject(getPositionInCode(source, `ok`, true))
expect(
consumer.originalPositionFor(getPositionInCode(code, `list`))
).toMatchObject(getPositionInCode(source, `list`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `_ctx.list`, `list`))
).toMatchObject(getPositionInCode(source, `list`, true))
expect(
consumer.originalPositionFor(getPositionInCode(code, `value`))
).toMatchObject(getPositionInCode(source, `value`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `index`))
).toMatchObject(getPositionInCode(source, `index`))
expect(
consumer.originalPositionFor(getPositionInCode(code, `value + index`))
).toMatchObject(getPositionInCode(source, `value + index`))
})
})
| packages/compiler-core/__tests__/compile.spec.ts | 0 | https://github.com/vuejs/core/commit/c463a71bb31f01da55927424533e2ece3a3c4efe | [
0.00017964474682230502,
0.00017682212637737393,
0.00016643854905851185,
0.0001784764026524499,
0.0000034438719467289047
]
|
{
"id": 0,
"code_window": [
"\n",
"describe('SSR hydration', () => {\n",
" mockWarn()\n",
"\n",
" test('text', async () => {\n",
" const msg = ref('foo')\n",
" const { vnode, container } = mountWithHydration('foo', () => msg.value)\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" beforeEach(() => {\n",
" document.body.innerHTML = ''\n",
" })\n",
"\n"
],
"file_path": "packages/runtime-core/__tests__/hydration.spec.ts",
"type": "add",
"edit_start_line_idx": 39
} | import { Ref, ref, isRef, unref, reactive, expectType } from './index'
function plainType(arg: number | Ref<number>) {
// ref coercing
const coerced = ref(arg)
expectType<Ref<number>>(coerced)
// isRef as type guard
if (isRef(arg)) {
expectType<Ref<number>>(arg)
}
// ref unwrapping
expectType<number>(unref(arg))
// ref inner type should be unwrapped
const nestedRef = ref({
foo: ref(1)
})
expectType<Ref<{ foo: number }>>(nestedRef)
expectType<{ foo: number }>(nestedRef.value)
// ref boolean
const falseRef = ref(false)
expectType<Ref<boolean>>(falseRef)
expectType<boolean>(falseRef.value)
// ref true
const trueRef = ref<true>(true)
expectType<Ref<true>>(trueRef)
expectType<true>(trueRef.value)
// tuple
expectType<[number, string]>(unref(ref([1, '1'])))
interface IteratorFoo {
[Symbol.iterator]: any
}
// with symbol
expectType<Ref<IteratorFoo | null | undefined>>(
ref<IteratorFoo | null | undefined>()
)
}
plainType(1)
function bailType(arg: HTMLElement | Ref<HTMLElement>) {
// ref coercing
const coerced = ref(arg)
expectType<Ref<HTMLElement>>(coerced)
// isRef as type guard
if (isRef(arg)) {
expectType<Ref<HTMLElement>>(arg)
}
// ref unwrapping
expectType<HTMLElement>(unref(arg))
// ref inner type should be unwrapped
const nestedRef = ref({ foo: ref(document.createElement('DIV')) })
expectType<Ref<{ foo: HTMLElement }>>(nestedRef)
expectType<{ foo: HTMLElement }>(nestedRef.value)
}
const el = document.createElement('DIV')
bailType(el)
function withSymbol() {
const customSymbol = Symbol()
const obj = {
[Symbol.asyncIterator]: { a: 1 },
[Symbol.unscopables]: { b: '1' },
[customSymbol]: { c: [1, 2, 3] }
}
const objRef = ref(obj)
expectType<{ a: number }>(objRef.value[Symbol.asyncIterator])
expectType<{ b: string }>(objRef.value[Symbol.unscopables])
expectType<{ c: Array<number> }>(objRef.value[customSymbol])
}
withSymbol()
const state = reactive({
foo: {
value: 1,
label: 'bar'
}
})
expectType<string>(state.foo.label)
| test-dts/ref.test-d.ts | 0 | https://github.com/vuejs/core/commit/c463a71bb31f01da55927424533e2ece3a3c4efe | [
0.0003786398738157004,
0.00019802090537268668,
0.0001666921889409423,
0.0001773481344571337,
0.000060739614127669483
]
|
{
"id": 0,
"code_window": [
"\n",
"describe('SSR hydration', () => {\n",
" mockWarn()\n",
"\n",
" test('text', async () => {\n",
" const msg = ref('foo')\n",
" const { vnode, container } = mountWithHydration('foo', () => msg.value)\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" beforeEach(() => {\n",
" document.body.innerHTML = ''\n",
" })\n",
"\n"
],
"file_path": "packages/runtime-core/__tests__/hydration.spec.ts",
"type": "add",
"edit_start_line_idx": 39
} | import {
onMounted,
onErrorCaptured,
render,
h,
nodeOps,
watch,
ref,
nextTick,
defineComponent,
watchEffect
} from '@vue/runtime-test'
import { setErrorRecovery } from '../src/errorHandling'
import { mockWarn } from '@vue/shared'
describe('error handling', () => {
mockWarn()
beforeEach(() => {
setErrorRecovery(true)
})
afterEach(() => {
setErrorRecovery(false)
})
test('propagation', () => {
const err = new Error('foo')
const fn = jest.fn()
const Comp = {
setup() {
onErrorCaptured((err, instance, info) => {
fn(err, info, 'root')
return true
})
return () => h(Child)
}
}
const Child = {
setup() {
onErrorCaptured((err, instance, info) => {
fn(err, info, 'child')
})
return () => h(GrandChild)
}
}
const GrandChild = {
setup() {
onMounted(() => {
throw err
})
return () => null
}
}
render(h(Comp), nodeOps.createElement('div'))
expect(fn).toHaveBeenCalledTimes(2)
expect(fn).toHaveBeenCalledWith(err, 'mounted hook', 'root')
expect(fn).toHaveBeenCalledWith(err, 'mounted hook', 'child')
})
test('propagation stoppage', () => {
const err = new Error('foo')
const fn = jest.fn()
const Comp = {
setup() {
onErrorCaptured((err, instance, info) => {
fn(err, info, 'root')
return true
})
return () => h(Child)
}
}
const Child = {
setup() {
onErrorCaptured((err, instance, info) => {
fn(err, info, 'child')
return true
})
return () => h(GrandChild)
}
}
const GrandChild = {
setup() {
onMounted(() => {
throw err
})
return () => null
}
}
render(h(Comp), nodeOps.createElement('div'))
expect(fn).toHaveBeenCalledTimes(1)
expect(fn).toHaveBeenCalledWith(err, 'mounted hook', 'child')
})
test('async error handling', async () => {
const err = new Error('foo')
const fn = jest.fn()
const Comp = {
setup() {
onErrorCaptured((err, instance, info) => {
fn(err, info)
return true
})
return () => h(Child)
}
}
const Child = {
setup() {
onMounted(async () => {
throw err
})
},
render() {}
}
render(h(Comp), nodeOps.createElement('div'))
expect(fn).not.toHaveBeenCalled()
await new Promise(r => setTimeout(r))
expect(fn).toHaveBeenCalledWith(err, 'mounted hook')
})
test('error thrown in onErrorCaptured', () => {
const err = new Error('foo')
const err2 = new Error('bar')
const fn = jest.fn()
const Comp = {
setup() {
onErrorCaptured((err, instance, info) => {
fn(err, info)
return true
})
return () => h(Child)
}
}
const Child = {
setup() {
onErrorCaptured(() => {
throw err2
})
return () => h(GrandChild)
}
}
const GrandChild = {
setup() {
onMounted(() => {
throw err
})
return () => null
}
}
render(h(Comp), nodeOps.createElement('div'))
expect(fn).toHaveBeenCalledTimes(2)
expect(fn).toHaveBeenCalledWith(err, 'mounted hook')
expect(fn).toHaveBeenCalledWith(err2, 'errorCaptured hook')
})
test('setup function', () => {
const err = new Error('foo')
const fn = jest.fn()
const Comp = {
setup() {
onErrorCaptured((err, instance, info) => {
fn(err, info)
return true
})
return () => h(Child)
}
}
const Child = {
setup() {
throw err
},
render() {}
}
render(h(Comp), nodeOps.createElement('div'))
expect(fn).toHaveBeenCalledWith(err, 'setup function')
})
test('in render function', () => {
const err = new Error('foo')
const fn = jest.fn()
const Comp = {
setup() {
onErrorCaptured((err, instance, info) => {
fn(err, info)
return true
})
return () => h(Child)
}
}
const Child = {
setup() {
return () => {
throw err
}
}
}
render(h(Comp), nodeOps.createElement('div'))
expect(fn).toHaveBeenCalledWith(err, 'render function')
})
test('in function ref', () => {
const err = new Error('foo')
const ref = () => {
throw err
}
const fn = jest.fn()
const Comp = {
setup() {
onErrorCaptured((err, instance, info) => {
fn(err, info)
return true
})
return () => h(Child)
}
}
const Child = defineComponent(() => () => h('div', { ref }))
render(h(Comp), nodeOps.createElement('div'))
expect(fn).toHaveBeenCalledWith(err, 'ref function')
})
test('in effect', () => {
const err = new Error('foo')
const fn = jest.fn()
const Comp = {
setup() {
onErrorCaptured((err, instance, info) => {
fn(err, info)
return true
})
return () => h(Child)
}
}
const Child = {
setup() {
watchEffect(() => {
throw err
})
return () => null
}
}
render(h(Comp), nodeOps.createElement('div'))
expect(fn).toHaveBeenCalledWith(err, 'watcher callback')
})
test('in watch getter', () => {
const err = new Error('foo')
const fn = jest.fn()
const Comp = {
setup() {
onErrorCaptured((err, instance, info) => {
fn(err, info)
return true
})
return () => h(Child)
}
}
const Child = {
setup() {
watch(
() => {
throw err
},
() => {}
)
return () => null
}
}
render(h(Comp), nodeOps.createElement('div'))
expect(fn).toHaveBeenCalledWith(err, 'watcher getter')
})
test('in watch callback', async () => {
const err = new Error('foo')
const fn = jest.fn()
const Comp = {
setup() {
onErrorCaptured((err, instance, info) => {
fn(err, info)
return true
})
return () => h(Child)
}
}
const count = ref(0)
const Child = {
setup() {
watch(
() => count.value,
() => {
throw err
}
)
return () => null
}
}
render(h(Comp), nodeOps.createElement('div'))
count.value++
await nextTick()
expect(fn).toHaveBeenCalledWith(err, 'watcher callback')
})
test('in effect cleanup', async () => {
const err = new Error('foo')
const count = ref(0)
const fn = jest.fn()
const Comp = {
setup() {
onErrorCaptured((err, instance, info) => {
fn(err, info)
return true
})
return () => h(Child)
}
}
const Child = {
setup() {
watchEffect(onCleanup => {
count.value
onCleanup(() => {
throw err
})
})
return () => null
}
}
render(h(Comp), nodeOps.createElement('div'))
count.value++
await nextTick()
expect(fn).toHaveBeenCalledWith(err, 'watcher cleanup function')
})
test('in component event handler via emit', () => {
const err = new Error('foo')
const fn = jest.fn()
const Comp = {
setup() {
onErrorCaptured((err, instance, info) => {
fn(err, info)
return true
})
return () =>
h(Child, {
onFoo: () => {
throw err
}
})
}
}
const Child = {
setup(props: any, { emit }: any) {
emit('foo')
return () => null
}
}
render(h(Comp), nodeOps.createElement('div'))
expect(fn).toHaveBeenCalledWith(err, 'component event handler')
})
test('in component event handler via emit (async)', async () => {
const err = new Error('foo')
const fn = jest.fn()
const Comp = {
setup() {
onErrorCaptured((err, instance, info) => {
fn(err, info)
return true
})
return () =>
h(Child, {
async onFoo() {
throw err
}
})
}
}
const Child = {
props: ['onFoo'],
setup(props: any, { emit }: any) {
emit('foo')
return () => null
}
}
render(h(Comp), nodeOps.createElement('div'))
await nextTick()
expect(fn).toHaveBeenCalledWith(err, 'component event handler')
})
test('in component event handler via emit (async + array)', async () => {
const err = new Error('foo')
const fn = jest.fn()
const res: Promise<any>[] = []
const createAsyncHandler = (p: Promise<any>) => () => {
res.push(p)
return p
}
const Comp = {
setup() {
onErrorCaptured((err, instance, info) => {
fn(err, info)
return true
})
return () =>
h(Child, {
onFoo: [
createAsyncHandler(Promise.reject(err)),
createAsyncHandler(Promise.resolve(1))
]
})
}
}
const Child = {
setup(props: any, { emit }: any) {
emit('foo')
return () => null
}
}
render(h(Comp), nodeOps.createElement('div'))
try {
await Promise.all(res)
} catch (e) {
expect(e).toBe(err)
}
expect(fn).toHaveBeenCalledWith(err, 'component event handler')
})
it('should warn unhandled', () => {
const onError = jest.spyOn(console, 'error')
onError.mockImplementation(() => {})
const groupCollapsed = jest.spyOn(console, 'groupCollapsed')
groupCollapsed.mockImplementation(() => {})
const log = jest.spyOn(console, 'log')
log.mockImplementation(() => {})
const err = new Error('foo')
const fn = jest.fn()
const Comp = {
setup() {
onErrorCaptured((err, instance, info) => {
fn(err, info)
})
return () => h(Child)
}
}
const Child = {
setup() {
throw err
},
render() {}
}
render(h(Comp), nodeOps.createElement('div'))
expect(fn).toHaveBeenCalledWith(err, 'setup function')
expect(
`Unhandled error during execution of setup function`
).toHaveBeenWarned()
expect(onError).toHaveBeenCalledWith(err)
onError.mockRestore()
groupCollapsed.mockRestore()
log.mockRestore()
})
// native event handler handling should be tested in respective renderers
})
| packages/runtime-core/__tests__/errorHandling.spec.ts | 0 | https://github.com/vuejs/core/commit/c463a71bb31f01da55927424533e2ece3a3c4efe | [
0.0026164688169956207,
0.00023194013920146972,
0.00016313832020387053,
0.0001710348151391372,
0.0003495216660667211
]
|
{
"id": 1,
"code_window": [
" // as 2nd fragment child.\n",
" expect(`Hydration text content mismatch`).toHaveBeenWarned()\n",
" // excessive children removal\n",
" expect(`Hydration children mismatch`).toHaveBeenWarned()\n",
" })\n",
" })\n",
"})"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"\n",
" test('Teleport target has empty children', () => {\n",
" const teleportContainer = document.createElement('div')\n",
" teleportContainer.id = 'teleport'\n",
" document.body.appendChild(teleportContainer)\n",
"\n",
" mountWithHydration('<!--teleport start--><!--teleport end-->', () =>\n",
" h(Teleport, { to: '#teleport' }, [h('span', 'value')])\n",
" )\n",
" expect(teleportContainer.innerHTML).toBe(`<span>value</span>`)\n",
" expect(`Hydration children mismatch`).toHaveBeenWarned()\n",
" })\n"
],
"file_path": "packages/runtime-core/__tests__/hydration.spec.ts",
"type": "add",
"edit_start_line_idx": 688
} | import {
createSSRApp,
h,
ref,
nextTick,
VNode,
Teleport,
createStaticVNode,
Suspense,
onMounted,
defineAsyncComponent,
defineComponent
} from '@vue/runtime-dom'
import { renderToString } from '@vue/server-renderer'
import { mockWarn } from '@vue/shared'
import { SSRContext } from 'packages/server-renderer/src/renderToString'
function mountWithHydration(html: string, render: () => any) {
const container = document.createElement('div')
container.innerHTML = html
const app = createSSRApp({
render
})
return {
vnode: app.mount(container).$.subTree as VNode<Node, Element> & {
el: Element
},
container
}
}
const triggerEvent = (type: string, el: Element) => {
const event = new Event(type)
el.dispatchEvent(event)
}
describe('SSR hydration', () => {
mockWarn()
test('text', async () => {
const msg = ref('foo')
const { vnode, container } = mountWithHydration('foo', () => msg.value)
expect(vnode.el).toBe(container.firstChild)
expect(container.textContent).toBe('foo')
msg.value = 'bar'
await nextTick()
expect(container.textContent).toBe('bar')
})
test('comment', () => {
const { vnode, container } = mountWithHydration('<!---->', () => null)
expect(vnode.el).toBe(container.firstChild)
expect(vnode.el.nodeType).toBe(8) // comment
})
test('static', () => {
const html = '<div><span>hello</span></div>'
const { vnode, container } = mountWithHydration(html, () =>
createStaticVNode('', 1)
)
expect(vnode.el).toBe(container.firstChild)
expect(vnode.el.outerHTML).toBe(html)
expect(vnode.anchor).toBe(container.firstChild)
expect(vnode.children).toBe(html)
})
test('static (multiple elements)', () => {
const staticContent = '<div></div><span>hello</span>'
const html = `<div><div>hi</div>` + staticContent + `<div>ho</div></div>`
const n1 = h('div', 'hi')
const s = createStaticVNode('', 2)
const n2 = h('div', 'ho')
const { container } = mountWithHydration(html, () => h('div', [n1, s, n2]))
const div = container.firstChild!
expect(n1.el).toBe(div.firstChild)
expect(n2.el).toBe(div.lastChild)
expect(s.el).toBe(div.childNodes[1])
expect(s.anchor).toBe(div.childNodes[2])
expect(s.children).toBe(staticContent)
})
test('element with text children', async () => {
const msg = ref('foo')
const { vnode, container } = mountWithHydration(
'<div class="foo">foo</div>',
() => h('div', { class: msg.value }, msg.value)
)
expect(vnode.el).toBe(container.firstChild)
expect(container.firstChild!.textContent).toBe('foo')
msg.value = 'bar'
await nextTick()
expect(container.innerHTML).toBe(`<div class="bar">bar</div>`)
})
test('element with elements children', async () => {
const msg = ref('foo')
const fn = jest.fn()
const { vnode, container } = mountWithHydration(
'<div><span>foo</span><span class="foo"></span></div>',
() =>
h('div', [
h('span', msg.value),
h('span', { class: msg.value, onClick: fn })
])
)
expect(vnode.el).toBe(container.firstChild)
expect((vnode.children as VNode[])[0].el).toBe(
container.firstChild!.childNodes[0]
)
expect((vnode.children as VNode[])[1].el).toBe(
container.firstChild!.childNodes[1]
)
// event handler
triggerEvent('click', vnode.el.querySelector('.foo')!)
expect(fn).toHaveBeenCalled()
msg.value = 'bar'
await nextTick()
expect(vnode.el.innerHTML).toBe(`<span>bar</span><span class="bar"></span>`)
})
test('element with ref', () => {
const el = ref()
const { vnode, container } = mountWithHydration('<div></div>', () =>
h('div', { ref: el })
)
expect(vnode.el).toBe(container.firstChild)
expect(el.value).toBe(vnode.el)
})
test('Fragment', async () => {
const msg = ref('foo')
const fn = jest.fn()
const { vnode, container } = mountWithHydration(
'<div><!--[--><span>foo</span><!--[--><span class="foo"></span><!--]--><!--]--></div>',
() =>
h('div', [
[h('span', msg.value), [h('span', { class: msg.value, onClick: fn })]]
])
)
expect(vnode.el).toBe(container.firstChild)
expect(vnode.el.innerHTML).toBe(
`<!--[--><span>foo</span><!--[--><span class="foo"></span><!--]--><!--]-->`
)
// start fragment 1
const fragment1 = (vnode.children as VNode[])[0]
expect(fragment1.el).toBe(vnode.el.childNodes[0])
const fragment1Children = fragment1.children as VNode[]
// first <span>
expect(fragment1Children[0].el!.tagName).toBe('SPAN')
expect(fragment1Children[0].el).toBe(vnode.el.childNodes[1])
// start fragment 2
const fragment2 = fragment1Children[1]
expect(fragment2.el).toBe(vnode.el.childNodes[2])
const fragment2Children = fragment2.children as VNode[]
// second <span>
expect(fragment2Children[0].el!.tagName).toBe('SPAN')
expect(fragment2Children[0].el).toBe(vnode.el.childNodes[3])
// end fragment 2
expect(fragment2.anchor).toBe(vnode.el.childNodes[4])
// end fragment 1
expect(fragment1.anchor).toBe(vnode.el.childNodes[5])
// event handler
triggerEvent('click', vnode.el.querySelector('.foo')!)
expect(fn).toHaveBeenCalled()
msg.value = 'bar'
await nextTick()
expect(vnode.el.innerHTML).toBe(
`<!--[--><span>bar</span><!--[--><span class="bar"></span><!--]--><!--]-->`
)
})
test('Teleport', async () => {
const msg = ref('foo')
const fn = jest.fn()
const teleportContainer = document.createElement('div')
teleportContainer.id = 'teleport'
teleportContainer.innerHTML = `<span>foo</span><span class="foo"></span><!---->`
document.body.appendChild(teleportContainer)
const { vnode, container } = mountWithHydration(
'<!--teleport start--><!--teleport end-->',
() =>
h(Teleport, { to: '#teleport' }, [
h('span', msg.value),
h('span', { class: msg.value, onClick: fn })
])
)
expect(vnode.el).toBe(container.firstChild)
expect(vnode.anchor).toBe(container.lastChild)
expect(vnode.target).toBe(teleportContainer)
expect((vnode.children as VNode[])[0].el).toBe(
teleportContainer.childNodes[0]
)
expect((vnode.children as VNode[])[1].el).toBe(
teleportContainer.childNodes[1]
)
expect(vnode.targetAnchor).toBe(teleportContainer.childNodes[2])
// event handler
triggerEvent('click', teleportContainer.querySelector('.foo')!)
expect(fn).toHaveBeenCalled()
msg.value = 'bar'
await nextTick()
expect(teleportContainer.innerHTML).toBe(
`<span>bar</span><span class="bar"></span><!---->`
)
})
test('Teleport (multiple + integration)', async () => {
const msg = ref('foo')
const fn1 = jest.fn()
const fn2 = jest.fn()
const Comp = () => [
h(Teleport, { to: '#teleport2' }, [
h('span', msg.value),
h('span', { class: msg.value, onClick: fn1 })
]),
h(Teleport, { to: '#teleport2' }, [
h('span', msg.value + '2'),
h('span', { class: msg.value + '2', onClick: fn2 })
])
]
const teleportContainer = document.createElement('div')
teleportContainer.id = 'teleport2'
const ctx: SSRContext = {}
const mainHtml = await renderToString(h(Comp), ctx)
expect(mainHtml).toMatchInlineSnapshot(
`"<!--[--><!--teleport start--><!--teleport end--><!--teleport start--><!--teleport end--><!--]-->"`
)
const teleportHtml = ctx.teleports!['#teleport2']
expect(teleportHtml).toMatchInlineSnapshot(
`"<span>foo</span><span class=\\"foo\\"></span><!----><span>foo2</span><span class=\\"foo2\\"></span><!---->"`
)
teleportContainer.innerHTML = teleportHtml
document.body.appendChild(teleportContainer)
const { vnode, container } = mountWithHydration(mainHtml, Comp)
expect(vnode.el).toBe(container.firstChild)
const teleportVnode1 = (vnode.children as VNode[])[0]
const teleportVnode2 = (vnode.children as VNode[])[1]
expect(teleportVnode1.el).toBe(container.childNodes[1])
expect(teleportVnode1.anchor).toBe(container.childNodes[2])
expect(teleportVnode2.el).toBe(container.childNodes[3])
expect(teleportVnode2.anchor).toBe(container.childNodes[4])
expect(teleportVnode1.target).toBe(teleportContainer)
expect((teleportVnode1 as any).children[0].el).toBe(
teleportContainer.childNodes[0]
)
expect(teleportVnode1.targetAnchor).toBe(teleportContainer.childNodes[2])
expect(teleportVnode2.target).toBe(teleportContainer)
expect((teleportVnode2 as any).children[0].el).toBe(
teleportContainer.childNodes[3]
)
expect(teleportVnode2.targetAnchor).toBe(teleportContainer.childNodes[5])
// // event handler
triggerEvent('click', teleportContainer.querySelector('.foo')!)
expect(fn1).toHaveBeenCalled()
triggerEvent('click', teleportContainer.querySelector('.foo2')!)
expect(fn2).toHaveBeenCalled()
msg.value = 'bar'
await nextTick()
expect(teleportContainer.innerHTML).toMatchInlineSnapshot(
`"<span>bar</span><span class=\\"bar\\"></span><!----><span>bar2</span><span class=\\"bar2\\"></span><!---->"`
)
})
test('Teleport (disabled)', async () => {
const msg = ref('foo')
const fn1 = jest.fn()
const fn2 = jest.fn()
const Comp = () => [
h('div', 'foo'),
h(Teleport, { to: '#teleport3', disabled: true }, [
h('span', msg.value),
h('span', { class: msg.value, onClick: fn1 })
]),
h('div', { class: msg.value + '2', onClick: fn2 }, 'bar')
]
const teleportContainer = document.createElement('div')
teleportContainer.id = 'teleport3'
const ctx: SSRContext = {}
const mainHtml = await renderToString(h(Comp), ctx)
expect(mainHtml).toMatchInlineSnapshot(
`"<!--[--><div>foo</div><!--teleport start--><span>foo</span><span class=\\"foo\\"></span><!--teleport end--><div class=\\"foo2\\">bar</div><!--]-->"`
)
const teleportHtml = ctx.teleports!['#teleport3']
expect(teleportHtml).toMatchInlineSnapshot(`"<!---->"`)
teleportContainer.innerHTML = teleportHtml
document.body.appendChild(teleportContainer)
const { vnode, container } = mountWithHydration(mainHtml, Comp)
expect(vnode.el).toBe(container.firstChild)
const children = vnode.children as VNode[]
expect(children[0].el).toBe(container.childNodes[1])
const teleportVnode = children[1]
expect(teleportVnode.el).toBe(container.childNodes[2])
expect((teleportVnode.children as VNode[])[0].el).toBe(
container.childNodes[3]
)
expect((teleportVnode.children as VNode[])[1].el).toBe(
container.childNodes[4]
)
expect(teleportVnode.anchor).toBe(container.childNodes[5])
expect(children[2].el).toBe(container.childNodes[6])
expect(teleportVnode.target).toBe(teleportContainer)
expect(teleportVnode.targetAnchor).toBe(teleportContainer.childNodes[0])
// // event handler
triggerEvent('click', container.querySelector('.foo')!)
expect(fn1).toHaveBeenCalled()
triggerEvent('click', container.querySelector('.foo2')!)
expect(fn2).toHaveBeenCalled()
msg.value = 'bar'
await nextTick()
expect(container.innerHTML).toMatchInlineSnapshot(
`"<!--[--><div>foo</div><!--teleport start--><span>bar</span><span class=\\"bar\\"></span><!--teleport end--><div class=\\"bar2\\">bar</div><!--]-->"`
)
})
// compile SSR + client render fn from the same template & hydrate
test('full compiler integration', async () => {
const mounted: string[] = []
const log = jest.fn()
const toggle = ref(true)
const Child = {
data() {
return {
count: 0,
text: 'hello',
style: {
color: 'red'
}
}
},
mounted() {
mounted.push('child')
},
template: `
<div>
<span class="count" :style="style">{{ count }}</span>
<button class="inc" @click="count++">inc</button>
<button class="change" @click="style.color = 'green'" >change color</button>
<button class="emit" @click="$emit('foo')">emit</button>
<span class="text">{{ text }}</span>
<input v-model="text">
</div>
`
}
const App = {
setup() {
return { toggle }
},
mounted() {
mounted.push('parent')
},
template: `
<div>
<span>hello</span>
<template v-if="toggle">
<Child @foo="log('child')"/>
<template v-if="true">
<button class="parent-click" @click="log('click')">click me</button>
</template>
</template>
<span>hello</span>
</div>`,
components: {
Child
},
methods: {
log
}
}
const container = document.createElement('div')
// server render
container.innerHTML = await renderToString(h(App))
// hydrate
createSSRApp(App).mount(container)
// assert interactions
// 1. parent button click
triggerEvent('click', container.querySelector('.parent-click')!)
expect(log).toHaveBeenCalledWith('click')
// 2. child inc click + text interpolation
const count = container.querySelector('.count') as HTMLElement
expect(count.textContent).toBe(`0`)
triggerEvent('click', container.querySelector('.inc')!)
await nextTick()
expect(count.textContent).toBe(`1`)
// 3. child color click + style binding
expect(count.style.color).toBe('red')
triggerEvent('click', container.querySelector('.change')!)
await nextTick()
expect(count.style.color).toBe('green')
// 4. child event emit
triggerEvent('click', container.querySelector('.emit')!)
expect(log).toHaveBeenCalledWith('child')
// 5. child v-model
const text = container.querySelector('.text')!
const input = container.querySelector('input')!
expect(text.textContent).toBe('hello')
input.value = 'bye'
triggerEvent('input', input)
await nextTick()
expect(text.textContent).toBe('bye')
})
test('Suspense', async () => {
const AsyncChild = {
async setup() {
const count = ref(0)
return () =>
h(
'span',
{
onClick: () => {
count.value++
}
},
count.value
)
}
}
const { vnode, container } = mountWithHydration('<span>0</span>', () =>
h(Suspense, () => h(AsyncChild))
)
expect(vnode.el).toBe(container.firstChild)
// wait for hydration to finish
await new Promise(r => setTimeout(r))
triggerEvent('click', container.querySelector('span')!)
await nextTick()
expect(container.innerHTML).toBe(`<span>1</span>`)
})
test('Suspense (full integration)', async () => {
const mountedCalls: number[] = []
const asyncDeps: Promise<any>[] = []
const AsyncChild = defineComponent({
props: ['n'],
async setup(props) {
const count = ref(props.n)
onMounted(() => {
mountedCalls.push(props.n)
})
const p = new Promise(r => setTimeout(r, props.n * 10))
asyncDeps.push(p)
await p
return () =>
h(
'span',
{
onClick: () => {
count.value++
}
},
count.value
)
}
})
const done = jest.fn()
const App = {
template: `
<Suspense @resolve="done">
<AsyncChild :n="1" />
<AsyncChild :n="2" />
</Suspense>`,
components: {
AsyncChild
},
methods: {
done
}
}
const container = document.createElement('div')
// server render
container.innerHTML = await renderToString(h(App))
expect(container.innerHTML).toMatchInlineSnapshot(
`"<!--[--><span>1</span><span>2</span><!--]-->"`
)
// reset asyncDeps from ssr
asyncDeps.length = 0
// hydrate
createSSRApp(App).mount(container)
expect(mountedCalls.length).toBe(0)
expect(asyncDeps.length).toBe(2)
// wait for hydration to complete
await Promise.all(asyncDeps)
await new Promise(r => setTimeout(r))
// should flush buffered effects
expect(mountedCalls).toMatchObject([1, 2])
expect(container.innerHTML).toMatch(`<span>1</span><span>2</span>`)
const span1 = container.querySelector('span')!
triggerEvent('click', span1)
await nextTick()
expect(container.innerHTML).toMatch(`<span>2</span><span>2</span>`)
const span2 = span1.nextSibling as Element
triggerEvent('click', span2)
await nextTick()
expect(container.innerHTML).toMatch(`<span>2</span><span>3</span>`)
})
test('async component', async () => {
const spy = jest.fn()
const Comp = () =>
h(
'button',
{
onClick: spy
},
'hello!'
)
let serverResolve: any
let AsyncComp = defineAsyncComponent(
() =>
new Promise(r => {
serverResolve = r
})
)
const App = {
render() {
return ['hello', h(AsyncComp), 'world']
}
}
// server render
const htmlPromise = renderToString(h(App))
serverResolve(Comp)
const html = await htmlPromise
expect(html).toMatchInlineSnapshot(
`"<!--[-->hello<button>hello!</button>world<!--]-->"`
)
// hydration
let clientResolve: any
AsyncComp = defineAsyncComponent(
() =>
new Promise(r => {
clientResolve = r
})
)
const container = document.createElement('div')
container.innerHTML = html
createSSRApp(App).mount(container)
// hydration not complete yet
triggerEvent('click', container.querySelector('button')!)
expect(spy).not.toHaveBeenCalled()
// resolve
clientResolve(Comp)
await new Promise(r => setTimeout(r))
// should be hydrated now
triggerEvent('click', container.querySelector('button')!)
expect(spy).toHaveBeenCalled()
})
describe('mismatch handling', () => {
test('text node', () => {
const { container } = mountWithHydration(`foo`, () => 'bar')
expect(container.textContent).toBe('bar')
expect(`Hydration text mismatch`).toHaveBeenWarned()
})
test('element text content', () => {
const { container } = mountWithHydration(`<div>foo</div>`, () =>
h('div', 'bar')
)
expect(container.innerHTML).toBe('<div>bar</div>')
expect(`Hydration text content mismatch in <div>`).toHaveBeenWarned()
})
test('not enough children', () => {
const { container } = mountWithHydration(`<div></div>`, () =>
h('div', [h('span', 'foo'), h('span', 'bar')])
)
expect(container.innerHTML).toBe(
'<div><span>foo</span><span>bar</span></div>'
)
expect(`Hydration children mismatch in <div>`).toHaveBeenWarned()
})
test('too many children', () => {
const { container } = mountWithHydration(
`<div><span>foo</span><span>bar</span></div>`,
() => h('div', [h('span', 'foo')])
)
expect(container.innerHTML).toBe('<div><span>foo</span></div>')
expect(`Hydration children mismatch in <div>`).toHaveBeenWarned()
})
test('complete mismatch', () => {
const { container } = mountWithHydration(
`<div><span>foo</span><span>bar</span></div>`,
() => h('div', [h('div', 'foo'), h('p', 'bar')])
)
expect(container.innerHTML).toBe('<div><div>foo</div><p>bar</p></div>')
expect(`Hydration node mismatch`).toHaveBeenWarnedTimes(2)
})
test('fragment mismatch removal', () => {
const { container } = mountWithHydration(
`<div><!--[--><div>foo</div><div>bar</div><!--]--></div>`,
() => h('div', [h('span', 'replaced')])
)
expect(container.innerHTML).toBe('<div><span>replaced</span></div>')
expect(`Hydration node mismatch`).toHaveBeenWarned()
})
test('fragment not enough children', () => {
const { container } = mountWithHydration(
`<div><!--[--><div>foo</div><!--]--><div>baz</div></div>`,
() => h('div', [[h('div', 'foo'), h('div', 'bar')], h('div', 'baz')])
)
expect(container.innerHTML).toBe(
'<div><!--[--><div>foo</div><div>bar</div><!--]--><div>baz</div></div>'
)
expect(`Hydration node mismatch`).toHaveBeenWarned()
})
test('fragment too many children', () => {
const { container } = mountWithHydration(
`<div><!--[--><div>foo</div><div>bar</div><!--]--><div>baz</div></div>`,
() => h('div', [[h('div', 'foo')], h('div', 'baz')])
)
expect(container.innerHTML).toBe(
'<div><!--[--><div>foo</div><!--]--><div>baz</div></div>'
)
// fragment ends early and attempts to hydrate the extra <div>bar</div>
// as 2nd fragment child.
expect(`Hydration text content mismatch`).toHaveBeenWarned()
// excessive children removal
expect(`Hydration children mismatch`).toHaveBeenWarned()
})
})
})
| packages/runtime-core/__tests__/hydration.spec.ts | 1 | https://github.com/vuejs/core/commit/c463a71bb31f01da55927424533e2ece3a3c4efe | [
0.9494930505752563,
0.014826680533587933,
0.00016342729213647544,
0.00017346639651805162,
0.11256064474582672
]
|
{
"id": 1,
"code_window": [
" // as 2nd fragment child.\n",
" expect(`Hydration text content mismatch`).toHaveBeenWarned()\n",
" // excessive children removal\n",
" expect(`Hydration children mismatch`).toHaveBeenWarned()\n",
" })\n",
" })\n",
"})"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"\n",
" test('Teleport target has empty children', () => {\n",
" const teleportContainer = document.createElement('div')\n",
" teleportContainer.id = 'teleport'\n",
" document.body.appendChild(teleportContainer)\n",
"\n",
" mountWithHydration('<!--teleport start--><!--teleport end-->', () =>\n",
" h(Teleport, { to: '#teleport' }, [h('span', 'value')])\n",
" )\n",
" expect(teleportContainer.innerHTML).toBe(`<span>value</span>`)\n",
" expect(`Hydration children mismatch`).toHaveBeenWarned()\n",
" })\n"
],
"file_path": "packages/runtime-core/__tests__/hydration.spec.ts",
"type": "add",
"edit_start_line_idx": 688
} | /**
* This module is Node-only.
*/
import {
NodeTypes,
ElementNode,
TransformContext,
TemplateChildNode,
SimpleExpressionNode,
createCallExpression,
HoistTransform,
CREATE_STATIC,
ExpressionNode,
ElementTypes,
PlainElementNode,
JSChildNode,
TextCallNode
} from '@vue/compiler-core'
import {
isVoidTag,
isString,
isSymbol,
isKnownAttr,
escapeHtml,
toDisplayString,
normalizeClass,
normalizeStyle,
stringifyStyle,
makeMap
} from '@vue/shared'
export const enum StringifyThresholds {
ELEMENT_WITH_BINDING_COUNT = 5,
NODE_COUNT = 20
}
type StringifiableNode = PlainElementNode | TextCallNode
/**
* Turn eligible hoisted static trees into stringified static nodes, e.g.
*
* ```js
* const _hoisted_1 = createStaticVNode(`<div class="foo">bar</div>`)
* ```
*
* A single static vnode can contain stringified content for **multiple**
* consecutive nodes (element and plain text), called a "chunk".
* `@vue/runtime-dom` will create the content via innerHTML in a hidden
* container element and insert all the nodes in place. The call must also
* provide the number of nodes contained in the chunk so that during hydration
* we can know how many nodes the static vnode should adopt.
*
* The optimization scans a children list that contains hoisted nodes, and
* tries to find the largest chunk of consecutive hoisted nodes before running
* into a non-hoisted node or the end of the list. A chunk is then converted
* into a single static vnode and replaces the hoisted expression of the first
* node in the chunk. Other nodes in the chunk are considered "merged" and
* therefore removed from both the hoist list and the children array.
*
* This optimization is only performed in Node.js.
*/
export const stringifyStatic: HoistTransform = (children, context, parent) => {
if (
parent.type === NodeTypes.ELEMENT &&
(parent.tagType === ElementTypes.COMPONENT ||
parent.tagType === ElementTypes.TEMPLATE)
) {
return
}
let nc = 0 // current node count
let ec = 0 // current element with binding count
const currentChunk: StringifiableNode[] = []
const stringifyCurrentChunk = (currentIndex: number): number => {
if (
nc >= StringifyThresholds.NODE_COUNT ||
ec >= StringifyThresholds.ELEMENT_WITH_BINDING_COUNT
) {
// combine all currently eligible nodes into a single static vnode call
const staticCall = createCallExpression(context.helper(CREATE_STATIC), [
JSON.stringify(
currentChunk.map(node => stringifyNode(node, context)).join('')
),
// the 2nd argument indicates the number of DOM nodes this static vnode
// will insert / hydrate
String(currentChunk.length)
])
// replace the first node's hoisted expression with the static vnode call
replaceHoist(currentChunk[0], staticCall, context)
if (currentChunk.length > 1) {
for (let i = 1; i < currentChunk.length; i++) {
// for the merged nodes, set their hoisted expression to null
replaceHoist(currentChunk[i], null, context)
}
// also remove merged nodes from children
const deleteCount = currentChunk.length - 1
children.splice(currentIndex - currentChunk.length + 1, deleteCount)
return deleteCount
}
}
return 0
}
let i = 0
for (; i < children.length; i++) {
const child = children[i]
const hoisted = getHoistedNode(child)
if (hoisted) {
// presence of hoisted means child must be a stringifiable node
const node = child as StringifiableNode
const result = analyzeNode(node)
if (result) {
// node is stringifiable, record state
nc += result[0]
ec += result[1]
currentChunk.push(node)
continue
}
}
// we only reach here if we ran into a node that is not stringifiable
// check if currently analyzed nodes meet criteria for stringification.
// adjust iteration index
i -= stringifyCurrentChunk(i)
// reset state
nc = 0
ec = 0
currentChunk.length = 0
}
// in case the last node was also stringifiable
stringifyCurrentChunk(i)
}
const getHoistedNode = (node: TemplateChildNode) =>
((node.type === NodeTypes.ELEMENT && node.tagType === ElementTypes.ELEMENT) ||
node.type == NodeTypes.TEXT_CALL) &&
node.codegenNode &&
node.codegenNode.type === NodeTypes.SIMPLE_EXPRESSION &&
node.codegenNode.hoisted
const dataAriaRE = /^(data|aria)-/
const isStringifiableAttr = (name: string) => {
return isKnownAttr(name) || dataAriaRE.test(name)
}
const replaceHoist = (
node: StringifiableNode,
replacement: JSChildNode | null,
context: TransformContext
) => {
const hoistToReplace = (node.codegenNode as SimpleExpressionNode).hoisted!
context.hoists[context.hoists.indexOf(hoistToReplace)] = replacement
}
const isNonStringifiable = /*#__PURE__*/ makeMap(
`caption,thead,tr,th,tbody,td,tfoot,colgroup,col`
)
/**
* for a hoisted node, analyze it and return:
* - false: bailed (contains runtime constant)
* - [nc, ec] where
* - nc is the number of nodes inside
* - ec is the number of element with bindings inside
*/
function analyzeNode(node: StringifiableNode): [number, number] | false {
if (node.type === NodeTypes.ELEMENT && isNonStringifiable(node.tag)) {
return false
}
if (node.type === NodeTypes.TEXT_CALL) {
return [1, 0]
}
let nc = 1 // node count
let ec = node.props.length > 0 ? 1 : 0 // element w/ binding count
let bailed = false
const bail = (): false => {
bailed = true
return false
}
// TODO: check for cases where using innerHTML will result in different
// output compared to imperative node insertions.
// probably only need to check for most common case
// i.e. non-phrasing-content tags inside `<p>`
function walk(node: ElementNode): boolean {
for (let i = 0; i < node.props.length; i++) {
const p = node.props[i]
// bail on non-attr bindings
if (p.type === NodeTypes.ATTRIBUTE && !isStringifiableAttr(p.name)) {
return bail()
}
if (p.type === NodeTypes.DIRECTIVE && p.name === 'bind') {
// bail on non-attr bindings
if (
p.arg &&
(p.arg.type === NodeTypes.COMPOUND_EXPRESSION ||
(p.arg.isStatic && !isStringifiableAttr(p.arg.content)))
) {
return bail()
}
}
}
for (let i = 0; i < node.children.length; i++) {
nc++
const child = node.children[i]
if (child.type === NodeTypes.ELEMENT) {
if (child.props.length > 0) {
ec++
}
walk(child)
if (bailed) {
return false
}
}
}
return true
}
return walk(node) ? [nc, ec] : false
}
function stringifyNode(
node: string | TemplateChildNode,
context: TransformContext
): string {
if (isString(node)) {
return node
}
if (isSymbol(node)) {
return ``
}
switch (node.type) {
case NodeTypes.ELEMENT:
return stringifyElement(node, context)
case NodeTypes.TEXT:
return escapeHtml(node.content)
case NodeTypes.COMMENT:
return `<!--${escapeHtml(node.content)}-->`
case NodeTypes.INTERPOLATION:
return escapeHtml(toDisplayString(evaluateConstant(node.content)))
case NodeTypes.COMPOUND_EXPRESSION:
return escapeHtml(evaluateConstant(node))
case NodeTypes.TEXT_CALL:
return stringifyNode(node.content, context)
default:
// static trees will not contain if/for nodes
return ''
}
}
function stringifyElement(
node: ElementNode,
context: TransformContext
): string {
let res = `<${node.tag}`
for (let i = 0; i < node.props.length; i++) {
const p = node.props[i]
if (p.type === NodeTypes.ATTRIBUTE) {
res += ` ${p.name}`
if (p.value) {
res += `="${escapeHtml(p.value.content)}"`
}
} else if (p.type === NodeTypes.DIRECTIVE && p.name === 'bind') {
// constant v-bind, e.g. :foo="1"
let evaluated = evaluateConstant(p.exp as SimpleExpressionNode)
const arg = p.arg && (p.arg as SimpleExpressionNode).content
if (arg === 'class') {
evaluated = normalizeClass(evaluated)
} else if (arg === 'style') {
evaluated = stringifyStyle(normalizeStyle(evaluated))
}
res += ` ${(p.arg as SimpleExpressionNode).content}="${escapeHtml(
evaluated
)}"`
}
}
if (context.scopeId) {
res += ` ${context.scopeId}`
}
res += `>`
for (let i = 0; i < node.children.length; i++) {
res += stringifyNode(node.children[i], context)
}
if (!isVoidTag(node.tag)) {
res += `</${node.tag}>`
}
return res
}
// __UNSAFE__
// Reason: eval.
// It's technically safe to eval because only constant expressions are possible
// here, e.g. `{{ 1 }}` or `{{ 'foo' }}`
// in addition, constant exps bail on presence of parens so you can't even
// run JSFuck in here. But we mark it unsafe for security review purposes.
// (see compiler-core/src/transformExpressions)
function evaluateConstant(exp: ExpressionNode): string {
if (exp.type === NodeTypes.SIMPLE_EXPRESSION) {
return new Function(`return ${exp.content}`)()
} else {
// compound
let res = ``
exp.children.forEach(c => {
if (isString(c) || isSymbol(c)) {
return
}
if (c.type === NodeTypes.TEXT) {
res += c.content
} else if (c.type === NodeTypes.INTERPOLATION) {
res += toDisplayString(evaluateConstant(c.content))
} else {
res += evaluateConstant(c)
}
})
return res
}
}
| packages/compiler-dom/src/transforms/stringifyStatic.ts | 0 | https://github.com/vuejs/core/commit/c463a71bb31f01da55927424533e2ece3a3c4efe | [
0.000651622423902154,
0.0001884847297333181,
0.0001615165383554995,
0.0001710339856799692,
0.00008297114982269704
]
|
{
"id": 1,
"code_window": [
" // as 2nd fragment child.\n",
" expect(`Hydration text content mismatch`).toHaveBeenWarned()\n",
" // excessive children removal\n",
" expect(`Hydration children mismatch`).toHaveBeenWarned()\n",
" })\n",
" })\n",
"})"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"\n",
" test('Teleport target has empty children', () => {\n",
" const teleportContainer = document.createElement('div')\n",
" teleportContainer.id = 'teleport'\n",
" document.body.appendChild(teleportContainer)\n",
"\n",
" mountWithHydration('<!--teleport start--><!--teleport end-->', () =>\n",
" h(Teleport, { to: '#teleport' }, [h('span', 'value')])\n",
" )\n",
" expect(teleportContainer.innerHTML).toBe(`<span>value</span>`)\n",
" expect(`Hydration children mismatch`).toHaveBeenWarned()\n",
" })\n"
],
"file_path": "packages/runtime-core/__tests__/hydration.spec.ts",
"type": "add",
"edit_start_line_idx": 688
} | // Patch flags are optimization hints generated by the compiler.
// when a block with dynamicChildren is encountered during diff, the algorithm
// enters "optimized mode". In this mode, we know that the vdom is produced by
// a render function generated by the compiler, so the algorithm only needs to
// handle updates explicitly marked by these patch flags.
// Patch flags can be combined using the | bitwise operator and can be checked
// using the & operator, e.g.
//
// const flag = TEXT | CLASS
// if (flag & TEXT) { ... }
//
// Check the `patchElement` function in './renderer.ts' to see how the
// flags are handled during diff.
export const enum PatchFlags {
// Indicates an element with dynamic textContent (children fast path)
TEXT = 1,
// Indicates an element with dynamic class binding.
CLASS = 1 << 1,
// Indicates an element with dynamic style
// The compiler pre-compiles static string styles into static objects
// + detects and hoists inline static objects
// e.g. style="color: red" and :style="{ color: 'red' }" both get hoisted as
// const style = { color: 'red' }
// render() { return e('div', { style }) }
STYLE = 1 << 2,
// Indicates an element that has non-class/style dynamic props.
// Can also be on a component that has any dynamic props (includes
// class/style). when this flag is present, the vnode also has a dynamicProps
// array that contains the keys of the props that may change so the runtime
// can diff them faster (without having to worry about removed props)
PROPS = 1 << 3,
// Indicates an element with props with dynamic keys. When keys change, a full
// diff is always needed to remove the old key. This flag is mutually
// exclusive with CLASS, STYLE and PROPS.
FULL_PROPS = 1 << 4,
// Indicates an element with event listeners (which need to be attached
// during hydration)
HYDRATE_EVENTS = 1 << 5,
// Indicates a fragment whose children order doesn't change.
STABLE_FRAGMENT = 1 << 6,
// Indicates a fragment with keyed or partially keyed children
KEYED_FRAGMENT = 1 << 7,
// Indicates a fragment with unkeyed children.
UNKEYED_FRAGMENT = 1 << 8,
// Indicates an element that only needs non-props patching, e.g. ref or
// directives (onVnodeXXX hooks). since every patched vnode checks for refs
// and onVnodeXXX hooks, it simply marks the vnode so that a parent block
// will track it.
NEED_PATCH = 1 << 9,
// Indicates a component with dynamic slots (e.g. slot that references a v-for
// iterated value, or dynamic slot names).
// Components with this flag are always force updated.
DYNAMIC_SLOTS = 1 << 10,
// SPECIAL FLAGS -------------------------------------------------------------
// Special flags are negative integers. They are never matched against using
// bitwise operators (bitwise matching should only happen in branches where
// patchFlag > 0), and are mutually exclusive. When checking for a special
// flag, simply check patchFlag === FLAG.
// Indicates a hoisted static vnode. This is a hint for hydration to skip
// the entire sub tree since static content never needs to be updated.
HOISTED = -1,
// A special flag that indicates that the diffing algorithm should bail out
// of optimized mode. For example, on block fragments created by renderSlot()
// when encountering non-compiler generated slots (i.e. manually written
// render functions, which should always be fully diffed)
// OR manually cloneVNodes
BAIL = -2
}
// dev only flag -> name mapping
export const PatchFlagNames = {
[PatchFlags.TEXT]: `TEXT`,
[PatchFlags.CLASS]: `CLASS`,
[PatchFlags.STYLE]: `STYLE`,
[PatchFlags.PROPS]: `PROPS`,
[PatchFlags.FULL_PROPS]: `FULL_PROPS`,
[PatchFlags.HYDRATE_EVENTS]: `HYDRATE_EVENTS`,
[PatchFlags.STABLE_FRAGMENT]: `STABLE_FRAGMENT`,
[PatchFlags.KEYED_FRAGMENT]: `KEYED_FRAGMENT`,
[PatchFlags.UNKEYED_FRAGMENT]: `UNKEYED_FRAGMENT`,
[PatchFlags.DYNAMIC_SLOTS]: `DYNAMIC_SLOTS`,
[PatchFlags.NEED_PATCH]: `NEED_PATCH`,
[PatchFlags.HOISTED]: `HOISTED`,
[PatchFlags.BAIL]: `BAIL`
}
| packages/shared/src/patchFlags.ts | 0 | https://github.com/vuejs/core/commit/c463a71bb31f01da55927424533e2ece3a3c4efe | [
0.23024362325668335,
0.022432154044508934,
0.0001653699582675472,
0.00017304462380707264,
0.06582526862621307
]
|
{
"id": 1,
"code_window": [
" // as 2nd fragment child.\n",
" expect(`Hydration text content mismatch`).toHaveBeenWarned()\n",
" // excessive children removal\n",
" expect(`Hydration children mismatch`).toHaveBeenWarned()\n",
" })\n",
" })\n",
"})"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"\n",
" test('Teleport target has empty children', () => {\n",
" const teleportContainer = document.createElement('div')\n",
" teleportContainer.id = 'teleport'\n",
" document.body.appendChild(teleportContainer)\n",
"\n",
" mountWithHydration('<!--teleport start--><!--teleport end-->', () =>\n",
" h(Teleport, { to: '#teleport' }, [h('span', 'value')])\n",
" )\n",
" expect(teleportContainer.innerHTML).toBe(`<span>value</span>`)\n",
" expect(`Hydration children mismatch`).toHaveBeenWarned()\n",
" })\n"
],
"file_path": "packages/runtime-core/__tests__/hydration.spec.ts",
"type": "add",
"edit_start_line_idx": 688
} | import { compile } from '../src'
describe('ssr: v-model', () => {
test('<input> (text types)', () => {
expect(compile(`<input v-model="bar">`).code).toMatchInlineSnapshot(`
"const { ssrRenderAttr: _ssrRenderAttr } = require(\\"@vue/server-renderer\\")
return function ssrRender(_ctx, _push, _parent) {
_push(\`<input\${_ssrRenderAttr(\\"value\\", _ctx.bar)}>\`)
}"
`)
expect(compile(`<input type="email" v-model="bar">`).code)
.toMatchInlineSnapshot(`
"const { ssrRenderAttr: _ssrRenderAttr } = require(\\"@vue/server-renderer\\")
return function ssrRender(_ctx, _push, _parent) {
_push(\`<input type=\\"email\\"\${_ssrRenderAttr(\\"value\\", _ctx.bar)}>\`)
}"
`)
})
test('<input type="radio">', () => {
expect(compile(`<input type="radio" value="foo" v-model="bar">`).code)
.toMatchInlineSnapshot(`
"const { ssrLooseEqual: _ssrLooseEqual } = require(\\"@vue/server-renderer\\")
return function ssrRender(_ctx, _push, _parent) {
_push(\`<input type=\\"radio\\" value=\\"foo\\"\${(_ssrLooseEqual(_ctx.bar, \\"foo\\")) ? \\" checked\\" : \\"\\"}>\`)
}"
`)
})
test('<input type="checkbox"', () => {
expect(compile(`<input type="checkbox" v-model="bar">`).code)
.toMatchInlineSnapshot(`
"const { ssrLooseContain: _ssrLooseContain } = require(\\"@vue/server-renderer\\")
return function ssrRender(_ctx, _push, _parent) {
_push(\`<input type=\\"checkbox\\"\${((Array.isArray(_ctx.bar))
? _ssrLooseContain(_ctx.bar, null)
: _ctx.bar) ? \\" checked\\" : \\"\\"}>\`)
}"
`)
expect(compile(`<input type="checkbox" value="foo" v-model="bar">`).code)
.toMatchInlineSnapshot(`
"const { ssrLooseContain: _ssrLooseContain } = require(\\"@vue/server-renderer\\")
return function ssrRender(_ctx, _push, _parent) {
_push(\`<input type=\\"checkbox\\" value=\\"foo\\"\${((Array.isArray(_ctx.bar))
? _ssrLooseContain(_ctx.bar, \\"foo\\")
: _ctx.bar) ? \\" checked\\" : \\"\\"}>\`)
}"
`)
})
test('<textarea>', () => {
expect(compile(`<textarea v-model="foo">bar</textarea>`).code)
.toMatchInlineSnapshot(`
"const { ssrInterpolate: _ssrInterpolate } = require(\\"@vue/server-renderer\\")
return function ssrRender(_ctx, _push, _parent) {
_push(\`<textarea>\${_ssrInterpolate(_ctx.foo)}</textarea>\`)
}"
`)
})
test('<input :type="x">', () => {
expect(compile(`<input :type="x" v-model="foo">`).code)
.toMatchInlineSnapshot(`
"const { ssrRenderAttr: _ssrRenderAttr, ssrRenderDynamicModel: _ssrRenderDynamicModel } = require(\\"@vue/server-renderer\\")
return function ssrRender(_ctx, _push, _parent) {
_push(\`<input\${
_ssrRenderAttr(\\"type\\", _ctx.x)
}\${
_ssrRenderDynamicModel(_ctx.x, _ctx.foo, null)
}>\`)
}"
`)
expect(compile(`<input :type="x" v-model="foo" value="bar">`).code)
.toMatchInlineSnapshot(`
"const { ssrRenderAttr: _ssrRenderAttr, ssrRenderDynamicModel: _ssrRenderDynamicModel } = require(\\"@vue/server-renderer\\")
return function ssrRender(_ctx, _push, _parent) {
_push(\`<input\${
_ssrRenderAttr(\\"type\\", _ctx.x)
}\${
_ssrRenderDynamicModel(_ctx.x, _ctx.foo, \\"bar\\")
} value=\\"bar\\">\`)
}"
`)
expect(compile(`<input :type="x" v-model="foo" :value="bar">`).code)
.toMatchInlineSnapshot(`
"const { ssrRenderAttr: _ssrRenderAttr, ssrRenderDynamicModel: _ssrRenderDynamicModel } = require(\\"@vue/server-renderer\\")
return function ssrRender(_ctx, _push, _parent) {
_push(\`<input\${
_ssrRenderAttr(\\"type\\", _ctx.x)
}\${
_ssrRenderDynamicModel(_ctx.x, _ctx.foo, _ctx.bar)
}\${
_ssrRenderAttr(\\"value\\", _ctx.bar)
}>\`)
}"
`)
})
test('<input v-bind="obj">', () => {
expect(compile(`<input v-bind="obj" v-model="foo">`).code)
.toMatchInlineSnapshot(`
"const { mergeProps: _mergeProps } = require(\\"vue\\")
const { ssrRenderAttrs: _ssrRenderAttrs, ssrGetDynamicModelProps: _ssrGetDynamicModelProps } = require(\\"@vue/server-renderer\\")
return function ssrRender(_ctx, _push, _parent) {
let _temp0
_push(\`<input\${_ssrRenderAttrs((_temp0 = _ctx.obj, _mergeProps(_temp0, _ssrGetDynamicModelProps(_temp0, _ctx.foo))))}>\`)
}"
`)
expect(compile(`<input id="x" v-bind="obj" v-model="foo" class="y">`).code)
.toMatchInlineSnapshot(`
"const { mergeProps: _mergeProps } = require(\\"vue\\")
const { ssrRenderAttrs: _ssrRenderAttrs, ssrGetDynamicModelProps: _ssrGetDynamicModelProps } = require(\\"@vue/server-renderer\\")
return function ssrRender(_ctx, _push, _parent) {
let _temp0
_push(\`<input\${_ssrRenderAttrs((_temp0 = _mergeProps({ id: \\"x\\" }, _ctx.obj, { class: \\"y\\" }), _mergeProps(_temp0, _ssrGetDynamicModelProps(_temp0, _ctx.foo))))}>\`)
}"
`)
})
})
| packages/compiler-ssr/__tests__/ssrVModel.spec.ts | 0 | https://github.com/vuejs/core/commit/c463a71bb31f01da55927424533e2ece3a3c4efe | [
0.00017851863231044263,
0.00017228529031854123,
0.00016584922559559345,
0.00017309140821453184,
0.000003561378662197967
]
|
{
"id": 2,
"code_window": [
" parentComponent,\n",
" parentSuspense,\n",
" optimized\n",
" )\n",
" }\n",
" ;(target as TeleportTargetElement)._lpa = nextSibling(\n",
" vnode.targetAnchor as Node\n",
" )\n",
" }\n",
" }\n",
" return vnode.anchor && nextSibling(vnode.anchor as Node)\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ;(target as TeleportTargetElement)._lpa =\n",
" vnode.targetAnchor && nextSibling(vnode.targetAnchor as Node)\n"
],
"file_path": "packages/runtime-core/src/components/Teleport.ts",
"type": "replace",
"edit_start_line_idx": 316
} | import {
createSSRApp,
h,
ref,
nextTick,
VNode,
Teleport,
createStaticVNode,
Suspense,
onMounted,
defineAsyncComponent,
defineComponent
} from '@vue/runtime-dom'
import { renderToString } from '@vue/server-renderer'
import { mockWarn } from '@vue/shared'
import { SSRContext } from 'packages/server-renderer/src/renderToString'
function mountWithHydration(html: string, render: () => any) {
const container = document.createElement('div')
container.innerHTML = html
const app = createSSRApp({
render
})
return {
vnode: app.mount(container).$.subTree as VNode<Node, Element> & {
el: Element
},
container
}
}
const triggerEvent = (type: string, el: Element) => {
const event = new Event(type)
el.dispatchEvent(event)
}
describe('SSR hydration', () => {
mockWarn()
test('text', async () => {
const msg = ref('foo')
const { vnode, container } = mountWithHydration('foo', () => msg.value)
expect(vnode.el).toBe(container.firstChild)
expect(container.textContent).toBe('foo')
msg.value = 'bar'
await nextTick()
expect(container.textContent).toBe('bar')
})
test('comment', () => {
const { vnode, container } = mountWithHydration('<!---->', () => null)
expect(vnode.el).toBe(container.firstChild)
expect(vnode.el.nodeType).toBe(8) // comment
})
test('static', () => {
const html = '<div><span>hello</span></div>'
const { vnode, container } = mountWithHydration(html, () =>
createStaticVNode('', 1)
)
expect(vnode.el).toBe(container.firstChild)
expect(vnode.el.outerHTML).toBe(html)
expect(vnode.anchor).toBe(container.firstChild)
expect(vnode.children).toBe(html)
})
test('static (multiple elements)', () => {
const staticContent = '<div></div><span>hello</span>'
const html = `<div><div>hi</div>` + staticContent + `<div>ho</div></div>`
const n1 = h('div', 'hi')
const s = createStaticVNode('', 2)
const n2 = h('div', 'ho')
const { container } = mountWithHydration(html, () => h('div', [n1, s, n2]))
const div = container.firstChild!
expect(n1.el).toBe(div.firstChild)
expect(n2.el).toBe(div.lastChild)
expect(s.el).toBe(div.childNodes[1])
expect(s.anchor).toBe(div.childNodes[2])
expect(s.children).toBe(staticContent)
})
test('element with text children', async () => {
const msg = ref('foo')
const { vnode, container } = mountWithHydration(
'<div class="foo">foo</div>',
() => h('div', { class: msg.value }, msg.value)
)
expect(vnode.el).toBe(container.firstChild)
expect(container.firstChild!.textContent).toBe('foo')
msg.value = 'bar'
await nextTick()
expect(container.innerHTML).toBe(`<div class="bar">bar</div>`)
})
test('element with elements children', async () => {
const msg = ref('foo')
const fn = jest.fn()
const { vnode, container } = mountWithHydration(
'<div><span>foo</span><span class="foo"></span></div>',
() =>
h('div', [
h('span', msg.value),
h('span', { class: msg.value, onClick: fn })
])
)
expect(vnode.el).toBe(container.firstChild)
expect((vnode.children as VNode[])[0].el).toBe(
container.firstChild!.childNodes[0]
)
expect((vnode.children as VNode[])[1].el).toBe(
container.firstChild!.childNodes[1]
)
// event handler
triggerEvent('click', vnode.el.querySelector('.foo')!)
expect(fn).toHaveBeenCalled()
msg.value = 'bar'
await nextTick()
expect(vnode.el.innerHTML).toBe(`<span>bar</span><span class="bar"></span>`)
})
test('element with ref', () => {
const el = ref()
const { vnode, container } = mountWithHydration('<div></div>', () =>
h('div', { ref: el })
)
expect(vnode.el).toBe(container.firstChild)
expect(el.value).toBe(vnode.el)
})
test('Fragment', async () => {
const msg = ref('foo')
const fn = jest.fn()
const { vnode, container } = mountWithHydration(
'<div><!--[--><span>foo</span><!--[--><span class="foo"></span><!--]--><!--]--></div>',
() =>
h('div', [
[h('span', msg.value), [h('span', { class: msg.value, onClick: fn })]]
])
)
expect(vnode.el).toBe(container.firstChild)
expect(vnode.el.innerHTML).toBe(
`<!--[--><span>foo</span><!--[--><span class="foo"></span><!--]--><!--]-->`
)
// start fragment 1
const fragment1 = (vnode.children as VNode[])[0]
expect(fragment1.el).toBe(vnode.el.childNodes[0])
const fragment1Children = fragment1.children as VNode[]
// first <span>
expect(fragment1Children[0].el!.tagName).toBe('SPAN')
expect(fragment1Children[0].el).toBe(vnode.el.childNodes[1])
// start fragment 2
const fragment2 = fragment1Children[1]
expect(fragment2.el).toBe(vnode.el.childNodes[2])
const fragment2Children = fragment2.children as VNode[]
// second <span>
expect(fragment2Children[0].el!.tagName).toBe('SPAN')
expect(fragment2Children[0].el).toBe(vnode.el.childNodes[3])
// end fragment 2
expect(fragment2.anchor).toBe(vnode.el.childNodes[4])
// end fragment 1
expect(fragment1.anchor).toBe(vnode.el.childNodes[5])
// event handler
triggerEvent('click', vnode.el.querySelector('.foo')!)
expect(fn).toHaveBeenCalled()
msg.value = 'bar'
await nextTick()
expect(vnode.el.innerHTML).toBe(
`<!--[--><span>bar</span><!--[--><span class="bar"></span><!--]--><!--]-->`
)
})
test('Teleport', async () => {
const msg = ref('foo')
const fn = jest.fn()
const teleportContainer = document.createElement('div')
teleportContainer.id = 'teleport'
teleportContainer.innerHTML = `<span>foo</span><span class="foo"></span><!---->`
document.body.appendChild(teleportContainer)
const { vnode, container } = mountWithHydration(
'<!--teleport start--><!--teleport end-->',
() =>
h(Teleport, { to: '#teleport' }, [
h('span', msg.value),
h('span', { class: msg.value, onClick: fn })
])
)
expect(vnode.el).toBe(container.firstChild)
expect(vnode.anchor).toBe(container.lastChild)
expect(vnode.target).toBe(teleportContainer)
expect((vnode.children as VNode[])[0].el).toBe(
teleportContainer.childNodes[0]
)
expect((vnode.children as VNode[])[1].el).toBe(
teleportContainer.childNodes[1]
)
expect(vnode.targetAnchor).toBe(teleportContainer.childNodes[2])
// event handler
triggerEvent('click', teleportContainer.querySelector('.foo')!)
expect(fn).toHaveBeenCalled()
msg.value = 'bar'
await nextTick()
expect(teleportContainer.innerHTML).toBe(
`<span>bar</span><span class="bar"></span><!---->`
)
})
test('Teleport (multiple + integration)', async () => {
const msg = ref('foo')
const fn1 = jest.fn()
const fn2 = jest.fn()
const Comp = () => [
h(Teleport, { to: '#teleport2' }, [
h('span', msg.value),
h('span', { class: msg.value, onClick: fn1 })
]),
h(Teleport, { to: '#teleport2' }, [
h('span', msg.value + '2'),
h('span', { class: msg.value + '2', onClick: fn2 })
])
]
const teleportContainer = document.createElement('div')
teleportContainer.id = 'teleport2'
const ctx: SSRContext = {}
const mainHtml = await renderToString(h(Comp), ctx)
expect(mainHtml).toMatchInlineSnapshot(
`"<!--[--><!--teleport start--><!--teleport end--><!--teleport start--><!--teleport end--><!--]-->"`
)
const teleportHtml = ctx.teleports!['#teleport2']
expect(teleportHtml).toMatchInlineSnapshot(
`"<span>foo</span><span class=\\"foo\\"></span><!----><span>foo2</span><span class=\\"foo2\\"></span><!---->"`
)
teleportContainer.innerHTML = teleportHtml
document.body.appendChild(teleportContainer)
const { vnode, container } = mountWithHydration(mainHtml, Comp)
expect(vnode.el).toBe(container.firstChild)
const teleportVnode1 = (vnode.children as VNode[])[0]
const teleportVnode2 = (vnode.children as VNode[])[1]
expect(teleportVnode1.el).toBe(container.childNodes[1])
expect(teleportVnode1.anchor).toBe(container.childNodes[2])
expect(teleportVnode2.el).toBe(container.childNodes[3])
expect(teleportVnode2.anchor).toBe(container.childNodes[4])
expect(teleportVnode1.target).toBe(teleportContainer)
expect((teleportVnode1 as any).children[0].el).toBe(
teleportContainer.childNodes[0]
)
expect(teleportVnode1.targetAnchor).toBe(teleportContainer.childNodes[2])
expect(teleportVnode2.target).toBe(teleportContainer)
expect((teleportVnode2 as any).children[0].el).toBe(
teleportContainer.childNodes[3]
)
expect(teleportVnode2.targetAnchor).toBe(teleportContainer.childNodes[5])
// // event handler
triggerEvent('click', teleportContainer.querySelector('.foo')!)
expect(fn1).toHaveBeenCalled()
triggerEvent('click', teleportContainer.querySelector('.foo2')!)
expect(fn2).toHaveBeenCalled()
msg.value = 'bar'
await nextTick()
expect(teleportContainer.innerHTML).toMatchInlineSnapshot(
`"<span>bar</span><span class=\\"bar\\"></span><!----><span>bar2</span><span class=\\"bar2\\"></span><!---->"`
)
})
test('Teleport (disabled)', async () => {
const msg = ref('foo')
const fn1 = jest.fn()
const fn2 = jest.fn()
const Comp = () => [
h('div', 'foo'),
h(Teleport, { to: '#teleport3', disabled: true }, [
h('span', msg.value),
h('span', { class: msg.value, onClick: fn1 })
]),
h('div', { class: msg.value + '2', onClick: fn2 }, 'bar')
]
const teleportContainer = document.createElement('div')
teleportContainer.id = 'teleport3'
const ctx: SSRContext = {}
const mainHtml = await renderToString(h(Comp), ctx)
expect(mainHtml).toMatchInlineSnapshot(
`"<!--[--><div>foo</div><!--teleport start--><span>foo</span><span class=\\"foo\\"></span><!--teleport end--><div class=\\"foo2\\">bar</div><!--]-->"`
)
const teleportHtml = ctx.teleports!['#teleport3']
expect(teleportHtml).toMatchInlineSnapshot(`"<!---->"`)
teleportContainer.innerHTML = teleportHtml
document.body.appendChild(teleportContainer)
const { vnode, container } = mountWithHydration(mainHtml, Comp)
expect(vnode.el).toBe(container.firstChild)
const children = vnode.children as VNode[]
expect(children[0].el).toBe(container.childNodes[1])
const teleportVnode = children[1]
expect(teleportVnode.el).toBe(container.childNodes[2])
expect((teleportVnode.children as VNode[])[0].el).toBe(
container.childNodes[3]
)
expect((teleportVnode.children as VNode[])[1].el).toBe(
container.childNodes[4]
)
expect(teleportVnode.anchor).toBe(container.childNodes[5])
expect(children[2].el).toBe(container.childNodes[6])
expect(teleportVnode.target).toBe(teleportContainer)
expect(teleportVnode.targetAnchor).toBe(teleportContainer.childNodes[0])
// // event handler
triggerEvent('click', container.querySelector('.foo')!)
expect(fn1).toHaveBeenCalled()
triggerEvent('click', container.querySelector('.foo2')!)
expect(fn2).toHaveBeenCalled()
msg.value = 'bar'
await nextTick()
expect(container.innerHTML).toMatchInlineSnapshot(
`"<!--[--><div>foo</div><!--teleport start--><span>bar</span><span class=\\"bar\\"></span><!--teleport end--><div class=\\"bar2\\">bar</div><!--]-->"`
)
})
// compile SSR + client render fn from the same template & hydrate
test('full compiler integration', async () => {
const mounted: string[] = []
const log = jest.fn()
const toggle = ref(true)
const Child = {
data() {
return {
count: 0,
text: 'hello',
style: {
color: 'red'
}
}
},
mounted() {
mounted.push('child')
},
template: `
<div>
<span class="count" :style="style">{{ count }}</span>
<button class="inc" @click="count++">inc</button>
<button class="change" @click="style.color = 'green'" >change color</button>
<button class="emit" @click="$emit('foo')">emit</button>
<span class="text">{{ text }}</span>
<input v-model="text">
</div>
`
}
const App = {
setup() {
return { toggle }
},
mounted() {
mounted.push('parent')
},
template: `
<div>
<span>hello</span>
<template v-if="toggle">
<Child @foo="log('child')"/>
<template v-if="true">
<button class="parent-click" @click="log('click')">click me</button>
</template>
</template>
<span>hello</span>
</div>`,
components: {
Child
},
methods: {
log
}
}
const container = document.createElement('div')
// server render
container.innerHTML = await renderToString(h(App))
// hydrate
createSSRApp(App).mount(container)
// assert interactions
// 1. parent button click
triggerEvent('click', container.querySelector('.parent-click')!)
expect(log).toHaveBeenCalledWith('click')
// 2. child inc click + text interpolation
const count = container.querySelector('.count') as HTMLElement
expect(count.textContent).toBe(`0`)
triggerEvent('click', container.querySelector('.inc')!)
await nextTick()
expect(count.textContent).toBe(`1`)
// 3. child color click + style binding
expect(count.style.color).toBe('red')
triggerEvent('click', container.querySelector('.change')!)
await nextTick()
expect(count.style.color).toBe('green')
// 4. child event emit
triggerEvent('click', container.querySelector('.emit')!)
expect(log).toHaveBeenCalledWith('child')
// 5. child v-model
const text = container.querySelector('.text')!
const input = container.querySelector('input')!
expect(text.textContent).toBe('hello')
input.value = 'bye'
triggerEvent('input', input)
await nextTick()
expect(text.textContent).toBe('bye')
})
test('Suspense', async () => {
const AsyncChild = {
async setup() {
const count = ref(0)
return () =>
h(
'span',
{
onClick: () => {
count.value++
}
},
count.value
)
}
}
const { vnode, container } = mountWithHydration('<span>0</span>', () =>
h(Suspense, () => h(AsyncChild))
)
expect(vnode.el).toBe(container.firstChild)
// wait for hydration to finish
await new Promise(r => setTimeout(r))
triggerEvent('click', container.querySelector('span')!)
await nextTick()
expect(container.innerHTML).toBe(`<span>1</span>`)
})
test('Suspense (full integration)', async () => {
const mountedCalls: number[] = []
const asyncDeps: Promise<any>[] = []
const AsyncChild = defineComponent({
props: ['n'],
async setup(props) {
const count = ref(props.n)
onMounted(() => {
mountedCalls.push(props.n)
})
const p = new Promise(r => setTimeout(r, props.n * 10))
asyncDeps.push(p)
await p
return () =>
h(
'span',
{
onClick: () => {
count.value++
}
},
count.value
)
}
})
const done = jest.fn()
const App = {
template: `
<Suspense @resolve="done">
<AsyncChild :n="1" />
<AsyncChild :n="2" />
</Suspense>`,
components: {
AsyncChild
},
methods: {
done
}
}
const container = document.createElement('div')
// server render
container.innerHTML = await renderToString(h(App))
expect(container.innerHTML).toMatchInlineSnapshot(
`"<!--[--><span>1</span><span>2</span><!--]-->"`
)
// reset asyncDeps from ssr
asyncDeps.length = 0
// hydrate
createSSRApp(App).mount(container)
expect(mountedCalls.length).toBe(0)
expect(asyncDeps.length).toBe(2)
// wait for hydration to complete
await Promise.all(asyncDeps)
await new Promise(r => setTimeout(r))
// should flush buffered effects
expect(mountedCalls).toMatchObject([1, 2])
expect(container.innerHTML).toMatch(`<span>1</span><span>2</span>`)
const span1 = container.querySelector('span')!
triggerEvent('click', span1)
await nextTick()
expect(container.innerHTML).toMatch(`<span>2</span><span>2</span>`)
const span2 = span1.nextSibling as Element
triggerEvent('click', span2)
await nextTick()
expect(container.innerHTML).toMatch(`<span>2</span><span>3</span>`)
})
test('async component', async () => {
const spy = jest.fn()
const Comp = () =>
h(
'button',
{
onClick: spy
},
'hello!'
)
let serverResolve: any
let AsyncComp = defineAsyncComponent(
() =>
new Promise(r => {
serverResolve = r
})
)
const App = {
render() {
return ['hello', h(AsyncComp), 'world']
}
}
// server render
const htmlPromise = renderToString(h(App))
serverResolve(Comp)
const html = await htmlPromise
expect(html).toMatchInlineSnapshot(
`"<!--[-->hello<button>hello!</button>world<!--]-->"`
)
// hydration
let clientResolve: any
AsyncComp = defineAsyncComponent(
() =>
new Promise(r => {
clientResolve = r
})
)
const container = document.createElement('div')
container.innerHTML = html
createSSRApp(App).mount(container)
// hydration not complete yet
triggerEvent('click', container.querySelector('button')!)
expect(spy).not.toHaveBeenCalled()
// resolve
clientResolve(Comp)
await new Promise(r => setTimeout(r))
// should be hydrated now
triggerEvent('click', container.querySelector('button')!)
expect(spy).toHaveBeenCalled()
})
describe('mismatch handling', () => {
test('text node', () => {
const { container } = mountWithHydration(`foo`, () => 'bar')
expect(container.textContent).toBe('bar')
expect(`Hydration text mismatch`).toHaveBeenWarned()
})
test('element text content', () => {
const { container } = mountWithHydration(`<div>foo</div>`, () =>
h('div', 'bar')
)
expect(container.innerHTML).toBe('<div>bar</div>')
expect(`Hydration text content mismatch in <div>`).toHaveBeenWarned()
})
test('not enough children', () => {
const { container } = mountWithHydration(`<div></div>`, () =>
h('div', [h('span', 'foo'), h('span', 'bar')])
)
expect(container.innerHTML).toBe(
'<div><span>foo</span><span>bar</span></div>'
)
expect(`Hydration children mismatch in <div>`).toHaveBeenWarned()
})
test('too many children', () => {
const { container } = mountWithHydration(
`<div><span>foo</span><span>bar</span></div>`,
() => h('div', [h('span', 'foo')])
)
expect(container.innerHTML).toBe('<div><span>foo</span></div>')
expect(`Hydration children mismatch in <div>`).toHaveBeenWarned()
})
test('complete mismatch', () => {
const { container } = mountWithHydration(
`<div><span>foo</span><span>bar</span></div>`,
() => h('div', [h('div', 'foo'), h('p', 'bar')])
)
expect(container.innerHTML).toBe('<div><div>foo</div><p>bar</p></div>')
expect(`Hydration node mismatch`).toHaveBeenWarnedTimes(2)
})
test('fragment mismatch removal', () => {
const { container } = mountWithHydration(
`<div><!--[--><div>foo</div><div>bar</div><!--]--></div>`,
() => h('div', [h('span', 'replaced')])
)
expect(container.innerHTML).toBe('<div><span>replaced</span></div>')
expect(`Hydration node mismatch`).toHaveBeenWarned()
})
test('fragment not enough children', () => {
const { container } = mountWithHydration(
`<div><!--[--><div>foo</div><!--]--><div>baz</div></div>`,
() => h('div', [[h('div', 'foo'), h('div', 'bar')], h('div', 'baz')])
)
expect(container.innerHTML).toBe(
'<div><!--[--><div>foo</div><div>bar</div><!--]--><div>baz</div></div>'
)
expect(`Hydration node mismatch`).toHaveBeenWarned()
})
test('fragment too many children', () => {
const { container } = mountWithHydration(
`<div><!--[--><div>foo</div><div>bar</div><!--]--><div>baz</div></div>`,
() => h('div', [[h('div', 'foo')], h('div', 'baz')])
)
expect(container.innerHTML).toBe(
'<div><!--[--><div>foo</div><!--]--><div>baz</div></div>'
)
// fragment ends early and attempts to hydrate the extra <div>bar</div>
// as 2nd fragment child.
expect(`Hydration text content mismatch`).toHaveBeenWarned()
// excessive children removal
expect(`Hydration children mismatch`).toHaveBeenWarned()
})
})
})
| packages/runtime-core/__tests__/hydration.spec.ts | 1 | https://github.com/vuejs/core/commit/c463a71bb31f01da55927424533e2ece3a3c4efe | [
0.007893215864896774,
0.0007452791323885322,
0.0001645443553570658,
0.00017639866564422846,
0.0012935781851410866
]
|
{
"id": 2,
"code_window": [
" parentComponent,\n",
" parentSuspense,\n",
" optimized\n",
" )\n",
" }\n",
" ;(target as TeleportTargetElement)._lpa = nextSibling(\n",
" vnode.targetAnchor as Node\n",
" )\n",
" }\n",
" }\n",
" return vnode.anchor && nextSibling(vnode.anchor as Node)\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ;(target as TeleportTargetElement)._lpa =\n",
" vnode.targetAnchor && nextSibling(vnode.targetAnchor as Node)\n"
],
"file_path": "packages/runtime-core/src/components/Teleport.ts",
"type": "replace",
"edit_start_line_idx": 316
} | import {
ComponentNode,
TransformContext,
buildSlots,
createFunctionExpression,
FunctionExpression,
TemplateChildNode,
createCallExpression,
SlotsExpression
} from '@vue/compiler-dom'
import {
SSRTransformContext,
processChildrenAsStatement
} from '../ssrCodegenTransform'
import { SSR_RENDER_SUSPENSE } from '../runtimeHelpers'
const wipMap = new WeakMap<ComponentNode, WIPEntry>()
interface WIPEntry {
slotsExp: SlotsExpression
wipSlots: Array<{
fn: FunctionExpression
children: TemplateChildNode[]
}>
}
// phase 1
export function ssrTransformSuspense(
node: ComponentNode,
context: TransformContext
) {
return () => {
if (node.children.length) {
const wipEntry: WIPEntry = {
slotsExp: null as any,
wipSlots: []
}
wipMap.set(node, wipEntry)
wipEntry.slotsExp = buildSlots(node, context, (_props, children, loc) => {
const fn = createFunctionExpression(
[],
undefined, // no return, assign body later
true, // newline
false, // suspense slots are not treated as normal slots
loc
)
wipEntry.wipSlots.push({
fn,
children
})
return fn
}).slots
}
}
}
// phase 2
export function ssrProcessSuspense(
node: ComponentNode,
context: SSRTransformContext
) {
// complete wip slots with ssr code
const wipEntry = wipMap.get(node)
if (!wipEntry) {
return
}
const { slotsExp, wipSlots } = wipEntry
for (let i = 0; i < wipSlots.length; i++) {
const { fn, children } = wipSlots[i]
fn.body = processChildrenAsStatement(children, context)
}
// _push(ssrRenderSuspense(slots))
context.pushStatement(
createCallExpression(context.helper(SSR_RENDER_SUSPENSE), [
`_push`,
slotsExp
])
)
}
| packages/compiler-ssr/src/transforms/ssrTransformSuspense.ts | 0 | https://github.com/vuejs/core/commit/c463a71bb31f01da55927424533e2ece3a3c4efe | [
0.00020928938465658575,
0.00017304190259892493,
0.0001651211641728878,
0.00016786385094746947,
0.000013854450116923545
]
|
{
"id": 2,
"code_window": [
" parentComponent,\n",
" parentSuspense,\n",
" optimized\n",
" )\n",
" }\n",
" ;(target as TeleportTargetElement)._lpa = nextSibling(\n",
" vnode.targetAnchor as Node\n",
" )\n",
" }\n",
" }\n",
" return vnode.anchor && nextSibling(vnode.anchor as Node)\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ;(target as TeleportTargetElement)._lpa =\n",
" vnode.targetAnchor && nextSibling(vnode.targetAnchor as Node)\n"
],
"file_path": "packages/runtime-core/src/components/Teleport.ts",
"type": "replace",
"edit_start_line_idx": 316
} | import {
locStub,
generate,
NodeTypes,
RootNode,
createSimpleExpression,
createObjectExpression,
createObjectProperty,
createArrayExpression,
createCompoundExpression,
createInterpolation,
createCallExpression,
createConditionalExpression,
ForCodegenNode,
createCacheExpression,
createTemplateLiteral,
createBlockStatement,
createIfStatement,
createAssignmentExpression,
IfConditionalExpression,
createVNodeCall,
VNodeCall,
DirectiveArguments
} from '../src'
import {
CREATE_VNODE,
TO_DISPLAY_STRING,
RESOLVE_DIRECTIVE,
helperNameMap,
RESOLVE_COMPONENT,
CREATE_COMMENT,
FRAGMENT,
RENDER_LIST
} from '../src/runtimeHelpers'
import { createElementWithCodegen } from './testUtils'
import { PatchFlags } from '@vue/shared'
function createRoot(options: Partial<RootNode> = {}): RootNode {
return {
type: NodeTypes.ROOT,
children: [],
helpers: [],
components: [],
directives: [],
imports: [],
hoists: [],
cached: 0,
temps: 0,
codegenNode: createSimpleExpression(`null`, false),
loc: locStub,
...options
}
}
describe('compiler: codegen', () => {
test('module mode preamble', () => {
const root = createRoot({
helpers: [CREATE_VNODE, RESOLVE_DIRECTIVE]
})
const { code } = generate(root, { mode: 'module' })
expect(code).toMatch(
`import { ${helperNameMap[CREATE_VNODE]} as _${
helperNameMap[CREATE_VNODE]
}, ${helperNameMap[RESOLVE_DIRECTIVE]} as _${
helperNameMap[RESOLVE_DIRECTIVE]
} } from "vue"`
)
expect(code).toMatchSnapshot()
})
test('module mode preamble w/ optimizeBindings: true', () => {
const root = createRoot({
helpers: [CREATE_VNODE, RESOLVE_DIRECTIVE]
})
const { code } = generate(root, { mode: 'module', optimizeBindings: true })
expect(code).toMatch(
`import { ${helperNameMap[CREATE_VNODE]}, ${
helperNameMap[RESOLVE_DIRECTIVE]
} } from "vue"`
)
expect(code).toMatch(
`const _${helperNameMap[CREATE_VNODE]} = ${
helperNameMap[CREATE_VNODE]
}, _${helperNameMap[RESOLVE_DIRECTIVE]} = ${
helperNameMap[RESOLVE_DIRECTIVE]
}`
)
expect(code).toMatchSnapshot()
})
test('function mode preamble', () => {
const root = createRoot({
helpers: [CREATE_VNODE, RESOLVE_DIRECTIVE]
})
const { code } = generate(root, { mode: 'function' })
expect(code).toMatch(`const _Vue = Vue`)
expect(code).toMatch(
`const { ${helperNameMap[CREATE_VNODE]}: _${
helperNameMap[CREATE_VNODE]
}, ${helperNameMap[RESOLVE_DIRECTIVE]}: _${
helperNameMap[RESOLVE_DIRECTIVE]
} } = _Vue`
)
expect(code).toMatchSnapshot()
})
test('function mode preamble w/ prefixIdentifiers: true', () => {
const root = createRoot({
helpers: [CREATE_VNODE, RESOLVE_DIRECTIVE]
})
const { code } = generate(root, {
mode: 'function',
prefixIdentifiers: true
})
expect(code).not.toMatch(`const _Vue = Vue`)
expect(code).toMatch(
`const { ${helperNameMap[CREATE_VNODE]}: _${
helperNameMap[CREATE_VNODE]
}, ${helperNameMap[RESOLVE_DIRECTIVE]}: _${
helperNameMap[RESOLVE_DIRECTIVE]
} } = Vue`
)
expect(code).toMatchSnapshot()
})
test('assets + temps', () => {
const root = createRoot({
components: [`Foo`, `bar-baz`, `barbaz`],
directives: [`my_dir_0`, `my_dir_1`],
temps: 3
})
const { code } = generate(root, { mode: 'function' })
expect(code).toMatch(
`const _component_Foo = _${helperNameMap[RESOLVE_COMPONENT]}("Foo")\n`
)
expect(code).toMatch(
`const _component_bar_baz = _${
helperNameMap[RESOLVE_COMPONENT]
}("bar-baz")\n`
)
expect(code).toMatch(
`const _component_barbaz = _${
helperNameMap[RESOLVE_COMPONENT]
}("barbaz")\n`
)
expect(code).toMatch(
`const _directive_my_dir_0 = _${
helperNameMap[RESOLVE_DIRECTIVE]
}("my_dir_0")\n`
)
expect(code).toMatch(
`const _directive_my_dir_1 = _${
helperNameMap[RESOLVE_DIRECTIVE]
}("my_dir_1")\n`
)
expect(code).toMatch(`let _temp0, _temp1, _temp2`)
expect(code).toMatchSnapshot()
})
test('hoists', () => {
const root = createRoot({
hoists: [
createSimpleExpression(`hello`, false, locStub),
createObjectExpression(
[
createObjectProperty(
createSimpleExpression(`id`, true, locStub),
createSimpleExpression(`foo`, true, locStub)
)
],
locStub
)
]
})
const { code } = generate(root)
expect(code).toMatch(`const _hoisted_1 = hello`)
expect(code).toMatch(`const _hoisted_2 = { id: "foo" }`)
expect(code).toMatchSnapshot()
})
test('temps', () => {
const root = createRoot({
temps: 3
})
const { code } = generate(root)
expect(code).toMatch(`let _temp0, _temp1, _temp2`)
expect(code).toMatchSnapshot()
})
test('static text', () => {
const { code } = generate(
createRoot({
codegenNode: {
type: NodeTypes.TEXT,
content: 'hello',
loc: locStub
}
})
)
expect(code).toMatch(`return "hello"`)
expect(code).toMatchSnapshot()
})
test('interpolation', () => {
const { code } = generate(
createRoot({
codegenNode: createInterpolation(`hello`, locStub)
})
)
expect(code).toMatch(`return _${helperNameMap[TO_DISPLAY_STRING]}(hello)`)
expect(code).toMatchSnapshot()
})
test('comment', () => {
const { code } = generate(
createRoot({
codegenNode: {
type: NodeTypes.COMMENT,
content: 'foo',
loc: locStub
}
})
)
expect(code).toMatch(`return _${helperNameMap[CREATE_COMMENT]}("foo")`)
expect(code).toMatchSnapshot()
})
test('compound expression', () => {
const { code } = generate(
createRoot({
codegenNode: createCompoundExpression([
`_ctx.`,
createSimpleExpression(`foo`, false, locStub),
` + `,
{
type: NodeTypes.INTERPOLATION,
loc: locStub,
content: createSimpleExpression(`bar`, false, locStub)
},
// nested compound
createCompoundExpression([` + `, `nested`])
])
})
)
expect(code).toMatch(
`return _ctx.foo + _${helperNameMap[TO_DISPLAY_STRING]}(bar) + nested`
)
expect(code).toMatchSnapshot()
})
test('ifNode', () => {
const { code } = generate(
createRoot({
codegenNode: {
type: NodeTypes.IF,
loc: locStub,
branches: [],
codegenNode: createConditionalExpression(
createSimpleExpression('foo', false),
createSimpleExpression('bar', false),
createSimpleExpression('baz', false)
) as IfConditionalExpression
}
})
)
expect(code).toMatch(/return foo\s+\? bar\s+: baz/)
expect(code).toMatchSnapshot()
})
test('forNode', () => {
const { code } = generate(
createRoot({
codegenNode: {
type: NodeTypes.FOR,
loc: locStub,
source: createSimpleExpression('foo', false),
valueAlias: undefined,
keyAlias: undefined,
objectIndexAlias: undefined,
children: [],
parseResult: {} as any,
codegenNode: {
type: NodeTypes.VNODE_CALL,
tag: FRAGMENT,
isBlock: true,
isForBlock: true,
props: undefined,
children: createCallExpression(RENDER_LIST),
patchFlag: '1',
dynamicProps: undefined,
directives: undefined,
loc: locStub
} as ForCodegenNode
}
})
)
expect(code).toMatch(`openBlock(true)`)
expect(code).toMatchSnapshot()
})
test('Element (callExpression + objectExpression + TemplateChildNode[])', () => {
const { code } = generate(
createRoot({
codegenNode: createElementWithCodegen(
// string
`"div"`,
// ObjectExpression
createObjectExpression(
[
createObjectProperty(
createSimpleExpression(`id`, true, locStub),
createSimpleExpression(`foo`, true, locStub)
),
createObjectProperty(
createSimpleExpression(`prop`, false, locStub),
createSimpleExpression(`bar`, false, locStub)
),
// compound expression as computed key
createObjectProperty(
{
type: NodeTypes.COMPOUND_EXPRESSION,
loc: locStub,
children: [
`foo + `,
createSimpleExpression(`bar`, false, locStub)
]
},
createSimpleExpression(`bar`, false, locStub)
)
],
locStub
),
// ChildNode[]
[
createElementWithCodegen(
`"p"`,
createObjectExpression(
[
createObjectProperty(
// should quote the key!
createSimpleExpression(`some-key`, true, locStub),
createSimpleExpression(`foo`, true, locStub)
)
],
locStub
)
)
],
// flag
PatchFlags.FULL_PROPS + ''
)
})
)
expect(code).toMatch(`
return _${helperNameMap[CREATE_VNODE]}("div", {
id: "foo",
[prop]: bar,
[foo + bar]: bar
}, [
_${helperNameMap[CREATE_VNODE]}("p", { "some-key": "foo" })
], ${PatchFlags.FULL_PROPS})`)
expect(code).toMatchSnapshot()
})
test('ArrayExpression', () => {
const { code } = generate(
createRoot({
codegenNode: createArrayExpression([
createSimpleExpression(`foo`, false),
createCallExpression(`bar`, [`baz`])
])
})
)
expect(code).toMatch(`return [
foo,
bar(baz)
]`)
expect(code).toMatchSnapshot()
})
test('ConditionalExpression', () => {
const { code } = generate(
createRoot({
codegenNode: createConditionalExpression(
createSimpleExpression(`ok`, false),
createCallExpression(`foo`),
createConditionalExpression(
createSimpleExpression(`orNot`, false),
createCallExpression(`bar`),
createCallExpression(`baz`)
)
)
})
)
expect(code).toMatch(
`return ok
? foo()
: orNot
? bar()
: baz()`
)
expect(code).toMatchSnapshot()
})
test('CacheExpression', () => {
const { code } = generate(
createRoot({
cached: 1,
codegenNode: createCacheExpression(
1,
createSimpleExpression(`foo`, false)
)
}),
{
mode: 'module',
prefixIdentifiers: true
}
)
expect(code).toMatch(`_cache[1] || (_cache[1] = foo)`)
expect(code).toMatchSnapshot()
})
test('CacheExpression w/ isVNode: true', () => {
const { code } = generate(
createRoot({
cached: 1,
codegenNode: createCacheExpression(
1,
createSimpleExpression(`foo`, false),
true
)
}),
{
mode: 'module',
prefixIdentifiers: true
}
)
expect(code).toMatch(
`
_cache[1] || (
_setBlockTracking(-1),
_cache[1] = foo,
_setBlockTracking(1),
_cache[1]
)
`.trim()
)
expect(code).toMatchSnapshot()
})
test('TemplateLiteral', () => {
const { code } = generate(
createRoot({
codegenNode: createCallExpression(`_push`, [
createTemplateLiteral([
`foo`,
createCallExpression(`_renderAttr`, ['id', 'foo']),
`bar`
])
])
}),
{ ssr: true, mode: 'module' }
)
expect(code).toMatchInlineSnapshot(`
"
export function ssrRender(_ctx, _push, _parent) {
_push(\`foo\${_renderAttr(id, foo)}bar\`)
}"
`)
})
describe('IfStatement', () => {
test('if', () => {
const { code } = generate(
createRoot({
codegenNode: createBlockStatement([
createIfStatement(
createSimpleExpression('foo', false),
createBlockStatement([createCallExpression(`ok`)])
)
])
}),
{ ssr: true, mode: 'module' }
)
expect(code).toMatchInlineSnapshot(`
"
export function ssrRender(_ctx, _push, _parent) {
if (foo) {
ok()
}
}"
`)
})
test('if/else', () => {
const { code } = generate(
createRoot({
codegenNode: createBlockStatement([
createIfStatement(
createSimpleExpression('foo', false),
createBlockStatement([createCallExpression(`foo`)]),
createBlockStatement([createCallExpression('bar')])
)
])
}),
{ ssr: true, mode: 'module' }
)
expect(code).toMatchInlineSnapshot(`
"
export function ssrRender(_ctx, _push, _parent) {
if (foo) {
foo()
} else {
bar()
}
}"
`)
})
test('if/else-if', () => {
const { code } = generate(
createRoot({
codegenNode: createBlockStatement([
createIfStatement(
createSimpleExpression('foo', false),
createBlockStatement([createCallExpression(`foo`)]),
createIfStatement(
createSimpleExpression('bar', false),
createBlockStatement([createCallExpression(`bar`)])
)
)
])
}),
{ ssr: true, mode: 'module' }
)
expect(code).toMatchInlineSnapshot(`
"
export function ssrRender(_ctx, _push, _parent) {
if (foo) {
foo()
} else if (bar) {
bar()
}
}"
`)
})
test('if/else-if/else', () => {
const { code } = generate(
createRoot({
codegenNode: createBlockStatement([
createIfStatement(
createSimpleExpression('foo', false),
createBlockStatement([createCallExpression(`foo`)]),
createIfStatement(
createSimpleExpression('bar', false),
createBlockStatement([createCallExpression(`bar`)]),
createBlockStatement([createCallExpression('baz')])
)
)
])
}),
{ ssr: true, mode: 'module' }
)
expect(code).toMatchInlineSnapshot(`
"
export function ssrRender(_ctx, _push, _parent) {
if (foo) {
foo()
} else if (bar) {
bar()
} else {
baz()
}
}"
`)
})
})
test('AssignmentExpression', () => {
const { code } = generate(
createRoot({
codegenNode: createAssignmentExpression(
createSimpleExpression(`foo`, false),
createSimpleExpression(`bar`, false)
)
})
)
expect(code).toMatchInlineSnapshot(`
"
return function render(_ctx, _cache) {
with (_ctx) {
return foo = bar
}
}"
`)
})
describe('VNodeCall', () => {
function genCode(node: VNodeCall) {
return generate(
createRoot({
codegenNode: node
})
).code.match(/with \(_ctx\) \{\s+([^]+)\s+\}\s+\}$/)![1]
}
const mockProps = createObjectExpression([
createObjectProperty(`foo`, createSimpleExpression(`bar`, true))
])
const mockChildren = createCompoundExpression(['children'])
const mockDirs = createArrayExpression([
createArrayExpression([`foo`, createSimpleExpression(`bar`, false)])
]) as DirectiveArguments
test('tag only', () => {
expect(genCode(createVNodeCall(null, `"div"`))).toMatchInlineSnapshot(`
"return _createVNode(\\"div\\")
"
`)
expect(genCode(createVNodeCall(null, FRAGMENT))).toMatchInlineSnapshot(`
"return _createVNode(_Fragment)
"
`)
})
test('with props', () => {
expect(genCode(createVNodeCall(null, `"div"`, mockProps)))
.toMatchInlineSnapshot(`
"return _createVNode(\\"div\\", { foo: \\"bar\\" })
"
`)
})
test('with children, no props', () => {
expect(genCode(createVNodeCall(null, `"div"`, undefined, mockChildren)))
.toMatchInlineSnapshot(`
"return _createVNode(\\"div\\", null, children)
"
`)
})
test('with children + props', () => {
expect(genCode(createVNodeCall(null, `"div"`, mockProps, mockChildren)))
.toMatchInlineSnapshot(`
"return _createVNode(\\"div\\", { foo: \\"bar\\" }, children)
"
`)
})
test('with patchFlag and no children/props', () => {
expect(genCode(createVNodeCall(null, `"div"`, undefined, undefined, '1')))
.toMatchInlineSnapshot(`
"return _createVNode(\\"div\\", null, null, 1)
"
`)
})
test('as block', () => {
expect(
genCode(
createVNodeCall(
null,
`"div"`,
mockProps,
mockChildren,
undefined,
undefined,
undefined,
true
)
)
).toMatchInlineSnapshot(`
"return (_openBlock(), _createBlock(\\"div\\", { foo: \\"bar\\" }, children))
"
`)
})
test('as for block', () => {
expect(
genCode(
createVNodeCall(
null,
`"div"`,
mockProps,
mockChildren,
undefined,
undefined,
undefined,
true,
true
)
)
).toMatchInlineSnapshot(`
"return (_openBlock(true), _createBlock(\\"div\\", { foo: \\"bar\\" }, children))
"
`)
})
test('with directives', () => {
expect(
genCode(
createVNodeCall(
null,
`"div"`,
mockProps,
mockChildren,
undefined,
undefined,
mockDirs
)
)
).toMatchInlineSnapshot(`
"return _withDirectives(_createVNode(\\"div\\", { foo: \\"bar\\" }, children), [
[foo, bar]
])
"
`)
})
test('block + directives', () => {
expect(
genCode(
createVNodeCall(
null,
`"div"`,
mockProps,
mockChildren,
undefined,
undefined,
mockDirs,
true
)
)
).toMatchInlineSnapshot(`
"return _withDirectives((_openBlock(), _createBlock(\\"div\\", { foo: \\"bar\\" }, children)), [
[foo, bar]
])
"
`)
})
})
})
| packages/compiler-core/__tests__/codegen.spec.ts | 0 | https://github.com/vuejs/core/commit/c463a71bb31f01da55927424533e2ece3a3c4efe | [
0.00018146653019357473,
0.000172657091752626,
0.00016481222701258957,
0.0001728861388983205,
0.000003490342351142317
]
|
{
"id": 2,
"code_window": [
" parentComponent,\n",
" parentSuspense,\n",
" optimized\n",
" )\n",
" }\n",
" ;(target as TeleportTargetElement)._lpa = nextSibling(\n",
" vnode.targetAnchor as Node\n",
" )\n",
" }\n",
" }\n",
" return vnode.anchor && nextSibling(vnode.anchor as Node)\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ;(target as TeleportTargetElement)._lpa =\n",
" vnode.targetAnchor && nextSibling(vnode.targetAnchor as Node)\n"
],
"file_path": "packages/runtime-core/src/components/Teleport.ts",
"type": "replace",
"edit_start_line_idx": 316
} | import { ObjectDirective } from '@vue/runtime-core'
interface VShowElement extends HTMLElement {
// _vod = vue original display
_vod: string
}
export const vShow: ObjectDirective<VShowElement> = {
beforeMount(el, { value }, { transition }) {
el._vod = el.style.display === 'none' ? '' : el.style.display
if (transition && value) {
transition.beforeEnter(el)
} else {
setDisplay(el, value)
}
},
mounted(el, { value }, { transition }) {
if (transition && value) {
transition.enter(el)
}
},
updated(el, { value, oldValue }, { transition }) {
if (!value === !oldValue) return
if (transition) {
if (value) {
transition.beforeEnter(el)
setDisplay(el, true)
transition.enter(el)
} else {
transition.leave(el, () => {
setDisplay(el, false)
})
}
} else {
setDisplay(el, value)
}
},
beforeUnmount(el) {
setDisplay(el, true)
}
}
if (__NODE_JS__) {
vShow.getSSRProps = ({ value }) => {
if (!value) {
return { style: { display: 'none' } }
}
}
}
function setDisplay(el: VShowElement, value: unknown): void {
el.style.display = value ? el._vod : 'none'
}
| packages/runtime-dom/src/directives/vShow.ts | 0 | https://github.com/vuejs/core/commit/c463a71bb31f01da55927424533e2ece3a3c4efe | [
0.00017599677084945142,
0.0001727595372358337,
0.0001694289967417717,
0.00017363480583298951,
0.0000023884003894636407
]
|
{
"id": 0,
"code_window": [
"\tariaLabel?: string;\n",
"\tgetKeyBinding?: (action: IAction) => ResolvedKeybinding;\n",
"\tactionRunner?: IActionRunner;\n",
"}\n",
"\n",
"/**\n",
" * A widget that combines an action bar for primary actions and a dropdown for secondary actions.\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\ttoggleMenuTitle?: string;\n"
],
"file_path": "src/vs/base/browser/ui/toolbar/toolbar.ts",
"type": "add",
"edit_start_line_idx": 24
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as DOM from 'vs/base/browser/dom';
import { renderMarkdown } from 'vs/base/browser/htmlContentRenderer';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import { Separator } from 'vs/base/browser/ui/actionbar/actionbar';
import { alert as ariaAlert } from 'vs/base/browser/ui/aria/aria';
import { Button } from 'vs/base/browser/ui/button/button';
import { Checkbox } from 'vs/base/browser/ui/checkbox/checkbox';
import { InputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { SelectBox } from 'vs/base/browser/ui/selectBox/selectBox';
import { ToolBar } from 'vs/base/browser/ui/toolbar/toolbar';
import { Action, IAction } from 'vs/base/common/actions';
import * as arrays from 'vs/base/common/arrays';
import { Color, RGBA } from 'vs/base/common/color';
import { onUnexpectedError } from 'vs/base/common/errors';
import { Emitter, Event } from 'vs/base/common/event';
import { KeyCode } from 'vs/base/common/keyCodes';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import { escapeRegExpCharacters, startsWith } from 'vs/base/common/strings';
import { URI } from 'vs/base/common/uri';
import { TPromise } from 'vs/base/common/winjs.base';
import { IAccessibilityProvider, IDataSource, IFilter, IRenderer as ITreeRenderer, ITree, ITreeConfiguration } from 'vs/base/parts/tree/browser/tree';
import { DefaultTreestyler } from 'vs/base/parts/tree/browser/treeDefaults';
import { Tree } from 'vs/base/parts/tree/browser/treeImpl';
import { localize } from 'vs/nls';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { WorkbenchTreeController } from 'vs/platform/list/browser/listService';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { editorBackground, errorForeground, focusBorder, foreground, inputValidationErrorBackground, inputValidationErrorForeground, inputValidationErrorBorder } from 'vs/platform/theme/common/colorRegistry';
import { attachButtonStyler, attachInputBoxStyler, attachSelectBoxStyler, attachStyler } from 'vs/platform/theme/common/styler';
import { ICssStyleCollector, ITheme, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { ITOCEntry } from 'vs/workbench/parts/preferences/browser/settingsLayout';
import { ISettingsEditorViewState, isExcludeSetting, SettingsTreeElement, SettingsTreeGroupElement, SettingsTreeNewExtensionsElement, settingKeyToDisplayFormat, SettingsTreeSettingElement } from 'vs/workbench/parts/preferences/browser/settingsTreeModels';
import { ExcludeSettingWidget, IExcludeDataItem, settingsHeaderForeground, settingsNumberInputBackground, settingsNumberInputBorder, settingsNumberInputForeground, settingsSelectBackground, settingsSelectBorder, settingsSelectListBorder, settingsSelectForeground, settingsTextInputBackground, settingsTextInputBorder, settingsTextInputForeground } from 'vs/workbench/parts/preferences/browser/settingsWidgets';
import { ISetting, ISettingsGroup } from 'vs/workbench/services/preferences/common/preferences';
const $ = DOM.$;
function getExcludeDisplayValue(element: SettingsTreeSettingElement): IExcludeDataItem[] {
const data = element.isConfigured ?
{ ...element.defaultValue, ...element.scopeValue } :
element.defaultValue;
return Object.keys(data)
.filter(key => !!data[key])
.map(key => {
const value = data[key];
const sibling = typeof value === 'boolean' ? undefined : value.when;
return {
id: key,
pattern: key,
sibling
};
});
}
export function resolveSettingsTree(tocData: ITOCEntry, coreSettingsGroups: ISettingsGroup[]): { tree: ITOCEntry, leftoverSettings: Set<ISetting> } {
const allSettings = getFlatSettings(coreSettingsGroups);
return {
tree: _resolveSettingsTree(tocData, allSettings),
leftoverSettings: allSettings
};
}
export function resolveExtensionsSettings(groups: ISettingsGroup[]): ITOCEntry {
const settingsGroupToEntry = (group: ISettingsGroup) => {
const flatSettings = arrays.flatten(
group.sections.map(section => section.settings));
return {
id: group.id,
label: group.title,
settings: flatSettings
};
};
const extGroups = groups
.sort((a, b) => a.title.localeCompare(b.title))
.map(g => settingsGroupToEntry(g));
return {
id: 'extensions',
label: localize('extensions', "Extensions"),
children: extGroups
};
}
function _resolveSettingsTree(tocData: ITOCEntry, allSettings: Set<ISetting>): ITOCEntry {
let children: ITOCEntry[];
if (tocData.children) {
children = tocData.children
.map(child => _resolveSettingsTree(child, allSettings))
.filter(child => (child.children && child.children.length) || (child.settings && child.settings.length));
}
let settings: ISetting[];
if (tocData.settings) {
settings = arrays.flatten(tocData.settings.map(pattern => getMatchingSettings(allSettings, <string>pattern)));
}
if (!children && !settings) {
return null;
}
return {
id: tocData.id,
label: tocData.label,
children,
settings
};
}
function getMatchingSettings(allSettings: Set<ISetting>, pattern: string): ISetting[] {
const result: ISetting[] = [];
allSettings.forEach(s => {
if (settingMatches(s, pattern)) {
result.push(s);
allSettings.delete(s);
}
});
return result.sort((a, b) => a.key.localeCompare(b.key));
}
const settingPatternCache = new Map<string, RegExp>();
function createSettingMatchRegExp(pattern: string): RegExp {
pattern = escapeRegExpCharacters(pattern)
.replace(/\\\*/g, '.*');
return new RegExp(`^${pattern}`, 'i');
}
function settingMatches(s: ISetting, pattern: string): boolean {
let regExp = settingPatternCache.get(pattern);
if (!regExp) {
regExp = createSettingMatchRegExp(pattern);
settingPatternCache.set(pattern, regExp);
}
return regExp.test(s.key);
}
function getFlatSettings(settingsGroups: ISettingsGroup[]) {
const result: Set<ISetting> = new Set();
for (let group of settingsGroups) {
for (let section of group.sections) {
for (let s of section.settings) {
if (!s.overrides || !s.overrides.length) {
result.add(s);
}
}
}
}
return result;
}
export class SettingsDataSource implements IDataSource {
getId(tree: ITree, element: SettingsTreeElement): string {
return element.id;
}
hasChildren(tree: ITree, element: SettingsTreeElement): boolean {
if (element instanceof SettingsTreeGroupElement) {
return true;
}
return false;
}
getChildren(tree: ITree, element: SettingsTreeElement): TPromise<any> {
return TPromise.as(this._getChildren(element));
}
private _getChildren(element: SettingsTreeElement): SettingsTreeElement[] {
if (element instanceof SettingsTreeGroupElement) {
return element.children;
} else {
// No children...
return null;
}
}
getParent(tree: ITree, element: SettingsTreeElement): TPromise<any> {
return TPromise.wrap(element && element.parent);
}
shouldAutoexpand(): boolean {
return true;
}
}
export class SimplePagedDataSource implements IDataSource {
private static readonly SETTINGS_PER_PAGE = 30;
private static readonly BUFFER = 5;
private loadedToIndex: number;
constructor(private realDataSource: IDataSource) {
this.reset();
}
reset(): void {
this.loadedToIndex = SimplePagedDataSource.SETTINGS_PER_PAGE * 2;
}
pageTo(index: number, top = false): boolean {
const buffer = top ? SimplePagedDataSource.SETTINGS_PER_PAGE : SimplePagedDataSource.BUFFER;
if (index > this.loadedToIndex - buffer) {
this.loadedToIndex = (Math.ceil(index / SimplePagedDataSource.SETTINGS_PER_PAGE) + 1) * SimplePagedDataSource.SETTINGS_PER_PAGE;
return true;
} else {
return false;
}
}
getId(tree: ITree, element: any): string {
return this.realDataSource.getId(tree, element);
}
hasChildren(tree: ITree, element: any): boolean {
return this.realDataSource.hasChildren(tree, element);
}
getChildren(tree: ITree, element: SettingsTreeGroupElement): TPromise<any> {
return this.realDataSource.getChildren(tree, element).then(realChildren => {
return this._getChildren(realChildren);
});
}
_getChildren(realChildren: SettingsTreeElement[]): any[] {
const lastChild = realChildren[realChildren.length - 1];
if (lastChild && lastChild.index > this.loadedToIndex) {
return realChildren.filter(child => {
return child.index < this.loadedToIndex;
});
} else {
return realChildren;
}
}
getParent(tree: ITree, element: any): TPromise<any> {
return this.realDataSource.getParent(tree, element);
}
shouldAutoexpand(tree: ITree, element: any): boolean {
return this.realDataSource.shouldAutoexpand(tree, element);
}
}
interface IDisposableTemplate {
toDispose: IDisposable[];
}
interface ISettingItemTemplate<T = any> extends IDisposableTemplate {
onChange?: (value: T) => void;
context?: SettingsTreeSettingElement;
containerElement: HTMLElement;
categoryElement: HTMLElement;
labelElement: HTMLElement;
descriptionElement: HTMLElement;
controlElement: HTMLElement;
deprecationWarningElement: HTMLElement;
otherOverridesElement: HTMLElement;
toolbar: ToolBar;
}
interface ISettingBoolItemTemplate extends ISettingItemTemplate<boolean> {
checkbox: Checkbox;
}
interface ISettingTextItemTemplate extends ISettingItemTemplate<string> {
inputBox: InputBox;
validationErrorMessageElement: HTMLElement;
}
type ISettingNumberItemTemplate = ISettingTextItemTemplate;
interface ISettingEnumItemTemplate extends ISettingItemTemplate<number> {
selectBox: SelectBox;
enumDescriptionElement: HTMLElement;
}
interface ISettingComplexItemTemplate extends ISettingItemTemplate<void> {
button: Button;
}
interface ISettingExcludeItemTemplate extends ISettingItemTemplate<void> {
excludeWidget: ExcludeSettingWidget;
}
interface ISettingNewExtensionsTemplate extends IDisposableTemplate {
button: Button;
context?: SettingsTreeNewExtensionsElement;
}
interface IGroupTitleTemplate extends IDisposableTemplate {
context?: SettingsTreeGroupElement;
parent: HTMLElement;
}
const SETTINGS_TEXT_TEMPLATE_ID = 'settings.text.template';
const SETTINGS_NUMBER_TEMPLATE_ID = 'settings.number.template';
const SETTINGS_ENUM_TEMPLATE_ID = 'settings.enum.template';
const SETTINGS_BOOL_TEMPLATE_ID = 'settings.bool.template';
const SETTINGS_EXCLUDE_TEMPLATE_ID = 'settings.exclude.template';
const SETTINGS_COMPLEX_TEMPLATE_ID = 'settings.complex.template';
const SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID = 'settings.newExtensions.template';
const SETTINGS_GROUP_ELEMENT_TEMPLATE_ID = 'settings.group.template';
export interface ISettingChangeEvent {
key: string;
value: any; // undefined => reset/unconfigure
}
export interface ISettingLinkClickEvent {
source: SettingsTreeSettingElement;
targetKey: string;
}
export class SettingsRenderer implements ITreeRenderer {
public static readonly CONTROL_CLASS = 'setting-control-focus-target';
public static readonly CONTROL_SELECTOR = '.' + SettingsRenderer.CONTROL_CLASS;
public static readonly SETTING_KEY_ATTR = 'data-key';
private readonly _onDidChangeSetting: Emitter<ISettingChangeEvent> = new Emitter<ISettingChangeEvent>();
public readonly onDidChangeSetting: Event<ISettingChangeEvent> = this._onDidChangeSetting.event;
private readonly _onDidOpenSettings: Emitter<string> = new Emitter<string>();
public readonly onDidOpenSettings: Event<string> = this._onDidOpenSettings.event;
private readonly _onDidClickSettingLink: Emitter<ISettingLinkClickEvent> = new Emitter<ISettingLinkClickEvent>();
public readonly onDidClickSettingLink: Event<ISettingLinkClickEvent> = this._onDidClickSettingLink.event;
private readonly _onDidFocusSetting: Emitter<SettingsTreeSettingElement> = new Emitter<SettingsTreeSettingElement>();
public readonly onDidFocusSetting: Event<SettingsTreeSettingElement> = this._onDidFocusSetting.event;
private descriptionMeasureContainer: HTMLElement;
private longestSingleLineDescription = 0;
private rowHeightCache = new Map<string, number>();
private lastRenderedWidth: number;
private settingActions: IAction[];
constructor(
_measureContainer: HTMLElement,
@IThemeService private themeService: IThemeService,
@IContextViewService private contextViewService: IContextViewService,
@IOpenerService private readonly openerService: IOpenerService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@ICommandService private readonly commandService: ICommandService,
@IContextMenuService private contextMenuService: IContextMenuService
) {
this.descriptionMeasureContainer = $('.setting-item-description');
DOM.append(_measureContainer,
$('.setting-measure-container.monaco-tree-row', undefined,
$('.setting-item', undefined,
this.descriptionMeasureContainer)));
this.settingActions = [
new Action('settings.resetSetting', localize('resetSettingLabel', "Reset Setting"), undefined, undefined, (context: SettingsTreeSettingElement) => {
if (context) {
this._onDidChangeSetting.fire({ key: context.setting.key, value: undefined });
}
return TPromise.wrap(null);
}),
new Separator(),
this.instantiationService.createInstance(CopySettingIdAction),
this.instantiationService.createInstance(CopySettingAsJSONAction),
];
}
showContextMenu(element: SettingsTreeSettingElement, settingDOMElement: HTMLElement): void {
const toolbarElement: HTMLElement = settingDOMElement.querySelector('.toolbar-toggle-more');
if (toolbarElement) {
this.contextMenuService.showContextMenu({
getActions: () => TPromise.wrap(this.settingActions),
getAnchor: () => toolbarElement,
getActionsContext: () => element
});
}
}
updateWidth(width: number): void {
if (this.lastRenderedWidth !== width) {
this.rowHeightCache = new Map<string, number>();
}
this.longestSingleLineDescription = 0;
this.lastRenderedWidth = width;
}
getHeight(tree: ITree, element: SettingsTreeElement): number {
if (this.rowHeightCache.has(element.id) && !(element instanceof SettingsTreeSettingElement && isExcludeSetting(element.setting))) {
return this.rowHeightCache.get(element.id);
}
const h = this._getHeight(tree, element);
this.rowHeightCache.set(element.id, h);
return h;
}
_getHeight(tree: ITree, element: SettingsTreeElement): number {
if (element instanceof SettingsTreeGroupElement) {
if (element.isFirstGroup) {
return 31;
}
return 40 + (7 * element.level);
}
if (element instanceof SettingsTreeSettingElement) {
if (isExcludeSetting(element.setting)) {
return this._getExcludeSettingHeight(element);
} else {
return this.measureSettingElementHeight(tree, element);
}
}
if (element instanceof SettingsTreeNewExtensionsElement) {
return 40;
}
return 0;
}
_getExcludeSettingHeight(element: SettingsTreeSettingElement): number {
const displayValue = getExcludeDisplayValue(element);
return (displayValue.length + 1) * 22 + 66 + this.measureSettingDescription(element);
}
private measureSettingElementHeight(tree: ITree, element: SettingsTreeSettingElement): number {
let heightExcludingDescription = 86;
if (element.valueType === 'boolean') {
heightExcludingDescription = 60;
}
return heightExcludingDescription + this.measureSettingDescription(element);
}
private measureSettingDescription(element: SettingsTreeSettingElement): number {
if (element.description.length < this.longestSingleLineDescription * .8) {
// Most setting descriptions are one short line, so try to avoid measuring them.
// If the description is less than 80% of the longest single line description, assume this will also render to be one line.
return 18;
}
const boolMeasureClass = 'measure-bool-description';
if (element.valueType === 'boolean') {
this.descriptionMeasureContainer.classList.add(boolMeasureClass);
} else if (this.descriptionMeasureContainer.classList.contains(boolMeasureClass)) {
this.descriptionMeasureContainer.classList.remove(boolMeasureClass);
}
const shouldRenderMarkdown = element.setting.descriptionIsMarkdown && element.description.indexOf('\n- ') >= 0;
while (this.descriptionMeasureContainer.firstChild) {
this.descriptionMeasureContainer.removeChild(this.descriptionMeasureContainer.firstChild);
}
if (shouldRenderMarkdown) {
const text = fixSettingLinks(element.description);
const rendered = renderMarkdown({ value: text });
rendered.classList.add('setting-item-description-markdown');
this.descriptionMeasureContainer.appendChild(rendered);
return this.descriptionMeasureContainer.offsetHeight;
} else {
// Remove markdown links, setting links, backticks
const measureText = element.setting.descriptionIsMarkdown ?
fixSettingLinks(element.description)
.replace(/\[(.*)\]\(.*\)/g, '$1')
.replace(/`([^`]*)`/g, '$1') :
element.description;
this.descriptionMeasureContainer.innerText = measureText;
const h = this.descriptionMeasureContainer.offsetHeight;
if (h < 20 && measureText.length > this.longestSingleLineDescription) {
this.longestSingleLineDescription = measureText.length;
}
return h;
}
}
getTemplateId(tree: ITree, element: SettingsTreeElement): string {
if (element instanceof SettingsTreeGroupElement) {
return SETTINGS_GROUP_ELEMENT_TEMPLATE_ID;
}
if (element instanceof SettingsTreeSettingElement) {
if (element.valueType === 'boolean') {
return SETTINGS_BOOL_TEMPLATE_ID;
}
if (element.valueType === 'integer' || element.valueType === 'number' || element.valueType === 'nullable-integer' || element.valueType === 'nullable-number') {
return SETTINGS_NUMBER_TEMPLATE_ID;
}
if (element.valueType === 'string') {
return SETTINGS_TEXT_TEMPLATE_ID;
}
if (element.valueType === 'enum') {
return SETTINGS_ENUM_TEMPLATE_ID;
}
if (element.valueType === 'exclude') {
return SETTINGS_EXCLUDE_TEMPLATE_ID;
}
return SETTINGS_COMPLEX_TEMPLATE_ID;
}
if (element instanceof SettingsTreeNewExtensionsElement) {
return SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID;
}
return '';
}
renderTemplate(tree: ITree, templateId: string, container: HTMLElement) {
if (templateId === SETTINGS_GROUP_ELEMENT_TEMPLATE_ID) {
return this.renderGroupTitleTemplate(container);
}
if (templateId === SETTINGS_TEXT_TEMPLATE_ID) {
return this.renderSettingTextTemplate(tree, container);
}
if (templateId === SETTINGS_NUMBER_TEMPLATE_ID) {
return this.renderSettingNumberTemplate(tree, container);
}
if (templateId === SETTINGS_BOOL_TEMPLATE_ID) {
return this.renderSettingBoolTemplate(tree, container);
}
if (templateId === SETTINGS_ENUM_TEMPLATE_ID) {
return this.renderSettingEnumTemplate(tree, container);
}
if (templateId === SETTINGS_EXCLUDE_TEMPLATE_ID) {
return this.renderSettingExcludeTemplate(tree, container);
}
if (templateId === SETTINGS_COMPLEX_TEMPLATE_ID) {
return this.renderSettingComplexTemplate(tree, container);
}
if (templateId === SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID) {
return this.renderNewExtensionsTemplate(container);
}
return null;
}
private renderGroupTitleTemplate(container: HTMLElement): IGroupTitleTemplate {
DOM.addClass(container, 'group-title');
const toDispose = [];
const template: IGroupTitleTemplate = {
parent: container,
toDispose
};
return template;
}
private renderCommonTemplate(tree: ITree, container: HTMLElement, typeClass: string): ISettingItemTemplate {
DOM.addClass(container, 'setting-item');
DOM.addClass(container, 'setting-item-' + typeClass);
const titleElement = DOM.append(container, $('.setting-item-title'));
const labelCategoryContainer = DOM.append(titleElement, $('.setting-item-cat-label-container'));
const categoryElement = DOM.append(labelCategoryContainer, $('span.setting-item-category'));
const labelElement = DOM.append(labelCategoryContainer, $('span.setting-item-label'));
const otherOverridesElement = DOM.append(titleElement, $('span.setting-item-overrides'));
const descriptionElement = DOM.append(container, $('.setting-item-description'));
const modifiedIndicatorElement = DOM.append(container, $('.setting-item-modified-indicator'));
modifiedIndicatorElement.title = localize('modified', "Modified");
const valueElement = DOM.append(container, $('.setting-item-value'));
const controlElement = DOM.append(valueElement, $('div.setting-item-control'));
const deprecationWarningElement = DOM.append(container, $('.setting-item-deprecation-message'));
const toDispose = [];
const toolbar = this.renderSettingToolbar(container);
const template: ISettingItemTemplate = {
toDispose,
containerElement: container,
categoryElement,
labelElement,
descriptionElement,
controlElement,
deprecationWarningElement,
otherOverridesElement,
toolbar
};
// Prevent clicks from being handled by list
toDispose.push(DOM.addDisposableListener(controlElement, 'mousedown', (e: IMouseEvent) => e.stopPropagation()));
toDispose.push(DOM.addStandardDisposableListener(valueElement, 'keydown', (e: StandardKeyboardEvent) => {
if (e.keyCode === KeyCode.Escape) {
tree.domFocus();
e.browserEvent.stopPropagation();
}
}));
return template;
}
private addSettingElementFocusHandler(template: ISettingItemTemplate): void {
const focusTracker = DOM.trackFocus(template.containerElement);
template.toDispose.push(focusTracker);
focusTracker.onDidBlur(() => {
if (template.containerElement.classList.contains('focused')) {
template.containerElement.classList.remove('focused');
}
});
focusTracker.onDidFocus(() => {
template.containerElement.classList.add('focused');
if (template.context) {
this._onDidFocusSetting.fire(template.context);
}
});
}
private renderSettingTextTemplate(tree: ITree, container: HTMLElement, type = 'text'): ISettingTextItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'text');
const validationErrorMessageElement = DOM.append(container, $('.setting-item-validation-message'));
const inputBox = new InputBox(common.controlElement, this.contextViewService);
common.toDispose.push(inputBox);
common.toDispose.push(attachInputBoxStyler(inputBox, this.themeService, {
inputBackground: settingsTextInputBackground,
inputForeground: settingsTextInputForeground,
inputBorder: settingsTextInputBorder
}));
common.toDispose.push(
inputBox.onDidChange(e => {
if (template.onChange) {
template.onChange(e);
}
}));
common.toDispose.push(inputBox);
inputBox.inputElement.classList.add(SettingsRenderer.CONTROL_CLASS);
const template: ISettingTextItemTemplate = {
...common,
inputBox,
validationErrorMessageElement
};
this.addSettingElementFocusHandler(template);
return template;
}
private renderSettingNumberTemplate(tree: ITree, container: HTMLElement): ISettingNumberItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'number');
const validationErrorMessageElement = DOM.append(container, $('.setting-item-validation-message'));
const inputBox = new InputBox(common.controlElement, this.contextViewService, { type: 'number' });
common.toDispose.push(inputBox);
common.toDispose.push(attachInputBoxStyler(inputBox, this.themeService, {
inputBackground: settingsNumberInputBackground,
inputForeground: settingsNumberInputForeground,
inputBorder: settingsNumberInputBorder
}));
common.toDispose.push(
inputBox.onDidChange(e => {
if (template.onChange) {
template.onChange(e);
}
}));
common.toDispose.push(inputBox);
inputBox.inputElement.classList.add(SettingsRenderer.CONTROL_CLASS);
const template: ISettingNumberItemTemplate = {
...common,
inputBox,
validationErrorMessageElement
};
this.addSettingElementFocusHandler(template);
return template;
}
private renderSettingToolbar(container: HTMLElement): ToolBar {
const toolbar = new ToolBar(container, this.contextMenuService, {});
toolbar.setActions([], this.settingActions)();
const button = container.querySelector('.toolbar-toggle-more');
if (button) {
(<HTMLElement>button).tabIndex = -1;
}
return toolbar;
}
private renderSettingBoolTemplate(tree: ITree, container: HTMLElement): ISettingBoolItemTemplate {
DOM.addClass(container, 'setting-item');
DOM.addClass(container, 'setting-item-bool');
const titleElement = DOM.append(container, $('.setting-item-title'));
const categoryElement = DOM.append(titleElement, $('span.setting-item-category'));
const labelElement = DOM.append(titleElement, $('span.setting-item-label'));
const otherOverridesElement = DOM.append(titleElement, $('span.setting-item-overrides'));
const descriptionAndValueElement = DOM.append(container, $('.setting-item-value-description'));
const controlElement = DOM.append(descriptionAndValueElement, $('.setting-item-bool-control'));
const descriptionElement = DOM.append(descriptionAndValueElement, $('.setting-item-description'));
const modifiedIndicatorElement = DOM.append(container, $('.setting-item-modified-indicator'));
modifiedIndicatorElement.title = localize('modified', "Modified");
const deprecationWarningElement = DOM.append(container, $('.setting-item-deprecation-message'));
const toDispose = [];
const checkbox = new Checkbox({ actionClassName: 'setting-value-checkbox', isChecked: true, title: '', inputActiveOptionBorder: null });
controlElement.appendChild(checkbox.domNode);
toDispose.push(checkbox);
toDispose.push(checkbox.onChange(() => {
if (template.onChange) {
template.onChange(checkbox.checked);
}
}));
// Need to listen for mouse clicks on description and toggle checkbox - use target ID for safety
// Also have to ignore embedded links - too buried to stop propagation
toDispose.push(DOM.addDisposableListener(descriptionElement, DOM.EventType.MOUSE_DOWN, (e) => {
const targetElement = <HTMLElement>e.toElement;
const targetId = descriptionElement.getAttribute('checkbox_label_target_id');
// Make sure we are not a link and the target ID matches
// Toggle target checkbox
if (targetElement.tagName.toLowerCase() !== 'a' && targetId === template.checkbox.domNode.id) {
template.checkbox.checked = template.checkbox.checked ? false : true;
template.onChange(checkbox.checked);
}
DOM.EventHelper.stop(e);
}));
checkbox.domNode.classList.add(SettingsRenderer.CONTROL_CLASS);
const toolbar = this.renderSettingToolbar(container);
toDispose.push(toolbar);
const template: ISettingBoolItemTemplate = {
toDispose,
containerElement: container,
categoryElement,
labelElement,
controlElement,
checkbox,
descriptionElement,
deprecationWarningElement,
otherOverridesElement,
toolbar
};
this.addSettingElementFocusHandler(template);
// Prevent clicks from being handled by list
toDispose.push(DOM.addDisposableListener(controlElement, 'mousedown', (e: IMouseEvent) => e.stopPropagation()));
toDispose.push(DOM.addStandardDisposableListener(controlElement, 'keydown', (e: StandardKeyboardEvent) => {
if (e.keyCode === KeyCode.Escape) {
tree.domFocus();
e.browserEvent.stopPropagation();
}
}));
return template;
}
public cancelSuggesters() {
this.contextViewService.hideContextView();
}
private renderSettingEnumTemplate(tree: ITree, container: HTMLElement): ISettingEnumItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'enum');
const selectBox = new SelectBox([], undefined, this.contextViewService, undefined, {
hasDetails: true
});
common.toDispose.push(selectBox);
common.toDispose.push(attachSelectBoxStyler(selectBox, this.themeService, {
selectBackground: settingsSelectBackground,
selectForeground: settingsSelectForeground,
selectBorder: settingsSelectBorder,
selectListBorder: settingsSelectListBorder
}));
selectBox.render(common.controlElement);
const selectElement = common.controlElement.querySelector('select');
if (selectElement) {
selectElement.classList.add(SettingsRenderer.CONTROL_CLASS);
}
common.toDispose.push(
selectBox.onDidSelect(e => {
if (template.onChange) {
template.onChange(e.index);
}
}));
const enumDescriptionElement = common.containerElement.insertBefore($('.setting-item-enumDescription'), common.descriptionElement.nextSibling);
const template: ISettingEnumItemTemplate = {
...common,
selectBox,
enumDescriptionElement
};
this.addSettingElementFocusHandler(template);
return template;
}
private renderSettingExcludeTemplate(tree: ITree, container: HTMLElement): ISettingExcludeItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'exclude');
const excludeWidget = this.instantiationService.createInstance(ExcludeSettingWidget, common.controlElement);
excludeWidget.domNode.classList.add(SettingsRenderer.CONTROL_CLASS);
common.toDispose.push(excludeWidget);
const template: ISettingExcludeItemTemplate = {
...common,
excludeWidget
};
this.addSettingElementFocusHandler(template);
common.toDispose.push(excludeWidget.onDidChangeExclude(e => {
if (template.context) {
let newValue = { ...template.context.scopeValue };
// first delete the existing entry, if present
if (e.originalPattern) {
if (e.originalPattern in template.context.defaultValue) {
// delete a default by overriding it
newValue[e.originalPattern] = false;
} else {
delete newValue[e.originalPattern];
}
}
// then add the new or updated entry, if present
if (e.pattern) {
if (e.pattern in template.context.defaultValue && !e.sibling) {
// add a default by deleting its override
delete newValue[e.pattern];
} else {
newValue[e.pattern] = e.sibling ? { when: e.sibling } : true;
}
}
const sortKeys = (obj) => {
const keyArray = Object.keys(obj)
.map(key => ({ key, val: obj[key] }))
.sort((a, b) => a.key.localeCompare(b.key));
const retVal = {};
keyArray.forEach(pair => {
retVal[pair.key] = pair.val;
});
return retVal;
};
this._onDidChangeSetting.fire({
key: template.context.setting.key,
value: Object.keys(newValue).length === 0 ? undefined : sortKeys(newValue)
});
}
}));
return template;
}
private renderSettingComplexTemplate(tree: ITree, container: HTMLElement): ISettingComplexItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'complex');
const openSettingsButton = new Button(common.controlElement, { title: true, buttonBackground: null, buttonHoverBackground: null });
common.toDispose.push(openSettingsButton);
common.toDispose.push(openSettingsButton.onDidClick(() => template.onChange(null)));
openSettingsButton.label = localize('editInSettingsJson', "Edit in settings.json");
openSettingsButton.element.classList.add('edit-in-settings-button');
common.toDispose.push(attachButtonStyler(openSettingsButton, this.themeService, {
buttonBackground: Color.transparent.toString(),
buttonHoverBackground: Color.transparent.toString(),
buttonForeground: 'foreground'
}));
const template: ISettingComplexItemTemplate = {
...common,
button: openSettingsButton
};
this.addSettingElementFocusHandler(template);
return template;
}
private renderNewExtensionsTemplate(container: HTMLElement): ISettingNewExtensionsTemplate {
const toDispose = [];
container.classList.add('setting-item-new-extensions');
const button = new Button(container, { title: true, buttonBackground: null, buttonHoverBackground: null });
toDispose.push(button);
toDispose.push(button.onDidClick(() => {
if (template.context) {
this.commandService.executeCommand('workbench.extensions.action.showExtensionsWithIds', template.context.extensionIds);
}
}));
button.label = localize('newExtensionsButtonLabel', "Show matching extensions");
button.element.classList.add('settings-new-extensions-button');
toDispose.push(attachButtonStyler(button, this.themeService));
const template: ISettingNewExtensionsTemplate = {
button,
toDispose
};
// this.addSettingElementFocusHandler(template);
return template;
}
renderElement(tree: ITree, element: SettingsTreeElement, templateId: string, template: any): void {
if (templateId === SETTINGS_GROUP_ELEMENT_TEMPLATE_ID) {
return this.renderGroupElement(<SettingsTreeGroupElement>element, template);
}
if (templateId === SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID) {
return this.renderNewExtensionsElement(<SettingsTreeNewExtensionsElement>element, template);
}
return this.renderSettingElement(tree, <SettingsTreeSettingElement>element, templateId, template);
}
private renderGroupElement(element: SettingsTreeGroupElement, template: IGroupTitleTemplate): void {
template.parent.innerHTML = '';
const labelElement = DOM.append(template.parent, $('div.settings-group-title-label'));
labelElement.classList.add(`settings-group-level-${element.level}`);
labelElement.textContent = (<SettingsTreeGroupElement>element).label;
if (element.isFirstGroup) {
labelElement.classList.add('settings-group-first');
}
}
private renderNewExtensionsElement(element: SettingsTreeNewExtensionsElement, template: ISettingNewExtensionsTemplate): void {
template.context = element;
}
public getSettingDOMElementForDOMElement(domElement: HTMLElement): HTMLElement {
const parent = DOM.findParentWithClass(domElement, 'setting-item');
if (parent) {
return parent;
}
return null;
}
public getDOMElementsForSettingKey(treeContainer: HTMLElement, key: string): NodeListOf<HTMLElement> {
return treeContainer.querySelectorAll(`[${SettingsRenderer.SETTING_KEY_ATTR}="${key}"]`);
}
public getKeyForDOMElementInSetting(element: HTMLElement): string {
const settingElement = this.getSettingDOMElementForDOMElement(element);
return settingElement && settingElement.getAttribute(SettingsRenderer.SETTING_KEY_ATTR);
}
private renderSettingElement(tree: ITree, element: SettingsTreeSettingElement, templateId: string, template: ISettingItemTemplate | ISettingBoolItemTemplate): void {
template.context = element;
template.toolbar.context = element;
const setting = element.setting;
DOM.toggleClass(template.containerElement, 'is-configured', element.isConfigured);
DOM.toggleClass(template.containerElement, 'is-expanded', true);
template.containerElement.setAttribute(SettingsRenderer.SETTING_KEY_ATTR, element.setting.key);
const titleTooltip = setting.key + (element.isConfigured ? ' - Modified' : '');
template.categoryElement.textContent = element.displayCategory && (element.displayCategory + ': ');
template.categoryElement.title = titleTooltip;
template.labelElement.textContent = element.displayLabel;
template.labelElement.title = titleTooltip;
this.renderValue(element, templateId, <ISettingItemTemplate>template);
template.descriptionElement.innerHTML = '';
if (element.setting.descriptionIsMarkdown) {
const renderedDescription = this.renderDescriptionMarkdown(element, element.description, template.toDispose);
template.descriptionElement.appendChild(renderedDescription);
} else {
template.descriptionElement.innerText = element.description;
}
const baseId = (element.displayCategory + '_' + element.displayLabel).replace(/ /g, '_').toLowerCase();
template.descriptionElement.id = baseId + '_setting_description';
if (templateId === SETTINGS_BOOL_TEMPLATE_ID) {
// Add checkbox target to description clickable and able to toggle checkbox
template.descriptionElement.setAttribute('checkbox_label_target_id', baseId + '_setting_item');
}
if (element.overriddenScopeList.length) {
let otherOverridesLabel = element.isConfigured ?
localize('alsoConfiguredIn', "Also modified in") :
localize('configuredIn', "Modified in");
template.otherOverridesElement.textContent = `(${otherOverridesLabel}: ${element.overriddenScopeList.join(', ')})`;
} else {
template.otherOverridesElement.textContent = '';
}
// Remove tree attributes - sometimes overridden by tree - should be managed there
template.containerElement.parentElement.removeAttribute('role');
template.containerElement.parentElement.removeAttribute('aria-level');
template.containerElement.parentElement.removeAttribute('aria-posinset');
template.containerElement.parentElement.removeAttribute('aria-setsize');
}
private renderDescriptionMarkdown(element: SettingsTreeSettingElement, text: string, disposeables: IDisposable[]): HTMLElement {
// Rewrite `#editor.fontSize#` to link format
text = fixSettingLinks(text);
const renderedMarkdown = renderMarkdown({ value: text }, {
actionHandler: {
callback: (content: string) => {
if (startsWith(content, '#')) {
const e: ISettingLinkClickEvent = {
source: element,
targetKey: content.substr(1)
};
this._onDidClickSettingLink.fire(e);
} else {
this.openerService.open(URI.parse(content)).then(void 0, onUnexpectedError);
}
},
disposeables
}
});
renderedMarkdown.classList.add('setting-item-description-markdown');
cleanRenderedMarkdown(renderedMarkdown);
return renderedMarkdown;
}
private renderValue(element: SettingsTreeSettingElement, templateId: string, template: ISettingItemTemplate | ISettingBoolItemTemplate): void {
const onChange = value => this._onDidChangeSetting.fire({ key: element.setting.key, value });
template.deprecationWarningElement.innerText = element.setting.deprecationMessage || '';
if (templateId === SETTINGS_ENUM_TEMPLATE_ID) {
this.renderEnum(element, <ISettingEnumItemTemplate>template, onChange);
} else if (templateId === SETTINGS_TEXT_TEMPLATE_ID) {
this.renderText(element, <ISettingTextItemTemplate>template, onChange);
} else if (templateId === SETTINGS_NUMBER_TEMPLATE_ID) {
this.renderNumber(element, <ISettingTextItemTemplate>template, onChange);
} else if (templateId === SETTINGS_BOOL_TEMPLATE_ID) {
this.renderBool(element, <ISettingBoolItemTemplate>template, onChange);
} else if (templateId === SETTINGS_EXCLUDE_TEMPLATE_ID) {
this.renderExcludeSetting(element, <ISettingExcludeItemTemplate>template);
} else if (templateId === SETTINGS_COMPLEX_TEMPLATE_ID) {
this.renderComplexSetting(element, <ISettingComplexItemTemplate>template);
}
}
private renderBool(dataElement: SettingsTreeSettingElement, template: ISettingBoolItemTemplate, onChange: (value: boolean) => void): void {
template.onChange = null;
template.checkbox.checked = dataElement.value;
template.onChange = onChange;
// Setup and add ARIA attributes
// Create id and label for control/input element - parent is wrapper div
const baseId = (dataElement.displayCategory + '_' + dataElement.displayLabel).replace(/ /g, '_').toLowerCase();
const modifiedText = dataElement.isConfigured ? 'Modified' : '';
const label = dataElement.displayCategory + ' ' + dataElement.displayLabel + ' ' + modifiedText;
// We use the parent control div for the aria-labelledby target
// Does not appear you can use the direct label on the element itself within a tree
template.checkbox.domNode.parentElement.id = baseId + '_setting_label';
template.checkbox.domNode.parentElement.setAttribute('aria-label', label);
// Labels will not be read on descendent input elements of the parent treeitem
// unless defined as role=treeitem and indirect aria-labelledby approach
template.checkbox.domNode.id = baseId + '_setting_item';
template.checkbox.domNode.setAttribute('role', 'checkbox');
template.checkbox.domNode.setAttribute('aria-labelledby', baseId + '_setting_label');
template.checkbox.domNode.setAttribute('aria-describedby', baseId + '_setting_description');
}
private renderEnum(dataElement: SettingsTreeSettingElement, template: ISettingEnumItemTemplate, onChange: (value: string) => void): void {
const displayOptions = dataElement.setting.enum
.map(String)
.map(escapeInvisibleChars);
template.selectBox.setOptions(displayOptions);
const enumDescriptions = dataElement.setting.enumDescriptions;
const enumDescriptionsAreMarkdown = dataElement.setting.enumDescriptionsAreMarkdown;
template.selectBox.setDetailsProvider(index =>
({
details: enumDescriptions && enumDescriptions[index] && (enumDescriptionsAreMarkdown ? fixSettingLinks(enumDescriptions[index], false) : enumDescriptions[index]),
isMarkdown: enumDescriptionsAreMarkdown
}));
const modifiedText = dataElement.isConfigured ? 'Modified' : '';
const label = dataElement.displayCategory + ' ' + dataElement.displayLabel + ' ' + modifiedText;
const baseId = (dataElement.displayCategory + '_' + dataElement.displayLabel).replace(/ /g, '_').toLowerCase();
template.selectBox.setAriaLabel(label);
const idx = dataElement.setting.enum.indexOf(dataElement.value);
template.onChange = null;
template.selectBox.select(idx);
template.onChange = idx => onChange(dataElement.setting.enum[idx]);
if (template.controlElement.firstElementChild) {
// SelectBox needs to have treeitem changed to combobox to read correctly within tree
template.controlElement.firstElementChild.setAttribute('role', 'combobox');
template.controlElement.firstElementChild.setAttribute('aria-describedby', baseId + '_setting_description');
}
template.enumDescriptionElement.innerHTML = '';
}
private renderText(dataElement: SettingsTreeSettingElement, template: ISettingTextItemTemplate, onChange: (value: string) => void): void {
const modifiedText = dataElement.isConfigured ? 'Modified' : '';
const label = dataElement.displayCategory + ' ' + dataElement.displayLabel + ' ' + modifiedText; template.onChange = null;
template.inputBox.value = dataElement.value;
template.onChange = value => { renderValidations(dataElement, template, false, label); onChange(value); };
// Setup and add ARIA attributes
// Create id and label for control/input element - parent is wrapper div
const baseId = (dataElement.displayCategory + '_' + dataElement.displayLabel).replace(/ /g, '_').toLowerCase();
// We use the parent control div for the aria-labelledby target
// Does not appear you can use the direct label on the element itself within a tree
template.inputBox.inputElement.parentElement.id = baseId + '_setting_label';
template.inputBox.inputElement.parentElement.setAttribute('aria-label', label);
// Labels will not be read on descendent input elements of the parent treeitem
// unless defined as role=treeitem and indirect aria-labelledby approach
template.inputBox.inputElement.id = baseId + '_setting_item';
template.inputBox.inputElement.setAttribute('role', 'textbox');
template.inputBox.inputElement.setAttribute('aria-labelledby', baseId + '_setting_label');
template.inputBox.inputElement.setAttribute('aria-describedby', baseId + '_setting_description');
renderValidations(dataElement, template, true, label);
}
private renderNumber(dataElement: SettingsTreeSettingElement, template: ISettingTextItemTemplate, onChange: (value: number) => void): void {
const modifiedText = dataElement.isConfigured ? 'Modified' : '';
const label = dataElement.displayCategory + ' ' + dataElement.displayLabel + ' number ' + modifiedText; const numParseFn = (dataElement.valueType === 'integer' || dataElement.valueType === 'nullable-integer')
? parseInt : parseFloat;
const nullNumParseFn = (dataElement.valueType === 'nullable-integer' || dataElement.valueType === 'nullable-number')
? (v => v === '' ? null : numParseFn(v)) : numParseFn;
template.onChange = null;
template.inputBox.value = dataElement.value;
template.onChange = value => { renderValidations(dataElement, template, false, label); onChange(nullNumParseFn(value)); };
// Setup and add ARIA attributes
// Create id and label for control/input element - parent is wrapper div
const baseId = (dataElement.displayCategory + '_' + dataElement.displayLabel).replace(/ /g, '_').toLowerCase();
// We use the parent control div for the aria-labelledby target
// Does not appear you can use the direct label on the element itself within a tree
template.inputBox.inputElement.parentElement.id = baseId + '_setting_label';
template.inputBox.inputElement.parentElement.setAttribute('aria-label', label);
// Labels will not be read on descendent input elements of the parent treeitem
// unless defined as role=treeitem and indirect aria-labelledby approach
template.inputBox.inputElement.id = baseId + '_setting_item';
template.inputBox.inputElement.setAttribute('role', 'textbox');
template.inputBox.inputElement.setAttribute('aria-labelledby', baseId + '_setting_label');
template.inputBox.inputElement.setAttribute('aria-describedby', baseId + '_setting_description');
renderValidations(dataElement, template, true, label);
}
private renderExcludeSetting(dataElement: SettingsTreeSettingElement, template: ISettingExcludeItemTemplate): void {
const value = getExcludeDisplayValue(dataElement);
template.excludeWidget.setValue(value);
template.context = dataElement;
}
private renderComplexSetting(dataElement: SettingsTreeSettingElement, template: ISettingComplexItemTemplate): void {
template.onChange = () => this._onDidOpenSettings.fire(dataElement.setting.key);
}
disposeTemplate(tree: ITree, templateId: string, template: IDisposableTemplate): void {
dispose(template.toDispose);
}
}
function renderValidations(dataElement: SettingsTreeSettingElement, template: ISettingTextItemTemplate, calledOnStartup: boolean, originalAriaLabel: string) {
if (dataElement.setting.validator) {
let errMsg = dataElement.setting.validator(template.inputBox.value);
if (errMsg) {
DOM.addClass(template.containerElement, 'invalid-input');
template.validationErrorMessageElement.innerText = errMsg;
let validationError = localize('validationError', "Validation Error.");
template.inputBox.inputElement.parentElement.setAttribute('aria-label', [originalAriaLabel, validationError, errMsg].join(' '));
if (!calledOnStartup) { ariaAlert(validationError + ' ' + errMsg); }
return;
} else {
template.inputBox.inputElement.parentElement.setAttribute('aria-label', originalAriaLabel);
}
}
DOM.removeClass(template.containerElement, 'invalid-input');
}
function cleanRenderedMarkdown(element: Node): void {
for (let i = 0; i < element.childNodes.length; i++) {
const child = element.childNodes.item(i);
const tagName = (<Element>child).tagName && (<Element>child).tagName.toLowerCase();
if (tagName === 'img') {
element.removeChild(child);
} else {
cleanRenderedMarkdown(child);
}
}
}
function fixSettingLinks(text: string, linkify = true): string {
return text.replace(/`#([^#]*)#`/g, (match, settingKey) => {
const targetDisplayFormat = settingKeyToDisplayFormat(settingKey);
const targetName = `${targetDisplayFormat.category}: ${targetDisplayFormat.label}`;
return linkify ?
`[${targetName}](#${settingKey})` :
`"${targetName}"`;
});
}
function escapeInvisibleChars(enumValue: string): string {
return enumValue && enumValue
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r');
}
export class SettingsTreeFilter implements IFilter {
constructor(
private viewState: ISettingsEditorViewState,
) { }
isVisible(tree: ITree, element: SettingsTreeElement): boolean {
// Filter during search
if (this.viewState.filterToCategory && element instanceof SettingsTreeSettingElement) {
if (!this.settingContainedInGroup(element.setting, this.viewState.filterToCategory)) {
return false;
}
}
if (element instanceof SettingsTreeSettingElement && this.viewState.tagFilters) {
return element.matchesAllTags(this.viewState.tagFilters);
}
if (element instanceof SettingsTreeGroupElement) {
if (typeof element.count === 'number') {
return element.count > 0;
}
return element.children.some(child => this.isVisible(tree, child));
}
if (element instanceof SettingsTreeNewExtensionsElement) {
if ((this.viewState.tagFilters && this.viewState.tagFilters.size) || this.viewState.filterToCategory) {
return false;
}
}
return true;
}
private settingContainedInGroup(setting: ISetting, group: SettingsTreeGroupElement): boolean {
return group.children.some(child => {
if (child instanceof SettingsTreeGroupElement) {
return this.settingContainedInGroup(setting, child);
} else if (child instanceof SettingsTreeSettingElement) {
return child.setting.key === setting.key;
} else {
return false;
}
});
}
}
export class SettingsTreeController extends WorkbenchTreeController {
constructor(
@IConfigurationService configurationService: IConfigurationService
) {
super({}, configurationService);
}
protected onLeftClick(tree: ITree, element: any, eventish: IMouseEvent, origin?: string): boolean {
const isLink = eventish.target.tagName.toLowerCase() === 'a' ||
eventish.target.parentElement.tagName.toLowerCase() === 'a'; // <code> inside <a>
if (isLink && (DOM.findParentWithClass(eventish.target, 'setting-item-description-markdown', tree.getHTMLElement()) || DOM.findParentWithClass(eventish.target, 'select-box-description-markdown'))) {
return true;
}
return false;
}
}
export class SettingsAccessibilityProvider implements IAccessibilityProvider {
getAriaLabel(tree: ITree, element: SettingsTreeElement): string {
if (!element) {
return '';
}
if (element instanceof SettingsTreeSettingElement) {
return localize('settingRowAriaLabel', "{0} {1}, Setting", element.displayCategory, element.displayLabel);
}
if (element instanceof SettingsTreeGroupElement) {
return localize('groupRowAriaLabel', "{0}, group", element.label);
}
return '';
}
}
class NonExpandableOrSelectableTree extends Tree {
expand(): TPromise<any> {
return TPromise.wrap(null);
}
collapse(): TPromise<any> {
return TPromise.wrap(null);
}
public setFocus(element?: any, eventPayload?: any): void {
return;
}
public focusNext(count?: number, eventPayload?: any): void {
return;
}
public focusPrevious(count?: number, eventPayload?: any): void {
return;
}
public focusParent(eventPayload?: any): void {
return;
}
public focusFirstChild(eventPayload?: any): void {
return;
}
public focusFirst(eventPayload?: any, from?: any): void {
return;
}
public focusNth(index: number, eventPayload?: any): void {
return;
}
public focusLast(eventPayload?: any, from?: any): void {
return;
}
public focusNextPage(eventPayload?: any): void {
return;
}
public focusPreviousPage(eventPayload?: any): void {
return;
}
public select(element: any, eventPayload?: any): void {
return;
}
public selectRange(fromElement: any, toElement: any, eventPayload?: any): void {
return;
}
public selectAll(elements: any[], eventPayload?: any): void {
return;
}
public setSelection(elements: any[], eventPayload?: any): void {
return;
}
public toggleSelection(element: any, eventPayload?: any): void {
return;
}
}
export class SettingsTree extends NonExpandableOrSelectableTree {
protected disposables: IDisposable[];
constructor(
container: HTMLElement,
viewState: ISettingsEditorViewState,
configuration: Partial<ITreeConfiguration>,
@IThemeService themeService: IThemeService,
@IInstantiationService instantiationService: IInstantiationService
) {
const treeClass = 'settings-editor-tree';
const controller = instantiationService.createInstance(SettingsTreeController);
const fullConfiguration = <ITreeConfiguration>{
controller,
accessibilityProvider: instantiationService.createInstance(SettingsAccessibilityProvider),
filter: instantiationService.createInstance(SettingsTreeFilter, viewState),
styler: new DefaultTreestyler(DOM.createStyleSheet(container), treeClass),
...configuration
};
const options = {
ariaLabel: localize('treeAriaLabel', "Settings"),
showLoading: false,
indentPixels: 0,
twistiePixels: 20, // Actually for gear button
};
super(container,
fullConfiguration,
options);
this.disposables = [];
this.disposables.push(controller);
this.disposables.push(registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => {
const activeBorderColor = theme.getColor(focusBorder);
if (activeBorderColor) {
// TODO@rob - why isn't this applied when added to the stylesheet from tocTree.ts? Seems like a chromium glitch.
collector.addRule(`.settings-editor > .settings-body > .settings-toc-container .monaco-tree:focus .monaco-tree-row.focused {outline: solid 1px ${activeBorderColor}; outline-offset: -1px; }`);
}
const foregroundColor = theme.getColor(foreground);
if (foregroundColor) {
// Links appear inside other elements in markdown. CSS opacity acts like a mask. So we have to dynamically compute the description color to avoid
// applying an opacity to the link color.
const fgWithOpacity = new Color(new RGBA(foregroundColor.rgba.r, foregroundColor.rgba.g, foregroundColor.rgba.b, .9));
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-description { color: ${fgWithOpacity}; }`);
}
const errorColor = theme.getColor(errorForeground);
if (errorColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-deprecation-message { color: ${errorColor}; }`);
}
const invalidInputBackground = theme.getColor(inputValidationErrorBackground);
if (invalidInputBackground) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-validation-message { background-color: ${invalidInputBackground}; }`);
}
const invalidInputForeground = theme.getColor(inputValidationErrorForeground);
if (invalidInputForeground) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-validation-message { color: ${invalidInputForeground}; }`);
}
const invalidInputBorder = theme.getColor(inputValidationErrorBorder);
if (invalidInputBorder) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-validation-message { border-style:solid; border-width: 1px; border-color: ${invalidInputBorder}; }`);
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item.invalid-input .setting-item-control .monaco-inputbox.idle { outline-width: 0; border-style:solid; border-width: 1px; border-color: ${invalidInputBorder}; }`);
}
const headerForegroundColor = theme.getColor(settingsHeaderForeground);
if (headerForegroundColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .settings-group-title-label { color: ${headerForegroundColor}; }`);
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item-label { color: ${headerForegroundColor}; }`);
}
const focusBorderColor = theme.getColor(focusBorder);
if (focusBorderColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-description-markdown a:focus { outline-color: ${focusBorderColor} }`);
}
}));
this.getHTMLElement().classList.add(treeClass);
this.disposables.push(attachStyler(themeService, {
listActiveSelectionBackground: editorBackground,
listActiveSelectionForeground: foreground,
listFocusAndSelectionBackground: editorBackground,
listFocusAndSelectionForeground: foreground,
listFocusBackground: editorBackground,
listFocusForeground: foreground,
listHoverForeground: foreground,
listHoverBackground: editorBackground,
listHoverOutline: editorBackground,
listFocusOutline: editorBackground,
listInactiveSelectionBackground: editorBackground,
listInactiveSelectionForeground: foreground
}, colors => {
this.style(colors);
}));
}
}
class CopySettingIdAction extends Action {
static readonly ID = 'settings.copySettingId';
static readonly LABEL = localize('copySettingIdLabel', "Copy Setting ID");
constructor(
@IClipboardService private clipboardService: IClipboardService
) {
super(CopySettingIdAction.ID, CopySettingIdAction.LABEL);
}
run(context: SettingsTreeSettingElement): TPromise<void> {
if (context) {
this.clipboardService.writeText(context.setting.key);
}
return TPromise.as(null);
}
}
class CopySettingAsJSONAction extends Action {
static readonly ID = 'settings.copySettingAsJSON';
static readonly LABEL = localize('copySettingAsJSONLabel', "Copy Setting as JSON");
constructor(
@IClipboardService private clipboardService: IClipboardService
) {
super(CopySettingAsJSONAction.ID, CopySettingAsJSONAction.LABEL);
}
run(context: SettingsTreeSettingElement): TPromise<void> {
if (context) {
const jsonResult = `"${context.setting.key}": ${JSON.stringify(context.value, undefined, ' ')}`;
this.clipboardService.writeText(jsonResult);
}
return TPromise.as(null);
}
} | src/vs/workbench/parts/preferences/browser/settingsTree.ts | 1 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.000239509143284522,
0.0001703095913399011,
0.00016569336003158242,
0.0001696486142463982,
0.0000072455950430594385
]
|
{
"id": 0,
"code_window": [
"\tariaLabel?: string;\n",
"\tgetKeyBinding?: (action: IAction) => ResolvedKeybinding;\n",
"\tactionRunner?: IActionRunner;\n",
"}\n",
"\n",
"/**\n",
" * A widget that combines an action bar for primary actions and a dropdown for secondary actions.\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\ttoggleMenuTitle?: string;\n"
],
"file_path": "src/vs/base/browser/ui/toolbar/toolbar.ts",
"type": "add",
"edit_start_line_idx": 24
} | using System;
namespace SampleNamespace
{
class TestClass
{
static void Main(string[] args)
{
int[] radii = { 15, 32, 108, 74, 9 };
const double pi = 3.14159;
foreach (int radius in radii) {
double circumference = pi * (2 * radius);
// Display the number of command line arguments:
System.Console.WriteLine("Circumference = {0:N2}", circumference);
}
}
}
} | extensions/csharp/test/colorize-fixtures/test.cs | 0 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.00017212341481354088,
0.00017034733900800347,
0.00016857124865055084,
0.00017034733900800347,
0.0000017760830814950168
]
|
{
"id": 0,
"code_window": [
"\tariaLabel?: string;\n",
"\tgetKeyBinding?: (action: IAction) => ResolvedKeybinding;\n",
"\tactionRunner?: IActionRunner;\n",
"}\n",
"\n",
"/**\n",
" * A widget that combines an action bar for primary actions and a dropdown for secondary actions.\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\ttoggleMenuTitle?: string;\n"
],
"file_path": "src/vs/base/browser/ui/toolbar/toolbar.ts",
"type": "add",
"edit_start_line_idx": 24
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { IExtensionService, IExtensionDescription, ProfileSession, IExtensionHostProfile, ProfileSegmentId } from 'vs/workbench/services/extensions/common/extensions';
import { TPromise } from 'vs/base/common/winjs.base';
import { TernarySearchTree } from 'vs/base/common/map';
import { realpathSync } from 'vs/base/node/extfs';
import { Profile, ProfileNode } from 'v8-inspect-profiler';
export class ExtensionHostProfiler {
constructor(private readonly _port: number, @IExtensionService private readonly _extensionService: IExtensionService) {
}
public start(): TPromise<ProfileSession> {
return TPromise.wrap(import('v8-inspect-profiler')).then(profiler => {
return profiler.startProfiling({ port: this._port }).then(session => {
return {
stop: () => {
return TPromise.wrap(session.stop()).then(profile => {
return this._extensionService.getExtensions().then(extensions => {
return this.distill(profile.profile, extensions);
});
});
}
};
});
});
}
private distill(profile: Profile, extensions: IExtensionDescription[]): IExtensionHostProfile {
let searchTree = TernarySearchTree.forPaths<IExtensionDescription>();
for (let extension of extensions) {
searchTree.set(realpathSync(extension.extensionLocation.fsPath), extension);
}
let nodes = profile.nodes;
let idsToNodes = new Map<number, ProfileNode>();
let idsToSegmentId = new Map<number, ProfileSegmentId>();
for (let node of nodes) {
idsToNodes.set(node.id, node);
}
function visit(node: ProfileNode, segmentId: ProfileSegmentId) {
if (!segmentId) {
switch (node.callFrame.functionName) {
case '(root)':
break;
case '(program)':
segmentId = 'program';
break;
case '(garbage collector)':
segmentId = 'gc';
break;
default:
segmentId = 'self';
break;
}
} else if (segmentId === 'self' && node.callFrame.url) {
let extension = searchTree.findSubstr(node.callFrame.url);
if (extension) {
segmentId = extension.id;
}
}
idsToSegmentId.set(node.id, segmentId);
if (node.children) {
for (let child of node.children) {
visit(idsToNodes.get(child), segmentId);
}
}
}
visit(nodes[0], null);
let samples = profile.samples;
let timeDeltas = profile.timeDeltas;
let distilledDeltas: number[] = [];
let distilledIds: ProfileSegmentId[] = [];
let currSegmentTime = 0;
let currSegmentId: string = void 0;
for (let i = 0; i < samples.length; i++) {
let id = samples[i];
let segmentId = idsToSegmentId.get(id);
if (segmentId !== currSegmentId) {
if (currSegmentId) {
distilledIds.push(currSegmentId);
distilledDeltas.push(currSegmentTime);
}
currSegmentId = segmentId;
currSegmentTime = 0;
}
currSegmentTime += timeDeltas[i];
}
if (currSegmentId) {
distilledIds.push(currSegmentId);
distilledDeltas.push(currSegmentTime);
}
idsToNodes = null;
idsToSegmentId = null;
searchTree = null;
return {
startTime: profile.startTime,
endTime: profile.endTime,
deltas: distilledDeltas,
ids: distilledIds,
data: profile,
getAggregatedTimes: () => {
let segmentsToTime = new Map<ProfileSegmentId, number>();
for (let i = 0; i < distilledIds.length; i++) {
let id = distilledIds[i];
segmentsToTime.set(id, (segmentsToTime.get(id) || 0) + distilledDeltas[i]);
}
return segmentsToTime;
}
};
}
}
| src/vs/workbench/services/extensions/electron-browser/extensionHostProfiler.ts | 0 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.00017417276103515178,
0.00017183127056341618,
0.00016740913270041347,
0.00017171556828543544,
0.0000016616376115052844
]
|
{
"id": 0,
"code_window": [
"\tariaLabel?: string;\n",
"\tgetKeyBinding?: (action: IAction) => ResolvedKeybinding;\n",
"\tactionRunner?: IActionRunner;\n",
"}\n",
"\n",
"/**\n",
" * A widget that combines an action bar for primary actions and a dropdown for secondary actions.\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\ttoggleMenuTitle?: string;\n"
],
"file_path": "src/vs/base/browser/ui/toolbar/toolbar.ts",
"type": "add",
"edit_start_line_idx": 24
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/* marker zone */
.monaco-editor .marker-widget {
padding-left: 2px;
text-overflow: ellipsis;
white-space: nowrap;
}
.monaco-editor .marker-widget > .stale {
opacity: 0.6;
font-style: italic;
}
.monaco-editor .marker-widget div.block {
display: inline-block;
vertical-align: top;
}
.monaco-editor .marker-widget .title {
display: inline-block;
padding-right: 5px;
}
.monaco-editor .marker-widget .descriptioncontainer {
position: relative;
white-space: pre;
-webkit-user-select: text;
user-select: text;
}
.monaco-editor .marker-widget .descriptioncontainer .filename {
cursor: pointer;
opacity: 0.6;
}
| src/vs/editor/contrib/gotoError/gotoErrorWidget.css | 0 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.00017071432375814766,
0.00016913395666051656,
0.00016772437084000558,
0.00016904858057387173,
0.0000013184945828470518
]
|
{
"id": 1,
"code_window": [
"\t\tsuper();\n",
"\n",
"\t\tthis.options = options;\n",
"\t\tthis.lookupKeybindings = typeof this.options.getKeyBinding === 'function';\n",
"\n",
"\t\tthis.toggleMenuAction = this._register(new ToggleMenuAction(() => this.toggleMenuActionItem && this.toggleMenuActionItem.show()));\n",
"\n",
"\t\tlet element = document.createElement('div');\n",
"\t\telement.className = 'monaco-toolbar';\n",
"\t\tcontainer.appendChild(element);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis.toggleMenuAction = this._register(new ToggleMenuAction(() => this.toggleMenuActionItem && this.toggleMenuActionItem.show(), options.toggleMenuTitle));\n"
],
"file_path": "src/vs/base/browser/ui/toolbar/toolbar.ts",
"type": "replace",
"edit_start_line_idx": 43
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as DOM from 'vs/base/browser/dom';
import { renderMarkdown } from 'vs/base/browser/htmlContentRenderer';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import { Separator } from 'vs/base/browser/ui/actionbar/actionbar';
import { alert as ariaAlert } from 'vs/base/browser/ui/aria/aria';
import { Button } from 'vs/base/browser/ui/button/button';
import { Checkbox } from 'vs/base/browser/ui/checkbox/checkbox';
import { InputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { SelectBox } from 'vs/base/browser/ui/selectBox/selectBox';
import { ToolBar } from 'vs/base/browser/ui/toolbar/toolbar';
import { Action, IAction } from 'vs/base/common/actions';
import * as arrays from 'vs/base/common/arrays';
import { Color, RGBA } from 'vs/base/common/color';
import { onUnexpectedError } from 'vs/base/common/errors';
import { Emitter, Event } from 'vs/base/common/event';
import { KeyCode } from 'vs/base/common/keyCodes';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import { escapeRegExpCharacters, startsWith } from 'vs/base/common/strings';
import { URI } from 'vs/base/common/uri';
import { TPromise } from 'vs/base/common/winjs.base';
import { IAccessibilityProvider, IDataSource, IFilter, IRenderer as ITreeRenderer, ITree, ITreeConfiguration } from 'vs/base/parts/tree/browser/tree';
import { DefaultTreestyler } from 'vs/base/parts/tree/browser/treeDefaults';
import { Tree } from 'vs/base/parts/tree/browser/treeImpl';
import { localize } from 'vs/nls';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { WorkbenchTreeController } from 'vs/platform/list/browser/listService';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { editorBackground, errorForeground, focusBorder, foreground, inputValidationErrorBackground, inputValidationErrorForeground, inputValidationErrorBorder } from 'vs/platform/theme/common/colorRegistry';
import { attachButtonStyler, attachInputBoxStyler, attachSelectBoxStyler, attachStyler } from 'vs/platform/theme/common/styler';
import { ICssStyleCollector, ITheme, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { ITOCEntry } from 'vs/workbench/parts/preferences/browser/settingsLayout';
import { ISettingsEditorViewState, isExcludeSetting, SettingsTreeElement, SettingsTreeGroupElement, SettingsTreeNewExtensionsElement, settingKeyToDisplayFormat, SettingsTreeSettingElement } from 'vs/workbench/parts/preferences/browser/settingsTreeModels';
import { ExcludeSettingWidget, IExcludeDataItem, settingsHeaderForeground, settingsNumberInputBackground, settingsNumberInputBorder, settingsNumberInputForeground, settingsSelectBackground, settingsSelectBorder, settingsSelectListBorder, settingsSelectForeground, settingsTextInputBackground, settingsTextInputBorder, settingsTextInputForeground } from 'vs/workbench/parts/preferences/browser/settingsWidgets';
import { ISetting, ISettingsGroup } from 'vs/workbench/services/preferences/common/preferences';
const $ = DOM.$;
function getExcludeDisplayValue(element: SettingsTreeSettingElement): IExcludeDataItem[] {
const data = element.isConfigured ?
{ ...element.defaultValue, ...element.scopeValue } :
element.defaultValue;
return Object.keys(data)
.filter(key => !!data[key])
.map(key => {
const value = data[key];
const sibling = typeof value === 'boolean' ? undefined : value.when;
return {
id: key,
pattern: key,
sibling
};
});
}
export function resolveSettingsTree(tocData: ITOCEntry, coreSettingsGroups: ISettingsGroup[]): { tree: ITOCEntry, leftoverSettings: Set<ISetting> } {
const allSettings = getFlatSettings(coreSettingsGroups);
return {
tree: _resolveSettingsTree(tocData, allSettings),
leftoverSettings: allSettings
};
}
export function resolveExtensionsSettings(groups: ISettingsGroup[]): ITOCEntry {
const settingsGroupToEntry = (group: ISettingsGroup) => {
const flatSettings = arrays.flatten(
group.sections.map(section => section.settings));
return {
id: group.id,
label: group.title,
settings: flatSettings
};
};
const extGroups = groups
.sort((a, b) => a.title.localeCompare(b.title))
.map(g => settingsGroupToEntry(g));
return {
id: 'extensions',
label: localize('extensions', "Extensions"),
children: extGroups
};
}
function _resolveSettingsTree(tocData: ITOCEntry, allSettings: Set<ISetting>): ITOCEntry {
let children: ITOCEntry[];
if (tocData.children) {
children = tocData.children
.map(child => _resolveSettingsTree(child, allSettings))
.filter(child => (child.children && child.children.length) || (child.settings && child.settings.length));
}
let settings: ISetting[];
if (tocData.settings) {
settings = arrays.flatten(tocData.settings.map(pattern => getMatchingSettings(allSettings, <string>pattern)));
}
if (!children && !settings) {
return null;
}
return {
id: tocData.id,
label: tocData.label,
children,
settings
};
}
function getMatchingSettings(allSettings: Set<ISetting>, pattern: string): ISetting[] {
const result: ISetting[] = [];
allSettings.forEach(s => {
if (settingMatches(s, pattern)) {
result.push(s);
allSettings.delete(s);
}
});
return result.sort((a, b) => a.key.localeCompare(b.key));
}
const settingPatternCache = new Map<string, RegExp>();
function createSettingMatchRegExp(pattern: string): RegExp {
pattern = escapeRegExpCharacters(pattern)
.replace(/\\\*/g, '.*');
return new RegExp(`^${pattern}`, 'i');
}
function settingMatches(s: ISetting, pattern: string): boolean {
let regExp = settingPatternCache.get(pattern);
if (!regExp) {
regExp = createSettingMatchRegExp(pattern);
settingPatternCache.set(pattern, regExp);
}
return regExp.test(s.key);
}
function getFlatSettings(settingsGroups: ISettingsGroup[]) {
const result: Set<ISetting> = new Set();
for (let group of settingsGroups) {
for (let section of group.sections) {
for (let s of section.settings) {
if (!s.overrides || !s.overrides.length) {
result.add(s);
}
}
}
}
return result;
}
export class SettingsDataSource implements IDataSource {
getId(tree: ITree, element: SettingsTreeElement): string {
return element.id;
}
hasChildren(tree: ITree, element: SettingsTreeElement): boolean {
if (element instanceof SettingsTreeGroupElement) {
return true;
}
return false;
}
getChildren(tree: ITree, element: SettingsTreeElement): TPromise<any> {
return TPromise.as(this._getChildren(element));
}
private _getChildren(element: SettingsTreeElement): SettingsTreeElement[] {
if (element instanceof SettingsTreeGroupElement) {
return element.children;
} else {
// No children...
return null;
}
}
getParent(tree: ITree, element: SettingsTreeElement): TPromise<any> {
return TPromise.wrap(element && element.parent);
}
shouldAutoexpand(): boolean {
return true;
}
}
export class SimplePagedDataSource implements IDataSource {
private static readonly SETTINGS_PER_PAGE = 30;
private static readonly BUFFER = 5;
private loadedToIndex: number;
constructor(private realDataSource: IDataSource) {
this.reset();
}
reset(): void {
this.loadedToIndex = SimplePagedDataSource.SETTINGS_PER_PAGE * 2;
}
pageTo(index: number, top = false): boolean {
const buffer = top ? SimplePagedDataSource.SETTINGS_PER_PAGE : SimplePagedDataSource.BUFFER;
if (index > this.loadedToIndex - buffer) {
this.loadedToIndex = (Math.ceil(index / SimplePagedDataSource.SETTINGS_PER_PAGE) + 1) * SimplePagedDataSource.SETTINGS_PER_PAGE;
return true;
} else {
return false;
}
}
getId(tree: ITree, element: any): string {
return this.realDataSource.getId(tree, element);
}
hasChildren(tree: ITree, element: any): boolean {
return this.realDataSource.hasChildren(tree, element);
}
getChildren(tree: ITree, element: SettingsTreeGroupElement): TPromise<any> {
return this.realDataSource.getChildren(tree, element).then(realChildren => {
return this._getChildren(realChildren);
});
}
_getChildren(realChildren: SettingsTreeElement[]): any[] {
const lastChild = realChildren[realChildren.length - 1];
if (lastChild && lastChild.index > this.loadedToIndex) {
return realChildren.filter(child => {
return child.index < this.loadedToIndex;
});
} else {
return realChildren;
}
}
getParent(tree: ITree, element: any): TPromise<any> {
return this.realDataSource.getParent(tree, element);
}
shouldAutoexpand(tree: ITree, element: any): boolean {
return this.realDataSource.shouldAutoexpand(tree, element);
}
}
interface IDisposableTemplate {
toDispose: IDisposable[];
}
interface ISettingItemTemplate<T = any> extends IDisposableTemplate {
onChange?: (value: T) => void;
context?: SettingsTreeSettingElement;
containerElement: HTMLElement;
categoryElement: HTMLElement;
labelElement: HTMLElement;
descriptionElement: HTMLElement;
controlElement: HTMLElement;
deprecationWarningElement: HTMLElement;
otherOverridesElement: HTMLElement;
toolbar: ToolBar;
}
interface ISettingBoolItemTemplate extends ISettingItemTemplate<boolean> {
checkbox: Checkbox;
}
interface ISettingTextItemTemplate extends ISettingItemTemplate<string> {
inputBox: InputBox;
validationErrorMessageElement: HTMLElement;
}
type ISettingNumberItemTemplate = ISettingTextItemTemplate;
interface ISettingEnumItemTemplate extends ISettingItemTemplate<number> {
selectBox: SelectBox;
enumDescriptionElement: HTMLElement;
}
interface ISettingComplexItemTemplate extends ISettingItemTemplate<void> {
button: Button;
}
interface ISettingExcludeItemTemplate extends ISettingItemTemplate<void> {
excludeWidget: ExcludeSettingWidget;
}
interface ISettingNewExtensionsTemplate extends IDisposableTemplate {
button: Button;
context?: SettingsTreeNewExtensionsElement;
}
interface IGroupTitleTemplate extends IDisposableTemplate {
context?: SettingsTreeGroupElement;
parent: HTMLElement;
}
const SETTINGS_TEXT_TEMPLATE_ID = 'settings.text.template';
const SETTINGS_NUMBER_TEMPLATE_ID = 'settings.number.template';
const SETTINGS_ENUM_TEMPLATE_ID = 'settings.enum.template';
const SETTINGS_BOOL_TEMPLATE_ID = 'settings.bool.template';
const SETTINGS_EXCLUDE_TEMPLATE_ID = 'settings.exclude.template';
const SETTINGS_COMPLEX_TEMPLATE_ID = 'settings.complex.template';
const SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID = 'settings.newExtensions.template';
const SETTINGS_GROUP_ELEMENT_TEMPLATE_ID = 'settings.group.template';
export interface ISettingChangeEvent {
key: string;
value: any; // undefined => reset/unconfigure
}
export interface ISettingLinkClickEvent {
source: SettingsTreeSettingElement;
targetKey: string;
}
export class SettingsRenderer implements ITreeRenderer {
public static readonly CONTROL_CLASS = 'setting-control-focus-target';
public static readonly CONTROL_SELECTOR = '.' + SettingsRenderer.CONTROL_CLASS;
public static readonly SETTING_KEY_ATTR = 'data-key';
private readonly _onDidChangeSetting: Emitter<ISettingChangeEvent> = new Emitter<ISettingChangeEvent>();
public readonly onDidChangeSetting: Event<ISettingChangeEvent> = this._onDidChangeSetting.event;
private readonly _onDidOpenSettings: Emitter<string> = new Emitter<string>();
public readonly onDidOpenSettings: Event<string> = this._onDidOpenSettings.event;
private readonly _onDidClickSettingLink: Emitter<ISettingLinkClickEvent> = new Emitter<ISettingLinkClickEvent>();
public readonly onDidClickSettingLink: Event<ISettingLinkClickEvent> = this._onDidClickSettingLink.event;
private readonly _onDidFocusSetting: Emitter<SettingsTreeSettingElement> = new Emitter<SettingsTreeSettingElement>();
public readonly onDidFocusSetting: Event<SettingsTreeSettingElement> = this._onDidFocusSetting.event;
private descriptionMeasureContainer: HTMLElement;
private longestSingleLineDescription = 0;
private rowHeightCache = new Map<string, number>();
private lastRenderedWidth: number;
private settingActions: IAction[];
constructor(
_measureContainer: HTMLElement,
@IThemeService private themeService: IThemeService,
@IContextViewService private contextViewService: IContextViewService,
@IOpenerService private readonly openerService: IOpenerService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@ICommandService private readonly commandService: ICommandService,
@IContextMenuService private contextMenuService: IContextMenuService
) {
this.descriptionMeasureContainer = $('.setting-item-description');
DOM.append(_measureContainer,
$('.setting-measure-container.monaco-tree-row', undefined,
$('.setting-item', undefined,
this.descriptionMeasureContainer)));
this.settingActions = [
new Action('settings.resetSetting', localize('resetSettingLabel', "Reset Setting"), undefined, undefined, (context: SettingsTreeSettingElement) => {
if (context) {
this._onDidChangeSetting.fire({ key: context.setting.key, value: undefined });
}
return TPromise.wrap(null);
}),
new Separator(),
this.instantiationService.createInstance(CopySettingIdAction),
this.instantiationService.createInstance(CopySettingAsJSONAction),
];
}
showContextMenu(element: SettingsTreeSettingElement, settingDOMElement: HTMLElement): void {
const toolbarElement: HTMLElement = settingDOMElement.querySelector('.toolbar-toggle-more');
if (toolbarElement) {
this.contextMenuService.showContextMenu({
getActions: () => TPromise.wrap(this.settingActions),
getAnchor: () => toolbarElement,
getActionsContext: () => element
});
}
}
updateWidth(width: number): void {
if (this.lastRenderedWidth !== width) {
this.rowHeightCache = new Map<string, number>();
}
this.longestSingleLineDescription = 0;
this.lastRenderedWidth = width;
}
getHeight(tree: ITree, element: SettingsTreeElement): number {
if (this.rowHeightCache.has(element.id) && !(element instanceof SettingsTreeSettingElement && isExcludeSetting(element.setting))) {
return this.rowHeightCache.get(element.id);
}
const h = this._getHeight(tree, element);
this.rowHeightCache.set(element.id, h);
return h;
}
_getHeight(tree: ITree, element: SettingsTreeElement): number {
if (element instanceof SettingsTreeGroupElement) {
if (element.isFirstGroup) {
return 31;
}
return 40 + (7 * element.level);
}
if (element instanceof SettingsTreeSettingElement) {
if (isExcludeSetting(element.setting)) {
return this._getExcludeSettingHeight(element);
} else {
return this.measureSettingElementHeight(tree, element);
}
}
if (element instanceof SettingsTreeNewExtensionsElement) {
return 40;
}
return 0;
}
_getExcludeSettingHeight(element: SettingsTreeSettingElement): number {
const displayValue = getExcludeDisplayValue(element);
return (displayValue.length + 1) * 22 + 66 + this.measureSettingDescription(element);
}
private measureSettingElementHeight(tree: ITree, element: SettingsTreeSettingElement): number {
let heightExcludingDescription = 86;
if (element.valueType === 'boolean') {
heightExcludingDescription = 60;
}
return heightExcludingDescription + this.measureSettingDescription(element);
}
private measureSettingDescription(element: SettingsTreeSettingElement): number {
if (element.description.length < this.longestSingleLineDescription * .8) {
// Most setting descriptions are one short line, so try to avoid measuring them.
// If the description is less than 80% of the longest single line description, assume this will also render to be one line.
return 18;
}
const boolMeasureClass = 'measure-bool-description';
if (element.valueType === 'boolean') {
this.descriptionMeasureContainer.classList.add(boolMeasureClass);
} else if (this.descriptionMeasureContainer.classList.contains(boolMeasureClass)) {
this.descriptionMeasureContainer.classList.remove(boolMeasureClass);
}
const shouldRenderMarkdown = element.setting.descriptionIsMarkdown && element.description.indexOf('\n- ') >= 0;
while (this.descriptionMeasureContainer.firstChild) {
this.descriptionMeasureContainer.removeChild(this.descriptionMeasureContainer.firstChild);
}
if (shouldRenderMarkdown) {
const text = fixSettingLinks(element.description);
const rendered = renderMarkdown({ value: text });
rendered.classList.add('setting-item-description-markdown');
this.descriptionMeasureContainer.appendChild(rendered);
return this.descriptionMeasureContainer.offsetHeight;
} else {
// Remove markdown links, setting links, backticks
const measureText = element.setting.descriptionIsMarkdown ?
fixSettingLinks(element.description)
.replace(/\[(.*)\]\(.*\)/g, '$1')
.replace(/`([^`]*)`/g, '$1') :
element.description;
this.descriptionMeasureContainer.innerText = measureText;
const h = this.descriptionMeasureContainer.offsetHeight;
if (h < 20 && measureText.length > this.longestSingleLineDescription) {
this.longestSingleLineDescription = measureText.length;
}
return h;
}
}
getTemplateId(tree: ITree, element: SettingsTreeElement): string {
if (element instanceof SettingsTreeGroupElement) {
return SETTINGS_GROUP_ELEMENT_TEMPLATE_ID;
}
if (element instanceof SettingsTreeSettingElement) {
if (element.valueType === 'boolean') {
return SETTINGS_BOOL_TEMPLATE_ID;
}
if (element.valueType === 'integer' || element.valueType === 'number' || element.valueType === 'nullable-integer' || element.valueType === 'nullable-number') {
return SETTINGS_NUMBER_TEMPLATE_ID;
}
if (element.valueType === 'string') {
return SETTINGS_TEXT_TEMPLATE_ID;
}
if (element.valueType === 'enum') {
return SETTINGS_ENUM_TEMPLATE_ID;
}
if (element.valueType === 'exclude') {
return SETTINGS_EXCLUDE_TEMPLATE_ID;
}
return SETTINGS_COMPLEX_TEMPLATE_ID;
}
if (element instanceof SettingsTreeNewExtensionsElement) {
return SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID;
}
return '';
}
renderTemplate(tree: ITree, templateId: string, container: HTMLElement) {
if (templateId === SETTINGS_GROUP_ELEMENT_TEMPLATE_ID) {
return this.renderGroupTitleTemplate(container);
}
if (templateId === SETTINGS_TEXT_TEMPLATE_ID) {
return this.renderSettingTextTemplate(tree, container);
}
if (templateId === SETTINGS_NUMBER_TEMPLATE_ID) {
return this.renderSettingNumberTemplate(tree, container);
}
if (templateId === SETTINGS_BOOL_TEMPLATE_ID) {
return this.renderSettingBoolTemplate(tree, container);
}
if (templateId === SETTINGS_ENUM_TEMPLATE_ID) {
return this.renderSettingEnumTemplate(tree, container);
}
if (templateId === SETTINGS_EXCLUDE_TEMPLATE_ID) {
return this.renderSettingExcludeTemplate(tree, container);
}
if (templateId === SETTINGS_COMPLEX_TEMPLATE_ID) {
return this.renderSettingComplexTemplate(tree, container);
}
if (templateId === SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID) {
return this.renderNewExtensionsTemplate(container);
}
return null;
}
private renderGroupTitleTemplate(container: HTMLElement): IGroupTitleTemplate {
DOM.addClass(container, 'group-title');
const toDispose = [];
const template: IGroupTitleTemplate = {
parent: container,
toDispose
};
return template;
}
private renderCommonTemplate(tree: ITree, container: HTMLElement, typeClass: string): ISettingItemTemplate {
DOM.addClass(container, 'setting-item');
DOM.addClass(container, 'setting-item-' + typeClass);
const titleElement = DOM.append(container, $('.setting-item-title'));
const labelCategoryContainer = DOM.append(titleElement, $('.setting-item-cat-label-container'));
const categoryElement = DOM.append(labelCategoryContainer, $('span.setting-item-category'));
const labelElement = DOM.append(labelCategoryContainer, $('span.setting-item-label'));
const otherOverridesElement = DOM.append(titleElement, $('span.setting-item-overrides'));
const descriptionElement = DOM.append(container, $('.setting-item-description'));
const modifiedIndicatorElement = DOM.append(container, $('.setting-item-modified-indicator'));
modifiedIndicatorElement.title = localize('modified', "Modified");
const valueElement = DOM.append(container, $('.setting-item-value'));
const controlElement = DOM.append(valueElement, $('div.setting-item-control'));
const deprecationWarningElement = DOM.append(container, $('.setting-item-deprecation-message'));
const toDispose = [];
const toolbar = this.renderSettingToolbar(container);
const template: ISettingItemTemplate = {
toDispose,
containerElement: container,
categoryElement,
labelElement,
descriptionElement,
controlElement,
deprecationWarningElement,
otherOverridesElement,
toolbar
};
// Prevent clicks from being handled by list
toDispose.push(DOM.addDisposableListener(controlElement, 'mousedown', (e: IMouseEvent) => e.stopPropagation()));
toDispose.push(DOM.addStandardDisposableListener(valueElement, 'keydown', (e: StandardKeyboardEvent) => {
if (e.keyCode === KeyCode.Escape) {
tree.domFocus();
e.browserEvent.stopPropagation();
}
}));
return template;
}
private addSettingElementFocusHandler(template: ISettingItemTemplate): void {
const focusTracker = DOM.trackFocus(template.containerElement);
template.toDispose.push(focusTracker);
focusTracker.onDidBlur(() => {
if (template.containerElement.classList.contains('focused')) {
template.containerElement.classList.remove('focused');
}
});
focusTracker.onDidFocus(() => {
template.containerElement.classList.add('focused');
if (template.context) {
this._onDidFocusSetting.fire(template.context);
}
});
}
private renderSettingTextTemplate(tree: ITree, container: HTMLElement, type = 'text'): ISettingTextItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'text');
const validationErrorMessageElement = DOM.append(container, $('.setting-item-validation-message'));
const inputBox = new InputBox(common.controlElement, this.contextViewService);
common.toDispose.push(inputBox);
common.toDispose.push(attachInputBoxStyler(inputBox, this.themeService, {
inputBackground: settingsTextInputBackground,
inputForeground: settingsTextInputForeground,
inputBorder: settingsTextInputBorder
}));
common.toDispose.push(
inputBox.onDidChange(e => {
if (template.onChange) {
template.onChange(e);
}
}));
common.toDispose.push(inputBox);
inputBox.inputElement.classList.add(SettingsRenderer.CONTROL_CLASS);
const template: ISettingTextItemTemplate = {
...common,
inputBox,
validationErrorMessageElement
};
this.addSettingElementFocusHandler(template);
return template;
}
private renderSettingNumberTemplate(tree: ITree, container: HTMLElement): ISettingNumberItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'number');
const validationErrorMessageElement = DOM.append(container, $('.setting-item-validation-message'));
const inputBox = new InputBox(common.controlElement, this.contextViewService, { type: 'number' });
common.toDispose.push(inputBox);
common.toDispose.push(attachInputBoxStyler(inputBox, this.themeService, {
inputBackground: settingsNumberInputBackground,
inputForeground: settingsNumberInputForeground,
inputBorder: settingsNumberInputBorder
}));
common.toDispose.push(
inputBox.onDidChange(e => {
if (template.onChange) {
template.onChange(e);
}
}));
common.toDispose.push(inputBox);
inputBox.inputElement.classList.add(SettingsRenderer.CONTROL_CLASS);
const template: ISettingNumberItemTemplate = {
...common,
inputBox,
validationErrorMessageElement
};
this.addSettingElementFocusHandler(template);
return template;
}
private renderSettingToolbar(container: HTMLElement): ToolBar {
const toolbar = new ToolBar(container, this.contextMenuService, {});
toolbar.setActions([], this.settingActions)();
const button = container.querySelector('.toolbar-toggle-more');
if (button) {
(<HTMLElement>button).tabIndex = -1;
}
return toolbar;
}
private renderSettingBoolTemplate(tree: ITree, container: HTMLElement): ISettingBoolItemTemplate {
DOM.addClass(container, 'setting-item');
DOM.addClass(container, 'setting-item-bool');
const titleElement = DOM.append(container, $('.setting-item-title'));
const categoryElement = DOM.append(titleElement, $('span.setting-item-category'));
const labelElement = DOM.append(titleElement, $('span.setting-item-label'));
const otherOverridesElement = DOM.append(titleElement, $('span.setting-item-overrides'));
const descriptionAndValueElement = DOM.append(container, $('.setting-item-value-description'));
const controlElement = DOM.append(descriptionAndValueElement, $('.setting-item-bool-control'));
const descriptionElement = DOM.append(descriptionAndValueElement, $('.setting-item-description'));
const modifiedIndicatorElement = DOM.append(container, $('.setting-item-modified-indicator'));
modifiedIndicatorElement.title = localize('modified', "Modified");
const deprecationWarningElement = DOM.append(container, $('.setting-item-deprecation-message'));
const toDispose = [];
const checkbox = new Checkbox({ actionClassName: 'setting-value-checkbox', isChecked: true, title: '', inputActiveOptionBorder: null });
controlElement.appendChild(checkbox.domNode);
toDispose.push(checkbox);
toDispose.push(checkbox.onChange(() => {
if (template.onChange) {
template.onChange(checkbox.checked);
}
}));
// Need to listen for mouse clicks on description and toggle checkbox - use target ID for safety
// Also have to ignore embedded links - too buried to stop propagation
toDispose.push(DOM.addDisposableListener(descriptionElement, DOM.EventType.MOUSE_DOWN, (e) => {
const targetElement = <HTMLElement>e.toElement;
const targetId = descriptionElement.getAttribute('checkbox_label_target_id');
// Make sure we are not a link and the target ID matches
// Toggle target checkbox
if (targetElement.tagName.toLowerCase() !== 'a' && targetId === template.checkbox.domNode.id) {
template.checkbox.checked = template.checkbox.checked ? false : true;
template.onChange(checkbox.checked);
}
DOM.EventHelper.stop(e);
}));
checkbox.domNode.classList.add(SettingsRenderer.CONTROL_CLASS);
const toolbar = this.renderSettingToolbar(container);
toDispose.push(toolbar);
const template: ISettingBoolItemTemplate = {
toDispose,
containerElement: container,
categoryElement,
labelElement,
controlElement,
checkbox,
descriptionElement,
deprecationWarningElement,
otherOverridesElement,
toolbar
};
this.addSettingElementFocusHandler(template);
// Prevent clicks from being handled by list
toDispose.push(DOM.addDisposableListener(controlElement, 'mousedown', (e: IMouseEvent) => e.stopPropagation()));
toDispose.push(DOM.addStandardDisposableListener(controlElement, 'keydown', (e: StandardKeyboardEvent) => {
if (e.keyCode === KeyCode.Escape) {
tree.domFocus();
e.browserEvent.stopPropagation();
}
}));
return template;
}
public cancelSuggesters() {
this.contextViewService.hideContextView();
}
private renderSettingEnumTemplate(tree: ITree, container: HTMLElement): ISettingEnumItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'enum');
const selectBox = new SelectBox([], undefined, this.contextViewService, undefined, {
hasDetails: true
});
common.toDispose.push(selectBox);
common.toDispose.push(attachSelectBoxStyler(selectBox, this.themeService, {
selectBackground: settingsSelectBackground,
selectForeground: settingsSelectForeground,
selectBorder: settingsSelectBorder,
selectListBorder: settingsSelectListBorder
}));
selectBox.render(common.controlElement);
const selectElement = common.controlElement.querySelector('select');
if (selectElement) {
selectElement.classList.add(SettingsRenderer.CONTROL_CLASS);
}
common.toDispose.push(
selectBox.onDidSelect(e => {
if (template.onChange) {
template.onChange(e.index);
}
}));
const enumDescriptionElement = common.containerElement.insertBefore($('.setting-item-enumDescription'), common.descriptionElement.nextSibling);
const template: ISettingEnumItemTemplate = {
...common,
selectBox,
enumDescriptionElement
};
this.addSettingElementFocusHandler(template);
return template;
}
private renderSettingExcludeTemplate(tree: ITree, container: HTMLElement): ISettingExcludeItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'exclude');
const excludeWidget = this.instantiationService.createInstance(ExcludeSettingWidget, common.controlElement);
excludeWidget.domNode.classList.add(SettingsRenderer.CONTROL_CLASS);
common.toDispose.push(excludeWidget);
const template: ISettingExcludeItemTemplate = {
...common,
excludeWidget
};
this.addSettingElementFocusHandler(template);
common.toDispose.push(excludeWidget.onDidChangeExclude(e => {
if (template.context) {
let newValue = { ...template.context.scopeValue };
// first delete the existing entry, if present
if (e.originalPattern) {
if (e.originalPattern in template.context.defaultValue) {
// delete a default by overriding it
newValue[e.originalPattern] = false;
} else {
delete newValue[e.originalPattern];
}
}
// then add the new or updated entry, if present
if (e.pattern) {
if (e.pattern in template.context.defaultValue && !e.sibling) {
// add a default by deleting its override
delete newValue[e.pattern];
} else {
newValue[e.pattern] = e.sibling ? { when: e.sibling } : true;
}
}
const sortKeys = (obj) => {
const keyArray = Object.keys(obj)
.map(key => ({ key, val: obj[key] }))
.sort((a, b) => a.key.localeCompare(b.key));
const retVal = {};
keyArray.forEach(pair => {
retVal[pair.key] = pair.val;
});
return retVal;
};
this._onDidChangeSetting.fire({
key: template.context.setting.key,
value: Object.keys(newValue).length === 0 ? undefined : sortKeys(newValue)
});
}
}));
return template;
}
private renderSettingComplexTemplate(tree: ITree, container: HTMLElement): ISettingComplexItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'complex');
const openSettingsButton = new Button(common.controlElement, { title: true, buttonBackground: null, buttonHoverBackground: null });
common.toDispose.push(openSettingsButton);
common.toDispose.push(openSettingsButton.onDidClick(() => template.onChange(null)));
openSettingsButton.label = localize('editInSettingsJson', "Edit in settings.json");
openSettingsButton.element.classList.add('edit-in-settings-button');
common.toDispose.push(attachButtonStyler(openSettingsButton, this.themeService, {
buttonBackground: Color.transparent.toString(),
buttonHoverBackground: Color.transparent.toString(),
buttonForeground: 'foreground'
}));
const template: ISettingComplexItemTemplate = {
...common,
button: openSettingsButton
};
this.addSettingElementFocusHandler(template);
return template;
}
private renderNewExtensionsTemplate(container: HTMLElement): ISettingNewExtensionsTemplate {
const toDispose = [];
container.classList.add('setting-item-new-extensions');
const button = new Button(container, { title: true, buttonBackground: null, buttonHoverBackground: null });
toDispose.push(button);
toDispose.push(button.onDidClick(() => {
if (template.context) {
this.commandService.executeCommand('workbench.extensions.action.showExtensionsWithIds', template.context.extensionIds);
}
}));
button.label = localize('newExtensionsButtonLabel', "Show matching extensions");
button.element.classList.add('settings-new-extensions-button');
toDispose.push(attachButtonStyler(button, this.themeService));
const template: ISettingNewExtensionsTemplate = {
button,
toDispose
};
// this.addSettingElementFocusHandler(template);
return template;
}
renderElement(tree: ITree, element: SettingsTreeElement, templateId: string, template: any): void {
if (templateId === SETTINGS_GROUP_ELEMENT_TEMPLATE_ID) {
return this.renderGroupElement(<SettingsTreeGroupElement>element, template);
}
if (templateId === SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID) {
return this.renderNewExtensionsElement(<SettingsTreeNewExtensionsElement>element, template);
}
return this.renderSettingElement(tree, <SettingsTreeSettingElement>element, templateId, template);
}
private renderGroupElement(element: SettingsTreeGroupElement, template: IGroupTitleTemplate): void {
template.parent.innerHTML = '';
const labelElement = DOM.append(template.parent, $('div.settings-group-title-label'));
labelElement.classList.add(`settings-group-level-${element.level}`);
labelElement.textContent = (<SettingsTreeGroupElement>element).label;
if (element.isFirstGroup) {
labelElement.classList.add('settings-group-first');
}
}
private renderNewExtensionsElement(element: SettingsTreeNewExtensionsElement, template: ISettingNewExtensionsTemplate): void {
template.context = element;
}
public getSettingDOMElementForDOMElement(domElement: HTMLElement): HTMLElement {
const parent = DOM.findParentWithClass(domElement, 'setting-item');
if (parent) {
return parent;
}
return null;
}
public getDOMElementsForSettingKey(treeContainer: HTMLElement, key: string): NodeListOf<HTMLElement> {
return treeContainer.querySelectorAll(`[${SettingsRenderer.SETTING_KEY_ATTR}="${key}"]`);
}
public getKeyForDOMElementInSetting(element: HTMLElement): string {
const settingElement = this.getSettingDOMElementForDOMElement(element);
return settingElement && settingElement.getAttribute(SettingsRenderer.SETTING_KEY_ATTR);
}
private renderSettingElement(tree: ITree, element: SettingsTreeSettingElement, templateId: string, template: ISettingItemTemplate | ISettingBoolItemTemplate): void {
template.context = element;
template.toolbar.context = element;
const setting = element.setting;
DOM.toggleClass(template.containerElement, 'is-configured', element.isConfigured);
DOM.toggleClass(template.containerElement, 'is-expanded', true);
template.containerElement.setAttribute(SettingsRenderer.SETTING_KEY_ATTR, element.setting.key);
const titleTooltip = setting.key + (element.isConfigured ? ' - Modified' : '');
template.categoryElement.textContent = element.displayCategory && (element.displayCategory + ': ');
template.categoryElement.title = titleTooltip;
template.labelElement.textContent = element.displayLabel;
template.labelElement.title = titleTooltip;
this.renderValue(element, templateId, <ISettingItemTemplate>template);
template.descriptionElement.innerHTML = '';
if (element.setting.descriptionIsMarkdown) {
const renderedDescription = this.renderDescriptionMarkdown(element, element.description, template.toDispose);
template.descriptionElement.appendChild(renderedDescription);
} else {
template.descriptionElement.innerText = element.description;
}
const baseId = (element.displayCategory + '_' + element.displayLabel).replace(/ /g, '_').toLowerCase();
template.descriptionElement.id = baseId + '_setting_description';
if (templateId === SETTINGS_BOOL_TEMPLATE_ID) {
// Add checkbox target to description clickable and able to toggle checkbox
template.descriptionElement.setAttribute('checkbox_label_target_id', baseId + '_setting_item');
}
if (element.overriddenScopeList.length) {
let otherOverridesLabel = element.isConfigured ?
localize('alsoConfiguredIn', "Also modified in") :
localize('configuredIn', "Modified in");
template.otherOverridesElement.textContent = `(${otherOverridesLabel}: ${element.overriddenScopeList.join(', ')})`;
} else {
template.otherOverridesElement.textContent = '';
}
// Remove tree attributes - sometimes overridden by tree - should be managed there
template.containerElement.parentElement.removeAttribute('role');
template.containerElement.parentElement.removeAttribute('aria-level');
template.containerElement.parentElement.removeAttribute('aria-posinset');
template.containerElement.parentElement.removeAttribute('aria-setsize');
}
private renderDescriptionMarkdown(element: SettingsTreeSettingElement, text: string, disposeables: IDisposable[]): HTMLElement {
// Rewrite `#editor.fontSize#` to link format
text = fixSettingLinks(text);
const renderedMarkdown = renderMarkdown({ value: text }, {
actionHandler: {
callback: (content: string) => {
if (startsWith(content, '#')) {
const e: ISettingLinkClickEvent = {
source: element,
targetKey: content.substr(1)
};
this._onDidClickSettingLink.fire(e);
} else {
this.openerService.open(URI.parse(content)).then(void 0, onUnexpectedError);
}
},
disposeables
}
});
renderedMarkdown.classList.add('setting-item-description-markdown');
cleanRenderedMarkdown(renderedMarkdown);
return renderedMarkdown;
}
private renderValue(element: SettingsTreeSettingElement, templateId: string, template: ISettingItemTemplate | ISettingBoolItemTemplate): void {
const onChange = value => this._onDidChangeSetting.fire({ key: element.setting.key, value });
template.deprecationWarningElement.innerText = element.setting.deprecationMessage || '';
if (templateId === SETTINGS_ENUM_TEMPLATE_ID) {
this.renderEnum(element, <ISettingEnumItemTemplate>template, onChange);
} else if (templateId === SETTINGS_TEXT_TEMPLATE_ID) {
this.renderText(element, <ISettingTextItemTemplate>template, onChange);
} else if (templateId === SETTINGS_NUMBER_TEMPLATE_ID) {
this.renderNumber(element, <ISettingTextItemTemplate>template, onChange);
} else if (templateId === SETTINGS_BOOL_TEMPLATE_ID) {
this.renderBool(element, <ISettingBoolItemTemplate>template, onChange);
} else if (templateId === SETTINGS_EXCLUDE_TEMPLATE_ID) {
this.renderExcludeSetting(element, <ISettingExcludeItemTemplate>template);
} else if (templateId === SETTINGS_COMPLEX_TEMPLATE_ID) {
this.renderComplexSetting(element, <ISettingComplexItemTemplate>template);
}
}
private renderBool(dataElement: SettingsTreeSettingElement, template: ISettingBoolItemTemplate, onChange: (value: boolean) => void): void {
template.onChange = null;
template.checkbox.checked = dataElement.value;
template.onChange = onChange;
// Setup and add ARIA attributes
// Create id and label for control/input element - parent is wrapper div
const baseId = (dataElement.displayCategory + '_' + dataElement.displayLabel).replace(/ /g, '_').toLowerCase();
const modifiedText = dataElement.isConfigured ? 'Modified' : '';
const label = dataElement.displayCategory + ' ' + dataElement.displayLabel + ' ' + modifiedText;
// We use the parent control div for the aria-labelledby target
// Does not appear you can use the direct label on the element itself within a tree
template.checkbox.domNode.parentElement.id = baseId + '_setting_label';
template.checkbox.domNode.parentElement.setAttribute('aria-label', label);
// Labels will not be read on descendent input elements of the parent treeitem
// unless defined as role=treeitem and indirect aria-labelledby approach
template.checkbox.domNode.id = baseId + '_setting_item';
template.checkbox.domNode.setAttribute('role', 'checkbox');
template.checkbox.domNode.setAttribute('aria-labelledby', baseId + '_setting_label');
template.checkbox.domNode.setAttribute('aria-describedby', baseId + '_setting_description');
}
private renderEnum(dataElement: SettingsTreeSettingElement, template: ISettingEnumItemTemplate, onChange: (value: string) => void): void {
const displayOptions = dataElement.setting.enum
.map(String)
.map(escapeInvisibleChars);
template.selectBox.setOptions(displayOptions);
const enumDescriptions = dataElement.setting.enumDescriptions;
const enumDescriptionsAreMarkdown = dataElement.setting.enumDescriptionsAreMarkdown;
template.selectBox.setDetailsProvider(index =>
({
details: enumDescriptions && enumDescriptions[index] && (enumDescriptionsAreMarkdown ? fixSettingLinks(enumDescriptions[index], false) : enumDescriptions[index]),
isMarkdown: enumDescriptionsAreMarkdown
}));
const modifiedText = dataElement.isConfigured ? 'Modified' : '';
const label = dataElement.displayCategory + ' ' + dataElement.displayLabel + ' ' + modifiedText;
const baseId = (dataElement.displayCategory + '_' + dataElement.displayLabel).replace(/ /g, '_').toLowerCase();
template.selectBox.setAriaLabel(label);
const idx = dataElement.setting.enum.indexOf(dataElement.value);
template.onChange = null;
template.selectBox.select(idx);
template.onChange = idx => onChange(dataElement.setting.enum[idx]);
if (template.controlElement.firstElementChild) {
// SelectBox needs to have treeitem changed to combobox to read correctly within tree
template.controlElement.firstElementChild.setAttribute('role', 'combobox');
template.controlElement.firstElementChild.setAttribute('aria-describedby', baseId + '_setting_description');
}
template.enumDescriptionElement.innerHTML = '';
}
private renderText(dataElement: SettingsTreeSettingElement, template: ISettingTextItemTemplate, onChange: (value: string) => void): void {
const modifiedText = dataElement.isConfigured ? 'Modified' : '';
const label = dataElement.displayCategory + ' ' + dataElement.displayLabel + ' ' + modifiedText; template.onChange = null;
template.inputBox.value = dataElement.value;
template.onChange = value => { renderValidations(dataElement, template, false, label); onChange(value); };
// Setup and add ARIA attributes
// Create id and label for control/input element - parent is wrapper div
const baseId = (dataElement.displayCategory + '_' + dataElement.displayLabel).replace(/ /g, '_').toLowerCase();
// We use the parent control div for the aria-labelledby target
// Does not appear you can use the direct label on the element itself within a tree
template.inputBox.inputElement.parentElement.id = baseId + '_setting_label';
template.inputBox.inputElement.parentElement.setAttribute('aria-label', label);
// Labels will not be read on descendent input elements of the parent treeitem
// unless defined as role=treeitem and indirect aria-labelledby approach
template.inputBox.inputElement.id = baseId + '_setting_item';
template.inputBox.inputElement.setAttribute('role', 'textbox');
template.inputBox.inputElement.setAttribute('aria-labelledby', baseId + '_setting_label');
template.inputBox.inputElement.setAttribute('aria-describedby', baseId + '_setting_description');
renderValidations(dataElement, template, true, label);
}
private renderNumber(dataElement: SettingsTreeSettingElement, template: ISettingTextItemTemplate, onChange: (value: number) => void): void {
const modifiedText = dataElement.isConfigured ? 'Modified' : '';
const label = dataElement.displayCategory + ' ' + dataElement.displayLabel + ' number ' + modifiedText; const numParseFn = (dataElement.valueType === 'integer' || dataElement.valueType === 'nullable-integer')
? parseInt : parseFloat;
const nullNumParseFn = (dataElement.valueType === 'nullable-integer' || dataElement.valueType === 'nullable-number')
? (v => v === '' ? null : numParseFn(v)) : numParseFn;
template.onChange = null;
template.inputBox.value = dataElement.value;
template.onChange = value => { renderValidations(dataElement, template, false, label); onChange(nullNumParseFn(value)); };
// Setup and add ARIA attributes
// Create id and label for control/input element - parent is wrapper div
const baseId = (dataElement.displayCategory + '_' + dataElement.displayLabel).replace(/ /g, '_').toLowerCase();
// We use the parent control div for the aria-labelledby target
// Does not appear you can use the direct label on the element itself within a tree
template.inputBox.inputElement.parentElement.id = baseId + '_setting_label';
template.inputBox.inputElement.parentElement.setAttribute('aria-label', label);
// Labels will not be read on descendent input elements of the parent treeitem
// unless defined as role=treeitem and indirect aria-labelledby approach
template.inputBox.inputElement.id = baseId + '_setting_item';
template.inputBox.inputElement.setAttribute('role', 'textbox');
template.inputBox.inputElement.setAttribute('aria-labelledby', baseId + '_setting_label');
template.inputBox.inputElement.setAttribute('aria-describedby', baseId + '_setting_description');
renderValidations(dataElement, template, true, label);
}
private renderExcludeSetting(dataElement: SettingsTreeSettingElement, template: ISettingExcludeItemTemplate): void {
const value = getExcludeDisplayValue(dataElement);
template.excludeWidget.setValue(value);
template.context = dataElement;
}
private renderComplexSetting(dataElement: SettingsTreeSettingElement, template: ISettingComplexItemTemplate): void {
template.onChange = () => this._onDidOpenSettings.fire(dataElement.setting.key);
}
disposeTemplate(tree: ITree, templateId: string, template: IDisposableTemplate): void {
dispose(template.toDispose);
}
}
function renderValidations(dataElement: SettingsTreeSettingElement, template: ISettingTextItemTemplate, calledOnStartup: boolean, originalAriaLabel: string) {
if (dataElement.setting.validator) {
let errMsg = dataElement.setting.validator(template.inputBox.value);
if (errMsg) {
DOM.addClass(template.containerElement, 'invalid-input');
template.validationErrorMessageElement.innerText = errMsg;
let validationError = localize('validationError', "Validation Error.");
template.inputBox.inputElement.parentElement.setAttribute('aria-label', [originalAriaLabel, validationError, errMsg].join(' '));
if (!calledOnStartup) { ariaAlert(validationError + ' ' + errMsg); }
return;
} else {
template.inputBox.inputElement.parentElement.setAttribute('aria-label', originalAriaLabel);
}
}
DOM.removeClass(template.containerElement, 'invalid-input');
}
function cleanRenderedMarkdown(element: Node): void {
for (let i = 0; i < element.childNodes.length; i++) {
const child = element.childNodes.item(i);
const tagName = (<Element>child).tagName && (<Element>child).tagName.toLowerCase();
if (tagName === 'img') {
element.removeChild(child);
} else {
cleanRenderedMarkdown(child);
}
}
}
function fixSettingLinks(text: string, linkify = true): string {
return text.replace(/`#([^#]*)#`/g, (match, settingKey) => {
const targetDisplayFormat = settingKeyToDisplayFormat(settingKey);
const targetName = `${targetDisplayFormat.category}: ${targetDisplayFormat.label}`;
return linkify ?
`[${targetName}](#${settingKey})` :
`"${targetName}"`;
});
}
function escapeInvisibleChars(enumValue: string): string {
return enumValue && enumValue
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r');
}
export class SettingsTreeFilter implements IFilter {
constructor(
private viewState: ISettingsEditorViewState,
) { }
isVisible(tree: ITree, element: SettingsTreeElement): boolean {
// Filter during search
if (this.viewState.filterToCategory && element instanceof SettingsTreeSettingElement) {
if (!this.settingContainedInGroup(element.setting, this.viewState.filterToCategory)) {
return false;
}
}
if (element instanceof SettingsTreeSettingElement && this.viewState.tagFilters) {
return element.matchesAllTags(this.viewState.tagFilters);
}
if (element instanceof SettingsTreeGroupElement) {
if (typeof element.count === 'number') {
return element.count > 0;
}
return element.children.some(child => this.isVisible(tree, child));
}
if (element instanceof SettingsTreeNewExtensionsElement) {
if ((this.viewState.tagFilters && this.viewState.tagFilters.size) || this.viewState.filterToCategory) {
return false;
}
}
return true;
}
private settingContainedInGroup(setting: ISetting, group: SettingsTreeGroupElement): boolean {
return group.children.some(child => {
if (child instanceof SettingsTreeGroupElement) {
return this.settingContainedInGroup(setting, child);
} else if (child instanceof SettingsTreeSettingElement) {
return child.setting.key === setting.key;
} else {
return false;
}
});
}
}
export class SettingsTreeController extends WorkbenchTreeController {
constructor(
@IConfigurationService configurationService: IConfigurationService
) {
super({}, configurationService);
}
protected onLeftClick(tree: ITree, element: any, eventish: IMouseEvent, origin?: string): boolean {
const isLink = eventish.target.tagName.toLowerCase() === 'a' ||
eventish.target.parentElement.tagName.toLowerCase() === 'a'; // <code> inside <a>
if (isLink && (DOM.findParentWithClass(eventish.target, 'setting-item-description-markdown', tree.getHTMLElement()) || DOM.findParentWithClass(eventish.target, 'select-box-description-markdown'))) {
return true;
}
return false;
}
}
export class SettingsAccessibilityProvider implements IAccessibilityProvider {
getAriaLabel(tree: ITree, element: SettingsTreeElement): string {
if (!element) {
return '';
}
if (element instanceof SettingsTreeSettingElement) {
return localize('settingRowAriaLabel', "{0} {1}, Setting", element.displayCategory, element.displayLabel);
}
if (element instanceof SettingsTreeGroupElement) {
return localize('groupRowAriaLabel', "{0}, group", element.label);
}
return '';
}
}
class NonExpandableOrSelectableTree extends Tree {
expand(): TPromise<any> {
return TPromise.wrap(null);
}
collapse(): TPromise<any> {
return TPromise.wrap(null);
}
public setFocus(element?: any, eventPayload?: any): void {
return;
}
public focusNext(count?: number, eventPayload?: any): void {
return;
}
public focusPrevious(count?: number, eventPayload?: any): void {
return;
}
public focusParent(eventPayload?: any): void {
return;
}
public focusFirstChild(eventPayload?: any): void {
return;
}
public focusFirst(eventPayload?: any, from?: any): void {
return;
}
public focusNth(index: number, eventPayload?: any): void {
return;
}
public focusLast(eventPayload?: any, from?: any): void {
return;
}
public focusNextPage(eventPayload?: any): void {
return;
}
public focusPreviousPage(eventPayload?: any): void {
return;
}
public select(element: any, eventPayload?: any): void {
return;
}
public selectRange(fromElement: any, toElement: any, eventPayload?: any): void {
return;
}
public selectAll(elements: any[], eventPayload?: any): void {
return;
}
public setSelection(elements: any[], eventPayload?: any): void {
return;
}
public toggleSelection(element: any, eventPayload?: any): void {
return;
}
}
export class SettingsTree extends NonExpandableOrSelectableTree {
protected disposables: IDisposable[];
constructor(
container: HTMLElement,
viewState: ISettingsEditorViewState,
configuration: Partial<ITreeConfiguration>,
@IThemeService themeService: IThemeService,
@IInstantiationService instantiationService: IInstantiationService
) {
const treeClass = 'settings-editor-tree';
const controller = instantiationService.createInstance(SettingsTreeController);
const fullConfiguration = <ITreeConfiguration>{
controller,
accessibilityProvider: instantiationService.createInstance(SettingsAccessibilityProvider),
filter: instantiationService.createInstance(SettingsTreeFilter, viewState),
styler: new DefaultTreestyler(DOM.createStyleSheet(container), treeClass),
...configuration
};
const options = {
ariaLabel: localize('treeAriaLabel', "Settings"),
showLoading: false,
indentPixels: 0,
twistiePixels: 20, // Actually for gear button
};
super(container,
fullConfiguration,
options);
this.disposables = [];
this.disposables.push(controller);
this.disposables.push(registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => {
const activeBorderColor = theme.getColor(focusBorder);
if (activeBorderColor) {
// TODO@rob - why isn't this applied when added to the stylesheet from tocTree.ts? Seems like a chromium glitch.
collector.addRule(`.settings-editor > .settings-body > .settings-toc-container .monaco-tree:focus .monaco-tree-row.focused {outline: solid 1px ${activeBorderColor}; outline-offset: -1px; }`);
}
const foregroundColor = theme.getColor(foreground);
if (foregroundColor) {
// Links appear inside other elements in markdown. CSS opacity acts like a mask. So we have to dynamically compute the description color to avoid
// applying an opacity to the link color.
const fgWithOpacity = new Color(new RGBA(foregroundColor.rgba.r, foregroundColor.rgba.g, foregroundColor.rgba.b, .9));
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-description { color: ${fgWithOpacity}; }`);
}
const errorColor = theme.getColor(errorForeground);
if (errorColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-deprecation-message { color: ${errorColor}; }`);
}
const invalidInputBackground = theme.getColor(inputValidationErrorBackground);
if (invalidInputBackground) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-validation-message { background-color: ${invalidInputBackground}; }`);
}
const invalidInputForeground = theme.getColor(inputValidationErrorForeground);
if (invalidInputForeground) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-validation-message { color: ${invalidInputForeground}; }`);
}
const invalidInputBorder = theme.getColor(inputValidationErrorBorder);
if (invalidInputBorder) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-validation-message { border-style:solid; border-width: 1px; border-color: ${invalidInputBorder}; }`);
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item.invalid-input .setting-item-control .monaco-inputbox.idle { outline-width: 0; border-style:solid; border-width: 1px; border-color: ${invalidInputBorder}; }`);
}
const headerForegroundColor = theme.getColor(settingsHeaderForeground);
if (headerForegroundColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .settings-group-title-label { color: ${headerForegroundColor}; }`);
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item-label { color: ${headerForegroundColor}; }`);
}
const focusBorderColor = theme.getColor(focusBorder);
if (focusBorderColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-description-markdown a:focus { outline-color: ${focusBorderColor} }`);
}
}));
this.getHTMLElement().classList.add(treeClass);
this.disposables.push(attachStyler(themeService, {
listActiveSelectionBackground: editorBackground,
listActiveSelectionForeground: foreground,
listFocusAndSelectionBackground: editorBackground,
listFocusAndSelectionForeground: foreground,
listFocusBackground: editorBackground,
listFocusForeground: foreground,
listHoverForeground: foreground,
listHoverBackground: editorBackground,
listHoverOutline: editorBackground,
listFocusOutline: editorBackground,
listInactiveSelectionBackground: editorBackground,
listInactiveSelectionForeground: foreground
}, colors => {
this.style(colors);
}));
}
}
class CopySettingIdAction extends Action {
static readonly ID = 'settings.copySettingId';
static readonly LABEL = localize('copySettingIdLabel', "Copy Setting ID");
constructor(
@IClipboardService private clipboardService: IClipboardService
) {
super(CopySettingIdAction.ID, CopySettingIdAction.LABEL);
}
run(context: SettingsTreeSettingElement): TPromise<void> {
if (context) {
this.clipboardService.writeText(context.setting.key);
}
return TPromise.as(null);
}
}
class CopySettingAsJSONAction extends Action {
static readonly ID = 'settings.copySettingAsJSON';
static readonly LABEL = localize('copySettingAsJSONLabel', "Copy Setting as JSON");
constructor(
@IClipboardService private clipboardService: IClipboardService
) {
super(CopySettingAsJSONAction.ID, CopySettingAsJSONAction.LABEL);
}
run(context: SettingsTreeSettingElement): TPromise<void> {
if (context) {
const jsonResult = `"${context.setting.key}": ${JSON.stringify(context.value, undefined, ' ')}`;
this.clipboardService.writeText(jsonResult);
}
return TPromise.as(null);
}
} | src/vs/workbench/parts/preferences/browser/settingsTree.ts | 1 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.8167109489440918,
0.01657465100288391,
0.00015977794828359038,
0.00017218972789123654,
0.0994783341884613
]
|
{
"id": 1,
"code_window": [
"\t\tsuper();\n",
"\n",
"\t\tthis.options = options;\n",
"\t\tthis.lookupKeybindings = typeof this.options.getKeyBinding === 'function';\n",
"\n",
"\t\tthis.toggleMenuAction = this._register(new ToggleMenuAction(() => this.toggleMenuActionItem && this.toggleMenuActionItem.show()));\n",
"\n",
"\t\tlet element = document.createElement('div');\n",
"\t\telement.className = 'monaco-toolbar';\n",
"\t\tcontainer.appendChild(element);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis.toggleMenuAction = this._register(new ToggleMenuAction(() => this.toggleMenuActionItem && this.toggleMenuActionItem.show(), options.toggleMenuTitle));\n"
],
"file_path": "src/vs/base/browser/ui/toolbar/toolbar.ts",
"type": "replace",
"edit_start_line_idx": 43
} | {
"Region Start": {
"prefix": "#region",
"body": [
"#pragma region $0"
],
"description": "Folding Region Start"
},
"Region End": {
"prefix": "#endregion",
"body": [
"#pragma endregion"
],
"description": "Folding Region End"
}
}
| extensions/cpp/snippets/c.json | 0 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.00017503532581031322,
0.00017395775648765266,
0.00017288020171690732,
0.00017395775648765266,
0.0000010775620467029512
]
|
{
"id": 1,
"code_window": [
"\t\tsuper();\n",
"\n",
"\t\tthis.options = options;\n",
"\t\tthis.lookupKeybindings = typeof this.options.getKeyBinding === 'function';\n",
"\n",
"\t\tthis.toggleMenuAction = this._register(new ToggleMenuAction(() => this.toggleMenuActionItem && this.toggleMenuActionItem.show()));\n",
"\n",
"\t\tlet element = document.createElement('div');\n",
"\t\telement.className = 'monaco-toolbar';\n",
"\t\tcontainer.appendChild(element);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis.toggleMenuAction = this._register(new ToggleMenuAction(() => this.toggleMenuActionItem && this.toggleMenuActionItem.show(), options.toggleMenuTitle));\n"
],
"file_path": "src/vs/base/browser/ui/toolbar/toolbar.ts",
"type": "replace",
"edit_start_line_idx": 43
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { IResourceInput, ITextEditorOptions, IEditorOptions } from 'vs/platform/editor/common/editor';
import { IEditorInput, IEditor, GroupIdentifier, IFileEditorInput, IUntitledResourceInput, IResourceDiffInput, IResourceSideBySideInput, IEditorInputFactoryRegistry, Extensions as EditorExtensions, IFileInputFactory, EditorInput, SideBySideEditorInput, IEditorInputWithOptions, isEditorInputWithOptions, EditorOptions, TextEditorOptions, IEditorIdentifier, IEditorCloseEvent, ITextEditor, ITextDiffEditor, ITextSideBySideEditor, toResource } from 'vs/workbench/common/editor';
import { ResourceEditorInput } from 'vs/workbench/common/editor/resourceEditorInput';
import { DataUriEditorInput } from 'vs/workbench/common/editor/dataUriEditorInput';
import { Registry } from 'vs/platform/registry/common/platform';
import { ResourceMap } from 'vs/base/common/map';
import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { IFileService } from 'vs/platform/files/common/files';
import { Schemas } from 'vs/base/common/network';
import { Event, once, Emitter } from 'vs/base/common/event';
import { URI } from 'vs/base/common/uri';
import { basename } from 'vs/base/common/paths';
import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput';
import { localize } from 'vs/nls';
import { TPromise } from 'vs/base/common/winjs.base';
import { IEditorGroupsService, IEditorGroup, GroupsOrder, IEditorReplacement, GroupChangeKind, preferredSideBySideGroupDirection } from 'vs/workbench/services/group/common/editorGroupsService';
import { IResourceEditor, ACTIVE_GROUP_TYPE, SIDE_GROUP_TYPE, SIDE_GROUP, IResourceEditorReplacement, IOpenEditorOverrideHandler } from 'vs/workbench/services/editor/common/editorService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { Disposable, IDisposable, dispose, toDisposable } from 'vs/base/common/lifecycle';
import { coalesce } from 'vs/base/common/arrays';
import { isCodeEditor, isDiffEditor, ICodeEditor, IDiffEditor } from 'vs/editor/browser/editorBrowser';
import { IEditorGroupView, IEditorOpeningEvent, EditorGroupsServiceImpl, EditorServiceImpl } from 'vs/workbench/browser/parts/editor/editor';
import { ILabelService } from 'vs/platform/label/common/label';
type ICachedEditorInput = ResourceEditorInput | IFileEditorInput | DataUriEditorInput;
export class EditorService extends Disposable implements EditorServiceImpl {
_serviceBrand: any;
private static CACHE: ResourceMap<ICachedEditorInput> = new ResourceMap<ICachedEditorInput>();
//#region events
private _onDidActiveEditorChange: Emitter<void> = this._register(new Emitter<void>());
get onDidActiveEditorChange(): Event<void> { return this._onDidActiveEditorChange.event; }
private _onDidVisibleEditorsChange: Emitter<void> = this._register(new Emitter<void>());
get onDidVisibleEditorsChange(): Event<void> { return this._onDidVisibleEditorsChange.event; }
private _onDidCloseEditor: Emitter<IEditorCloseEvent> = this._register(new Emitter<IEditorCloseEvent>());
get onDidCloseEditor(): Event<IEditorCloseEvent> { return this._onDidCloseEditor.event; }
private _onDidOpenEditorFail: Emitter<IEditorIdentifier> = this._register(new Emitter<IEditorIdentifier>());
get onDidOpenEditorFail(): Event<IEditorIdentifier> { return this._onDidOpenEditorFail.event; }
//#endregion
private fileInputFactory: IFileInputFactory;
private openEditorHandlers: IOpenEditorOverrideHandler[] = [];
private lastActiveEditor: IEditorInput;
private lastActiveGroupId: GroupIdentifier;
constructor(
@IEditorGroupsService private editorGroupService: EditorGroupsServiceImpl,
@IUntitledEditorService private untitledEditorService: IUntitledEditorService,
@IInstantiationService private instantiationService: IInstantiationService,
@ILabelService private labelService: ILabelService,
@IFileService private fileService: IFileService,
@IConfigurationService private configurationService: IConfigurationService
) {
super();
this.fileInputFactory = Registry.as<IEditorInputFactoryRegistry>(EditorExtensions.EditorInputFactories).getFileInputFactory();
this.registerListeners();
}
private registerListeners(): void {
this.editorGroupService.whenRestored.then(() => this.onEditorsRestored());
this.editorGroupService.onDidActiveGroupChange(group => this.handleActiveEditorChange(group));
this.editorGroupService.onDidAddGroup(group => this.registerGroupListeners(group as IEditorGroupView));
}
private onEditorsRestored(): void {
// Register listeners to each opened group
this.editorGroupService.groups.forEach(group => this.registerGroupListeners(group as IEditorGroupView));
// Fire initial set of editor events if there is an active editor
if (this.activeEditor) {
this.doEmitActiveEditorChangeEvent();
this._onDidVisibleEditorsChange.fire();
}
}
private handleActiveEditorChange(group: IEditorGroup): void {
if (group !== this.editorGroupService.activeGroup) {
return; // ignore if not the active group
}
if (!this.lastActiveEditor && !group.activeEditor) {
return; // ignore if we still have no active editor
}
if (this.lastActiveGroupId === group.id && this.lastActiveEditor === group.activeEditor) {
return; // ignore if the editor actually did not change
}
this.doEmitActiveEditorChangeEvent();
}
private doEmitActiveEditorChangeEvent(): void {
const activeGroup = this.editorGroupService.activeGroup;
this.lastActiveGroupId = activeGroup.id;
this.lastActiveEditor = activeGroup.activeEditor;
this._onDidActiveEditorChange.fire();
}
private registerGroupListeners(group: IEditorGroupView): void {
const groupDisposeables: IDisposable[] = [];
groupDisposeables.push(group.onDidGroupChange(e => {
if (e.kind === GroupChangeKind.EDITOR_ACTIVE) {
this.handleActiveEditorChange(group);
this._onDidVisibleEditorsChange.fire();
}
}));
groupDisposeables.push(group.onDidCloseEditor(event => {
this._onDidCloseEditor.fire(event);
}));
groupDisposeables.push(group.onWillOpenEditor(event => {
this.onGroupWillOpenEditor(group, event);
}));
groupDisposeables.push(group.onDidOpenEditorFail(editor => {
this._onDidOpenEditorFail.fire({ editor, groupId: group.id });
}));
once(group.onWillDispose)(() => {
dispose(groupDisposeables);
});
}
private onGroupWillOpenEditor(group: IEditorGroup, event: IEditorOpeningEvent): void {
for (let i = 0; i < this.openEditorHandlers.length; i++) {
const handler = this.openEditorHandlers[i];
const result = handler(event.editor, event.options, group);
if (result && result.override) {
event.prevent((() => result.override));
break;
}
}
}
get activeControl(): IEditor {
const activeGroup = this.editorGroupService.activeGroup;
return activeGroup ? activeGroup.activeControl : void 0;
}
get activeTextEditorWidget(): ICodeEditor | IDiffEditor {
const activeControl = this.activeControl;
if (activeControl) {
const activeControlWidget = activeControl.getControl();
if (isCodeEditor(activeControlWidget) || isDiffEditor(activeControlWidget)) {
return activeControlWidget;
}
}
return void 0;
}
get editors(): IEditorInput[] {
const editors: IEditorInput[] = [];
this.editorGroupService.groups.forEach(group => {
editors.push(...group.editors);
});
return editors;
}
get activeEditor(): IEditorInput {
const activeGroup = this.editorGroupService.activeGroup;
return activeGroup ? activeGroup.activeEditor : void 0;
}
get visibleControls(): IEditor[] {
return coalesce(this.editorGroupService.groups.map(group => group.activeControl));
}
get visibleTextEditorWidgets(): (ICodeEditor | IDiffEditor)[] {
return this.visibleControls.map(control => control.getControl() as ICodeEditor | IDiffEditor).filter(widget => isCodeEditor(widget) || isDiffEditor(widget));
}
get visibleEditors(): IEditorInput[] {
return coalesce(this.editorGroupService.groups.map(group => group.activeEditor));
}
//#region preventOpenEditor()
overrideOpenEditor(handler: IOpenEditorOverrideHandler): IDisposable {
this.openEditorHandlers.push(handler);
return toDisposable(() => {
const index = this.openEditorHandlers.indexOf(handler);
if (index >= 0) {
this.openEditorHandlers.splice(index, 1);
}
});
}
//#endregion
//#region openEditor()
openEditor(editor: IEditorInput, options?: IEditorOptions | ITextEditorOptions, group?: IEditorGroup | GroupIdentifier | SIDE_GROUP_TYPE | ACTIVE_GROUP_TYPE): TPromise<IEditor>;
openEditor(editor: IResourceInput | IUntitledResourceInput, group?: IEditorGroup | GroupIdentifier | SIDE_GROUP_TYPE | ACTIVE_GROUP_TYPE): TPromise<ITextEditor>;
openEditor(editor: IResourceDiffInput, group?: IEditorGroup | GroupIdentifier | SIDE_GROUP_TYPE | ACTIVE_GROUP_TYPE): TPromise<ITextDiffEditor>;
openEditor(editor: IResourceSideBySideInput, group?: IEditorGroup | GroupIdentifier | SIDE_GROUP_TYPE | ACTIVE_GROUP_TYPE): TPromise<ITextSideBySideEditor>;
openEditor(editor: IEditorInput | IResourceEditor, optionsOrGroup?: IEditorOptions | ITextEditorOptions | IEditorGroup | GroupIdentifier | SIDE_GROUP_TYPE | ACTIVE_GROUP_TYPE, group?: GroupIdentifier): TPromise<IEditor> {
// Typed Editor Support
if (editor instanceof EditorInput) {
const editorOptions = this.toOptions(optionsOrGroup as IEditorOptions);
const targetGroup = this.findTargetGroup(editor, editorOptions, group);
return this.doOpenEditor(targetGroup, editor, editorOptions);
}
// Untyped Text Editor Support
const textInput = <IResourceEditor>editor;
const typedInput = this.createInput(textInput);
if (typedInput) {
const editorOptions = TextEditorOptions.from(textInput);
const targetGroup = this.findTargetGroup(typedInput, editorOptions, optionsOrGroup as IEditorGroup | GroupIdentifier);
return this.doOpenEditor(targetGroup, typedInput, editorOptions);
}
return TPromise.wrap<IEditor>(null);
}
protected doOpenEditor(group: IEditorGroup, editor: IEditorInput, options?: IEditorOptions): TPromise<IEditor> {
return group.openEditor(editor, options).then(() => group.activeControl);
}
private findTargetGroup(input: IEditorInput, options?: IEditorOptions, group?: IEditorGroup | GroupIdentifier | SIDE_GROUP_TYPE | ACTIVE_GROUP_TYPE): IEditorGroup {
let targetGroup: IEditorGroup;
// Group: Instance of Group
if (group && typeof group !== 'number') {
return group;
}
// Group: Side by Side
if (group === SIDE_GROUP) {
targetGroup = this.findSideBySideGroup();
}
// Group: Specific Group
else if (typeof group === 'number' && group >= 0) {
targetGroup = this.editorGroupService.getGroup(group);
}
// Group: Unspecified without a specific index to open
else if (!options || typeof options.index !== 'number') {
const groupsByLastActive = this.editorGroupService.getGroups(GroupsOrder.MOST_RECENTLY_ACTIVE);
// Respect option to reveal an editor if it is already visible in any group
if (options && options.revealIfVisible) {
for (let i = 0; i < groupsByLastActive.length; i++) {
const group = groupsByLastActive[i];
if (input.matches(group.activeEditor)) {
targetGroup = group;
break;
}
}
}
// Respect option to reveal an editor if it is open (not necessarily visible)
if ((options && options.revealIfOpened) || this.configurationService.getValue<boolean>('workbench.editor.revealIfOpen')) {
for (let i = 0; i < groupsByLastActive.length; i++) {
const group = groupsByLastActive[i];
if (group.isOpened(input)) {
targetGroup = group;
break;
}
}
}
}
// Fallback to active group if target not valid
if (!targetGroup) {
targetGroup = this.editorGroupService.activeGroup;
}
return targetGroup;
}
private findSideBySideGroup(): IEditorGroup {
const direction = preferredSideBySideGroupDirection(this.configurationService);
let neighbourGroup = this.editorGroupService.findGroup({ direction });
if (!neighbourGroup) {
neighbourGroup = this.editorGroupService.addGroup(this.editorGroupService.activeGroup, direction);
}
return neighbourGroup;
}
private toOptions(options?: IEditorOptions | EditorOptions): EditorOptions {
if (!options || options instanceof EditorOptions) {
return options as EditorOptions;
}
const textOptions: ITextEditorOptions = options;
if (!!textOptions.selection) {
return TextEditorOptions.create(options);
}
return EditorOptions.create(options);
}
//#endregion
//#region openEditors()
openEditors(editors: IEditorInputWithOptions[], group?: IEditorGroup | GroupIdentifier | SIDE_GROUP_TYPE | ACTIVE_GROUP_TYPE): TPromise<IEditor[]>;
openEditors(editors: IResourceEditor[], group?: IEditorGroup | GroupIdentifier | SIDE_GROUP_TYPE | ACTIVE_GROUP_TYPE): TPromise<IEditor[]>;
openEditors(editors: (IEditorInputWithOptions | IResourceEditor)[], group?: IEditorGroup | GroupIdentifier | SIDE_GROUP_TYPE | ACTIVE_GROUP_TYPE): TPromise<IEditor[]> {
// Convert to typed editors and options
const typedEditors: IEditorInputWithOptions[] = [];
editors.forEach(editor => {
if (isEditorInputWithOptions(editor)) {
typedEditors.push(editor);
} else {
typedEditors.push({ editor: this.createInput(editor), options: TextEditorOptions.from(editor) });
}
});
// Find target groups to open
const mapGroupToEditors = new Map<IEditorGroup, IEditorInputWithOptions[]>();
if (group === SIDE_GROUP) {
mapGroupToEditors.set(this.findSideBySideGroup(), typedEditors);
} else {
typedEditors.forEach(typedEditor => {
const targetGroup = this.findTargetGroup(typedEditor.editor, typedEditor.options, group);
let targetGroupEditors = mapGroupToEditors.get(targetGroup);
if (!targetGroupEditors) {
targetGroupEditors = [];
mapGroupToEditors.set(targetGroup, targetGroupEditors);
}
targetGroupEditors.push(typedEditor);
});
}
// Open in targets
const result: TPromise<IEditor>[] = [];
mapGroupToEditors.forEach((editorsWithOptions, group) => {
result.push((group.openEditors(editorsWithOptions)).then(() => group.activeControl));
});
return TPromise.join(result);
}
//#endregion
//#region isOpen()
isOpen(editor: IEditorInput | IResourceInput | IUntitledResourceInput, group?: IEditorGroup | GroupIdentifier): boolean {
let groups: IEditorGroup[] = [];
if (typeof group === 'number') {
groups.push(this.editorGroupService.getGroup(group));
} else if (group) {
groups.push(group);
} else {
groups = [...this.editorGroupService.groups];
}
return groups.some(group => {
if (editor instanceof EditorInput) {
return group.isOpened(editor);
}
const resourceInput = editor as IResourceInput | IUntitledResourceInput;
if (!resourceInput.resource) {
return false;
}
return group.editors.some(editorInGroup => {
const resource = toResource(editorInGroup, { supportSideBySide: true });
return resource && resource.toString() === resourceInput.resource.toString();
});
});
}
//#endregion
//#region replaceEditors()
replaceEditors(editors: IResourceEditorReplacement[], group: IEditorGroup | GroupIdentifier): TPromise<void>;
replaceEditors(editors: IEditorReplacement[], group: IEditorGroup | GroupIdentifier): TPromise<void>;
replaceEditors(editors: (IEditorReplacement | IResourceEditorReplacement)[], group: IEditorGroup | GroupIdentifier): TPromise<void> {
const typedEditors: IEditorReplacement[] = [];
editors.forEach(replaceEditorArg => {
if (replaceEditorArg.editor instanceof EditorInput) {
typedEditors.push(replaceEditorArg as IEditorReplacement);
} else {
const editor = replaceEditorArg.editor as IResourceEditor;
const typedEditor = this.createInput(editor);
const replacementEditor = this.createInput(replaceEditorArg.replacement as IResourceEditor);
typedEditors.push({
editor: typedEditor,
replacement: replacementEditor,
options: this.toOptions(editor.options)
});
}
});
const targetGroup = typeof group === 'number' ? this.editorGroupService.getGroup(group) : group;
return targetGroup.replaceEditors(typedEditors);
}
//#endregion
//#region invokeWithinEditorContext()
invokeWithinEditorContext<T>(fn: (accessor: ServicesAccessor) => T): T {
const activeTextEditorWidget = this.activeTextEditorWidget;
if (isCodeEditor(activeTextEditorWidget)) {
return activeTextEditorWidget.invokeWithinContext(fn);
}
const activeGroup = this.editorGroupService.activeGroup;
if (activeGroup) {
return activeGroup.invokeWithinContext(fn);
}
return this.instantiationService.invokeFunction(fn);
}
//#endregion
//#region createInput()
createInput(input: IEditorInputWithOptions | IEditorInput | IResourceEditor): EditorInput {
// Typed Editor Input Support (EditorInput)
if (input instanceof EditorInput) {
return input;
}
// Typed Editor Input Support (IEditorInputWithOptions)
const editorInputWithOptions = input as IEditorInputWithOptions;
if (editorInputWithOptions.editor instanceof EditorInput) {
return editorInputWithOptions.editor;
}
// Side by Side Support
const resourceSideBySideInput = <IResourceSideBySideInput>input;
if (resourceSideBySideInput.masterResource && resourceSideBySideInput.detailResource) {
const masterInput = this.createInput({ resource: resourceSideBySideInput.masterResource, forceFile: resourceSideBySideInput.forceFile });
const detailInput = this.createInput({ resource: resourceSideBySideInput.detailResource, forceFile: resourceSideBySideInput.forceFile });
return new SideBySideEditorInput(
resourceSideBySideInput.label || masterInput.getName(),
typeof resourceSideBySideInput.description === 'string' ? resourceSideBySideInput.description : masterInput.getDescription(),
detailInput,
masterInput
);
}
// Diff Editor Support
const resourceDiffInput = <IResourceDiffInput>input;
if (resourceDiffInput.leftResource && resourceDiffInput.rightResource) {
const leftInput = this.createInput({ resource: resourceDiffInput.leftResource, forceFile: resourceDiffInput.forceFile });
const rightInput = this.createInput({ resource: resourceDiffInput.rightResource, forceFile: resourceDiffInput.forceFile });
const label = resourceDiffInput.label || localize('compareLabels', "{0} β {1}", this.toDiffLabel(leftInput), this.toDiffLabel(rightInput));
return new DiffEditorInput(label, resourceDiffInput.description, leftInput, rightInput);
}
// Untitled file support
const untitledInput = <IUntitledResourceInput>input;
if (!untitledInput.resource || typeof untitledInput.filePath === 'string' || (untitledInput.resource instanceof URI && untitledInput.resource.scheme === Schemas.untitled)) {
return this.untitledEditorService.createOrGet(
untitledInput.filePath ? URI.file(untitledInput.filePath) : untitledInput.resource,
untitledInput.language,
untitledInput.contents,
untitledInput.encoding
);
}
// Resource Editor Support
const resourceInput = <IResourceInput>input;
if (resourceInput.resource instanceof URI) {
let label = resourceInput.label;
if (!label && resourceInput.resource.scheme !== Schemas.data) {
label = basename(resourceInput.resource.fsPath); // derive the label from the path (but not for data URIs)
}
return this.createOrGet(resourceInput.resource, this.instantiationService, label, resourceInput.description, resourceInput.encoding, resourceInput.forceFile) as EditorInput;
}
return null;
}
private createOrGet(resource: URI, instantiationService: IInstantiationService, label: string, description: string, encoding?: string, forceFile?: boolean): ICachedEditorInput {
if (EditorService.CACHE.has(resource)) {
const input = EditorService.CACHE.get(resource);
if (input instanceof ResourceEditorInput) {
input.setName(label);
input.setDescription(description);
} else if (!(input instanceof DataUriEditorInput)) {
input.setPreferredEncoding(encoding);
}
return input;
}
let input: ICachedEditorInput;
// File
if (forceFile /* fix for https://github.com/Microsoft/vscode/issues/48275 */ || this.fileService.canHandleResource(resource)) {
input = this.fileInputFactory.createFileInput(resource, encoding, instantiationService);
}
// Data URI
else if (resource.scheme === Schemas.data) {
input = instantiationService.createInstance(DataUriEditorInput, label, description, resource);
}
// Resource
else {
input = instantiationService.createInstance(ResourceEditorInput, label, description, resource);
}
EditorService.CACHE.set(resource, input);
once(input.onDispose)(() => {
EditorService.CACHE.delete(resource);
});
return input;
}
private toDiffLabel(input: EditorInput): string {
const res = input.getResource();
// Do not try to extract any paths from simple untitled editors
if (res.scheme === Schemas.untitled && !this.untitledEditorService.hasAssociatedFilePath(res)) {
return input.getName();
}
// Otherwise: for diff labels prefer to see the path as part of the label
return this.labelService.getUriLabel(res, true);
}
//#endregion
}
export interface IEditorOpenHandler {
(group: IEditorGroup, editor: IEditorInput, options?: IEditorOptions | ITextEditorOptions): TPromise<IEditor>;
}
/**
* The delegating workbench editor service can be used to override the behaviour of the openEditor()
* method by providing a IEditorOpenHandler.
*/
export class DelegatingEditorService extends EditorService {
private editorOpenHandler: IEditorOpenHandler;
constructor(
@IEditorGroupsService editorGroupService: EditorGroupsServiceImpl,
@IUntitledEditorService untitledEditorService: IUntitledEditorService,
@IInstantiationService instantiationService: IInstantiationService,
@ILabelService labelService: ILabelService,
@IFileService fileService: IFileService,
@IConfigurationService configurationService: IConfigurationService
) {
super(
editorGroupService,
untitledEditorService,
instantiationService,
labelService,
fileService,
configurationService
);
}
setEditorOpenHandler(handler: IEditorOpenHandler): void {
this.editorOpenHandler = handler;
}
protected doOpenEditor(group: IEditorGroup, editor: IEditorInput, options?: IEditorOptions): TPromise<IEditor> {
const handleOpen = this.editorOpenHandler ? this.editorOpenHandler(group, editor, options) : TPromise.as(void 0);
return handleOpen.then(control => {
if (control) {
return TPromise.as<IEditor>(control); // the opening was handled, so return early
}
return super.doOpenEditor(group, editor, options);
});
}
}
| src/vs/workbench/services/editor/browser/editorService.ts | 0 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.0010062006767839193,
0.00020138655963819474,
0.00016552692977711558,
0.00017230708908755332,
0.00011788589472416788
]
|
{
"id": 1,
"code_window": [
"\t\tsuper();\n",
"\n",
"\t\tthis.options = options;\n",
"\t\tthis.lookupKeybindings = typeof this.options.getKeyBinding === 'function';\n",
"\n",
"\t\tthis.toggleMenuAction = this._register(new ToggleMenuAction(() => this.toggleMenuActionItem && this.toggleMenuActionItem.show()));\n",
"\n",
"\t\tlet element = document.createElement('div');\n",
"\t\telement.className = 'monaco-toolbar';\n",
"\t\tcontainer.appendChild(element);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis.toggleMenuAction = this._register(new ToggleMenuAction(() => this.toggleMenuActionItem && this.toggleMenuActionItem.show(), options.toggleMenuTitle));\n"
],
"file_path": "src/vs/base/browser/ui/toolbar/toolbar.ts",
"type": "replace",
"edit_start_line_idx": 43
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Event, Emitter } from 'vs/base/common/event';
import { CONTEXT_EXPRESSION_SELECTED, IViewModel, IStackFrame, IDebugSession, IThread, IExpression, IFunctionBreakpoint, CONTEXT_BREAKPOINT_SELECTED, CONTEXT_LOADED_SCRIPTS_SUPPORTED } from 'vs/workbench/parts/debug/common/debug';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
export class ViewModel implements IViewModel {
firstSessionStart = true;
private _focusedStackFrame: IStackFrame;
private _focusedSession: IDebugSession;
private _focusedThread: IThread;
private selectedExpression: IExpression;
private selectedFunctionBreakpoint: IFunctionBreakpoint;
private readonly _onDidFocusSession: Emitter<IDebugSession | undefined>;
private readonly _onDidFocusStackFrame: Emitter<{ stackFrame: IStackFrame, explicit: boolean }>;
private readonly _onDidSelectExpression: Emitter<IExpression>;
private multiSessionView: boolean;
private expressionSelectedContextKey: IContextKey<boolean>;
private breakpointSelectedContextKey: IContextKey<boolean>;
private loadedScriptsSupportedContextKey: IContextKey<boolean>;
constructor(contextKeyService: IContextKeyService) {
this._onDidFocusSession = new Emitter<IDebugSession | undefined>();
this._onDidFocusStackFrame = new Emitter<{ stackFrame: IStackFrame, explicit: boolean }>();
this._onDidSelectExpression = new Emitter<IExpression>();
this.multiSessionView = false;
this.expressionSelectedContextKey = CONTEXT_EXPRESSION_SELECTED.bindTo(contextKeyService);
this.breakpointSelectedContextKey = CONTEXT_BREAKPOINT_SELECTED.bindTo(contextKeyService);
this.loadedScriptsSupportedContextKey = CONTEXT_LOADED_SCRIPTS_SUPPORTED.bindTo(contextKeyService);
}
getId(): string {
return 'root';
}
get focusedSession(): IDebugSession {
return this._focusedSession;
}
get focusedThread(): IThread {
if (this._focusedStackFrame) {
return this._focusedStackFrame.thread;
}
if (this._focusedSession) {
const threads = this._focusedSession.getAllThreads();
if (threads && threads.length) {
return threads[threads.length - 1];
}
}
return undefined;
}
get focusedStackFrame(): IStackFrame {
return this._focusedStackFrame;
}
setFocus(stackFrame: IStackFrame, thread: IThread, session: IDebugSession, explicit: boolean): void {
const shouldEmit = this._focusedSession !== session || this._focusedThread !== thread || this._focusedStackFrame !== stackFrame;
this._focusedStackFrame = stackFrame;
this._focusedThread = thread;
if (this._focusedSession !== session) {
this._focusedSession = session;
this._onDidFocusSession.fire(session);
}
this.loadedScriptsSupportedContextKey.set(session && session.capabilities.supportsLoadedSourcesRequest);
if (shouldEmit) {
this._onDidFocusStackFrame.fire({ stackFrame, explicit });
}
}
get onDidFocusSession(): Event<IDebugSession> {
return this._onDidFocusSession.event;
}
get onDidFocusStackFrame(): Event<{ stackFrame: IStackFrame, explicit: boolean }> {
return this._onDidFocusStackFrame.event;
}
getSelectedExpression(): IExpression {
return this.selectedExpression;
}
setSelectedExpression(expression: IExpression) {
this.selectedExpression = expression;
this.expressionSelectedContextKey.set(!!expression);
this._onDidSelectExpression.fire(expression);
}
get onDidSelectExpression(): Event<IExpression> {
return this._onDidSelectExpression.event;
}
getSelectedFunctionBreakpoint(): IFunctionBreakpoint {
return this.selectedFunctionBreakpoint;
}
setSelectedFunctionBreakpoint(functionBreakpoint: IFunctionBreakpoint): void {
this.selectedFunctionBreakpoint = functionBreakpoint;
this.breakpointSelectedContextKey.set(!!functionBreakpoint);
}
isMultiSessionView(): boolean {
return this.multiSessionView;
}
setMultiSessionView(isMultiSessionView: boolean): void {
this.multiSessionView = isMultiSessionView;
}
}
| src/vs/workbench/parts/debug/common/debugViewModel.ts | 0 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.00017560906417202204,
0.0001722269953461364,
0.00016827606305014342,
0.0001727923663565889,
0.000001948098997672787
]
|
{
"id": 2,
"code_window": [
"\tstatic readonly ID = 'toolbar.toggle.more';\n",
"\n",
"\tprivate _menuActions: IAction[];\n",
"\tprivate toggleDropdownMenu: () => void;\n",
"\n",
"\tconstructor(toggleDropdownMenu: () => void) {\n",
"\t\tsuper(ToggleMenuAction.ID, nls.localize('moreActions', \"More Actions...\"), null, true);\n",
"\n",
"\t\tthis.toggleDropdownMenu = toggleDropdownMenu;\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tconstructor(toggleDropdownMenu: () => void, title?: string) {\n",
"\t\ttitle = title || nls.localize('moreActions', \"More Actions...\");\n",
"\t\tsuper(ToggleMenuAction.ID, title, null, true);\n"
],
"file_path": "src/vs/base/browser/ui/toolbar/toolbar.ts",
"type": "replace",
"edit_start_line_idx": 172
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import 'vs/css!./toolbar';
import * as nls from 'vs/nls';
import { TPromise } from 'vs/base/common/winjs.base';
import { Action, IActionRunner, IAction } from 'vs/base/common/actions';
import { ActionBar, ActionsOrientation, IActionItemProvider } from 'vs/base/browser/ui/actionbar/actionbar';
import { IContextMenuProvider, DropdownMenuActionItem } from 'vs/base/browser/ui/dropdown/dropdown';
import { ResolvedKeybinding } from 'vs/base/common/keyCodes';
import { Disposable } from 'vs/base/common/lifecycle';
export const CONTEXT = 'context.toolbar';
export interface IToolBarOptions {
orientation?: ActionsOrientation;
actionItemProvider?: IActionItemProvider;
ariaLabel?: string;
getKeyBinding?: (action: IAction) => ResolvedKeybinding;
actionRunner?: IActionRunner;
}
/**
* A widget that combines an action bar for primary actions and a dropdown for secondary actions.
*/
export class ToolBar extends Disposable {
private options: IToolBarOptions;
private actionBar: ActionBar;
private toggleMenuAction: ToggleMenuAction;
private toggleMenuActionItem: DropdownMenuActionItem;
private hasSecondaryActions: boolean;
private lookupKeybindings: boolean;
constructor(container: HTMLElement, contextMenuProvider: IContextMenuProvider, options: IToolBarOptions = { orientation: ActionsOrientation.HORIZONTAL }) {
super();
this.options = options;
this.lookupKeybindings = typeof this.options.getKeyBinding === 'function';
this.toggleMenuAction = this._register(new ToggleMenuAction(() => this.toggleMenuActionItem && this.toggleMenuActionItem.show()));
let element = document.createElement('div');
element.className = 'monaco-toolbar';
container.appendChild(element);
this.actionBar = this._register(new ActionBar(element, {
orientation: options.orientation,
ariaLabel: options.ariaLabel,
actionRunner: options.actionRunner,
actionItemProvider: (action: Action) => {
// Return special action item for the toggle menu action
if (action.id === ToggleMenuAction.ID) {
// Dispose old
if (this.toggleMenuActionItem) {
this.toggleMenuActionItem.dispose();
}
// Create new
this.toggleMenuActionItem = new DropdownMenuActionItem(
action,
(<ToggleMenuAction>action).menuActions,
contextMenuProvider,
this.options.actionItemProvider,
this.actionRunner,
this.options.getKeyBinding,
'toolbar-toggle-more'
);
this.toggleMenuActionItem.setActionContext(this.actionBar.context);
return this.toggleMenuActionItem;
}
return options.actionItemProvider ? options.actionItemProvider(action) : null;
}
}));
}
set actionRunner(actionRunner: IActionRunner) {
this.actionBar.actionRunner = actionRunner;
}
get actionRunner(): IActionRunner {
return this.actionBar.actionRunner;
}
set context(context: any) {
this.actionBar.context = context;
if (this.toggleMenuActionItem) {
this.toggleMenuActionItem.setActionContext(context);
}
}
getContainer(): HTMLElement {
return this.actionBar.getContainer();
}
getItemsWidth(): number {
let itemsWidth = 0;
for (let i = 0; i < this.actionBar.length(); i++) {
itemsWidth += this.actionBar.getWidth(i);
}
return itemsWidth;
}
setAriaLabel(label: string): void {
this.actionBar.setAriaLabel(label);
}
setActions(primaryActions: IAction[], secondaryActions?: IAction[]): () => void {
return () => {
let primaryActionsToSet = primaryActions ? primaryActions.slice(0) : [];
// Inject additional action to open secondary actions if present
this.hasSecondaryActions = secondaryActions && secondaryActions.length > 0;
if (this.hasSecondaryActions) {
this.toggleMenuAction.menuActions = secondaryActions.slice(0);
primaryActionsToSet.push(this.toggleMenuAction);
}
this.actionBar.clear();
primaryActionsToSet.forEach(action => {
this.actionBar.push(action, { icon: true, label: false, keybinding: this.getKeybindingLabel(action) });
});
};
}
private getKeybindingLabel(action: IAction): string {
const key = this.lookupKeybindings ? this.options.getKeyBinding(action) : void 0;
return key ? key.getLabel() : void 0;
}
addPrimaryAction(primaryAction: IAction): () => void {
return () => {
// Add after the "..." action if we have secondary actions
if (this.hasSecondaryActions) {
let itemCount = this.actionBar.length();
this.actionBar.push(primaryAction, { icon: true, label: false, index: itemCount, keybinding: this.getKeybindingLabel(primaryAction) });
}
// Otherwise just add to the end
else {
this.actionBar.push(primaryAction, { icon: true, label: false, keybinding: this.getKeybindingLabel(primaryAction) });
}
};
}
dispose(): void {
if (this.toggleMenuActionItem) {
this.toggleMenuActionItem.dispose();
this.toggleMenuActionItem = void 0;
}
super.dispose();
}
}
class ToggleMenuAction extends Action {
static readonly ID = 'toolbar.toggle.more';
private _menuActions: IAction[];
private toggleDropdownMenu: () => void;
constructor(toggleDropdownMenu: () => void) {
super(ToggleMenuAction.ID, nls.localize('moreActions', "More Actions..."), null, true);
this.toggleDropdownMenu = toggleDropdownMenu;
}
run(): TPromise<any> {
this.toggleDropdownMenu();
return TPromise.as(true);
}
get menuActions() {
return this._menuActions;
}
set menuActions(actions: IAction[]) {
this._menuActions = actions;
}
} | src/vs/base/browser/ui/toolbar/toolbar.ts | 1 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.9981191754341125,
0.14871159195899963,
0.00016719552513677627,
0.0018652959261089563,
0.34184396266937256
]
|
{
"id": 2,
"code_window": [
"\tstatic readonly ID = 'toolbar.toggle.more';\n",
"\n",
"\tprivate _menuActions: IAction[];\n",
"\tprivate toggleDropdownMenu: () => void;\n",
"\n",
"\tconstructor(toggleDropdownMenu: () => void) {\n",
"\t\tsuper(ToggleMenuAction.ID, nls.localize('moreActions', \"More Actions...\"), null, true);\n",
"\n",
"\t\tthis.toggleDropdownMenu = toggleDropdownMenu;\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tconstructor(toggleDropdownMenu: () => void, title?: string) {\n",
"\t\ttitle = title || nls.localize('moreActions', \"More Actions...\");\n",
"\t\tsuper(ToggleMenuAction.ID, title, null, true);\n"
],
"file_path": "src/vs/base/browser/ui/toolbar/toolbar.ts",
"type": "replace",
"edit_start_line_idx": 172
} | {
"name": "json",
"displayName": "%displayName%",
"description": "%description%",
"version": "1.0.0",
"publisher": "vscode",
"engines": {
"vscode": "0.10.x"
},
"scripts": {
"update-grammar": "node ./build/update-grammars.js"
},
"contributes": {
"languages": [
{
"id": "json",
"aliases": [
"JSON",
"json"
],
"extensions": [
".json",
".bowerrc",
".jshintrc",
".jscsrc",
".eslintrc",
".babelrc",
".webmanifest",
".js.map",
".css.map"
],
"filenames": [
".watchmanconfig",
".ember-cli"
],
"mimetypes": [
"application/json",
"application/manifest+json"
],
"configuration": "./language-configuration.json"
},
{
"id": "jsonc",
"aliases": [
"JSON with Comments"
],
"extensions": [
".jsonc"
],
"configuration": "./language-configuration.json"
}
],
"grammars": [
{
"language": "json",
"scopeName": "source.json",
"path": "./syntaxes/JSON.tmLanguage.json"
},
{
"language": "jsonc",
"scopeName": "source.json.comments",
"path": "./syntaxes/JSONC.tmLanguage.json"
}
],
"jsonValidation": [
{
"fileMatch": "*.schema.json",
"url": "http://json-schema.org/draft-07/schema#"
}
]
}
}
| extensions/json/package.json | 0 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.00017616382683627307,
0.00017461745301261544,
0.0001722243905533105,
0.00017478950030636042,
0.0000012294379985178239
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.