hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 0, "code_window": [ " type: 'CheckboxControl',\n", " label: t('Legend'),\n", " renderTrigger: true,\n", " default: true,\n", " description: t('Whether to display the legend (toggles)'),\n", " },\n", " },\n", " {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " default: false,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-heatmap/src/controlPanel.ts", "type": "replace", "edit_start_line_idx": 194 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """allow_dml Revision ID: 65903709c321 Revises: 4500485bde7d Create Date: 2016-09-15 08:48:27.284752 """ import logging import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "65903709c321" down_revision = "4500485bde7d" def upgrade(): op.add_column("dbs", sa.Column("allow_dml", sa.Boolean(), nullable=True)) def downgrade(): try: op.drop_column("dbs", "allow_dml") except Exception as ex: logging.exception(ex) pass
superset/migrations/versions/65903709c321_allow_dml.py
0
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.00017475600179750472, 0.00017157886759378016, 0.0001672618673183024, 0.0001720034924801439, 0.000002448048462611041 ]
{ "id": 0, "code_window": [ " type: 'CheckboxControl',\n", " label: t('Legend'),\n", " renderTrigger: true,\n", " default: true,\n", " description: t('Whether to display the legend (toggles)'),\n", " },\n", " },\n", " {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " default: false,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-heatmap/src/controlPanel.ts", "type": "replace", "edit_start_line_idx": 194 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Add implicit tags Revision ID: c82ee8a39623 Revises: c18bd4186f15 Create Date: 2018-07-26 11:10:23.653524 """ # revision identifiers, used by Alembic. revision = "c82ee8a39623" down_revision = "c617da68de7d" from datetime import datetime from alembic import op from flask_appbuilder.models.mixins import AuditMixin from sqlalchemy import Column, DateTime, Enum, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base, declared_attr from superset.models.tags import ObjectTypes, TagTypes Base = declarative_base() class AuditMixinNullable(AuditMixin): """Altering the AuditMixin to use nullable fields Allows creating objects programmatically outside of CRUD """ created_on = Column(DateTime, default=datetime.now, nullable=True) changed_on = Column( DateTime, default=datetime.now, onupdate=datetime.now, nullable=True ) @declared_attr def created_by_fk(self) -> Column: return Column( Integer, ForeignKey("ab_user.id"), default=self.get_user_id, nullable=True, ) @declared_attr def changed_by_fk(self) -> Column: return Column( Integer, ForeignKey("ab_user.id"), default=self.get_user_id, onupdate=self.get_user_id, nullable=True, ) class Tag(Base, AuditMixinNullable): """A tag attached to an object (query, chart or dashboard).""" __tablename__ = "tag" id = Column(Integer, primary_key=True) name = Column(String(250), unique=True) type = Column(Enum(TagTypes)) class TaggedObject(Base, AuditMixinNullable): __tablename__ = "tagged_object" id = Column(Integer, primary_key=True) tag_id = Column(Integer, ForeignKey("tag.id")) object_id = Column(Integer) object_type = Column(Enum(ObjectTypes)) class User(Base): """Declarative class to do query in upgrade""" __tablename__ = "ab_user" id = Column(Integer, primary_key=True) def upgrade(): bind = op.get_bind() Tag.__table__.create(bind) TaggedObject.__table__.create(bind) def downgrade(): op.drop_table("tagged_object") op.drop_table("tag")
superset/migrations/versions/c82ee8a39623_add_implicit_tags.py
0
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.0035538075026124716, 0.00047787762014195323, 0.00016454592696391046, 0.00017123486031778157, 0.0009726982680149376 ]
{ "id": 1, "code_window": [ " normalized: PropTypes.bool,\n", " binCount: PropTypes.number,\n", " opacity: PropTypes.number,\n", " xAxisLabel: PropTypes.string,\n", " yAxisLabel: PropTypes.string,\n", "};\n", "const defaultProps = {\n", " binCount: 15,\n", " className: '',\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " showLegend: PropTypes.bool,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/Histogram.jsx", "type": "add", "edit_start_line_idx": 44 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { t, validateNonEmpty } from '@superset-ui/core'; import { ControlPanelConfig, columnChoices, formatSelectOptions, sections, } from '@superset-ui/chart-controls'; const config: ControlPanelConfig = { controlPanelSections: [ sections.legacyRegularTime, { label: t('Query'), expanded: true, controlSetRows: [ [ { name: 'all_columns_x', config: { type: 'SelectControl', label: t('Columns'), default: null, description: t('Select the numeric columns to draw the histogram'), mapStateToProps: state => ({ choices: columnChoices(state.datasource), }), multi: true, validators: [validateNonEmpty], }, }, ], ['adhoc_filters'], ['row_limit'], ['groupby'], ], }, { label: t('Chart Options'), expanded: true, controlSetRows: [ ['color_scheme', 'label_colors'], [ { name: 'link_length', config: { type: 'SelectControl', renderTrigger: true, freeForm: true, label: t('No of Bins'), default: 5, choices: formatSelectOptions(['10', '25', '50', '75', '100', '150', '200', '250']), description: t('Select the number of bins for the histogram'), }, }, ], [ { name: 'x_axis_label', config: { type: 'TextControl', label: t('X Axis Label'), renderTrigger: true, default: '', }, }, { name: 'y_axis_label', config: { type: 'TextControl', label: t('Y Axis Label'), renderTrigger: true, default: '', }, }, ], [ { name: 'normalized', config: { type: 'CheckboxControl', label: t('Normalized'), renderTrigger: true, description: t('Whether to normalize the histogram'), default: false, }, }, ], ], }, ], }; export default config;
superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/controlPanel.ts
1
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.0001790551032172516, 0.0001709931530058384, 0.00016665166185703129, 0.00017059690435416996, 0.0000040179093048209324 ]
{ "id": 1, "code_window": [ " normalized: PropTypes.bool,\n", " binCount: PropTypes.number,\n", " opacity: PropTypes.number,\n", " xAxisLabel: PropTypes.string,\n", " yAxisLabel: PropTypes.string,\n", "};\n", "const defaultProps = {\n", " binCount: 15,\n", " className: '',\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " showLegend: PropTypes.bool,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/Histogram.jsx", "type": "add", "edit_start_line_idx": 44 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import { render, screen } from 'spec/helpers/testing-library'; import userEvent from '@testing-library/user-event'; import { Ellipsis } from './Ellipsis'; test('Ellipsis - click when the button is enabled', () => { const click = jest.fn(); render(<Ellipsis onClick={click} />); expect(click).toBeCalledTimes(0); userEvent.click(screen.getByRole('button')); expect(click).toBeCalledTimes(1); }); test('Ellipsis - click when the button is disabled', () => { const click = jest.fn(); render(<Ellipsis onClick={click} disabled />); expect(click).toBeCalledTimes(0); userEvent.click(screen.getByRole('button')); expect(click).toBeCalledTimes(0); });
superset-frontend/src/components/Pagination/Ellipsis.test.tsx
0
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.00017769887926988304, 0.00017557991668581963, 0.00017445166304241866, 0.00017508456949144602, 0.000001285349867430341 ]
{ "id": 1, "code_window": [ " normalized: PropTypes.bool,\n", " binCount: PropTypes.number,\n", " opacity: PropTypes.number,\n", " xAxisLabel: PropTypes.string,\n", " yAxisLabel: PropTypes.string,\n", "};\n", "const defaultProps = {\n", " binCount: 15,\n", " className: '',\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " showLegend: PropTypes.bool,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/Histogram.jsx", "type": "add", "edit_start_line_idx": 44 }
import CategoricalScheme from '../../CategoricalScheme'; const schemes = [ { id: 'echarts4Colors', label: 'ECharts v4.x Colors', colors: [ '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83', '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3', ], }, { id: 'echarts5Colors', label: 'ECharts v5.x Colors', colors: [ '#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE', '#3BA272', '#FC8452', '#9A60B4', '#EA7CCC', ], }, ].map(s => new CategoricalScheme(s)); export default schemes;
superset-frontend/temporary_superset_ui/superset-ui/packages/superset-ui-core/src/color/colorSchemes/categorical/echarts.ts
0
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.00017472633044235408, 0.0001732678065309301, 0.00017187446064781398, 0.00017323519568890333, 0.0000013415924513537902 ]
{ "id": 1, "code_window": [ " normalized: PropTypes.bool,\n", " binCount: PropTypes.number,\n", " opacity: PropTypes.number,\n", " xAxisLabel: PropTypes.string,\n", " yAxisLabel: PropTypes.string,\n", "};\n", "const defaultProps = {\n", " binCount: 15,\n", " className: '',\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " showLegend: PropTypes.bool,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/Histogram.jsx", "type": "add", "edit_start_line_idx": 44 }
--- name: Teradata menu: Connecting to Databases route: /docs/databases/teradata index: 25 version: 1 --- ## Teradata The recommended connector library is [sqlalchemy-teradata](https://github.com/Teradata/sqlalchemy-teradata). The connection string for Teradata looks like this: ``` teradata://{user}:{password}@{host} ``` Note: Its required to have Teradata ODBC drivers installed and environment variables configured for proper work of sqlalchemy dialect. Teradata ODBC Drivers available here: https://downloads.teradata.com/download/connectivity/odbc-driver/linux Required environment variables: ``` export ODBCINI=/.../teradata/client/ODBC_64/odbc.ini export ODBCINST=/.../teradata/client/ODBC_64/odbcinst.ini ```
docs/src/pages/docs/Connecting to Databases/teradata.mdx
0
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.0001734695106279105, 0.00016774704272393137, 0.00016338039131369442, 0.00016639125533401966, 0.0000042289652810723055 ]
{ "id": 2, "code_window": [ " normalized,\n", " opacity,\n", " xAxisLabel,\n", " yAxisLabel,\n", " } = this.props;\n", "\n", " const colorFn = CategoricalColorNamespace.getScale(colorScheme);\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " showLegend,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/Histogram.jsx", "type": "add", "edit_start_line_idx": 68 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { t, validateNonEmpty } from '@superset-ui/core'; import { ControlPanelConfig, columnChoices, formatSelectOptions, sections, } from '@superset-ui/chart-controls'; const config: ControlPanelConfig = { controlPanelSections: [ sections.legacyRegularTime, { label: t('Query'), expanded: true, controlSetRows: [ [ { name: 'all_columns_x', config: { type: 'SelectControl', label: t('Columns'), default: null, description: t('Select the numeric columns to draw the histogram'), mapStateToProps: state => ({ choices: columnChoices(state.datasource), }), multi: true, validators: [validateNonEmpty], }, }, ], ['adhoc_filters'], ['row_limit'], ['groupby'], ], }, { label: t('Chart Options'), expanded: true, controlSetRows: [ ['color_scheme', 'label_colors'], [ { name: 'link_length', config: { type: 'SelectControl', renderTrigger: true, freeForm: true, label: t('No of Bins'), default: 5, choices: formatSelectOptions(['10', '25', '50', '75', '100', '150', '200', '250']), description: t('Select the number of bins for the histogram'), }, }, ], [ { name: 'x_axis_label', config: { type: 'TextControl', label: t('X Axis Label'), renderTrigger: true, default: '', }, }, { name: 'y_axis_label', config: { type: 'TextControl', label: t('Y Axis Label'), renderTrigger: true, default: '', }, }, ], [ { name: 'normalized', config: { type: 'CheckboxControl', label: t('Normalized'), renderTrigger: true, description: t('Whether to normalize the histogram'), default: false, }, }, ], ], }, ], }; export default config;
superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/controlPanel.ts
1
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.0001777356374077499, 0.0001705290051177144, 0.00016291510837618262, 0.00017053696501534432, 0.000004820962658413919 ]
{ "id": 2, "code_window": [ " normalized,\n", " opacity,\n", " xAxisLabel,\n", " yAxisLabel,\n", " } = this.props;\n", "\n", " const colorFn = CategoricalColorNamespace.getScale(colorScheme);\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " showLegend,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/Histogram.jsx", "type": "add", "edit_start_line_idx": 68 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """add impersonate_user to dbs Revision ID: a9c47e2c1547 Revises: ca69c70ec99b Create Date: 2017-08-31 17:35:58.230723 """ # revision identifiers, used by Alembic. revision = "a9c47e2c1547" down_revision = "ca69c70ec99b" import sqlalchemy as sa from alembic import op def upgrade(): op.add_column("dbs", sa.Column("impersonate_user", sa.Boolean(), nullable=True)) def downgrade(): op.drop_column("dbs", "impersonate_user")
superset/migrations/versions/a9c47e2c1547_add_impersonate_user_to_dbs.py
0
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.00017691256653051823, 0.00017589342314749956, 0.00017495172505732626, 0.00017585468594916165, 8.458323463855777e-7 ]
{ "id": 2, "code_window": [ " normalized,\n", " opacity,\n", " xAxisLabel,\n", " yAxisLabel,\n", " } = this.props;\n", "\n", " const colorFn = CategoricalColorNamespace.getScale(colorScheme);\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " showLegend,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/Histogram.jsx", "type": "add", "edit_start_line_idx": 68 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import { t, validateNonEmpty } from '@superset-ui/core'; import { formatSelectOptionsForRange, ColumnOption, columnChoices, ControlPanelConfig, sections, SelectControlConfig, ColumnMeta, } from '@superset-ui/chart-controls'; const config: ControlPanelConfig = { controlPanelSections: [ sections.legacyRegularTime, { label: t('Event definition'), controlSetRows: [ ['entity'], [ { name: 'all_columns_x', config: { type: 'SelectControl', label: t('Event Names'), description: t('Columns to display'), mapStateToProps: state => ({ choices: columnChoices(state?.datasource), }), // choices is from `mapStateToProps` default: (control: { choices?: string[] }) => control.choices && control.choices.length > 0 ? control.choices[0][0] : null, validators: [validateNonEmpty], }, }, ], ['row_limit'], [ { name: 'order_by_entity', config: { type: 'CheckboxControl', label: t('Order by entity id'), description: t( 'Important! Select this if the table is not already sorted by entity id, ' + 'else there is no guarantee that all events for each entity are returned.', ), default: true, }, }, ], [ { name: 'min_leaf_node_event_count', config: { type: 'SelectControl', freeForm: false, label: t('Minimum leaf node event count'), default: 1, choices: formatSelectOptionsForRange(1, 10), description: t( 'Leaf nodes that represent fewer than this number of events will be initially ' + 'hidden in the visualization', ), }, }, ], ], }, { label: t('Query'), expanded: true, controlSetRows: [['adhoc_filters']], }, { label: t('Additional metadata'), controlSetRows: [ [ { name: 'all_columns', // eslint-disable-next-line @typescript-eslint/consistent-type-assertions config: { type: 'SelectControl', multi: true, label: t('Metadata'), default: [], description: t('Select any columns for metadata inspection'), optionRenderer: c => <ColumnOption showType column={c} />, valueRenderer: c => <ColumnOption column={c} />, valueKey: 'column_name', allowAll: true, mapStateToProps: state => ({ options: state.datasource ? state.datasource.columns : [], }), commaChoosesOption: false, freeForm: true, } as SelectControlConfig<ColumnMeta>, }, ], ], }, ], controlOverrides: { entity: { label: t('Entity ID'), description: t('e.g., a "user id" column'), }, row_limit: { label: t('Max Events'), description: t('The maximum number of events to return, equivalent to the number of rows'), }, }, }; export default config;
superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-event-flow/src/controlPanel.tsx
0
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.00017871208547148854, 0.00017219933215528727, 0.00016717863036319613, 0.00017194086103700101, 0.00000314567614623229 ]
{ "id": 2, "code_window": [ " normalized,\n", " opacity,\n", " xAxisLabel,\n", " yAxisLabel,\n", " } = this.props;\n", "\n", " const colorFn = CategoricalColorNamespace.getScale(colorScheme);\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " showLegend,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/Histogram.jsx", "type": "add", "edit_start_line_idx": 68 }
/* eslint-disable jsx-a11y/label-has-associated-control */ import React from 'react'; import { formatTime } from '@superset-ui/core'; const propTypes = {}; const defaultProps = {}; class TimeFormatValidator extends React.PureComponent { constructor(props) { super(props); this.state = { formatString: '%Y-%m-%d %H:%M:%S', testValues: [ new Date(Date.UTC(1986, 5, 14, 8, 30, 53)), new Date(Date.UTC(2001, 9, 27, 13, 45, 2, 678)), new Date(Date.UTC(2009, 1, 1, 0, 0, 0)), new Date(Date.UTC(2018, 1, 1, 10, 20, 33)), 0, null, undefined, ], }; this.handleFormatChange = this.handleFormatChange.bind(this); } handleFormatChange(event) { this.setState({ formatString: event.target.value, }); } render() { const { formatString, testValues } = this.state; return ( <div className="container"> <div className="row" style={{ margin: '40px 20px 0 20px' }}> <div className="col-sm"> <p> This <code>@superset-ui/time-format</code> package enriches <code>d3-time-format</code> to handle invalid formats as well as edge case values. Use the validator below to preview outputs from the specified format string. See <a href="https://github.com/d3/d3-time-format#locale_format" target="_blank" rel="noopener noreferrer" > D3 Time Format Reference </a> for how to write a D3 time format string. </p> </div> </div> <div className="row" style={{ margin: '10px 0 30px 0' }}> <div className="col-sm" /> <div className="col-sm-8"> <div className="form"> <div className="form-group"> <label>Enter D3 time format string:&nbsp;&nbsp;</label> <input id="formatString" className="form-control form-control-lg" type="text" value={formatString} onChange={this.handleFormatChange} /> </div> </div> </div> <div className="col-sm" /> </div> <div className="row"> <div className="col-sm"> <table className="table table-striped table-sm"> <thead> <tr> <th>Input (time)</th> <th>Formatted output (string)</th> </tr> </thead> <tbody> {testValues.map(v => ( <tr key={v}> <td> <code>{v instanceof Date ? v.toUTCString() : `${v}`}</code> </td> <td> <code>&quot;{formatTime(formatString, v)}&quot;</code> </td> </tr> ))} </tbody> </table> </div> </div> </div> ); } } TimeFormatValidator.propTypes = propTypes; TimeFormatValidator.defaultProps = defaultProps; export default { title: 'Core Packages|@superset-ui/time-format', }; export const validator = () => <TimeFormatValidator />;
superset-frontend/temporary_superset_ui/superset-ui/packages/superset-ui-demo/storybook/stories/superset-ui-time-format/TimeFormatStories.jsx
0
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.00018555736460257322, 0.00017150446365121752, 0.00016528168634977192, 0.0001698240521363914, 0.000005322127435647417 ]
{ "id": 3, "code_window": [ " <WithLegend\n", " className={`superset-legacy-chart-histogram ${className}`}\n", " width={width}\n", " height={height}\n", " position=\"top\"\n", " renderLegend={({ direction, style }) => (\n", " <LegendOrdinal\n", " style={style}\n", " scale={colorScale}\n", " direction={direction}\n", " shape=\"rect\"\n", " labelMargin=\"0 15px 0 0\"\n", " />\n", " )}\n", " renderChart={parent => (\n", " <Histogram\n", " width={parent.width}\n", " height={parent.height}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " renderLegend={({ direction, style }) =>\n", " showLegend && (\n", " <LegendOrdinal\n", " style={style}\n", " scale={colorScale}\n", " direction={direction}\n", " shape=\"rect\"\n", " labelMargin=\"0 15px 0 0\"\n", " />\n", " )\n", " }\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/Histogram.jsx", "type": "replace", "edit_start_line_idx": 83 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ export default function transformProps(chartProps) { const { width, height, formData, queriesData } = chartProps; const { colorScheme, linkLength, normalized, globalOpacity, xAxisLabel, yAxisLabel } = formData; return { width, height, data: queriesData[0].data, binCount: parseInt(linkLength, 10), colorScheme, normalized, opacity: globalOpacity, xAxisLabel, yAxisLabel, }; }
superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/transformProps.js
1
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.0009109952370636165, 0.0003546219377312809, 0.0001608843303984031, 0.00017330409900750965, 0.00032128760358318686 ]
{ "id": 3, "code_window": [ " <WithLegend\n", " className={`superset-legacy-chart-histogram ${className}`}\n", " width={width}\n", " height={height}\n", " position=\"top\"\n", " renderLegend={({ direction, style }) => (\n", " <LegendOrdinal\n", " style={style}\n", " scale={colorScale}\n", " direction={direction}\n", " shape=\"rect\"\n", " labelMargin=\"0 15px 0 0\"\n", " />\n", " )}\n", " renderChart={parent => (\n", " <Histogram\n", " width={parent.width}\n", " height={parent.height}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " renderLegend={({ direction, style }) =>\n", " showLegend && (\n", " <LegendOrdinal\n", " style={style}\n", " scale={colorScale}\n", " direction={direction}\n", " shape=\"rect\"\n", " labelMargin=\"0 15px 0 0\"\n", " />\n", " )\n", " }\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/Histogram.jsx", "type": "replace", "edit_start_line_idx": 83 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { rgb } from 'd3-color'; export default function transformProps(chartProps) { const { width, height, formData, queriesData } = chartProps; const { maxBubbleSize, showBubbles, linearColorScheme, colorPicker } = formData; const { r, g, b } = colorPicker; return { data: queriesData[0].data, width, height, maxBubbleSize: parseInt(maxBubbleSize, 10), showBubbles, linearColorScheme, color: rgb(r, g, b).hex(), }; }
superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-world-map/src/transformProps.js
0
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.000983823323622346, 0.00037779746344313025, 0.000171324034454301, 0.00017802129150368273, 0.0003499005688354373 ]
{ "id": 3, "code_window": [ " <WithLegend\n", " className={`superset-legacy-chart-histogram ${className}`}\n", " width={width}\n", " height={height}\n", " position=\"top\"\n", " renderLegend={({ direction, style }) => (\n", " <LegendOrdinal\n", " style={style}\n", " scale={colorScale}\n", " direction={direction}\n", " shape=\"rect\"\n", " labelMargin=\"0 15px 0 0\"\n", " />\n", " )}\n", " renderChart={parent => (\n", " <Histogram\n", " width={parent.width}\n", " height={parent.height}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " renderLegend={({ direction, style }) =>\n", " showLegend && (\n", " <LegendOrdinal\n", " style={style}\n", " scale={colorScale}\n", " direction={direction}\n", " shape=\"rect\"\n", " labelMargin=\"0 15px 0 0\"\n", " />\n", " )\n", " }\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/Histogram.jsx", "type": "replace", "edit_start_line_idx": 83 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { getChartControlPanelRegistry, t } from '@superset-ui/core'; import { ControlConfig, ControlPanelState, CustomControlItem, DatasourceMeta, } from '@superset-ui/chart-controls'; import { getControlConfig, getControlState, applyMapStateToPropsToControl, findControlItem, } from 'src/explore/controlUtils'; import { controlPanelSectionsChartOptions, controlPanelSectionsChartOptionsOnlyColorScheme, controlPanelSectionsChartOptionsTable, } from 'spec/javascripts/explore/fixtures'; const getKnownControlConfig = (controlKey: string, vizType: string) => getControlConfig(controlKey, vizType) as ControlConfig; const getKnownControlState = (...args: Parameters<typeof getControlState>) => getControlState(...args) as Exclude<ReturnType<typeof getControlState>, null>; describe('controlUtils', () => { const state: ControlPanelState = { datasource: { columns: [{ column_name: 'a' }], metrics: [{ metric_name: 'first' }, { metric_name: 'second' }], } as unknown as DatasourceMeta, controls: {}, form_data: { datasource: '1__table', viz_type: 'table' }, }; beforeAll(() => { getChartControlPanelRegistry() .registerValue('test-chart', { controlPanelSections: controlPanelSectionsChartOptions, }) .registerValue('test-chart-override', { controlPanelSections: controlPanelSectionsChartOptionsOnlyColorScheme, controlOverrides: { color_scheme: { label: t('My beautiful colors'), }, }, }) .registerValue('table', { controlPanelSections: controlPanelSectionsChartOptionsTable, }); }); afterAll(() => { getChartControlPanelRegistry() .remove('test-chart') .remove('test-chart-override'); }); describe('getControlConfig', () => { it('returns a valid spatial controlConfig', () => { const spatialControl = getControlConfig('color_scheme', 'test-chart'); expect(spatialControl?.type).toEqual('ColorSchemeControl'); }); it('overrides according to vizType', () => { let control = getKnownControlConfig('color_scheme', 'test-chart'); expect(control.label).toEqual('Color Scheme'); control = getKnownControlConfig('color_scheme', 'test-chart-override'); expect(control.label).toEqual('My beautiful colors'); }); it( 'returns correct control config when control config is defined ' + 'in the control panel definition', () => { const roseAreaProportionControlConfig = getControlConfig( 'rose_area_proportion', 'test-chart', ); expect(roseAreaProportionControlConfig).toEqual({ type: 'CheckboxControl', label: t('Use Area Proportions'), description: t( 'Check if the Rose Chart should use segment area instead of ' + 'segment radius for proportioning', ), default: false, renderTrigger: true, }); }, ); }); describe('applyMapStateToPropsToControl,', () => { it('applies state to props as expected', () => { let control = getKnownControlConfig('all_columns', 'table'); control = applyMapStateToPropsToControl(control, state); expect(control.options).toEqual([{ column_name: 'a' }]); }); }); describe('getControlState', () => { it('to still have the functions', () => { const control = getKnownControlState('metrics', 'table', state, 'a'); expect(typeof control.mapStateToProps).toBe('function'); expect(typeof control.validators?.[0]).toBe('function'); }); it('to make sure value is array', () => { const control = getKnownControlState('all_columns', 'table', state, 'a'); expect(control.value).toEqual(['a']); }); it('removes missing/invalid choice', () => { let control = getControlState( 'stacked_style', 'test-chart', state, 'stack', ); expect(control?.value).toBe('stack'); control = getControlState('stacked_style', 'test-chart', state, 'FOO'); expect(control?.value).toBeNull(); }); it('returns null for non-existent field', () => { const control = getControlState('NON_EXISTENT', 'table', state); expect(control).toBeNull(); }); it('metrics control should be empty by default', () => { const control = getControlState('metrics', 'table', state); expect(control?.default).toBeUndefined(); }); it('metric control should be empty by default', () => { const control = getControlState('metric', 'table', state); expect(control?.default).toBeUndefined(); }); it('should not apply mapStateToProps when initializing', () => { const control = getControlState('metrics', 'table', { ...state, controls: undefined, }); expect(control?.value).toBe(undefined); }); }); describe('validateControl', () => { it('validates the control, returns an error if empty', () => { const control = getControlState('metric', 'table', state, null); expect(control?.validationErrors).toEqual(['cannot be empty']); }); it('should not validate if control panel is initializing', () => { const control = getControlState( 'metric', 'table', { ...state, controls: undefined }, undefined, ); expect(control?.validationErrors).toBeUndefined(); }); }); describe('findControlItem', () => { it('find control as a string', () => { const controlItem = findControlItem( controlPanelSectionsChartOptions, 'color_scheme', ); expect(controlItem).toEqual('color_scheme'); }); it('find control as a control object', () => { let controlItem = findControlItem( controlPanelSectionsChartOptions, 'rose_area_proportion', ) as CustomControlItem; expect(controlItem.name).toEqual('rose_area_proportion'); expect(controlItem).toHaveProperty('config'); controlItem = findControlItem( controlPanelSectionsChartOptions, 'stacked_style', ) as CustomControlItem; expect(controlItem.name).toEqual('stacked_style'); expect(controlItem).toHaveProperty('config'); }); it('returns null when key is not found', () => { const controlItem = findControlItem( controlPanelSectionsChartOptions, 'non_existing_key', ); expect(controlItem).toBeNull(); }); }); });
superset-frontend/spec/javascripts/explore/controlUtils_spec.tsx
0
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.0001790086826076731, 0.00017184732132591307, 0.00016439129831269383, 0.0001716888800729066, 0.0000032897012260946212 ]
{ "id": 3, "code_window": [ " <WithLegend\n", " className={`superset-legacy-chart-histogram ${className}`}\n", " width={width}\n", " height={height}\n", " position=\"top\"\n", " renderLegend={({ direction, style }) => (\n", " <LegendOrdinal\n", " style={style}\n", " scale={colorScale}\n", " direction={direction}\n", " shape=\"rect\"\n", " labelMargin=\"0 15px 0 0\"\n", " />\n", " )}\n", " renderChart={parent => (\n", " <Histogram\n", " width={parent.width}\n", " height={parent.height}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " renderLegend={({ direction, style }) =>\n", " showLegend && (\n", " <LegendOrdinal\n", " style={style}\n", " scale={colorScale}\n", " direction={direction}\n", " shape=\"rect\"\n", " labelMargin=\"0 15px 0 0\"\n", " />\n", " )\n", " }\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/Histogram.jsx", "type": "replace", "edit_start_line_idx": 83 }
#!/bin/bash # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # set -eo pipefail if [ "${#}" -ne 0 ]; then exec "${@}" else gunicorn \ --bind "0.0.0.0:${SUPERSET_PORT}" \ --access-logfile '-' \ --error-logfile '-' \ --workers 1 \ --worker-class gthread \ --threads 20 \ --timeout ${GUNICORN_TIMEOUT:-60} \ --limit-request-line 0 \ --limit-request-field_size 0 \ "${FLASK_APP}" fi
docker/docker-entrypoint.sh
0
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.00018220704805571586, 0.00017625287000555545, 0.0001710640062810853, 0.00017587022739462554, 0.000004484131750359666 ]
{ "id": 4, "code_window": [ " expanded: true,\n", " controlSetRows: [\n", " ['color_scheme', 'label_colors'],\n", " [\n", " {\n", " name: 'link_length',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " [\n", " {\n", " name: 'show_legend',\n", " config: {\n", " type: 'CheckboxControl',\n", " label: t('Legend'),\n", " renderTrigger: true,\n", " default: false,\n", " description: t('Whether to display the legend (toggles)'),\n", " },\n", " },\n", " ],\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/controlPanel.ts", "type": "add", "edit_start_line_idx": 59 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* eslint-disable react/sort-prop-types */ import PropTypes from 'prop-types'; import React from 'react'; import { Histogram, BarSeries, XAxis, YAxis } from '@data-ui/histogram'; import { chartTheme } from '@data-ui/theme'; import { LegendOrdinal } from '@vx/legend'; import { scaleOrdinal } from '@vx/scale'; import { CategoricalColorNamespace, styled } from '@superset-ui/core'; import WithLegend from './WithLegend'; const propTypes = { className: PropTypes.string, data: PropTypes.arrayOf( PropTypes.shape({ key: PropTypes.string, values: PropTypes.arrayOf(PropTypes.number), }), ).isRequired, width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, colorScheme: PropTypes.string, normalized: PropTypes.bool, binCount: PropTypes.number, opacity: PropTypes.number, xAxisLabel: PropTypes.string, yAxisLabel: PropTypes.string, }; const defaultProps = { binCount: 15, className: '', colorScheme: '', normalized: false, opacity: 1, xAxisLabel: '', yAxisLabel: '', }; class CustomHistogram extends React.PureComponent { render() { const { className, data, width, height, binCount, colorScheme, normalized, opacity, xAxisLabel, yAxisLabel, } = this.props; const colorFn = CategoricalColorNamespace.getScale(colorScheme); const keys = data.map(d => d.key); const colorScale = scaleOrdinal({ domain: keys, range: keys.map(x => colorFn(x)), }); return ( <WithLegend className={`superset-legacy-chart-histogram ${className}`} width={width} height={height} position="top" renderLegend={({ direction, style }) => ( <LegendOrdinal style={style} scale={colorScale} direction={direction} shape="rect" labelMargin="0 15px 0 0" /> )} renderChart={parent => ( <Histogram width={parent.width} height={parent.height} ariaLabel="Histogram" normalized={normalized} binCount={binCount} binType="numeric" margin={{ top: 20, right: 20 }} renderTooltip={({ datum, color }) => ( <div> <strong style={{ color }}> {datum.bin0} to {datum.bin1} </strong> <div> <strong>count </strong> {datum.count} </div> <div> <strong>cumulative </strong> {datum.cumulative} </div> </div> )} valueAccessor={datum => datum} theme={chartTheme} > {data.map(series => ( <BarSeries key={series.key} animated rawData={series.values} fill={colorScale(series.key)} fillOpacity={opacity} /> ))} <XAxis label={xAxisLabel} /> <YAxis label={yAxisLabel} /> </Histogram> )} /> ); } } CustomHistogram.propTypes = propTypes; CustomHistogram.defaultProps = defaultProps; export default styled(CustomHistogram)` .superset-legacy-chart-histogram { overflow: hidden; } `;
superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/Histogram.jsx
1
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.0002014969359152019, 0.00017297585145570338, 0.000166688856552355, 0.00017113513604272157, 0.000007976611414051149 ]
{ "id": 4, "code_window": [ " expanded: true,\n", " controlSetRows: [\n", " ['color_scheme', 'label_colors'],\n", " [\n", " {\n", " name: 'link_length',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " [\n", " {\n", " name: 'show_legend',\n", " config: {\n", " type: 'CheckboxControl',\n", " label: t('Legend'),\n", " renderTrigger: true,\n", " default: false,\n", " description: t('Whether to display the legend (toggles)'),\n", " },\n", " },\n", " ],\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/controlPanel.ts", "type": "add", "edit_start_line_idx": 59 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* eslint-disable no-param-reassign */ import { CHART_TYPE } from './componentTypes'; export default function getLayoutComponentFromChartId(layout, chartId) { return Object.values(layout).find( currentComponent => currentComponent && currentComponent.type === CHART_TYPE && currentComponent.meta && currentComponent.meta.chartId === chartId, ); }
superset-frontend/src/dashboard/util/getLayoutComponentFromChartId.js
0
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.00017340319755021483, 0.00017115435912273824, 0.0001676867832429707, 0.00017176373512484133, 0.0000021779337657790165 ]
{ "id": 4, "code_window": [ " expanded: true,\n", " controlSetRows: [\n", " ['color_scheme', 'label_colors'],\n", " [\n", " {\n", " name: 'link_length',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " [\n", " {\n", " name: 'show_legend',\n", " config: {\n", " type: 'CheckboxControl',\n", " label: t('Legend'),\n", " renderTrigger: true,\n", " default: false,\n", " description: t('Whether to display the legend (toggles)'),\n", " },\n", " },\n", " ],\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/controlPanel.ts", "type": "add", "edit_start_line_idx": 59 }
import CategoricalScheme from '../../CategoricalScheme'; const schemes = [ { id: 'echarts4Colors', label: 'ECharts v4.x Colors', colors: [ '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83', '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3', ], }, { id: 'echarts5Colors', label: 'ECharts v5.x Colors', colors: [ '#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE', '#3BA272', '#FC8452', '#9A60B4', '#EA7CCC', ], }, ].map(s => new CategoricalScheme(s)); export default schemes;
superset-frontend/temporary_superset_ui/superset-ui/packages/superset-ui-core/src/color/colorSchemes/categorical/echarts.ts
0
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.00019806972704827785, 0.0001761970779625699, 0.00016483047511428595, 0.00017094405484385788, 0.000012898322893306613 ]
{ "id": 4, "code_window": [ " expanded: true,\n", " controlSetRows: [\n", " ['color_scheme', 'label_colors'],\n", " [\n", " {\n", " name: 'link_length',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " [\n", " {\n", " name: 'show_legend',\n", " config: {\n", " type: 'CheckboxControl',\n", " label: t('Legend'),\n", " renderTrigger: true,\n", " default: false,\n", " description: t('Whether to display the legend (toggles)'),\n", " },\n", " },\n", " ],\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/controlPanel.ts", "type": "add", "edit_start_line_idx": 59 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { buildQueryContext, QueryFormData } from '@superset-ui/core'; /** * The buildQuery function is used to create an instance of QueryContext that's * sent to the chart data endpoint. In addition to containing information of which * datasource to use, it specifies the type (e.g. full payload, samples, query) and * format (e.g. CSV or JSON) of the result and whether or not to force refresh the data from * the datasource as opposed to using a cached copy of the data, if available. * * More importantly though, QueryContext contains a property `queries`, which is an array of * QueryObjects specifying individual data requests to be made. A QueryObject specifies which * columns, metrics and filters, among others, to use during the query. Usually it will be enough * to specify just one query based on the baseQueryObject, but for some more advanced use cases * it is possible to define post processing operations in the QueryObject, or multiple queries * if a viz needs multiple different result sets. */ export default function buildQuery(formData: QueryFormData) { return buildQueryContext(formData, () => [ { result_type: 'timegrains', columns: [], metrics: [], orderby: [], }, ]); }
superset-frontend/src/filters/components/TimeGrain/buildQuery.ts
0
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.00017252219549845904, 0.0001703287271084264, 0.00016538826457690448, 0.00017179302813019603, 0.0000026361974505562102 ]
{ "id": 5, "code_window": [ " * under the License.\n", " */\n", "export default function transformProps(chartProps) {\n", " const { width, height, formData, queriesData } = chartProps;\n", " const { colorScheme, linkLength, normalized, globalOpacity, xAxisLabel, yAxisLabel } = formData;\n", "\n", " return {\n", " width,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const {\n", " colorScheme,\n", " linkLength,\n", " normalized,\n", " globalOpacity,\n", " xAxisLabel,\n", " yAxisLabel,\n", " showLegend,\n", " } = formData;\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/transformProps.js", "type": "replace", "edit_start_line_idx": 20 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ export default function transformProps(chartProps) { const { width, height, formData, queriesData } = chartProps; const { colorScheme, linkLength, normalized, globalOpacity, xAxisLabel, yAxisLabel } = formData; return { width, height, data: queriesData[0].data, binCount: parseInt(linkLength, 10), colorScheme, normalized, opacity: globalOpacity, xAxisLabel, yAxisLabel, }; }
superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/transformProps.js
1
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.998136043548584, 0.5026132464408875, 0.0001756519341142848, 0.5060706734657288, 0.49496540427207947 ]
{ "id": 5, "code_window": [ " * under the License.\n", " */\n", "export default function transformProps(chartProps) {\n", " const { width, height, formData, queriesData } = chartProps;\n", " const { colorScheme, linkLength, normalized, globalOpacity, xAxisLabel, yAxisLabel } = formData;\n", "\n", " return {\n", " width,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const {\n", " colorScheme,\n", " linkLength,\n", " normalized,\n", " globalOpacity,\n", " xAxisLabel,\n", " yAxisLabel,\n", " showLegend,\n", " } = formData;\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/transformProps.js", "type": "replace", "edit_start_line_idx": 20 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React, { useCallback, useEffect, useMemo, useState } from 'react'; import { JsonObject, styled, t } from '@superset-ui/core'; import Collapse from 'src/components/Collapse'; import Tabs from 'src/components/Tabs'; import Loading from 'src/components/Loading'; import TableView, { EmptyWrapperType } from 'src/components/TableView'; import { getChartDataRequest } from 'src/chart/chartAction'; import { getClientErrorObject } from 'src/utils/getClientErrorObject'; import { getFromLocalStorage, setInLocalStorage, } from 'src/utils/localStorageHelpers'; import { CopyToClipboardButton, FilterInput, RowCount, useFilteredTableData, useTableColumns, } from 'src/explore/components/DataTableControl'; import { applyFormattingToTabularData } from 'src/utils/common'; const RESULT_TYPES = { results: 'results' as const, samples: 'samples' as const, }; const NULLISH_RESULTS_STATE = { [RESULT_TYPES.results]: undefined, [RESULT_TYPES.samples]: undefined, }; const DATA_TABLE_PAGE_SIZE = 50; const STORAGE_KEYS = { isOpen: 'is_datapanel_open', }; const DATAPANEL_KEY = 'data'; const TableControlsWrapper = styled.div` display: flex; align-items: center; span { flex-shrink: 0; } `; const SouthPane = styled.div` position: relative; background-color: ${({ theme }) => theme.colors.grayscale.light5}; z-index: 5; overflow: hidden; `; const TabsWrapper = styled.div<{ contentHeight: number }>` height: ${({ contentHeight }) => contentHeight}px; overflow: hidden; .table-condensed { height: 100%; overflow: auto; } `; const CollapseWrapper = styled.div` height: 100%; .collapse-inner { height: 100%; .ant-collapse-item { height: 100%; .ant-collapse-content { height: calc(100% - ${({ theme }) => theme.gridUnit * 8}px); .ant-collapse-content-box { padding-top: 0; height: 100%; } } } } `; const Error = styled.pre` margin-top: ${({ theme }) => `${theme.gridUnit * 4}px`}; `; interface DataTableProps { columnNames: string[]; filterText: string; data: object[] | undefined; isLoading: boolean; error: string | undefined; errorMessage: React.ReactElement | undefined; } const DataTable = ({ columnNames, filterText, data, isLoading, error, errorMessage, }: DataTableProps) => { // this is to preserve the order of the columns, even if there are integer values, // while also only grabbing the first column's keys const columns = useTableColumns(columnNames, data); const filteredData = useFilteredTableData(filterText, data); if (isLoading) { return <Loading />; } if (error) { return <Error>{error}</Error>; } if (data) { if (data.length === 0) { return <span>No data</span>; } return ( <TableView columns={columns} data={filteredData} pageSize={DATA_TABLE_PAGE_SIZE} noDataText={t('No data')} emptyWrapperType={EmptyWrapperType.Small} className="table-condensed" isPaginationSticky showRowCount={false} small /> ); } if (errorMessage) { return <Error>{errorMessage}</Error>; } return null; }; export const DataTablesPane = ({ queryFormData, tableSectionHeight, onCollapseChange, chartStatus, ownState, errorMessage, queriesResponse, }: { queryFormData: Record<string, any>; tableSectionHeight: number; chartStatus: string; ownState?: JsonObject; onCollapseChange: (openPanelName: string) => void; errorMessage?: JSX.Element; queriesResponse: Record<string, any>; }) => { const [data, setData] = useState<{ [RESULT_TYPES.results]?: Record<string, any>[]; [RESULT_TYPES.samples]?: Record<string, any>[]; }>(NULLISH_RESULTS_STATE); const [isLoading, setIsLoading] = useState({ [RESULT_TYPES.results]: true, [RESULT_TYPES.samples]: true, }); const [columnNames, setColumnNames] = useState<{ [RESULT_TYPES.results]: string[]; [RESULT_TYPES.samples]: string[]; }>({ [RESULT_TYPES.results]: [], [RESULT_TYPES.samples]: [], }); const [error, setError] = useState(NULLISH_RESULTS_STATE); const [filterText, setFilterText] = useState(''); const [activeTabKey, setActiveTabKey] = useState<string>( RESULT_TYPES.results, ); const [isRequestPending, setIsRequestPending] = useState<{ [RESULT_TYPES.results]?: boolean; [RESULT_TYPES.samples]?: boolean; }>(NULLISH_RESULTS_STATE); const [panelOpen, setPanelOpen] = useState( getFromLocalStorage(STORAGE_KEYS.isOpen, false), ); const formattedData = useMemo( () => ({ [RESULT_TYPES.results]: applyFormattingToTabularData( data[RESULT_TYPES.results], ), [RESULT_TYPES.samples]: applyFormattingToTabularData( data[RESULT_TYPES.samples], ), }), [data], ); const getData = useCallback( (resultType: string) => { setIsLoading(prevIsLoading => ({ ...prevIsLoading, [resultType]: true, })); return getChartDataRequest({ formData: queryFormData, resultFormat: 'json', resultType, ownState, }) .then(({ json }) => { // Only displaying the first query is currently supported if (json.result.length > 1) { const data: any[] = []; json.result.forEach((item: { data: any[] }) => { item.data.forEach((row, i) => { if (data[i] !== undefined) { data[i] = { ...data[i], ...row }; } else { data[i] = row; } }); }); setData(prevData => ({ ...prevData, [resultType]: data, })); } else { setData(prevData => ({ ...prevData, [resultType]: json.result[0].data, })); } const checkCols = json?.result[0]?.data?.length ? Object.keys(json.result[0].data[0]) : null; setColumnNames(prevColumnNames => ({ ...prevColumnNames, [resultType]: json.result[0].columns || checkCols, })); setIsLoading(prevIsLoading => ({ ...prevIsLoading, [resultType]: false, })); setError(prevError => ({ ...prevError, [resultType]: null, })); }) .catch(response => { getClientErrorObject(response).then(({ error, message }) => { setError(prevError => ({ ...prevError, [resultType]: error || message || t('Sorry, An error occurred'), })); setIsLoading(prevIsLoading => ({ ...prevIsLoading, [resultType]: false, })); }); }); }, [queryFormData, columnNames], ); useEffect(() => { setInLocalStorage(STORAGE_KEYS.isOpen, panelOpen); }, [panelOpen]); useEffect(() => { setIsRequestPending(prevState => ({ ...prevState, [RESULT_TYPES.results]: true, })); }, [queryFormData]); useEffect(() => { setIsRequestPending(prevState => ({ ...prevState, [RESULT_TYPES.samples]: true, })); }, [queryFormData?.adhoc_filters, queryFormData?.datasource]); useEffect(() => { if (queriesResponse && chartStatus === 'success') { const { colnames } = queriesResponse[0]; setColumnNames({ ...columnNames, [RESULT_TYPES.results]: [...colnames], }); } }, [queriesResponse]); useEffect(() => { if (panelOpen && isRequestPending[RESULT_TYPES.results]) { if (errorMessage) { setIsRequestPending(prevState => ({ ...prevState, [RESULT_TYPES.results]: false, })); setIsLoading(prevIsLoading => ({ ...prevIsLoading, [RESULT_TYPES.results]: false, })); return; } if (chartStatus === 'loading') { setIsLoading(prevIsLoading => ({ ...prevIsLoading, [RESULT_TYPES.results]: true, })); } else { setIsRequestPending(prevState => ({ ...prevState, [RESULT_TYPES.results]: false, })); getData(RESULT_TYPES.results); } } if ( panelOpen && isRequestPending[RESULT_TYPES.samples] && activeTabKey === RESULT_TYPES.samples ) { setIsRequestPending(prevState => ({ ...prevState, [RESULT_TYPES.samples]: false, })); getData(RESULT_TYPES.samples); } }, [ panelOpen, isRequestPending, getData, activeTabKey, chartStatus, errorMessage, ]); const TableControls = ( <TableControlsWrapper> <RowCount data={data[activeTabKey]} loading={isLoading[activeTabKey]} /> <CopyToClipboardButton data={formattedData[activeTabKey]} columns={columnNames[activeTabKey]} /> <FilterInput onChangeHandler={setFilterText} /> </TableControlsWrapper> ); const handleCollapseChange = (openPanelName: string) => { onCollapseChange(openPanelName); setPanelOpen(!!openPanelName); }; return ( <SouthPane data-test="some-purposeful-instance"> <TabsWrapper contentHeight={tableSectionHeight}> <CollapseWrapper data-test="data-tab"> <Collapse accordion bordered={false} defaultActiveKey={panelOpen ? DATAPANEL_KEY : undefined} onChange={handleCollapseChange} bold ghost className="collapse-inner" > <Collapse.Panel header={t('Data')} key={DATAPANEL_KEY}> <Tabs fullWidth={false} tabBarExtraContent={TableControls} activeKey={activeTabKey} onChange={setActiveTabKey} > <Tabs.TabPane tab={t('View results')} key={RESULT_TYPES.results} > <DataTable isLoading={isLoading[RESULT_TYPES.results]} data={data[RESULT_TYPES.results]} columnNames={columnNames[RESULT_TYPES.results]} filterText={filterText} error={error[RESULT_TYPES.results]} errorMessage={errorMessage} /> </Tabs.TabPane> <Tabs.TabPane tab={t('View samples')} key={RESULT_TYPES.samples} > <DataTable isLoading={isLoading[RESULT_TYPES.samples]} data={data[RESULT_TYPES.samples]} columnNames={columnNames[RESULT_TYPES.samples]} filterText={filterText} error={error[RESULT_TYPES.samples]} errorMessage={errorMessage} /> </Tabs.TabPane> </Tabs> </Collapse.Panel> </Collapse> </CollapseWrapper> </TabsWrapper> </SouthPane> ); };
superset-frontend/src/explore/components/DataTablesPane/index.tsx
0
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.00929295551031828, 0.0003934042470064014, 0.00016673399659339339, 0.00017607180052436888, 0.0013736035907641053 ]
{ "id": 5, "code_window": [ " * under the License.\n", " */\n", "export default function transformProps(chartProps) {\n", " const { width, height, formData, queriesData } = chartProps;\n", " const { colorScheme, linkLength, normalized, globalOpacity, xAxisLabel, yAxisLabel } = formData;\n", "\n", " return {\n", " width,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const {\n", " colorScheme,\n", " linkLength,\n", " normalized,\n", " globalOpacity,\n", " xAxisLabel,\n", " yAxisLabel,\n", " showLegend,\n", " } = formData;\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/transformProps.js", "type": "replace", "edit_start_line_idx": 20 }
package-lock=false
superset-frontend/temporary_superset_ui/superset-ui/.npmrc
0
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.00017852355085778981, 0.00017852355085778981, 0.00017852355085778981, 0.00017852355085778981, 0 ]
{ "id": 5, "code_window": [ " * under the License.\n", " */\n", "export default function transformProps(chartProps) {\n", " const { width, height, formData, queriesData } = chartProps;\n", " const { colorScheme, linkLength, normalized, globalOpacity, xAxisLabel, yAxisLabel } = formData;\n", "\n", " return {\n", " width,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const {\n", " colorScheme,\n", " linkLength,\n", " normalized,\n", " globalOpacity,\n", " xAxisLabel,\n", " yAxisLabel,\n", " showLegend,\n", " } = formData;\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/transformProps.js", "type": "replace", "edit_start_line_idx": 20 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { sections } from '../src'; describe('@superset-ui/chart-controls', () => { it('exports sections', () => { expect(sections).toBeDefined(); expect(sections.datasourceAndVizType).toBeDefined(); }); });
superset-frontend/temporary_superset_ui/superset-ui/packages/superset-ui-chart-controls/test/index.test.ts
0
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.0001756519341142848, 0.00017462554387748241, 0.00017318873142357916, 0.00017503599519841373, 0.0000010466418416399392 ]
{ "id": 6, "code_window": [ " colorScheme,\n", " normalized,\n", " opacity: globalOpacity,\n", " xAxisLabel,\n", " yAxisLabel,\n", " };\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " showLegend,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/transformProps.js", "type": "add", "edit_start_line_idx": 32 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ export default function transformProps(chartProps) { const { width, height, formData, queriesData } = chartProps; const { colorScheme, linkLength, normalized, globalOpacity, xAxisLabel, yAxisLabel } = formData; return { width, height, data: queriesData[0].data, binCount: parseInt(linkLength, 10), colorScheme, normalized, opacity: globalOpacity, xAxisLabel, yAxisLabel, }; }
superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/transformProps.js
1
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.40072473883628845, 0.10138320922851562, 0.0001743417524266988, 0.0023168744519352913, 0.17283377051353455 ]
{ "id": 6, "code_window": [ " colorScheme,\n", " normalized,\n", " opacity: globalOpacity,\n", " xAxisLabel,\n", " yAxisLabel,\n", " };\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " showLegend,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/transformProps.js", "type": "add", "edit_start_line_idx": 32 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from flask_babel import lazy_gettext as _ from superset.commands.exceptions import CommandException class DatasetColumnNotFoundError(CommandException): message = _("Dataset column not found.") class DatasetColumnDeleteFailedError(CommandException): message = _("Dataset column delete failed.") class DatasetColumnForbiddenError(CommandException): message = _("Changing this dataset is forbidden.")
superset/datasets/columns/commands/exceptions.py
0
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.0007784835179336369, 0.0003263965481892228, 0.00017331559502054006, 0.00017689354717731476, 0.0002610172959975898 ]
{ "id": 6, "code_window": [ " colorScheme,\n", " normalized,\n", " opacity: globalOpacity,\n", " xAxisLabel,\n", " yAxisLabel,\n", " };\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " showLegend,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/transformProps.js", "type": "add", "edit_start_line_idx": 32 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ describe('Advanced analytics', () => { beforeEach(() => { cy.login(); cy.intercept('POST', '/superset/explore_json/**').as('postJson'); cy.intercept('GET', '/superset/explore_json/**').as('getJson'); }); it('Create custom time compare', () => { cy.visitChartByName('Num Births Trend'); cy.verifySliceSuccess({ waitAlias: '@postJson' }); cy.get('.ant-collapse-header').contains('Advanced Analytics').click(); cy.get('[data-test=time_compare]').find('.ant-select').click(); cy.get('[data-test=time_compare]') .find('input[type=search]') .type('28 days{enter}'); cy.get('[data-test=time_compare]') .find('input[type=search]') .type('1 year{enter}'); cy.get('button[data-test="run-query-button"]').click(); cy.wait('@postJson'); cy.reload(); cy.verifySliceSuccess({ waitAlias: '@postJson', chartSelector: 'svg', }); cy.get('.ant-collapse-header').contains('Advanced Analytics').click(); cy.get('[data-test=time_compare]') .find('.ant-select-selector') .contains('28 days'); cy.get('[data-test=time_compare]') .find('.ant-select-selector') .contains('1 year'); }); });
superset-frontend/cypress-base/cypress/integration/explore/advanced_analytics.test.ts
0
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.00017606845358386636, 0.00017485082207713276, 0.00017367508553434163, 0.00017477659275755286, 9.234453273165855e-7 ]
{ "id": 6, "code_window": [ " colorScheme,\n", " normalized,\n", " opacity: globalOpacity,\n", " xAxisLabel,\n", " yAxisLabel,\n", " };\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " showLegend,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/transformProps.js", "type": "add", "edit_start_line_idx": 32 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import { t } from '@superset-ui/core'; import { Radio } from 'src/components/Radio'; import { COMMON_RANGE_OPTIONS, COMMON_RANGE_SET, } from 'src/explore/components/controls/DateFilterControl/utils'; import { CommonRangeType, FrameComponentProps, } from 'src/explore/components/controls/DateFilterControl/types'; export function CommonFrame(props: FrameComponentProps) { let commonRange = 'Last week'; if (COMMON_RANGE_SET.has(props.value as CommonRangeType)) { commonRange = props.value; } else { props.onChange(commonRange); } return ( <> <div className="section-title">{t('Configure Time Range: Last...')}</div> <Radio.Group value={commonRange} onChange={(e: any) => props.onChange(e.target.value)} > {COMMON_RANGE_OPTIONS.map(({ value, label }) => ( <Radio key={value} value={value} className="vertical-radio"> {label} </Radio> ))} </Radio.Group> </> ); }
superset-frontend/src/explore/components/controls/DateFilterControl/components/CommonFrame.tsx
0
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.00017742611817084253, 0.0001726826885715127, 0.00016957057232502848, 0.0001718435960356146, 0.000002688241238502087 ]
{ "id": 0, "code_window": [ "import { hasProtocol, joinURL, parseURL } from 'ufo'\n", "import { useNuxtApp, useRuntimeConfig } from '../nuxt'\n", "import type { NuxtError } from './error'\n", "import { createError } from './error'\n", "import { useState } from './state'\n", "\n", "export const useRouter = () => {\n", " return useNuxtApp()?.$router as Router\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { setResponseStatus } from './ssr'\n" ], "file_path": "packages/nuxt/src/app/composables/router.ts", "type": "add", "edit_start_line_idx": 8 }
import { reactive, h, isReadonly } from 'vue' import { parseURL, stringifyParsedURL, parseQuery, stringifyQuery, withoutBase, isEqual, joinURL } from 'ufo' import { createError } from 'h3' import { defineNuxtPlugin, clearError, navigateTo, showError, useRuntimeConfig, useState } from '..' import { callWithNuxt } from '../nuxt' // @ts-ignore import { globalMiddleware } from '#build/middleware' interface Route { /** Percentage encoded pathname section of the URL. */ path: string /** The whole location including the `search` and `hash`. */ fullPath: string /** Object representation of the `search` property of the current location. */ query: Record<string, any> /** Hash of the current location. If present, starts with a `#`. */ hash: string /** Name of the matched record */ name: string | null | undefined /** Object of decoded params extracted from the `path`. */ params: Record<string, any> /** * The location we were initially trying to access before ending up * on the current location. */ redirectedFrom: Route | undefined /** Merged `meta` properties from all of the matched route records. */ meta: Record<string, any> } function getRouteFromPath (fullPath: string | Partial<Route>) { if (typeof fullPath === 'object') { fullPath = stringifyParsedURL({ pathname: fullPath.path || '', search: stringifyQuery(fullPath.query || {}), hash: fullPath.hash || '' }) } const url = parseURL(fullPath.toString()) return { path: url.pathname, fullPath, query: parseQuery(url.search), hash: url.hash, // stub properties for compat with vue-router params: {}, name: undefined, matched: [], redirectedFrom: undefined, meta: {}, href: fullPath } } type RouteGuardReturn = void | Error | string | false interface RouteGuard { (to: Route, from: Route): RouteGuardReturn | Promise<RouteGuardReturn> } interface RouterHooks { 'resolve:before': (to: Route, from: Route) => RouteGuardReturn | Promise<RouteGuardReturn> 'navigate:before': (to: Route, from: Route) => RouteGuardReturn | Promise<RouteGuardReturn> 'navigate:after': (to: Route, from: Route) => void | Promise<void> 'error': (err: any) => void | Promise<void> } interface Router { currentRoute: Route isReady: () => Promise<void> options: {} install: () => Promise<void> // Navigation push: (url: string) => Promise<void> replace: (url: string) => Promise<void> back: () => void go: (delta: number) => void forward: () => void // Guards beforeResolve: (guard: RouterHooks['resolve:before']) => () => void beforeEach: (guard: RouterHooks['navigate:before']) => () => void afterEach: (guard: RouterHooks['navigate:after']) => () => void onError: (handler: RouterHooks['error']) => () => void // Routes resolve: (url: string | Partial<Route>) => Route addRoute: (parentName: string, route: Route) => void getRoutes: () => any[] hasRoute: (name: string) => boolean removeRoute: (name: string) => void } export default defineNuxtPlugin<{ route: Route, router: Router }>((nuxtApp) => { const initialURL = process.client ? withoutBase(window.location.pathname, useRuntimeConfig().app.baseURL) + window.location.search + window.location.hash : nuxtApp.ssrContext!.url const routes: Route[] = [] const hooks: { [key in keyof RouterHooks]: RouterHooks[key][] } = { 'navigate:before': [], 'resolve:before': [], 'navigate:after': [], error: [] } const registerHook = <T extends keyof RouterHooks>(hook: T, guard: RouterHooks[T]) => { hooks[hook].push(guard) return () => hooks[hook].splice(hooks[hook].indexOf(guard), 1) } const baseURL = useRuntimeConfig().app.baseURL const route: Route = reactive(getRouteFromPath(initialURL)) async function handleNavigation (url: string | Partial<Route>, replace?: boolean): Promise<void> { try { // Resolve route const to = getRouteFromPath(url) // Run beforeEach hooks for (const middleware of hooks['navigate:before']) { const result = await middleware(to, route) // Cancel navigation if (result === false || result instanceof Error) { return } // Redirect if (result) { return handleNavigation(result, true) } } for (const handler of hooks['resolve:before']) { await handler(to, route) } // Perform navigation Object.assign(route, to) if (process.client) { window.history[replace ? 'replaceState' : 'pushState']({}, '', joinURL(baseURL, to.fullPath)) if (!nuxtApp.isHydrating) { // Clear any existing errors await callWithNuxt(nuxtApp, clearError) } } // Run afterEach hooks for (const middleware of hooks['navigate:after']) { await middleware(to, route) } } catch (err) { if (process.dev && !hooks.error.length) { console.warn('No error handlers registered to handle middleware errors. You can register an error handler with `router.onError()`', err) } for (const handler of hooks.error) { await handler(err) } } } const router: Router = { currentRoute: route, isReady: () => Promise.resolve(), // These options provide a similar API to vue-router but have no effect options: {}, install: () => Promise.resolve(), // Navigation push: (url: string) => handleNavigation(url, false), replace: (url: string) => handleNavigation(url, true), back: () => window.history.go(-1), go: (delta: number) => window.history.go(delta), forward: () => window.history.go(1), // Guards beforeResolve: (guard: RouterHooks['resolve:before']) => registerHook('resolve:before', guard), beforeEach: (guard: RouterHooks['navigate:before']) => registerHook('navigate:before', guard), afterEach: (guard: RouterHooks['navigate:after']) => registerHook('navigate:after', guard), onError: (handler: RouterHooks['error']) => registerHook('error', handler), // Routes resolve: getRouteFromPath, addRoute: (parentName: string, route: Route) => { routes.push(route) }, getRoutes: () => routes, hasRoute: (name: string) => routes.some(route => route.name === name), removeRoute: (name: string) => { const index = routes.findIndex(route => route.name === name) if (index !== -1) { routes.splice(index, 1) } } } nuxtApp.vueApp.component('RouterLink', { functional: true, props: { to: String, custom: Boolean, replace: Boolean, // Not implemented activeClass: String, exactActiveClass: String, ariaCurrentValue: String }, setup: (props, { slots }) => { const navigate = () => handleNavigation(props.to, props.replace) return () => { const route = router.resolve(props.to) return props.custom ? slots.default?.({ href: props.to, navigate, route }) : h('a', { href: props.to, onClick: (e: MouseEvent) => { e.preventDefault(); return navigate() } }, slots) } } }) if (process.client) { window.addEventListener('popstate', (event) => { const location = (event.target as Window).location router.replace(location.href.replace(location.origin, '')) }) } nuxtApp._route = route // Handle middleware nuxtApp._middleware = nuxtApp._middleware || { global: [], named: {} } const initialLayout = useState('_layout') nuxtApp.hooks.hookOnce('app:created', async () => { router.beforeEach(async (to, from) => { to.meta = reactive(to.meta || {}) if (nuxtApp.isHydrating && initialLayout.value && !isReadonly(to.meta.layout)) { to.meta.layout = initialLayout.value } nuxtApp._processingMiddleware = true const middlewareEntries = new Set<RouteGuard>([...globalMiddleware, ...nuxtApp._middleware.global]) for (const middleware of middlewareEntries) { const result = await callWithNuxt(nuxtApp, middleware, [to, from]) if (process.server) { if (result === false || result instanceof Error) { const error = result || createError({ statusCode: 404, statusMessage: `Page Not Found: ${initialURL}` }) return callWithNuxt(nuxtApp, showError, [error]) } } if (result || result === false) { return result } } }) router.afterEach(() => { delete nuxtApp._processingMiddleware }) await router.replace(initialURL) if (!isEqual(route.fullPath, initialURL)) { await callWithNuxt(nuxtApp, navigateTo, [route.fullPath]) } }) return { provide: { route, router } } })
packages/nuxt/src/app/plugins/router.ts
1
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.9519540667533875, 0.03664521127939224, 0.0001661965507082641, 0.0002420903620077297, 0.17955413460731506 ]
{ "id": 0, "code_window": [ "import { hasProtocol, joinURL, parseURL } from 'ufo'\n", "import { useNuxtApp, useRuntimeConfig } from '../nuxt'\n", "import type { NuxtError } from './error'\n", "import { createError } from './error'\n", "import { useState } from './state'\n", "\n", "export const useRouter = () => {\n", " return useNuxtApp()?.$router as Router\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { setResponseStatus } from './ssr'\n" ], "file_path": "packages/nuxt/src/app/composables/router.ts", "type": "add", "edit_start_line_idx": 8 }
export default defineNuxtRouteMiddleware((to) => { if ('middleware' in to.query) { return showError('error in middleware') } })
examples/app/error-handling/middleware/error.global.ts
0
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.0012415803503245115, 0.0012415803503245115, 0.0012415803503245115, 0.0012415803503245115, 0 ]
{ "id": 0, "code_window": [ "import { hasProtocol, joinURL, parseURL } from 'ufo'\n", "import { useNuxtApp, useRuntimeConfig } from '../nuxt'\n", "import type { NuxtError } from './error'\n", "import { createError } from './error'\n", "import { useState } from './state'\n", "\n", "export const useRouter = () => {\n", " return useNuxtApp()?.$router as Router\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { setResponseStatus } from './ssr'\n" ], "file_path": "packages/nuxt/src/app/composables/router.ts", "type": "add", "edit_start_line_idx": 8 }
<?xml version="1.0" encoding="utf-8"?> <!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="324px" height="60px" viewBox="-143 367 324 60" style="enable-background:new -143 367 324 60;" xml:space="preserve"> <style type="text/css"> .st0{fill:#FFFFFF;} </style> <g> <g> <path class="st0" d="M41.6,386.2c-1-1-2.2-1.5-3.5-1.5c-1.9,0-3.3,0.7-4.2,2c-0.9,1.3-1.3,3-1.3,5v14c0,0.6,0,1.1,0.1,1.6 c0.1,0.5,0.2,0.9,0.5,1.4l-5.2,0.1c0.3-0.5,0.5-1,0.6-1.7c0.1-0.7,0.2-1.4,0.2-2v-18.8c0-0.8,0-1.5-0.1-2.1 c-0.1-0.6-0.3-1.2-0.6-1.8h4.5v5.6c1.2-1.6,2.5-2.9,3.9-3.8c1.6-1.1,3.3-1.8,5.1-2L41.6,386.2L41.6,386.2z"/> <path class="st0" d="M43.8,391.4c-0.2,1.3-0.2,2.1-0.3,2.6c0,0.5,0,0.9,0,1.2c0,3.6,0.7,6.6,2.2,8.8c1.8,2.7,4.4,4,7.8,4 c1.5,0,3.1-0.3,4.6-0.9c1.5-0.6,2.9-1.4,4.1-2.5l-0.3,1.4c-1.6,1.2-3.1,2.1-4.5,2.6c-1.4,0.5-3.1,0.8-4.9,0.8 c-3.9,0-7.1-1.4-9.4-4c-2.4-2.7-3.5-6.1-3.5-10.1c0-3.9,1.2-7.2,3.7-9.8c2.5-2.6,5.6-3.9,9.5-3.9c2.9,0,5.4,0.9,7.5,2.6 c2.1,1.8,3.3,4.1,3.6,7L43.8,391.4L43.8,391.4z M56.8,390.8c1.7,0,2.6-0.8,2.6-2.5c0-1.7-0.7-3.2-2-4.3c-1.4-1.1-2.9-1.7-4.7-1.7 c-2.3,0-4.3,0.8-5.9,2.5c-1.4,1.5-2.4,3.5-2.9,5.9L56.8,390.8L56.8,390.8z"/> <path class="st0" d="M65.9,403.3v-17c0-1-0.1-1.7-0.2-2.1c-0.1-0.5-0.3-0.9-0.6-1.4h5v22.4c0,1,0,1.7,0.1,2.1s0.3,1,0.6,1.5h-5.9 c0.4-0.6,0.6-1.2,0.8-1.7c0.1-0.5,0.2-1.2,0.2-2C65.9,404.3,65.9,403.7,65.9,403.3z M68.1,370.6c0.8,0,1.5,0.2,2.1,0.7 c0.6,0.5,0.9,1.1,0.9,1.9c0,0.8-0.3,1.4-0.9,1.8c-0.6,0.4-1.3,0.7-2.1,0.7c-0.8,0-1.4-0.2-2.1-0.7c-0.6-0.5-0.9-1.1-0.9-1.8 c0-0.8,0.3-1.4,0.9-1.9C66.6,370.9,67.3,370.6,68.1,370.6z"/> <path class="st0" d="M73.7,403.5V386c0-1.1,0-1.8-0.1-2.2c-0.1-0.4-0.2-0.9-0.4-1.5h4.3v4.5c1.5-1.6,2.9-2.9,4.2-3.6 c1.7-1,3.5-1.4,5.4-1.4h1.8c2.6,0.3,4.4,1.1,5.4,2.3c1,1.2,1.5,3.1,1.5,5.7v15.3c0,0.5,0,1,0,1.7c0,0.7,0.2,1.3,0.5,2h-4.7 c0.2-2.1,0.3-4.3,0.3-6.4v-11.1c0-2.3-0.4-4.2-1.3-5.5c-1-1.6-2.6-2.4-4.9-2.4c-0.7,0-1.5,0.1-2.4,0.3c-2.2,0.5-3.8,1.3-4.7,2.7 c-0.9,1.3-1.4,3.2-1.4,5.5v13.7c0,0.6,0,1.1,0.1,1.7c0.1,0.5,0.2,1.1,0.5,1.6h-5.1c0.2-0.4,0.4-0.9,0.6-1.5 c0.1-0.6,0.2-1.4,0.2-2.5C73.7,404.2,73.7,403.8,73.7,403.5z"/> <path class="st0" d="M101.8,382.3l-0.1,0.7c0,0.5,0.1,1,0.2,1.5c0.1,0.6,0.3,1.2,0.6,1.8l7,19.3l7-19.3c0.3-0.8,0.4-1.5,0.4-2.2 c0-0.6-0.2-1.2-0.5-1.9h3.2c-0.9,1-1.6,2.2-2.1,3.6l-8.5,22.9h-2.5l-8.4-22.9c-0.3-0.7-0.5-1.4-0.8-2c-0.3-0.6-0.7-1.1-1.2-1.7 H101.8z"/> <path class="st0" d="M122.7,391.4c-0.2,1.3-0.2,2.1-0.3,2.6c0,0.5,0,0.9,0,1.2c0,3.6,0.7,6.6,2.2,8.8c1.8,2.7,4.4,4,7.8,4 c1.5,0,3.1-0.3,4.6-0.9c1.5-0.6,2.9-1.4,4.1-2.5l-0.3,1.4c-1.6,1.2-3.1,2.1-4.5,2.6c-1.4,0.5-3.1,0.8-4.9,0.8 c-3.9,0-7.1-1.4-9.4-4c-2.4-2.7-3.5-6.1-3.5-10.1c0-3.9,1.2-7.2,3.7-9.8c2.5-2.6,5.6-3.9,9.5-3.9c2.9,0,5.4,0.9,7.5,2.6 c2.1,1.8,3.3,4.1,3.6,7L122.7,391.4L122.7,391.4z M135.8,390.8c1.7,0,2.6-0.8,2.6-2.5c0-1.7-0.7-3.2-2-4.3 c-1.4-1.1-2.9-1.7-4.7-1.7c-2.3,0-4.3,0.8-5.9,2.5c-1.4,1.5-2.4,3.5-2.9,5.9L135.8,390.8L135.8,390.8z"/> <path class="st0" d="M144.6,403.5V386c0-1.1,0-1.8-0.1-2.2c-0.1-0.4-0.2-0.9-0.4-1.5h4.3v4.5c1.5-1.6,2.9-2.9,4.2-3.6 c1.6-1,3.5-1.4,5.4-1.4h1.8c2.6,0.3,4.4,1.1,5.4,2.3c1,1.2,1.5,3.1,1.5,5.7v15.3c0,0.5,0,1,0,1.7c0,0.7,0.2,1.3,0.5,2h-4.7 c0.2-2.1,0.3-4.3,0.3-6.4v-11.1c0-2.3-0.4-4.2-1.3-5.5c-1-1.6-2.7-2.4-4.9-2.4c-0.7,0-1.5,0.1-2.4,0.3c-2.2,0.5-3.8,1.3-4.7,2.7 c-0.9,1.3-1.4,3.2-1.4,5.5v13.7c0,0.6,0,1.1,0.1,1.7c0.1,0.5,0.2,1.1,0.5,1.6h-5.1c0.2-0.4,0.4-0.9,0.6-1.5 c0.1-0.6,0.2-1.4,0.2-2.5C144.6,404.2,144.6,403.8,144.6,403.5z"/> <path class="st0" d="M168.3,382.6h2.2v-5.9l4-1.1v7h5.5l-0.2,1h-5.3v19.1c0,1.5,0.2,2.6,0.6,3.3c0.5,1.1,1.5,1.6,2.8,1.6 c1,0,1.8-0.3,2.6-0.8v1c-0.7,0.5-1.5,0.8-2.3,1c-0.8,0.2-1.7,0.3-2.6,0.3c-2,0-3.4-0.7-4.1-2.1c-0.6-1-0.9-2.6-0.9-4.8v-18.8h-2.4 L168.3,382.6z"/> </g> </g> <g> <g> <g> <path class="st0" d="M-77.1,382.8h9.9l4.3,16.8l5.4-16.8h9.2l5.6,16.8l4.3-16.8h9.8l-9.8,26.7h-9.1l-5.4-16.1l-5.2,16.1h-9.1 L-77.1,382.8z"/> </g> <g> <path class="st0" d="M-1.7,398.7h-20.5c0.2,1.6,0.6,2.9,1.3,3.7c1,1.2,2.3,1.7,3.9,1.7c1,0,2-0.3,2.9-0.8 c0.6-0.3,1.1-0.9,1.8-1.7l10.1,0.9c-1.5,2.7-3.4,4.6-5.6,5.8c-2.2,1.2-5.3,1.7-9.4,1.7c-3.5,0-6.3-0.5-8.3-1.5s-3.7-2.6-5-4.8 c-1.3-2.2-2-4.7-2-7.7c0-4.2,1.3-7.5,4-10.1c2.7-2.6,6.4-3.9,11.1-3.9c3.8,0,6.8,0.6,9,1.7c2.2,1.2,3.9,2.8,5.1,5 c1.2,2.2,1.7,5.1,1.7,8.6L-1.7,398.7L-1.7,398.7z M-12.1,393.8c-0.2-2-0.7-3.4-1.6-4.2c-0.9-0.9-2-1.3-3.4-1.3 c-1.6,0-2.9,0.6-3.9,1.9c-0.6,0.8-1,2-1.2,3.6L-12.1,393.8L-12.1,393.8z"/> </g> <g> <path class="st0" d="M-1.7,372.6H8.7v12.8c1-1.1,2.2-1.9,3.5-2.4c1.3-0.5,2.7-0.8,4.3-0.8c3.3,0,5.9,1.2,8.1,3.5 c2.1,2.3,3.2,5.7,3.2,10.1c0,2.9-0.5,5.5-1.5,7.7c-1,2.2-2.3,3.9-4,5c-1.7,1.1-3.6,1.6-5.7,1.6c-1.8,0-3.4-0.4-4.9-1.2 c-1.1-0.6-2.3-1.7-3.7-3.4v3.9h-9.6L-1.7,372.6L-1.7,372.6z M8.6,396.1c0,2.3,0.4,4,1.3,5c0.9,1,2,1.5,3.3,1.5 c1.2,0,2.2-0.5,3.1-1.5c0.8-1,1.2-2.7,1.2-5.1c0-2.1-0.4-3.7-1.2-4.7c-0.8-1-1.8-1.5-3-1.5c-1.4,0-2.5,0.5-3.4,1.5 C9,392.4,8.6,394,8.6,396.1z"/> </g> </g> </g> <g> <path class="st0" d="M-63.5,423.9c-0.1,0-0.2,0.1-0.4,0.1c-0.2,0-0.3,0-0.5,0.1c-0.2,0-0.4,0-0.6,0.1c-0.2,0-0.4,0-0.6,0 c-0.2,0-0.5-0.1-0.7-0.2c-0.2-0.1-0.4-0.2-0.5-0.4c-0.2-0.2-0.3-0.4-0.4-0.6c-0.1-0.2-0.1-0.4-0.1-0.6c0-0.4,0.1-0.8,0.3-1.1 s0.5-0.5,0.8-0.7s0.7-0.3,1.2-0.3c0.5-0.1,0.9-0.1,1.5-0.1v-0.7c0-0.9-0.5-1.3-1.4-1.3c-0.3,0-0.6,0-0.9,0.1 c-0.3,0.1-0.6,0.2-0.9,0.4l-0.3-0.5c0.4-0.2,0.8-0.4,1.2-0.4c0.4-0.1,0.7-0.1,1.1-0.1c0.2,0,0.4,0,0.6,0.1c0.2,0,0.4,0.1,0.6,0.2 c0.2,0.1,0.4,0.3,0.5,0.5c0.1,0.2,0.2,0.5,0.2,0.8v4.8L-63.5,423.9z M-63.5,420.8c-0.4,0-0.8,0-1.2,0c-0.4,0-0.7,0.1-1,0.2 c-0.3,0.1-0.5,0.3-0.7,0.5c-0.2,0.2-0.3,0.5-0.3,0.8c0,0.4,0.1,0.7,0.4,0.9c0.2,0.2,0.5,0.4,0.9,0.4c0.1,0,0.3,0,0.5,0 c0.2,0,0.4,0,0.5-0.1c0.2,0,0.3-0.1,0.5-0.1c0.1,0,0.3-0.1,0.3-0.1L-63.5,420.8L-63.5,420.8z"/> <path class="st0" d="M-49.9,424.2l-0.3-0.2l-1.9-4.8l-2,5l-0.3-0.2l-2.6-6.1l0.6-0.3l2.2,5.3l2-5.1l0.2-0.2l2,5.3l2.3-5.3l0.6,0.3 L-49.9,424.2z"/> <path class="st0" d="M-42.1,417.9c0.3,0.1,0.6,0.3,0.9,0.5c0.3,0.2,0.5,0.6,0.6,0.9c0.2,0.4,0.2,0.8,0.2,1.3h-4.9 c0,0.4,0,0.8,0.1,1.1c0.1,0.3,0.3,0.6,0.5,0.9c0.2,0.3,0.5,0.5,0.8,0.6c0.3,0.1,0.7,0.2,1,0.2c0.4,0,0.7-0.1,1-0.2 c0.3-0.1,0.6-0.3,1-0.5l0.3,0.5c-0.7,0.6-1.5,0.8-2.4,0.8c-0.4,0-0.9-0.1-1.2-0.2c-0.4-0.2-0.7-0.4-1-0.7c-0.3-0.3-0.5-0.6-0.6-1 c-0.2-0.4-0.2-0.8-0.2-1.3c0-0.4,0.1-0.9,0.2-1.3c0.1-0.4,0.3-0.7,0.6-1c0.3-0.3,0.6-0.5,0.9-0.7c0.3-0.2,0.7-0.2,1.1-0.2 C-42.8,417.7-42.4,417.8-42.1,417.9z M-43.1,418.4c-0.5,0-1,0.2-1.3,0.5c-0.4,0.3-0.6,0.8-0.7,1.3h4C-41.4,419-42,418.4-43.1,418.4 z"/> <path class="st0" d="M-32.9,422.2c-0.2,0.4-0.4,0.8-0.7,1.1c-0.3,0.3-0.7,0.5-1.1,0.7c-0.4,0.2-0.9,0.2-1.4,0.2 c-0.4,0-0.7,0-1.1-0.1c-0.3-0.1-0.7-0.2-1.1-0.4v-9.1l0.7-0.2v4c0.3-0.2,0.6-0.4,1-0.5c0.3-0.1,0.7-0.2,1.2-0.2 c0.4,0,0.8,0.1,1.1,0.2s0.6,0.4,0.9,0.6c0.2,0.3,0.4,0.6,0.6,1s0.2,0.8,0.2,1.2C-32.7,421.3-32.8,421.7-32.9,422.2z M-33.6,419.8 c-0.1-0.3-0.3-0.6-0.5-0.8c-0.2-0.2-0.4-0.4-0.7-0.5c-0.3-0.1-0.5-0.2-0.9-0.2c-0.4,0-0.7,0.1-1.1,0.2c-0.3,0.1-0.7,0.3-1.1,0.7 v4.1c0.3,0.1,0.5,0.2,0.8,0.2c0.2,0.1,0.5,0.1,0.7,0.1c0.4,0,0.8-0.1,1.1-0.2c0.3-0.1,0.6-0.3,0.9-0.6c0.2-0.2,0.4-0.5,0.6-0.9 s0.2-0.7,0.2-1.1C-33.4,420.4-33.4,420.1-33.6,419.8z"/> <path class="st0" d="M-24.7,415.1l-0.9,0.9l-0.9-0.9l0.9-0.9L-24.7,415.1z M-26,424v-6.1l0.7-0.3v6.4H-26z"/> <path class="st0" d="M-18.3,424v-3.5c0-0.7-0.2-1.2-0.5-1.6c-0.3-0.4-0.8-0.6-1.3-0.6c-0.4,0-0.8,0-1.2,0.1 c-0.3,0.1-0.6,0.2-0.9,0.4v5.2h-0.7v-6.2l0.7,0.3v0c0.3-0.1,0.6-0.2,1-0.3c0.4-0.1,0.8-0.1,1.1-0.1c0.7,0,1.3,0.2,1.7,0.6 s0.7,1.1,0.7,1.9v3.8L-18.3,424L-18.3,424z"/> <path class="st0" d="M-10.8,424v-3.5c0-0.7-0.2-1.2-0.5-1.6c-0.3-0.4-0.8-0.6-1.3-0.6c-0.4,0-0.8,0-1.2,0.1 c-0.3,0.1-0.6,0.2-0.9,0.4v5.2h-0.7v-6.2l0.7,0.3v0c0.3-0.1,0.6-0.2,1-0.3c0.4-0.1,0.8-0.1,1.1-0.1c0.7,0,1.3,0.2,1.7,0.6 s0.7,1.1,0.7,1.9v3.8L-10.8,424L-10.8,424z"/> <path class="st0" d="M-2,422.2c-0.2,0.4-0.4,0.7-0.7,1c-0.3,0.3-0.6,0.5-1,0.7c-0.4,0.2-0.8,0.2-1.3,0.2s-0.9-0.1-1.3-0.2 c-0.4-0.2-0.7-0.4-1-0.7c-0.3-0.3-0.5-0.6-0.7-1c-0.2-0.4-0.2-0.8-0.2-1.3c0-0.5,0.1-0.9,0.2-1.3c0.2-0.4,0.4-0.7,0.7-1 c0.3-0.3,0.6-0.5,1-0.7c0.4-0.2,0.8-0.2,1.3-0.2s0.9,0.1,1.3,0.2c0.4,0.2,0.7,0.4,1,0.7c0.3,0.3,0.5,0.6,0.7,1 c0.2,0.4,0.2,0.8,0.2,1.3C-1.8,421.4-1.9,421.8-2,422.2z M-2.7,419.9c-0.1-0.3-0.3-0.6-0.5-0.8c-0.2-0.2-0.5-0.4-0.8-0.6 c-0.3-0.1-0.6-0.2-1-0.2c-0.4,0-0.7,0.1-1,0.2c-0.3,0.1-0.6,0.3-0.8,0.5s-0.4,0.5-0.5,0.8c-0.1,0.3-0.2,0.7-0.2,1 c0,0.4,0.1,0.7,0.2,1c0.1,0.3,0.3,0.6,0.5,0.8c0.2,0.2,0.5,0.4,0.8,0.5c0.3,0.1,0.6,0.2,1,0.2c0.3,0,0.7-0.1,1-0.2 c0.3-0.1,0.6-0.3,0.8-0.5c0.2-0.2,0.4-0.5,0.5-0.8c0.1-0.3,0.2-0.7,0.2-1C-2.5,420.6-2.6,420.2-2.7,419.9z"/> <path class="st0" d="M2.5,424.4l-0.3-0.2l-2.8-6.3l0.6-0.2l2.4,5.4l2.3-5.4l0.6,0.2L2.5,424.4z"/> <path class="st0" d="M10.2,423.9c-0.1,0-0.2,0.1-0.4,0.1c-0.2,0-0.3,0-0.5,0.1c-0.2,0-0.4,0-0.6,0.1c-0.2,0-0.4,0-0.6,0 c-0.2,0-0.5-0.1-0.7-0.2c-0.2-0.1-0.4-0.2-0.5-0.4c-0.2-0.2-0.3-0.4-0.4-0.6c-0.1-0.2-0.1-0.4-0.1-0.6c0-0.4,0.1-0.8,0.3-1.1 s0.5-0.5,0.8-0.7s0.7-0.3,1.2-0.3c0.5-0.1,0.9-0.1,1.5-0.1v-0.7c0-0.9-0.5-1.3-1.4-1.3c-0.3,0-0.6,0-0.9,0.1 c-0.3,0.1-0.6,0.2-0.9,0.4l-0.3-0.5c0.4-0.2,0.8-0.4,1.2-0.4c0.4-0.1,0.7-0.1,1.1-0.1c0.2,0,0.4,0,0.6,0.1c0.2,0,0.4,0.1,0.6,0.2 c0.2,0.1,0.4,0.3,0.5,0.5c0.1,0.2,0.2,0.5,0.2,0.8v4.8L10.2,423.9z M10.2,420.8c-0.4,0-0.8,0-1.2,0c-0.4,0-0.7,0.1-1,0.2 c-0.3,0.1-0.5,0.3-0.7,0.5s-0.3,0.5-0.3,0.8c0,0.4,0.1,0.7,0.4,0.9c0.2,0.2,0.5,0.4,0.9,0.4c0.1,0,0.3,0,0.5,0c0.2,0,0.4,0,0.5-0.1 c0.2,0,0.3-0.1,0.5-0.1c0.1,0,0.3-0.1,0.3-0.1L10.2,420.8L10.2,420.8z"/> <path class="st0" d="M15.6,424.1c-0.3,0.1-0.5,0.1-0.7,0.1c-0.2,0-0.3,0-0.5-0.1c-0.2-0.1-0.3-0.1-0.5-0.2 c-0.1-0.1-0.2-0.2-0.3-0.4c-0.1-0.2-0.1-0.4-0.1-0.6v-4.4h-1.2v-0.5h1.2v-1.7l0.7-0.4v2.1h1.7v0.5h-1.7v3.7c0,0.3,0,0.5,0,0.7 c0,0.2,0,0.3,0.1,0.5c0.1,0.1,0.2,0.2,0.3,0.3c0.1,0.1,0.3,0.1,0.5,0.1c0.2,0,0.3,0,0.4,0c0.1,0,0.3-0.1,0.5-0.2l0.3,0.5 C16.1,423.9,15.9,424,15.6,424.1z"/> <path class="st0" d="M19.2,415.1l-0.9,0.9l-0.9-0.9l0.9-0.9L19.2,415.1z M17.9,424v-6.1l0.7-0.3v6.4H17.9z"/> <path class="st0" d="M26.8,422.2c-0.2,0.4-0.4,0.7-0.7,1c-0.3,0.3-0.6,0.5-1,0.7c-0.4,0.2-0.8,0.2-1.3,0.2s-0.9-0.1-1.3-0.2 c-0.4-0.2-0.7-0.4-1-0.7c-0.3-0.3-0.5-0.6-0.7-1c-0.2-0.4-0.2-0.8-0.2-1.3c0-0.5,0.1-0.9,0.2-1.3c0.2-0.4,0.4-0.7,0.7-1 c0.3-0.3,0.6-0.5,1-0.7c0.4-0.2,0.8-0.2,1.3-0.2s0.9,0.1,1.3,0.2c0.4,0.2,0.7,0.4,1,0.7c0.3,0.3,0.5,0.6,0.7,1 c0.2,0.4,0.2,0.8,0.2,1.3C27,421.4,27,421.8,26.8,422.2z M26.1,419.9c-0.1-0.3-0.3-0.6-0.5-0.8c-0.2-0.2-0.5-0.4-0.8-0.6 c-0.3-0.1-0.6-0.2-1-0.2c-0.4,0-0.7,0.1-1,0.2c-0.3,0.1-0.6,0.3-0.8,0.5s-0.4,0.5-0.5,0.8c-0.1,0.3-0.2,0.7-0.2,1 c0,0.4,0.1,0.7,0.2,1c0.1,0.3,0.3,0.6,0.5,0.8c0.2,0.2,0.5,0.4,0.8,0.5c0.3,0.1,0.6,0.2,1,0.2c0.3,0,0.7-0.1,1-0.2 c0.3-0.1,0.6-0.3,0.8-0.5c0.2-0.2,0.4-0.5,0.5-0.8c0.1-0.3,0.2-0.7,0.2-1C26.3,420.6,26.3,420.2,26.1,419.9z"/> <path class="st0" d="M33.5,424v-3.5c0-0.7-0.2-1.2-0.5-1.6c-0.3-0.4-0.8-0.6-1.3-0.6c-0.4,0-0.8,0-1.2,0.1 c-0.3,0.1-0.6,0.2-0.9,0.4v5.2H29v-6.2l0.7,0.3v0c0.3-0.1,0.6-0.2,1-0.3c0.4-0.1,0.8-0.1,1.1-0.1c0.7,0,1.3,0.2,1.7,0.6 s0.7,1.1,0.7,1.9v3.8L33.5,424L33.5,424z"/> <path class="st0" d="M45.1,424.1c-0.4,0.1-0.8,0.1-1.1,0.1c-0.5,0-0.9-0.1-1.3-0.2c-0.4-0.2-0.7-0.4-1-0.6c-0.3-0.3-0.5-0.6-0.7-1 c-0.2-0.4-0.2-0.8-0.2-1.3c0-0.5,0.1-0.9,0.2-1.3c0.2-0.4,0.4-0.8,0.7-1c0.3-0.3,0.6-0.5,1-0.7s0.8-0.2,1.3-0.2c0.3,0,0.6,0,1,0.1 s0.7,0.2,1,0.3l-0.3,0.6c-0.2-0.1-0.4-0.1-0.5-0.2s-0.3-0.1-0.4-0.1c-0.1,0-0.3,0-0.4-0.1s-0.3,0-0.4,0c-0.4,0-0.7,0.1-1,0.2 c-0.3,0.1-0.6,0.3-0.8,0.5c-0.2,0.2-0.4,0.5-0.5,0.8c-0.1,0.3-0.2,0.7-0.2,1.1c0,0.8,0.2,1.4,0.7,1.9c0.5,0.5,1.1,0.7,1.9,0.7 c0.1,0,0.3,0,0.4,0c0.1,0,0.3,0,0.4-0.1c0.1,0,0.3-0.1,0.4-0.1c0.2,0,0.3-0.1,0.5-0.2l0.3,0.6C45.9,423.9,45.5,424,45.1,424.1z"/> <path class="st0" d="M53.6,422.2c-0.2,0.4-0.4,0.7-0.7,1c-0.3,0.3-0.6,0.5-1,0.7c-0.4,0.2-0.8,0.2-1.3,0.2s-0.9-0.1-1.3-0.2 c-0.4-0.2-0.7-0.4-1-0.7c-0.3-0.3-0.5-0.6-0.7-1c-0.2-0.4-0.2-0.8-0.2-1.3c0-0.5,0.1-0.9,0.2-1.3c0.2-0.4,0.4-0.7,0.7-1 c0.3-0.3,0.6-0.5,1-0.7c0.4-0.2,0.8-0.2,1.3-0.2s0.9,0.1,1.3,0.2c0.4,0.2,0.7,0.4,1,0.7c0.3,0.3,0.5,0.6,0.7,1 c0.2,0.4,0.2,0.8,0.2,1.3C53.8,421.4,53.7,421.8,53.6,422.2z M52.9,419.9c-0.1-0.3-0.3-0.6-0.5-0.8c-0.2-0.2-0.5-0.4-0.8-0.6 c-0.3-0.1-0.6-0.2-1-0.2c-0.4,0-0.7,0.1-1,0.2c-0.3,0.1-0.6,0.3-0.8,0.5s-0.4,0.5-0.5,0.8c-0.1,0.3-0.2,0.7-0.2,1 c0,0.4,0.1,0.7,0.2,1c0.1,0.3,0.3,0.6,0.5,0.8c0.2,0.2,0.5,0.4,0.8,0.5c0.3,0.1,0.6,0.2,1,0.2c0.3,0,0.7-0.1,1-0.2 c0.3-0.1,0.6-0.3,0.8-0.5c0.2-0.2,0.4-0.5,0.5-0.8c0.1-0.3,0.2-0.7,0.2-1C53.1,420.6,53,420.2,52.9,419.9z"/> <path class="st0" d="M64.1,424v-3.5c0-0.3,0-0.6-0.1-0.9c-0.1-0.3-0.1-0.5-0.3-0.7c-0.1-0.2-0.3-0.3-0.5-0.4 c-0.2-0.1-0.5-0.2-0.8-0.2c-0.4,0-0.8,0.1-1.1,0.2c-0.3,0.1-0.6,0.3-0.9,0.6c0,0,0,0.2,0.1,0.4c0,0.2,0.1,0.4,0.1,0.6v3.9h-0.7 v-3.5c0-0.8-0.1-1.3-0.4-1.7s-0.7-0.5-1.2-0.5c-0.4,0-0.8,0.1-1.1,0.2c-0.3,0.1-0.5,0.3-0.8,0.4v5.1h-0.7v-6.2l0.7,0.4 c0.2-0.1,0.5-0.2,0.8-0.3c0.3-0.1,0.6-0.1,1.1-0.1c0.5,0,0.9,0.1,1.2,0.3c0.3,0.2,0.5,0.4,0.7,0.6c0.4-0.2,0.7-0.5,1.1-0.6 c0.4-0.2,0.8-0.2,1.3-0.2c0.7,0,1.3,0.2,1.6,0.7c0.3,0.4,0.5,1,0.5,1.8v3.8L64.1,424L64.1,424z"/> <path class="st0" d="M72.5,422.2c-0.2,0.4-0.4,0.7-0.7,1c-0.3,0.3-0.6,0.5-1,0.7c-0.4,0.2-0.8,0.2-1.2,0.2c-0.3,0-0.6,0-0.9-0.1 c-0.3-0.1-0.6-0.1-0.9-0.3v3.4h-0.7v-9.5l0.7,0.3c0.3-0.1,0.6-0.2,0.9-0.2c0.3-0.1,0.6-0.1,1-0.1c0.4,0,0.8,0.1,1.2,0.2 c0.4,0.2,0.7,0.4,1,0.7c0.3,0.3,0.5,0.6,0.6,1c0.2,0.4,0.2,0.8,0.2,1.3C72.7,421.4,72.6,421.8,72.5,422.2z M71.8,419.9 c-0.1-0.3-0.3-0.6-0.5-0.8c-0.2-0.2-0.5-0.4-0.8-0.5c-0.3-0.1-0.7-0.2-1-0.2c-0.3,0-0.5,0-0.8,0.1c-0.2,0-0.5,0.1-0.9,0.3v4.3 c0.3,0.2,0.6,0.3,0.9,0.4c0.3,0.1,0.5,0.1,0.8,0.1c0.4,0,0.7-0.1,1-0.2c0.3-0.1,0.6-0.3,0.8-0.5s0.4-0.5,0.5-0.8 c0.1-0.3,0.2-0.7,0.2-1S71.9,420.3,71.8,419.9z"/> <path class="st0" d="M78.2,423.9c-0.1,0-0.2,0.1-0.4,0.1c-0.2,0-0.3,0-0.5,0.1c-0.2,0-0.4,0-0.6,0.1c-0.2,0-0.4,0-0.6,0 c-0.2,0-0.5-0.1-0.7-0.2c-0.2-0.1-0.4-0.2-0.5-0.4c-0.2-0.2-0.3-0.4-0.4-0.6c-0.1-0.2-0.1-0.4-0.1-0.6c0-0.4,0.1-0.8,0.3-1.1 s0.5-0.5,0.8-0.7s0.7-0.3,1.2-0.3c0.5-0.1,0.9-0.1,1.5-0.1v-0.7c0-0.9-0.5-1.3-1.4-1.3c-0.3,0-0.6,0-0.9,0.1 c-0.3,0.1-0.6,0.2-0.9,0.4l-0.3-0.5c0.4-0.2,0.8-0.4,1.2-0.4c0.4-0.1,0.7-0.1,1.1-0.1c0.2,0,0.4,0,0.6,0.1c0.2,0,0.4,0.1,0.6,0.2 c0.2,0.1,0.4,0.3,0.5,0.5c0.1,0.2,0.2,0.5,0.2,0.8v4.8L78.2,423.9z M78.2,420.8c-0.4,0-0.8,0-1.2,0c-0.4,0-0.7,0.1-1,0.2 c-0.3,0.1-0.5,0.3-0.7,0.5s-0.3,0.5-0.3,0.8c0,0.4,0.1,0.7,0.4,0.9c0.2,0.2,0.5,0.4,0.9,0.4c0.1,0,0.3,0,0.5,0c0.2,0,0.4,0,0.5-0.1 c0.2,0,0.3-0.1,0.5-0.1c0.1,0,0.3-0.1,0.3-0.1L78.2,420.8L78.2,420.8z"/> <path class="st0" d="M85.6,424v-3.5c0-0.7-0.2-1.2-0.5-1.6c-0.3-0.4-0.8-0.6-1.3-0.6c-0.4,0-0.8,0-1.2,0.1 c-0.3,0.1-0.6,0.2-0.9,0.4v5.2h-0.7v-6.2l0.7,0.3v0c0.3-0.1,0.6-0.2,1-0.3c0.4-0.1,0.8-0.1,1.1-0.1c0.7,0,1.3,0.2,1.7,0.6 s0.7,1.1,0.7,1.9v3.8L85.6,424L85.6,424z"/> <path class="st0" d="M90.6,424c-0.3,0.6-0.6,1-0.8,1.3c-0.3,0.3-0.6,0.6-0.8,0.8c-0.3,0.2-0.5,0.3-0.7,0.4 c-0.2,0.1-0.4,0.1-0.5,0.1l-0.2-0.5c0.2,0,0.4-0.1,0.6-0.2c0.2-0.1,0.4-0.2,0.6-0.3c0.2-0.1,0.4-0.3,0.6-0.6 c0.2-0.2,0.4-0.6,0.6-0.9c0.1-0.1,0.1-0.2,0.2-0.4c0.1-0.1,0.1-0.3,0.2-0.4c0.1-0.1,0.1-0.2,0.1-0.3c0-0.1,0-0.1,0-0.2l-2.6-4.9 l0.6-0.3l2.4,4.6l2.2-4.6l0.6,0.3L90.6,424z"/> </g> <g> <path class="st0" d="M-114.3,409.9c6.4,6.4,13.5-0.8,13.5-0.8c7.6-7.3,0.8-13.7,0.8-13.7l-4.5-4.4c-0.8-0.7-2-0.7-2.7,0l-0.6,0.6 c-0.7,0.8-0.7,2,0,2.7l4.4,4.4c0,0,4,3.5-0.1,7.5c0,0-3.9,4.4-7.6,0.3l-4.5-4.4c-0.7-0.7-2-0.7-2.7,0l-0.6,0.6 c-0.7,0.8-0.7,2,0,2.7L-114.3,409.9z"/> <path class="st0" d="M-113.2,400.1c-0.8-0.8-0.9-2.1-0.2-2.9l0.6-0.6c0.7-0.8,2-0.7,2.9,0.2l4.9,4.9c0.8,0.8,0.9,2.1,0.2,2.9 l-0.6,0.6c-0.7,0.7-2,0.7-2.9-0.2L-113.2,400.1z"/> </g> <path class="st0" d="M-83.3,423.7c-1.6-7.8-1.2-14.9-0.7-21.9c0.6-10.7,1.3-20.9-6.9-29.1c-7.1-7.1-18.7-7.1-25.9,0 c-4,4-5.8,9.6-5.2,15.1c-5.5-0.6-11.1,1.2-15.1,5.2c-7.1,7.1-7.1,18.7,0,25.9c8.5,8.5,18.7,7.9,29.5,7.2c0.7,0,1.4-0.1,2.1-0.1 l2.5-0.2l-9.2-4.3l-3.1,0.1c-7.1,0.1-13-0.9-18.2-6.1c-5.2-5.2-5.2-13.7,0-19c3.6-3.6,9.2-4.9,14-3.1l4.9,1.8l-1.8-4.9 c-1.8-4.9-0.5-10.4,3.1-14c5.2-5.2,13.7-5.2,19,0c6.6,6.6,6.1,14.9,5.5,25.3c-0.2,3.7-0.5,7.6-0.4,11.7l6.4,13.1L-83.3,423.7z"/> </svg>
docs/public/assets/support/agencies/full/light/webreinvent.svg
0
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.0003110876423306763, 0.00020389046403579414, 0.00016319029964506626, 0.00018155747966375202, 0.00004718249329016544 ]
{ "id": 0, "code_window": [ "import { hasProtocol, joinURL, parseURL } from 'ufo'\n", "import { useNuxtApp, useRuntimeConfig } from '../nuxt'\n", "import type { NuxtError } from './error'\n", "import { createError } from './error'\n", "import { useState } from './state'\n", "\n", "export const useRouter = () => {\n", " return useNuxtApp()?.$router as Router\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { setResponseStatus } from './ssr'\n" ], "file_path": "packages/nuxt/src/app/composables/router.ts", "type": "add", "edit_start_line_idx": 8 }
import adhoc from './adhoc' import app from './app' import build from './build' import common from './common' import dev from './dev' import experimental from './experimental' import generate from './generate' import internal from './internal' import nitro from './nitro' import postcss from './postcss' import router from './router' import typescript from './typescript' import vite from './vite' import webpack from './webpack' export default { ...adhoc, ...app, ...build, ...common, ...dev, ...experimental, ...generate, ...internal, ...nitro, ...postcss, ...router, ...typescript, ...vite, ...webpack }
packages/schema/src/config/index.ts
0
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.00030954007524996996, 0.00020508552552200854, 0.00016413301636930555, 0.0001733344979584217, 0.000060467442381195724 ]
{ "id": 1, "code_window": [ "\n", " if (process.server) {\n", " const nuxtApp = useNuxtApp()\n", " if (nuxtApp.ssrContext && nuxtApp.ssrContext.event) {\n", " const redirectLocation = isExternal ? toPath : joinURL(useRuntimeConfig().app.baseURL, router.resolve(to).fullPath || '/')\n" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " // Let vue-router handle internal redirects within middleware\n", " // to prevent the navigation happening after response is sent\n", " if (isProcessingMiddleware() && !isExternal) {\n", " setResponseStatus(options?.redirectCode || 302)\n", " return to\n", " }\n" ], "file_path": "packages/nuxt/src/app/composables/router.ts", "type": "add", "edit_start_line_idx": 99 }
import { getCurrentInstance, inject, onUnmounted } from 'vue' import type { Router, RouteLocationNormalizedLoaded, NavigationGuard, RouteLocationNormalized, RouteLocationRaw, NavigationFailure, RouteLocationPathRaw } from 'vue-router' import { sendRedirect } from 'h3' import { hasProtocol, joinURL, parseURL } from 'ufo' import { useNuxtApp, useRuntimeConfig } from '../nuxt' import type { NuxtError } from './error' import { createError } from './error' import { useState } from './state' export const useRouter = () => { return useNuxtApp()?.$router as Router } export const useRoute = (): RouteLocationNormalizedLoaded => { if (getCurrentInstance()) { return inject('_route', useNuxtApp()._route) } return useNuxtApp()._route } export const onBeforeRouteLeave = (guard: NavigationGuard) => { const unsubscribe = useRouter().beforeEach((to, from, next) => { if (to === from) { return } return guard(to, from, next) }) onUnmounted(unsubscribe) } export const onBeforeRouteUpdate = (guard: NavigationGuard) => { const unsubscribe = useRouter().beforeEach(guard) onUnmounted(unsubscribe) } export interface RouteMiddleware { (to: RouteLocationNormalized, from: RouteLocationNormalized): ReturnType<NavigationGuard> } export const defineNuxtRouteMiddleware = (middleware: RouteMiddleware) => middleware export interface AddRouteMiddlewareOptions { global?: boolean } interface AddRouteMiddleware { (name: string, middleware: RouteMiddleware, options?: AddRouteMiddlewareOptions): void (middleware: RouteMiddleware): void } export const addRouteMiddleware: AddRouteMiddleware = (name: string | RouteMiddleware, middleware?: RouteMiddleware, options: AddRouteMiddlewareOptions = {}) => { const nuxtApp = useNuxtApp() if (options.global || typeof name === 'function') { nuxtApp._middleware.global.push(typeof name === 'function' ? name : middleware) } else { nuxtApp._middleware.named[name] = middleware } } const isProcessingMiddleware = () => { try { if (useNuxtApp()._processingMiddleware) { return true } } catch { // Within an async middleware return true } return false } export interface NavigateToOptions { replace?: boolean redirectCode?: number, external?: boolean } export const navigateTo = (to: RouteLocationRaw | undefined | null, options?: NavigateToOptions): Promise<void | NavigationFailure> | RouteLocationRaw => { if (!to) { to = '/' } const toPath = typeof to === 'string' ? to : ((to as RouteLocationPathRaw).path || '/') const isExternal = hasProtocol(toPath, true) if (isExternal && !options?.external) { throw new Error('Navigating to external URL is not allowed by default. Use `nagivateTo (url, { external: true })`.') } if (isExternal && parseURL(toPath).protocol === 'script:') { throw new Error('Cannot navigate to an URL with script protocol.') } // Early redirect on client-side if (process.client && !isExternal && isProcessingMiddleware()) { return to } const router = useRouter() if (process.server) { const nuxtApp = useNuxtApp() if (nuxtApp.ssrContext && nuxtApp.ssrContext.event) { const redirectLocation = isExternal ? toPath : joinURL(useRuntimeConfig().app.baseURL, router.resolve(to).fullPath || '/') return nuxtApp.callHook('app:redirected').then(() => sendRedirect(nuxtApp.ssrContext!.event, redirectLocation, options?.redirectCode || 302)) } } // Client-side redirection using vue-router if (isExternal) { if (options?.replace) { location.replace(toPath) } else { location.href = toPath } return Promise.resolve() } return options?.replace ? router.replace(to) : router.push(to) } /** This will abort navigation within a Nuxt route middleware handler. */ export const abortNavigation = (err?: string | Partial<NuxtError>) => { if (process.dev && !isProcessingMiddleware()) { throw new Error('abortNavigation() is only usable inside a route middleware handler.') } if (err) { throw createError(err) } return false } export const setPageLayout = (layout: string) => { if (process.server) { if (process.dev && getCurrentInstance() && useState('_layout').value !== layout) { console.warn('[warn] [nuxt] `setPageLayout` should not be called to change the layout on the server within a component as this will cause hydration errors.') } useState('_layout').value = layout } const nuxtApp = useNuxtApp() if (process.dev && nuxtApp.isHydrating && useState('_layout').value !== layout) { console.warn('[warn] [nuxt] `setPageLayout` should not be called to change the layout during hydration as this will cause hydration errors.') } const inMiddleware = isProcessingMiddleware() if (inMiddleware || process.server || nuxtApp.isHydrating) { const unsubscribe = useRouter().beforeResolve((to) => { to.meta.layout = layout unsubscribe() }) } if (!inMiddleware) { useRoute().meta.layout = layout } }
packages/nuxt/src/app/composables/router.ts
1
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.99920254945755, 0.3915506601333618, 0.0001677194086369127, 0.028980448842048645, 0.46915894746780396 ]
{ "id": 1, "code_window": [ "\n", " if (process.server) {\n", " const nuxtApp = useNuxtApp()\n", " if (nuxtApp.ssrContext && nuxtApp.ssrContext.event) {\n", " const redirectLocation = isExternal ? toPath : joinURL(useRuntimeConfig().app.baseURL, router.resolve(to).fullPath || '/')\n" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " // Let vue-router handle internal redirects within middleware\n", " // to prevent the navigation happening after response is sent\n", " if (isProcessingMiddleware() && !isExternal) {\n", " setResponseStatus(options?.redirectCode || 302)\n", " return to\n", " }\n" ], "file_path": "packages/nuxt/src/app/composables/router.ts", "type": "add", "edit_start_line_idx": 99 }
import type { NuxtHooks } from './hooks' import type { Nuxt } from "./nuxt" import type { NuxtCompatibility } from './compatibility' export interface ModuleMeta { /** Module name. */ name?: string /** Module version. */ version?: string /** * The configuration key used within `nuxt.config` for this module's options. * For example, `@nuxtjs/axios` uses `axios`. */ configKey?: string /** * Constraints for the versions of Nuxt or features this module requires. */ compatibility?: NuxtCompatibility [key: string]: any } /** The options received. */ export type ModuleOptions = Record<string, any> /** Input module passed to defineNuxtModule. */ export interface ModuleDefinition<T extends ModuleOptions = ModuleOptions> { meta?: ModuleMeta defaults?: T | ((nuxt: Nuxt) => T) schema?: T hooks?: Partial<NuxtHooks> setup?: (this: void, resolvedOptions: T, nuxt: Nuxt) => void | Promise<void> } /** Nuxt modules are always a simple function. */ export interface NuxtModule<T extends ModuleOptions = ModuleOptions> { (this: void, inlineOptions: T, nuxt: Nuxt): void | Promise<void> getOptions?: (inlineOptions?: T, nuxt?: Nuxt) => Promise<T> getMeta?: () => Promise<ModuleMeta> }
packages/schema/src/types/module.ts
0
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.0013211783953011036, 0.00060318224132061, 0.00016660844266880304, 0.00019240005349274725, 0.0005253396811895072 ]
{ "id": 1, "code_window": [ "\n", " if (process.server) {\n", " const nuxtApp = useNuxtApp()\n", " if (nuxtApp.ssrContext && nuxtApp.ssrContext.event) {\n", " const redirectLocation = isExternal ? toPath : joinURL(useRuntimeConfig().app.baseURL, router.resolve(to).fullPath || '/')\n" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " // Let vue-router handle internal redirects within middleware\n", " // to prevent the navigation happening after response is sent\n", " if (isProcessingMiddleware() && !isExternal) {\n", " setResponseStatus(options?.redirectCode || 302)\n", " return to\n", " }\n" ], "file_path": "packages/nuxt/src/app/composables/router.ts", "type": "add", "edit_start_line_idx": 99 }
<svg width="479" height="460" viewBox="0 0 479 460" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M215.565 6.99105C211.297 9.6443 207.11 13.8313 198.737 22.2052C190.366 30.5777 186.177 34.7661 183.526 39.0325C174.745 53.1546 174.745 71.0386 183.526 85.1608C186.177 89.428 190.364 93.6123 198.732 101.984L198.737 101.986C207.11 110.361 211.297 114.548 215.565 117.202C229.684 125.984 247.567 125.984 261.686 117.202C265.954 114.548 270.141 110.363 278.514 101.989C286.887 93.6151 291.071 89.428 293.725 85.1608C302.506 71.0386 302.506 53.1546 293.725 39.0325C291.071 34.7658 286.887 30.579 278.514 22.2052C270.141 13.8313 265.954 9.6443 261.686 6.99105C247.567 -1.79064 229.684 -1.79064 215.565 6.99105Z" fill="#02C652"/> <path d="M270.651 268.966L368.077 171.528C372.114 167.493 376.907 164.289 382.18 162.105C387.453 159.92 393.107 158.795 398.815 158.795C404.523 158.795 410.174 159.92 415.45 162.105C420.723 164.289 425.516 167.493 429.55 171.528L478.508 220.49C478.212 220.783 239.427 459.595 239.427 459.595L0.346191 220.49C0.994698 219.843 27.4645 193.37 49.8174 171.014C53.8516 166.979 58.6411 163.778 63.9118 161.594C69.1851 159.412 74.8334 158.287 80.5388 158.287C86.2441 158.287 91.8951 159.412 97.1657 161.597C102.436 163.781 107.226 166.982 111.261 171.019L209.199 268.968C213.234 273.003 218.026 276.204 223.297 278.389C228.57 280.573 234.219 281.695 239.927 281.695C245.632 281.695 251.283 280.57 256.554 278.386C261.827 276.201 266.617 273.001 270.651 268.966Z" fill="#02C652"/> </svg>
docs/public/assets/support/agencies/square/dark/vue-storefront.svg
0
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.0005099462578073144, 0.0005099462578073144, 0.0005099462578073144, 0.0005099462578073144, 0 ]
{ "id": 1, "code_window": [ "\n", " if (process.server) {\n", " const nuxtApp = useNuxtApp()\n", " if (nuxtApp.ssrContext && nuxtApp.ssrContext.event) {\n", " const redirectLocation = isExternal ? toPath : joinURL(useRuntimeConfig().app.baseURL, router.resolve(to).fullPath || '/')\n" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " // Let vue-router handle internal redirects within middleware\n", " // to prevent the navigation happening after response is sent\n", " if (isProcessingMiddleware() && !isExternal) {\n", " setResponseStatus(options?.redirectCode || 302)\n", " return to\n", " }\n" ], "file_path": "packages/nuxt/src/app/composables/router.ts", "type": "add", "edit_start_line_idx": 99 }
import { defineUntypedSchema } from 'untyped' export default defineUntypedSchema({ generate: { /** * The routes to generate. * * If you are using the crawler, this will be only the starting point for route generation. * This is often necessary when using dynamic routes. * * It is preferred to use `nitro.prerender.routes`. * * @example * ```js * routes: ['/users/1', '/users/2', '/users/3'] * ``` */ routes: [], /** * This option is no longer used. Instead, use `nitro.prerender.ignore`. */ exclude: [] } })
packages/schema/src/config/generate.ts
0
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.00017314069555141032, 0.00017056842625606805, 0.00016680237604305148, 0.00017176222172565758, 0.0000027218161449127365 ]
{ "id": 2, "code_window": [ " const redirectLocation = isExternal ? toPath : joinURL(useRuntimeConfig().app.baseURL, router.resolve(to).fullPath || '/')\n", " return nuxtApp.callHook('app:redirected').then(() => sendRedirect(nuxtApp.ssrContext!.event, redirectLocation, options?.redirectCode || 302))\n", " }\n", " }\n", "\n", " // Client-side redirection using vue-router\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return nuxtApp.callHook('app:redirected')\n", " .then(() => sendRedirect(nuxtApp.ssrContext!.event, redirectLocation, options?.redirectCode || 302))\n" ], "file_path": "packages/nuxt/src/app/composables/router.ts", "type": "replace", "edit_start_line_idx": 100 }
import { getCurrentInstance, inject, onUnmounted } from 'vue' import type { Router, RouteLocationNormalizedLoaded, NavigationGuard, RouteLocationNormalized, RouteLocationRaw, NavigationFailure, RouteLocationPathRaw } from 'vue-router' import { sendRedirect } from 'h3' import { hasProtocol, joinURL, parseURL } from 'ufo' import { useNuxtApp, useRuntimeConfig } from '../nuxt' import type { NuxtError } from './error' import { createError } from './error' import { useState } from './state' export const useRouter = () => { return useNuxtApp()?.$router as Router } export const useRoute = (): RouteLocationNormalizedLoaded => { if (getCurrentInstance()) { return inject('_route', useNuxtApp()._route) } return useNuxtApp()._route } export const onBeforeRouteLeave = (guard: NavigationGuard) => { const unsubscribe = useRouter().beforeEach((to, from, next) => { if (to === from) { return } return guard(to, from, next) }) onUnmounted(unsubscribe) } export const onBeforeRouteUpdate = (guard: NavigationGuard) => { const unsubscribe = useRouter().beforeEach(guard) onUnmounted(unsubscribe) } export interface RouteMiddleware { (to: RouteLocationNormalized, from: RouteLocationNormalized): ReturnType<NavigationGuard> } export const defineNuxtRouteMiddleware = (middleware: RouteMiddleware) => middleware export interface AddRouteMiddlewareOptions { global?: boolean } interface AddRouteMiddleware { (name: string, middleware: RouteMiddleware, options?: AddRouteMiddlewareOptions): void (middleware: RouteMiddleware): void } export const addRouteMiddleware: AddRouteMiddleware = (name: string | RouteMiddleware, middleware?: RouteMiddleware, options: AddRouteMiddlewareOptions = {}) => { const nuxtApp = useNuxtApp() if (options.global || typeof name === 'function') { nuxtApp._middleware.global.push(typeof name === 'function' ? name : middleware) } else { nuxtApp._middleware.named[name] = middleware } } const isProcessingMiddleware = () => { try { if (useNuxtApp()._processingMiddleware) { return true } } catch { // Within an async middleware return true } return false } export interface NavigateToOptions { replace?: boolean redirectCode?: number, external?: boolean } export const navigateTo = (to: RouteLocationRaw | undefined | null, options?: NavigateToOptions): Promise<void | NavigationFailure> | RouteLocationRaw => { if (!to) { to = '/' } const toPath = typeof to === 'string' ? to : ((to as RouteLocationPathRaw).path || '/') const isExternal = hasProtocol(toPath, true) if (isExternal && !options?.external) { throw new Error('Navigating to external URL is not allowed by default. Use `nagivateTo (url, { external: true })`.') } if (isExternal && parseURL(toPath).protocol === 'script:') { throw new Error('Cannot navigate to an URL with script protocol.') } // Early redirect on client-side if (process.client && !isExternal && isProcessingMiddleware()) { return to } const router = useRouter() if (process.server) { const nuxtApp = useNuxtApp() if (nuxtApp.ssrContext && nuxtApp.ssrContext.event) { const redirectLocation = isExternal ? toPath : joinURL(useRuntimeConfig().app.baseURL, router.resolve(to).fullPath || '/') return nuxtApp.callHook('app:redirected').then(() => sendRedirect(nuxtApp.ssrContext!.event, redirectLocation, options?.redirectCode || 302)) } } // Client-side redirection using vue-router if (isExternal) { if (options?.replace) { location.replace(toPath) } else { location.href = toPath } return Promise.resolve() } return options?.replace ? router.replace(to) : router.push(to) } /** This will abort navigation within a Nuxt route middleware handler. */ export const abortNavigation = (err?: string | Partial<NuxtError>) => { if (process.dev && !isProcessingMiddleware()) { throw new Error('abortNavigation() is only usable inside a route middleware handler.') } if (err) { throw createError(err) } return false } export const setPageLayout = (layout: string) => { if (process.server) { if (process.dev && getCurrentInstance() && useState('_layout').value !== layout) { console.warn('[warn] [nuxt] `setPageLayout` should not be called to change the layout on the server within a component as this will cause hydration errors.') } useState('_layout').value = layout } const nuxtApp = useNuxtApp() if (process.dev && nuxtApp.isHydrating && useState('_layout').value !== layout) { console.warn('[warn] [nuxt] `setPageLayout` should not be called to change the layout during hydration as this will cause hydration errors.') } const inMiddleware = isProcessingMiddleware() if (inMiddleware || process.server || nuxtApp.isHydrating) { const unsubscribe = useRouter().beforeResolve((to) => { to.meta.layout = layout unsubscribe() }) } if (!inMiddleware) { useRoute().meta.layout = layout } }
packages/nuxt/src/app/composables/router.ts
1
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.9925522804260254, 0.1248503029346466, 0.00016559354844503105, 0.0012443072628229856, 0.32628923654556274 ]
{ "id": 2, "code_window": [ " const redirectLocation = isExternal ? toPath : joinURL(useRuntimeConfig().app.baseURL, router.resolve(to).fullPath || '/')\n", " return nuxtApp.callHook('app:redirected').then(() => sendRedirect(nuxtApp.ssrContext!.event, redirectLocation, options?.redirectCode || 302))\n", " }\n", " }\n", "\n", " // Client-side redirection using vue-router\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return nuxtApp.callHook('app:redirected')\n", " .then(() => sendRedirect(nuxtApp.ssrContext!.event, redirectLocation, options?.redirectCode || 302))\n" ], "file_path": "packages/nuxt/src/app/composables/router.ts", "type": "replace", "edit_start_line_idx": 100 }
<script setup lang="ts"> let count = $ref(0) function inc () { count++ } function dec () { count-- } </script> <template> <NuxtExampleLayout example="experimental/reactivity-transform"> <div> <Label :count="count" /> <div class="flex gap-1 justify-center"> <NButton @click="inc()"> Inc </NButton> <NButton @click="dec()"> Dec </NButton> </div> </div> </NuxtExampleLayout> </template>
examples/experimental/reactivity-transform/app.vue
0
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.000171979219885543, 0.0001712200464680791, 0.0001708019117359072, 0.0001708789641270414, 5.377477805268427e-7 ]
{ "id": 2, "code_window": [ " const redirectLocation = isExternal ? toPath : joinURL(useRuntimeConfig().app.baseURL, router.resolve(to).fullPath || '/')\n", " return nuxtApp.callHook('app:redirected').then(() => sendRedirect(nuxtApp.ssrContext!.event, redirectLocation, options?.redirectCode || 302))\n", " }\n", " }\n", "\n", " // Client-side redirection using vue-router\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return nuxtApp.callHook('app:redirected')\n", " .then(() => sendRedirect(nuxtApp.ssrContext!.event, redirectLocation, options?.redirectCode || 302))\n" ], "file_path": "packages/nuxt/src/app/composables/router.ts", "type": "replace", "edit_start_line_idx": 100 }
<svg width="528" height="470" viewBox="0 0 528 470" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M222.56 407.466L299.098 451.716M222.56 407.466C215.569 403.424 211.261 395.947 211.261 387.855M222.56 407.466L222.435 407.394C215.52 403.396 211.261 396.014 211.261 388.026L211.261 387.855M299.098 451.716C305.932 455.667 314.328 455.755 321.242 451.948M299.098 451.716V451.716C305.882 455.638 314.379 455.727 321.242 451.948V451.948M321.242 451.948L402.195 407.381M402.195 407.381C409.417 403.404 413.906 395.799 413.906 387.537M402.195 407.381L402.323 407.31C409.468 403.377 413.906 395.867 413.906 387.712L413.906 387.537M413.906 387.537L413.906 207.491M413.906 207.491C413.906 199.278 409.469 191.709 402.312 187.713M413.906 207.491L413.906 207.318C413.906 199.21 409.519 191.737 402.44 187.784L402.312 187.713M402.312 187.713L321.363 142.517M321.363 142.517C314.386 138.622 305.876 138.712 298.982 142.753M321.363 142.517V142.517C314.438 138.651 305.824 138.742 298.982 142.753V142.753M298.982 142.753L222.441 187.631M222.441 187.631C215.517 191.691 211.261 199.13 211.261 207.173M222.441 187.631L222.317 187.704C215.468 191.719 211.261 199.064 211.261 207.003L211.261 207.173M211.261 207.173L211.261 387.855" stroke="url(#paint0_linear_3895_44525)" stroke-width="15.5152"/> <path d="M445.47 17.9898L407.525 40.062M445.47 17.9898C448.936 15.9735 453.219 15.9608 456.702 17.9564M445.47 17.9898V17.9898C448.937 15.9733 453.222 15.963 456.702 17.9564V17.9564M407.525 40.062C404.137 42.0328 402.027 45.629 401.958 49.5479M407.525 40.062V40.062C404.138 42.0323 402.027 45.6298 401.958 49.5479V49.5479M401.958 49.5479L401.159 95.426M401.159 95.426C401.087 99.5192 403.253 103.329 406.81 105.367M401.159 95.426V95.426C401.087 99.5196 403.257 103.331 406.81 105.367V105.367M406.81 105.367L447.022 128.402M447.022 128.402C450.557 130.428 454.911 130.382 458.398 128.284M447.022 128.402V128.402C450.553 130.426 454.911 130.383 458.398 128.284V128.284M458.398 128.284L497.839 104.544M497.839 104.544C501.239 102.497 503.301 98.8077 503.263 94.8402M497.839 104.544V104.544C501.238 102.498 503.301 98.8068 503.263 94.8402V94.8402M503.263 94.8402L502.84 50.7868M502.84 50.7868C502.802 46.8014 500.65 43.1326 497.188 41.1492M502.84 50.7868V50.7868C502.802 46.801 500.647 43.1305 497.188 41.1492V41.1492M497.188 41.1492L456.702 17.9564" stroke="url(#paint1_linear_3895_44525)" stroke-width="11.2767"/> <g filter="url(#filter0_f_3895_44525)"> <ellipse cx="500.446" cy="72.7109" rx="4.75453" ry="45.987" transform="rotate(-0.193229 500.446 72.7109)" fill="url(#paint2_radial_3895_44525)" fill-opacity="0.8"/> </g> <path d="M69.1296 309.186L31.1847 331.258M69.1296 309.186C72.5958 307.17 76.8781 307.157 80.3617 309.153M69.1296 309.186V309.186C72.5962 307.17 76.8819 307.159 80.3617 309.153V309.153M31.1847 331.258C27.7966 333.229 25.6861 336.825 25.6178 340.744M31.1847 331.258V331.258C27.7974 333.229 25.6861 336.826 25.6178 340.744V340.744M25.6178 340.744L24.8182 386.622M24.8182 386.622C24.7468 390.715 26.9128 394.525 30.4693 396.563M24.8182 386.622V386.622C24.7468 390.716 26.9167 394.528 30.4693 396.563V396.563M30.4693 396.563L70.6811 419.599M70.6811 419.599C74.2169 421.624 78.5706 421.579 82.0576 419.48M70.6811 419.599V419.599C74.213 421.622 78.5702 421.579 82.0576 419.48V419.48M82.0576 419.48L121.499 395.74M121.499 395.74C124.898 393.694 126.961 390.004 126.923 386.036M121.499 395.74V395.74C124.898 393.694 126.961 390.003 126.923 386.036V386.036M126.923 386.036L126.5 341.983M126.5 341.983C126.461 337.998 124.31 334.329 120.847 332.345M126.5 341.983V341.983C126.461 337.997 124.306 334.327 120.847 332.345V332.345M120.847 332.345L80.3617 309.153" stroke="url(#paint3_linear_3895_44525)" stroke-width="11.2767"/> <g filter="url(#filter1_f_3895_44525)"> <ellipse cx="124.105" cy="363.907" rx="4.75453" ry="45.987" transform="rotate(-0.193229 124.105 363.907)" fill="url(#paint4_radial_3895_44525)" fill-opacity="0.8"/> </g> <defs> <filter id="filter0_f_3895_44525" x="477.786" y="8.82098" width="45.3204" height="127.78" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"> <feFlood flood-opacity="0" result="BackgroundImageFix"/> <feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/> <feGaussianBlur stdDeviation="8.95157" result="effect1_foregroundBlur_3895_44525"/> </filter> <filter id="filter1_f_3895_44525" x="101.445" y="300.017" width="45.3204" height="127.78" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"> <feFlood flood-opacity="0" result="BackgroundImageFix"/> <feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/> <feGaussianBlur stdDeviation="8.95157" result="effect1_foregroundBlur_3895_44525"/> </filter> <linearGradient id="paint0_linear_3895_44525" x1="221.554" y1="176.881" x2="348.941" y2="374.703" gradientUnits="userSpaceOnUse"> <stop stop-color="#00DC82"/> <stop offset="0.505208" stop-color="#1AD6FF"/> <stop offset="1" stop-color="#0047E1"/> </linearGradient> <linearGradient id="paint1_linear_3895_44525" x1="416.845" y1="17.4419" x2="515.118" y2="95.9661" gradientUnits="userSpaceOnUse"> <stop stop-color="#00DC82"/> <stop offset="0.505208" stop-color="#1AD6FF"/> <stop offset="1" stop-color="#0047E1"/> </linearGradient> <radialGradient id="paint2_radial_3895_44525" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(500.446 72.7109) rotate(90) scale(45.987 4.75453)"> <stop stop-color="white"/> <stop offset="1" stop-color="white" stop-opacity="0"/> </radialGradient> <linearGradient id="paint3_linear_3895_44525" x1="40.5044" y1="308.638" x2="138.778" y2="387.162" gradientUnits="userSpaceOnUse"> <stop stop-color="#00DC82"/> <stop offset="0.505208" stop-color="#1AD6FF"/> <stop offset="1" stop-color="#0047E1"/> </linearGradient> <radialGradient id="paint4_radial_3895_44525" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(124.105 363.907) rotate(90) scale(45.987 4.75453)"> <stop stop-color="white"/> <stop offset="1" stop-color="white" stop-opacity="0"/> </radialGradient> </defs> </svg>
docs/public/assets/support/agencies/gems.svg
0
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.0002610954688861966, 0.000191362458281219, 0.00017250707605853677, 0.00017434838810004294, 0.000034880089515354484 ]
{ "id": 2, "code_window": [ " const redirectLocation = isExternal ? toPath : joinURL(useRuntimeConfig().app.baseURL, router.resolve(to).fullPath || '/')\n", " return nuxtApp.callHook('app:redirected').then(() => sendRedirect(nuxtApp.ssrContext!.event, redirectLocation, options?.redirectCode || 302))\n", " }\n", " }\n", "\n", " // Client-side redirection using vue-router\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return nuxtApp.callHook('app:redirected')\n", " .then(() => sendRedirect(nuxtApp.ssrContext!.event, redirectLocation, options?.redirectCode || 302))\n" ], "file_path": "packages/nuxt/src/app/composables/router.ts", "type": "replace", "edit_start_line_idx": 100 }
import clear from 'clear' import { bold, gray, green } from 'colorette' import { version } from '../../package.json' import { tryRequireModule } from './cjs' export function showBanner (_clear?: boolean) { if (_clear) { clear() } console.log(gray(`Nuxi ${(bold(version))}`)) } export function showVersions (cwd: string) { const getPkgVersion = (pkg: string) => { return tryRequireModule(`${pkg}/package.json`, cwd)?.version || '' } const nuxtVersion = getPkgVersion('nuxt') || getPkgVersion('nuxt-edge') const nitroVersion = getPkgVersion('nitropack') console.log(gray( green(`Nuxt ${bold(nuxtVersion)}`) + (nitroVersion ? ` with Nitro ${(bold(nitroVersion))}` : '') )) }
packages/nuxi/src/utils/banner.ts
0
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.002916041063144803, 0.001087202224880457, 0.00016834298730827868, 0.00017722253687679768, 0.0012931893579661846 ]
{ "id": 3, "code_window": [ "import { reactive, h, isReadonly } from 'vue'\n", "import { parseURL, stringifyParsedURL, parseQuery, stringifyQuery, withoutBase, isEqual, joinURL } from 'ufo'\n", "import { createError } from 'h3'\n", "import { defineNuxtPlugin, clearError, navigateTo, showError, useRuntimeConfig, useState } from '..'\n", "import { callWithNuxt } from '../nuxt'\n", "// @ts-ignore\n", "import { globalMiddleware } from '#build/middleware'\n", "\n", "interface Route {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { defineNuxtPlugin, clearError, navigateTo, showError, useRuntimeConfig, useState, useRequestEvent } from '..'\n" ], "file_path": "packages/nuxt/src/app/plugins/router.ts", "type": "replace", "edit_start_line_idx": 3 }
import { getCurrentInstance, inject, onUnmounted } from 'vue' import type { Router, RouteLocationNormalizedLoaded, NavigationGuard, RouteLocationNormalized, RouteLocationRaw, NavigationFailure, RouteLocationPathRaw } from 'vue-router' import { sendRedirect } from 'h3' import { hasProtocol, joinURL, parseURL } from 'ufo' import { useNuxtApp, useRuntimeConfig } from '../nuxt' import type { NuxtError } from './error' import { createError } from './error' import { useState } from './state' export const useRouter = () => { return useNuxtApp()?.$router as Router } export const useRoute = (): RouteLocationNormalizedLoaded => { if (getCurrentInstance()) { return inject('_route', useNuxtApp()._route) } return useNuxtApp()._route } export const onBeforeRouteLeave = (guard: NavigationGuard) => { const unsubscribe = useRouter().beforeEach((to, from, next) => { if (to === from) { return } return guard(to, from, next) }) onUnmounted(unsubscribe) } export const onBeforeRouteUpdate = (guard: NavigationGuard) => { const unsubscribe = useRouter().beforeEach(guard) onUnmounted(unsubscribe) } export interface RouteMiddleware { (to: RouteLocationNormalized, from: RouteLocationNormalized): ReturnType<NavigationGuard> } export const defineNuxtRouteMiddleware = (middleware: RouteMiddleware) => middleware export interface AddRouteMiddlewareOptions { global?: boolean } interface AddRouteMiddleware { (name: string, middleware: RouteMiddleware, options?: AddRouteMiddlewareOptions): void (middleware: RouteMiddleware): void } export const addRouteMiddleware: AddRouteMiddleware = (name: string | RouteMiddleware, middleware?: RouteMiddleware, options: AddRouteMiddlewareOptions = {}) => { const nuxtApp = useNuxtApp() if (options.global || typeof name === 'function') { nuxtApp._middleware.global.push(typeof name === 'function' ? name : middleware) } else { nuxtApp._middleware.named[name] = middleware } } const isProcessingMiddleware = () => { try { if (useNuxtApp()._processingMiddleware) { return true } } catch { // Within an async middleware return true } return false } export interface NavigateToOptions { replace?: boolean redirectCode?: number, external?: boolean } export const navigateTo = (to: RouteLocationRaw | undefined | null, options?: NavigateToOptions): Promise<void | NavigationFailure> | RouteLocationRaw => { if (!to) { to = '/' } const toPath = typeof to === 'string' ? to : ((to as RouteLocationPathRaw).path || '/') const isExternal = hasProtocol(toPath, true) if (isExternal && !options?.external) { throw new Error('Navigating to external URL is not allowed by default. Use `nagivateTo (url, { external: true })`.') } if (isExternal && parseURL(toPath).protocol === 'script:') { throw new Error('Cannot navigate to an URL with script protocol.') } // Early redirect on client-side if (process.client && !isExternal && isProcessingMiddleware()) { return to } const router = useRouter() if (process.server) { const nuxtApp = useNuxtApp() if (nuxtApp.ssrContext && nuxtApp.ssrContext.event) { const redirectLocation = isExternal ? toPath : joinURL(useRuntimeConfig().app.baseURL, router.resolve(to).fullPath || '/') return nuxtApp.callHook('app:redirected').then(() => sendRedirect(nuxtApp.ssrContext!.event, redirectLocation, options?.redirectCode || 302)) } } // Client-side redirection using vue-router if (isExternal) { if (options?.replace) { location.replace(toPath) } else { location.href = toPath } return Promise.resolve() } return options?.replace ? router.replace(to) : router.push(to) } /** This will abort navigation within a Nuxt route middleware handler. */ export const abortNavigation = (err?: string | Partial<NuxtError>) => { if (process.dev && !isProcessingMiddleware()) { throw new Error('abortNavigation() is only usable inside a route middleware handler.') } if (err) { throw createError(err) } return false } export const setPageLayout = (layout: string) => { if (process.server) { if (process.dev && getCurrentInstance() && useState('_layout').value !== layout) { console.warn('[warn] [nuxt] `setPageLayout` should not be called to change the layout on the server within a component as this will cause hydration errors.') } useState('_layout').value = layout } const nuxtApp = useNuxtApp() if (process.dev && nuxtApp.isHydrating && useState('_layout').value !== layout) { console.warn('[warn] [nuxt] `setPageLayout` should not be called to change the layout during hydration as this will cause hydration errors.') } const inMiddleware = isProcessingMiddleware() if (inMiddleware || process.server || nuxtApp.isHydrating) { const unsubscribe = useRouter().beforeResolve((to) => { to.meta.layout = layout unsubscribe() }) } if (!inMiddleware) { useRoute().meta.layout = layout } }
packages/nuxt/src/app/composables/router.ts
1
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.9501054286956787, 0.06119689717888832, 0.00016501083155162632, 0.0002997302508447319, 0.22954273223876953 ]
{ "id": 3, "code_window": [ "import { reactive, h, isReadonly } from 'vue'\n", "import { parseURL, stringifyParsedURL, parseQuery, stringifyQuery, withoutBase, isEqual, joinURL } from 'ufo'\n", "import { createError } from 'h3'\n", "import { defineNuxtPlugin, clearError, navigateTo, showError, useRuntimeConfig, useState } from '..'\n", "import { callWithNuxt } from '../nuxt'\n", "// @ts-ignore\n", "import { globalMiddleware } from '#build/middleware'\n", "\n", "interface Route {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { defineNuxtPlugin, clearError, navigateTo, showError, useRuntimeConfig, useState, useRequestEvent } from '..'\n" ], "file_path": "packages/nuxt/src/app/plugins/router.ts", "type": "replace", "edit_start_line_idx": 3 }
<template> <div>Extended component from foo</div> </template>
test/fixtures/basic/extends/node_modules/foo/components/ExtendsFoo.vue
0
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.00017110200133174658, 0.00017110200133174658, 0.00017110200133174658, 0.00017110200133174658, 0 ]
{ "id": 3, "code_window": [ "import { reactive, h, isReadonly } from 'vue'\n", "import { parseURL, stringifyParsedURL, parseQuery, stringifyQuery, withoutBase, isEqual, joinURL } from 'ufo'\n", "import { createError } from 'h3'\n", "import { defineNuxtPlugin, clearError, navigateTo, showError, useRuntimeConfig, useState } from '..'\n", "import { callWithNuxt } from '../nuxt'\n", "// @ts-ignore\n", "import { globalMiddleware } from '#build/middleware'\n", "\n", "interface Route {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { defineNuxtPlugin, clearError, navigateTo, showError, useRuntimeConfig, useState, useRequestEvent } from '..'\n" ], "file_path": "packages/nuxt/src/app/plugins/router.ts", "type": "replace", "edit_start_line_idx": 3 }
import type { Compilation, Compiler } from 'webpack' import webpack from 'webpack' import { validate, isJS, extractQueryPartJS } from './util' export interface VueSSRServerPluginOptions { filename: string } export default class VueSSRServerPlugin { options: VueSSRServerPluginOptions constructor (options: Partial<VueSSRServerPluginOptions> = {}) { this.options = Object.assign({ filename: null }, options) as VueSSRServerPluginOptions } apply (compiler: Compiler) { validate(compiler) compiler.hooks.make.tap('VueSSRServerPlugin', (compilation: Compilation) => { compilation.hooks.processAssets.tapAsync({ name: 'VueSSRServerPlugin', stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL }, (assets: any, cb: any) => { const stats = compilation.getStats().toJson() const [entryName] = Object.keys(stats.entrypoints!) const entryInfo = stats.entrypoints![entryName] if (!entryInfo) { // #5553 return cb() } const entryAssets = entryInfo.assets!.filter((asset: { name: string }) => isJS(asset.name)) if (entryAssets.length > 1) { throw new Error( 'Server-side bundle should have one single entry file. ' + 'Avoid using CommonsChunkPlugin in the server config.' ) } const [entry] = entryAssets if (!entry || typeof entry.name !== 'string') { throw new Error( `Entry "${entryName}" not found. Did you specify the correct entry option?` ) } const bundle = { entry: entry.name, files: {} as Record<string, string>, maps: {} as Record<string, string> } stats.assets!.forEach((asset: any) => { if (isJS(asset.name)) { const queryPart = extractQueryPartJS(asset.name) if (queryPart !== undefined) { bundle.files[asset.name] = asset.name.replace(queryPart, '') } else { bundle.files[asset.name] = asset.name } } else if (asset.name.match(/\.js\.map$/)) { bundle.maps[asset.name.replace(/\.map$/, '')] = asset.name } else { // Do not emit non-js assets for server delete assets[asset.name] } }) const src = JSON.stringify(bundle, null, 2) assets[this.options.filename] = { source: () => src, size: () => src.length } const mjsSrc = 'export default ' + src assets[this.options.filename.replace('.json', '.mjs')] = { source: () => mjsSrc, map: () => null, size: () => mjsSrc.length } cb() }) }) } }
packages/webpack/src/plugins/vue/server.ts
0
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.00022022493067197502, 0.00017627734632696956, 0.0001665115705691278, 0.00017330306582152843, 0.000015039828213048168 ]
{ "id": 3, "code_window": [ "import { reactive, h, isReadonly } from 'vue'\n", "import { parseURL, stringifyParsedURL, parseQuery, stringifyQuery, withoutBase, isEqual, joinURL } from 'ufo'\n", "import { createError } from 'h3'\n", "import { defineNuxtPlugin, clearError, navigateTo, showError, useRuntimeConfig, useState } from '..'\n", "import { callWithNuxt } from '../nuxt'\n", "// @ts-ignore\n", "import { globalMiddleware } from '#build/middleware'\n", "\n", "interface Route {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { defineNuxtPlugin, clearError, navigateTo, showError, useRuntimeConfig, useState, useRequestEvent } from '..'\n" ], "file_path": "packages/nuxt/src/app/plugins/router.ts", "type": "replace", "edit_start_line_idx": 3 }
<svg width="132" height="32" viewBox="0 0 132 32" fill="none" xmlns="http://www.w3.org/2000/svg"> <g clip-path="url(#clip0_1264_7350)"> <path d="M26.8295 31.4227H44.4182C44.9769 31.4228 45.5257 31.2802 46.0095 31.0092C46.4933 30.7382 46.895 30.3485 47.1742 29.8791C47.4534 29.4098 47.6003 28.8774 47.6001 28.3355C47.5998 27.7936 47.4525 27.2614 47.1728 26.7922L35.3608 6.94689C35.0816 6.47766 34.6799 6.08799 34.1962 5.81706C33.7125 5.54614 33.1638 5.4035 32.6053 5.4035C32.0467 5.4035 31.498 5.54614 31.0143 5.81706C30.5306 6.08799 30.129 6.47766 29.8498 6.94689L26.8295 12.0246L20.9243 2.09529C20.6449 1.62609 20.2431 1.23648 19.7593 0.965601C19.2754 0.694725 18.7266 0.552124 18.168 0.552124C17.6094 0.552124 17.0606 0.694725 16.5767 0.965601C16.0929 1.23648 15.6911 1.62609 15.4117 2.09529L0.712988 26.7922C0.433357 27.2614 0.28601 27.7936 0.285767 28.3355C0.285524 28.8774 0.432393 29.4098 0.711603 29.8791C0.990813 30.3485 1.39252 30.7382 1.87631 31.0092C2.36011 31.2802 2.90894 31.4228 3.4676 31.4227H14.5083C18.8828 31.4227 22.1088 29.5589 24.3286 25.9227L29.7178 16.8696L32.6044 12.0246L41.2677 26.5778H29.7178L26.8295 31.4227ZM14.3283 26.5728L6.62332 26.5711L18.1731 7.16803L23.9361 16.8696L20.0775 23.3539C18.6034 25.7132 16.9287 26.5728 14.3283 26.5728Z" fill="#00DC82"/> <path d="M60.65 31.1321V19.5774C60.65 16.2709 60.3057 12.9644 60.3057 12.9644C60.3057 12.9644 61.614 15.9802 63.2665 18.8144L70.3243 31.1321H75.8673V5.69727H70.6686V17.2519C70.6686 20.5585 71.0129 23.9013 71.0129 23.9013C71.0129 23.9013 69.7046 20.8491 68.0865 18.015L60.9942 5.69727H55.4857V31.1321H60.65Z" fill="white"/> <path d="M92.2457 12.819V22.8476C92.2457 25.1731 90.7653 26.9172 88.6652 26.9172C86.7028 26.9172 85.3256 25.3184 85.3256 23.1019V12.819H80.5401V24.2283C80.5401 28.4069 83.0878 31.4228 86.9782 31.4228C89.3538 31.4228 91.2817 30.3327 92.2457 28.5886V31.1321H97.0657V12.819H92.2457Z" fill="white"/> <path d="M111.082 21.6122L116.901 12.819H111.633L108.466 17.6516L105.298 12.819H100.065L105.884 21.5759L99.6177 31.1321H104.748L108.5 25.5001L112.218 31.1321H117.314L111.082 21.6122Z" fill="white"/> <path d="M122.281 12.819H118.941V17.0339H122.281V24.4827C122.281 28.7339 124.863 31.1321 128.857 31.1321H131.714V26.8808H129.511C127.962 26.8808 127.066 26.0451 127.066 24.2647V17.0339H131.714V12.819H127.066V7.40503H122.281V12.819Z" fill="white"/> </g> <defs> <clipPath id="clip0_1264_7350"> <rect width="131.429" height="32" fill="white" transform="translate(0.285767)"/> </clipPath> </defs> </svg>
docs/public/assets/design-kit/logo/full-logo-green-light.svg
0
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.0003032514068763703, 0.00023857792257331312, 0.0001739044237183407, 0.00023857792257331312, 0.00006467349157901481 ]
{ "id": 4, "code_window": [ " delete nuxtApp._processingMiddleware\n", " })\n", "\n", " await router.replace(initialURL)\n", " if (!isEqual(route.fullPath, initialURL)) {\n", " await callWithNuxt(nuxtApp, navigateTo, [route.fullPath])\n", " }\n", " })\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const event = await callWithNuxt(nuxtApp, useRequestEvent)\n", " const options = { redirectCode: event.node.res.statusCode !== 200 ? event.node.res.statusCode || 302 : 302 }\n", " await callWithNuxt(nuxtApp, navigateTo, [route.fullPath, options])\n" ], "file_path": "packages/nuxt/src/app/plugins/router.ts", "type": "replace", "edit_start_line_idx": 252 }
import { getCurrentInstance, inject, onUnmounted } from 'vue' import type { Router, RouteLocationNormalizedLoaded, NavigationGuard, RouteLocationNormalized, RouteLocationRaw, NavigationFailure, RouteLocationPathRaw } from 'vue-router' import { sendRedirect } from 'h3' import { hasProtocol, joinURL, parseURL } from 'ufo' import { useNuxtApp, useRuntimeConfig } from '../nuxt' import type { NuxtError } from './error' import { createError } from './error' import { useState } from './state' export const useRouter = () => { return useNuxtApp()?.$router as Router } export const useRoute = (): RouteLocationNormalizedLoaded => { if (getCurrentInstance()) { return inject('_route', useNuxtApp()._route) } return useNuxtApp()._route } export const onBeforeRouteLeave = (guard: NavigationGuard) => { const unsubscribe = useRouter().beforeEach((to, from, next) => { if (to === from) { return } return guard(to, from, next) }) onUnmounted(unsubscribe) } export const onBeforeRouteUpdate = (guard: NavigationGuard) => { const unsubscribe = useRouter().beforeEach(guard) onUnmounted(unsubscribe) } export interface RouteMiddleware { (to: RouteLocationNormalized, from: RouteLocationNormalized): ReturnType<NavigationGuard> } export const defineNuxtRouteMiddleware = (middleware: RouteMiddleware) => middleware export interface AddRouteMiddlewareOptions { global?: boolean } interface AddRouteMiddleware { (name: string, middleware: RouteMiddleware, options?: AddRouteMiddlewareOptions): void (middleware: RouteMiddleware): void } export const addRouteMiddleware: AddRouteMiddleware = (name: string | RouteMiddleware, middleware?: RouteMiddleware, options: AddRouteMiddlewareOptions = {}) => { const nuxtApp = useNuxtApp() if (options.global || typeof name === 'function') { nuxtApp._middleware.global.push(typeof name === 'function' ? name : middleware) } else { nuxtApp._middleware.named[name] = middleware } } const isProcessingMiddleware = () => { try { if (useNuxtApp()._processingMiddleware) { return true } } catch { // Within an async middleware return true } return false } export interface NavigateToOptions { replace?: boolean redirectCode?: number, external?: boolean } export const navigateTo = (to: RouteLocationRaw | undefined | null, options?: NavigateToOptions): Promise<void | NavigationFailure> | RouteLocationRaw => { if (!to) { to = '/' } const toPath = typeof to === 'string' ? to : ((to as RouteLocationPathRaw).path || '/') const isExternal = hasProtocol(toPath, true) if (isExternal && !options?.external) { throw new Error('Navigating to external URL is not allowed by default. Use `nagivateTo (url, { external: true })`.') } if (isExternal && parseURL(toPath).protocol === 'script:') { throw new Error('Cannot navigate to an URL with script protocol.') } // Early redirect on client-side if (process.client && !isExternal && isProcessingMiddleware()) { return to } const router = useRouter() if (process.server) { const nuxtApp = useNuxtApp() if (nuxtApp.ssrContext && nuxtApp.ssrContext.event) { const redirectLocation = isExternal ? toPath : joinURL(useRuntimeConfig().app.baseURL, router.resolve(to).fullPath || '/') return nuxtApp.callHook('app:redirected').then(() => sendRedirect(nuxtApp.ssrContext!.event, redirectLocation, options?.redirectCode || 302)) } } // Client-side redirection using vue-router if (isExternal) { if (options?.replace) { location.replace(toPath) } else { location.href = toPath } return Promise.resolve() } return options?.replace ? router.replace(to) : router.push(to) } /** This will abort navigation within a Nuxt route middleware handler. */ export const abortNavigation = (err?: string | Partial<NuxtError>) => { if (process.dev && !isProcessingMiddleware()) { throw new Error('abortNavigation() is only usable inside a route middleware handler.') } if (err) { throw createError(err) } return false } export const setPageLayout = (layout: string) => { if (process.server) { if (process.dev && getCurrentInstance() && useState('_layout').value !== layout) { console.warn('[warn] [nuxt] `setPageLayout` should not be called to change the layout on the server within a component as this will cause hydration errors.') } useState('_layout').value = layout } const nuxtApp = useNuxtApp() if (process.dev && nuxtApp.isHydrating && useState('_layout').value !== layout) { console.warn('[warn] [nuxt] `setPageLayout` should not be called to change the layout during hydration as this will cause hydration errors.') } const inMiddleware = isProcessingMiddleware() if (inMiddleware || process.server || nuxtApp.isHydrating) { const unsubscribe = useRouter().beforeResolve((to) => { to.meta.layout = layout unsubscribe() }) } if (!inMiddleware) { useRoute().meta.layout = layout } }
packages/nuxt/src/app/composables/router.ts
1
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.007615889422595501, 0.00192515819799155, 0.00017537327948957682, 0.0012895779218524694, 0.002144554629921913 ]
{ "id": 4, "code_window": [ " delete nuxtApp._processingMiddleware\n", " })\n", "\n", " await router.replace(initialURL)\n", " if (!isEqual(route.fullPath, initialURL)) {\n", " await callWithNuxt(nuxtApp, navigateTo, [route.fullPath])\n", " }\n", " })\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const event = await callWithNuxt(nuxtApp, useRequestEvent)\n", " const options = { redirectCode: event.node.res.statusCode !== 200 ? event.node.res.statusCode || 302 : 302 }\n", " await callWithNuxt(nuxtApp, navigateTo, [route.fullPath, options])\n" ], "file_path": "packages/nuxt/src/app/plugins/router.ts", "type": "replace", "edit_start_line_idx": 252 }
<script lang="ts"> export default defineNuxtComponent({ name: 'ClientScript', props: { foo: { type: String } }, setup (_p, ctx) { const count = ref(0) const add = () => count.value++ ctx.expose({ add }) return { count, add } } }) </script> <template> <div> <div class="client-only-css"> client only script component {{ foo }} </div> <button @click="add"> {{ count }} </button> <slot name="test" /> </div> </template> <style> :root { --client-only: "client-only"; } </style> <style scoped> .client-only-css { color: rgb(50, 50, 50); } </style>
test/fixtures/basic/components/client/Script.client.vue
0
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.0001766433852026239, 0.00017010215378832072, 0.00016437217709608376, 0.0001703468442428857, 0.00000426804217568133 ]
{ "id": 4, "code_window": [ " delete nuxtApp._processingMiddleware\n", " })\n", "\n", " await router.replace(initialURL)\n", " if (!isEqual(route.fullPath, initialURL)) {\n", " await callWithNuxt(nuxtApp, navigateTo, [route.fullPath])\n", " }\n", " })\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const event = await callWithNuxt(nuxtApp, useRequestEvent)\n", " const options = { redirectCode: event.node.res.statusCode !== 200 ? event.node.res.statusCode || 302 : 302 }\n", " await callWithNuxt(nuxtApp, navigateTo, [route.fullPath, options])\n" ], "file_path": "packages/nuxt/src/app/plugins/router.ts", "type": "replace", "edit_start_line_idx": 252 }
import type { Component } from 'vue' import type { Router } from 'vue-router' import { useNuxtApp } from '../nuxt' import { useRouter } from './router' /** * Preload a component or components that have been globally registered. * * @param components Pascal-cased name or names of components to prefetch */ export const preloadComponents = async (components: string | string[]) => { if (process.server) { return } const nuxtApp = useNuxtApp() components = Array.isArray(components) ? components : [components] await Promise.all(components.map(name => _loadAsyncComponent(nuxtApp.vueApp._context.components[name]))) } /** * Prefetch a component or components that have been globally registered. * * @param components Pascal-cased name or names of components to prefetch */ export const prefetchComponents = (components: string | string[]) => { // TODO return preloadComponents(components) } // --- Internal --- function _loadAsyncComponent (component: Component) { if ((component as any)?.__asyncLoader && !(component as any).__asyncResolved) { return (component as any).__asyncLoader() } } export async function preloadRouteComponents (to: string, router: Router & { _routePreloaded?: Set<string>; _preloadPromises?: Array<Promise<any>> } = useRouter()): Promise<void> { if (process.server) { return } if (!router._routePreloaded) { router._routePreloaded = new Set() } if (router._routePreloaded.has(to)) { return } router._routePreloaded.add(to) const promises = router._preloadPromises = router._preloadPromises || [] if (promises.length > 4) { // Defer adding new preload requests until the existing ones have resolved return Promise.all(promises).then(() => preloadRouteComponents(to, router)) } const components = router.resolve(to).matched .map(component => component.components?.default) .filter(component => typeof component === 'function') for (const component of components) { const promise = Promise.resolve((component as Function)()) .catch(() => {}) .finally(() => promises.splice(promises.indexOf(promise))) promises.push(promise) } await Promise.all(promises) }
packages/nuxt/src/app/composables/preload.ts
0
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.006272431463003159, 0.0013264162698760629, 0.0001697017578408122, 0.00018966387142427266, 0.0020963975694030523 ]
{ "id": 4, "code_window": [ " delete nuxtApp._processingMiddleware\n", " })\n", "\n", " await router.replace(initialURL)\n", " if (!isEqual(route.fullPath, initialURL)) {\n", " await callWithNuxt(nuxtApp, navigateTo, [route.fullPath])\n", " }\n", " })\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const event = await callWithNuxt(nuxtApp, useRequestEvent)\n", " const options = { redirectCode: event.node.res.statusCode !== 200 ? event.node.res.statusCode || 302 : 302 }\n", " await callWithNuxt(nuxtApp, navigateTo, [route.fullPath, options])\n" ], "file_path": "packages/nuxt/src/app/plugins/router.ts", "type": "replace", "edit_start_line_idx": 252 }
--- navigation.icon: uil:layer-group description: Nuxt provides a powerful system that allows you to extend the default files, configs, and much more. --- # Layers One of the core features of Nuxt 3 is the layers and extending support. You can extend a default Nuxt application to reuse components, utils, and configuration. The layers structure is almost identical to a standard Nuxt application which makes them easy to author and maintain. Some example use cases: ::list{type="success"} - Share reusable configuration presets across projects using `nuxt.config` and `app.config` - Create a component library using `components/` directory - Create utility and composable library using `composables/` and `utils/` directories - Create Nuxt themes - Create Nuxt module presets - Share standard setup across projects :: You can extend a layer by adding the [extends](/docs/api/configuration/nuxt-config#extends) property to the `nuxt.config.ts` file. ```ts{}[nuxt.config.ts] export default defineNuxtConfig({ extends: [ '../base', // Extend from a local layer '@my-themes/awesome', // Extend from an installed npm package 'github:my-themes/awesome#v1', // Extend from a git repository ] }) ``` ## Authoring Nuxt Layers See [Layer Author Guide](/docs/guide/going-further/layers) to learn more. ## Examples - [Nuxt Docus Theme](https://github.com/nuxt-themes/docus#readme) - [Nuxt Content Wind Theme](https://github.com/Atinux/content-wind#readme)
docs/content/1.docs/1.getting-started/9.layers.md
0
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.0011045796563848853, 0.00039928764454089105, 0.0001625597506063059, 0.00016500556375831366, 0.00040720278047956526 ]
{ "id": 5, "code_window": [ "} from 'vue-router'\n", "import { createError } from 'h3'\n", "import { withoutBase, isEqual } from 'ufo'\n", "import type NuxtPage from '../page'\n", "import { callWithNuxt, defineNuxtPlugin, useRuntimeConfig, showError, clearError, navigateTo, useError, useState } from '#app'\n", "// @ts-ignore\n", "import _routes from '#build/routes'\n", "// @ts-ignore\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { callWithNuxt, defineNuxtPlugin, useRuntimeConfig, showError, clearError, navigateTo, useError, useState, useRequestEvent } from '#app'\n" ], "file_path": "packages/nuxt/src/pages/runtime/plugins/router.ts", "type": "replace", "edit_start_line_idx": 14 }
import { computed, isReadonly, reactive, shallowRef } from 'vue' import type { NavigationGuard, RouteLocation } from 'vue-router' import { createRouter, createWebHistory, createMemoryHistory, createWebHashHistory } from 'vue-router' import { createError } from 'h3' import { withoutBase, isEqual } from 'ufo' import type NuxtPage from '../page' import { callWithNuxt, defineNuxtPlugin, useRuntimeConfig, showError, clearError, navigateTo, useError, useState } from '#app' // @ts-ignore import _routes from '#build/routes' // @ts-ignore import routerOptions from '#build/router.options' // @ts-ignore import { globalMiddleware, namedMiddleware } from '#build/middleware' declare module '@vue/runtime-core' { export interface GlobalComponents { NuxtPage: typeof NuxtPage } } // https://github.com/vuejs/router/blob/4a0cc8b9c1e642cdf47cc007fa5bbebde70afc66/packages/router/src/history/html5.ts#L37 function createCurrentLocation ( base: string, location: Location ): string { const { pathname, search, hash } = location // allows hash bases like #, /#, #/, #!, #!/, /#!/, or even /folder#end const hashPos = base.indexOf('#') if (hashPos > -1) { const slicePos = hash.includes(base.slice(hashPos)) ? base.slice(hashPos).length : 1 let pathFromHash = hash.slice(slicePos) // prepend the starting slash to hash so the url starts with /# if (pathFromHash[0] !== '/') { pathFromHash = '/' + pathFromHash } return withoutBase(pathFromHash, '') } const path = withoutBase(pathname, base) return path + search + hash } export default defineNuxtPlugin(async (nuxtApp) => { let routerBase = useRuntimeConfig().app.baseURL if (routerOptions.hashMode && !routerBase.includes('#')) { // allow the user to provide a `#` in the middle: `/base/#/app` routerBase += '#' } const history = routerOptions.history?.(routerBase) ?? (process.client ? (routerOptions.hashMode ? createWebHashHistory(routerBase) : createWebHistory(routerBase)) : createMemoryHistory(routerBase) ) const routes = routerOptions.routes?.(_routes) ?? _routes const initialURL = process.server ? nuxtApp.ssrContext!.url : createCurrentLocation(routerBase, window.location) const router = createRouter({ ...routerOptions, history, routes }) nuxtApp.vueApp.use(router) const previousRoute = shallowRef(router.currentRoute.value) router.afterEach((_to, from) => { previousRoute.value = from }) Object.defineProperty(nuxtApp.vueApp.config.globalProperties, 'previousRoute', { get: () => previousRoute.value }) // Allows suspending the route object until page navigation completes const _route = shallowRef(router.resolve(initialURL) as RouteLocation) const syncCurrentRoute = () => { _route.value = router.currentRoute.value } nuxtApp.hook('page:finish', syncCurrentRoute) router.afterEach((to, from) => { // We won't trigger suspense if the component is reused between routes // so we need to update the route manually if (to.matched[0]?.components?.default === from.matched[0]?.components?.default) { syncCurrentRoute() } }) // https://github.com/vuejs/router/blob/main/packages/router/src/router.ts#L1225-L1233 const route = {} as RouteLocation for (const key in _route.value) { (route as any)[key] = computed(() => _route.value[key as keyof RouteLocation]) } nuxtApp._route = reactive(route) nuxtApp._middleware = nuxtApp._middleware || { global: [], named: {} } const error = useError() try { if (process.server) { await router.push(initialURL) } await router.isReady() } catch (error: any) { // We'll catch 404s here await callWithNuxt(nuxtApp, showError, [error]) } const initialLayout = useState('_layout') router.beforeEach(async (to, from) => { to.meta = reactive(to.meta) if (nuxtApp.isHydrating && initialLayout.value && !isReadonly(to.meta.layout)) { to.meta.layout = initialLayout.value } nuxtApp._processingMiddleware = true type MiddlewareDef = string | NavigationGuard const middlewareEntries = new Set<MiddlewareDef>([...globalMiddleware, ...nuxtApp._middleware.global]) for (const component of to.matched) { const componentMiddleware = component.meta.middleware as MiddlewareDef | MiddlewareDef[] if (!componentMiddleware) { continue } if (Array.isArray(componentMiddleware)) { for (const entry of componentMiddleware) { middlewareEntries.add(entry) } } else { middlewareEntries.add(componentMiddleware) } } for (const entry of middlewareEntries) { const middleware = typeof entry === 'string' ? nuxtApp._middleware.named[entry] || await namedMiddleware[entry]?.().then((r: any) => r.default || r) : entry if (!middleware) { if (process.dev) { throw new Error(`Unknown route middleware: '${entry}'. Valid middleware: ${Object.keys(namedMiddleware).map(mw => `'${mw}'`).join(', ')}.`) } throw new Error(`Unknown route middleware: '${entry}'.`) } const result = await callWithNuxt(nuxtApp, middleware, [to, from]) if (process.server || (!nuxtApp.payload.serverRendered && nuxtApp.isHydrating)) { if (result === false || result instanceof Error) { const error = result || createError({ statusCode: 404, statusMessage: `Page Not Found: ${initialURL}` }) await callWithNuxt(nuxtApp, showError, [error]) return false } } if (result || result === false) { return result } } }) router.afterEach(async (to) => { delete nuxtApp._processingMiddleware if (process.client && !nuxtApp.isHydrating && error.value) { // Clear any existing errors await callWithNuxt(nuxtApp, clearError) } if (to.matched.length === 0) { await callWithNuxt(nuxtApp, showError, [createError({ statusCode: 404, fatal: false, statusMessage: `Page not found: ${to.fullPath}` })]) } else if (process.server) { const currentURL = to.fullPath || '/' if (!isEqual(currentURL, initialURL)) { await callWithNuxt(nuxtApp, navigateTo, [currentURL]) } } }) nuxtApp.hooks.hookOnce('app:created', async () => { try { await router.replace({ ...router.resolve(initialURL), name: undefined, // #4920, #$4982 force: true }) } catch (error: any) { // We'll catch middleware errors or deliberate exceptions here await callWithNuxt(nuxtApp, showError, [error]) } }) return { provide: { router } } })
packages/nuxt/src/pages/runtime/plugins/router.ts
1
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.9942131638526917, 0.0487818606197834, 0.00016469253750983626, 0.0004709312634076923, 0.21143895387649536 ]
{ "id": 5, "code_window": [ "} from 'vue-router'\n", "import { createError } from 'h3'\n", "import { withoutBase, isEqual } from 'ufo'\n", "import type NuxtPage from '../page'\n", "import { callWithNuxt, defineNuxtPlugin, useRuntimeConfig, showError, clearError, navigateTo, useError, useState } from '#app'\n", "// @ts-ignore\n", "import _routes from '#build/routes'\n", "// @ts-ignore\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { callWithNuxt, defineNuxtPlugin, useRuntimeConfig, showError, clearError, navigateTo, useError, useState, useRequestEvent } from '#app'\n" ], "file_path": "packages/nuxt/src/pages/runtime/plugins/router.ts", "type": "replace", "edit_start_line_idx": 14 }
import chokidar from 'chokidar' import type { Nuxt } from '@nuxt/schema' import { importModule, isIgnored } from '@nuxt/kit' import { debounce } from 'perfect-debounce' import { normalize } from 'pathe' import { createApp, generateApp as _generateApp } from './app' export async function build (nuxt: Nuxt) { const app = createApp(nuxt) const generateApp = debounce(() => _generateApp(nuxt, app), undefined, { leading: true }) await generateApp() if (nuxt.options.dev) { watch(nuxt) nuxt.hook('builder:watch', async (event, path) => { if (event !== 'change' && /^(app\.|error\.|plugins\/|middleware\/|layouts\/)/i.test(path)) { if (path.startsWith('app')) { app.mainComponent = undefined } if (path.startsWith('error')) { app.errorComponent = undefined } await generateApp() } }) nuxt.hook('builder:generateApp', (options) => { // Bypass debounce if we are selectively invalidating templates if (options) { return _generateApp(nuxt, app, options) } return generateApp() }) } await nuxt.callHook('build:before') if (!nuxt.options._prepare) { await bundle(nuxt) await nuxt.callHook('build:done') } if (!nuxt.options.dev) { await nuxt.callHook('close', nuxt) } } function watch (nuxt: Nuxt) { const watcher = chokidar.watch(nuxt.options._layers.map(i => i.config.srcDir as string).filter(Boolean), { ...nuxt.options.watchers.chokidar, cwd: nuxt.options.srcDir, ignoreInitial: true, ignored: [ isIgnored, '.nuxt', 'node_modules' ] }) watcher.on('all', (event, path) => nuxt.callHook('builder:watch', event, normalize(path))) nuxt.hook('close', () => watcher.close()) return watcher } async function bundle (nuxt: Nuxt) { try { const { bundle } = typeof nuxt.options.builder === 'string' ? await importModule(nuxt.options.builder, { paths: nuxt.options.rootDir }) : nuxt.options.builder return bundle(nuxt) } catch (error: any) { await nuxt.callHook('build:error', error) if (error.toString().includes('Cannot find module \'@nuxt/webpack-builder\'')) { throw new Error([ 'Could not load `@nuxt/webpack-builder`. You may need to add it to your project dependencies, following the steps in `https://github.com/nuxt/framework/pull/2812`.' ].join('\n')) } throw error } }
packages/nuxt/src/core/builder.ts
0
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.0002164623001590371, 0.00017648711218498647, 0.0001684592425590381, 0.0001706715556792915, 0.000015235980754368939 ]
{ "id": 5, "code_window": [ "} from 'vue-router'\n", "import { createError } from 'h3'\n", "import { withoutBase, isEqual } from 'ufo'\n", "import type NuxtPage from '../page'\n", "import { callWithNuxt, defineNuxtPlugin, useRuntimeConfig, showError, clearError, navigateTo, useError, useState } from '#app'\n", "// @ts-ignore\n", "import _routes from '#build/routes'\n", "// @ts-ignore\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { callWithNuxt, defineNuxtPlugin, useRuntimeConfig, showError, clearError, navigateTo, useError, useState, useRequestEvent } from '#app'\n" ], "file_path": "packages/nuxt/src/pages/runtime/plugins/router.ts", "type": "replace", "edit_start_line_idx": 14 }
<template> <div>You should not see me</div> </template> <script setup> definePageMeta({ middleware: () => { return navigateTo({ path: '/' }, { redirectCode: 307 }) } }) </script>
test/fixtures/basic/pages/navigate-to-redirect.vue
0
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.0006830162601545453, 0.0004274118400644511, 0.00017180743452627212, 0.0004274118400644511, 0.00025560439098626375 ]
{ "id": 5, "code_window": [ "} from 'vue-router'\n", "import { createError } from 'h3'\n", "import { withoutBase, isEqual } from 'ufo'\n", "import type NuxtPage from '../page'\n", "import { callWithNuxt, defineNuxtPlugin, useRuntimeConfig, showError, clearError, navigateTo, useError, useState } from '#app'\n", "// @ts-ignore\n", "import _routes from '#build/routes'\n", "// @ts-ignore\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { callWithNuxt, defineNuxtPlugin, useRuntimeConfig, showError, clearError, navigateTo, useError, useState, useRequestEvent } from '#app'\n" ], "file_path": "packages/nuxt/src/pages/runtime/plugins/router.ts", "type": "replace", "edit_start_line_idx": 14 }
export default defineNuxtRouteMiddleware((to) => { to.meta.foo = 'Injected by extended middleware from foo' })
test/fixtures/basic/extends/node_modules/foo/middleware/foo.ts
0
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.0038917900528758764, 0.0038917900528758764, 0.0038917900528758764, 0.0038917900528758764, 0 ]
{ "id": 6, "code_window": [ " })])\n", " } else if (process.server) {\n", " const currentURL = to.fullPath || '/'\n", " if (!isEqual(currentURL, initialURL)) {\n", " await callWithNuxt(nuxtApp, navigateTo, [currentURL])\n", " }\n", " }\n", " })\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const event = await callWithNuxt(nuxtApp, useRequestEvent)\n", " const options = { redirectCode: event.node.res.statusCode !== 200 ? event.node.res.statusCode || 302 : 302 }\n", " await callWithNuxt(nuxtApp, navigateTo, [currentURL, options])\n" ], "file_path": "packages/nuxt/src/pages/runtime/plugins/router.ts", "type": "replace", "edit_start_line_idx": 181 }
import { reactive, h, isReadonly } from 'vue' import { parseURL, stringifyParsedURL, parseQuery, stringifyQuery, withoutBase, isEqual, joinURL } from 'ufo' import { createError } from 'h3' import { defineNuxtPlugin, clearError, navigateTo, showError, useRuntimeConfig, useState } from '..' import { callWithNuxt } from '../nuxt' // @ts-ignore import { globalMiddleware } from '#build/middleware' interface Route { /** Percentage encoded pathname section of the URL. */ path: string /** The whole location including the `search` and `hash`. */ fullPath: string /** Object representation of the `search` property of the current location. */ query: Record<string, any> /** Hash of the current location. If present, starts with a `#`. */ hash: string /** Name of the matched record */ name: string | null | undefined /** Object of decoded params extracted from the `path`. */ params: Record<string, any> /** * The location we were initially trying to access before ending up * on the current location. */ redirectedFrom: Route | undefined /** Merged `meta` properties from all of the matched route records. */ meta: Record<string, any> } function getRouteFromPath (fullPath: string | Partial<Route>) { if (typeof fullPath === 'object') { fullPath = stringifyParsedURL({ pathname: fullPath.path || '', search: stringifyQuery(fullPath.query || {}), hash: fullPath.hash || '' }) } const url = parseURL(fullPath.toString()) return { path: url.pathname, fullPath, query: parseQuery(url.search), hash: url.hash, // stub properties for compat with vue-router params: {}, name: undefined, matched: [], redirectedFrom: undefined, meta: {}, href: fullPath } } type RouteGuardReturn = void | Error | string | false interface RouteGuard { (to: Route, from: Route): RouteGuardReturn | Promise<RouteGuardReturn> } interface RouterHooks { 'resolve:before': (to: Route, from: Route) => RouteGuardReturn | Promise<RouteGuardReturn> 'navigate:before': (to: Route, from: Route) => RouteGuardReturn | Promise<RouteGuardReturn> 'navigate:after': (to: Route, from: Route) => void | Promise<void> 'error': (err: any) => void | Promise<void> } interface Router { currentRoute: Route isReady: () => Promise<void> options: {} install: () => Promise<void> // Navigation push: (url: string) => Promise<void> replace: (url: string) => Promise<void> back: () => void go: (delta: number) => void forward: () => void // Guards beforeResolve: (guard: RouterHooks['resolve:before']) => () => void beforeEach: (guard: RouterHooks['navigate:before']) => () => void afterEach: (guard: RouterHooks['navigate:after']) => () => void onError: (handler: RouterHooks['error']) => () => void // Routes resolve: (url: string | Partial<Route>) => Route addRoute: (parentName: string, route: Route) => void getRoutes: () => any[] hasRoute: (name: string) => boolean removeRoute: (name: string) => void } export default defineNuxtPlugin<{ route: Route, router: Router }>((nuxtApp) => { const initialURL = process.client ? withoutBase(window.location.pathname, useRuntimeConfig().app.baseURL) + window.location.search + window.location.hash : nuxtApp.ssrContext!.url const routes: Route[] = [] const hooks: { [key in keyof RouterHooks]: RouterHooks[key][] } = { 'navigate:before': [], 'resolve:before': [], 'navigate:after': [], error: [] } const registerHook = <T extends keyof RouterHooks>(hook: T, guard: RouterHooks[T]) => { hooks[hook].push(guard) return () => hooks[hook].splice(hooks[hook].indexOf(guard), 1) } const baseURL = useRuntimeConfig().app.baseURL const route: Route = reactive(getRouteFromPath(initialURL)) async function handleNavigation (url: string | Partial<Route>, replace?: boolean): Promise<void> { try { // Resolve route const to = getRouteFromPath(url) // Run beforeEach hooks for (const middleware of hooks['navigate:before']) { const result = await middleware(to, route) // Cancel navigation if (result === false || result instanceof Error) { return } // Redirect if (result) { return handleNavigation(result, true) } } for (const handler of hooks['resolve:before']) { await handler(to, route) } // Perform navigation Object.assign(route, to) if (process.client) { window.history[replace ? 'replaceState' : 'pushState']({}, '', joinURL(baseURL, to.fullPath)) if (!nuxtApp.isHydrating) { // Clear any existing errors await callWithNuxt(nuxtApp, clearError) } } // Run afterEach hooks for (const middleware of hooks['navigate:after']) { await middleware(to, route) } } catch (err) { if (process.dev && !hooks.error.length) { console.warn('No error handlers registered to handle middleware errors. You can register an error handler with `router.onError()`', err) } for (const handler of hooks.error) { await handler(err) } } } const router: Router = { currentRoute: route, isReady: () => Promise.resolve(), // These options provide a similar API to vue-router but have no effect options: {}, install: () => Promise.resolve(), // Navigation push: (url: string) => handleNavigation(url, false), replace: (url: string) => handleNavigation(url, true), back: () => window.history.go(-1), go: (delta: number) => window.history.go(delta), forward: () => window.history.go(1), // Guards beforeResolve: (guard: RouterHooks['resolve:before']) => registerHook('resolve:before', guard), beforeEach: (guard: RouterHooks['navigate:before']) => registerHook('navigate:before', guard), afterEach: (guard: RouterHooks['navigate:after']) => registerHook('navigate:after', guard), onError: (handler: RouterHooks['error']) => registerHook('error', handler), // Routes resolve: getRouteFromPath, addRoute: (parentName: string, route: Route) => { routes.push(route) }, getRoutes: () => routes, hasRoute: (name: string) => routes.some(route => route.name === name), removeRoute: (name: string) => { const index = routes.findIndex(route => route.name === name) if (index !== -1) { routes.splice(index, 1) } } } nuxtApp.vueApp.component('RouterLink', { functional: true, props: { to: String, custom: Boolean, replace: Boolean, // Not implemented activeClass: String, exactActiveClass: String, ariaCurrentValue: String }, setup: (props, { slots }) => { const navigate = () => handleNavigation(props.to, props.replace) return () => { const route = router.resolve(props.to) return props.custom ? slots.default?.({ href: props.to, navigate, route }) : h('a', { href: props.to, onClick: (e: MouseEvent) => { e.preventDefault(); return navigate() } }, slots) } } }) if (process.client) { window.addEventListener('popstate', (event) => { const location = (event.target as Window).location router.replace(location.href.replace(location.origin, '')) }) } nuxtApp._route = route // Handle middleware nuxtApp._middleware = nuxtApp._middleware || { global: [], named: {} } const initialLayout = useState('_layout') nuxtApp.hooks.hookOnce('app:created', async () => { router.beforeEach(async (to, from) => { to.meta = reactive(to.meta || {}) if (nuxtApp.isHydrating && initialLayout.value && !isReadonly(to.meta.layout)) { to.meta.layout = initialLayout.value } nuxtApp._processingMiddleware = true const middlewareEntries = new Set<RouteGuard>([...globalMiddleware, ...nuxtApp._middleware.global]) for (const middleware of middlewareEntries) { const result = await callWithNuxt(nuxtApp, middleware, [to, from]) if (process.server) { if (result === false || result instanceof Error) { const error = result || createError({ statusCode: 404, statusMessage: `Page Not Found: ${initialURL}` }) return callWithNuxt(nuxtApp, showError, [error]) } } if (result || result === false) { return result } } }) router.afterEach(() => { delete nuxtApp._processingMiddleware }) await router.replace(initialURL) if (!isEqual(route.fullPath, initialURL)) { await callWithNuxt(nuxtApp, navigateTo, [route.fullPath]) } }) return { provide: { route, router } } })
packages/nuxt/src/app/plugins/router.ts
1
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.014066820032894611, 0.0014180921716615558, 0.0001616536610526964, 0.0002229490492027253, 0.0027825739234685898 ]
{ "id": 6, "code_window": [ " })])\n", " } else if (process.server) {\n", " const currentURL = to.fullPath || '/'\n", " if (!isEqual(currentURL, initialURL)) {\n", " await callWithNuxt(nuxtApp, navigateTo, [currentURL])\n", " }\n", " }\n", " })\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const event = await callWithNuxt(nuxtApp, useRequestEvent)\n", " const options = { redirectCode: event.node.res.statusCode !== 200 ? event.node.res.statusCode || 302 : 302 }\n", " await callWithNuxt(nuxtApp, navigateTo, [currentURL, options])\n" ], "file_path": "packages/nuxt/src/pages/runtime/plugins/router.ts", "type": "replace", "edit_start_line_idx": 181 }
export default defineNuxtRouteMiddleware(async () => { await new Promise(resolve => setTimeout(resolve, 10)) setPageLayout('custom') })
test/fixtures/basic/middleware/sets-layout.ts
0
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.0003421572328079492, 0.0003421572328079492, 0.0003421572328079492, 0.0003421572328079492, 0 ]
{ "id": 6, "code_window": [ " })])\n", " } else if (process.server) {\n", " const currentURL = to.fullPath || '/'\n", " if (!isEqual(currentURL, initialURL)) {\n", " await callWithNuxt(nuxtApp, navigateTo, [currentURL])\n", " }\n", " }\n", " })\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const event = await callWithNuxt(nuxtApp, useRequestEvent)\n", " const options = { redirectCode: event.node.res.statusCode !== 200 ? event.node.res.statusCode || 302 : 302 }\n", " await callWithNuxt(nuxtApp, navigateTo, [currentURL, options])\n" ], "file_path": "packages/nuxt/src/pages/runtime/plugins/router.ts", "type": "replace", "edit_start_line_idx": 181 }
import type { WebpackPluginInstance, Configuration as WebpackConfig } from 'webpack' import type { Plugin as VitePlugin, UserConfig as ViteConfig } from 'vite' import { useNuxt } from './context' export interface ExtendConfigOptions { /** * Install plugin on dev * * @default true */ dev?: boolean /** * Install plugin on build * * @default true */ build?: boolean /** * Install plugin on server side * * @default true */ server?: boolean /** * Install plugin on client side * * @default true */ client?: boolean } export interface ExtendWebpackConfigOptions extends ExtendConfigOptions { } export interface ExtendViteConfigOptions extends ExtendConfigOptions {} /** * Extend webpack config * * The fallback function might be called multiple times * when applying to both client and server builds. */ export function extendWebpackConfig ( fn: ((config: WebpackConfig)=> void), options: ExtendWebpackConfigOptions = {} ) { const nuxt = useNuxt() if (options.dev === false && nuxt.options.dev) { return } if (options.build === false && nuxt.options.build) { return } nuxt.hook('webpack:config', (configs: WebpackConfig[]) => { if (options.server !== false) { const config = configs.find(i => i.name === 'server') if (config) { fn(config) } } if (options.client !== false) { const config = configs.find(i => i.name === 'client') if (config) { fn(config) } } }) } /** * Extend Vite config */ export function extendViteConfig ( fn: ((config: ViteConfig) => void), options: ExtendViteConfigOptions = {} ) { const nuxt = useNuxt() if (options.dev === false && nuxt.options.dev) { return } if (options.build === false && nuxt.options.build) { return } if (options.server !== false && options.client !== false) { // Call fn() only once return nuxt.hook('vite:extend', ({ config }) => fn(config)) } nuxt.hook('vite:extendConfig', (config, { isClient, isServer }) => { if (options.server !== false && isServer) { return fn(config) } if (options.client !== false && isClient) { return fn(config) } }) } /** * Append webpack plugin to the config. */ export function addWebpackPlugin (plugin: WebpackPluginInstance | WebpackPluginInstance[], options?: ExtendWebpackConfigOptions) { extendWebpackConfig((config) => { config.plugins = config.plugins || [] if (Array.isArray(plugin)) { config.plugins.push(...plugin) } else { config.plugins.push(plugin) } }, options) } /** * Append Vite plugin to the config. */ export function addVitePlugin (plugin: VitePlugin | VitePlugin[], options?: ExtendViteConfigOptions) { extendViteConfig((config) => { config.plugins = config.plugins || [] if (Array.isArray(plugin)) { config.plugins.push(...plugin) } else { config.plugins.push(plugin) } }, options) }
packages/kit/src/build.ts
0
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.004182730335742235, 0.0007137133507058024, 0.00016628230514470488, 0.00017364048107992858, 0.0012576202861964703 ]
{ "id": 6, "code_window": [ " })])\n", " } else if (process.server) {\n", " const currentURL = to.fullPath || '/'\n", " if (!isEqual(currentURL, initialURL)) {\n", " await callWithNuxt(nuxtApp, navigateTo, [currentURL])\n", " }\n", " }\n", " })\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const event = await callWithNuxt(nuxtApp, useRequestEvent)\n", " const options = { redirectCode: event.node.res.statusCode !== 200 ? event.node.res.statusCode || 302 : 302 }\n", " await callWithNuxt(nuxtApp, navigateTo, [currentURL, options])\n" ], "file_path": "packages/nuxt/src/pages/runtime/plugins/router.ts", "type": "replace", "edit_start_line_idx": 181 }
--- description: This wrapper around useAsyncData triggers navigation immediately. --- # `useLazyAsyncData` `useLazyAsyncData` provides a wrapper around `useAsyncData` that triggers navigation before the handler is resolved by setting the `lazy` option to `true`. ## Description By default, [useAsyncData](/docs/api/composables/use-async-data) blocks navigation until its async handler is resolved. > `useLazyAsyncData` has the same signature as `useAsyncData`. :ReadMore{link="/docs/api/composables/use-async-data"} ## Example ```vue <template> <div> {{ pending ? 'Loading' : count }} </div> </template> <script setup> /* Navigation will occur before fetching is complete. Handle pending and error states directly within your component's template */ const { pending, data: count } = useLazyAsyncData('count', () => $fetch('/api/count')) watch(count, (newCount) => { // Because count starts out null, you won't have access // to its contents immediately, but you can watch it. }) </script> ``` :ReadMore{link="/docs/getting-started/data-fetching#uselazyasyncdata"}
docs/content/1.docs/3.api/1.composables/use-lazy-async-data.md
0
https://github.com/nuxt/nuxt/commit/de4086f6edabefc1a46ee08a099c3065f24f6fe5
[ 0.00017191068036481738, 0.0001676385145401582, 0.00016169990703929216, 0.00016847174265421927, 0.000003767855559999589 ]
{ "id": 0, "code_window": [ " return '';\n", " } else if (Math.random() > 0) {\n", " return [''];\n", " }\n", " return new Error('');\n", " },\n", " BAD_listing: true,\n", " },\n", " },\n", " options: { files: { relativeTo: __dirname } }\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " }\n" ], "file_path": "types/hapi__inert/hapi__inert-tests.ts", "type": "replace", "edit_start_line_idx": 99 }
import { Server, Lifecycle, } from '@hapi/hapi'; import * as path from 'path'; import * as inert from '@hapi/inert'; const server = new Server({ port: 3000, routes: { files: { relativeTo: path.join(__dirname, 'public') } } }); const provision = async () => { await server.register(inert); await server.register({ plugin: inert, options: { etagsCacheMaxSize: 400 }, }); await server.register({ plugin: inert, once: true, }); server.route({ method: 'GET', path: '/{param*}', handler: { directory: { path: '.', redirectToSlash: true, index: true } } }); // https://github.com/hapijs/inert#serving-a-single-file server.route({ method: 'GET', path: '/{path*}', handler: { file: 'page.html' } }); // https://github.com/hapijs/inert#customized-file-response server.route({ method: 'GET', path: '/file', handler(request, reply) { let path = 'plain.txt'; if (request.headers['x-magic'] === 'sekret') { path = 'awesome.png'; } return reply.file(path).vary('x-magic'); } }); const handler: Lifecycle.Method = (request, h) => { const response = request.response; if (response instanceof Error && response.output.statusCode === 404) { return h.file('404.html').code(404); } return h.continue; }; server.ext('onPostHandler', handler); const file: inert.FileHandlerRouteObject = { path: '', confine: true, }; const directory: inert.DirectoryHandlerRouteObject = { path: '', listing: true }; server.route({ path: '', method: 'GET', handler: { file, directory: { path() { if (Math.random() > 0.5) { return ''; } else if (Math.random() > 0) { return ['']; } return new Error(''); }, BAD_listing: true, }, }, options: { files: { relativeTo: __dirname } } }); };
types/hapi__inert/hapi__inert-tests.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9c19be36acb0e6c0c3c652465361b0da1090e3ce
[ 0.9911813735961914, 0.09104729443788528, 0.00016519581549800932, 0.00017015771300066262, 0.2846556007862091 ]
{ "id": 0, "code_window": [ " return '';\n", " } else if (Math.random() > 0) {\n", " return [''];\n", " }\n", " return new Error('');\n", " },\n", " BAD_listing: true,\n", " },\n", " },\n", " options: { files: { relativeTo: __dirname } }\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " }\n" ], "file_path": "types/hapi__inert/hapi__inert-tests.ts", "type": "replace", "edit_start_line_idx": 99 }
// Type definitions for express-handlebars // Project: https://github.com/ericf/express-handlebars // Definitions by: Sam Saint-Pettersen <https://github.com/stpettersens>, Igor Dultsev <https://github.com/yhaskell> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 interface PartialTemplateOptions { cache?: boolean; precompiled?: boolean; } interface RenderOptions { cache?: boolean; data?: Object; helpers?: any; partials?: any; } interface ExphbsOptions { handlebars?: any; extname?: string; layoutsDir?: string; partialsDir?: any; defaultLayout?: string; helpers?: any; compilerOptions?: any; } interface ExphbsCallback { (err: any, content?: string): void; } interface Exphbs { engine: Function; extname: string; compiled: Object; precompiled: Object; create(options?: ExphbsOptions): Exphbs; getPartials(options?: PartialTemplateOptions): Promise<Object>; getTemplate(filePath: string, options?: PartialTemplateOptions): Promise<Function>; getTemplates(dirPath: string, options?: PartialTemplateOptions): Promise<Object>; render(filePath: string, context: Object, options?: RenderOptions): Promise<string>; renderView(viewPath: string, callback: ExphbsCallback): void; renderView(viewPath: string, options: any, callback: ExphbsCallback): void; } interface ExpressHandlebars { (options?: ExphbsOptions): Function; create (options?: ExphbsOptions): Exphbs; } declare module "express-handlebars" { var exphbs: ExpressHandlebars; export = exphbs; }
types/express-handlebars/index.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9c19be36acb0e6c0c3c652465361b0da1090e3ce
[ 0.00021800310059916228, 0.0001774693955667317, 0.000163519405759871, 0.00017109766486100852, 0.000018546792489360087 ]
{ "id": 0, "code_window": [ " return '';\n", " } else if (Math.random() > 0) {\n", " return [''];\n", " }\n", " return new Error('');\n", " },\n", " BAD_listing: true,\n", " },\n", " },\n", " options: { files: { relativeTo: __dirname } }\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " }\n" ], "file_path": "types/hapi__inert/hapi__inert-tests.ts", "type": "replace", "edit_start_line_idx": 99 }
// Type definitions for NodeEach v0.4.9 // Project: http://www.adaltas.com/projects/node-each/ // Definitions by: Michael Zabka <https://github.com/misak113> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Each { paused: boolean; readable: boolean; started: number; done: number; total: number; on(eventName: string, onCallback: Function): Each; on(eventName: "item", onItem: (item: any, next: (error?: Error) => void) => void): Each; on(eventName: "error", onError: (error: Error[]) => void): Each; on(eventName: "error", onError: (error: Error) => void): Each; on(eventName: "both", onBoth: (error?: Error[]) => void): Each; on(eventName: "end", onEnd: () => void): Each; parallel(mode: number): Each; parallel(mode: boolean): Each; shift(items: any[]): void; write(items: any[]): void; unshift(items: any[]): void; end(): Each; times(): Each; repeat(): Each; sync(): Each; files(glob: any): void; files(base: any, glob: any): void; } interface EachStatic { (array: any[]): Each; } declare var each: EachStatic; declare module "each" { export = each; }
types/each/index.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9c19be36acb0e6c0c3c652465361b0da1090e3ce
[ 0.00017525862494949251, 0.0001724676985759288, 0.000170210943906568, 0.0001722005836199969, 0.0000018592079413792817 ]
{ "id": 0, "code_window": [ " return '';\n", " } else if (Math.random() > 0) {\n", " return [''];\n", " }\n", " return new Error('');\n", " },\n", " BAD_listing: true,\n", " },\n", " },\n", " options: { files: { relativeTo: __dirname } }\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " }\n" ], "file_path": "types/hapi__inert/hapi__inert-tests.ts", "type": "replace", "edit_start_line_idx": 99 }
import * as clamp from 'clamp-js'; const lineElement: HTMLElement = document.createElement('div'); lineElement.style.setProperty('font-size', '3px'); lineElement.style.setProperty('line-height', '5px'); lineElement.style.setProperty('height', '11px'); lineElement.style.setProperty('width', '15px'); const newtext: Text = document.createTextNode('Lorem ipsum, dolor sit amet.'); lineElement.appendChild(newtext); const clampFromElement = clamp(lineElement); const clampFromDefaults = clamp(lineElement, { clamp: 'auto', useNativeClamp: true, splitOnChars: ['.', '-', '–', '—', ' '], animate: false, truncationChar: '…', truncationHTML: null }); const clampWithOptions = clamp(lineElement, { clamp: 1, useNativeClamp: false, splitOnChars: [','], animate: true, truncationChar: '--', truncationHTML: '<span></span>' });
types/clamp-js/clamp-js-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9c19be36acb0e6c0c3c652465361b0da1090e3ce
[ 0.0001745606423355639, 0.0001700910652289167, 0.000166409183293581, 0.0001693033700576052, 0.0000033741091556294123 ]
{ "id": 1, "code_window": [ " return [''];\n", " }\n", " return new Error('');\n", " },\n", " BAD_listing: true,\n", " },\n", " },\n", " options: { files: { relativeTo: __dirname } }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "types/inert/inert-tests.ts", "type": "replace", "edit_start_line_idx": 100 }
// Copied from: https://github.com/hapijs/inert#examples import Path = require('path'); import Hapi = require('hapi'); import Inert = require('inert'); const server = new Hapi.Server({ connections: { routes: { files: { relativeTo: Path.join(__dirname, 'public') } } } }); server.connection({ port: 3000 }); server.register(Inert, () => {}); // added in addition to code from docs const options: Inert.OptionalRegistrationOptions = {etagsCacheMaxSize: 400}; server.register({ register: Inert, options, }, (err) => {}); // added in addition to code from docs server.register({ register: Inert, once: true, }, (err) => {}); server.route({ method: 'GET', path: '/{param*}', handler: { directory: { path: '.', redirectToSlash: true, index: true } } }); server.start((err) => { if (err) { throw err; } console.log('Server running at:', server.info!.uri); }); // https://github.com/hapijs/inert#serving-a-single-file server.route({ method: 'GET', path: '/{path*}', handler: { file: 'page.html' } }); // https://github.com/hapijs/inert#customized-file-response server.route({ method: 'GET', path: '/file', handler: function (request, reply) { let path = 'plain.txt'; if (request.headers['x-magic'] === 'sekret') { path = 'awesome.png'; } return reply.file(path).vary('x-magic'); } }); const handler: Hapi.ServerExtRequestHandler = function (request, reply) { const response = request.response!; if (response.isBoom && response.output!.statusCode === 404) { return reply.file('404.html').code(404); } return reply.continue(); } server.ext('onPostHandler', handler); // additional code added in addition to doc example code var file: Inert.FileHandlerRouteObject = { path: '', confine: true, }; var directory: Inert.DirectoryHandlerRouteObject = { path: '', listing: true }; file = { path: '', confine: true, }; server.route({ path: '', method: 'GET', handler: { file, directory: { path: function(){ if(Math.random() > 0.5) { return ''; } else if(Math.random() > 0) { return ['']; } return new Error(''); }, BAD_listing: true, // TODO change typings to make this error }, }, config: { files: { relativeTo: __dirname } } })
types/inert/v4/inert-tests.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9c19be36acb0e6c0c3c652465361b0da1090e3ce
[ 0.9884429574012756, 0.07076326012611389, 0.0001613552012713626, 0.0001672054931987077, 0.2545185387134552 ]
{ "id": 1, "code_window": [ " return [''];\n", " }\n", " return new Error('');\n", " },\n", " BAD_listing: true,\n", " },\n", " },\n", " options: { files: { relativeTo: __dirname } }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "types/inert/inert-tests.ts", "type": "replace", "edit_start_line_idx": 100 }
// Type definitions for Redux Mock Store 0.0.1 // Project: https://github.com/arnaudbenard/redux-mock-store // Definitions by: Marian Palkus <https://github.com/MarianPalkus>, Cap3 <http://www.cap3.de> // Definitions: https://github.com/borisyankov/DefinitelyTyped // TypeScript Version: 2.3 import * as Redux from 'redux'; export interface MockStore<T> extends Redux.Store<T> { getActions(): any[]; clearActions(): void; } export type MockStoreCreator<T = {}> = (state?: T) => MockStore<T>; declare function createMockStore<T>(middlewares?: Redux.Middleware[]): MockStoreCreator<T>; export default createMockStore;
types/redux-mock-store/v0/index.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9c19be36acb0e6c0c3c652465361b0da1090e3ce
[ 0.0001686919858912006, 0.00016784848412498832, 0.0001670049678068608, 0.00016784848412498832, 8.435090421698987e-7 ]
{ "id": 1, "code_window": [ " return [''];\n", " }\n", " return new Error('');\n", " },\n", " BAD_listing: true,\n", " },\n", " },\n", " options: { files: { relativeTo: __dirname } }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "types/inert/inert-tests.ts", "type": "replace", "edit_start_line_idx": 100 }
import DS from 'ember-data'; export default DS.JSONSerializer;
types/ember-data/v2/serializers/json.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9c19be36acb0e6c0c3c652465361b0da1090e3ce
[ 0.00016735024109948426, 0.00016735024109948426, 0.00016735024109948426, 0.00016735024109948426, 0 ]
{ "id": 1, "code_window": [ " return [''];\n", " }\n", " return new Error('');\n", " },\n", " BAD_listing: true,\n", " },\n", " },\n", " options: { files: { relativeTo: __dirname } }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "types/inert/inert-tests.ts", "type": "replace", "edit_start_line_idx": 100 }
{ "extends": "dtslint/dt.json" }
types/doge-seed/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9c19be36acb0e6c0c3c652465361b0da1090e3ce
[ 0.0001649531041039154, 0.0001649531041039154, 0.0001649531041039154, 0.0001649531041039154, 0 ]
{ "id": 2, "code_window": [ " else if(Math.random() > 0) {\n", " return [''];\n", " }\n", " return new Error('');\n", " },\n", " BAD_listing: true, // TODO change typings to make this error\n", " },\n", " },\n", " config: { files: { relativeTo: __dirname } }\n", "})\n", "" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " }\n" ], "file_path": "types/inert/v4/inert-tests.ts", "type": "replace", "edit_start_line_idx": 123 }
// Copied from: https://github.com/hapijs/inert#examples import Path = require('path'); import Hapi = require('hapi'); import Inert = require('inert'); const server = new Hapi.Server({ connections: { routes: { files: { relativeTo: Path.join(__dirname, 'public') } } } }); server.connection({ port: 3000 }); server.register(Inert, () => {}); // added in addition to code from docs const options: Inert.OptionalRegistrationOptions = {etagsCacheMaxSize: 400}; server.register({ register: Inert, options, }, (err) => {}); // added in addition to code from docs server.register({ register: Inert, once: true, }, (err) => {}); server.route({ method: 'GET', path: '/{param*}', handler: { directory: { path: '.', redirectToSlash: true, index: true } } }); server.start((err) => { if (err) { throw err; } console.log('Server running at:', server.info!.uri); }); // https://github.com/hapijs/inert#serving-a-single-file server.route({ method: 'GET', path: '/{path*}', handler: { file: 'page.html' } }); // https://github.com/hapijs/inert#customized-file-response server.route({ method: 'GET', path: '/file', handler: function (request, reply) { let path = 'plain.txt'; if (request.headers['x-magic'] === 'sekret') { path = 'awesome.png'; } return reply.file(path).vary('x-magic'); } }); const handler: Hapi.ServerExtRequestHandler = function (request, reply) { const response = request.response!; if (response.isBoom && response.output!.statusCode === 404) { return reply.file('404.html').code(404); } return reply.continue(); } server.ext('onPostHandler', handler); // additional code added in addition to doc example code var file: Inert.FileHandlerRouteObject = { path: '', confine: true, }; var directory: Inert.DirectoryHandlerRouteObject = { path: '', listing: true }; file = { path: '', confine: true, }; server.route({ path: '', method: 'GET', handler: { file, directory: { path: function(){ if(Math.random() > 0.5) { return ''; } else if(Math.random() > 0) { return ['']; } return new Error(''); }, BAD_listing: true, // TODO change typings to make this error }, }, config: { files: { relativeTo: __dirname } } })
types/inert/v4/inert-tests.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9c19be36acb0e6c0c3c652465361b0da1090e3ce
[ 0.9752535223960876, 0.0720193162560463, 0.00016260627307929099, 0.00016849323583301157, 0.250637024641037 ]
{ "id": 2, "code_window": [ " else if(Math.random() > 0) {\n", " return [''];\n", " }\n", " return new Error('');\n", " },\n", " BAD_listing: true, // TODO change typings to make this error\n", " },\n", " },\n", " config: { files: { relativeTo: __dirname } }\n", "})\n", "" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " }\n" ], "file_path": "types/inert/v4/inert-tests.ts", "type": "replace", "edit_start_line_idx": 123 }
var testHtmlElement = document.getElementById('test'); /** * Basic */ noUiSlider.create(testHtmlElement, { start: 80, range: { 'min': 0, 'max': 10000 } }); /** * All options */ noUiSlider.create(testHtmlElement, { start: [ 20, 80 ], step: 10, margin: 20, connect: true, direction: 'rtl', orientation: 'vertical', // Configure tapping, or make the selected range dragable. behaviour: 'tap-drag', // Full number format support. format: wNumb({ mark: ',', decimals: 1 }), // Support for non-linear ranges by adding intervals. range: { 'min': 0, 'max': 100 } }); /** * Pips */ noUiSlider.create(testHtmlElement, { start: 0, range: { min: 0, max: 10 }, pips: { mode: 'steps', density: 3, filter: function () { return 1 }, format: wNumb({ decimals: 2, prefix: '$' }), } }); /** * Functions * Need to cast the HTMLElement as noUiSlider.Instance. */ // Get value (<noUiSlider.Instance>testHtmlElement).noUiSlider.get(); // Set one value (<noUiSlider.Instance>testHtmlElement).noUiSlider.set(10); (<noUiSlider.Instance>testHtmlElement).noUiSlider.set([150]); // Set the upper handle, // don't change the lower one. (<noUiSlider.Instance>testHtmlElement).noUiSlider.set([null, 14]); // Set both slider handles (<noUiSlider.Instance>testHtmlElement).noUiSlider.set([13.2, 15.7]); // Events var callback: noUiSlider.Callback = (values, handle, unencoded) => {}; (<noUiSlider.Instance>testHtmlElement).noUiSlider.on('event', callback); (<noUiSlider.Instance>testHtmlElement).noUiSlider.off('event'); (<noUiSlider.Instance>testHtmlElement).noUiSlider.destroy();
types/nouislider/v8/nouislider-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9c19be36acb0e6c0c3c652465361b0da1090e3ce
[ 0.00017425217083655298, 0.00016977261111605912, 0.00016144478286150843, 0.00017060886602848768, 0.0000036789028854400385 ]
{ "id": 2, "code_window": [ " else if(Math.random() > 0) {\n", " return [''];\n", " }\n", " return new Error('');\n", " },\n", " BAD_listing: true, // TODO change typings to make this error\n", " },\n", " },\n", " config: { files: { relativeTo: __dirname } }\n", "})\n", "" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " }\n" ], "file_path": "types/inert/v4/inert-tests.ts", "type": "replace", "edit_start_line_idx": 123 }
import ThemePackage from "@carbon/themes"; interface Theme { active01: string; activeDanger: string; activePrimary: string; activeSecondary: string; activeTertiary: string; activeUI: string; brand01: string; brand02: string; brand03: string; disabled01: string; disabled02: string; disabled03: string; field01: string; field02: string; focus: string; highlight: string; hoverDanger: string; hoverField: string; hoverPrimary: string; hoverPrimaryText: string; hoverRow: string; hoverSecondary: string; hoverSelectedUI: string; hoverTertiary: string; hoverUI: string; icon01: string; icon02: string; interactive01: string; interactive02: string; interactive03: string; inverse01: string; inverse02: string; overlay01: string; selectedUI: string; support01: string; support02: string; support03: string; support04: string; text01: string; text02: string; text03: string; text04: string; ui01: string; ui02: string; ui03: string; ui04: string; ui05: string; uiBackground: string; visitedLink: string; } const getDefaultTheme = (): Theme => { return ThemePackage.white; }; getDefaultTheme();
types/carbon__themes/carbon__themes-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9c19be36acb0e6c0c3c652465361b0da1090e3ce
[ 0.00017451039457228035, 0.00017333828145638108, 0.00017122669669333845, 0.00017376801406498998, 0.000001088406293092703 ]
{ "id": 2, "code_window": [ " else if(Math.random() > 0) {\n", " return [''];\n", " }\n", " return new Error('');\n", " },\n", " BAD_listing: true, // TODO change typings to make this error\n", " },\n", " },\n", " config: { files: { relativeTo: __dirname } }\n", "})\n", "" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " }\n" ], "file_path": "types/inert/v4/inert-tests.ts", "type": "replace", "edit_start_line_idx": 123 }
{ "compilerOptions": { "module": "commonjs", "lib": [ "es6", "dom" ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", "offscreencanvas-tests.ts" ] }
types/offscreencanvas/tsconfig.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9c19be36acb0e6c0c3c652465361b0da1090e3ce
[ 0.00017061228572856635, 0.00016914225125219673, 0.00016756387776695192, 0.0001692505757091567, 0.0000012468625527617405 ]
{ "id": 0, "code_window": [ "\tMenuLogo *string `json:\"menuLogo,omitempty\"`\n", "\tLoginBackground *string `json:\"loginBackground,omitempty\"`\n", "\tLoginSubtitle *string `json:\"loginSubtitle,omitempty\"`\n", "\tLoginBoxBackground *string `json:\"loginBoxBackground,omitempty\"`\n", "\tLoadingLogo *string `json:\"loadingLogo,omitempty\"`\n", "\tPublicDashboardFooter *FrontendSettingsPublicDashboardFooterConfigDTO `json:\"publicDashboardFooter,omitempty\"` // PR TODO: type this properly\n", "}\n", "\n", "type FrontendSettingsSqlConnectionLimitsDTO struct {\n", "\tMaxOpenConns int `json:\"maxOpenConns\"`\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tHideEdition *bool `json:\"hideEdition,omitempty\"`\n" ], "file_path": "pkg/api/dtos/frontend_settings.go", "type": "add", "edit_start_line_idx": 113 }
import React from 'react'; import { LinkTarget } from '@grafana/data'; import { config } from '@grafana/runtime'; import { Icon, IconName } from '@grafana/ui'; import { t } from 'app/core/internationalization'; export interface FooterLink { target: LinkTarget; text: string; id: string; icon?: IconName; url?: string; } export let getFooterLinks = (): FooterLink[] => { return [ { target: '_blank', id: 'documentation', text: t('nav.help/documentation', 'Documentation'), icon: 'document-info', url: 'https://grafana.com/docs/grafana/latest/?utm_source=grafana_footer', }, { target: '_blank', id: 'support', text: t('nav.help/support', 'Support'), icon: 'question-circle', url: 'https://grafana.com/products/enterprise/?utm_source=grafana_footer', }, { target: '_blank', id: 'community', text: t('nav.help/community', 'Community'), icon: 'comments-alt', url: 'https://community.grafana.com/?utm_source=grafana_footer', }, ]; }; export function getVersionMeta(version: string) { const isBeta = version.includes('-beta'); return { hasReleaseNotes: true, isBeta, }; } export function getVersionLinks(): FooterLink[] { const { buildInfo, licenseInfo } = config; const links: FooterLink[] = []; const stateInfo = licenseInfo.stateInfo ? ` (${licenseInfo.stateInfo})` : ''; links.push({ target: '_blank', id: 'license', text: `${buildInfo.edition}${stateInfo}`, url: licenseInfo.licenseUrl, }); if (buildInfo.hideVersion) { return links; } const { hasReleaseNotes } = getVersionMeta(buildInfo.version); links.push({ target: '_blank', id: 'version', text: `v${buildInfo.version} (${buildInfo.commit})`, url: hasReleaseNotes ? `https://github.com/grafana/grafana/blob/main/CHANGELOG.md` : undefined, }); if (buildInfo.hasUpdate) { links.push({ target: '_blank', id: 'updateVersion', text: `New version available!`, icon: 'download-alt', url: 'https://grafana.com/grafana/download?utm_source=grafana_footer', }); } return links; } export function setFooterLinksFn(fn: typeof getFooterLinks) { getFooterLinks = fn; } export interface Props { /** Link overrides to show specific links in the UI */ customLinks?: FooterLink[] | null; } export const Footer = React.memo(({ customLinks }: Props) => { const links = (customLinks || getFooterLinks()).concat(getVersionLinks()); return ( <footer className="footer"> <div className="text-center"> <ul> {links.map((link) => ( <li key={link.text}> <FooterItem item={link} /> </li> ))} </ul> </div> </footer> ); }); Footer.displayName = 'Footer'; function FooterItem({ item }: { item: FooterLink }) { const content = item.url ? ( <a href={item.url} target={item.target} rel="noopener noreferrer" id={item.id}> {item.text} </a> ) : ( item.text ); return ( <> {item.icon && <Icon name={item.icon} />} {content} </> ); }
public/app/core/components/Footer/Footer.tsx
1
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.000593838281929493, 0.0002853006590157747, 0.00016568877617828548, 0.00019733334193006158, 0.00015738981892354786 ]
{ "id": 0, "code_window": [ "\tMenuLogo *string `json:\"menuLogo,omitempty\"`\n", "\tLoginBackground *string `json:\"loginBackground,omitempty\"`\n", "\tLoginSubtitle *string `json:\"loginSubtitle,omitempty\"`\n", "\tLoginBoxBackground *string `json:\"loginBoxBackground,omitempty\"`\n", "\tLoadingLogo *string `json:\"loadingLogo,omitempty\"`\n", "\tPublicDashboardFooter *FrontendSettingsPublicDashboardFooterConfigDTO `json:\"publicDashboardFooter,omitempty\"` // PR TODO: type this properly\n", "}\n", "\n", "type FrontendSettingsSqlConnectionLimitsDTO struct {\n", "\tMaxOpenConns int `json:\"maxOpenConns\"`\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tHideEdition *bool `json:\"hideEdition,omitempty\"`\n" ], "file_path": "pkg/api/dtos/frontend_settings.go", "type": "add", "edit_start_line_idx": 113 }
<?xml version="1.0" encoding="utf-8"?> <!-- Generator: Adobe Illustrator 19.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="121px" height="100px" viewBox="0 0 121 100" style="enable-background:new 0 0 121 100;" xml:space="preserve"> <style type="text/css"> .st0{fill:url(#SVGID_1_);} .st1{fill:#161719;} .st2{fill:url(#SVGID_2_);} .st3{fill:url(#SVGID_3_);} </style> <g> <g> <linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="60.5" y1="130.7753" x2="60.5" y2="18.6673"> <stop offset="0" style="stop-color:#FFF100"/> <stop offset="1" style="stop-color:#F05A28"/> </linearGradient> <path class="st0" d="M120.8,50L87.2,16.4C78.1,6.3,64.9,0,50.2,0c-27.6,0-50,22.4-50,50s22.4,50,50,50c14.4,0,27.5-6.1,36.6-15.9 c0.1-0.1,0.1-0.1,0.2-0.2L120.8,50z"/> </g> <path class="st1" d="M94.1,50c0-24.4-19.9-44.3-44.3-44.3S5.6,25.6,5.6,50s19.9,44.3,44.3,44.3S94.1,74.4,94.1,50z"/> <g> <linearGradient id="SVGID_2_" gradientUnits="userSpaceOnUse" x1="50.6946" y1="113.8319" x2="50.6946" y2="21.7994"> <stop offset="0" style="stop-color:#FFF100"/> <stop offset="1" style="stop-color:#F05A28"/> </linearGradient> <path class="st2" d="M78.3,65.9H25.9V30.5c0-1.5-1.2-2.8-2.8-2.8c-1.5,0-2.8,1.2-2.8,2.8v38.1c0,1.5,1.2,2.8,2.8,2.8h55.2 c1.5,0,2.8-1.2,2.8-2.8S79.8,65.9,78.3,65.9z"/> <g> <linearGradient id="SVGID_3_" gradientUnits="userSpaceOnUse" x1="53.553" y1="113.8319" x2="53.553" y2="21.7994"> <stop offset="0" style="stop-color:#FFF100"/> <stop offset="1" style="stop-color:#F05A28"/> </linearGradient> <polygon class="st3" points="78.2,63.1 78.5,49 63.4,28.3 47.5,49.5 36.3,38.7 28.6,43.1 28.6,63.1 "/> </g> </g> </g> </svg>
public/img/icons_dark_theme/icon_visualize_active.svg
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.0003522362094372511, 0.000256184721365571, 0.00020168357877992094, 0.00023540956317447126, 0.00005715350198443048 ]
{ "id": 0, "code_window": [ "\tMenuLogo *string `json:\"menuLogo,omitempty\"`\n", "\tLoginBackground *string `json:\"loginBackground,omitempty\"`\n", "\tLoginSubtitle *string `json:\"loginSubtitle,omitempty\"`\n", "\tLoginBoxBackground *string `json:\"loginBoxBackground,omitempty\"`\n", "\tLoadingLogo *string `json:\"loadingLogo,omitempty\"`\n", "\tPublicDashboardFooter *FrontendSettingsPublicDashboardFooterConfigDTO `json:\"publicDashboardFooter,omitempty\"` // PR TODO: type this properly\n", "}\n", "\n", "type FrontendSettingsSqlConnectionLimitsDTO struct {\n", "\tMaxOpenConns int `json:\"maxOpenConns\"`\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tHideEdition *bool `json:\"hideEdition,omitempty\"`\n" ], "file_path": "pkg/api/dtos/frontend_settings.go", "type": "add", "edit_start_line_idx": 113 }
import React from 'react'; import { DataSourceInstanceSettings, DataSourcePluginOptionsEditorProps, updateDatasourcePluginJsonDataOption, } from '@grafana/data'; import { Button, InlineField, InlineFieldRow, useStyles2 } from '@grafana/ui'; import { DataSourcePicker } from 'app/features/datasources/components/picker/DataSourcePicker'; import { TempoJsonData } from '../types'; import { getStyles } from './QuerySettings'; interface Props extends DataSourcePluginOptionsEditorProps<TempoJsonData> {} export function ServiceGraphSettings({ options, onOptionsChange }: Props) { const styles = useStyles2(getStyles); return ( <div className={styles.container}> <InlineFieldRow className={styles.row}> <InlineField tooltip="The Prometheus data source with the service graph data" label="Data source" labelWidth={26} > <DataSourcePicker inputId="service-graph-data-source-picker" pluginId="prometheus" current={options.jsonData.serviceMap?.datasourceUid} noDefault={true} width={40} onChange={(ds: DataSourceInstanceSettings) => updateDatasourcePluginJsonDataOption({ onOptionsChange, options }, 'serviceMap', { datasourceUid: ds.uid, }) } /> </InlineField> {options.jsonData.serviceMap?.datasourceUid ? ( <Button type={'button'} variant={'secondary'} size={'sm'} fill={'text'} onClick={() => { updateDatasourcePluginJsonDataOption({ onOptionsChange, options }, 'serviceMap', { datasourceUid: undefined, }); }} > Clear </Button> ) : null} </InlineFieldRow> </div> ); }
public/app/plugins/datasource/tempo/configuration/ServiceGraphSettings.tsx
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.0007516242912970483, 0.00036936000105924904, 0.0001925292453961447, 0.00025724241277202964, 0.00021290508448146284 ]
{ "id": 0, "code_window": [ "\tMenuLogo *string `json:\"menuLogo,omitempty\"`\n", "\tLoginBackground *string `json:\"loginBackground,omitempty\"`\n", "\tLoginSubtitle *string `json:\"loginSubtitle,omitempty\"`\n", "\tLoginBoxBackground *string `json:\"loginBoxBackground,omitempty\"`\n", "\tLoadingLogo *string `json:\"loadingLogo,omitempty\"`\n", "\tPublicDashboardFooter *FrontendSettingsPublicDashboardFooterConfigDTO `json:\"publicDashboardFooter,omitempty\"` // PR TODO: type this properly\n", "}\n", "\n", "type FrontendSettingsSqlConnectionLimitsDTO struct {\n", "\tMaxOpenConns int `json:\"maxOpenConns\"`\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tHideEdition *bool `json:\"hideEdition,omitempty\"`\n" ], "file_path": "pkg/api/dtos/frontend_settings.go", "type": "add", "edit_start_line_idx": 113 }
package api import ( "net/http" "strconv" "time" "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/components/satokengen" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model" "github.com/grafana/grafana/pkg/services/serviceaccounts" "github.com/grafana/grafana/pkg/web" ) const ( failedToDeleteMsg = "Failed to delete service account token" ServiceID = "sa" ) // swagger:model type TokenDTO struct { // example: 1 Id int64 `json:"id"` // example: grafana Name string `json:"name"` // example: 2022-03-23T10:31:02Z Created *time.Time `json:"created"` // example: 2022-03-23T10:31:02Z LastUsedAt *time.Time `json:"lastUsedAt"` // example: 2022-03-23T10:31:02Z Expiration *time.Time `json:"expiration"` // example: 0 SecondsUntilExpiration *float64 `json:"secondsUntilExpiration"` // example: false HasExpired bool `json:"hasExpired"` // example: false IsRevoked *bool `json:"isRevoked"` } func hasExpired(expiration *int64) bool { if expiration == nil { return false } v := time.Unix(*expiration, 0) return (v).Before(time.Now()) } const sevenDaysAhead = 7 * 24 * time.Hour // swagger:route GET /serviceaccounts/{serviceAccountId}/tokens service_accounts listTokens // // # Get service account tokens // // Required permissions (See note in the [introduction](https://grafana.com/docs/grafana/latest/developers/http_api/serviceaccount/#service-account-api) for an explanation): // action: `serviceaccounts:read` scope: `global:serviceaccounts:id:1` (single service account) // // Requires basic authentication and that the authenticated user is a Grafana Admin. // // Responses: // 200: listTokensResponse // 400: badRequestError // 401: unauthorisedError // 403: forbiddenError // 500: internalServerError func (api *ServiceAccountsAPI) ListTokens(ctx *contextmodel.ReqContext) response.Response { saID, err := strconv.ParseInt(web.Params(ctx.Req)[":serviceAccountId"], 10, 64) if err != nil { return response.Error(http.StatusBadRequest, "Service Account ID is invalid", err) } orgID := ctx.SignedInUser.GetOrgID() saTokens, err := api.service.ListTokens(ctx.Req.Context(), &serviceaccounts.GetSATokensQuery{ OrgID: &orgID, ServiceAccountID: &saID, }) if err != nil { return response.Error(http.StatusInternalServerError, "Internal server error", err) } result := make([]TokenDTO, len(saTokens)) for i, t := range saTokens { var ( token = t // pin pointer expiration *time.Time = nil secondsUntilExpiration float64 = 0 ) isExpired := hasExpired(t.Expires) if t.Expires != nil { v := time.Unix(*t.Expires, 0) expiration = &v if !isExpired && (*expiration).Before(time.Now().Add(sevenDaysAhead)) { secondsUntilExpiration = time.Until(*expiration).Seconds() } } result[i] = TokenDTO{ Id: token.ID, Name: token.Name, Created: &token.Created, Expiration: expiration, SecondsUntilExpiration: &secondsUntilExpiration, HasExpired: isExpired, LastUsedAt: token.LastUsedAt, IsRevoked: token.IsRevoked, } } return response.JSON(http.StatusOK, result) } // swagger:route POST /serviceaccounts/{serviceAccountId}/tokens service_accounts createToken // // # CreateNewToken adds a token to a service account // // Required permissions (See note in the [introduction](https://grafana.com/docs/grafana/latest/developers/http_api/serviceaccount/#service-account-api) for an explanation): // action: `serviceaccounts:write` scope: `serviceaccounts:id:1` (single service account) // // Responses: // 200: createTokenResponse // 400: badRequestError // 401: unauthorisedError // 403: forbiddenError // 404: notFoundError // 409: conflictError // 500: internalServerError func (api *ServiceAccountsAPI) CreateToken(c *contextmodel.ReqContext) response.Response { saID, err := strconv.ParseInt(web.Params(c.Req)[":serviceAccountId"], 10, 64) if err != nil { return response.Error(http.StatusBadRequest, "Service Account ID is invalid", err) } // confirm service account exists if _, err = api.service.RetrieveServiceAccount(c.Req.Context(), c.SignedInUser.GetOrgID(), saID); err != nil { return response.ErrOrFallback(http.StatusInternalServerError, "Failed to retrieve service account", err) } cmd := serviceaccounts.AddServiceAccountTokenCommand{} if err = web.Bind(c.Req, &cmd); err != nil { return response.Error(http.StatusBadRequest, "Bad request data", err) } // Force affected service account to be the one referenced in the URL cmd.OrgId = c.SignedInUser.GetOrgID() if api.cfg.ApiKeyMaxSecondsToLive != -1 { if cmd.SecondsToLive == 0 { return response.Error(http.StatusBadRequest, "Number of seconds before expiration should be set", nil) } if cmd.SecondsToLive > api.cfg.ApiKeyMaxSecondsToLive { return response.Error(http.StatusBadRequest, "Number of seconds before expiration is greater than the global limit", nil) } } if api.cfg.SATokenExpirationDayLimit > 0 { dayExpireLimit := time.Now().Add(time.Duration(api.cfg.SATokenExpirationDayLimit) * time.Hour * 24).Truncate(24 * time.Hour) expirationDate := time.Now().Add(time.Duration(cmd.SecondsToLive) * time.Second).Truncate(24 * time.Hour) if expirationDate.After(dayExpireLimit) { return response.Respond(http.StatusBadRequest, "The expiration date input exceeds the limit for service account access tokens expiration date") } } newKeyInfo, err := satokengen.New(ServiceID) if err != nil { return response.Error(http.StatusInternalServerError, "Generating service account token failed", err) } cmd.Key = newKeyInfo.HashedKey apiKey, err := api.service.AddServiceAccountToken(c.Req.Context(), saID, &cmd) if err != nil { return response.ErrOrFallback(http.StatusInternalServerError, "failed to add service account token", err) } result := &dtos.NewApiKeyResult{ ID: apiKey.ID, Name: apiKey.Name, Key: newKeyInfo.ClientSecret, } return response.JSON(http.StatusOK, result) } // swagger:route DELETE /serviceaccounts/{serviceAccountId}/tokens/{tokenId} service_accounts deleteToken // // # DeleteToken deletes service account tokens // // Required permissions (See note in the [introduction](https://grafana.com/docs/grafana/latest/developers/http_api/serviceaccount/#service-account-api) for an explanation): // action: `serviceaccounts:write` scope: `serviceaccounts:id:1` (single service account) // // Requires basic authentication and that the authenticated user is a Grafana Admin. // // Responses: // 200: okResponse // 400: badRequestError // 401: unauthorisedError // 403: forbiddenError // 404: notFoundError // 500: internalServerError func (api *ServiceAccountsAPI) DeleteToken(c *contextmodel.ReqContext) response.Response { saID, err := strconv.ParseInt(web.Params(c.Req)[":serviceAccountId"], 10, 64) if err != nil { return response.Error(http.StatusBadRequest, "Service Account ID is invalid", err) } // confirm service account exists if _, err := api.service.RetrieveServiceAccount(c.Req.Context(), c.SignedInUser.GetOrgID(), saID); err != nil { return response.ErrOrFallback(http.StatusInternalServerError, "Failed to retrieve service account", err) } tokenID, err := strconv.ParseInt(web.Params(c.Req)[":tokenId"], 10, 64) if err != nil { return response.Error(http.StatusBadRequest, "Token ID is invalid", err) } if err = api.service.DeleteServiceAccountToken(c.Req.Context(), c.SignedInUser.GetOrgID(), saID, tokenID); err != nil { return response.ErrOrFallback(http.StatusInternalServerError, failedToDeleteMsg, err) } return response.Success("Service account token deleted") } // swagger:parameters listTokens type ListTokensParams struct { // in:path ServiceAccountId int64 `json:"serviceAccountId"` } // swagger:parameters createToken type CreateTokenParams struct { // in:path ServiceAccountId int64 `json:"serviceAccountId"` // in:body Body serviceaccounts.AddServiceAccountTokenCommand } // swagger:parameters deleteToken type DeleteTokenParams struct { // in:path TokenId int64 `json:"tokenId"` // in:path ServiceAccountId int64 `json:"serviceAccountId"` } // swagger:response listTokensResponse type ListTokensResponse struct { // in:body Body *TokenDTO } // swagger:response createTokenResponse type CreateTokenResponse struct { // in:body Body *dtos.NewApiKeyResult }
pkg/services/serviceaccounts/api/token.go
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.003749353112652898, 0.0005944687873125076, 0.00016889171092770994, 0.0002291062701260671, 0.0008537349058315158 ]
{ "id": 1, "code_window": [ " static LoginBoxBackground = LoginBoxBackground;\n", " static AppTitle = 'Grafana';\n", " static LoginTitle = 'Welcome to Grafana';\n", " static GetLoginSubTitle = (): null | string => {\n", " return null;\n", " };\n", "}" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " static HideEdition = false;\n" ], "file_path": "public/app/core/components/Branding/Branding.tsx", "type": "add", "edit_start_line_idx": 63 }
import React from 'react'; import { LinkTarget } from '@grafana/data'; import { config } from '@grafana/runtime'; import { Icon, IconName } from '@grafana/ui'; import { t } from 'app/core/internationalization'; export interface FooterLink { target: LinkTarget; text: string; id: string; icon?: IconName; url?: string; } export let getFooterLinks = (): FooterLink[] => { return [ { target: '_blank', id: 'documentation', text: t('nav.help/documentation', 'Documentation'), icon: 'document-info', url: 'https://grafana.com/docs/grafana/latest/?utm_source=grafana_footer', }, { target: '_blank', id: 'support', text: t('nav.help/support', 'Support'), icon: 'question-circle', url: 'https://grafana.com/products/enterprise/?utm_source=grafana_footer', }, { target: '_blank', id: 'community', text: t('nav.help/community', 'Community'), icon: 'comments-alt', url: 'https://community.grafana.com/?utm_source=grafana_footer', }, ]; }; export function getVersionMeta(version: string) { const isBeta = version.includes('-beta'); return { hasReleaseNotes: true, isBeta, }; } export function getVersionLinks(): FooterLink[] { const { buildInfo, licenseInfo } = config; const links: FooterLink[] = []; const stateInfo = licenseInfo.stateInfo ? ` (${licenseInfo.stateInfo})` : ''; links.push({ target: '_blank', id: 'license', text: `${buildInfo.edition}${stateInfo}`, url: licenseInfo.licenseUrl, }); if (buildInfo.hideVersion) { return links; } const { hasReleaseNotes } = getVersionMeta(buildInfo.version); links.push({ target: '_blank', id: 'version', text: `v${buildInfo.version} (${buildInfo.commit})`, url: hasReleaseNotes ? `https://github.com/grafana/grafana/blob/main/CHANGELOG.md` : undefined, }); if (buildInfo.hasUpdate) { links.push({ target: '_blank', id: 'updateVersion', text: `New version available!`, icon: 'download-alt', url: 'https://grafana.com/grafana/download?utm_source=grafana_footer', }); } return links; } export function setFooterLinksFn(fn: typeof getFooterLinks) { getFooterLinks = fn; } export interface Props { /** Link overrides to show specific links in the UI */ customLinks?: FooterLink[] | null; } export const Footer = React.memo(({ customLinks }: Props) => { const links = (customLinks || getFooterLinks()).concat(getVersionLinks()); return ( <footer className="footer"> <div className="text-center"> <ul> {links.map((link) => ( <li key={link.text}> <FooterItem item={link} /> </li> ))} </ul> </div> </footer> ); }); Footer.displayName = 'Footer'; function FooterItem({ item }: { item: FooterLink }) { const content = item.url ? ( <a href={item.url} target={item.target} rel="noopener noreferrer" id={item.id}> {item.text} </a> ) : ( item.text ); return ( <> {item.icon && <Icon name={item.icon} />} {content} </> ); }
public/app/core/components/Footer/Footer.tsx
1
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.0003746498841792345, 0.00019095856987405568, 0.00016634176427032799, 0.00017623034364078194, 0.0000518148772243876 ]
{ "id": 1, "code_window": [ " static LoginBoxBackground = LoginBoxBackground;\n", " static AppTitle = 'Grafana';\n", " static LoginTitle = 'Welcome to Grafana';\n", " static GetLoginSubTitle = (): null | string => {\n", " return null;\n", " };\n", "}" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " static HideEdition = false;\n" ], "file_path": "public/app/core/components/Branding/Branding.tsx", "type": "add", "edit_start_line_idx": 63 }
import { useLocation, useParams } from 'react-router-dom'; import { NavModel, NavModelItem } from '@grafana/data'; import { getDataSourceSrv } from '@grafana/runtime'; import { getNavModel } from 'app/core/selectors/navModel'; import { useDataSource, useDataSourceSettings } from 'app/features/datasources/state/hooks'; import { getDataSourceLoadingNav, buildNavModel, getDataSourceNav } from 'app/features/datasources/state/navModel'; import { useGetSingle } from 'app/features/plugins/admin/state/hooks'; import { useSelector } from 'app/types'; export function useDataSourceSettingsNav(pageIdParam?: string) { const { uid } = useParams<{ uid: string }>(); const location = useLocation(); const datasource = useDataSource(uid); const datasourcePlugin = useGetSingle(datasource.type); const params = new URLSearchParams(location.search); const pageId = pageIdParam || params.get('page'); const { plugin, loadError, loading } = useDataSourceSettings(); const dsi = getDataSourceSrv()?.getInstanceSettings(uid); const hasAlertingEnabled = Boolean(dsi?.meta?.alerting ?? false); const isAlertManagerDatasource = dsi?.type === 'alertmanager'; const alertingSupported = hasAlertingEnabled || isAlertManagerDatasource; const navIndex = useSelector((state) => state.navIndex); const navIndexId = pageId ? `datasource-${pageId}-${uid}` : `datasource-settings-${uid}`; let pageNav: NavModel = { node: { text: 'Data Source Nav Node', }, main: { text: 'Data Source Nav Node', }, }; if (loadError) { const node: NavModelItem = { text: loadError, subTitle: 'Data Source Error', icon: 'exclamation-triangle', }; pageNav = { node: node, main: node, }; } if (loading || !plugin) { pageNav = getNavModel(navIndex, navIndexId, getDataSourceLoadingNav('settings')); } if (plugin) { pageNav = getNavModel( navIndex, navIndexId, getDataSourceNav(buildNavModel(datasource, plugin), pageId || 'settings') ); } const connectionsPageNav = { ...pageNav.main, dataSourcePluginName: datasourcePlugin?.name || plugin?.meta.name || '', active: true, text: datasource.name, subTitle: `Type: ${datasourcePlugin?.name}`, children: (pageNav.main.children || []).map((navModelItem) => ({ ...navModelItem, url: navModelItem.url?.replace('datasources/edit/', '/connections/datasources/edit/'), })), }; return { navId: 'connections-datasources', pageNav: connectionsPageNav, dataSourceHeader: { alertingSupported, }, }; }
public/app/features/connections/hooks/useDataSourceSettingsNav.ts
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.00017950520850718021, 0.0001746527705108747, 0.00016991046140901744, 0.00017493388440925628, 0.0000023776601665304042 ]
{ "id": 1, "code_window": [ " static LoginBoxBackground = LoginBoxBackground;\n", " static AppTitle = 'Grafana';\n", " static LoginTitle = 'Welcome to Grafana';\n", " static GetLoginSubTitle = (): null | string => {\n", " return null;\n", " };\n", "}" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " static HideEdition = false;\n" ], "file_path": "public/app/core/components/Branding/Branding.tsx", "type": "add", "edit_start_line_idx": 63 }
import { quoteLiteral, unquoteIdentifier } from './sqlUtil'; export function buildTableQuery(dataset?: string) { const database = dataset !== undefined ? quoteIdentAsLiteral(dataset) : 'database()'; return `SELECT table_name FROM information_schema.tables WHERE table_schema = ${database} ORDER BY table_name`; } export function showDatabases() { return `SELECT DISTINCT TABLE_SCHEMA from information_schema.TABLES where TABLE_TYPE != 'SYSTEM VIEW' ORDER BY TABLE_SCHEMA`; } export function buildColumnQuery(table: string, dbName?: string) { let query = 'SELECT column_name, data_type FROM information_schema.columns WHERE '; query += buildTableConstraint(table, dbName); query += ' ORDER BY column_name'; return query; } export function buildTableConstraint(table: string, dbName?: string) { let query = ''; // check for schema qualified table if (table.includes('.')) { const parts = table.split('.'); query = 'table_schema = ' + quoteIdentAsLiteral(parts[0]); query += ' AND table_name = ' + quoteIdentAsLiteral(parts[1]); return query; } else { const database = dbName !== undefined ? quoteIdentAsLiteral(dbName) : 'database()'; query = `table_schema = ${database} AND table_name = ` + quoteIdentAsLiteral(table); return query; } } export function quoteIdentAsLiteral(value: string) { return quoteLiteral(unquoteIdentifier(value)); }
public/app/plugins/datasource/mysql/mySqlMetaQuery.ts
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.00017950520850718021, 0.00017421532538719475, 0.00016975759353954345, 0.00017451522580813617, 0.0000032015682336350437 ]
{ "id": 1, "code_window": [ " static LoginBoxBackground = LoginBoxBackground;\n", " static AppTitle = 'Grafana';\n", " static LoginTitle = 'Welcome to Grafana';\n", " static GetLoginSubTitle = (): null | string => {\n", " return null;\n", " };\n", "}" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " static HideEdition = false;\n" ], "file_path": "public/app/core/components/Branding/Branding.tsx", "type": "add", "edit_start_line_idx": 63 }
<svg width="101" height="48" viewBox="0 0 101 48" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M0 1.04083V13H31V0H1.29545C0.951872 0 0.62237 0.109659 0.379427 0.304853C0.136484 0.500047 0 0.764787 0 1.04083Z" fill="url(#paint0_linear_1248_126353)"/> <path d="M31 17H0V48H31V17Z" fill="#84AFF1"/> <path d="M17 29.5H15.0954L13 30.7266V32.3984L14.9004 31.3047H14.9502V37.5H17V29.5Z" fill="#24292E"/> <path d="M66 0H35V13H66V0Z" fill="url(#paint1_linear_1248_126353)"/> <path d="M66 17H35V48H66V17Z" fill="#84AFF1"/> <path d="M48.1164 37.5H54V35.9624H50.7788V35.9123L51.7296 35.0414C53.4528 33.5501 53.903 32.7909 53.903 31.8854C53.903 30.4634 52.7348 29.5 50.9301 29.5C49.1721 29.5 47.9961 30.5058 48 32.1127H49.8202C49.8202 31.3998 50.2626 30.9875 50.9224 30.9875C51.5705 30.9875 52.0401 31.3844 52.0401 32.0356C52.0401 32.6252 51.6675 33.026 51.0155 33.6079L48.1164 36.1281V37.5Z" fill="#24292E"/> <path d="M70 13H101V1.04083C101 0.764787 100.864 0.500047 100.621 0.304853C100.378 0.109659 100.048 0 99.7046 0L70 0V13Z" fill="url(#paint2_linear_1248_126353)"/> <path d="M101 17H70V48H101V17Z" fill="#84AFF1"/> <path d="M78 29H76.0954L74 30.2266V31.8984L75.9004 30.8047H75.9502V37H78V29Z" fill="#24292E"/> <path d="M90.1164 37H96V35.4624H92.7788V35.4123L93.7296 34.5414C95.4528 33.0501 95.903 32.2909 95.903 31.3854C95.903 29.9634 94.7348 29 92.9301 29C91.1721 29 89.9961 30.0058 90 31.6127H91.8202C91.8202 30.8998 92.2626 30.4875 92.9224 30.4875C93.5705 30.4875 94.0401 30.8844 94.0401 31.5356C94.0401 32.1252 93.6675 32.526 93.0155 33.1079L90.1164 35.6281V37Z" fill="#24292E"/> <path d="M83.7432 36H85.2568V34.2568H87V32.7432H85.2568V31H83.7432V32.7432H82V34.2568H83.7432V36Z" fill="#24292E"/> <defs> <linearGradient id="paint0_linear_1248_126353" x1="0" y1="6.5052" x2="31" y2="6.5052" gradientUnits="userSpaceOnUse"> <stop stop-color="#F2CC0C"/> <stop offset="1" stop-color="#FF9830"/> </linearGradient> <linearGradient id="paint1_linear_1248_126353" x1="35" y1="6.5052" x2="66.013" y2="6.5052" gradientUnits="userSpaceOnUse"> <stop stop-color="#F2CC0C"/> <stop offset="1" stop-color="#FF9830"/> </linearGradient> <linearGradient id="paint2_linear_1248_126353" x1="70" y1="6.5052" x2="101" y2="6.5052" gradientUnits="userSpaceOnUse"> <stop stop-color="#F2CC0C"/> <stop offset="1" stop-color="#FF9830"/> </linearGradient> </defs> </svg>
public/img/transformations/light/calculateField.svg
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.0008259557653218508, 0.00038906108238734305, 0.00016415696882177144, 0.00017707052757032216, 0.0003089761594310403 ]
{ "id": 2, "code_window": [ " menuLogo?: string;\n", " favIcon?: string;\n", " loadingLogo?: string;\n", " appleTouchIcon?: string;\n", "}" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " hideEdition?: boolean;\n" ], "file_path": "public/app/core/components/Branding/types.ts", "type": "add", "edit_start_line_idx": 14 }
import React from 'react'; import { LinkTarget } from '@grafana/data'; import { config } from '@grafana/runtime'; import { Icon, IconName } from '@grafana/ui'; import { t } from 'app/core/internationalization'; export interface FooterLink { target: LinkTarget; text: string; id: string; icon?: IconName; url?: string; } export let getFooterLinks = (): FooterLink[] => { return [ { target: '_blank', id: 'documentation', text: t('nav.help/documentation', 'Documentation'), icon: 'document-info', url: 'https://grafana.com/docs/grafana/latest/?utm_source=grafana_footer', }, { target: '_blank', id: 'support', text: t('nav.help/support', 'Support'), icon: 'question-circle', url: 'https://grafana.com/products/enterprise/?utm_source=grafana_footer', }, { target: '_blank', id: 'community', text: t('nav.help/community', 'Community'), icon: 'comments-alt', url: 'https://community.grafana.com/?utm_source=grafana_footer', }, ]; }; export function getVersionMeta(version: string) { const isBeta = version.includes('-beta'); return { hasReleaseNotes: true, isBeta, }; } export function getVersionLinks(): FooterLink[] { const { buildInfo, licenseInfo } = config; const links: FooterLink[] = []; const stateInfo = licenseInfo.stateInfo ? ` (${licenseInfo.stateInfo})` : ''; links.push({ target: '_blank', id: 'license', text: `${buildInfo.edition}${stateInfo}`, url: licenseInfo.licenseUrl, }); if (buildInfo.hideVersion) { return links; } const { hasReleaseNotes } = getVersionMeta(buildInfo.version); links.push({ target: '_blank', id: 'version', text: `v${buildInfo.version} (${buildInfo.commit})`, url: hasReleaseNotes ? `https://github.com/grafana/grafana/blob/main/CHANGELOG.md` : undefined, }); if (buildInfo.hasUpdate) { links.push({ target: '_blank', id: 'updateVersion', text: `New version available!`, icon: 'download-alt', url: 'https://grafana.com/grafana/download?utm_source=grafana_footer', }); } return links; } export function setFooterLinksFn(fn: typeof getFooterLinks) { getFooterLinks = fn; } export interface Props { /** Link overrides to show specific links in the UI */ customLinks?: FooterLink[] | null; } export const Footer = React.memo(({ customLinks }: Props) => { const links = (customLinks || getFooterLinks()).concat(getVersionLinks()); return ( <footer className="footer"> <div className="text-center"> <ul> {links.map((link) => ( <li key={link.text}> <FooterItem item={link} /> </li> ))} </ul> </div> </footer> ); }); Footer.displayName = 'Footer'; function FooterItem({ item }: { item: FooterLink }) { const content = item.url ? ( <a href={item.url} target={item.target} rel="noopener noreferrer" id={item.id}> {item.text} </a> ) : ( item.text ); return ( <> {item.icon && <Icon name={item.icon} />} {content} </> ); }
public/app/core/components/Footer/Footer.tsx
1
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.0001832825073506683, 0.0001734782272251323, 0.00016776980191934854, 0.0001730122312437743, 0.000004256807187630329 ]
{ "id": 2, "code_window": [ " menuLogo?: string;\n", " favIcon?: string;\n", " loadingLogo?: string;\n", " appleTouchIcon?: string;\n", "}" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " hideEdition?: boolean;\n" ], "file_path": "public/app/core/components/Branding/types.ts", "type": "add", "edit_start_line_idx": 14 }
// Copyright 2016 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 import ( "errors" "fmt" "reflect" "sort" "strconv" "strings" "xorm.io/builder" "xorm.io/core" ) // ErrNoElementsOnSlice represents an error there is no element when insert var ErrNoElementsOnSlice = errors.New("no element on slice when insert") // Insert insert one or more beans func (session *Session) Insert(beans ...interface{}) (int64, error) { var affected int64 var err error if session.isAutoClose { defer session.Close() } session.autoResetStatement = false defer func() { session.autoResetStatement = true session.resetStatement() }() for _, bean := range beans { switch bean := bean.(type) { case map[string]interface{}: cnt, err := session.insertMapInterface(bean) if err != nil { return affected, err } affected += cnt case []map[string]interface{}: for i := 0; i < len(bean); i++ { cnt, err := session.insertMapInterface(bean[i]) if err != nil { return affected, err } affected += cnt } case map[string]string: cnt, err := session.insertMapString(bean) if err != nil { return affected, err } affected += cnt case []map[string]string: for i := 0; i < len(bean); i++ { cnt, err := session.insertMapString(bean[i]) if err != nil { return affected, err } affected += cnt } default: sliceValue := reflect.Indirect(reflect.ValueOf(bean)) if sliceValue.Kind() == reflect.Slice { size := sliceValue.Len() if size <= 0 { return 0, ErrNoElementsOnSlice } if session.engine.SupportInsertMany() { cnt, err := session.innerInsertMulti(bean) if err != nil { return affected, err } affected += cnt } else { for i := 0; i < size; i++ { cnt, err := session.innerInsert(sliceValue.Index(i).Interface()) if err != nil { return affected, err } affected += cnt } } } else { cnt, err := session.innerInsert(bean) if err != nil { return affected, err } affected += cnt } } } return affected, err } func (session *Session) innerInsertMulti(rowsSlicePtr interface{}) (int64, error) { sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr)) if sliceValue.Kind() != reflect.Slice { return 0, errors.New("needs a pointer to a slice") } if sliceValue.Len() <= 0 { return 0, errors.New("could not insert a empty slice") } if err := session.statement.setRefBean(sliceValue.Index(0).Interface()); err != nil { return 0, err } tableName := session.statement.TableName() if len(tableName) <= 0 { return 0, ErrTableNotFound } table := session.statement.RefTable size := sliceValue.Len() var colNames []string var colMultiPlaces []string var args []interface{} var cols []*core.Column for i := 0; i < size; i++ { v := sliceValue.Index(i) vv := reflect.Indirect(v) elemValue := v.Interface() var colPlaces []string // handle BeforeInsertProcessor // !nashtsai! does user expect it's same slice to passed closure when using Before()/After() when insert multi?? for _, closure := range session.beforeClosures { closure(elemValue) } if processor, ok := interface{}(elemValue).(BeforeInsertProcessor); ok { processor.BeforeInsert() } if i == 0 { for _, col := range table.Columns() { ptrFieldValue, err := col.ValueOfV(&vv) if err != nil { return 0, err } fieldValue := *ptrFieldValue if col.IsAutoIncrement && isZero(fieldValue.Interface()) { continue } if col.MapType == core.ONLYFROMDB { continue } if col.IsDeleted { continue } if session.statement.omitColumnMap.contain(col.Name) { continue } if len(session.statement.columnMap) > 0 && !session.statement.columnMap.contain(col.Name) { continue } if (col.IsCreated || col.IsUpdated) && session.statement.UseAutoTime { val, t := session.engine.nowTime(col) args = append(args, val) var colName = col.Name session.afterClosures = append(session.afterClosures, func(bean interface{}) { col := table.GetColumn(colName) setColumnTime(bean, col, t) }) } else if col.IsVersion && session.statement.checkVersion { args = append(args, 1) var colName = col.Name session.afterClosures = append(session.afterClosures, func(bean interface{}) { col := table.GetColumn(colName) setColumnInt(bean, col, 1) }) } else { arg, err := session.value2Interface(col, fieldValue) if err != nil { return 0, err } args = append(args, arg) } colNames = append(colNames, col.Name) cols = append(cols, col) colPlaces = append(colPlaces, "?") } } else { for _, col := range cols { ptrFieldValue, err := col.ValueOfV(&vv) if err != nil { return 0, err } fieldValue := *ptrFieldValue if col.IsAutoIncrement && isZero(fieldValue.Interface()) { continue } if col.MapType == core.ONLYFROMDB { continue } if col.IsDeleted { continue } if session.statement.omitColumnMap.contain(col.Name) { continue } if len(session.statement.columnMap) > 0 && !session.statement.columnMap.contain(col.Name) { continue } if (col.IsCreated || col.IsUpdated) && session.statement.UseAutoTime { val, t := session.engine.nowTime(col) args = append(args, val) var colName = col.Name session.afterClosures = append(session.afterClosures, func(bean interface{}) { col := table.GetColumn(colName) setColumnTime(bean, col, t) }) } else if col.IsVersion && session.statement.checkVersion { args = append(args, 1) var colName = col.Name session.afterClosures = append(session.afterClosures, func(bean interface{}) { col := table.GetColumn(colName) setColumnInt(bean, col, 1) }) } else { arg, err := session.value2Interface(col, fieldValue) if err != nil { return 0, err } args = append(args, arg) } colPlaces = append(colPlaces, "?") } } colMultiPlaces = append(colMultiPlaces, strings.Join(colPlaces, ", ")) } cleanupProcessorsClosures(&session.beforeClosures) var sql string if session.engine.dialect.DBType() == core.ORACLE { temp := fmt.Sprintf(") INTO %s (%v) VALUES (", session.engine.Quote(tableName), quoteColumns(colNames, session.engine.Quote, ",")) sql = fmt.Sprintf("INSERT ALL INTO %s (%v) VALUES (%v) SELECT 1 FROM DUAL", session.engine.Quote(tableName), quoteColumns(colNames, session.engine.Quote, ","), strings.Join(colMultiPlaces, temp)) } else { sql = fmt.Sprintf("INSERT INTO %s (%v) VALUES (%v)", session.engine.Quote(tableName), quoteColumns(colNames, session.engine.Quote, ","), strings.Join(colMultiPlaces, "),(")) } res, err := session.exec(sql, args...) if err != nil { return 0, err } lenAfterClosures := len(session.afterClosures) for i := 0; i < size; i++ { elemValue := reflect.Indirect(sliceValue.Index(i)).Addr().Interface() // handle AfterInsertProcessor if session.isAutoCommit { // !nashtsai! does user expect it's same slice to passed closure when using Before()/After() when insert multi?? for _, closure := range session.afterClosures { closure(elemValue) } if processor, ok := interface{}(elemValue).(AfterInsertProcessor); ok { processor.AfterInsert() } } else { if lenAfterClosures > 0 { if value, has := session.afterInsertBeans[elemValue]; has && value != nil { *value = append(*value, session.afterClosures...) } else { afterClosures := make([]func(interface{}), lenAfterClosures) copy(afterClosures, session.afterClosures) session.afterInsertBeans[elemValue] = &afterClosures } } else { if _, ok := interface{}(elemValue).(AfterInsertProcessor); ok { session.afterInsertBeans[elemValue] = nil } } } } cleanupProcessorsClosures(&session.afterClosures) return res.RowsAffected() } // InsertMulti insert multiple records func (session *Session) InsertMulti(rowsSlicePtr interface{}) (int64, error) { if session.isAutoClose { defer session.Close() } sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr)) if sliceValue.Kind() != reflect.Slice { return 0, ErrParamsType } if sliceValue.Len() <= 0 { return 0, nil } return session.innerInsertMulti(rowsSlicePtr) } func (session *Session) innerInsert(bean interface{}) (int64, error) { if err := session.statement.setRefBean(bean); err != nil { return 0, err } if len(session.statement.TableName()) <= 0 { return 0, ErrTableNotFound } table := session.statement.RefTable // handle BeforeInsertProcessor for _, closure := range session.beforeClosures { closure(bean) } cleanupProcessorsClosures(&session.beforeClosures) // cleanup after used if processor, ok := interface{}(bean).(BeforeInsertProcessor); ok { processor.BeforeInsert() } colNames, args, err := session.genInsertColumns(bean) if err != nil { return 0, err } exprs := session.statement.exprColumns colPlaces := strings.Repeat("?, ", len(colNames)) if exprs.Len() <= 0 && len(colPlaces) > 0 { colPlaces = colPlaces[0 : len(colPlaces)-2] } var tableName = session.statement.TableName() var output string var buf = builder.NewWriter() if _, err := buf.WriteString(fmt.Sprintf("INSERT INTO %s", session.engine.Quote(tableName))); err != nil { return 0, err } if len(colPlaces) <= 0 { if session.engine.dialect.DBType() == core.MYSQL { if _, err := buf.WriteString(" VALUES ()"); err != nil { return 0, err } } else { if _, err := buf.WriteString(fmt.Sprintf("%s DEFAULT VALUES", output)); err != nil { return 0, err } } } else { if _, err := buf.WriteString(" ("); err != nil { return 0, err } if err := writeStrings(buf, append(colNames, exprs.colNames...), "`", "`"); err != nil { return 0, err } if session.statement.cond.IsValid() { if _, err := buf.WriteString(fmt.Sprintf(")%s SELECT ", output)); err != nil { return 0, err } if err := session.statement.writeArgs(buf, args); err != nil { return 0, err } if len(exprs.args) > 0 { if _, err := buf.WriteString(","); err != nil { return 0, err } } if err := exprs.writeArgs(buf); err != nil { return 0, err } if _, err := buf.WriteString(fmt.Sprintf(" FROM %v WHERE ", session.engine.Quote(tableName))); err != nil { return 0, err } if err := session.statement.cond.WriteTo(buf); err != nil { return 0, err } } else { buf.Append(args...) if _, err := buf.WriteString(fmt.Sprintf(")%s VALUES (%v", output, colPlaces)); err != nil { return 0, err } if err := exprs.writeArgs(buf); err != nil { return 0, err } if _, err := buf.WriteString(")"); err != nil { return 0, err } } } if len(table.AutoIncrement) > 0 && session.engine.dialect.DBType() == core.POSTGRES { if _, err := buf.WriteString(" RETURNING " + session.engine.Quote(table.AutoIncrement)); err != nil { return 0, err } } sqlStr := buf.String() args = buf.Args() handleAfterInsertProcessorFunc := func(bean interface{}) { if session.isAutoCommit { for _, closure := range session.afterClosures { closure(bean) } if processor, ok := interface{}(bean).(AfterInsertProcessor); ok { processor.AfterInsert() } } else { lenAfterClosures := len(session.afterClosures) if lenAfterClosures > 0 { if value, has := session.afterInsertBeans[bean]; has && value != nil { *value = append(*value, session.afterClosures...) } else { afterClosures := make([]func(interface{}), lenAfterClosures) copy(afterClosures, session.afterClosures) session.afterInsertBeans[bean] = &afterClosures } } else { if _, ok := interface{}(bean).(AfterInsertProcessor); ok { session.afterInsertBeans[bean] = nil } } } cleanupProcessorsClosures(&session.afterClosures) // cleanup after used } // for postgres, many of them didn't implement lastInsertId, so we should // implemented it ourself. if session.engine.dialect.DBType() == core.ORACLE && len(table.AutoIncrement) > 0 { res, err := session.queryBytes("select seq_atable.currval from dual", args...) if err != nil { return 0, err } defer handleAfterInsertProcessorFunc(bean) if table.Version != "" && session.statement.checkVersion { verValue, err := table.VersionColumn().ValueOf(bean) if err != nil { session.engine.logger.Error(err) } else if verValue.IsValid() && verValue.CanSet() { session.incrVersionFieldValue(verValue) } } if len(res) < 1 { return 0, errors.New("insert no error but not returned id") } idByte := res[0][table.AutoIncrement] id, err := strconv.ParseInt(string(idByte), 10, 64) if err != nil || id <= 0 { return 1, err } aiValue, err := table.AutoIncrColumn().ValueOf(bean) if err != nil { session.engine.logger.Error(err) } if aiValue == nil || !aiValue.IsValid() || !aiValue.CanSet() { return 1, nil } aiValue.Set(int64ToIntValue(id, aiValue.Type())) return 1, nil } else if len(table.AutoIncrement) > 0 && (session.engine.dialect.DBType() == core.POSTGRES) { res, err := session.queryBytes(sqlStr, args...) if err != nil { return 0, err } defer handleAfterInsertProcessorFunc(bean) if table.Version != "" && session.statement.checkVersion { verValue, err := table.VersionColumn().ValueOf(bean) if err != nil { session.engine.logger.Error(err) } else if verValue.IsValid() && verValue.CanSet() { session.incrVersionFieldValue(verValue) } } if len(res) < 1 { return 0, errors.New("insert successfully but not returned id") } idByte := res[0][table.AutoIncrement] id, err := strconv.ParseInt(string(idByte), 10, 64) if err != nil || id <= 0 { return 1, err } aiValue, err := table.AutoIncrColumn().ValueOf(bean) if err != nil { session.engine.logger.Error(err) } if aiValue == nil || !aiValue.IsValid() || !aiValue.CanSet() { return 1, nil } aiValue.Set(int64ToIntValue(id, aiValue.Type())) return 1, nil } else { res, err := session.exec(sqlStr, args...) if err != nil { return 0, err } defer handleAfterInsertProcessorFunc(bean) if table.Version != "" && session.statement.checkVersion { verValue, err := table.VersionColumn().ValueOf(bean) if err != nil { session.engine.logger.Error(err) } else if verValue.IsValid() && verValue.CanSet() { session.incrVersionFieldValue(verValue) } } if table.AutoIncrement == "" { return res.RowsAffected() } var id int64 id, err = res.LastInsertId() if err != nil || id <= 0 { return res.RowsAffected() } aiValue, err := table.AutoIncrColumn().ValueOf(bean) if err != nil { session.engine.logger.Error(err) } if aiValue == nil || !aiValue.IsValid() || !aiValue.CanSet() { return res.RowsAffected() } aiValue.Set(int64ToIntValue(id, aiValue.Type())) return res.RowsAffected() } } // InsertOne insert only one struct into database as a record. // The in parameter bean must a struct or a point to struct. The return // parameter is inserted and error func (session *Session) InsertOne(bean interface{}) (int64, error) { if session.isAutoClose { defer session.Close() } return session.innerInsert(bean) } // genInsertColumns generates insert needed columns func (session *Session) genInsertColumns(bean interface{}) ([]string, []interface{}, error) { table := session.statement.RefTable colNames := make([]string, 0, len(table.ColumnsSeq())) args := make([]interface{}, 0, len(table.ColumnsSeq())) for _, col := range table.Columns() { if col.MapType == core.ONLYFROMDB { continue } if col.IsDeleted { continue } if session.statement.omitColumnMap.contain(col.Name) { continue } if len(session.statement.columnMap) > 0 && !session.statement.columnMap.contain(col.Name) { continue } if session.statement.incrColumns.isColExist(col.Name) { continue } else if session.statement.decrColumns.isColExist(col.Name) { continue } else if session.statement.exprColumns.isColExist(col.Name) { continue } fieldValuePtr, err := col.ValueOf(bean) if err != nil { return nil, nil, err } fieldValue := *fieldValuePtr if col.IsAutoIncrement { switch fieldValue.Type().Kind() { case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int, reflect.Int64: if fieldValue.Int() == 0 { continue } case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint, reflect.Uint64: if fieldValue.Uint() == 0 { continue } case reflect.String: if len(fieldValue.String()) == 0 { continue } case reflect.Ptr: if fieldValue.Pointer() == 0 { continue } } } // !evalphobia! set fieldValue as nil when column is nullable and zero-value if _, ok := getFlagForColumn(session.statement.nullableMap, col); ok { if col.Nullable && isZeroValue(fieldValue) { var nilValue *int fieldValue = reflect.ValueOf(nilValue) } } if (col.IsCreated || col.IsUpdated) && session.statement.UseAutoTime /*&& isZero(fieldValue.Interface())*/ { // if time is non-empty, then set to auto time val, t := session.engine.nowTime(col) args = append(args, val) var colName = col.Name session.afterClosures = append(session.afterClosures, func(bean interface{}) { col := table.GetColumn(colName) setColumnTime(bean, col, t) }) } else if col.IsVersion && session.statement.checkVersion { args = append(args, 1) } else { arg, err := session.value2Interface(col, fieldValue) if err != nil { return colNames, args, err } args = append(args, arg) } colNames = append(colNames, col.Name) } return colNames, args, nil } func (session *Session) insertMapInterface(m map[string]interface{}) (int64, error) { if len(m) == 0 { return 0, ErrParamsType } tableName := session.statement.TableName() if len(tableName) <= 0 { return 0, ErrTableNotFound } var columns = make([]string, 0, len(m)) exprs := session.statement.exprColumns for k := range m { if !exprs.isColExist(k) { columns = append(columns, k) } } sort.Strings(columns) var args = make([]interface{}, 0, len(m)) for _, colName := range columns { args = append(args, m[colName]) } return session.insertMap(columns, args) } func (session *Session) insertMapString(m map[string]string) (int64, error) { if len(m) == 0 { return 0, ErrParamsType } tableName := session.statement.TableName() if len(tableName) <= 0 { return 0, ErrTableNotFound } var columns = make([]string, 0, len(m)) exprs := session.statement.exprColumns for k := range m { if !exprs.isColExist(k) { columns = append(columns, k) } } sort.Strings(columns) var args = make([]interface{}, 0, len(m)) for _, colName := range columns { args = append(args, m[colName]) } return session.insertMap(columns, args) } func (session *Session) insertMap(columns []string, args []interface{}) (int64, error) { tableName := session.statement.TableName() if len(tableName) <= 0 { return 0, ErrTableNotFound } exprs := session.statement.exprColumns w := builder.NewWriter() // if insert where if session.statement.cond.IsValid() { if _, err := w.WriteString(fmt.Sprintf("INSERT INTO %s (", session.engine.Quote(tableName))); err != nil { return 0, err } if err := writeStrings(w, append(columns, exprs.colNames...), "`", "`"); err != nil { return 0, err } if _, err := w.WriteString(") SELECT "); err != nil { return 0, err } if err := session.statement.writeArgs(w, args); err != nil { return 0, err } if len(exprs.args) > 0 { if _, err := w.WriteString(","); err != nil { return 0, err } if err := exprs.writeArgs(w); err != nil { return 0, err } } if _, err := w.WriteString(fmt.Sprintf(" FROM %s WHERE ", session.engine.Quote(tableName))); err != nil { return 0, err } if err := session.statement.cond.WriteTo(w); err != nil { return 0, err } } else { qm := strings.Repeat("?,", len(columns)) qm = qm[:len(qm)-1] if _, err := w.WriteString(fmt.Sprintf("INSERT INTO %s (", session.engine.Quote(tableName))); err != nil { return 0, err } if err := writeStrings(w, append(columns, exprs.colNames...), "`", "`"); err != nil { return 0, err } if _, err := w.WriteString(fmt.Sprintf(") VALUES (%s", qm)); err != nil { return 0, err } w.Append(args...) if len(exprs.args) > 0 { if _, err := w.WriteString(","); err != nil { return 0, err } if err := exprs.writeArgs(w); err != nil { return 0, err } } if _, err := w.WriteString(")"); err != nil { return 0, err } } sql := w.String() args = w.Args() res, err := session.exec(sql, args...) if err != nil { return 0, err } affected, err := res.RowsAffected() if err != nil { return 0, err } return affected, nil }
pkg/util/xorm/session_insert.go
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.00017954286886379123, 0.00017226093041244894, 0.00016714658704586327, 0.00017232983373105526, 0.0000023464206151402323 ]
{ "id": 2, "code_window": [ " menuLogo?: string;\n", " favIcon?: string;\n", " loadingLogo?: string;\n", " appleTouchIcon?: string;\n", "}" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " hideEdition?: boolean;\n" ], "file_path": "public/app/core/components/Branding/types.ts", "type": "add", "edit_start_line_idx": 14 }
import { isNumber } from 'lodash'; import React, { PureComponent } from 'react'; import { DisplayValueAlignmentFactors, FieldDisplay, getDisplayValueAlignmentFactors, getFieldDisplayValues, PanelProps, FieldConfig, DisplayProcessor, DisplayValue, VizOrientation, } from '@grafana/data'; import { BarGauge, DataLinksContextMenu, VizRepeater, VizRepeaterRenderValueProps } from '@grafana/ui'; import { DataLinksContextMenuApi } from '@grafana/ui/src/components/DataLinks/DataLinksContextMenu'; import { config } from 'app/core/config'; import { Options } from './panelcfg.gen'; export class BarGaugePanel extends PureComponent<BarGaugePanelProps> { renderComponent = ( valueProps: VizRepeaterRenderValueProps<FieldDisplay, DisplayValueAlignmentFactors>, menuProps: DataLinksContextMenuApi ): JSX.Element => { const { options, fieldConfig } = this.props; const { value, alignmentFactors, orientation, width, height, count } = valueProps; const { field, display, view, colIndex } = value; const { openMenu, targetClassName } = menuProps; let processor: DisplayProcessor | undefined = undefined; if (view && isNumber(colIndex)) { processor = view.getFieldDisplayProcessor(colIndex); } return ( <BarGauge value={clearNameForSingleSeries(count, fieldConfig.defaults, display)} width={width} height={height} orientation={orientation} field={field} text={options.text} display={processor} theme={config.theme2} itemSpacing={this.getItemSpacing()} displayMode={options.displayMode} onClick={openMenu} className={targetClassName} alignmentFactors={count > 1 ? alignmentFactors : undefined} showUnfilled={options.showUnfilled} valueDisplayMode={options.valueMode} /> ); }; renderValue = (valueProps: VizRepeaterRenderValueProps<FieldDisplay, DisplayValueAlignmentFactors>): JSX.Element => { const { value, orientation } = valueProps; const { hasLinks, getLinks } = value; if (hasLinks && getLinks) { return ( <div style={{ width: '100%', display: orientation === VizOrientation.Vertical ? 'flex' : 'initial' }}> <DataLinksContextMenu style={{ height: '100%' }} links={getLinks}> {(api) => this.renderComponent(valueProps, api)} </DataLinksContextMenu> </div> ); } return this.renderComponent(valueProps, {}); }; getValues = (): FieldDisplay[] => { const { data, options, replaceVariables, fieldConfig, timeZone } = this.props; return getFieldDisplayValues({ fieldConfig, reduceOptions: options.reduceOptions, replaceVariables, theme: config.theme2, data: data.series, timeZone, }); }; getItemSpacing(): number { if (this.props.options.displayMode === 'lcd') { return 2; } return 10; } render() { const { height, width, options, data, renderCounter } = this.props; return ( <VizRepeater source={data} getAlignmentFactors={getDisplayValueAlignmentFactors} getValues={this.getValues} renderValue={this.renderValue} renderCounter={renderCounter} width={width} height={height} minVizWidth={options.minVizWidth} minVizHeight={options.minVizHeight} itemSpacing={this.getItemSpacing()} orientation={options.orientation} /> ); } } export type BarGaugePanelProps = PanelProps<Options>; export function clearNameForSingleSeries(count: number, field: FieldConfig, display: DisplayValue): DisplayValue { if (count === 1 && !field.displayName) { return { ...display, title: undefined, }; } return display; }
public/app/plugins/panel/bargauge/BarGaugePanel.tsx
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.0003351398045197129, 0.00018592685228213668, 0.0001692238001851365, 0.00017412575834896415, 0.00004310650547267869 ]
{ "id": 2, "code_window": [ " menuLogo?: string;\n", " favIcon?: string;\n", " loadingLogo?: string;\n", " appleTouchIcon?: string;\n", "}" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " hideEdition?: boolean;\n" ], "file_path": "public/app/core/components/Branding/types.ts", "type": "add", "edit_start_line_idx": 14 }
import { find, get } from 'lodash'; import { FetchResponse } from '@grafana/runtime'; import TimeGrainConverter from '../time_grain_converter'; import { AzureMonitorLocalizedValue, AzureMonitorLocations, AzureMonitorMetricAvailabilityMetadata, AzureMonitorMetricsMetadataResponse, AzureMonitorOption, AzureAPIResponse, Location, Subscription, Resource, } from '../types'; export default class ResponseParser { static parseResponseValues<T>( result: AzureAPIResponse<T>, textFieldName: string, valueFieldName: string ): Array<{ text: string; value: string }> { const list: Array<{ text: string; value: string }> = []; if (!result) { return list; } for (let i = 0; i < result.value.length; i++) { if (!find(list, ['value', get(result.value[i], valueFieldName)])) { const value = get(result.value[i], valueFieldName); const text = get(result.value[i], textFieldName, value); list.push({ text: text, value: value, }); } } return list; } static parseResourceNames( result: AzureAPIResponse<Resource>, metricNamespace?: string ): Array<{ text: string; value: string }> { const list: Array<{ text: string; value: string }> = []; if (!result) { return list; } for (let i = 0; i < result.value.length; i++) { if ( typeof result.value[i].type === 'string' && (!metricNamespace || result.value[i].type.toLocaleLowerCase() === metricNamespace.toLocaleLowerCase()) ) { list.push({ text: result.value[i].name, value: result.value[i].name, }); } } return list; } static parseMetadata(result: AzureMonitorMetricsMetadataResponse, metricName: string) { const defaultAggTypes = ['None', 'Average', 'Minimum', 'Maximum', 'Total', 'Count']; const metricData = result?.value.find((v) => v.name.value === metricName); if (!metricData) { return { primaryAggType: '', supportedAggTypes: defaultAggTypes, supportedTimeGrains: [], dimensions: [], }; } return { primaryAggType: metricData.primaryAggregationType, supportedAggTypes: metricData.supportedAggregationTypes || defaultAggTypes, supportedTimeGrains: [ { label: 'Auto', value: 'auto' }, ...ResponseParser.parseTimeGrains(metricData.metricAvailabilities ?? []), ], dimensions: ResponseParser.parseDimensions(metricData.dimensions ?? []), }; } static parseTimeGrains(metricAvailabilities: AzureMonitorMetricAvailabilityMetadata[]): AzureMonitorOption[] { const timeGrains: AzureMonitorOption[] = []; if (!metricAvailabilities) { return timeGrains; } metricAvailabilities.forEach((avail) => { if (avail.timeGrain) { timeGrains.push({ label: TimeGrainConverter.createTimeGrainFromISO8601Duration(avail.timeGrain), value: avail.timeGrain, }); } }); return timeGrains; } static parseDimensions(metadataDimensions: AzureMonitorLocalizedValue[]) { return metadataDimensions.map((dimension) => { return { label: dimension.localizedValue || dimension.value, value: dimension.value, }; }); } static parseSubscriptions(result: AzureAPIResponse<Subscription>): Array<{ text: string; value: string }> { const list: Array<{ text: string; value: string }> = []; if (!result) { return list; } const valueFieldName = 'subscriptionId'; const textFieldName = 'displayName'; for (let i = 0; i < result.value.length; i++) { if (!find(list, ['value', get(result.value[i], valueFieldName)])) { list.push({ text: `${get(result.value[i], textFieldName)}`, value: get(result.value[i], valueFieldName), }); } } return list; } static parseSubscriptionsForSelect( result?: FetchResponse<AzureAPIResponse<Subscription>> ): Array<{ label: string; value: string }> { const list: Array<{ label: string; value: string }> = []; if (!result) { return list; } const valueFieldName = 'subscriptionId'; const textFieldName = 'displayName'; for (let i = 0; i < result.data.value.length; i++) { if (!find(list, ['value', get(result.data.value[i], valueFieldName)])) { list.push({ label: `${get(result.data.value[i], textFieldName)} - ${get(result.data.value[i], valueFieldName)}`, value: get(result.data.value[i], valueFieldName), }); } } return list; } static parseLocations(result: AzureAPIResponse<Location>) { const locations: AzureMonitorLocations[] = []; if (!result) { return locations; } for (const location of result.value) { locations.push({ name: location.name, displayName: location.displayName, supportsLogs: undefined }); } return locations; } }
public/app/plugins/datasource/azuremonitor/azure_monitor/response_parser.ts
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.00022106306278146803, 0.00017579861741978675, 0.00016932966536842287, 0.00017324578948318958, 0.000011264635759289376 ]
{ "id": 3, "code_window": [ " isBeta,\n", " };\n", "}\n", "\n", "export function getVersionLinks(): FooterLink[] {\n", " const { buildInfo, licenseInfo } = config;\n", " const links: FooterLink[] = [];\n", " const stateInfo = licenseInfo.stateInfo ? ` (${licenseInfo.stateInfo})` : '';\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function getVersionLinks(hideEdition?: boolean): FooterLink[] {\n" ], "file_path": "public/app/core/components/Footer/Footer.tsx", "type": "replace", "edit_start_line_idx": 50 }
import React from 'react'; import { LinkTarget } from '@grafana/data'; import { config } from '@grafana/runtime'; import { Icon, IconName } from '@grafana/ui'; import { t } from 'app/core/internationalization'; export interface FooterLink { target: LinkTarget; text: string; id: string; icon?: IconName; url?: string; } export let getFooterLinks = (): FooterLink[] => { return [ { target: '_blank', id: 'documentation', text: t('nav.help/documentation', 'Documentation'), icon: 'document-info', url: 'https://grafana.com/docs/grafana/latest/?utm_source=grafana_footer', }, { target: '_blank', id: 'support', text: t('nav.help/support', 'Support'), icon: 'question-circle', url: 'https://grafana.com/products/enterprise/?utm_source=grafana_footer', }, { target: '_blank', id: 'community', text: t('nav.help/community', 'Community'), icon: 'comments-alt', url: 'https://community.grafana.com/?utm_source=grafana_footer', }, ]; }; export function getVersionMeta(version: string) { const isBeta = version.includes('-beta'); return { hasReleaseNotes: true, isBeta, }; } export function getVersionLinks(): FooterLink[] { const { buildInfo, licenseInfo } = config; const links: FooterLink[] = []; const stateInfo = licenseInfo.stateInfo ? ` (${licenseInfo.stateInfo})` : ''; links.push({ target: '_blank', id: 'license', text: `${buildInfo.edition}${stateInfo}`, url: licenseInfo.licenseUrl, }); if (buildInfo.hideVersion) { return links; } const { hasReleaseNotes } = getVersionMeta(buildInfo.version); links.push({ target: '_blank', id: 'version', text: `v${buildInfo.version} (${buildInfo.commit})`, url: hasReleaseNotes ? `https://github.com/grafana/grafana/blob/main/CHANGELOG.md` : undefined, }); if (buildInfo.hasUpdate) { links.push({ target: '_blank', id: 'updateVersion', text: `New version available!`, icon: 'download-alt', url: 'https://grafana.com/grafana/download?utm_source=grafana_footer', }); } return links; } export function setFooterLinksFn(fn: typeof getFooterLinks) { getFooterLinks = fn; } export interface Props { /** Link overrides to show specific links in the UI */ customLinks?: FooterLink[] | null; } export const Footer = React.memo(({ customLinks }: Props) => { const links = (customLinks || getFooterLinks()).concat(getVersionLinks()); return ( <footer className="footer"> <div className="text-center"> <ul> {links.map((link) => ( <li key={link.text}> <FooterItem item={link} /> </li> ))} </ul> </div> </footer> ); }); Footer.displayName = 'Footer'; function FooterItem({ item }: { item: FooterLink }) { const content = item.url ? ( <a href={item.url} target={item.target} rel="noopener noreferrer" id={item.id}> {item.text} </a> ) : ( item.text ); return ( <> {item.icon && <Icon name={item.icon} />} {content} </> ); }
public/app/core/components/Footer/Footer.tsx
1
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.9991369843482971, 0.49816563725471497, 0.00017145901801995933, 0.4938148260116577, 0.4950307309627533 ]
{ "id": 3, "code_window": [ " isBeta,\n", " };\n", "}\n", "\n", "export function getVersionLinks(): FooterLink[] {\n", " const { buildInfo, licenseInfo } = config;\n", " const links: FooterLink[] = [];\n", " const stateInfo = licenseInfo.stateInfo ? ` (${licenseInfo.stateInfo})` : '';\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function getVersionLinks(hideEdition?: boolean): FooterLink[] {\n" ], "file_path": "public/app/core/components/Footer/Footer.tsx", "type": "replace", "edit_start_line_idx": 50 }
package dashboards import ( "context" "fmt" "os" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/provisioning/utils" ) // DashboardProvisioner is responsible for syncing dashboard from disk to // Grafana's database. type DashboardProvisioner interface { HasDashboardSources() bool Provision(ctx context.Context) error PollChanges(ctx context.Context) GetProvisionerResolvedPath(name string) string GetAllowUIUpdatesFromConfig(name string) bool CleanUpOrphanedDashboards(ctx context.Context) } // DashboardProvisionerFactory creates DashboardProvisioners based on input type DashboardProvisionerFactory func(context.Context, string, dashboards.DashboardProvisioningService, org.Service, utils.DashboardStore) (DashboardProvisioner, error) // Provisioner is responsible for syncing dashboard from disk to Grafana's database. type Provisioner struct { log log.Logger fileReaders []*FileReader configs []*config duplicateValidator duplicateValidator provisioner dashboards.DashboardProvisioningService } func (provider *Provisioner) HasDashboardSources() bool { return len(provider.fileReaders) > 0 } // New returns a new DashboardProvisioner func New(ctx context.Context, configDirectory string, provisioner dashboards.DashboardProvisioningService, orgService org.Service, dashboardStore utils.DashboardStore) (DashboardProvisioner, error) { logger := log.New("provisioning.dashboard") cfgReader := &configReader{path: configDirectory, log: logger, orgService: orgService} configs, err := cfgReader.readConfig(ctx) if err != nil { return nil, fmt.Errorf("%v: %w", "Failed to read dashboards config", err) } fileReaders, err := getFileReaders(configs, logger, provisioner, dashboardStore) if err != nil { return nil, fmt.Errorf("%v: %w", "Failed to initialize file readers", err) } d := &Provisioner{ log: logger, fileReaders: fileReaders, configs: configs, duplicateValidator: newDuplicateValidator(logger, fileReaders), provisioner: provisioner, } return d, nil } // Provision scans the disk for dashboards and updates // the database with the latest versions of those dashboards. func (provider *Provisioner) Provision(ctx context.Context) error { for _, reader := range provider.fileReaders { if err := reader.walkDisk(ctx); err != nil { if os.IsNotExist(err) { // don't stop the provisioning service in case the folder is missing. The folder can appear after the startup provider.log.Warn("Failed to provision config", "name", reader.Cfg.Name, "error", err) return nil } return fmt.Errorf("failed to provision config %v: %w", reader.Cfg.Name, err) } } provider.duplicateValidator.validate() return nil } // CleanUpOrphanedDashboards deletes provisioned dashboards missing a linked reader. func (provider *Provisioner) CleanUpOrphanedDashboards(ctx context.Context) { currentReaders := make([]string, len(provider.fileReaders)) for index, reader := range provider.fileReaders { currentReaders[index] = reader.Cfg.Name } if err := provider.provisioner.DeleteOrphanedProvisionedDashboards(ctx, &dashboards.DeleteOrphanedProvisionedDashboardsCommand{ReaderNames: currentReaders}); err != nil { provider.log.Warn("Failed to delete orphaned provisioned dashboards", "err", err) } } // PollChanges starts polling for changes in dashboard definition files. It creates a goroutine for each provider // defined in the config. func (provider *Provisioner) PollChanges(ctx context.Context) { for _, reader := range provider.fileReaders { go reader.pollChanges(ctx) } go provider.duplicateValidator.Run(ctx) } // GetProvisionerResolvedPath returns resolved path for the specified provisioner name. Can be used to generate // relative path to provisioning file from its external_id. func (provider *Provisioner) GetProvisionerResolvedPath(name string) string { for _, reader := range provider.fileReaders { if reader.Cfg.Name == name { return reader.resolvedPath() } } return "" } // GetAllowUIUpdatesFromConfig return if a dashboard provisioner allows updates from the UI func (provider *Provisioner) GetAllowUIUpdatesFromConfig(name string) bool { for _, config := range provider.configs { if config.Name == name { return config.AllowUIUpdates } } return false } func getFileReaders( configs []*config, logger log.Logger, service dashboards.DashboardProvisioningService, store utils.DashboardStore, ) ([]*FileReader, error) { var readers []*FileReader for _, config := range configs { switch config.Type { case "file": fileReader, err := NewDashboardFileReader(config, logger.New("type", config.Type, "name", config.Name), service, store) if err != nil { return nil, fmt.Errorf("failed to create file reader for config %v: %w", config.Name, err) } readers = append(readers, fileReader) default: return nil, fmt.Errorf("type %s is not supported", config.Type) } } return readers, nil }
pkg/services/provisioning/dashboards/dashboard.go
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.002689106622710824, 0.00046185709652490914, 0.00016492731811013073, 0.00016923477232921869, 0.0007376110879704356 ]
{ "id": 3, "code_window": [ " isBeta,\n", " };\n", "}\n", "\n", "export function getVersionLinks(): FooterLink[] {\n", " const { buildInfo, licenseInfo } = config;\n", " const links: FooterLink[] = [];\n", " const stateInfo = licenseInfo.stateInfo ? ` (${licenseInfo.stateInfo})` : '';\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function getVersionLinks(hideEdition?: boolean): FooterLink[] {\n" ], "file_path": "public/app/core/components/Footer/Footer.tsx", "type": "replace", "edit_start_line_idx": 50 }
package postgres import ( "fmt" "regexp" "strings" "time" "github.com/grafana/grafana-plugin-sdk-go/backend" "github.com/grafana/grafana-plugin-sdk-go/backend/gtime" "github.com/grafana/grafana/pkg/tsdb/sqleng" ) const rsIdentifier = `([_a-zA-Z0-9]+)` const sExpr = `\$` + rsIdentifier + `\(([^\)]*)\)` type postgresMacroEngine struct { *sqleng.SQLMacroEngineBase timescaledb bool } func newPostgresMacroEngine(timescaledb bool) sqleng.SQLMacroEngine { return &postgresMacroEngine{ SQLMacroEngineBase: sqleng.NewSQLMacroEngineBase(), timescaledb: timescaledb, } } func (m *postgresMacroEngine) Interpolate(query *backend.DataQuery, timeRange backend.TimeRange, sql string) (string, error) { // TODO: Handle error rExp, _ := regexp.Compile(sExpr) var macroError error sql = m.ReplaceAllStringSubmatchFunc(rExp, sql, func(groups []string) string { // detect if $__timeGroup is supposed to add AS time for pre 5.3 compatibility // if there is a ',' directly after the macro call $__timeGroup is probably used // in the old way. Inside window function ORDER BY $__timeGroup will be followed // by ')' if groups[1] == "__timeGroup" { if index := strings.Index(sql, groups[0]); index >= 0 { index += len(groups[0]) // check for character after macro expression if len(sql) > index && sql[index] == ',' { groups[1] = "__timeGroupAlias" } } } args := strings.Split(groups[2], ",") for i, arg := range args { args[i] = strings.Trim(arg, " ") } res, err := m.evaluateMacro(timeRange, query, groups[1], args) if err != nil && macroError == nil { macroError = err return "macro_error()" } return res }) if macroError != nil { return "", macroError } return sql, nil } //nolint:gocyclo func (m *postgresMacroEngine) evaluateMacro(timeRange backend.TimeRange, query *backend.DataQuery, name string, args []string) (string, error) { switch name { case "__time": if len(args) == 0 { return "", fmt.Errorf("missing time column argument for macro %v", name) } return fmt.Sprintf("%s AS \"time\"", args[0]), nil case "__timeEpoch": if len(args) == 0 { return "", fmt.Errorf("missing time column argument for macro %v", name) } return fmt.Sprintf("extract(epoch from %s) as \"time\"", args[0]), nil case "__timeFilter": if len(args) == 0 { return "", fmt.Errorf("missing time column argument for macro %v", name) } return fmt.Sprintf("%s BETWEEN '%s' AND '%s'", args[0], timeRange.From.UTC().Format(time.RFC3339Nano), timeRange.To.UTC().Format(time.RFC3339Nano)), nil case "__timeFrom": return fmt.Sprintf("'%s'", timeRange.From.UTC().Format(time.RFC3339Nano)), nil case "__timeTo": return fmt.Sprintf("'%s'", timeRange.To.UTC().Format(time.RFC3339Nano)), nil case "__timeGroup": if len(args) < 2 { return "", fmt.Errorf("macro %v needs time column and interval and optional fill value", name) } interval, err := gtime.ParseInterval(strings.Trim(args[1], `'`)) if err != nil { return "", fmt.Errorf("error parsing interval %v", args[1]) } if len(args) == 3 { err := sqleng.SetupFillmode(query, interval, args[2]) if err != nil { return "", err } } if m.timescaledb { return fmt.Sprintf("time_bucket('%.3fs',%s)", interval.Seconds(), args[0]), nil } return fmt.Sprintf( "floor(extract(epoch from %s)/%v)*%v", args[0], interval.Seconds(), interval.Seconds(), ), nil case "__timeGroupAlias": tg, err := m.evaluateMacro(timeRange, query, "__timeGroup", args) if err == nil { return tg + " AS \"time\"", nil } return "", err case "__unixEpochFilter": if len(args) == 0 { return "", fmt.Errorf("missing time column argument for macro %v", name) } return fmt.Sprintf("%s >= %d AND %s <= %d", args[0], timeRange.From.UTC().Unix(), args[0], timeRange.To.UTC().Unix()), nil case "__unixEpochNanoFilter": if len(args) == 0 { return "", fmt.Errorf("missing time column argument for macro %v", name) } return fmt.Sprintf("%s >= %d AND %s <= %d", args[0], timeRange.From.UTC().UnixNano(), args[0], timeRange.To.UTC().UnixNano()), nil case "__unixEpochNanoFrom": return fmt.Sprintf("%d", timeRange.From.UTC().UnixNano()), nil case "__unixEpochNanoTo": return fmt.Sprintf("%d", timeRange.To.UTC().UnixNano()), nil case "__unixEpochGroup": if len(args) < 2 { return "", fmt.Errorf("macro %v needs time column and interval and optional fill value", name) } interval, err := gtime.ParseInterval(strings.Trim(args[1], `'`)) if err != nil { return "", fmt.Errorf("error parsing interval %v", args[1]) } if len(args) == 3 { err := sqleng.SetupFillmode(query, interval, args[2]) if err != nil { return "", err } } return fmt.Sprintf("floor((%s)/%v)*%v", args[0], interval.Seconds(), interval.Seconds()), nil case "__unixEpochGroupAlias": tg, err := m.evaluateMacro(timeRange, query, "__unixEpochGroup", args) if err == nil { return tg + " AS \"time\"", nil } return "", err default: return "", fmt.Errorf("unknown macro %q", name) } }
pkg/tsdb/postgres/macros.go
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.0001790076494216919, 0.0001757349818944931, 0.0001675828971201554, 0.00017698798910714686, 0.0000028735025807691272 ]
{ "id": 3, "code_window": [ " isBeta,\n", " };\n", "}\n", "\n", "export function getVersionLinks(): FooterLink[] {\n", " const { buildInfo, licenseInfo } = config;\n", " const links: FooterLink[] = [];\n", " const stateInfo = licenseInfo.stateInfo ? ` (${licenseInfo.stateInfo})` : '';\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function getVersionLinks(hideEdition?: boolean): FooterLink[] {\n" ], "file_path": "public/app/core/components/Footer/Footer.tsx", "type": "replace", "edit_start_line_idx": 50 }
<div class="gf-form-group"> <div class="grafana-info-box"> <h5>Migration</h5> <p> Consider switching to the Time series visualization type. It is a more capable and performant version of this panel. </p> <p> <button class="btn btn-primary" ng-click="ctrl.migrateToReact()"> Migrate </button> </p> <p>Some features are not supported in the new panel yet.</p> </div> <gf-form-switch class="gf-form" label="Bars" label-class="width-8" checked="ctrl.panel.bars" on-change="ctrl.render()" ></gf-form-switch> <gf-form-switch class="gf-form" label="Lines" label-class="width-8" checked="ctrl.panel.lines" on-change="ctrl.render()" ></gf-form-switch> <div class="gf-form" ng-if="ctrl.panel.lines"> <label class="gf-form-label width-8" for="linewidth-select-input">Line width</label> <div class="gf-form-select-wrapper max-width-5"> <select id="linewidth-select-input" class="gf-form-input" ng-model="ctrl.panel.linewidth" ng-options="f for f in [0,1,2,3,4,5,6,7,8,9,10]" ng-change="ctrl.render()" ></select> </div> </div> <gf-form-switch ng-disabled="!ctrl.panel.lines" class="gf-form" label="Staircase" label-class="width-8" checked="ctrl.panel.steppedLine" on-change="ctrl.render()" ></gf-form-switch> <div class="gf-form" ng-if="ctrl.panel.lines"> <label class="gf-form-label width-8" for="fill-select-input">Area fill</label> <div class="gf-form-select-wrapper max-width-5"> <select id="fill-select-input" class="gf-form-input" ng-model="ctrl.panel.fill" ng-options="f for f in [0,1,2,3,4,5,6,7,8,9,10]" ng-change="ctrl.render()" ></select> </div> </div> <div class="gf-form" ng-if="ctrl.panel.lines && ctrl.panel.fill"> <label class="gf-form-label width-8">Fill gradient</label> <div class="gf-form-select-wrapper max-width-5"> <select class="gf-form-input" ng-model="ctrl.panel.fillGradient" ng-options="f for f in [0,1,2,3,4,5,6,7,8,9,10]" ng-change="ctrl.render()" ></select> </div> </div> <gf-form-switch class="gf-form" label="Points" label-class="width-8" checked="ctrl.panel.points" on-change="ctrl.render()" ></gf-form-switch> <div class="gf-form" ng-if="ctrl.panel.points"> <label class="gf-form-label width-8" for="pointradius-select-input">Point Radius</label> <div class="gf-form-select-wrapper max-width-5"> <select id="pointradius-select-input" class="gf-form-input" ng-model="ctrl.panel.pointradius" ng-options="f for f in [0.5,1,2,3,4,5,6,7,8,9,10]" ng-change="ctrl.render()" ></select> </div> </div> <gf-form-switch class="gf-form" label="Alert thresholds" label-class="width-8" checked="ctrl.panel.options.alertThreshold" on-change="ctrl.render()" ></gf-form-switch> </div> <div class="gf-form-group"> <h5 class="section-heading">Stacking and null value</h5> <gf-form-switch class="gf-form" label="Stack" label-class="width-7" checked="ctrl.panel.stack" on-change="ctrl.render()" > </gf-form-switch> <gf-form-switch class="gf-form" ng-show="ctrl.panel.stack" label="Percent" label-class="width-7" checked="ctrl.panel.percentage" on-change="ctrl.render()" > </gf-form-switch> <div class="gf-form"> <label class="gf-form-label width-7" for="null-value-select-input">Null value</label> <div class="gf-form-select-wrapper"> <select id="null-value-select-input" class="gf-form-input max-width-9" ng-model="ctrl.panel.nullPointMode" ng-options="f for f in ['connected', 'null', 'null as zero']" ng-change="ctrl.render()" ></select> </div> </div> </div> <div class="gf-form-group"> <h5 class="section-heading">Hover tooltip</h5> <div class="gf-form"> <label class="gf-form-label width-9" for="tooltip-mode-select-input">Mode</label> <div class="gf-form-select-wrapper max-width-8"> <select id="tooltip-mode-select-input" class="gf-form-input" ng-model="ctrl.panel.tooltip.shared" ng-options="f.value as f.text for f in [{text: 'All series', value: true}, {text: 'Single', value: false}]" ng-change="ctrl.render()" ></select> </div> </div> <div class="gf-form"> <label class="gf-form-label width-9" for="tooltip-sort-select-input">Sort order</label> <div class="gf-form-select-wrapper max-width-8"> <select id="tooltip-sort-select-input" class="gf-form-input" ng-model="ctrl.panel.tooltip.sort" ng-options="f.value as f.text for f in [{text: 'None', value: 0}, {text: 'Increasing', value: 1}, {text: 'Decreasing', value: 2}]" ng-change="ctrl.render()" ></select> </div> </div> <div class="gf-form" ng-show="ctrl.panel.stack"> <label class="gf-form-label width-9">Stacked value</label> <div class="gf-form-select-wrapper max-width-8"> <select class="gf-form-input" ng-model="ctrl.panel.tooltip.value_type" ng-options="f for f in ['cumulative','individual']" ng-change="ctrl.render()" ></select> </div> </div> </div>
public/app/plugins/panel/graph/tab_display.html
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.00017725228099152446, 0.0001733558310661465, 0.0001653009094297886, 0.00017378013581037521, 0.0000031323620532930363 ]
{ "id": 4, "code_window": [ " const links: FooterLink[] = [];\n", " const stateInfo = licenseInfo.stateInfo ? ` (${licenseInfo.stateInfo})` : '';\n", "\n", " links.push({\n", " target: '_blank',\n", " id: 'license',\n", " text: `${buildInfo.edition}${stateInfo}`,\n", " url: licenseInfo.licenseUrl,\n", " });\n", "\n", " if (buildInfo.hideVersion) {\n", " return links;\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (!hideEdition) {\n", " links.push({\n", " target: '_blank',\n", " id: 'license',\n", " text: `${buildInfo.edition}${stateInfo}`,\n", " url: licenseInfo.licenseUrl,\n", " });\n", " }\n" ], "file_path": "public/app/core/components/Footer/Footer.tsx", "type": "replace", "edit_start_line_idx": 55 }
import { cx, css, keyframes } from '@emotion/css'; import React, { useEffect, useState } from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { useStyles2, styleMixins } from '@grafana/ui'; import { Branding } from '../Branding/Branding'; import { BrandingSettings } from '../Branding/types'; import { Footer } from '../Footer/Footer'; interface InnerBoxProps { enterAnimation?: boolean; } export const InnerBox = ({ children, enterAnimation = true }: React.PropsWithChildren<InnerBoxProps>) => { const loginStyles = useStyles2(getLoginStyles); return <div className={cx(loginStyles.loginInnerBox, enterAnimation && loginStyles.enterAnimation)}>{children}</div>; }; export interface LoginLayoutProps { /** Custom branding settings that can be used e.g. for previewing the Login page changes */ branding?: BrandingSettings; isChangingPassword?: boolean; } export const LoginLayout = ({ children, branding, isChangingPassword }: React.PropsWithChildren<LoginLayoutProps>) => { const loginStyles = useStyles2(getLoginStyles); const [startAnim, setStartAnim] = useState(false); const subTitle = branding?.loginSubtitle ?? Branding.GetLoginSubTitle(); const loginTitle = branding?.loginTitle ?? Branding.LoginTitle; const loginBoxBackground = branding?.loginBoxBackground || Branding.LoginBoxBackground(); const loginLogo = branding?.loginLogo; useEffect(() => setStartAnim(true), []); return ( <Branding.LoginBackground className={cx(loginStyles.container, startAnim && loginStyles.loginAnim, branding?.loginBackground)} > <div className={loginStyles.loginMain}> <div className={cx(loginStyles.loginContent, loginBoxBackground, 'login-content-box')}> <div className={loginStyles.loginLogoWrapper}> <Branding.LoginLogo className={loginStyles.loginLogo} logo={loginLogo} /> <div className={loginStyles.titleWrapper}> {isChangingPassword ? ( <h1 className={loginStyles.mainTitle}>Update your password</h1> ) : ( <> <h1 className={loginStyles.mainTitle}>{loginTitle}</h1> {subTitle && <h3 className={loginStyles.subTitle}>{subTitle}</h3>} </> )} </div> </div> <div className={loginStyles.loginOuterBox}>{children}</div> </div> </div> {branding?.hideFooter ? <></> : <Footer customLinks={branding?.footerLinks} />} </Branding.LoginBackground> ); }; const flyInAnimation = keyframes` from{ opacity: 0; transform: translate(-60px, 0px); } to{ opacity: 1; transform: translate(0px, 0px); }`; export const getLoginStyles = (theme: GrafanaTheme2) => { return { loginMain: css({ flexGrow: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', minWidth: '100%', }), container: css({ minHeight: '100%', backgroundPosition: 'center', backgroundRepeat: 'no-repeat', minWidth: '100%', marginLeft: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', }), loginAnim: css` &:before { opacity: 1; } .login-content-box { opacity: 1; } `, submitButton: css` justify-content: center; width: 100%; `, loginLogo: css` width: 100%; max-width: 60px; margin-bottom: 15px; @media ${styleMixins.mediaUp(theme.v1.breakpoints.sm)} { max-width: 100px; } `, loginLogoWrapper: css` display: flex; align-items: center; justify-content: center; flex-direction: column; padding: ${theme.spacing(3)}; `, titleWrapper: css` text-align: center; `, mainTitle: css` font-size: 22px; @media ${styleMixins.mediaUp(theme.v1.breakpoints.sm)} { font-size: 32px; } `, subTitle: css` font-size: ${theme.typography.size.md}; color: ${theme.colors.text.secondary}; `, loginContent: css` max-width: 478px; width: calc(100% - 2rem); display: flex; align-items: stretch; flex-direction: column; position: relative; justify-content: flex-start; z-index: 1; min-height: 320px; border-radius: ${theme.shape.borderRadius(4)}; padding: ${theme.spacing(2, 0)}; opacity: 0; transition: opacity 0.5s ease-in-out; @media ${styleMixins.mediaUp(theme.v1.breakpoints.sm)} { min-height: 320px; justify-content: center; } `, loginOuterBox: css` display: flex; overflow-y: hidden; align-items: center; justify-content: center; `, loginInnerBox: css` padding: ${theme.spacing(0, 2, 2, 2)}; display: flex; flex-direction: column; align-items: center; justify-content: center; flex-grow: 1; max-width: 415px; width: 100%; transform: translate(0px, 0px); transition: 0.25s ease; `, enterAnimation: css` animation: ${flyInAnimation} ease-out 0.2s; `, }; };
public/app/core/components/Login/LoginLayout.tsx
1
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.00018129531235899776, 0.00017675399431027472, 0.00016495735326316208, 0.00017848220886662602, 0.0000045572814997285604 ]
{ "id": 4, "code_window": [ " const links: FooterLink[] = [];\n", " const stateInfo = licenseInfo.stateInfo ? ` (${licenseInfo.stateInfo})` : '';\n", "\n", " links.push({\n", " target: '_blank',\n", " id: 'license',\n", " text: `${buildInfo.edition}${stateInfo}`,\n", " url: licenseInfo.licenseUrl,\n", " });\n", "\n", " if (buildInfo.hideVersion) {\n", " return links;\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (!hideEdition) {\n", " links.push({\n", " target: '_blank',\n", " id: 'license',\n", " text: `${buildInfo.edition}${stateInfo}`,\n", " url: licenseInfo.licenseUrl,\n", " });\n", " }\n" ], "file_path": "public/app/core/components/Footer/Footer.tsx", "type": "replace", "edit_start_line_idx": 55 }
import { css, cx } from '@emotion/css'; import { isEqual } from 'lodash'; import React, { useEffect, useState } from 'react'; import { SelectableValue } from '@grafana/data'; import { EditorFieldGroup, EditorField, EditorList } from '@grafana/experimental'; import { InlineFieldRow, InlineLabel } from '@grafana/ui'; import { QueryBuilderLabelFilter } from '../shared/types'; import { LabelFilterItem } from './LabelFilterItem'; export const MISSING_LABEL_FILTER_ERROR_MESSAGE = 'Select at least 1 label filter (label and value)'; export interface Props { labelsFilters: QueryBuilderLabelFilter[]; onChange: (labelFilters: Array<Partial<QueryBuilderLabelFilter>>) => void; onGetLabelNames: (forLabel: Partial<QueryBuilderLabelFilter>) => Promise<SelectableValue[]>; onGetLabelValues: (forLabel: Partial<QueryBuilderLabelFilter>) => Promise<SelectableValue[]>; /** If set to true, component will show error message until at least 1 filter is selected */ labelFilterRequired?: boolean; getLabelValuesAutofillSuggestions: (query: string, labelName?: string) => Promise<SelectableValue[]>; debounceDuration: number; variableEditor?: boolean; } export function LabelFilters({ labelsFilters, onChange, onGetLabelNames, onGetLabelValues, labelFilterRequired, getLabelValuesAutofillSuggestions, debounceDuration, variableEditor, }: Props) { const defaultOp = '='; const [items, setItems] = useState<Array<Partial<QueryBuilderLabelFilter>>>([{ op: defaultOp }]); useEffect(() => { if (labelsFilters.length > 0) { setItems(labelsFilters); } else { setItems([{ op: defaultOp }]); } }, [labelsFilters]); const onLabelsChange = (newItems: Array<Partial<QueryBuilderLabelFilter>>) => { setItems(newItems); // Extract full label filters with both label & value const newLabels = newItems.filter((x) => x.label != null && x.value != null); if (!isEqual(newLabels, labelsFilters)) { onChange(newLabels); } }; const hasLabelFilter = items.some((item) => item.label && item.value); const editorList = () => { return ( <EditorList items={items} onChange={onLabelsChange} renderItem={(item: Partial<QueryBuilderLabelFilter>, onChangeItem, onDelete) => ( <LabelFilterItem debounceDuration={debounceDuration} item={item} defaultOp={defaultOp} onChange={onChangeItem} onDelete={onDelete} onGetLabelNames={onGetLabelNames} onGetLabelValues={onGetLabelValues} invalidLabel={labelFilterRequired && !item.label} invalidValue={labelFilterRequired && !item.value} getLabelValuesAutofillSuggestions={getLabelValuesAutofillSuggestions} /> )} /> ); }; return ( <> {variableEditor ? ( <InlineFieldRow> <div className={cx(css` display: flex; `)} > <InlineLabel width={20} tooltip={<div>Optional: used to filter the metric select for this query type.</div>} > Label filters </InlineLabel> {editorList()} </div> </InlineFieldRow> ) : ( <EditorFieldGroup> <EditorField label="Label filters" error={MISSING_LABEL_FILTER_ERROR_MESSAGE} invalid={labelFilterRequired && !hasLabelFilter} > {editorList()} </EditorField> </EditorFieldGroup> )} </> ); }
public/app/plugins/datasource/prometheus/querybuilder/components/LabelFilters.tsx
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.0001791169197531417, 0.00017622164159547538, 0.000168124824995175, 0.00017687198123894632, 0.000002664191697476781 ]
{ "id": 4, "code_window": [ " const links: FooterLink[] = [];\n", " const stateInfo = licenseInfo.stateInfo ? ` (${licenseInfo.stateInfo})` : '';\n", "\n", " links.push({\n", " target: '_blank',\n", " id: 'license',\n", " text: `${buildInfo.edition}${stateInfo}`,\n", " url: licenseInfo.licenseUrl,\n", " });\n", "\n", " if (buildInfo.hideVersion) {\n", " return links;\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (!hideEdition) {\n", " links.push({\n", " target: '_blank',\n", " id: 'license',\n", " text: `${buildInfo.edition}${stateInfo}`,\n", " url: licenseInfo.licenseUrl,\n", " });\n", " }\n" ], "file_path": "public/app/core/components/Footer/Footer.tsx", "type": "replace", "edit_start_line_idx": 55 }
import { SQLOptions, SQLQuery } from 'app/features/plugins/sql/types'; export interface MySQLOptions extends SQLOptions { allowCleartextPasswords?: boolean; } export interface MySQLQuery extends SQLQuery {}
public/app/plugins/datasource/mysql/types.ts
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.00017628783825784922, 0.00017628783825784922, 0.00017628783825784922, 0.00017628783825784922, 0 ]
{ "id": 4, "code_window": [ " const links: FooterLink[] = [];\n", " const stateInfo = licenseInfo.stateInfo ? ` (${licenseInfo.stateInfo})` : '';\n", "\n", " links.push({\n", " target: '_blank',\n", " id: 'license',\n", " text: `${buildInfo.edition}${stateInfo}`,\n", " url: licenseInfo.licenseUrl,\n", " });\n", "\n", " if (buildInfo.hideVersion) {\n", " return links;\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (!hideEdition) {\n", " links.push({\n", " target: '_blank',\n", " id: 'license',\n", " text: `${buildInfo.edition}${stateInfo}`,\n", " url: licenseInfo.licenseUrl,\n", " });\n", " }\n" ], "file_path": "public/app/core/components/Footer/Footer.tsx", "type": "replace", "edit_start_line_idx": 55 }
import { css } from '@emotion/css'; import classnames from 'classnames'; import React from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { Button, useTheme2 } from '@grafana/ui'; export interface Props { isExpanded?: boolean; onClick: () => void; } export const SectionNavToggle = ({ isExpanded, onClick }: Props) => { const theme = useTheme2(); const styles = getStyles(theme); return ( <Button title={'Toggle section navigation'} aria-label={isExpanded ? 'Close section navigation' : 'Open section navigation'} icon="arrow-to-right" className={classnames(styles.icon, { [styles.iconExpanded]: isExpanded, })} variant="secondary" fill="text" size="md" onClick={onClick} /> ); }; SectionNavToggle.displayName = 'SectionNavToggle'; const getStyles = (theme: GrafanaTheme2) => ({ icon: css({ alignSelf: 'center', margin: theme.spacing(1, 0), transform: 'rotate(90deg)', transition: theme.transitions.create('opacity'), color: theme.colors.text.secondary, zIndex: 1, [theme.breakpoints.up('md')]: { alignSelf: 'flex-start', position: 'relative', left: 0, margin: theme.spacing(0, 0, 0, 1), top: theme.spacing(2), transform: 'none', }, 'div:hover > &, &:focus': { opacity: 1, }, }), iconExpanded: css({ rotate: '180deg', [theme.breakpoints.up('md')]: { opacity: 0, margin: 0, position: 'absolute', right: 0, left: 'initial', }, }), });
public/app/core/components/AppChrome/SectionNav/SectionNavToggle.tsx
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.00018060482398141176, 0.00017782014037948102, 0.00017654537805356085, 0.00017765142547432333, 0.000001252706738341658 ]
{ "id": 5, "code_window": [ "}\n", "\n", "export interface Props {\n", " /** Link overrides to show specific links in the UI */\n", " customLinks?: FooterLink[] | null;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " hideEdition?: boolean;\n" ], "file_path": "public/app/core/components/Footer/Footer.tsx", "type": "add", "edit_start_line_idx": 95 }
import React from 'react'; import { LinkTarget } from '@grafana/data'; import { config } from '@grafana/runtime'; import { Icon, IconName } from '@grafana/ui'; import { t } from 'app/core/internationalization'; export interface FooterLink { target: LinkTarget; text: string; id: string; icon?: IconName; url?: string; } export let getFooterLinks = (): FooterLink[] => { return [ { target: '_blank', id: 'documentation', text: t('nav.help/documentation', 'Documentation'), icon: 'document-info', url: 'https://grafana.com/docs/grafana/latest/?utm_source=grafana_footer', }, { target: '_blank', id: 'support', text: t('nav.help/support', 'Support'), icon: 'question-circle', url: 'https://grafana.com/products/enterprise/?utm_source=grafana_footer', }, { target: '_blank', id: 'community', text: t('nav.help/community', 'Community'), icon: 'comments-alt', url: 'https://community.grafana.com/?utm_source=grafana_footer', }, ]; }; export function getVersionMeta(version: string) { const isBeta = version.includes('-beta'); return { hasReleaseNotes: true, isBeta, }; } export function getVersionLinks(): FooterLink[] { const { buildInfo, licenseInfo } = config; const links: FooterLink[] = []; const stateInfo = licenseInfo.stateInfo ? ` (${licenseInfo.stateInfo})` : ''; links.push({ target: '_blank', id: 'license', text: `${buildInfo.edition}${stateInfo}`, url: licenseInfo.licenseUrl, }); if (buildInfo.hideVersion) { return links; } const { hasReleaseNotes } = getVersionMeta(buildInfo.version); links.push({ target: '_blank', id: 'version', text: `v${buildInfo.version} (${buildInfo.commit})`, url: hasReleaseNotes ? `https://github.com/grafana/grafana/blob/main/CHANGELOG.md` : undefined, }); if (buildInfo.hasUpdate) { links.push({ target: '_blank', id: 'updateVersion', text: `New version available!`, icon: 'download-alt', url: 'https://grafana.com/grafana/download?utm_source=grafana_footer', }); } return links; } export function setFooterLinksFn(fn: typeof getFooterLinks) { getFooterLinks = fn; } export interface Props { /** Link overrides to show specific links in the UI */ customLinks?: FooterLink[] | null; } export const Footer = React.memo(({ customLinks }: Props) => { const links = (customLinks || getFooterLinks()).concat(getVersionLinks()); return ( <footer className="footer"> <div className="text-center"> <ul> {links.map((link) => ( <li key={link.text}> <FooterItem item={link} /> </li> ))} </ul> </div> </footer> ); }); Footer.displayName = 'Footer'; function FooterItem({ item }: { item: FooterLink }) { const content = item.url ? ( <a href={item.url} target={item.target} rel="noopener noreferrer" id={item.id}> {item.text} </a> ) : ( item.text ); return ( <> {item.icon && <Icon name={item.icon} />} {content} </> ); }
public/app/core/components/Footer/Footer.tsx
1
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.9985750913619995, 0.08075449615716934, 0.00016647964366711676, 0.00022387204808183014, 0.25520268082618713 ]
{ "id": 5, "code_window": [ "}\n", "\n", "export interface Props {\n", " /** Link overrides to show specific links in the UI */\n", " customLinks?: FooterLink[] | null;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " hideEdition?: boolean;\n" ], "file_path": "public/app/core/components/Footer/Footer.tsx", "type": "add", "edit_start_line_idx": 95 }
import { Receiver } from 'app/plugins/datasource/alertmanager/types'; import { useGetOnCallIntegrationsQuery } from '../../../api/onCallApi'; import { usePluginBridge } from '../../../hooks/usePluginBridge'; import { SupportedPlugin } from '../../../types/pluginBridges'; import { isOnCallReceiver } from './onCall/onCall'; import { AmRouteReceiver, ReceiverWithTypes } from './types'; export const useGetGrafanaReceiverTypeChecker = () => { const { installed: isOnCallEnabled } = usePluginBridge(SupportedPlugin.OnCall); const { data } = useGetOnCallIntegrationsQuery(undefined, { skip: !isOnCallEnabled, }); const getGrafanaReceiverType = (receiver: Receiver): SupportedPlugin | undefined => { //CHECK FOR ONCALL PLUGIN const onCallIntegrations = data ?? []; if (isOnCallEnabled && isOnCallReceiver(receiver, onCallIntegrations)) { return SupportedPlugin.OnCall; } //WE WILL ADD IN HERE IF THERE ARE MORE TYPES TO CHECK return undefined; }; return getGrafanaReceiverType; }; export const useGetAmRouteReceiverWithGrafanaAppTypes = (receivers: Receiver[]) => { const getGrafanaReceiverType = useGetGrafanaReceiverTypeChecker(); const receiverToSelectableContactPointValue = (receiver: Receiver): AmRouteReceiver => { const amRouteReceiverValue: AmRouteReceiver = { label: receiver.name, value: receiver.name, grafanaAppReceiverType: getGrafanaReceiverType(receiver), }; return amRouteReceiverValue; }; return receivers.map(receiverToSelectableContactPointValue); }; export const useGetReceiversWithGrafanaAppTypes = (receivers: Receiver[]): ReceiverWithTypes[] => { const getGrafanaReceiverType = useGetGrafanaReceiverTypeChecker(); return receivers.map((receiver: Receiver) => { return { ...receiver, grafanaAppReceiverType: getGrafanaReceiverType(receiver), }; }); };
public/app/features/alerting/unified/components/receivers/grafanaAppReceivers/grafanaApp.ts
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.00017540121916681528, 0.0001721870357869193, 0.00016695147496648133, 0.0001723768509691581, 0.0000028945280519110383 ]
{ "id": 5, "code_window": [ "}\n", "\n", "export interface Props {\n", " /** Link overrides to show specific links in the UI */\n", " customLinks?: FooterLink[] | null;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " hideEdition?: boolean;\n" ], "file_path": "public/app/core/components/Footer/Footer.tsx", "type": "add", "edit_start_line_idx": 95 }
// Copyright (c) 2020 The Jaeger Authors // // 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 { TraceSpan } from '../types'; import { getHeaderTags, _getTraceNameImpl as getTraceName } from './trace-viewer'; describe('getTraceName', () => { const firstSpanId = 'firstSpanId'; const secondSpanId = 'secondSpanId'; const thirdSpanId = 'thirdSpanId'; const missingSpanId = 'missingSpanId'; const currentTraceId = 'currentTraceId'; const serviceName = 'serviceName'; const operationName = 'operationName'; const t = 1583758670000; // Note: this trace has a loop S1 <- S2 <- S3 <- S1, which is the only way // to make the algorithm return an empty string as trace name. const spansWithNoRoots = [ { spanID: firstSpanId, traceID: currentTraceId, startTime: t + 200, process: {}, references: [ { spanID: secondSpanId, traceID: currentTraceId, }, ], }, { spanID: secondSpanId, traceID: currentTraceId, startTime: t + 100, process: {}, references: [ { spanID: thirdSpanId, traceID: currentTraceId, }, ], }, { spanID: thirdSpanId, traceID: currentTraceId, startTime: t, process: {}, references: [ { spanID: firstSpanId, traceID: currentTraceId, }, ], }, ]; const spansWithMultipleRootsDifferentByStartTime = [ { spanID: firstSpanId, traceID: currentTraceId, startTime: t + 200, process: {}, references: [ { spanID: thirdSpanId, traceID: currentTraceId, }, ], }, { spanID: secondSpanId, // may be a root span traceID: currentTraceId, startTime: t + 100, process: {}, references: [ { spanID: missingSpanId, traceID: currentTraceId, }, ], }, { spanID: thirdSpanId, // root span (as the earliest) traceID: currentTraceId, startTime: t, operationName, process: { serviceName, }, references: [ { spanID: missingSpanId, traceID: currentTraceId, }, ], }, ]; const spansWithMultipleRootsWithOneWithoutRefs = [ { spanID: firstSpanId, traceID: currentTraceId, startTime: t + 200, process: {}, references: [ { spanID: thirdSpanId, traceID: currentTraceId, }, ], }, { spanID: secondSpanId, // root span (as a span without any refs) traceID: currentTraceId, startTime: t + 100, operationName, process: { serviceName, }, }, { spanID: thirdSpanId, // may be a root span traceID: currentTraceId, startTime: t, process: {}, references: [ { spanID: missingSpanId, traceID: currentTraceId, }, ], }, ]; const spansWithOneRootWithRemoteRef = [ { spanID: firstSpanId, traceID: currentTraceId, startTime: t + 200, process: {}, references: [ { spanID: secondSpanId, traceID: currentTraceId, }, ], }, { spanID: secondSpanId, traceID: currentTraceId, startTime: t + 100, process: {}, references: [ { spanID: thirdSpanId, traceID: currentTraceId, }, ], }, { spanID: thirdSpanId, // effective root span, since its parent is missing traceID: currentTraceId, startTime: t, operationName, process: { serviceName, }, references: [ { spanID: missingSpanId, traceID: currentTraceId, }, ], }, ]; const spansWithOneRootWithNoRefs = [ { spanID: firstSpanId, traceID: currentTraceId, startTime: t + 200, process: {}, references: [ { spanID: thirdSpanId, traceID: currentTraceId, }, ], }, { spanID: secondSpanId, // root span traceID: currentTraceId, startTime: t + 100, operationName, process: { serviceName, }, }, { spanID: thirdSpanId, traceID: currentTraceId, startTime: t, process: {}, references: [ { spanID: secondSpanId, traceID: currentTraceId, }, ], }, ]; const spansWithHeaderTags = [ { spanID: firstSpanId, traceID: currentTraceId, startTime: t + 200, process: {}, references: [], tags: [], }, { spanID: secondSpanId, traceID: currentTraceId, startTime: t + 100, process: {}, references: [], tags: [ { key: 'http.method', value: 'POST', }, { key: 'http.status_code', value: '200', }, ], }, { spanID: thirdSpanId, traceID: currentTraceId, startTime: t, process: {}, references: [], tags: [ { key: 'http.status_code', value: '400', }, { key: 'http.url', value: '/test:80', }, ], }, ]; const fullTraceName = `${serviceName}: ${operationName}`; it('returns an empty string if given spans with no root among them', () => { expect(getTraceName(spansWithNoRoots as TraceSpan[])).toEqual(''); }); it('returns an id of root span with the earliest startTime', () => { expect(getTraceName(spansWithMultipleRootsDifferentByStartTime as TraceSpan[])).toEqual(fullTraceName); }); it('returns an id of root span without any refs', () => { expect(getTraceName(spansWithMultipleRootsWithOneWithoutRefs as unknown as TraceSpan[])).toEqual(fullTraceName); }); it('returns an id of root span with remote ref', () => { expect(getTraceName(spansWithOneRootWithRemoteRef as TraceSpan[])).toEqual(fullTraceName); }); it('returns an id of root span with no refs', () => { expect(getTraceName(spansWithOneRootWithNoRefs as unknown as TraceSpan[])).toEqual(fullTraceName); }); it('returns span with header tags', () => { expect(getHeaderTags(spansWithHeaderTags as unknown as TraceSpan[])).toEqual({ method: [ { key: 'http.method', value: 'POST', }, ], status: [ { key: 'http.status_code', value: '200', }, ], url: [], }); }); });
public/app/features/explore/TraceView/components/model/find-trace-name.test.ts
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.00018000345153268427, 0.0001718379935482517, 0.00016707138274796307, 0.00017200085858348757, 0.0000024419850888079964 ]
{ "id": 5, "code_window": [ "}\n", "\n", "export interface Props {\n", " /** Link overrides to show specific links in the UI */\n", " customLinks?: FooterLink[] | null;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " hideEdition?: boolean;\n" ], "file_path": "public/app/core/components/Footer/Footer.tsx", "type": "add", "edit_start_line_idx": 95 }
import { MetricsConfiguration, MetricAggregation, PipelineMetricAggregationType } from '../../../types'; import { defaultPipelineVariable, generatePipelineVariableName, } from './SettingsEditor/BucketScriptSettingsEditor/utils'; import { isMetricAggregationWithField, isPipelineAggregationWithMultipleBucketPaths } from './aggregations'; export const metricAggregationConfig: MetricsConfiguration = { count: { label: 'Count', impliedQueryType: 'metrics', requiresField: false, isPipelineAgg: false, supportsMissing: false, supportsMultipleBucketPaths: false, hasSettings: false, hasMeta: false, supportsInlineScript: false, defaults: {}, }, avg: { label: 'Average', impliedQueryType: 'metrics', requiresField: true, supportsInlineScript: true, supportsMissing: true, isPipelineAgg: false, supportsMultipleBucketPaths: false, hasSettings: true, hasMeta: false, defaults: {}, }, sum: { label: 'Sum', impliedQueryType: 'metrics', requiresField: true, supportsInlineScript: true, supportsMissing: true, isPipelineAgg: false, supportsMultipleBucketPaths: false, hasSettings: true, hasMeta: false, defaults: {}, }, max: { label: 'Max', impliedQueryType: 'metrics', requiresField: true, supportsInlineScript: true, supportsMissing: true, isPipelineAgg: false, supportsMultipleBucketPaths: false, hasSettings: true, hasMeta: false, defaults: {}, }, min: { label: 'Min', impliedQueryType: 'metrics', requiresField: true, supportsInlineScript: true, supportsMissing: true, isPipelineAgg: false, supportsMultipleBucketPaths: false, hasSettings: true, hasMeta: false, defaults: {}, }, extended_stats: { label: 'Extended Stats', impliedQueryType: 'metrics', requiresField: true, supportsMissing: true, supportsInlineScript: true, isPipelineAgg: false, supportsMultipleBucketPaths: false, hasSettings: true, hasMeta: true, defaults: { meta: { std_deviation_bounds_lower: true, std_deviation_bounds_upper: true, }, }, }, percentiles: { label: 'Percentiles', impliedQueryType: 'metrics', requiresField: true, supportsMissing: true, supportsInlineScript: true, isPipelineAgg: false, supportsMultipleBucketPaths: false, hasSettings: true, hasMeta: false, defaults: { settings: { percents: ['25', '50', '75', '95', '99'], }, }, }, cardinality: { label: 'Unique Count', impliedQueryType: 'metrics', requiresField: true, supportsMissing: true, isPipelineAgg: false, supportsMultipleBucketPaths: false, hasSettings: true, supportsInlineScript: false, hasMeta: false, defaults: {}, }, moving_avg: { // deprecated in 6.4.0, removed in 8.0.0, // recommended replacement is moving_fn label: 'Moving Average', impliedQueryType: 'metrics', requiresField: true, isPipelineAgg: true, versionRange: '<8.0.0', supportsMissing: false, supportsMultipleBucketPaths: false, hasSettings: true, supportsInlineScript: false, hasMeta: false, defaults: { settings: { model: 'simple', window: '5', }, }, }, moving_fn: { // TODO: Check this label: 'Moving Function', impliedQueryType: 'metrics', requiresField: true, isPipelineAgg: true, supportsMultipleBucketPaths: false, supportsInlineScript: false, supportsMissing: false, hasMeta: false, hasSettings: true, defaults: {}, }, derivative: { label: 'Derivative', impliedQueryType: 'metrics', requiresField: true, isPipelineAgg: true, supportsMissing: false, supportsMultipleBucketPaths: false, hasSettings: true, supportsInlineScript: false, hasMeta: false, defaults: {}, }, serial_diff: { label: 'Serial Difference', impliedQueryType: 'metrics', requiresField: true, isPipelineAgg: true, supportsMissing: false, supportsMultipleBucketPaths: false, hasSettings: true, supportsInlineScript: false, hasMeta: false, defaults: { settings: { lag: '1', }, }, }, cumulative_sum: { label: 'Cumulative Sum', impliedQueryType: 'metrics', requiresField: true, isPipelineAgg: true, supportsMissing: false, supportsMultipleBucketPaths: false, hasSettings: true, supportsInlineScript: false, hasMeta: false, defaults: {}, }, bucket_script: { label: 'Bucket Script', impliedQueryType: 'metrics', requiresField: false, isPipelineAgg: true, supportsMissing: false, supportsMultipleBucketPaths: true, hasSettings: true, supportsInlineScript: false, hasMeta: false, defaults: { pipelineVariables: [defaultPipelineVariable(generatePipelineVariableName([]))], }, }, raw_document: { label: 'Raw Document (deprecated)', requiresField: false, impliedQueryType: 'raw_document', isPipelineAgg: false, supportsMissing: false, supportsMultipleBucketPaths: false, hasSettings: true, supportsInlineScript: false, hasMeta: false, defaults: { settings: { size: '500', }, }, }, raw_data: { label: 'Raw Data', requiresField: false, impliedQueryType: 'raw_data', isPipelineAgg: false, supportsMissing: false, supportsMultipleBucketPaths: false, hasSettings: true, supportsInlineScript: false, hasMeta: false, defaults: { settings: { size: '500', }, }, }, logs: { label: 'Logs', requiresField: false, isPipelineAgg: false, supportsMissing: false, supportsMultipleBucketPaths: false, hasSettings: true, impliedQueryType: 'logs', supportsInlineScript: false, hasMeta: false, defaults: { settings: { limit: '500', }, }, }, top_metrics: { label: 'Top Metrics', impliedQueryType: 'metrics', requiresField: false, isPipelineAgg: false, supportsMissing: false, supportsMultipleBucketPaths: false, hasSettings: true, supportsInlineScript: false, hasMeta: false, defaults: { settings: { order: 'desc', }, }, }, rate: { label: 'Rate', impliedQueryType: 'metrics', requiresField: true, isPipelineAgg: false, supportsMissing: false, supportsMultipleBucketPaths: false, hasSettings: true, supportsInlineScript: true, hasMeta: false, defaults: {}, }, }; interface PipelineOption { label: string; default?: string | number | boolean; } type PipelineOptions = { [K in PipelineMetricAggregationType]: PipelineOption[]; }; export const pipelineOptions: PipelineOptions = { moving_avg: [ { label: 'window', default: 5 }, { label: 'model', default: 'simple' }, { label: 'predict' }, { label: 'minimize', default: false }, ], moving_fn: [{ label: 'window', default: 5 }, { label: 'script' }], derivative: [{ label: 'unit' }], serial_diff: [{ label: 'lag' }], cumulative_sum: [{ label: 'format' }], bucket_script: [], }; /** * Given a metric `MetricA` and an array of metrics, returns all children of `MetricA`. * `MetricB` is considered a child of `MetricA` if `MetricA` is referenced by `MetricB` in its `field` attribute * (`MetricA.id === MetricB.field`) or in its pipeline aggregation variables (for bucket_scripts). * @param metric * @param metrics */ export const getChildren = (metric: MetricAggregation, metrics: MetricAggregation[]): MetricAggregation[] => { const children = metrics.filter((m) => { // TODO: Check this. if (isPipelineAggregationWithMultipleBucketPaths(m)) { return m.pipelineVariables?.some((pv) => pv.pipelineAgg === metric.id); } return isMetricAggregationWithField(m) && metric.id === m.field; }); return [...children, ...children.flatMap((child) => getChildren(child, metrics))]; };
public/app/plugins/datasource/elasticsearch/components/QueryEditor/MetricAggregationsEditor/utils.ts
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.00018214764713775367, 0.00017469450540374964, 0.0001693802187219262, 0.00017448558355681598, 0.000002535353814892005 ]
{ "id": 6, "code_window": [ "}\n", "\n", "export const Footer = React.memo(({ customLinks }: Props) => {\n", " const links = (customLinks || getFooterLinks()).concat(getVersionLinks());\n", "\n", " return (\n", " <footer className=\"footer\">\n", " <div className=\"text-center\">\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const Footer = React.memo(({ customLinks, hideEdition }: Props) => {\n", " const links = (customLinks || getFooterLinks()).concat(getVersionLinks(hideEdition));\n" ], "file_path": "public/app/core/components/Footer/Footer.tsx", "type": "replace", "edit_start_line_idx": 97 }
import React from 'react'; import { LinkTarget } from '@grafana/data'; import { config } from '@grafana/runtime'; import { Icon, IconName } from '@grafana/ui'; import { t } from 'app/core/internationalization'; export interface FooterLink { target: LinkTarget; text: string; id: string; icon?: IconName; url?: string; } export let getFooterLinks = (): FooterLink[] => { return [ { target: '_blank', id: 'documentation', text: t('nav.help/documentation', 'Documentation'), icon: 'document-info', url: 'https://grafana.com/docs/grafana/latest/?utm_source=grafana_footer', }, { target: '_blank', id: 'support', text: t('nav.help/support', 'Support'), icon: 'question-circle', url: 'https://grafana.com/products/enterprise/?utm_source=grafana_footer', }, { target: '_blank', id: 'community', text: t('nav.help/community', 'Community'), icon: 'comments-alt', url: 'https://community.grafana.com/?utm_source=grafana_footer', }, ]; }; export function getVersionMeta(version: string) { const isBeta = version.includes('-beta'); return { hasReleaseNotes: true, isBeta, }; } export function getVersionLinks(): FooterLink[] { const { buildInfo, licenseInfo } = config; const links: FooterLink[] = []; const stateInfo = licenseInfo.stateInfo ? ` (${licenseInfo.stateInfo})` : ''; links.push({ target: '_blank', id: 'license', text: `${buildInfo.edition}${stateInfo}`, url: licenseInfo.licenseUrl, }); if (buildInfo.hideVersion) { return links; } const { hasReleaseNotes } = getVersionMeta(buildInfo.version); links.push({ target: '_blank', id: 'version', text: `v${buildInfo.version} (${buildInfo.commit})`, url: hasReleaseNotes ? `https://github.com/grafana/grafana/blob/main/CHANGELOG.md` : undefined, }); if (buildInfo.hasUpdate) { links.push({ target: '_blank', id: 'updateVersion', text: `New version available!`, icon: 'download-alt', url: 'https://grafana.com/grafana/download?utm_source=grafana_footer', }); } return links; } export function setFooterLinksFn(fn: typeof getFooterLinks) { getFooterLinks = fn; } export interface Props { /** Link overrides to show specific links in the UI */ customLinks?: FooterLink[] | null; } export const Footer = React.memo(({ customLinks }: Props) => { const links = (customLinks || getFooterLinks()).concat(getVersionLinks()); return ( <footer className="footer"> <div className="text-center"> <ul> {links.map((link) => ( <li key={link.text}> <FooterItem item={link} /> </li> ))} </ul> </div> </footer> ); }); Footer.displayName = 'Footer'; function FooterItem({ item }: { item: FooterLink }) { const content = item.url ? ( <a href={item.url} target={item.target} rel="noopener noreferrer" id={item.id}> {item.text} </a> ) : ( item.text ); return ( <> {item.icon && <Icon name={item.icon} />} {content} </> ); }
public/app/core/components/Footer/Footer.tsx
1
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.9979123473167419, 0.2990792691707611, 0.00017032928008120507, 0.0016801839228719473, 0.43849802017211914 ]
{ "id": 6, "code_window": [ "}\n", "\n", "export const Footer = React.memo(({ customLinks }: Props) => {\n", " const links = (customLinks || getFooterLinks()).concat(getVersionLinks());\n", "\n", " return (\n", " <footer className=\"footer\">\n", " <div className=\"text-center\">\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const Footer = React.memo(({ customLinks, hideEdition }: Props) => {\n", " const links = (customLinks || getFooterLinks()).concat(getVersionLinks(hideEdition));\n" ], "file_path": "public/app/core/components/Footer/Footer.tsx", "type": "replace", "edit_start_line_idx": 97 }
// 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 { isEqual } from 'lodash'; import memoizeOne from 'memoize-one'; import * as React from 'react'; import { RefObject } from 'react'; import { GrafanaTheme2, LinkModel, TimeZone } from '@grafana/data'; import { config, reportInteraction } from '@grafana/runtime'; import { stylesFactory, withTheme2, ToolbarButton } from '@grafana/ui'; import { Accessors } from '../ScrollManager'; import { PEER_SERVICE } from '../constants/tag-keys'; import { SpanBarOptions, SpanLinkFunc, TNil } from '../types'; import TTraceTimeline from '../types/TTraceTimeline'; import { TraceLog, TraceSpan, Trace, TraceKeyValuePair, TraceLink, TraceSpanReference } from '../types/trace'; import { getColorByKey } from '../utils/color-generator'; import ListView from './ListView'; import SpanBarRow from './SpanBarRow'; import DetailState from './SpanDetail/DetailState'; import SpanDetailRow from './SpanDetailRow'; import { createViewedBoundsFunc, findServerChildSpan, isErrorSpan, isKindClient, spanContainsErredSpan, ViewedBoundsFunctionType, } from './utils'; const getStyles = stylesFactory((props: TVirtualizedTraceViewOwnProps) => { const { topOfViewRefType } = props; const position = topOfViewRefType === TopOfViewRefType.Explore ? 'fixed' : 'absolute'; return { rowsWrapper: css` width: 100%; `, row: css` width: 100%; `, scrollToTopButton: css` display: flex; flex-direction: column; justify-content: center; align-items: center; width: 40px; height: 40px; position: ${position}; bottom: 30px; right: 30px; z-index: 1; `, }; }); type RowState = { isDetail: boolean; span: TraceSpan; spanIndex: number; }; export enum TopOfViewRefType { Explore = 'Explore', Panel = 'Panel', } type TVirtualizedTraceViewOwnProps = { currentViewRangeTime: [number, number]; timeZone: TimeZone; findMatchesIDs: Set<string> | TNil; registerAccessors: (accesors: Accessors) => void; trace: Trace; spanBarOptions: SpanBarOptions | undefined; linksGetter: (span: TraceSpan, items: TraceKeyValuePair[], itemIndex: number) => TraceLink[]; childrenToggle: (spanID: string) => void; detailLogItemToggle: (spanID: string, log: TraceLog) => void; detailLogsToggle: (spanID: string) => void; detailWarningsToggle: (spanID: string) => void; detailStackTracesToggle: (spanID: string) => void; detailReferencesToggle: (spanID: string) => void; detailReferenceItemToggle: (spanID: string, reference: TraceSpanReference) => void; detailProcessToggle: (spanID: string) => void; detailTagsToggle: (spanID: string) => void; detailToggle: (spanID: string) => void; setSpanNameColumnWidth: (width: number) => void; hoverIndentGuideIds: Set<string>; addHoverIndentGuideId: (spanID: string) => void; removeHoverIndentGuideId: (spanID: string) => void; theme: GrafanaTheme2; createSpanLink?: SpanLinkFunc; scrollElement?: Element; focusedSpanId?: string; focusedSpanIdForSearch: string; showSpanFilterMatchesOnly: boolean; createFocusSpanLink: (traceId: string, spanId: string) => LinkModel; topOfViewRef?: RefObject<HTMLDivElement>; topOfViewRefType?: TopOfViewRefType; datasourceType: string; headerHeight: number; }; export type VirtualizedTraceViewProps = TVirtualizedTraceViewOwnProps & TTraceTimeline; // export for tests export const DEFAULT_HEIGHTS = { bar: 28, detail: 161, detailWithLogs: 197, }; const NUM_TICKS = 5; function generateRowStates( spans: TraceSpan[] | TNil, childrenHiddenIDs: Set<string>, detailStates: Map<string, DetailState | TNil>, findMatchesIDs: Set<string> | TNil, showSpanFilterMatchesOnly: boolean ): RowState[] { if (!spans) { return []; } if (showSpanFilterMatchesOnly && findMatchesIDs) { spans = spans.filter((span) => findMatchesIDs.has(span.spanID)); } let collapseDepth = null; const rowStates = []; for (let i = 0; i < spans.length; i++) { const span = spans[i]; const { spanID, depth } = span; let hidden = false; if (collapseDepth != null) { if (depth >= collapseDepth) { hidden = true; } else { collapseDepth = null; } } if (hidden) { continue; } if (childrenHiddenIDs.has(spanID)) { collapseDepth = depth + 1; } rowStates.push({ span, isDetail: false, spanIndex: i, }); if (detailStates.has(spanID)) { rowStates.push({ span, isDetail: true, spanIndex: i, }); } } return rowStates; } function getClipping(currentViewRange: [number, number]) { const [zoomStart, zoomEnd] = currentViewRange; return { left: zoomStart > 0, right: zoomEnd < 1, }; } function generateRowStatesFromTrace( trace: Trace | TNil, childrenHiddenIDs: Set<string>, detailStates: Map<string, DetailState | TNil>, findMatchesIDs: Set<string> | TNil, showSpanFilterMatchesOnly: boolean ): RowState[] { return trace ? generateRowStates(trace.spans, childrenHiddenIDs, detailStates, findMatchesIDs, showSpanFilterMatchesOnly) : []; } const memoizedGenerateRowStates = memoizeOne(generateRowStatesFromTrace); const memoizedViewBoundsFunc = memoizeOne(createViewedBoundsFunc, isEqual); const memoizedGetClipping = memoizeOne(getClipping, isEqual); // export from tests export class UnthemedVirtualizedTraceView extends React.Component<VirtualizedTraceViewProps> { listView: ListView | TNil; hasScrolledToSpan = false; componentDidMount() { this.scrollToSpan(this.props.headerHeight, this.props.focusedSpanId); } shouldComponentUpdate(nextProps: VirtualizedTraceViewProps) { // If any prop updates, VirtualizedTraceViewImpl should update. let key: keyof VirtualizedTraceViewProps; for (key in nextProps) { if (nextProps[key] !== this.props[key]) { return true; } } return false; } componentDidUpdate(prevProps: Readonly<VirtualizedTraceViewProps>) { const { registerAccessors } = prevProps; const { registerAccessors: nextRegisterAccessors, headerHeight, focusedSpanId, focusedSpanIdForSearch, } = this.props; if (this.listView && registerAccessors !== nextRegisterAccessors) { nextRegisterAccessors(this.getAccessors()); } if (!this.hasScrolledToSpan) { this.scrollToSpan(headerHeight, focusedSpanId); this.hasScrolledToSpan = true; } if (focusedSpanId !== prevProps.focusedSpanId) { this.scrollToSpan(headerHeight, focusedSpanId); } if (focusedSpanIdForSearch !== prevProps.focusedSpanIdForSearch) { this.scrollToSpan(headerHeight, focusedSpanIdForSearch); } } getRowStates(): RowState[] { const { childrenHiddenIDs, detailStates, trace, findMatchesIDs, showSpanFilterMatchesOnly } = this.props; return memoizedGenerateRowStates(trace, childrenHiddenIDs, detailStates, findMatchesIDs, showSpanFilterMatchesOnly); } getClipping(): { left: boolean; right: boolean } { const { currentViewRangeTime } = this.props; return memoizedGetClipping(currentViewRangeTime); } getViewedBounds(): ViewedBoundsFunctionType { const { currentViewRangeTime, trace } = this.props; const [zoomStart, zoomEnd] = currentViewRangeTime; return memoizedViewBoundsFunc({ min: trace.startTime, max: trace.endTime, viewStart: zoomStart, viewEnd: zoomEnd, }); } getAccessors() { const lv = this.listView; if (!lv) { throw new Error('ListView unavailable'); } return { getViewRange: this.getViewRange, getSearchedSpanIDs: this.getSearchedSpanIDs, getCollapsedChildren: this.getCollapsedChildren, getViewHeight: lv.getViewHeight, getBottomRowIndexVisible: lv.getBottomVisibleIndex, getTopRowIndexVisible: lv.getTopVisibleIndex, getRowPosition: lv.getRowPosition, mapRowIndexToSpanIndex: this.mapRowIndexToSpanIndex, mapSpanIndexToRowIndex: this.mapSpanIndexToRowIndex, }; } getViewRange = () => this.props.currentViewRangeTime; getSearchedSpanIDs = () => this.props.findMatchesIDs; getCollapsedChildren = () => this.props.childrenHiddenIDs; mapRowIndexToSpanIndex = (index: number) => this.getRowStates()[index].spanIndex; mapSpanIndexToRowIndex = (index: number) => { const max = this.getRowStates().length; for (let i = 0; i < max; i++) { const { spanIndex } = this.getRowStates()[i]; if (spanIndex === index) { return i; } } throw new Error(`unable to find row for span index: ${index}`); }; setListView = (listView: ListView | TNil) => { const isChanged = this.listView !== listView; this.listView = listView; if (listView && isChanged) { this.props.registerAccessors(this.getAccessors()); } }; // use long form syntax to avert flow error // https://github.com/facebook/flow/issues/3076#issuecomment-290944051 getKeyFromIndex = (index: number) => { const { isDetail, span } = this.getRowStates()[index]; return `${span.traceID}--${span.spanID}--${isDetail ? 'detail' : 'bar'}`; }; getIndexFromKey = (key: string) => { const parts = key.split('--'); const _traceID = parts[0]; const _spanID = parts[1]; const _isDetail = parts[2] === 'detail'; const max = this.getRowStates().length; for (let i = 0; i < max; i++) { const { span, isDetail } = this.getRowStates()[i]; if (span.spanID === _spanID && span.traceID === _traceID && isDetail === _isDetail) { return i; } } return -1; }; getRowHeight = (index: number) => { const { span, isDetail } = this.getRowStates()[index]; if (!isDetail) { return DEFAULT_HEIGHTS.bar; } if (Array.isArray(span.logs) && span.logs.length) { return DEFAULT_HEIGHTS.detailWithLogs; } return DEFAULT_HEIGHTS.detail; }; renderRow = (key: string, style: React.CSSProperties, index: number, attrs: {}) => { const { isDetail, span, spanIndex } = this.getRowStates()[index]; return isDetail ? this.renderSpanDetailRow(span, key, style, attrs) : this.renderSpanBarRow(span, spanIndex, key, style, attrs); }; scrollToSpan = (headerHeight: number, spanID?: string) => { if (spanID == null) { return; } const i = this.getRowStates().findIndex((row) => row.span.spanID === spanID); if (i >= 0) { this.listView?.scrollToIndex(i, headerHeight); } }; renderSpanBarRow(span: TraceSpan, spanIndex: number, key: string, style: React.CSSProperties, attrs: {}) { const { spanID } = span; const { serviceName } = span.process; const { childrenHiddenIDs, childrenToggle, detailStates, detailToggle, findMatchesIDs, spanNameColumnWidth, trace, spanBarOptions, hoverIndentGuideIds, addHoverIndentGuideId, removeHoverIndentGuideId, createSpanLink, focusedSpanId, focusedSpanIdForSearch, showSpanFilterMatchesOnly, theme, datasourceType, } = this.props; // to avert flow error if (!trace) { return null; } const color = getColorByKey(serviceName, theme); const isCollapsed = childrenHiddenIDs.has(spanID); const isDetailExpanded = detailStates.has(spanID); const isMatchingFilter = findMatchesIDs ? findMatchesIDs.has(spanID) : false; const isFocused = spanID === focusedSpanId || spanID === focusedSpanIdForSearch; const showErrorIcon = isErrorSpan(span) || (isCollapsed && spanContainsErredSpan(trace.spans, spanIndex)); // Check for direct child "server" span if the span is a "client" span. let rpc = null; if (isCollapsed) { const rpcSpan = findServerChildSpan(trace.spans.slice(spanIndex)); if (rpcSpan) { const rpcViewBounds = this.getViewedBounds()(rpcSpan.startTime, rpcSpan.startTime + rpcSpan.duration); rpc = { color: getColorByKey(rpcSpan.process.serviceName, theme), operationName: rpcSpan.operationName, serviceName: rpcSpan.process.serviceName, viewEnd: rpcViewBounds.end, viewStart: rpcViewBounds.start, }; } } const peerServiceKV = span.tags.find((kv) => kv.key === PEER_SERVICE); // Leaf, kind == client and has peer.service.tag, is likely a client span that does a request // to an uninstrumented/external service let noInstrumentedServer = null; if (!span.hasChildren && peerServiceKV && isKindClient(span)) { noInstrumentedServer = { serviceName: peerServiceKV.value, color: getColorByKey(peerServiceKV.value, theme), }; } const styles = getStyles(this.props); return ( <div className={styles.row} key={key} style={style} {...attrs}> <SpanBarRow clippingLeft={this.getClipping().left} clippingRight={this.getClipping().right} color={color} spanBarOptions={spanBarOptions} columnDivision={spanNameColumnWidth} isChildrenExpanded={!isCollapsed} isDetailExpanded={isDetailExpanded} isMatchingFilter={isMatchingFilter} isFocused={isFocused} showSpanFilterMatchesOnly={showSpanFilterMatchesOnly} numTicks={NUM_TICKS} onDetailToggled={detailToggle} onChildrenToggled={childrenToggle} rpc={rpc} noInstrumentedServer={noInstrumentedServer} showErrorIcon={showErrorIcon} getViewedBounds={this.getViewedBounds()} traceStartTime={trace.startTime} span={span} hoverIndentGuideIds={hoverIndentGuideIds} addHoverIndentGuideId={addHoverIndentGuideId} removeHoverIndentGuideId={removeHoverIndentGuideId} createSpanLink={createSpanLink} datasourceType={datasourceType} /> </div> ); } renderSpanDetailRow(span: TraceSpan, key: string, style: React.CSSProperties, attrs: {}) { const { spanID } = span; const { serviceName } = span.process; const { detailLogItemToggle, detailLogsToggle, detailProcessToggle, detailReferencesToggle, detailReferenceItemToggle, detailWarningsToggle, detailStackTracesToggle, detailStates, detailTagsToggle, detailToggle, spanNameColumnWidth, trace, timeZone, hoverIndentGuideIds, addHoverIndentGuideId, removeHoverIndentGuideId, linksGetter, createSpanLink, focusedSpanId, createFocusSpanLink, topOfViewRefType, theme, datasourceType, } = this.props; const detailState = detailStates.get(spanID); if (!trace || !detailState) { return null; } const color = getColorByKey(serviceName, theme); const styles = getStyles(this.props); return ( <div className={styles.row} key={key} style={{ ...style, zIndex: 1 }} {...attrs}> <SpanDetailRow color={color} columnDivision={spanNameColumnWidth} onDetailToggled={detailToggle} detailState={detailState} linksGetter={linksGetter} logItemToggle={detailLogItemToggle} logsToggle={detailLogsToggle} processToggle={detailProcessToggle} referenceItemToggle={detailReferenceItemToggle} referencesToggle={detailReferencesToggle} warningsToggle={detailWarningsToggle} stackTracesToggle={detailStackTracesToggle} span={span} timeZone={timeZone} tagsToggle={detailTagsToggle} traceStartTime={trace.startTime} hoverIndentGuideIds={hoverIndentGuideIds} addHoverIndentGuideId={addHoverIndentGuideId} removeHoverIndentGuideId={removeHoverIndentGuideId} createSpanLink={createSpanLink} focusedSpanId={focusedSpanId} createFocusSpanLink={createFocusSpanLink} topOfViewRefType={topOfViewRefType} datasourceType={datasourceType} /> </div> ); } scrollToTop = () => { const { topOfViewRef, datasourceType, trace } = this.props; topOfViewRef?.current?.scrollIntoView({ behavior: 'smooth' }); reportInteraction('grafana_traces_trace_view_scroll_to_top_clicked', { datasourceType: datasourceType, grafana_version: config.buildInfo.version, numServices: trace.services.length, numSpans: trace.spans.length, }); }; render() { const styles = getStyles(this.props); const { scrollElement } = this.props; return ( <> <ListView ref={this.setListView} dataLength={this.getRowStates().length} itemHeightGetter={this.getRowHeight} itemRenderer={this.renderRow} viewBuffer={50} viewBufferMin={50} itemsWrapperClassName={styles.rowsWrapper} getKeyFromIndex={this.getKeyFromIndex} getIndexFromKey={this.getIndexFromKey} windowScroller={false} scrollElement={scrollElement} /> <ToolbarButton className={styles.scrollToTopButton} onClick={this.scrollToTop} title="Scroll to top" icon="arrow-up" ></ToolbarButton> </> ); } } export default withTheme2(UnthemedVirtualizedTraceView);
public/app/features/explore/TraceView/components/TraceTimelineViewer/VirtualizedTraceView.tsx
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.0005774747114628553, 0.00019785315089393407, 0.0001626233133720234, 0.0001720756699796766, 0.00007051229476928711 ]
{ "id": 6, "code_window": [ "}\n", "\n", "export const Footer = React.memo(({ customLinks }: Props) => {\n", " const links = (customLinks || getFooterLinks()).concat(getVersionLinks());\n", "\n", " return (\n", " <footer className=\"footer\">\n", " <div className=\"text-center\">\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const Footer = React.memo(({ customLinks, hideEdition }: Props) => {\n", " const links = (customLinks || getFooterLinks()).concat(getVersionLinks(hideEdition));\n" ], "file_path": "public/app/core/components/Footer/Footer.tsx", "type": "replace", "edit_start_line_idx": 97 }
// Code generated - EDITING IS FUTILE. DO NOT EDIT. // // Generated by: // public/app/plugins/gen.go // Using jennies: // TSTypesJenny // PluginTSTypesJenny // // Run 'make gen-cue' from repository root to regenerate. import * as common from '@grafana/schema'; export interface Options { dedupStrategy: common.LogsDedupStrategy; enableLogDetails: boolean; prettifyLogMessage: boolean; showCommonLabels: boolean; showLabels: boolean; showTime: boolean; sortOrder: common.LogsSortOrder; wrapLogMessage: boolean; }
public/app/plugins/panel/logs/panelcfg.gen.ts
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.0001770649541867897, 0.00017318979371339083, 0.0001697676198091358, 0.00017273685079999268, 0.0000029962920962134376 ]
{ "id": 6, "code_window": [ "}\n", "\n", "export const Footer = React.memo(({ customLinks }: Props) => {\n", " const links = (customLinks || getFooterLinks()).concat(getVersionLinks());\n", "\n", " return (\n", " <footer className=\"footer\">\n", " <div className=\"text-center\">\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const Footer = React.memo(({ customLinks, hideEdition }: Props) => {\n", " const links = (customLinks || getFooterLinks()).concat(getVersionLinks(hideEdition));\n" ], "file_path": "public/app/core/components/Footer/Footer.tsx", "type": "replace", "edit_start_line_idx": 97 }
import { localTimeFormat, systemDateFormats } from './formats'; describe('Date Formats', () => { it('localTimeFormat', () => { const format = localTimeFormat( { year: '2-digit', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', }, '' ); expect(format).toBe('MM/DD/YYYY, hh:mm:ss A'); }); }); describe('Date Formats without hour12', () => { it('localTimeFormat', () => { const format = localTimeFormat( { year: '2-digit', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false, }, '' ); expect(format).toBe('MM/DD/YYYY, HH:mm:ss'); }); }); describe('systemDateFormats', () => { it('contains correct date formats', () => { expect(systemDateFormats.fullDate).toBe('YYYY-MM-DD HH:mm:ss'); expect(systemDateFormats.fullDateMS).toBe('YYYY-MM-DD HH:mm:ss.SSS'); expect(systemDateFormats.interval.millisecond).toBe('HH:mm:ss.SSS'); expect(systemDateFormats.interval.second).toBe('HH:mm:ss'); expect(systemDateFormats.interval.minute).toBe('HH:mm'); expect(systemDateFormats.interval.hour).toBe('MM/DD HH:mm'); expect(systemDateFormats.interval.day).toBe('MM/DD'); expect(systemDateFormats.interval.month).toBe('YYYY-MM'); expect(systemDateFormats.interval.year).toBe('YYYY'); }); it('contains correct browser-localized date formats', () => { systemDateFormats.useBrowserLocale(); expect(systemDateFormats.fullDate).toBe('MM/DD/YYYY, hh:mm:ss A'); expect(systemDateFormats.fullDateMS).toBe('MM/DD/YYYY, hh:mm:ss.SSS A'); expect(systemDateFormats.interval.millisecond).toBe('HH:mm:ss.SSS'); expect(systemDateFormats.interval.second).toBe('HH:mm:ss'); expect(systemDateFormats.interval.minute).toBe('HH:mm'); expect(systemDateFormats.interval.hour).toBe('MM/DD, HH:mm'); expect(systemDateFormats.interval.day).toBe('MM/DD'); expect(systemDateFormats.interval.month).toBe('MM/YYYY'); expect(systemDateFormats.interval.year).toBe('YYYY'); }); });
packages/grafana-data/src/datetime/formats.test.ts
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.00017863186076283455, 0.00017430000298190862, 0.0001717451959848404, 0.00017471400497015566, 0.0000021310540887498064 ]
{ "id": 7, "code_window": [ " const [startAnim, setStartAnim] = useState(false);\n", " const subTitle = branding?.loginSubtitle ?? Branding.GetLoginSubTitle();\n", " const loginTitle = branding?.loginTitle ?? Branding.LoginTitle;\n", " const loginBoxBackground = branding?.loginBoxBackground || Branding.LoginBoxBackground();\n", " const loginLogo = branding?.loginLogo;\n", "\n", " useEffect(() => setStartAnim(true), []);\n", "\n", " return (\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " const hideEdition = branding?.hideEdition ?? Branding.HideEdition;\n" ], "file_path": "public/app/core/components/Login/LoginLayout.tsx", "type": "add", "edit_start_line_idx": 31 }
package dtos import ( "github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/setting" ) type FrontendSettingsAuthDTO struct { OAuthSkipOrgRoleUpdateSync bool `json:"OAuthSkipOrgRoleUpdateSync"` SAMLSkipOrgRoleSync bool `json:"SAMLSkipOrgRoleSync"` LDAPSkipOrgRoleSync bool `json:"LDAPSkipOrgRoleSync"` GoogleSkipOrgRoleSync bool `json:"GoogleSkipOrgRoleSync"` GenericOAuthSkipOrgRoleSync bool `json:"GenericOAuthSkipOrgRoleSync"` JWTAuthSkipOrgRoleSync bool `json:"JWTAuthSkipOrgRoleSync"` GrafanaComSkipOrgRoleSync bool `json:"GrafanaComSkipOrgRoleSync"` AzureADSkipOrgRoleSync bool `json:"AzureADSkipOrgRoleSync"` GithubSkipOrgRoleSync bool `json:"GithubSkipOrgRoleSync"` GitLabSkipOrgRoleSync bool `json:"GitLabSkipOrgRoleSync"` OktaSkipOrgRoleSync bool `json:"OktaSkipOrgRoleSync"` AuthProxyEnableLoginToken bool `json:"AuthProxyEnableLoginToken"` } type FrontendSettingsBuildInfoDTO struct { HideVersion bool `json:"hideVersion"` Version string `json:"version"` Commit string `json:"commit"` Buildstamp int64 `json:"buildstamp"` Edition string `json:"edition"` LatestVersion string `json:"latestVersion"` HasUpdate bool `json:"hasUpdate"` Env string `json:"env"` } type FrontendSettingsLicenseInfoDTO struct { Expiry int64 `json:"expiry"` StateInfo string `json:"stateInfo"` LicenseUrl string `json:"licenseUrl"` Edition string `json:"edition"` EnabledFeatures map[string]bool `json:"enabledFeatures"` // Enterprise-only TrialExpiry *int64 `json:"trialExpiry,omitempty"` AppUrl *string `json:"appUrl,omitempty"` } type FrontendSettingsAzureDTO struct { Cloud string `json:"cloud"` ManagedIdentityEnabled bool `json:"managedIdentityEnabled"` UserIdentityEnabled bool `json:"userIdentityEnabled"` } type FrontendSettingsCachingDTO struct { Enabled bool `json:"enabled"` } type FrontendSettingsRecordedQueriesDTO struct { Enabled bool `json:"enabled"` } type FrontendSettingsReportingDTO struct { Enabled bool `json:"enabled"` } type FrontendSettingsUnifiedAlertingDTO struct { MinInterval string `json:"minInterval"` AlertStateHistoryBackend string `json:"alertStateHistoryBackend,omitempty"` AlertStateHistoryPrimary string `json:"alertStateHistoryPrimary,omitempty"` } // Enterprise-only type FrontendSettingsLicensingDTO struct { Slug *string `json:"slug,omitempty"` LimitBy *string `json:"limitBy,omitempty"` IncludedUsers *int64 `json:"includedUsers,omitempty"` LicenseExpiry *int64 `json:"licenseExpiry,omitempty"` LicenseExpiryWarnDays *int64 `json:"licenseExpiryWarnDays,omitempty"` TokenExpiry *int64 `json:"tokenExpiry,omitempty"` IsTrial *bool `json:"isTrial,omitempty"` TokenExpiryWarnDays *int64 `json:"tokenExpiryWarnDays,omitempty"` UsageBilling *bool `json:"usageBilling,omitempty"` ActiveAdminsAndEditors *int64 `json:"activeAdminsAndEditors,omitempty"` ActiveViewers *int64 `json:"activeViewers,omitempty"` ActiveUsers *int64 `json:"ActiveUsers,omitempty"` } // Enterprise-only type FrontendSettingsFooterConfigItemDTO struct { Text string `json:"text"` Url string `json:"url"` Icon string `json:"icon"` Target string `json:"blank"` } // Enterprise-only type FrontendSettingsPublicDashboardFooterConfigDTO struct { Hide bool `json:"hide"` Text string `json:"text"` Logo string `json:"logo"` Link string `json:"link"` } // Enterprise-only type FrontendSettingsWhitelabelingDTO struct { Links []FrontendSettingsFooterConfigItemDTO `json:"links"` LoginTitle string `json:"loginTitle"` AppTitle *string `json:"appTitle,omitempty"` LoginLogo *string `json:"loginLogo,omitempty"` MenuLogo *string `json:"menuLogo,omitempty"` LoginBackground *string `json:"loginBackground,omitempty"` LoginSubtitle *string `json:"loginSubtitle,omitempty"` LoginBoxBackground *string `json:"loginBoxBackground,omitempty"` LoadingLogo *string `json:"loadingLogo,omitempty"` PublicDashboardFooter *FrontendSettingsPublicDashboardFooterConfigDTO `json:"publicDashboardFooter,omitempty"` // PR TODO: type this properly } type FrontendSettingsSqlConnectionLimitsDTO struct { MaxOpenConns int `json:"maxOpenConns"` MaxIdleConns int `json:"maxIdleConns"` ConnMaxLifetime int `json:"connMaxLifetime"` } type FrontendSettingsDTO struct { DefaultDatasource string `json:"defaultDatasource"` Datasources map[string]plugins.DataSourceDTO `json:"datasources"` MinRefreshInterval string `json:"minRefreshInterval"` Panels map[string]plugins.PanelDTO `json:"panels"` Apps map[string]*plugins.AppDTO `json:"apps"` AppUrl string `json:"appUrl"` AppSubUrl string `json:"appSubUrl"` AllowOrgCreate bool `json:"allowOrgCreate"` AuthProxyEnabled bool `json:"authProxyEnabled"` LdapEnabled bool `json:"ldapEnabled"` JwtHeaderName string `json:"jwtHeaderName"` JwtUrlLogin bool `json:"jwtUrlLogin"` AlertingEnabled bool `json:"alertingEnabled"` AlertingErrorOrTimeout string `json:"alertingErrorOrTimeout"` AlertingNoDataOrNullValues string `json:"alertingNoDataOrNullValues"` AlertingMinInterval int64 `json:"alertingMinInterval"` LiveEnabled bool `json:"liveEnabled"` AutoAssignOrg bool `json:"autoAssignOrg"` VerifyEmailEnabled bool `json:"verifyEmailEnabled"` SigV4AuthEnabled bool `json:"sigV4AuthEnabled"` AzureAuthEnabled bool `json:"azureAuthEnabled"` RbacEnabled bool `json:"rbacEnabled"` ExploreEnabled bool `json:"exploreEnabled"` HelpEnabled bool `json:"helpEnabled"` ProfileEnabled bool `json:"profileEnabled"` NewsFeedEnabled bool `json:"newsFeedEnabled"` QueryHistoryEnabled bool `json:"queryHistoryEnabled"` GoogleAnalyticsId string `json:"googleAnalyticsId"` GoogleAnalytics4Id string `json:"googleAnalytics4Id"` GoogleAnalytics4SendManualPageViews bool `json:"GoogleAnalytics4SendManualPageViews"` RudderstackWriteKey string `json:"rudderstackWriteKey"` RudderstackDataPlaneUrl string `json:"rudderstackDataPlaneUrl"` RudderstackSdkUrl string `json:"rudderstackSdkUrl"` RudderstackConfigUrl string `json:"rudderstackConfigUrl"` FeedbackLinksEnabled bool `json:"feedbackLinksEnabled"` ApplicationInsightsConnectionString string `json:"applicationInsightsConnectionString"` ApplicationInsightsEndpointUrl string `json:"applicationInsightsEndpointUrl"` DisableLoginForm bool `json:"disableLoginForm"` DisableUserSignUp bool `json:"disableUserSignUp"` LoginHint string `json:"loginHint"` PasswordHint string `json:"passwordHint"` ExternalUserMngInfo string `json:"externalUserMngInfo"` ExternalUserMngLinkUrl string `json:"externalUserMngLinkUrl"` ExternalUserMngLinkName string `json:"externalUserMngLinkName"` ViewersCanEdit bool `json:"viewersCanEdit"` AngularSupportEnabled bool `json:"angularSupportEnabled"` EditorsCanAdmin bool `json:"editorsCanAdmin"` DisableSanitizeHtml bool `json:"disableSanitizeHtml"` TrustedTypesDefaultPolicyEnabled bool `json:"trustedTypesDefaultPolicyEnabled"` CSPReportOnlyEnabled bool `json:"cspReportOnlyEnabled"` DisableFrontendSandboxForPlugins []string `json:"disableFrontendSandboxForPlugins"` Auth FrontendSettingsAuthDTO `json:"auth"` BuildInfo FrontendSettingsBuildInfoDTO `json:"buildInfo"` LicenseInfo FrontendSettingsLicenseInfoDTO `json:"licenseInfo"` FeatureToggles map[string]bool `json:"featureToggles"` AnonymousEnabled bool `json:"anonymousEnabled"` RendererAvailable bool `json:"rendererAvailable"` RendererVersion string `json:"rendererVersion"` SecretsManagerPluginEnabled bool `json:"secretsManagerPluginEnabled"` Http2Enabled bool `json:"http2Enabled"` GrafanaJavascriptAgent setting.GrafanaJavascriptAgent `json:"grafanaJavascriptAgent"` PluginCatalogURL string `json:"pluginCatalogURL"` PluginAdminEnabled bool `json:"pluginAdminEnabled"` PluginAdminExternalManageEnabled bool `json:"pluginAdminExternalManageEnabled"` PluginCatalogHiddenPlugins []string `json:"pluginCatalogHiddenPlugins"` ExpressionsEnabled bool `json:"expressionsEnabled"` AwsAllowedAuthProviders []string `json:"awsAllowedAuthProviders"` AwsAssumeRoleEnabled bool `json:"awsAssumeRoleEnabled"` SupportBundlesEnabled bool `json:"supportBundlesEnabled"` SnapshotEnabled bool `json:"snapshotEnabled"` SecureSocksDSProxyEnabled bool `json:"secureSocksDSProxyEnabled"` Azure FrontendSettingsAzureDTO `json:"azure"` Caching FrontendSettingsCachingDTO `json:"caching"` RecordedQueries FrontendSettingsRecordedQueriesDTO `json:"recordedQueries"` Reporting FrontendSettingsReportingDTO `json:"reporting"` UnifiedAlertingEnabled bool `json:"unifiedAlertingEnabled"` UnifiedAlerting FrontendSettingsUnifiedAlertingDTO `json:"unifiedAlerting"` Oauth map[string]interface{} `json:"oauth"` SamlEnabled bool `json:"samlEnabled"` SamlName string `json:"samlName"` TokenExpirationDayLimit int `json:"tokenExpirationDayLimit"` GeomapDefaultBaseLayerConfig *map[string]interface{} `json:"geomapDefaultBaseLayerConfig,omitempty"` GeomapDisableCustomBaseLayer bool `json:"geomapDisableCustomBaseLayer"` IsPublicDashboardView bool `json:"isPublicDashboardView"` DateFormats setting.DateFormats `json:"dateFormats,omitempty"` LoginError string `json:"loginError,omitempty"` PluginsCDNBaseURL string `json:"pluginsCDNBaseURL,omitempty"` SqlConnectionLimits FrontendSettingsSqlConnectionLimitsDTO `json:"sqlConnectionLimits"` // Enterprise Licensing *FrontendSettingsLicensingDTO `json:"licensing,omitempty"` Whitelabeling *FrontendSettingsWhitelabelingDTO `json:"whitelabeling,omitempty"` }
pkg/api/dtos/frontend_settings.go
1
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.9966195821762085, 0.08175650984048843, 0.00016312868683598936, 0.00016989270807243884, 0.27063772082328796 ]
{ "id": 7, "code_window": [ " const [startAnim, setStartAnim] = useState(false);\n", " const subTitle = branding?.loginSubtitle ?? Branding.GetLoginSubTitle();\n", " const loginTitle = branding?.loginTitle ?? Branding.LoginTitle;\n", " const loginBoxBackground = branding?.loginBoxBackground || Branding.LoginBoxBackground();\n", " const loginLogo = branding?.loginLogo;\n", "\n", " useEffect(() => setStartAnim(true), []);\n", "\n", " return (\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " const hideEdition = branding?.hideEdition ?? Branding.HideEdition;\n" ], "file_path": "public/app/core/components/Login/LoginLayout.tsx", "type": "add", "edit_start_line_idx": 31 }
import { DataFrame } from '@grafana/data'; export interface FileImportResult { dataFrames: DataFrame[]; file: File; }
public/app/features/dataframe-import/types.ts
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.0001779752637958154, 0.0001779752637958154, 0.0001779752637958154, 0.0001779752637958154, 0 ]
{ "id": 7, "code_window": [ " const [startAnim, setStartAnim] = useState(false);\n", " const subTitle = branding?.loginSubtitle ?? Branding.GetLoginSubTitle();\n", " const loginTitle = branding?.loginTitle ?? Branding.LoginTitle;\n", " const loginBoxBackground = branding?.loginBoxBackground || Branding.LoginBoxBackground();\n", " const loginLogo = branding?.loginLogo;\n", "\n", " useEffect(() => setStartAnim(true), []);\n", "\n", " return (\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " const hideEdition = branding?.hideEdition ?? Branding.HideEdition;\n" ], "file_path": "public/app/core/components/Login/LoginLayout.tsx", "type": "add", "edit_start_line_idx": 31 }
--- aliases: [] hide_menu: true labels: products: - cloud - enterprise - oss title: Release notes for Grafana 8.5.6 --- <!-- Auto generated by update changelog github action --> # Release notes for Grafana 8.5.6 ### Bug fixes - **Dashboard:** Fixes random scrolling on time range change. [#50379](https://github.com/grafana/grafana/pull/50379), [@torkelo](https://github.com/torkelo) - **Security:** Fixes minor code scanning security warnings in old vendored javascript libs. [#50382](https://github.com/grafana/grafana/pull/50382), [@torkelo](https://github.com/torkelo)
docs/sources/release-notes/release-notes-8-5-6.md
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.0001753905089572072, 0.00017490852042101324, 0.00017442653188481927, 0.00017490852042101324, 4.819885361939669e-7 ]
{ "id": 7, "code_window": [ " const [startAnim, setStartAnim] = useState(false);\n", " const subTitle = branding?.loginSubtitle ?? Branding.GetLoginSubTitle();\n", " const loginTitle = branding?.loginTitle ?? Branding.LoginTitle;\n", " const loginBoxBackground = branding?.loginBoxBackground || Branding.LoginBoxBackground();\n", " const loginLogo = branding?.loginLogo;\n", "\n", " useEffect(() => setStartAnim(true), []);\n", "\n", " return (\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " const hideEdition = branding?.hideEdition ?? Branding.HideEdition;\n" ], "file_path": "public/app/core/components/Login/LoginLayout.tsx", "type": "add", "edit_start_line_idx": 31 }
<svg xmlns="http://www.w3.org/2000/svg" data-name="Layer 1" viewBox="0 0 24 24"><path d="M14.36,14.23a3.76,3.76,0,0,1-4.72,0,1,1,0,0,0-1.28,1.54,5.68,5.68,0,0,0,7.28,0,1,1,0,1,0-1.28-1.54ZM10.5,10A1.5,1.5,0,1,0,9,11.5,1.5,1.5,0,0,0,10.5,10ZM15,9H14a1,1,0,0,0,0,2h1a1,1,0,0,0,0-2ZM12,2A10,10,0,1,0,22,12,10,10,0,0,0,12,2Zm0,18a8,8,0,1,1,8-8A8,8,0,0,1,12,20Z"/></svg>
public/img/icons/unicons/smile-wink.svg
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.00017083562852349132, 0.00017083562852349132, 0.00017083562852349132, 0.00017083562852349132, 0 ]
{ "id": 8, "code_window": [ " </div>\n", " </div>\n", " <div className={loginStyles.loginOuterBox}>{children}</div>\n", " </div>\n", " </div>\n", " {branding?.hideFooter ? <></> : <Footer customLinks={branding?.footerLinks} />}\n", " </Branding.LoginBackground>\n", " );\n", "};\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " {branding?.hideFooter ? <></> : <Footer hideEdition={hideEdition} customLinks={branding?.footerLinks} />}\n" ], "file_path": "public/app/core/components/Login/LoginLayout.tsx", "type": "replace", "edit_start_line_idx": 56 }
import { cx, css, keyframes } from '@emotion/css'; import React, { useEffect, useState } from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { useStyles2, styleMixins } from '@grafana/ui'; import { Branding } from '../Branding/Branding'; import { BrandingSettings } from '../Branding/types'; import { Footer } from '../Footer/Footer'; interface InnerBoxProps { enterAnimation?: boolean; } export const InnerBox = ({ children, enterAnimation = true }: React.PropsWithChildren<InnerBoxProps>) => { const loginStyles = useStyles2(getLoginStyles); return <div className={cx(loginStyles.loginInnerBox, enterAnimation && loginStyles.enterAnimation)}>{children}</div>; }; export interface LoginLayoutProps { /** Custom branding settings that can be used e.g. for previewing the Login page changes */ branding?: BrandingSettings; isChangingPassword?: boolean; } export const LoginLayout = ({ children, branding, isChangingPassword }: React.PropsWithChildren<LoginLayoutProps>) => { const loginStyles = useStyles2(getLoginStyles); const [startAnim, setStartAnim] = useState(false); const subTitle = branding?.loginSubtitle ?? Branding.GetLoginSubTitle(); const loginTitle = branding?.loginTitle ?? Branding.LoginTitle; const loginBoxBackground = branding?.loginBoxBackground || Branding.LoginBoxBackground(); const loginLogo = branding?.loginLogo; useEffect(() => setStartAnim(true), []); return ( <Branding.LoginBackground className={cx(loginStyles.container, startAnim && loginStyles.loginAnim, branding?.loginBackground)} > <div className={loginStyles.loginMain}> <div className={cx(loginStyles.loginContent, loginBoxBackground, 'login-content-box')}> <div className={loginStyles.loginLogoWrapper}> <Branding.LoginLogo className={loginStyles.loginLogo} logo={loginLogo} /> <div className={loginStyles.titleWrapper}> {isChangingPassword ? ( <h1 className={loginStyles.mainTitle}>Update your password</h1> ) : ( <> <h1 className={loginStyles.mainTitle}>{loginTitle}</h1> {subTitle && <h3 className={loginStyles.subTitle}>{subTitle}</h3>} </> )} </div> </div> <div className={loginStyles.loginOuterBox}>{children}</div> </div> </div> {branding?.hideFooter ? <></> : <Footer customLinks={branding?.footerLinks} />} </Branding.LoginBackground> ); }; const flyInAnimation = keyframes` from{ opacity: 0; transform: translate(-60px, 0px); } to{ opacity: 1; transform: translate(0px, 0px); }`; export const getLoginStyles = (theme: GrafanaTheme2) => { return { loginMain: css({ flexGrow: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', minWidth: '100%', }), container: css({ minHeight: '100%', backgroundPosition: 'center', backgroundRepeat: 'no-repeat', minWidth: '100%', marginLeft: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', }), loginAnim: css` &:before { opacity: 1; } .login-content-box { opacity: 1; } `, submitButton: css` justify-content: center; width: 100%; `, loginLogo: css` width: 100%; max-width: 60px; margin-bottom: 15px; @media ${styleMixins.mediaUp(theme.v1.breakpoints.sm)} { max-width: 100px; } `, loginLogoWrapper: css` display: flex; align-items: center; justify-content: center; flex-direction: column; padding: ${theme.spacing(3)}; `, titleWrapper: css` text-align: center; `, mainTitle: css` font-size: 22px; @media ${styleMixins.mediaUp(theme.v1.breakpoints.sm)} { font-size: 32px; } `, subTitle: css` font-size: ${theme.typography.size.md}; color: ${theme.colors.text.secondary}; `, loginContent: css` max-width: 478px; width: calc(100% - 2rem); display: flex; align-items: stretch; flex-direction: column; position: relative; justify-content: flex-start; z-index: 1; min-height: 320px; border-radius: ${theme.shape.borderRadius(4)}; padding: ${theme.spacing(2, 0)}; opacity: 0; transition: opacity 0.5s ease-in-out; @media ${styleMixins.mediaUp(theme.v1.breakpoints.sm)} { min-height: 320px; justify-content: center; } `, loginOuterBox: css` display: flex; overflow-y: hidden; align-items: center; justify-content: center; `, loginInnerBox: css` padding: ${theme.spacing(0, 2, 2, 2)}; display: flex; flex-direction: column; align-items: center; justify-content: center; flex-grow: 1; max-width: 415px; width: 100%; transform: translate(0px, 0px); transition: 0.25s ease; `, enterAnimation: css` animation: ${flyInAnimation} ease-out 0.2s; `, }; };
public/app/core/components/Login/LoginLayout.tsx
1
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.9968752861022949, 0.05388926714658737, 0.00016593685722909868, 0.00017631793161854148, 0.2222813218832016 ]
{ "id": 8, "code_window": [ " </div>\n", " </div>\n", " <div className={loginStyles.loginOuterBox}>{children}</div>\n", " </div>\n", " </div>\n", " {branding?.hideFooter ? <></> : <Footer customLinks={branding?.footerLinks} />}\n", " </Branding.LoginBackground>\n", " );\n", "};\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " {branding?.hideFooter ? <></> : <Footer hideEdition={hideEdition} customLinks={branding?.footerLinks} />}\n" ], "file_path": "public/app/core/components/Login/LoginLayout.tsx", "type": "replace", "edit_start_line_idx": 56 }
--- aliases: - ../../data-sources/elasticsearch/template-variables/ description: Using template variables with Elasticsearch in Grafana keywords: - grafana - elasticsearch - templates - variables - queries labels: products: - cloud - enterprise - oss menuTitle: Template variables title: Elasticsearch template variables weight: 400 --- # Elasticsearch template variables Instead of hard-coding details such as server, application, and sensor names in metric queries, you can use variables. Grafana lists these variables in dropdown select boxes at the top of the dashboard to help you change the data displayed in your dashboard. Grafana refers to such variables as template variables. For an introduction to templating and template variables, refer to the [Templating][variables] and [Add and manage variables][add-template-variables] documentation. ## Choose a variable syntax The Elasticsearch data source supports two variable syntaxes for use in the **Query** field: - `$varname`, such as `hostname:$hostname`, which is easy to read and write but doesn't let you use a variable in the middle of a word. - `[[varname]]`, such as `hostname:[[hostname]]` When the _Multi-value_ or _Include all value_ options are enabled, Grafana converts the labels from plain text to a Lucene-compatible condition. For details, see the [Multi-value variables][add-template-variables-multi-value-variables] documentation. ## Use variables in queries You can use other variables inside the query. This example is used to define a variable named `$host`: ``` {"find": "terms", "field": "hostname", "query": "source:$source"} ``` This uses another variable named `$source` inside the query definition. Whenever you change the value of the `$source` variable via the dropdown, Grafana triggers an update of the `$host` variable to contain only hostnames filtered by, in this case, the `source` document property. These queries by default return results in term order (which can then be sorted alphabetically or numerically as for any variable). To produce a list of terms sorted by doc count (a top-N values list), add an `orderBy` property of "doc_count". This automatically selects a descending sort. {{% admonition type="note" %}} To use an ascending sort (`asc`) with doc_count (a bottom-N list), set `order: "asc"`. However, Elasticsearch [discourages this](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html#search-aggregations-bucket-terms-aggregation-order) because sorting by ascending doc count can return inaccurate results. {{% /admonition %}} To keep terms in the doc count order, set the variable's Sort dropdown to **Disabled**. You can alternatively use other sorting criteria, such as **Alphabetical**, to re-sort them. ``` {"find": "terms", "field": "hostname", "orderBy": "doc_count"} ``` ## Template variable examples {{< figure src="/static/img/docs/elasticsearch/elastic-templating-query-7-4.png" max-width="500px" class="docs-image--no-shadow" caption="Query with template variables" >}} In the above example, a Lucene query filters documents based on the `hostname` property using a variable named `$hostname`. The example also uses a variable in the _Terms_ group by field input box, which you can use to quickly change how data is grouped. To view an example dashboard on Grafana Play, see the [Elasticsearch Templated Dashboard](https://play.grafana.org/d/z8OZC66nk/elasticsearch-8-2-0-sample-flight-data?orgId=1). {{% docs/reference %}} [add-template-variables-multi-value-variables]: "/docs/grafana/ -> /docs/grafana/<GRAFANA VERSION>/dashboards/variables/add-template-variables#multi-value-variables" [add-template-variables-multi-value-variables]: "/docs/grafana-cloud/ -> /docs/grafana/<GRAFANA VERSION>/dashboards/variables/add-template-variables#multi-value-variables" [add-template-variables]: "/docs/grafana/ -> /docs/grafana/<GRAFANA VERSION>/dashboards/variables/add-template-variables" [add-template-variables]: "/docs/grafana-cloud/ -> /docs/grafana/<GRAFANA VERSION>/dashboards/variables/add-template-variables" [variables]: "/docs/grafana/ -> /docs/grafana/<GRAFANA VERSION>/dashboards/variables" [variables]: "/docs/grafana-cloud/ -> /docs/grafana/<GRAFANA VERSION>/dashboards/variables" {{% /docs/reference %}}
docs/sources/datasources/elasticsearch/template-variables/index.md
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.00017642506281845272, 0.00017065943393390626, 0.00016487290849909186, 0.00017241794557776302, 0.000003894859673891915 ]