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": 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 }
package service import ( "context" "fmt" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/infra/log" pluginDashboardsManager "github.com/grafana/grafana/pkg/plugins/manager/dashboards" "github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/plugindashboards" ) func ProvideService(pluginDashboardStore pluginDashboardsManager.FileStore, dashboardPluginService dashboards.PluginService) *Service { return &Service{ pluginDashboardStore: pluginDashboardStore, dashboardPluginService: dashboardPluginService, logger: log.New("plugindashboards"), } } type Service struct { pluginDashboardStore pluginDashboardsManager.FileStore dashboardPluginService dashboards.PluginService logger log.Logger } func (s Service) ListPluginDashboards(ctx context.Context, req *plugindashboards.ListPluginDashboardsRequest) (*plugindashboards.ListPluginDashboardsResponse, error) { if req == nil { return nil, fmt.Errorf("req cannot be nil") } listArgs := &pluginDashboardsManager.ListPluginDashboardFilesArgs{ PluginID: req.PluginID, } listResp, err := s.pluginDashboardStore.ListPluginDashboardFiles(ctx, listArgs) if err != nil { return nil, err } result := make([]*plugindashboards.PluginDashboard, 0) // load current dashboards query := dashboards.GetDashboardsByPluginIDQuery{OrgID: req.OrgID, PluginID: req.PluginID} queryResult, err := s.dashboardPluginService.GetDashboardsByPluginID(ctx, &query) if err != nil { return nil, err } existingMatches := make(map[int64]bool) for _, reference := range listResp.FileReferences { loadReq := &plugindashboards.LoadPluginDashboardRequest{ PluginID: req.PluginID, Reference: reference, } loadResp, err := s.LoadPluginDashboard(ctx, loadReq) if err != nil { return nil, err } dashboard := loadResp.Dashboard res := &plugindashboards.PluginDashboard{} res.UID = dashboard.UID res.Reference = reference res.PluginId = req.PluginID res.Title = dashboard.Title res.Revision = dashboard.Data.Get("revision").MustInt64(1) // find existing dashboard for _, existingDash := range queryResult { if existingDash.Slug == dashboard.Slug { res.UID = existingDash.UID res.DashboardId = existingDash.ID res.Imported = true res.ImportedUri = "db/" + existingDash.Slug res.ImportedUrl = existingDash.GetURL() res.ImportedRevision = existingDash.Data.Get("revision").MustInt64(1) existingMatches[existingDash.ID] = true break } } result = append(result, res) } // find deleted dashboards for _, dash := range queryResult { if _, exists := existingMatches[dash.ID]; !exists { result = append(result, &plugindashboards.PluginDashboard{ UID: dash.UID, Slug: dash.Slug, DashboardId: dash.ID, Removed: true, }) } } return &plugindashboards.ListPluginDashboardsResponse{ Items: result, }, nil } func (s Service) LoadPluginDashboard(ctx context.Context, req *plugindashboards.LoadPluginDashboardRequest) (*plugindashboards.LoadPluginDashboardResponse, error) { if req == nil { return nil, fmt.Errorf("req cannot be nil") } args := &pluginDashboardsManager.GetPluginDashboardFileContentsArgs{ PluginID: req.PluginID, FileReference: req.Reference, } resp, err := s.pluginDashboardStore.GetPluginDashboardFileContents(ctx, args) if err != nil { return nil, err } data, err := simplejson.NewJson(resp.Content) if err != nil { return nil, err } return &plugindashboards.LoadPluginDashboardResponse{ Dashboard: dashboards.NewDashboardFromJson(data), }, nil } var _ plugindashboards.Service = &Service{}
pkg/services/plugindashboards/service/service.go
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.00017581194697413594, 0.00017043572734110057, 0.00016540275828447193, 0.0001705423346720636, 0.0000031049387416715035 ]
{ "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 }
export { SecretInput } from './SecretInput';
packages/grafana-ui/src/components/SecretInput/index.tsx
0
https://github.com/grafana/grafana/commit/3bb23d6be739ace0a82974c0faca5a049866a0a4
[ 0.00017313902208115906, 0.00017313902208115906, 0.00017313902208115906, 0.00017313902208115906, 0 ]
{ "id": 0, "code_window": [ " 'arrow-down': true,\n", " 'arrow-from-right': true,\n", " 'arrow-left': true,\n", " 'arrow-random': true,\n", " 'arrow-right': true,\n", " 'arrow-up': true,\n", " 'arrows-h': true,\n", " 'arrows-v': true,\n", " backward: true,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'arrow-to-right': true,\n" ], "file_path": "packages/grafana-data/src/types/icon.ts", "type": "add", "edit_start_line_idx": 22 }
import { css, cx } from '@emotion/css'; import React, { useEffect, useState } from 'react'; import { useLocalStorage } from 'react-use'; import { NavModel, GrafanaTheme2 } from '@grafana/data'; import { useStyles2, CustomScrollbar, useTheme2 } from '@grafana/ui'; import { SectionNavItem } from './SectionNavItem'; import { SectionNavToggle } from './SectionNavToggle'; export interface Props { model: NavModel; } export function SectionNav({ model }: Props) { const styles = useStyles2(getStyles); const { isExpanded, onToggleSectionNav } = useSectionNavState(); if (!Boolean(model.main?.children?.length)) { return null; } return ( <> <nav className={cx(styles.nav, { [styles.navExpanded]: isExpanded, })} > <CustomScrollbar showScrollIndicators> <div className={styles.items} role="tablist"> <SectionNavItem item={model.main} isSectionRoot /> </div> </CustomScrollbar> </nav> <SectionNavToggle className={styles.collapseIcon} isExpanded={Boolean(isExpanded)} onClick={onToggleSectionNav} /> </> ); } function useSectionNavState() { const theme = useTheme2(); const isSmallScreen = window.matchMedia(`(max-width: ${theme.breakpoints.values.lg}px)`).matches; const [navExpandedPreference, setNavExpandedPreference] = useLocalStorage<boolean>( 'grafana.sectionNav.expanded', !isSmallScreen ); const [isExpanded, setIsExpanded] = useState(!isSmallScreen && navExpandedPreference); useEffect(() => { const mediaQuery = window.matchMedia(`(max-width: ${theme.breakpoints.values.lg}px)`); const onMediaQueryChange = (e: MediaQueryListEvent) => setIsExpanded(e.matches ? false : navExpandedPreference); mediaQuery.addEventListener('change', onMediaQueryChange); return () => mediaQuery.removeEventListener('change', onMediaQueryChange); }, [navExpandedPreference, theme.breakpoints.values.lg]); const onToggleSectionNav = () => { setNavExpandedPreference(!isExpanded); setIsExpanded(!isExpanded); }; return { isExpanded, onToggleSectionNav }; } const getStyles = (theme: GrafanaTheme2) => { return { nav: css({ display: 'flex', flexDirection: 'column', background: theme.colors.background.canvas, flexShrink: 0, transition: theme.transitions.create(['width', 'max-height']), maxHeight: 0, visibility: 'hidden', [theme.breakpoints.up('md')]: { width: 0, maxHeight: 'unset', }, }), navExpanded: css({ maxHeight: '50vh', visibility: 'visible', [theme.breakpoints.up('md')]: { width: '250px', maxHeight: 'unset', }, }), items: css({ display: 'flex', flexDirection: 'column', padding: theme.spacing(2, 1, 2, 2), minWidth: '250px', [theme.breakpoints.up('md')]: { padding: theme.spacing(4.5, 1, 2, 2), }, }), collapseIcon: css({ border: `1px solid ${theme.colors.border.weak}`, left: '50%', transform: 'translate(-50%, 50%) rotate(90deg)', top: theme.spacing(0), [theme.breakpoints.up('md')]: { transform: 'translateX(50%)', top: theme.spacing(8), left: theme.spacing(1), right: theme.spacing(-1), }, }), }; };
public/app/core/components/PageNew/SectionNav.tsx
1
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.00017615813703741878, 0.0001707390765659511, 0.00016618988593108952, 0.00017084309365600348, 0.0000031904880870570196 ]
{ "id": 0, "code_window": [ " 'arrow-down': true,\n", " 'arrow-from-right': true,\n", " 'arrow-left': true,\n", " 'arrow-random': true,\n", " 'arrow-right': true,\n", " 'arrow-up': true,\n", " 'arrows-h': true,\n", " 'arrows-v': true,\n", " backward: true,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'arrow-to-right': true,\n" ], "file_path": "packages/grafana-data/src/types/icon.ts", "type": "add", "edit_start_line_idx": 22 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M9,13h6a1,1,0,0,0,0-2H9a1,1,0,0,0,0,2ZM21,2H3A1,1,0,0,0,2,3V21a1,1,0,0,0,1,1H21a1,1,0,0,0,1-1V3A1,1,0,0,0,21,2ZM20,20H4V4H20Z"/></svg>
public/img/icons/unicons/minus-square-full.svg
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.00016843674529809505, 0.00016843674529809505, 0.00016843674529809505, 0.00016843674529809505, 0 ]
{ "id": 0, "code_window": [ " 'arrow-down': true,\n", " 'arrow-from-right': true,\n", " 'arrow-left': true,\n", " 'arrow-random': true,\n", " 'arrow-right': true,\n", " 'arrow-up': true,\n", " 'arrows-h': true,\n", " 'arrows-v': true,\n", " backward: true,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'arrow-to-right': true,\n" ], "file_path": "packages/grafana-data/src/types/icon.ts", "type": "add", "edit_start_line_idx": 22 }
import { FieldDisplay } from '@grafana/data'; export function filterDisplayItems(item: FieldDisplay) { return !item.field.custom?.hideFrom?.viz && !isNaN(item.display.numeric); } export function sumDisplayItemsReducer(acc: number, item: FieldDisplay) { return item.display.numeric + acc; }
public/app/plugins/panel/piechart/utils.ts
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.00017117755487561226, 0.00017117755487561226, 0.00017117755487561226, 0.00017117755487561226, 0 ]
{ "id": 0, "code_window": [ " 'arrow-down': true,\n", " 'arrow-from-right': true,\n", " 'arrow-left': true,\n", " 'arrow-random': true,\n", " 'arrow-right': true,\n", " 'arrow-up': true,\n", " 'arrows-h': true,\n", " 'arrows-v': true,\n", " backward: true,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'arrow-to-right': true,\n" ], "file_path": "packages/grafana-data/src/types/icon.ts", "type": "add", "edit_start_line_idx": 22 }
import { css } from '@emotion/css'; import React, { FC } from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { ConfirmModal, useStyles2 } from '@grafana/ui'; import { deleteFoldersAndDashboards } from 'app/features/manage-dashboards/state/actions'; import { OnMoveOrDeleleSelectedItems } from '../../types'; interface Props { onDeleteItems: OnMoveOrDeleleSelectedItems; results: Map<string, Set<string>>; isOpen: boolean; onDismiss: () => void; } export const ConfirmDeleteModal: FC<Props> = ({ results, onDeleteItems, isOpen, onDismiss }) => { const styles = useStyles2(getStyles); const dashboards = Array.from(results.get('dashboard') ?? []); const folders = Array.from(results.get('folder') ?? []); const folderCount = folders.length; const dashCount = dashboards.length; let text = 'Do you want to delete the '; let subtitle; const dashEnding = dashCount === 1 ? '' : 's'; const folderEnding = folderCount === 1 ? '' : 's'; if (folderCount > 0 && dashCount > 0) { text += `selected folder${folderEnding} and dashboard${dashEnding}?\n`; subtitle = `All dashboards and alerts of the selected folder${folderEnding} will also be deleted`; } else if (folderCount > 0) { text += `selected folder${folderEnding} and all ${folderCount === 1 ? 'its' : 'their'} dashboards and alerts?`; } else { text += `${dashCount} selected dashboard${dashEnding}?`; } const deleteItems = () => { deleteFoldersAndDashboards(folders, dashboards).then(() => { onDeleteItems(); onDismiss(); }); }; return isOpen ? ( <ConfirmModal isOpen={isOpen} title="Delete" body={ <> {text} {subtitle && <div className={styles.subtitle}>{subtitle}</div>} </> } confirmText="Delete" onConfirm={deleteItems} onDismiss={onDismiss} /> ) : null; }; const getStyles = (theme: GrafanaTheme2) => ({ subtitle: css` font-size: ${theme.typography.fontSize}px; padding-top: ${theme.spacing(2)}; `, });
public/app/features/search/page/components/ConfirmDeleteModal.tsx
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.00024339919036719948, 0.0001826298248488456, 0.0001662001886870712, 0.00017404112440999597, 0.00002502456118236296 ]
{ "id": 1, "code_window": [ " }\n", "\n", " return (\n", " <>\n", " <nav\n", " className={cx(styles.nav, {\n", " [styles.navExpanded]: isExpanded,\n", " })}\n", " >\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <div className={styles.navContainer}>\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "replace", "edit_start_line_idx": 23 }
import { css } from '@emotion/css'; import classnames from 'classnames'; import React from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { IconButton, useTheme2 } from '@grafana/ui'; export interface Props { className?: string; isExpanded: boolean; onClick: () => void; } export const SectionNavToggle = ({ className, isExpanded, onClick }: Props) => { const theme = useTheme2(); const styles = getStyles(theme); return ( <IconButton tooltip={'Toggle section navigation'} aria-label={isExpanded ? 'Close section navigation' : 'Open section navigation'} name={isExpanded ? 'angle-left' : 'angle-right'} className={classnames(className, styles.icon)} size="xl" onClick={onClick} /> ); }; SectionNavToggle.displayName = 'SectionNavToggle'; const getStyles = (theme: GrafanaTheme2) => ({ icon: css({ backgroundColor: theme.colors.background.secondary, border: `1px solid ${theme.colors.border.weak}`, borderRadius: '50%', marginRight: 0, zIndex: 1, }), });
public/app/core/components/PageNew/SectionNavToggle.tsx
1
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.9933348894119263, 0.3986237347126007, 0.00017623759049456567, 0.006728821899741888, 0.4853043854236603 ]
{ "id": 1, "code_window": [ " }\n", "\n", " return (\n", " <>\n", " <nav\n", " className={cx(styles.nav, {\n", " [styles.navExpanded]: isExpanded,\n", " })}\n", " >\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <div className={styles.navContainer}>\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "replace", "edit_start_line_idx": 23 }
--- _build: list: false title: Release notes for Grafana 7.4.2 --- <!-- Auto generated by update changelog github action --> # Release notes for Grafana 7.4.2 ### Features and enhancements - **Explore**: Do not show non queryable data sources in data source picker. [#31144](https://github.com/grafana/grafana/pull/31144), [@torkelo](https://github.com/torkelo) - **Security**: Do not allow an anonymous user to create snapshots. CVE-2021-27358. [#31263](https://github.com/grafana/grafana/pull/31263), [@marefr](https://github.com/marefr) ### Bug fixes - **CloudWatch**: Ensure empty query row errors are not passed to the panel. [#31172](https://github.com/grafana/grafana/pull/31172), [@sunker](https://github.com/sunker) - **DashboardLinks**: Fix the links that always cause a full page to reload. [#31178](https://github.com/grafana/grafana/pull/31178), [@torkelo](https://github.com/torkelo) - **DashboardListPanel**: Fix issue with folder picker always showing All and using old form styles. [#31160](https://github.com/grafana/grafana/pull/31160), [@torkelo](https://github.com/torkelo) - **IPv6**: Support host address configured with enclosing square brackets. [#31226](https://github.com/grafana/grafana/pull/31226), [@aknuds1](https://github.com/aknuds1) - **Permissions**: Fix team and role permissions on folders/dashboards not displayed for non Grafana Admin users. [#31132](https://github.com/grafana/grafana/pull/31132), [@AgnesToulet](https://github.com/AgnesToulet) - **Postgres**: Fix timeGroup macro converts long intervals to invalid numbers when TimescaleDB is enabled. [#31179](https://github.com/grafana/grafana/pull/31179), [@kurokochin](https://github.com/kurokochin) - **Prometheus**: Fix enabling of disabled queries when editing in dashboard. [#31055](https://github.com/grafana/grafana/pull/31055), [@ivanahuckova](https://github.com/ivanahuckova) - **QueryEditors**: Fix an issue that happens after moving queries then editing would update other queries. [#31193](https://github.com/grafana/grafana/pull/31193), [@torkelo](https://github.com/torkelo) - **SqlDataSources**: Fix the Show Generated SQL button in query editors. [#31236](https://github.com/grafana/grafana/pull/31236), [@torkelo](https://github.com/torkelo) - **StatPanels**: Fix an issue where the palette color scheme is not cleared when loading panel. [#31126](https://github.com/grafana/grafana/pull/31126), [@torkelo](https://github.com/torkelo) - **Variables**: Add the default option back for the data source variable. [#31208](https://github.com/grafana/grafana/pull/31208), [@hugohaggmark](https://github.com/hugohaggmark) - **Variables**: Fix missing empty elements from regex filters. [#31156](https://github.com/grafana/grafana/pull/31156), [@hugohaggmark](https://github.com/hugohaggmark)
docs/sources/release-notes/release-notes-7-4-2.md
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.0001724611793179065, 0.00016893474094104022, 0.0001650446793064475, 0.00016929834964685142, 0.0000030386706839635735 ]
{ "id": 1, "code_window": [ " }\n", "\n", " return (\n", " <>\n", " <nav\n", " className={cx(styles.nav, {\n", " [styles.navExpanded]: isExpanded,\n", " })}\n", " >\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <div className={styles.navContainer}>\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "replace", "edit_start_line_idx": 23 }
import { DataQuery as SchemaDataQuery, DataSourceRef as SchemaDataSourceRef } from '@grafana/schema'; /** * @deprecated use the type from @grafana/schema */ export interface DataQuery extends SchemaDataQuery {} /** * @deprecated use the type from @grafana/schema */ export interface DataSourceRef extends SchemaDataSourceRef {} /** * Attached to query results (not persisted) * * @public */ export enum DataTopic { Annotations = 'annotations', } /** * Abstract representation of any label-based query * @internal */ export interface AbstractQuery extends SchemaDataQuery { labelMatchers: AbstractLabelMatcher[]; } /** * @internal */ export enum AbstractLabelOperator { Equal = 'Equal', NotEqual = 'NotEqual', EqualRegEx = 'EqualRegEx', NotEqualRegEx = 'NotEqualRegEx', } /** * @internal */ export type AbstractLabelMatcher = { name: string; value: string; operator: AbstractLabelOperator; }; /** * @internal */ export interface DataSourceWithQueryImportSupport<TQuery extends SchemaDataQuery> { importFromAbstractQueries(labelBasedQuery: AbstractQuery[]): Promise<TQuery[]>; } /** * @internal */ export interface DataSourceWithQueryExportSupport<TQuery extends SchemaDataQuery> { exportToAbstractQueries(query: TQuery[]): Promise<AbstractQuery[]>; } /** * @internal */ export const hasQueryImportSupport = <TQuery extends SchemaDataQuery>( datasource: unknown ): datasource is DataSourceWithQueryImportSupport<TQuery> => { return (datasource as DataSourceWithQueryImportSupport<TQuery>).importFromAbstractQueries !== undefined; }; /** * @internal */ export const hasQueryExportSupport = <TQuery extends SchemaDataQuery>( datasource: unknown ): datasource is DataSourceWithQueryExportSupport<TQuery> => { return (datasource as DataSourceWithQueryExportSupport<TQuery>).exportToAbstractQueries !== undefined; };
packages/grafana-data/src/types/query.ts
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.00017537997337058187, 0.00017176009714603424, 0.0001675063685979694, 0.00017200052388943732, 0.0000024285611743835034 ]
{ "id": 1, "code_window": [ " }\n", "\n", " return (\n", " <>\n", " <nav\n", " className={cx(styles.nav, {\n", " [styles.navExpanded]: isExpanded,\n", " })}\n", " >\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <div className={styles.navContainer}>\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "replace", "edit_start_line_idx": 23 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M21,2H3A1,1,0,0,0,2,3V21a1,1,0,0,0,1,1H21a1,1,0,0,0,1-1V3A1,1,0,0,0,21,2ZM8,20H4V16H8Zm0-6H4V10H8ZM8,8H4V4H8Zm6,12H10V16h4Zm0-6H10V10h4Zm0-6H10V4h4Zm6,12H16V16h4Zm0-6H16V10h4Zm0-6H16V4h4Z"/></svg>
public/img/icons/unicons/table.svg
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.00017115764785557985, 0.00017115764785557985, 0.00017115764785557985, 0.00017115764785557985, 0 ]
{ "id": 2, "code_window": [ " <div className={styles.items} role=\"tablist\">\n", " <SectionNavItem item={model.main} isSectionRoot />\n", " </div>\n", " </CustomScrollbar>\n", " </nav>\n", " <SectionNavToggle className={styles.collapseIcon} isExpanded={Boolean(isExpanded)} onClick={onToggleSectionNav} />\n", " </>\n", " );\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " <SectionNavToggle\n", " className={cx(styles.collapseIcon, {\n", " [styles.collapseIconExpanded]: isExpanded,\n", " })}\n", " isExpanded={Boolean(isExpanded)}\n", " onClick={onToggleSectionNav}\n", " />\n", " </div>\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "replace", "edit_start_line_idx": 35 }
import { css } from '@emotion/css'; import classnames from 'classnames'; import React from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { IconButton, useTheme2 } from '@grafana/ui'; export interface Props { className?: string; isExpanded: boolean; onClick: () => void; } export const SectionNavToggle = ({ className, isExpanded, onClick }: Props) => { const theme = useTheme2(); const styles = getStyles(theme); return ( <IconButton tooltip={'Toggle section navigation'} aria-label={isExpanded ? 'Close section navigation' : 'Open section navigation'} name={isExpanded ? 'angle-left' : 'angle-right'} className={classnames(className, styles.icon)} size="xl" onClick={onClick} /> ); }; SectionNavToggle.displayName = 'SectionNavToggle'; const getStyles = (theme: GrafanaTheme2) => ({ icon: css({ backgroundColor: theme.colors.background.secondary, border: `1px solid ${theme.colors.border.weak}`, borderRadius: '50%', marginRight: 0, zIndex: 1, }), });
public/app/core/components/PageNew/SectionNavToggle.tsx
1
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.9980354905128479, 0.20017477869987488, 0.00016283124568872154, 0.0001753162796376273, 0.39893126487731934 ]
{ "id": 2, "code_window": [ " <div className={styles.items} role=\"tablist\">\n", " <SectionNavItem item={model.main} isSectionRoot />\n", " </div>\n", " </CustomScrollbar>\n", " </nav>\n", " <SectionNavToggle className={styles.collapseIcon} isExpanded={Boolean(isExpanded)} onClick={onToggleSectionNav} />\n", " </>\n", " );\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " <SectionNavToggle\n", " className={cx(styles.collapseIcon, {\n", " [styles.collapseIconExpanded]: isExpanded,\n", " })}\n", " isExpanded={Boolean(isExpanded)}\n", " onClick={onToggleSectionNav}\n", " />\n", " </div>\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "replace", "edit_start_line_idx": 35 }
package api import ( "context" "errors" "fmt" "io" "net/http" "net/textproto" "net/url" "sync" "github.com/grafana/grafana-plugin-sdk-go/backend" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins/backendplugin" "github.com/grafana/grafana/pkg/services/datasources" "github.com/grafana/grafana/pkg/util/proxyutil" "github.com/grafana/grafana/pkg/web" ) // CallResource passes a resource call from a plugin to the backend plugin. // // /api/plugins/:pluginId/resources/* func (hs *HTTPServer) CallResource(c *models.ReqContext) { hs.callPluginResource(c, web.Params(c.Req)[":pluginId"]) } func (hs *HTTPServer) callPluginResource(c *models.ReqContext, pluginID string) { pCtx, found, err := hs.PluginContextProvider.Get(c.Req.Context(), pluginID, c.SignedInUser) if err != nil { c.JsonApiErr(500, "Failed to get plugin settings", err) return } if !found { c.JsonApiErr(404, "Plugin not found", nil) return } req, err := hs.pluginResourceRequest(c) if err != nil { c.JsonApiErr(http.StatusBadRequest, "Failed for create plugin resource request", err) return } if err = hs.makePluginResourceRequest(c.Resp, req, pCtx); err != nil { handleCallResourceError(err, c) } } func (hs *HTTPServer) callPluginResourceWithDataSource(c *models.ReqContext, pluginID string, ds *datasources.DataSource) { pCtx, found, err := hs.PluginContextProvider.GetWithDataSource(c.Req.Context(), pluginID, c.SignedInUser, ds) if err != nil { c.JsonApiErr(500, "Failed to get plugin settings", err) return } if !found { c.JsonApiErr(404, "Plugin not found", nil) return } var dsURL string if pCtx.DataSourceInstanceSettings != nil { dsURL = pCtx.DataSourceInstanceSettings.URL } err = hs.PluginRequestValidator.Validate(dsURL, c.Req) if err != nil { c.JsonApiErr(http.StatusForbidden, "Access denied", err) return } req, err := hs.pluginResourceRequest(c) if err != nil { c.JsonApiErr(http.StatusBadRequest, "Failed for create plugin resource request", err) return } if err = hs.makePluginResourceRequest(c.Resp, req, pCtx); err != nil { handleCallResourceError(err, c) } } func (hs *HTTPServer) pluginResourceRequest(c *models.ReqContext) (*http.Request, error) { clonedReq := c.Req.Clone(c.Req.Context()) rawURL := web.Params(c.Req)["*"] if clonedReq.URL.RawQuery != "" { rawURL += "?" + clonedReq.URL.RawQuery } urlPath, err := url.Parse(rawURL) if err != nil { return nil, err } clonedReq.URL = urlPath return clonedReq, nil } func (hs *HTTPServer) makePluginResourceRequest(w http.ResponseWriter, req *http.Request, pCtx backend.PluginContext) error { proxyutil.PrepareProxyRequest(req) body, err := io.ReadAll(req.Body) if err != nil { return fmt.Errorf("failed to read request body: %w", err) } crReq := &backend.CallResourceRequest{ PluginContext: pCtx, Path: req.URL.Path, Method: req.Method, URL: req.URL.String(), Headers: req.Header, Body: body, } childCtx, cancel := context.WithCancel(req.Context()) defer cancel() stream := newCallResourceResponseStream(childCtx) var wg sync.WaitGroup wg.Add(1) defer func() { if err := stream.Close(); err != nil { hs.log.Warn("Failed to close plugin resource stream", "err", err) } wg.Wait() }() var flushStreamErr error go func() { flushStreamErr = hs.flushStream(stream, w) wg.Done() }() if err := hs.pluginClient.CallResource(req.Context(), crReq, stream); err != nil { return err } return flushStreamErr } func (hs *HTTPServer) flushStream(stream callResourceClientResponseStream, w http.ResponseWriter) error { processedStreams := 0 for { resp, err := stream.Recv() if errors.Is(err, io.EOF) { if processedStreams == 0 { return errors.New("received empty resource response") } return nil } if err != nil { if processedStreams == 0 { return fmt.Errorf("%v: %w", "failed to receive response from resource call", err) } hs.log.Error("Failed to receive response from resource call", "err", err) return stream.Close() } // Expected that headers and status are only part of first stream if processedStreams == 0 { var hasContentType bool for k, values := range resp.Headers { // Convert the keys to the canonical format of MIME headers. // This ensures that we can safely add/overwrite headers // even if the plugin returns them in non-canonical format // and be sure they won't be present multiple times in the response. k = textproto.CanonicalMIMEHeaderKey(k) switch k { case "Set-Cookie": // Due to security reasons we don't want to forward // cookies from a backend plugin to clients/browsers. continue case "Content-Type": hasContentType = true } for _, v := range values { // TODO: Figure out if we should use Set here instead // nolint:gocritic w.Header().Add(k, v) } } // Make sure a content type always is returned in response if !hasContentType && resp.Status != http.StatusNoContent { w.Header().Set("Content-Type", "application/json") } proxyutil.SetProxyResponseHeaders(w.Header()) w.WriteHeader(resp.Status) } if _, err := w.Write(resp.Body); err != nil { hs.log.Error("Failed to write resource response", "err", err) } if flusher, ok := w.(http.Flusher); ok { flusher.Flush() } processedStreams++ } } func handleCallResourceError(err error, reqCtx *models.ReqContext) { if errors.Is(err, backendplugin.ErrPluginUnavailable) { reqCtx.JsonApiErr(503, "Plugin unavailable", err) return } if errors.Is(err, backendplugin.ErrMethodNotImplemented) { reqCtx.JsonApiErr(404, "Not found", err) return } reqCtx.JsonApiErr(500, "Failed to call resource", err) } // callResourceClientResponseStream is used for receiving resource call responses. type callResourceClientResponseStream interface { Recv() (*backend.CallResourceResponse, error) Close() error } type callResourceResponseStream struct { ctx context.Context stream chan *backend.CallResourceResponse closed bool } func newCallResourceResponseStream(ctx context.Context) *callResourceResponseStream { return &callResourceResponseStream{ ctx: ctx, stream: make(chan *backend.CallResourceResponse), } } func (s *callResourceResponseStream) Send(res *backend.CallResourceResponse) error { if s.closed { return errors.New("cannot send to a closed stream") } select { case <-s.ctx.Done(): return errors.New("cancelled") case s.stream <- res: return nil } } func (s *callResourceResponseStream) Recv() (*backend.CallResourceResponse, error) { select { case <-s.ctx.Done(): return nil, s.ctx.Err() case res, ok := <-s.stream: if !ok { return nil, io.EOF } return res, nil } } func (s *callResourceResponseStream) Close() error { if s.closed { return errors.New("cannot close a closed stream") } close(s.stream) s.closed = true return nil }
pkg/api/plugin_resource.go
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.00017588924674782902, 0.0001711442891974002, 0.00015981208707671613, 0.00017207312339451164, 0.000004133361017011339 ]
{ "id": 2, "code_window": [ " <div className={styles.items} role=\"tablist\">\n", " <SectionNavItem item={model.main} isSectionRoot />\n", " </div>\n", " </CustomScrollbar>\n", " </nav>\n", " <SectionNavToggle className={styles.collapseIcon} isExpanded={Boolean(isExpanded)} onClick={onToggleSectionNav} />\n", " </>\n", " );\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " <SectionNavToggle\n", " className={cx(styles.collapseIcon, {\n", " [styles.collapseIconExpanded]: isExpanded,\n", " })}\n", " isExpanded={Boolean(isExpanded)}\n", " onClick={onToggleSectionNav}\n", " />\n", " </div>\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "replace", "edit_start_line_idx": 35 }
import { css } from '@emotion/css'; import React from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { useStyles2 } from '@grafana/ui'; import { DimensionContext, ScalarDimensionConfig } from 'app/features/dimensions'; import { ScalarDimensionEditor } from 'app/features/dimensions/editors'; import { CanvasElementItem, CanvasElementProps, defaultBgColor } from '../element'; interface DroneFrontData { rollAngle?: number; } interface DroneFrontConfig { rollAngle?: ScalarDimensionConfig; } const DroneFrontDisplay = ({ data }: CanvasElementProps<DroneFrontConfig, DroneFrontData>) => { const styles = useStyles2(getStyles); const droneFrontTransformStyle = `rotate(${data?.rollAngle ? data.rollAngle : 0}deg)`; return ( <svg className={styles.droneFront} xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" viewBox="0 0 1300 290" style={{ transform: droneFrontTransformStyle, stroke: defaultBgColor }} > <g className="arms" stroke={defaultBgColor} strokeWidth="28px"> <line x1="510" x2="320" y1="100" y2="150" /> <line x1="510" x2="320" y1="190" y2="210" /> <line x1="790" x2="980" y1="190" y2="210" /> <line x1="790" x2="980" y1="100" y2="150" /> </g> <g className="body" stroke={defaultBgColor} strokeWidth="28px"> <path fill="none" d=" M 510 130 C 510 124 510 110 510 100 C 510 90 530 71 540 70 C 640 61 670 60 760 70 C 770 71 790 90 790 100 Q 790 120 790 130 L 790 130 Q 790 177 790 196 C 790 207 770 225 760 226 C 670 236 640 236 540 226 C 530 226 510 206 510 196 Q 510 177 510 130 Q 510 133 510 130 Z " /> <circle cx="650" cy="160" r="40" fill="none" /> </g> <g className="motors" stroke={defaultBgColor} strokeWidth="28px"> <path className="motor" fill="none" d=" M 320 60 L 250 60 L 250 230 L 260 290 L 310 290 L 320 230 L 320 60 Z " /> <path className="motor" fill="none" d=" M 1050 60 L 980 60 L 980 230 L 990 290 L 1040 290 L 1050 230 L 1050 60 Z " /> </g> <g className="propellers" fill={defaultBgColor}> <path className="prop" d=" M 270 60 L 300 60 L 300 20 Q 311 30 330 30 Q 349 30 570 10 L 300 10 Q 300 0 290 0 C 286 0 284 0 280 0 Q 270 0 270 10 L 0 10 Q 220 30 240 30 Q 260 30 270 20 L 270 60 Z " /> <path className="prop" d=" M 1000 60 L 1030 60 L 1030 20 Q 1041 30 1060 30 Q 1079 30 1300 10 L 1030 10 Q 1030 0 1020 0 C 1016 0 1014 0 1010 0 Q 1000 0 1000 10 L 730 10 Q 950 30 970 30 Q 990 30 1000 20 L 1000 60 Z " /> </g> </svg> ); }; export const droneFrontItem: CanvasElementItem<any, any> = { id: 'droneFront', name: 'Drone Front', description: 'Drone front', display: DroneFrontDisplay, defaultSize: { width: 100, height: 26, }, getNewOptions: (options) => ({ ...options, background: { color: { fixed: 'transparent', }, }, placement: { width: options?.placement?.width ?? 100, height: options?.placement?.height ?? 26, top: options?.placement?.top, left: options?.placement?.left, }, }), // Called when data changes prepareData: (ctx: DimensionContext, cfg: DroneFrontConfig) => { const data: DroneFrontData = { rollAngle: cfg?.rollAngle ? ctx.getScalar(cfg.rollAngle).value() : 0, }; return data; }, registerOptionsUI: (builder) => { const category = ['Drone Front']; builder.addCustomEditor({ category, id: 'rollAngle', path: 'config.rollAngle', name: 'Roll Angle', editor: ScalarDimensionEditor, }); }, }; const getStyles = (theme: GrafanaTheme2) => ({ droneFront: css` transition: transform 0.4s; `, });
public/app/features/canvas/elements/droneFront.tsx
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.0015025065513327718, 0.0002743623044807464, 0.0001673520018812269, 0.00017359131015837193, 0.0003545453946571797 ]
{ "id": 2, "code_window": [ " <div className={styles.items} role=\"tablist\">\n", " <SectionNavItem item={model.main} isSectionRoot />\n", " </div>\n", " </CustomScrollbar>\n", " </nav>\n", " <SectionNavToggle className={styles.collapseIcon} isExpanded={Boolean(isExpanded)} onClick={onToggleSectionNav} />\n", " </>\n", " );\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " <SectionNavToggle\n", " className={cx(styles.collapseIcon, {\n", " [styles.collapseIconExpanded]: isExpanded,\n", " })}\n", " isExpanded={Boolean(isExpanded)}\n", " onClick={onToggleSectionNav}\n", " />\n", " </div>\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "replace", "edit_start_line_idx": 35 }
//go:build ignore package main import ( "fmt" "os" "text/template" "github.com/grafana/grafana/pkg/services/publicdashboards/commands/generate_datasources" ) var tsDatasourcesTemplate = ` // Code generated by go generate; DO NOT EDIT. export const supportedDatasources = new Set<string>([ {{- range . }} '{{ printf "%s" . }}', {{- end }} ]) ` func main() { baseUrl := "https://grafana.com" slugs, err := generate_datasources.GetCompatibleDatasources(baseUrl) tsTemplate := template.Must(template.New("").Parse(tsDatasourcesTemplate)) // Generate supported datasources for Typescript tsFile, err := os.Create("./../../../public/app/features/dashboard/components/ShareModal/SharePublicDashboard/SupportedPubdashDatasources.ts") if err != nil { fmt.Println(err) } err = tsTemplate.Execute(tsFile, slugs) if err != nil { fmt.Println(err) } }
pkg/services/publicdashboards/commands/generate_datasources/main.go
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.001266484265215695, 0.0004478795453906059, 0.0001711271470412612, 0.00017695341375656426, 0.00047262944281101227 ]
{ "id": 3, "code_window": [ " return { isExpanded, onToggleSectionNav };\n", "}\n", "\n", "const getStyles = (theme: GrafanaTheme2) => {\n", " return {\n", " nav: css({\n", " display: 'flex',\n", " flexDirection: 'column',\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " navContainer: css({\n", " display: 'flex',\n", " flexDirection: 'column',\n", "\n", " [theme.breakpoints.up('md')]: {\n", " flexDirection: 'row',\n", " },\n", " }),\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "add", "edit_start_line_idx": 67 }
import { css } from '@emotion/css'; import classnames from 'classnames'; import React from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { IconButton, useTheme2 } from '@grafana/ui'; export interface Props { className?: string; isExpanded: boolean; onClick: () => void; } export const SectionNavToggle = ({ className, isExpanded, onClick }: Props) => { const theme = useTheme2(); const styles = getStyles(theme); return ( <IconButton tooltip={'Toggle section navigation'} aria-label={isExpanded ? 'Close section navigation' : 'Open section navigation'} name={isExpanded ? 'angle-left' : 'angle-right'} className={classnames(className, styles.icon)} size="xl" onClick={onClick} /> ); }; SectionNavToggle.displayName = 'SectionNavToggle'; const getStyles = (theme: GrafanaTheme2) => ({ icon: css({ backgroundColor: theme.colors.background.secondary, border: `1px solid ${theme.colors.border.weak}`, borderRadius: '50%', marginRight: 0, zIndex: 1, }), });
public/app/core/components/PageNew/SectionNavToggle.tsx
1
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.9991070628166199, 0.3773652911186218, 0.0001780718594091013, 0.006465492770075798, 0.4601125717163086 ]
{ "id": 3, "code_window": [ " return { isExpanded, onToggleSectionNav };\n", "}\n", "\n", "const getStyles = (theme: GrafanaTheme2) => {\n", " return {\n", " nav: css({\n", " display: 'flex',\n", " flexDirection: 'column',\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " navContainer: css({\n", " display: 'flex',\n", " flexDirection: 'column',\n", "\n", " [theme.breakpoints.up('md')]: {\n", " flexDirection: 'row',\n", " },\n", " }),\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "add", "edit_start_line_idx": 67 }
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" viewBox="0 0 24 24"><path d="M16.9,9.2c-0.4-0.4-1-0.4-1.4,0L12,12.7L8.5,9.2c-0.4-0.4-1-0.4-1.4,0s-0.4,1,0,1.4l4.2,4.2c0.2,0.2,0.4,0.3,0.7,0.3c0.3,0,0.5-0.1,0.7-0.3l4.2-4.2C17.3,10.2,17.3,9.6,16.9,9.2z"/></svg>
public/img/icons/solid/angle-down.svg
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.000171887906617485, 0.000171887906617485, 0.000171887906617485, 0.000171887906617485, 0 ]
{ "id": 3, "code_window": [ " return { isExpanded, onToggleSectionNav };\n", "}\n", "\n", "const getStyles = (theme: GrafanaTheme2) => {\n", " return {\n", " nav: css({\n", " display: 'flex',\n", " flexDirection: 'column',\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " navContainer: css({\n", " display: 'flex',\n", " flexDirection: 'column',\n", "\n", " [theme.breakpoints.up('md')]: {\n", " flexDirection: 'row',\n", " },\n", " }),\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "add", "edit_start_line_idx": 67 }
import { DataQuery } from '@grafana/data/src'; export const defaultQuery: DataQuery = { refId: 'A', datasource: { type: 'datasource', uid: 'grafana', }, queryType: 'measurements', }; export const implementationComingSoonAlert = () => { alert('Implementation coming soon!'); };
public/app/features/query-library/utils.ts
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.0001756232959451154, 0.00017517697415314615, 0.00017473066691309214, 0.00017517697415314615, 4.4631451601162553e-7 ]
{ "id": 3, "code_window": [ " return { isExpanded, onToggleSectionNav };\n", "}\n", "\n", "const getStyles = (theme: GrafanaTheme2) => {\n", " return {\n", " nav: css({\n", " display: 'flex',\n", " flexDirection: 'column',\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " navContainer: css({\n", " display: 'flex',\n", " flexDirection: 'column',\n", "\n", " [theme.breakpoints.up('md')]: {\n", " flexDirection: 'row',\n", " },\n", " }),\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "add", "edit_start_line_idx": 67 }
import { applyFieldOverrides, ArrayDataFrame, getDefaultTimeRange, getProcessedDataFrames, LoadingState, PanelData, } from '@grafana/data'; import { config } from 'app/core/config'; import { SnapshotWorker } from '../../query/state/DashboardQueryRunner/SnapshotWorker'; import { getTimeSrv } from '../services/TimeSrv'; import { DashboardModel, PanelModel } from '../state'; import { applyPanelTimeOverrides } from './panel'; export function loadSnapshotData(panel: PanelModel, dashboard: DashboardModel): PanelData { const data = getProcessedDataFrames(panel.snapshotData); const worker = new SnapshotWorker(); const options = { dashboard, range: getDefaultTimeRange() }; const annotationEvents = worker.canWork(options) ? worker.getAnnotationsInSnapshot(dashboard, panel.id) : []; const annotations = [new ArrayDataFrame(annotationEvents)]; const timeData = applyPanelTimeOverrides(panel, getTimeSrv().timeRange()); return { timeRange: timeData.timeRange, state: LoadingState.Done, series: applyFieldOverrides({ data, fieldConfig: { defaults: {}, overrides: [], }, replaceVariables: panel.replaceVariables, fieldConfigRegistry: panel.plugin!.fieldConfigRegistry, theme: config.theme2, timeZone: dashboard.getTimezone(), }), annotations, }; }
public/app/features/dashboard/utils/loadSnapshotData.ts
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.00017966411542147398, 0.00017296674195677042, 0.00016718755068723112, 0.00017382368969265372, 0.000004332024218456354 ]
{ "id": 4, "code_window": [ " padding: theme.spacing(4.5, 1, 2, 2),\n", " },\n", " }),\n", " collapseIcon: css({\n", " border: `1px solid ${theme.colors.border.weak}`,\n", " left: '50%',\n", " transform: 'translate(-50%, 50%) rotate(90deg)',\n", " top: theme.spacing(0),\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ " alignSelf: 'center',\n", " margin: theme.spacing(1, 0),\n", " position: 'relative',\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "replace", "edit_start_line_idx": 98 }
import { css } from '@emotion/css'; import classnames from 'classnames'; import React from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { IconButton, useTheme2 } from '@grafana/ui'; export interface Props { className?: string; isExpanded: boolean; onClick: () => void; } export const SectionNavToggle = ({ className, isExpanded, onClick }: Props) => { const theme = useTheme2(); const styles = getStyles(theme); return ( <IconButton tooltip={'Toggle section navigation'} aria-label={isExpanded ? 'Close section navigation' : 'Open section navigation'} name={isExpanded ? 'angle-left' : 'angle-right'} className={classnames(className, styles.icon)} size="xl" onClick={onClick} /> ); }; SectionNavToggle.displayName = 'SectionNavToggle'; const getStyles = (theme: GrafanaTheme2) => ({ icon: css({ backgroundColor: theme.colors.background.secondary, border: `1px solid ${theme.colors.border.weak}`, borderRadius: '50%', marginRight: 0, zIndex: 1, }), });
public/app/core/components/PageNew/SectionNavToggle.tsx
1
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.008960508741438389, 0.0031618312932550907, 0.00016689814219716936, 0.00017882698739413172, 0.003754605073481798 ]
{ "id": 4, "code_window": [ " padding: theme.spacing(4.5, 1, 2, 2),\n", " },\n", " }),\n", " collapseIcon: css({\n", " border: `1px solid ${theme.colors.border.weak}`,\n", " left: '50%',\n", " transform: 'translate(-50%, 50%) rotate(90deg)',\n", " top: theme.spacing(0),\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ " alignSelf: 'center',\n", " margin: theme.spacing(1, 0),\n", " position: 'relative',\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "replace", "edit_start_line_idx": 98 }
package quotatest import ( "context" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/quota" ) type FakeQuotaService struct { reached bool err error } func New(reached bool, err error) *FakeQuotaService { return &FakeQuotaService{reached, err} } func (f *FakeQuotaService) GetQuotasByScope(ctx context.Context, scope quota.Scope, id int64) ([]quota.QuotaDTO, error) { return []quota.QuotaDTO{}, nil } func (f *FakeQuotaService) Update(ctx context.Context, cmd *quota.UpdateQuotaCmd) error { return nil } func (f *FakeQuotaService) QuotaReached(c *models.ReqContext, target quota.TargetSrv) (bool, error) { return f.reached, f.err } func (f *FakeQuotaService) CheckQuotaReached(c context.Context, target quota.TargetSrv, params *quota.ScopeParameters) (bool, error) { return f.reached, f.err } func (f *FakeQuotaService) DeleteQuotaForUser(c context.Context, userID int64) error { return f.err } func (f *FakeQuotaService) RegisterQuotaReporter(e *quota.NewUsageReporter) error { return f.err } type FakeQuotaStore struct { ExpectedError error } func (f *FakeQuotaStore) DeleteByUser(ctx quota.Context, userID int64) error { return f.ExpectedError } func (f *FakeQuotaStore) Get(ctx quota.Context, scopeParams *quota.ScopeParameters) (*quota.Map, error) { return nil, f.ExpectedError } func (f *FakeQuotaStore) Update(ctx quota.Context, cmd *quota.UpdateQuotaCmd) error { return f.ExpectedError }
pkg/services/quota/quotatest/fake.go
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.0004233609652146697, 0.0002105996827594936, 0.00016510447312612087, 0.00016765441978350282, 0.00009517904982203618 ]
{ "id": 4, "code_window": [ " padding: theme.spacing(4.5, 1, 2, 2),\n", " },\n", " }),\n", " collapseIcon: css({\n", " border: `1px solid ${theme.colors.border.weak}`,\n", " left: '50%',\n", " transform: 'translate(-50%, 50%) rotate(90deg)',\n", " top: theme.spacing(0),\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ " alignSelf: 'center',\n", " margin: theme.spacing(1, 0),\n", " position: 'relative',\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "replace", "edit_start_line_idx": 98 }
module.exports = { extends: ['stylelint-config-sass-guidelines', 'stylelint-config-prettier'], ignoreFiles: ['**/node_modules/**/*.scss'], rules: { 'at-rule-no-vendor-prefix': null, 'color-hex-case': null, 'color-hex-length': null, 'color-named': null, 'declaration-block-no-duplicate-properties': [ true, { ignore: 'consecutive-duplicates-with-different-values', ignoreProperties: ['font-size', 'word-break'], }, ], // Disable equivalent "borderZero" sass-lint rule 'declaration-property-value-disallowed-list': { border: [], 'border-bottom': [], 'border-left': [], 'border-right': [], 'border-top': [], }, 'function-comma-space-after': null, 'function-url-quotes': null, 'length-zero-no-unit': null, 'max-nesting-depth': null, 'number-no-trailing-zeros': null, 'order/order': null, 'order/properties-alphabetical-order': null, 'property-no-vendor-prefix': null, 'rule-empty-line-before': null, 'scss/at-function-pattern': null, 'scss/at-mixin-pattern': null, 'scss/dollar-variable-pattern': null, 'scss/at-extend-no-missing-placeholder': null, 'selector-class-pattern': null, 'selector-max-compound-selectors': null, 'selector-max-id': null, 'selector-no-qualifying-type': null, 'selector-pseudo-element-colon-notation': null, 'shorthand-property-no-redundant-values': null, 'value-no-vendor-prefix': null, }, };
stylelint.config.js
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.00017512230260763317, 0.0001683622394921258, 0.00016464795044157654, 0.00016668630996719003, 0.0000037426100334414514 ]
{ "id": 4, "code_window": [ " padding: theme.spacing(4.5, 1, 2, 2),\n", " },\n", " }),\n", " collapseIcon: css({\n", " border: `1px solid ${theme.colors.border.weak}`,\n", " left: '50%',\n", " transform: 'translate(-50%, 50%) rotate(90deg)',\n", " top: theme.spacing(0),\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ " alignSelf: 'center',\n", " margin: theme.spacing(1, 0),\n", " position: 'relative',\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "replace", "edit_start_line_idx": 98 }
import React from 'react'; import { DataFrame, FALLBACK_COLOR, Field, getDisplayProcessor, getFieldDisplayName, TimeZone, LinkModel, } from '@grafana/data'; import { MenuItem, SeriesTableRow, useTheme2 } from '@grafana/ui'; import { findNextStateIndex, fmtDuration } from './utils'; interface StateTimelineTooltipProps { data: DataFrame[]; alignedData: DataFrame; seriesIdx: number; datapointIdx: number; timeZone: TimeZone; onAnnotationAdd?: () => void; } export const StateTimelineTooltip: React.FC<StateTimelineTooltipProps> = ({ data, alignedData, seriesIdx, datapointIdx, timeZone, onAnnotationAdd, }) => { const theme = useTheme2(); if (!data || datapointIdx == null) { return null; } const field = alignedData.fields[seriesIdx!]; const links: Array<LinkModel<Field>> = []; const linkLookup = new Set<string>(); if (field.getLinks) { const v = field.values.get(datapointIdx); const disp = field.display ? field.display(v) : { text: `${v}`, numeric: +v }; field.getLinks({ calculatedValue: disp, valueRowIndex: datapointIdx }).forEach((link) => { const key = `${link.title}/${link.href}`; if (!linkLookup.has(key)) { links.push(link); linkLookup.add(key); } }); } const xField = alignedData.fields[0]; const xFieldFmt = xField.display || getDisplayProcessor({ field: xField, timeZone, theme }); const dataFrameFieldIndex = field.state?.origin; const fieldFmt = field.display || getDisplayProcessor({ field, timeZone, theme }); const value = field.values.get(datapointIdx!); const display = fieldFmt(value); const fieldDisplayName = dataFrameFieldIndex ? getFieldDisplayName( data[dataFrameFieldIndex.frameIndex].fields[dataFrameFieldIndex.fieldIndex], data[dataFrameFieldIndex.frameIndex], data ) : null; const nextStateIdx = findNextStateIndex(field, datapointIdx!); let nextStateTs; if (nextStateIdx) { nextStateTs = xField.values.get(nextStateIdx!); } const stateTs = xField.values.get(datapointIdx!); let toFragment = null; let durationFragment = null; if (nextStateTs) { const duration = nextStateTs && fmtDuration(nextStateTs - stateTs); durationFragment = ( <> <br /> <strong>Duration:</strong> {duration} </> ); toFragment = ( <> {' to'} <strong>{xFieldFmt(xField.values.get(nextStateIdx!)).text}</strong> </> ); } return ( <div> <div style={{ fontSize: theme.typography.bodySmall.fontSize }}> {fieldDisplayName} <br /> <SeriesTableRow label={display.text} color={display.color || FALLBACK_COLOR} isActive /> From <strong>{xFieldFmt(xField.values.get(datapointIdx!)).text}</strong> {toFragment} {durationFragment} </div> <div style={{ margin: theme.spacing(1, -1, -1, -1), borderTop: `1px solid ${theme.colors.border.weak}`, }} > {onAnnotationAdd && <MenuItem label={'Add annotation'} icon={'comment-alt'} onClick={onAnnotationAdd} />} {links.length > 0 && links.map((link, i) => ( <MenuItem key={i} icon={'external-link-alt'} target={link.target} label={link.title} url={link.href} onClick={link.onClick} /> ))} </div> </div> ); }; StateTimelineTooltip.displayName = 'StateTimelineTooltip';
public/app/plugins/panel/state-timeline/StateTimelineTooltip.tsx
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.010467905551195145, 0.0010695640230551362, 0.00016757266712374985, 0.00017100709374062717, 0.002658254001289606 ]
{ "id": 5, "code_window": [ " top: theme.spacing(0),\n", "\n" ], "labels": [ "add", "keep" ], "after_edit": [ " transform: 'rotate(90deg)',\n", " transition: theme.transitions.create('opacity'),\n", "\n", " [theme.breakpoints.up('md')]: {\n", " alignSelf: 'flex-start',\n", " left: 0,\n", " margin: theme.spacing(0, 0, 0, 1),\n", " top: theme.spacing(2),\n", " transform: 'none',\n", " },\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "add", "edit_start_line_idx": 102 }
import { css, cx } from '@emotion/css'; import React, { useEffect, useState } from 'react'; import { useLocalStorage } from 'react-use'; import { NavModel, GrafanaTheme2 } from '@grafana/data'; import { useStyles2, CustomScrollbar, useTheme2 } from '@grafana/ui'; import { SectionNavItem } from './SectionNavItem'; import { SectionNavToggle } from './SectionNavToggle'; export interface Props { model: NavModel; } export function SectionNav({ model }: Props) { const styles = useStyles2(getStyles); const { isExpanded, onToggleSectionNav } = useSectionNavState(); if (!Boolean(model.main?.children?.length)) { return null; } return ( <> <nav className={cx(styles.nav, { [styles.navExpanded]: isExpanded, })} > <CustomScrollbar showScrollIndicators> <div className={styles.items} role="tablist"> <SectionNavItem item={model.main} isSectionRoot /> </div> </CustomScrollbar> </nav> <SectionNavToggle className={styles.collapseIcon} isExpanded={Boolean(isExpanded)} onClick={onToggleSectionNav} /> </> ); } function useSectionNavState() { const theme = useTheme2(); const isSmallScreen = window.matchMedia(`(max-width: ${theme.breakpoints.values.lg}px)`).matches; const [navExpandedPreference, setNavExpandedPreference] = useLocalStorage<boolean>( 'grafana.sectionNav.expanded', !isSmallScreen ); const [isExpanded, setIsExpanded] = useState(!isSmallScreen && navExpandedPreference); useEffect(() => { const mediaQuery = window.matchMedia(`(max-width: ${theme.breakpoints.values.lg}px)`); const onMediaQueryChange = (e: MediaQueryListEvent) => setIsExpanded(e.matches ? false : navExpandedPreference); mediaQuery.addEventListener('change', onMediaQueryChange); return () => mediaQuery.removeEventListener('change', onMediaQueryChange); }, [navExpandedPreference, theme.breakpoints.values.lg]); const onToggleSectionNav = () => { setNavExpandedPreference(!isExpanded); setIsExpanded(!isExpanded); }; return { isExpanded, onToggleSectionNav }; } const getStyles = (theme: GrafanaTheme2) => { return { nav: css({ display: 'flex', flexDirection: 'column', background: theme.colors.background.canvas, flexShrink: 0, transition: theme.transitions.create(['width', 'max-height']), maxHeight: 0, visibility: 'hidden', [theme.breakpoints.up('md')]: { width: 0, maxHeight: 'unset', }, }), navExpanded: css({ maxHeight: '50vh', visibility: 'visible', [theme.breakpoints.up('md')]: { width: '250px', maxHeight: 'unset', }, }), items: css({ display: 'flex', flexDirection: 'column', padding: theme.spacing(2, 1, 2, 2), minWidth: '250px', [theme.breakpoints.up('md')]: { padding: theme.spacing(4.5, 1, 2, 2), }, }), collapseIcon: css({ border: `1px solid ${theme.colors.border.weak}`, left: '50%', transform: 'translate(-50%, 50%) rotate(90deg)', top: theme.spacing(0), [theme.breakpoints.up('md')]: { transform: 'translateX(50%)', top: theme.spacing(8), left: theme.spacing(1), right: theme.spacing(-1), }, }), }; };
public/app/core/components/PageNew/SectionNav.tsx
1
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.998202919960022, 0.24405086040496826, 0.00016659589891787618, 0.0024409862235188484, 0.3901759684085846 ]
{ "id": 5, "code_window": [ " top: theme.spacing(0),\n", "\n" ], "labels": [ "add", "keep" ], "after_edit": [ " transform: 'rotate(90deg)',\n", " transition: theme.transitions.create('opacity'),\n", "\n", " [theme.breakpoints.up('md')]: {\n", " alignSelf: 'flex-start',\n", " left: 0,\n", " margin: theme.spacing(0, 0, 0, 1),\n", " top: theme.spacing(2),\n", " transform: 'none',\n", " },\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "add", "edit_start_line_idx": 102 }
{ "RefId": "A", "RangeQuery": true, "Start": 1641889530, "End": 1641889532, "Step": 1 }
pkg/tsdb/prometheus/testdata/range_nan.query.json
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.00017499126261100173, 0.00017499126261100173, 0.00017499126261100173, 0.00017499126261100173, 0 ]
{ "id": 5, "code_window": [ " top: theme.spacing(0),\n", "\n" ], "labels": [ "add", "keep" ], "after_edit": [ " transform: 'rotate(90deg)',\n", " transition: theme.transitions.create('opacity'),\n", "\n", " [theme.breakpoints.up('md')]: {\n", " alignSelf: 'flex-start',\n", " left: 0,\n", " margin: theme.spacing(0, 0, 0, 1),\n", " top: theme.spacing(2),\n", " transform: 'none',\n", " },\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "add", "edit_start_line_idx": 102 }
export { DashboardExporter } from './DashboardExporter';
public/app/features/dashboard/components/DashExportModal/index.ts
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.000190188322449103, 0.000190188322449103, 0.000190188322449103, 0.000190188322449103, 0 ]
{ "id": 5, "code_window": [ " top: theme.spacing(0),\n", "\n" ], "labels": [ "add", "keep" ], "after_edit": [ " transform: 'rotate(90deg)',\n", " transition: theme.transitions.create('opacity'),\n", "\n", " [theme.breakpoints.up('md')]: {\n", " alignSelf: 'flex-start',\n", " left: 0,\n", " margin: theme.spacing(0, 0, 0, 1),\n", " top: theme.spacing(2),\n", " transform: 'none',\n", " },\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "add", "edit_start_line_idx": 102 }
import { css, cx } from '@emotion/css'; import React, { HTMLProps, ReactNode } from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { useStyles2 } from '../../themes'; export interface Props extends Omit<HTMLProps<HTMLDivElement>, 'css'> { children: ReactNode | ReactNode[]; } export const InlineFieldRow = ({ children, className, ...htmlProps }: Props) => { const styles = useStyles2(getStyles); return ( <div className={cx(styles.container, className)} {...htmlProps}> {children} </div> ); }; const getStyles = (theme: GrafanaTheme2) => { return { container: css` label: InlineFieldRow; display: flex; flex-direction: row; flex-wrap: wrap; align-content: flex-start; row-gap: ${theme.spacing(0.5)}; `, }; };
packages/grafana-ui/src/components/Forms/InlineFieldRow.tsx
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.1365031599998474, 0.03425481915473938, 0.00016888575919438154, 0.00017360912170261145, 0.0590331107378006 ]
{ "id": 6, "code_window": [ "\n", " [theme.breakpoints.up('md')]: {\n" ], "labels": [ "add", "keep" ], "after_edit": [ " 'div:hover > &, &:focus': {\n", " opacity: 1,\n", " },\n", " }),\n", " collapseIconExpanded: css({\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "add", "edit_start_line_idx": 103 }
import { css, cx } from '@emotion/css'; import React, { useEffect, useState } from 'react'; import { useLocalStorage } from 'react-use'; import { NavModel, GrafanaTheme2 } from '@grafana/data'; import { useStyles2, CustomScrollbar, useTheme2 } from '@grafana/ui'; import { SectionNavItem } from './SectionNavItem'; import { SectionNavToggle } from './SectionNavToggle'; export interface Props { model: NavModel; } export function SectionNav({ model }: Props) { const styles = useStyles2(getStyles); const { isExpanded, onToggleSectionNav } = useSectionNavState(); if (!Boolean(model.main?.children?.length)) { return null; } return ( <> <nav className={cx(styles.nav, { [styles.navExpanded]: isExpanded, })} > <CustomScrollbar showScrollIndicators> <div className={styles.items} role="tablist"> <SectionNavItem item={model.main} isSectionRoot /> </div> </CustomScrollbar> </nav> <SectionNavToggle className={styles.collapseIcon} isExpanded={Boolean(isExpanded)} onClick={onToggleSectionNav} /> </> ); } function useSectionNavState() { const theme = useTheme2(); const isSmallScreen = window.matchMedia(`(max-width: ${theme.breakpoints.values.lg}px)`).matches; const [navExpandedPreference, setNavExpandedPreference] = useLocalStorage<boolean>( 'grafana.sectionNav.expanded', !isSmallScreen ); const [isExpanded, setIsExpanded] = useState(!isSmallScreen && navExpandedPreference); useEffect(() => { const mediaQuery = window.matchMedia(`(max-width: ${theme.breakpoints.values.lg}px)`); const onMediaQueryChange = (e: MediaQueryListEvent) => setIsExpanded(e.matches ? false : navExpandedPreference); mediaQuery.addEventListener('change', onMediaQueryChange); return () => mediaQuery.removeEventListener('change', onMediaQueryChange); }, [navExpandedPreference, theme.breakpoints.values.lg]); const onToggleSectionNav = () => { setNavExpandedPreference(!isExpanded); setIsExpanded(!isExpanded); }; return { isExpanded, onToggleSectionNav }; } const getStyles = (theme: GrafanaTheme2) => { return { nav: css({ display: 'flex', flexDirection: 'column', background: theme.colors.background.canvas, flexShrink: 0, transition: theme.transitions.create(['width', 'max-height']), maxHeight: 0, visibility: 'hidden', [theme.breakpoints.up('md')]: { width: 0, maxHeight: 'unset', }, }), navExpanded: css({ maxHeight: '50vh', visibility: 'visible', [theme.breakpoints.up('md')]: { width: '250px', maxHeight: 'unset', }, }), items: css({ display: 'flex', flexDirection: 'column', padding: theme.spacing(2, 1, 2, 2), minWidth: '250px', [theme.breakpoints.up('md')]: { padding: theme.spacing(4.5, 1, 2, 2), }, }), collapseIcon: css({ border: `1px solid ${theme.colors.border.weak}`, left: '50%', transform: 'translate(-50%, 50%) rotate(90deg)', top: theme.spacing(0), [theme.breakpoints.up('md')]: { transform: 'translateX(50%)', top: theme.spacing(8), left: theme.spacing(1), right: theme.spacing(-1), }, }), }; };
public/app/core/components/PageNew/SectionNav.tsx
1
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.9882779717445374, 0.409393310546875, 0.0001686986070126295, 0.0028953112196177244, 0.48329609632492065 ]
{ "id": 6, "code_window": [ "\n", " [theme.breakpoints.up('md')]: {\n" ], "labels": [ "add", "keep" ], "after_edit": [ " 'div:hover > &, &:focus': {\n", " opacity: 1,\n", " },\n", " }),\n", " collapseIconExpanded: css({\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "add", "edit_start_line_idx": 103 }
--- aliases: - ../live/ - ../live/configure-grafana-live/ - ../live/live-channel/ - ../live/live-feature-overview/ - ../live/live-ha-setup/ - ../live/set-up-grafana-live/ description: Grafana Live is a real-time messaging engine that pushes event data to a frontend when an event occurs. menuTitle: Set up Grafana Live title: Set up Grafana Live weight: 1100 --- # Set up Grafana Live Grafana Live is a real-time messaging engine introduced in Grafana v8.0. With Grafana Live, you can push event data to a frontend as soon as an event occurs. This could be notifications about dashboard changes, new frames for rendered data, and so on. Live features can help eliminate a page reload or polling in many places, it can stream Internet of things (IoT) sensors or any other real-time data to panels. > **Note:** By `real-time`, we indicate a soft real-time. Due to network latencies, garbage collection cycles, and so on, the delay of a delivered message can be up to several hundred milliseconds or higher. ## Concepts Grafana Live sends data to clients over persistent WebSocket connection. Grafana frontend subscribes on channels to receive data which was published into that channel – in other words PUB/SUB mechanics is used. All subscriptions on a page multiplexed inside a single WebSocket connection. There are some rules regarding Live channel names – see [Grafana Live channel]({{< relref "#grafana-live-channel" >}}). Handling persistent connections like WebSocket in scale may require operating system and infrastructure tuning. That's why by default Grafana Live supports 100 simultaneous connections max. For more details on how to tune this limit, refer to [Live configuration section]({{< relref "#configure-grafana-live" >}}). ## Features Having a way to send data to clients in real-time opens a road for new ways of data interaction and visualization. Below we describe Grafana Live features supported at the moment. ### Dashboard change notifications As soon as there is a change to the dashboard layout, it is automatically reflected on other devices connected to Grafana Live. ### Data streaming from plugins With Grafana Live, backend data source plugins can stream updates to frontend panels. For data source plugin channels, Grafana uses `ds` scope. Namespace in the case of data source channels is a data source unique ID (UID) which is issued by Grafana at the moment of data source creation. The path is a custom string that plugin authors free to choose themselves (just make sure it consists of allowed symbols). For example, a data source channel looks like this: `ds/<DATASOURCE_UID>/<CUSTOM_PATH>`. Refer to the tutorial about [building a streaming data source backend plugin](https://grafana.com/tutorials/build-a-streaming-data-source-plugin/) for more details. The basic streaming example included in Grafana core streams frames with some generated data to a panel. To look at it create a new panel and point it to the `-- Grafana --` data source. Next, choose `Live Measurements` and select the `plugin/testdata/random-20Hz-stream` channel. ### Data streaming from Telegraf A new API endpoint `/api/live/push/:streamId` allows accepting metrics data in Influx format from Telegraf. These metrics are transformed into Grafana data frames and published to channels. Refer to the tutorial about [streaming metrics from Telegraf to Grafana](https://grafana.com/tutorials/stream-metrics-from-telegraf-to-grafana/) for more information. ## Grafana Live channel Grafana Live is a PUB/SUB server, clients subscribe to channels to receive real-time updates published to those channels. ### Channel structure Channel is a string identifier. In Grafana channel consists of 3 parts delimited by `/`: - Scope - Namespace - Path For example, the channel `grafana/dashboard/xyz` has the scope `grafana`, namespace `dashboard`, and path `xyz`. Scope, namespace and path can only have ASCII alphanumeric symbols (A-Z, a-z, 0-9), `_` (underscore) and `-` (dash) at the moment. The path part can additionally have `/`, `.` and `=` symbols. The meaning of scope, namespace and path is context-specific. The maximum length of a channel is 160 symbols. Scope determines the purpose of a channel in Grafana. For example, for data source plugin channels Grafana uses `ds` scope. For built-in features like dashboard edit notifications Grafana uses `grafana` scope. Namespace has a different meaning depending on scope. For example, for `grafana` scope this could be a name of built-in real-time feature like `dashboard` (i.e. dashboards events). The path, which is the final part of a channel, usually contains the identifier of some concrete resource such as the ID of a dashboard that a user is currently looking at. But a path can be anything. Channels are lightweight and ephemeral - they are created automatically on user subscription and removed as soon as last user left a channel. ### Data format All data travelling over Live channels must be JSON-encoded. ## Configure Grafana Live Grafana Live is enabled by default. In Grafana v8.0, it has a strict default for a maximum number of connections per Grafana server instance. ### Max number of connections Grafana Live uses persistent connections (WebSocket at the moment) to deliver real-time updates to clients. WebSocket is a persistent connection that starts with an HTTP Upgrade request (using the same HTTP port as the rest of Grafana) and then switches to a TCP mode where WebSocket frames can travel in both directions between a client and a server. Each logged-in user opens a WebSocket connection – one per browser tab. The number of maximum WebSocket connections users can establish with Grafana is limited to 100 by default. See [max_connections]({{< relref "configure-grafana/#max_connections" >}}) option. In case you want to increase this limit, ensure that your server and infrastructure allow handling more connections. The following sections discuss several common problems which could happen when managing persistent connections, in particular WebSocket connections. ### Request origin check To avoid hijacking of WebSocket connection Grafana Live checks the Origin request header sent by a client in an HTTP Upgrade request. Requests without Origin header pass through without any origin check. By default, Live accepts connections with Origin header that matches configured [root_url]({{< relref "configure-grafana/#root_url" >}}) (which is a public Grafana URL). It is possible to provide a list of additional origin patterns to allow WebSocket connections from. This can be achieved using the [allowed_origins]({{< relref "configure-grafana/#allowed_origins" >}}) option of Grafana Live configuration. #### Resource usage Each persistent connection costs some memory on a server. Typically, this should be about 50 KB per connection at this moment. Thus a server with 1 GB RAM is expected to handle about 20k connections max. Each active connection consumes additional CPU resources since the client and server send PING/PONG frames to each other to maintain a connection. Using the streaming functionality results in additional CPU usage. The exact CPU resource utilization can be hard to estimate as it heavily depends on the Grafana Live usage pattern. #### Open file limit Each WebSocket connection costs a file descriptor on a server machine where Grafana runs. Most operating systems have a quite low default limit for the maximum number of descriptors that process can open. To look at the current limit on Unix run: ``` ulimit -n ``` On a Linux system, you can also check out the current limits for a running process with: ``` cat /proc/<PROCESS_PID>/limits ``` The open files limit shows approximately how many user connections your server can currently handle. To increase this limit, refer to [these instructions](https://docs.riak.com/riak/kv/2.2.3/using/performance/open-files-limit.1.html)for popular operating systems. #### Ephemeral port exhaustion Ephemeral port exhaustion problem can happen between your load balancer (or reverse proxy) software and Grafana server. For example, when you load balance requests/connections between different Grafana instances. If you connect directly to a single Grafana server instance, then you should not come across this issue. The problem arises because each TCP connection uniquely identified in the OS by the 4-part-tuple: ``` source ip | source port | destination ip | destination port ``` By default, on load balancer/server boundary you are limited to 65535 possible variants. But actually, due to some OS limits (for example on Unix available ports defined in `ip_local_port_range` sysctl parameter) and sockets in TIME_WAIT state, the number is even less. In order to eliminate a problem you can: - Increase the ephemeral port range by tuning `ip_local_port_range` kernel option. - Deploy more Grafana server instances to load balance across. - Deploy more load balancer instances. - Use virtual network interfaces. #### WebSocket and proxies Not all proxies can transparently proxy WebSocket connections by default. For example, if you are using Nginx before Grafana you need to configure WebSocket proxy like this: ``` http { map $http_upgrade $connection_upgrade { default upgrade; '' close; } upstream grafana { server 127.0.0.1:3000; } server { listen 8000; location / { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_set_header Host $http_host; proxy_pass http://grafana; } } } ``` See the [Nginx blog on their website](https://www.nginx.com/blog/websocket-nginx/) for more information. Also, refer to your load balancer/reverse proxy documentation to find out more information on dealing with WebSocket connections. Some corporate proxies can remove headers required to properly establish a WebSocket connection. In this case, you should tune intermediate proxies to not remove required headers. However, the better option is to use Grafana with TLS. Now WebSocket connection will inherit TLS and thus must be handled transparently by proxies. Proxies like Nginx and Envoy have default limits on maximum number of connections which can be established. Make sure you have a reasonable limit for max number of incoming and outgoing connections in your proxy configuration. ## Configure Grafana Live HA setup By default, Grafana Live uses in-memory data structures and in-memory PUB/SUB hub for handling subscriptions. In a high availability Grafana setup involving several Grafana server instances behind a load balancer, you can find the following limitations: - Built-in features like dashboard change notifications will only be broadcasted to users connected to the same Grafana server process instance. - Streaming from Telegraf will deliver data only to clients connected to the same instance which received Telegraf data, active stream cache is not shared between different Grafana instances. - A separate unidirectional stream between Grafana and backend data source may be opened on different Grafana servers for the same channel. To bypass these limitations, Grafana v8.1 has an experimental Live HA engine that requires Redis to work. ### Configure Redis Live engine When the Redis engine is configured, Grafana Live keeps its state in Redis and uses Redis PUB/SUB functionality to deliver messages to all subscribers throughout all Grafana server nodes. Here is an example configuration: ``` [live] ha_engine = redis ha_engine_address = 127.0.0.1:6379 ``` For additional information, refer to the [ha_engine]({{< relref "configure-grafana/#ha_engine" >}}) and [ha_engine_address]({{< relref "configure-grafana/#ha_engine_address" >}}) options. After running: - All built-in real-time notifications like dashboard changes are delivered to all Grafana server instances and broadcasted to all subscribers. - Streaming from Telegraf delivers messages to all subscribers. - A separate unidirectional stream between Grafana and backend data source opens on different Grafana servers. Publishing data to a channel delivers messages to instance subscribers, as a result, publications from different instances on different machines do not produce duplicate data on panels. At the moment we only support single Redis node. > **Note:** It's possible to use Redis Sentinel and Haproxy to achieve a highly available Redis setup. Redis nodes should be managed by [Redis Sentinel](https://redis.io/topics/sentinel) to achieve automatic failover. Haproxy configuration example: > > ``` > listen redis > server redis-01 127.0.0.1:6380 check port 6380 check inter 2s weight 1 inter 2s downinter 5s rise 10 fall 2 on-marked-down shutdown-sessions on-marked-up shutdown-backup-sessions > server redis-02 127.0.0.1:6381 check port 6381 check inter 2s weight 1 inter 2s downinter 5s rise 10 fall 2 backup > bind *:6379 > mode tcp > option tcpka > option tcplog > option tcp-check > tcp-check send PING\r\n > tcp-check expect string +PONG > tcp-check send info\ replication\r\n > tcp-check expect string role:master > tcp-check send QUIT\r\n > tcp-check expect string +OK > balance roundrobin > ``` > > Next, point Grafana Live to Haproxy address:port.
docs/sources/setup-grafana/set-up-grafana-live.md
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.00033995613921433687, 0.00018026804900728166, 0.00016397189756389707, 0.00016914329899009317, 0.00004080045982846059 ]
{ "id": 6, "code_window": [ "\n", " [theme.breakpoints.up('md')]: {\n" ], "labels": [ "add", "keep" ], "after_edit": [ " 'div:hover > &, &:focus': {\n", " opacity: 1,\n", " },\n", " }),\n", " collapseIconExpanded: css({\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "add", "edit_start_line_idx": 103 }
import { render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import React from 'react'; import { Provider } from 'react-redux'; import { AwsAuthType } from '@grafana/aws-sdk'; import { configureStore } from 'app/store/configureStore'; import { CloudWatchSettings, setupMockedDataSource } from '../__mocks__/CloudWatchDataSource'; import { CloudWatchDatasource } from '../datasource'; import { ConfigEditor, Props } from './ConfigEditor'; const datasource = new CloudWatchDatasource(CloudWatchSettings); const loadDataSourceMock = jest.fn(); jest.mock('app/features/plugins/datasource_srv', () => ({ getDatasourceSrv: () => ({ loadDatasource: loadDataSourceMock, }), })); jest.mock('./XrayLinkConfig', () => ({ XrayLinkConfig: () => <></>, })); const putMock = jest.fn(); const getMock = jest.fn(); jest.mock('@grafana/runtime', () => ({ ...jest.requireActual('@grafana/runtime'), getBackendSrv: () => ({ put: putMock, get: getMock, }), })); const props: Props = { options: { id: 1, uid: 'z', orgId: 1, typeLogoUrl: '', name: 'CloudWatch', access: 'proxy', url: '', database: '', type: 'cloudwatch', typeName: 'Cloudwatch', user: '', basicAuth: false, basicAuthUser: '', isDefault: true, readOnly: false, withCredentials: false, version: 2, secureJsonFields: { accessKey: false, secretKey: false, }, jsonData: { assumeRoleArn: '', externalId: '', database: '', customMetricsNamespaces: '', authType: AwsAuthType.Keys, defaultRegion: 'us-east-2', timeField: '@timestamp', }, secureJsonData: { secretKey: '', accessKey: '', }, }, onOptionsChange: jest.fn(), }; const setup = (optionOverrides?: Partial<Props['options']>) => { const store = configureStore(); const newProps = { ...props, options: { ...props.options, ...optionOverrides, }, }; render( <Provider store={store}> <ConfigEditor {...newProps} /> </Provider> ); }; describe('Render', () => { beforeEach(() => { (window as any).grafanaBootData = { settings: {}, }; jest.resetAllMocks(); putMock.mockImplementation(async () => ({ datasource: setupMockedDataSource().datasource })); getMock.mockImplementation(async () => ({ datasource: setupMockedDataSource().datasource })); loadDataSourceMock.mockResolvedValue(datasource); datasource.resources.getRegions = jest.fn().mockResolvedValue([ { label: 'ap-east-1', value: 'ap-east-1', }, ]); datasource.getActualRegion = jest.fn().mockReturnValue('ap-east-1'); datasource.getVariables = jest.fn().mockReturnValue([]); }); it('it should disable access key id field when the datasource has been previously configured', async () => { setup({ secureJsonFields: { secretKey: true, }, }); await waitFor(async () => expect(screen.getByPlaceholderText('Configured')).toBeDisabled()); }); it('should show credentials profile name field', async () => { setup({ jsonData: { authType: AwsAuthType.Credentials, }, }); await waitFor(async () => expect(screen.getByLabelText('Credentials Profile Name')).toBeInTheDocument()); }); it('should show access key and secret access key fields when the datasource has not been configured before', async () => { setup({ jsonData: { authType: AwsAuthType.Keys, }, }); await waitFor(async () => { expect(screen.getByLabelText('Access Key ID')).toBeInTheDocument(); expect(screen.getByLabelText('Secret Access Key')).toBeInTheDocument(); }); }); it('should show arn role field', async () => { setup({ jsonData: { authType: AwsAuthType.ARN, }, }); await waitFor(async () => expect(screen.getByLabelText('Assume Role ARN')).toBeInTheDocument()); }); it('should display log group selector field', async () => { setup(); await waitFor(async () => expect(await screen.getByText('Select Log Groups')).toBeInTheDocument()); }); it('should only display the first two default log groups and show all of them when clicking "Show all" button', async () => { setup({ version: 2, jsonData: { logGroups: [ { arn: 'arn:aws:logs:us-east-2:123456789012:log-group:logGroup-foo:*', name: 'logGroup-foo' }, { arn: 'arn:aws:logs:us-east-2:123456789012:log-group:logGroup-bar:*', name: 'logGroup-bar' }, { arn: 'arn:aws:logs:us-east-2:123456789012:log-group:logGroup-baz:*', name: 'logGroup-baz' }, ], }, }); await waitFor(async () => { expect(await screen.getByText('logGroup-foo')).toBeInTheDocument(); expect(await screen.getByText('logGroup-bar')).toBeInTheDocument(); expect(await screen.queryByText('logGroup-baz')).not.toBeInTheDocument(); await userEvent.click(screen.getByText('Show all')); expect(await screen.getByText('logGroup-baz')).toBeInTheDocument(); }); }); it('should load the data source if it was saved before', async () => { const SAVED_VERSION = 2; const newProps = { ...props, options: { ...props.options, version: SAVED_VERSION, }, }; render(<ConfigEditor {...newProps} />); await waitFor(async () => expect(loadDataSourceMock).toHaveBeenCalled()); }); it('should not load the data source if it wasnt saved before', async () => { const SAVED_VERSION = undefined; const newProps = { ...props, options: { ...props.options, version: SAVED_VERSION, }, }; render(<ConfigEditor {...newProps} />); await waitFor(async () => expect(loadDataSourceMock).not.toHaveBeenCalled()); }); it('should show error message if Select log group button is clicked when data source is never saved', async () => { const SAVED_VERSION = undefined; const newProps = { ...props, options: { ...props.options, version: SAVED_VERSION, }, }; render(<ConfigEditor {...newProps} />); await waitFor(() => expect(screen.getByText('Select Log Groups')).toBeInTheDocument()); await userEvent.click(screen.getByText('Select Log Groups')); await waitFor(() => expect(screen.getByText('You need to save the data source before adding log groups.')).toBeInTheDocument() ); }); it('should show error message if Select log group button is clicked when data source is saved before but have unsaved changes', async () => { const SAVED_VERSION = 3; const newProps = { ...props, options: { ...props.options, version: SAVED_VERSION, }, }; const { rerender } = render(<ConfigEditor {...newProps} />); await waitFor(() => expect(screen.getByText('Select Log Groups')).toBeInTheDocument()); const rerenderProps = { ...newProps, options: { ...newProps.options, jsonData: { ...newProps.options.jsonData, authType: AwsAuthType.Default, }, }, }; rerender(<ConfigEditor {...rerenderProps} />); await waitFor(() => expect(screen.getByText('AWS SDK Default')).toBeInTheDocument()); await userEvent.click(screen.getByText('Select Log Groups')); await waitFor(() => expect( screen.getByText( 'You have unsaved connection detail changes. You need to save the data source before adding log groups.' ) ).toBeInTheDocument() ); }); it('should open log group selector if Select log group button is clicked when data source has saved changes', async () => { const SAVED_VERSION = undefined; const newProps = { ...props, options: { ...props.options, version: SAVED_VERSION, }, }; const { rerender } = render(<ConfigEditor {...newProps} />); await waitFor(() => expect(screen.getByText('Select Log Groups')).toBeInTheDocument()); const rerenderProps = { ...newProps, options: { ...newProps.options, version: 1, }, }; rerender(<ConfigEditor {...rerenderProps} />); await userEvent.click(screen.getByText('Select Log Groups')); await waitFor(() => expect(screen.getByText('Log group name prefix')).toBeInTheDocument()); }); });
public/app/plugins/datasource/cloudwatch/components/ConfigEditor.test.tsx
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.00017991114873439074, 0.00017032083997037262, 0.00016674942162353545, 0.00016990560106933117, 0.0000026832706225832226 ]
{ "id": 6, "code_window": [ "\n", " [theme.breakpoints.up('md')]: {\n" ], "labels": [ "add", "keep" ], "after_edit": [ " 'div:hover > &, &:focus': {\n", " opacity: 1,\n", " },\n", " }),\n", " collapseIconExpanded: css({\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "add", "edit_start_line_idx": 103 }
import React, { useState } from 'react'; import { DataFrame } from '@grafana/data'; import { CodeEditor, Modal, ModalTabsHeader, TabContent } from '@grafana/ui'; import { DataHoverView } from 'app/plugins/panel/geomap/components/DataHoverView'; export interface Props { name: string; explain: {}; frame: DataFrame; row: number; } const tabs = [ { label: 'Score', value: 'score' }, { label: 'Fields', value: 'fields' }, { label: 'Allowed actions', value: 'allowed_actions' }, ]; export function ExplainScorePopup({ name, explain, frame, row }: Props) { const [isOpen, setOpen] = useState<boolean>(true); const [activeTab, setActiveTab] = useState('score'); const modalHeader = ( <ModalTabsHeader title={name} icon={'info'} tabs={tabs} activeTab={activeTab} onChangeTab={(t) => { setActiveTab(t.value); }} /> ); return ( <Modal title={modalHeader} isOpen={isOpen} onDismiss={() => setOpen(false)} closeOnBackdropClick closeOnEscape> <TabContent> {activeTab === tabs[0].value && ( <CodeEditor width="100%" height="70vh" language="json" showLineNumbers={false} showMiniMap={true} value={JSON.stringify(explain, null, 2)} readOnly={false} /> )} {activeTab === tabs[1].value && ( <div> <DataHoverView data={frame} rowIndex={row} /> </div> )} {activeTab === tabs[2].value && ( <CodeEditor width="100%" height="70vh" language="json" showLineNumbers={false} showMiniMap={false} value={(() => { const allowedActions = frame.fields.find((f) => f.name === 'allowed_actions')?.values?.get(row); const dsUids = frame.fields.find((f) => f.name === 'ds_uid')?.values?.get(row); return JSON.stringify({ dsUids: dsUids ?? [], allowedActions: allowedActions ?? [] }, null, 2); })()} readOnly={false} /> )} </TabContent> </Modal> ); }
public/app/features/search/page/components/ExplainScorePopup.tsx
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.0001875542220659554, 0.00017360558558721095, 0.00016826916544232517, 0.00017224694602191448, 0.0000060379470596672036 ]
{ "id": 7, "code_window": [ " [theme.breakpoints.up('md')]: {\n", " transform: 'translateX(50%)',\n", " top: theme.spacing(8),\n", " left: theme.spacing(1),\n", " right: theme.spacing(-1),\n", " },\n", " }),\n", " };\n", "};" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " opacity: 0,\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "replace", "edit_start_line_idx": 104 }
import { css, cx } from '@emotion/css'; import React, { useEffect, useState } from 'react'; import { useLocalStorage } from 'react-use'; import { NavModel, GrafanaTheme2 } from '@grafana/data'; import { useStyles2, CustomScrollbar, useTheme2 } from '@grafana/ui'; import { SectionNavItem } from './SectionNavItem'; import { SectionNavToggle } from './SectionNavToggle'; export interface Props { model: NavModel; } export function SectionNav({ model }: Props) { const styles = useStyles2(getStyles); const { isExpanded, onToggleSectionNav } = useSectionNavState(); if (!Boolean(model.main?.children?.length)) { return null; } return ( <> <nav className={cx(styles.nav, { [styles.navExpanded]: isExpanded, })} > <CustomScrollbar showScrollIndicators> <div className={styles.items} role="tablist"> <SectionNavItem item={model.main} isSectionRoot /> </div> </CustomScrollbar> </nav> <SectionNavToggle className={styles.collapseIcon} isExpanded={Boolean(isExpanded)} onClick={onToggleSectionNav} /> </> ); } function useSectionNavState() { const theme = useTheme2(); const isSmallScreen = window.matchMedia(`(max-width: ${theme.breakpoints.values.lg}px)`).matches; const [navExpandedPreference, setNavExpandedPreference] = useLocalStorage<boolean>( 'grafana.sectionNav.expanded', !isSmallScreen ); const [isExpanded, setIsExpanded] = useState(!isSmallScreen && navExpandedPreference); useEffect(() => { const mediaQuery = window.matchMedia(`(max-width: ${theme.breakpoints.values.lg}px)`); const onMediaQueryChange = (e: MediaQueryListEvent) => setIsExpanded(e.matches ? false : navExpandedPreference); mediaQuery.addEventListener('change', onMediaQueryChange); return () => mediaQuery.removeEventListener('change', onMediaQueryChange); }, [navExpandedPreference, theme.breakpoints.values.lg]); const onToggleSectionNav = () => { setNavExpandedPreference(!isExpanded); setIsExpanded(!isExpanded); }; return { isExpanded, onToggleSectionNav }; } const getStyles = (theme: GrafanaTheme2) => { return { nav: css({ display: 'flex', flexDirection: 'column', background: theme.colors.background.canvas, flexShrink: 0, transition: theme.transitions.create(['width', 'max-height']), maxHeight: 0, visibility: 'hidden', [theme.breakpoints.up('md')]: { width: 0, maxHeight: 'unset', }, }), navExpanded: css({ maxHeight: '50vh', visibility: 'visible', [theme.breakpoints.up('md')]: { width: '250px', maxHeight: 'unset', }, }), items: css({ display: 'flex', flexDirection: 'column', padding: theme.spacing(2, 1, 2, 2), minWidth: '250px', [theme.breakpoints.up('md')]: { padding: theme.spacing(4.5, 1, 2, 2), }, }), collapseIcon: css({ border: `1px solid ${theme.colors.border.weak}`, left: '50%', transform: 'translate(-50%, 50%) rotate(90deg)', top: theme.spacing(0), [theme.breakpoints.up('md')]: { transform: 'translateX(50%)', top: theme.spacing(8), left: theme.spacing(1), right: theme.spacing(-1), }, }), }; };
public/app/core/components/PageNew/SectionNav.tsx
1
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.992056667804718, 0.08761101216077805, 0.00016830640379339457, 0.0020369584672152996, 0.2728334069252014 ]
{ "id": 7, "code_window": [ " [theme.breakpoints.up('md')]: {\n", " transform: 'translateX(50%)',\n", " top: theme.spacing(8),\n", " left: theme.spacing(1),\n", " right: theme.spacing(-1),\n", " },\n", " }),\n", " };\n", "};" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " opacity: 0,\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "replace", "edit_start_line_idx": 104 }
<svg xmlns="http://www.w3.org/2000/svg" data-name="Layer 1" viewBox="0 0 24 24"><path d="M13.23047,2.00342A7.36652,7.36652,0,0,0,7.77734,4.11719,7.44119,7.44119,0,0,0,5.5,9.46533L3.65625,12.46289a.995.995,0,0,0-.15625.52v.04053a.99952.99952,0,0,0,.07031.34668l1.43946,3.87256c.01269.03418.02734.06689.043.09912A2.9843,2.9843,0,0,0,7.73633,19H8.5v2a1,1,0,0,0,2,0V19h1.99689l.00311.00049a.99907.99907,0,0,0,.32129-.05371l3.70026-1.25623a.99865.99865,0,0,0,.01751.12049l1,3.4663a1.00148,1.00148,0,0,0,.96094.72315,1.01777,1.01777,0,0,0,.27734-.03955,1.00043,1.00043,0,0,0,.6836-1.23828l-.92383-3.2002,1.92969-7.26611A1.03147,1.03147,0,0,0,20.5,10V9.77246A7.698,7.698,0,0,0,13.23047,2.00342ZM11.5,17H7.73633a.99477.99477,0,0,1-.874-.51318L5.93848,14H11.5Zm5.523-1.59137-3.523,1.196V13.72089l4.34479-1.44831Zm1.41211-5.38843a.973.973,0,0,0-.25147.03107L12.3374,12H6.28906l1.07422-1.74658a.99913.99913,0,0,0,.14746-.562c0-.01026-.00976-.18116-.01074-.19141A5.45491,5.45491,0,0,1,9.16992,5.55273a5.52222,5.52222,0,0,1,4-1.55029A5.6849,5.6849,0,0,1,18.5,9.77246Z"/></svg>
public/img/icons/unicons/head-side-mask.svg
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.0001726368791423738, 0.0001726368791423738, 0.0001726368791423738, 0.0001726368791423738, 0 ]
{ "id": 7, "code_window": [ " [theme.breakpoints.up('md')]: {\n", " transform: 'translateX(50%)',\n", " top: theme.spacing(8),\n", " left: theme.spacing(1),\n", " right: theme.spacing(-1),\n", " },\n", " }),\n", " };\n", "};" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " opacity: 0,\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "replace", "edit_start_line_idx": 104 }
import Prism, { Token } from 'prismjs'; import { Value } from 'slate'; import { TypeaheadOutput } from '@grafana/ui'; import { CloudWatchDatasource } from '../../datasource'; import { ResourceResponse } from '../../resources/types'; import { LogGroupField } from '../../types'; import { CloudWatchLogsLanguageProvider } from './CloudWatchLogsLanguageProvider'; import { AGGREGATION_FUNCTIONS_STATS, BOOLEAN_FUNCTIONS, DATETIME_FUNCTIONS, IP_FUNCTIONS, NUMERIC_OPERATORS, QUERY_COMMANDS, STRING_FUNCTIONS, FIELD_AND_FILTER_FUNCTIONS, } from './syntax'; const fields = ['field1', '@message']; describe('CloudWatchLogsLanguageProvider', () => { it('should suggest ', async () => { await runSuggestionTest('stats count(^)', [fields]); // Make sure having a field prefix does not brake anything await runSuggestionTest('stats count(@mess^)', [fields]); }); it('should suggest query commands on start of query', async () => { await runSuggestionTest('^', [QUERY_COMMANDS.map((v) => v.label)]); }); it('should suggest query commands after pipe', async () => { await runSuggestionTest('fields f | ^', [QUERY_COMMANDS.map((v) => v.label)]); }); it('should suggest fields and functions after field command', async () => { await runSuggestionTest('fields ^', [fields, FIELD_AND_FILTER_FUNCTIONS.map((v) => v.label)]); }); it('should suggest fields and functions after comma', async () => { await runSuggestionTest('fields field1, ^', [fields, FIELD_AND_FILTER_FUNCTIONS.map((v) => v.label)]); }); it('should suggest fields and functions after comma with prefix', async () => { await runSuggestionTest('fields field1, @mess^', [fields, FIELD_AND_FILTER_FUNCTIONS.map((v) => v.label)]); }); it('should suggest fields and functions after display command', async () => { await runSuggestionTest('display ^', [fields, FIELD_AND_FILTER_FUNCTIONS.map((v) => v.label)]); }); it('should suggest functions after stats command', async () => { await runSuggestionTest('stats ^', [AGGREGATION_FUNCTIONS_STATS.map((v) => v.label)]); }); it('should suggest fields and some functions after `by` command', async () => { await runSuggestionTest('stats count(something) by ^', [ fields, STRING_FUNCTIONS.concat(DATETIME_FUNCTIONS, IP_FUNCTIONS).map((v) => v.label), ]); }); it('should suggest fields and some functions after comparison operator', async () => { await runSuggestionTest('filter field1 >= ^', [ fields, [...NUMERIC_OPERATORS.map((v) => v.label), ...BOOLEAN_FUNCTIONS.map((v) => v.label)], ]); }); it('should suggest fields directly after sort', async () => { await runSuggestionTest('sort ^', [fields]); }); it('should suggest fields directly after sort after a pipe', async () => { await runSuggestionTest('fields field1 | sort ^', [fields]); }); it('should suggest sort order after sort command and field', async () => { await runSuggestionTest('sort field1 ^', [['asc', 'desc']]); }); it('should suggest fields directly after parse', async () => { await runSuggestionTest('parse ^', [fields]); }); it('should suggest fields and bool functions after filter', async () => { await runSuggestionTest('filter ^', [fields, BOOLEAN_FUNCTIONS.map((v) => v.label)]); }); it('should suggest fields and functions after filter bin() function', async () => { await runSuggestionTest('stats count(@message) by bin(30m), ^', [ fields, STRING_FUNCTIONS.concat(DATETIME_FUNCTIONS, IP_FUNCTIONS).map((v) => v.label), ]); }); it('should not suggest anything if not after comma in by expression', async () => { await runSuggestionTest('stats count(@message) by bin(30m) ^', []); }); }); async function runSuggestionTest(query: string, expectedItems: string[][]) { const result = await getProvideCompletionItems(query); expectedItems.forEach((items, index) => { expect(result.suggestions[index].items.map((item) => item.label)).toEqual(items); }); } function makeDatasource(): CloudWatchDatasource { return { resources: { getLogGroupFields(): Promise<Array<ResourceResponse<LogGroupField>>> { return Promise.resolve([{ value: { name: 'field1' } }, { value: { name: '@message' } }]); }, }, /* eslint-disable @typescript-eslint/no-explicit-any */ } as any; } /** * Get suggestion items based on query. Use `^` to mark position of the cursor. */ function getProvideCompletionItems(query: string): Promise<TypeaheadOutput> { const provider = new CloudWatchLogsLanguageProvider(makeDatasource()); const cursorOffset = query.indexOf('^'); const queryWithoutCursor = query.replace('^', ''); let tokens: Token[] = Prism.tokenize(queryWithoutCursor, provider.getSyntax()) as any; tokens = addTokenMetadata(tokens); const value = new ValueMock(tokens, cursorOffset); return provider.provideCompletionItems( { value, /* eslint-disable @typescript-eslint/no-explicit-any */ } as any, { logGroups: [{ name: 'logGroup1', arn: 'logGroup1' }], region: 'custom' } ); } class ValueMock { selection: Value['selection']; data: Value['data']; constructor(tokens: Array<string | Token>, cursorOffset: number) { this.selection = { start: { offset: cursorOffset, }, /* eslint-disable @typescript-eslint/no-explicit-any */ } as any; this.data = { get() { return tokens; }, /* eslint-disable @typescript-eslint/no-explicit-any */ } as any; } } /** * Adds some Slate specific metadata * @param tokens */ function addTokenMetadata(tokens: Array<string | Token>): Token[] { /* eslint-disable @typescript-eslint/no-explicit-any */ let prev = undefined as any; let offset = 0; return tokens.reduce((acc, token) => { /* eslint-disable @typescript-eslint/no-explicit-any */ let newToken: any; if (typeof token === 'string') { newToken = { content: token, // Not sure what else could it be here, probably if we do not match something types: ['whitespace'], }; } else { newToken = { ...token }; newToken.types = [token.type]; } newToken.prev = prev; if (newToken.prev) { newToken.prev.next = newToken; } const end = offset + token.length; newToken.offsets = { start: offset, end, }; prev = newToken; offset = end; return [...acc, newToken]; }, [] as Token[]); }
public/app/plugins/datasource/cloudwatch/language/cloudwatch-logs/CloudWatchLogsLanguageProvider.test.ts
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.00024438282707706094, 0.00017740923794917762, 0.00016484413936268538, 0.00017510556790512055, 0.000015692272427259013 ]
{ "id": 7, "code_window": [ " [theme.breakpoints.up('md')]: {\n", " transform: 'translateX(50%)',\n", " top: theme.spacing(8),\n", " left: theme.spacing(1),\n", " right: theme.spacing(-1),\n", " },\n", " }),\n", " };\n", "};" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " opacity: 0,\n" ], "file_path": "public/app/core/components/PageNew/SectionNav.tsx", "type": "replace", "edit_start_line_idx": 104 }
<svg xmlns="http://www.w3.org/2000/svg" data-name="Layer 1" viewBox="0 0 24 24"><path d="M12,2A10,10,0,0,0,4.65,18.76l.09.1a10,10,0,0,0,14.52,0l.09-.1A10,10,0,0,0,12,2ZM5.61,16.79a7.93,7.93,0,0,1,0-9.58,6,6,0,0,1,0,9.58ZM12,20a7.91,7.91,0,0,1-5-1.77A8,8,0,0,0,7,5.77a7.95,7.95,0,0,1,10,0,8,8,0,0,0,0,12.46A7.91,7.91,0,0,1,12,20Zm6.39-3.21a6,6,0,0,1,0-9.58,7.93,7.93,0,0,1,0,9.58Z"/></svg>
public/img/icons/unicons/tennis-ball.svg
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.00017366497195325792, 0.00017366497195325792, 0.00017366497195325792, 0.00017366497195325792, 0 ]
{ "id": 8, "code_window": [ "import React from 'react';\n", "\n", "import { GrafanaTheme2 } from '@grafana/data';\n", "import { IconButton, useTheme2 } from '@grafana/ui';\n", "\n", "export interface Props {\n", " className?: string;\n", " isExpanded: boolean;\n", " onClick: () => void;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { Button, useTheme2 } from '@grafana/ui';\n" ], "file_path": "public/app/core/components/PageNew/SectionNavToggle.tsx", "type": "replace", "edit_start_line_idx": 5 }
import { css } from '@emotion/css'; import classnames from 'classnames'; import React from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { IconButton, useTheme2 } from '@grafana/ui'; export interface Props { className?: string; isExpanded: boolean; onClick: () => void; } export const SectionNavToggle = ({ className, isExpanded, onClick }: Props) => { const theme = useTheme2(); const styles = getStyles(theme); return ( <IconButton tooltip={'Toggle section navigation'} aria-label={isExpanded ? 'Close section navigation' : 'Open section navigation'} name={isExpanded ? 'angle-left' : 'angle-right'} className={classnames(className, styles.icon)} size="xl" onClick={onClick} /> ); }; SectionNavToggle.displayName = 'SectionNavToggle'; const getStyles = (theme: GrafanaTheme2) => ({ icon: css({ backgroundColor: theme.colors.background.secondary, border: `1px solid ${theme.colors.border.weak}`, borderRadius: '50%', marginRight: 0, zIndex: 1, }), });
public/app/core/components/PageNew/SectionNavToggle.tsx
1
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.9992450475692749, 0.39783620834350586, 0.0001789564557839185, 0.0008677303558215499, 0.48653703927993774 ]
{ "id": 8, "code_window": [ "import React from 'react';\n", "\n", "import { GrafanaTheme2 } from '@grafana/data';\n", "import { IconButton, useTheme2 } from '@grafana/ui';\n", "\n", "export interface Props {\n", " className?: string;\n", " isExpanded: boolean;\n", " onClick: () => void;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { Button, useTheme2 } from '@grafana/ui';\n" ], "file_path": "public/app/core/components/PageNew/SectionNavToggle.tsx", "type": "replace", "edit_start_line_idx": 5 }
#!/bin/bash ## ## Common variable declarations ## Find the latest tag on https://hub.docker.com/r/grafana/grafana-plugin-ci-e2e/tags ## DOCKER_IMAGE_BASE_NAME="grafana/grafana-plugin-ci-e2e" DOCKER_IMAGE_VERSION="1.6.1" DOCKER_IMAGE_NAME="${DOCKER_IMAGE_BASE_NAME}:${DOCKER_IMAGE_VERSION}"
packages/grafana-toolkit/docker/grafana-plugin-ci-e2e/common.sh
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.0001789564557839185, 0.00017714998102746904, 0.0001753435208229348, 0.00017714998102746904, 0.0000018064674804918468 ]
{ "id": 8, "code_window": [ "import React from 'react';\n", "\n", "import { GrafanaTheme2 } from '@grafana/data';\n", "import { IconButton, useTheme2 } from '@grafana/ui';\n", "\n", "export interface Props {\n", " className?: string;\n", " isExpanded: boolean;\n", " onClick: () => void;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { Button, useTheme2 } from '@grafana/ui';\n" ], "file_path": "public/app/core/components/PageNew/SectionNavToggle.tsx", "type": "replace", "edit_start_line_idx": 5 }
# Should not be included apiVersion: 1 #datasources: # - name: name # type: type # access: proxy # orgId: 2 # url: url # user: user # database: database # basicAuth: true # basicAuthUser: basic_auth_user # withCredentials: true # jsonData: # graphiteVersion: "1.1" # tlsAuth: true # tlsAuthWithCACert: true # secureJsonData: # tlsCACert: "MjNOcW9RdkbUDHZmpco2HCYzVq9dE+i6Yi+gmUJotq5CDA==" # tlsClientCert: "ckN0dGlyMXN503YNfjTcf9CV+GGQneN+xmAclQ==" # tlsClientKey: "ZkN4aG1aNkja/gKAB1wlnKFIsy2SRDq4slrM0A==" # editable: true # version: 10 # #deleteDatasources: # - name: old-graphite3 # orgId: 2
pkg/services/provisioning/datasources/testdata/all-properties/sample.yaml
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.0001789564557839185, 0.0001758882135618478, 0.00017416760965716094, 0.00017521437257528305, 0.000001899177732411772 ]
{ "id": 8, "code_window": [ "import React from 'react';\n", "\n", "import { GrafanaTheme2 } from '@grafana/data';\n", "import { IconButton, useTheme2 } from '@grafana/ui';\n", "\n", "export interface Props {\n", " className?: string;\n", " isExpanded: boolean;\n", " onClick: () => void;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { Button, useTheme2 } from '@grafana/ui';\n" ], "file_path": "public/app/core/components/PageNew/SectionNavToggle.tsx", "type": "replace", "edit_start_line_idx": 5 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M8.7,10a1,1,0,0,0,1.41,0,1,1,0,0,0,0-1.41L3.84,2.29A1,1,0,0,0,2.42,3.71ZM21,14a1,1,0,0,0-1,1v3.59L15.44,14A1,1,0,0,0,14,15.44L18.59,20H15a1,1,0,0,0,0,2h6a1,1,0,0,0,.38-.08,1,1,0,0,0,.54-.54A1,1,0,0,0,22,21V15A1,1,0,0,0,21,14Zm.92-11.38a1,1,0,0,0-.54-.54A1,1,0,0,0,21,2H15a1,1,0,0,0,0,2h3.59L2.29,20.29a1,1,0,0,0,0,1.42,1,1,0,0,0,1.42,0L20,5.41V9a1,1,0,0,0,2,0V3A1,1,0,0,0,21.92,2.62Z"/></svg>
public/img/icons/unicons/arrow-random.svg
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.00017378789198119193, 0.00017378789198119193, 0.00017378789198119193, 0.00017378789198119193, 0 ]
{ "id": 9, "code_window": [ "export const SectionNavToggle = ({ className, isExpanded, onClick }: Props) => {\n", " const theme = useTheme2();\n", " const styles = getStyles(theme);\n", "\n", " return (\n", " <IconButton\n", " tooltip={'Toggle section navigation'}\n", " aria-label={isExpanded ? 'Close section navigation' : 'Open section navigation'}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ " <Button\n", " title={'Toggle section navigation'}\n" ], "file_path": "public/app/core/components/PageNew/SectionNavToggle.tsx", "type": "replace", "edit_start_line_idx": 18 }
import { css } from '@emotion/css'; import classnames from 'classnames'; import React from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { IconButton, useTheme2 } from '@grafana/ui'; export interface Props { className?: string; isExpanded: boolean; onClick: () => void; } export const SectionNavToggle = ({ className, isExpanded, onClick }: Props) => { const theme = useTheme2(); const styles = getStyles(theme); return ( <IconButton tooltip={'Toggle section navigation'} aria-label={isExpanded ? 'Close section navigation' : 'Open section navigation'} name={isExpanded ? 'angle-left' : 'angle-right'} className={classnames(className, styles.icon)} size="xl" onClick={onClick} /> ); }; SectionNavToggle.displayName = 'SectionNavToggle'; const getStyles = (theme: GrafanaTheme2) => ({ icon: css({ backgroundColor: theme.colors.background.secondary, border: `1px solid ${theme.colors.border.weak}`, borderRadius: '50%', marginRight: 0, zIndex: 1, }), });
public/app/core/components/PageNew/SectionNavToggle.tsx
1
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.9982790946960449, 0.39918071031570435, 0.00017644827312324196, 0.0016783822793513536, 0.4876879155635834 ]
{ "id": 9, "code_window": [ "export const SectionNavToggle = ({ className, isExpanded, onClick }: Props) => {\n", " const theme = useTheme2();\n", " const styles = getStyles(theme);\n", "\n", " return (\n", " <IconButton\n", " tooltip={'Toggle section navigation'}\n", " aria-label={isExpanded ? 'Close section navigation' : 'Open section navigation'}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ " <Button\n", " title={'Toggle section navigation'}\n" ], "file_path": "public/app/core/components/PageNew/SectionNavToggle.tsx", "type": "replace", "edit_start_line_idx": 18 }
import { DataFrame, FieldType, getDefaultTimeRange, LoadingState, PanelData, PanelPluginMeta, toDataFrame, VisualizationSuggestion, } from '@grafana/data'; import { config } from 'app/core/config'; import { SuggestionName } from 'app/types/suggestions'; import { getAllSuggestions, panelsToCheckFirst } from './getAllSuggestions'; jest.unmock('app/core/core'); jest.unmock('app/features/plugins/plugin_loader'); for (const pluginId of panelsToCheckFirst) { config.panels[pluginId] = { module: `app/plugins/panel/${pluginId}/module`, } as any; } config.panels['text'] = { id: 'text', name: 'Text', skipDataQuery: true, info: { description: 'pretty decent plugin', logos: { small: 'small/logo', large: 'large/logo' }, }, } as PanelPluginMeta; class ScenarioContext { data: DataFrame[] = []; suggestions: VisualizationSuggestion[] = []; setData(scenarioData: DataFrame[]) { this.data = scenarioData; beforeAll(async () => { await this.run(); }); } async run() { const panelData: PanelData = { series: this.data, state: LoadingState.Done, timeRange: getDefaultTimeRange(), }; this.suggestions = await getAllSuggestions(panelData); } names() { return this.suggestions.map((x) => x.name); } } function scenario(name: string, setup: (ctx: ScenarioContext) => void) { describe(name, () => { const ctx = new ScenarioContext(); setup(ctx); }); } scenario('No series', (ctx) => { ctx.setData([]); it('should return correct suggestions', () => { expect(ctx.names()).toEqual([SuggestionName.Table, SuggestionName.TextPanel]); }); }); scenario('No rows', (ctx) => { ctx.setData([ toDataFrame({ fields: [ { name: 'Time', type: FieldType.time, values: [] }, { name: 'Max', type: FieldType.number, values: [] }, ], }), ]); it('should return correct suggestions', () => { expect(ctx.names()).toEqual([SuggestionName.Table]); }); }); scenario('Single frame with time and number field', (ctx) => { ctx.setData([ toDataFrame({ fields: [ { name: 'Time', type: FieldType.time, values: [1, 2, 3, 4, 5] }, { name: 'Max', type: FieldType.number, values: [1, 10, 50, 2, 5] }, ], }), ]); it('should return correct suggestions', () => { expect(ctx.names()).toEqual([ SuggestionName.LineChart, SuggestionName.LineChartSmooth, SuggestionName.AreaChart, SuggestionName.LineChartGradientColorScheme, SuggestionName.BarChart, SuggestionName.BarChartGradientColorScheme, SuggestionName.Gauge, SuggestionName.GaugeNoThresholds, SuggestionName.Stat, SuggestionName.StatColoredBackground, SuggestionName.BarGaugeBasic, SuggestionName.BarGaugeLCD, SuggestionName.Table, SuggestionName.StateTimeline, SuggestionName.StatusHistory, ]); }); it('Bar chart suggestion should be using timeseries panel', () => { expect(ctx.suggestions.find((x) => x.name === SuggestionName.BarChart)?.pluginId).toBe('timeseries'); }); it('Stat panels have reduce values disabled', () => { for (const suggestion of ctx.suggestions) { if (suggestion.options?.reduceOptions?.values) { throw new Error(`Suggestion ${suggestion.name} reduce.values set to true when it should be false`); } } }); }); scenario('Single frame with time 2 number fields', (ctx) => { ctx.setData([ toDataFrame({ fields: [ { name: 'Time', type: FieldType.time, values: [1, 2, 3, 4, 5] }, { name: 'ServerA', type: FieldType.number, values: [1, 10, 50, 2, 5] }, { name: 'ServerB', type: FieldType.number, values: [1, 10, 50, 2, 5] }, ], }), ]); it('should return correct suggestions', () => { expect(ctx.names()).toEqual([ SuggestionName.LineChart, SuggestionName.LineChartSmooth, SuggestionName.AreaChartStacked, SuggestionName.AreaChartStackedPercent, SuggestionName.BarChartStacked, SuggestionName.BarChartStackedPercent, SuggestionName.Gauge, SuggestionName.GaugeNoThresholds, SuggestionName.Stat, SuggestionName.StatColoredBackground, SuggestionName.PieChart, SuggestionName.PieChartDonut, SuggestionName.BarGaugeBasic, SuggestionName.BarGaugeLCD, SuggestionName.Table, SuggestionName.StateTimeline, SuggestionName.StatusHistory, ]); }); it('Stat panels have reduceOptions.values disabled', () => { for (const suggestion of ctx.suggestions) { if (suggestion.options?.reduceOptions?.values) { throw new Error(`Suggestion ${suggestion.name} reduce.values set to true when it should be false`); } } }); }); scenario('Single time series with 100 data points', (ctx) => { ctx.setData([ toDataFrame({ fields: [ { name: 'Time', type: FieldType.time, values: [...Array(100).keys()] }, { name: 'ServerA', type: FieldType.number, values: [...Array(100).keys()] }, ], }), ]); it('should not suggest bar chart', () => { expect(ctx.suggestions.find((x) => x.name === SuggestionName.BarChart)).toBe(undefined); }); }); scenario('30 time series with 100 data points', (ctx) => { ctx.setData( repeatFrame( 30, toDataFrame({ fields: [ { name: 'Time', type: FieldType.time, values: [...Array(100).keys()] }, { name: 'ServerA', type: FieldType.number, values: [...Array(100).keys()] }, ], }) ) ); it('should not suggest timeline', () => { expect(ctx.suggestions.find((x) => x.pluginId === 'state-timeline')).toBe(undefined); }); }); scenario('50 time series with 100 data points', (ctx) => { ctx.setData( repeatFrame( 50, toDataFrame({ fields: [ { name: 'Time', type: FieldType.time, values: [...Array(100).keys()] }, { name: 'ServerA', type: FieldType.number, values: [...Array(100).keys()] }, ], }) ) ); it('should not suggest gauge', () => { expect(ctx.suggestions.find((x) => x.pluginId === 'gauge')).toBe(undefined); }); }); scenario('Single frame with string and number field', (ctx) => { ctx.setData([ toDataFrame({ fields: [ { name: 'Name', type: FieldType.string, values: ['Hugo', 'Dominik', 'Marcus'] }, { name: 'ServerA', type: FieldType.number, values: [1, 2, 3] }, ], }), ]); it('should return correct suggestions', () => { expect(ctx.names()).toEqual([ SuggestionName.BarChart, SuggestionName.BarChartHorizontal, SuggestionName.Gauge, SuggestionName.GaugeNoThresholds, SuggestionName.Stat, SuggestionName.StatColoredBackground, SuggestionName.PieChart, SuggestionName.PieChartDonut, SuggestionName.BarGaugeBasic, SuggestionName.BarGaugeLCD, SuggestionName.Table, ]); }); it('Stat/Gauge/BarGauge/PieChart panels to have reduceOptions.values enabled', () => { for (const suggestion of ctx.suggestions) { if (suggestion.options?.reduceOptions && !suggestion.options?.reduceOptions?.values) { throw new Error(`Suggestion ${suggestion.name} reduce.values set to false when it should be true`); } } }); }); scenario('Single frame with string and 2 number field', (ctx) => { ctx.setData([ toDataFrame({ fields: [ { name: 'Name', type: FieldType.string, values: ['Hugo', 'Dominik', 'Marcus'] }, { name: 'ServerA', type: FieldType.number, values: [1, 2, 3] }, { name: 'ServerB', type: FieldType.number, values: [1, 2, 3] }, ], }), ]); it('should return correct suggestions', () => { expect(ctx.names()).toEqual([ SuggestionName.BarChart, SuggestionName.BarChartStacked, SuggestionName.BarChartStackedPercent, SuggestionName.BarChartHorizontal, SuggestionName.BarChartHorizontalStacked, SuggestionName.BarChartHorizontalStackedPercent, SuggestionName.Gauge, SuggestionName.GaugeNoThresholds, SuggestionName.Stat, SuggestionName.StatColoredBackground, SuggestionName.PieChart, SuggestionName.PieChartDonut, SuggestionName.BarGaugeBasic, SuggestionName.BarGaugeLCD, SuggestionName.Table, ]); }); }); scenario('Single frame with only string field', (ctx) => { ctx.setData([ toDataFrame({ fields: [{ name: 'Name', type: FieldType.string, values: ['Hugo', 'Dominik', 'Marcus'] }], }), ]); it('should return correct suggestions', () => { expect(ctx.names()).toEqual([SuggestionName.Stat, SuggestionName.Table]); }); it('Stat panels have reduceOptions.fields set to show all fields', () => { for (const suggestion of ctx.suggestions) { if (suggestion.options?.reduceOptions) { expect(suggestion.options.reduceOptions.fields).toBe('/.*/'); } } }); }); scenario('Given default loki logs data', (ctx) => { ctx.setData([ toDataFrame({ fields: [ { name: 'ts', type: FieldType.time, values: ['2021-11-11T13:38:45.440Z', '2021-11-11T13:38:45.190Z'] }, { name: 'line', type: FieldType.string, values: [ 't=2021-11-11T14:38:45+0100 lvl=dbug msg="Client connected" logger=live user=1 client=ee79155b-a8d1-4730-bcb3-94d8690df35c', 't=2021-11-11T14:38:45+0100 lvl=dbug msg="Adding CSP header to response" logger=http.server cfg=0xc0005fed00', ], labels: { filename: '/var/log/grafana/grafana.log', job: 'grafana' }, }, ], meta: { preferredVisualisationType: 'logs', }, }), ]); it('should return correct suggestions', () => { expect(ctx.names()).toEqual([SuggestionName.Logs, SuggestionName.Table]); }); }); function repeatFrame(count: number, frame: DataFrame): DataFrame[] { const frames: DataFrame[] = []; for (let i = 0; i < count; i++) { frames.push(frame); } return frames; }
public/app/features/panel/state/getAllSuggestions.test.ts
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.00017859558283817023, 0.00017553206998854876, 0.0001710930373519659, 0.00017580960411578417, 0.0000018152521761294338 ]
{ "id": 9, "code_window": [ "export const SectionNavToggle = ({ className, isExpanded, onClick }: Props) => {\n", " const theme = useTheme2();\n", " const styles = getStyles(theme);\n", "\n", " return (\n", " <IconButton\n", " tooltip={'Toggle section navigation'}\n", " aria-label={isExpanded ? 'Close section navigation' : 'Open section navigation'}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ " <Button\n", " title={'Toggle section navigation'}\n" ], "file_path": "public/app/core/components/PageNew/SectionNavToggle.tsx", "type": "replace", "edit_start_line_idx": 18 }
import { compareArrayValues, compareDataFrameStructures, PanelData } from '@grafana/data'; export const setStructureRevision = (result: PanelData, lastResult: PanelData | undefined) => { let structureRev = 1; if (lastResult?.structureRev && lastResult.series) { structureRev = lastResult.structureRev; const sameStructure = compareArrayValues(result.series, lastResult.series, compareDataFrameStructures); if (!sameStructure) { structureRev++; } } result.structureRev = structureRev; return result; };
public/app/features/query/state/processing/revision.ts
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.00017625404871068895, 0.000176102839759551, 0.00017595163080841303, 0.000176102839759551, 1.5120895113795996e-7 ]
{ "id": 9, "code_window": [ "export const SectionNavToggle = ({ className, isExpanded, onClick }: Props) => {\n", " const theme = useTheme2();\n", " const styles = getStyles(theme);\n", "\n", " return (\n", " <IconButton\n", " tooltip={'Toggle section navigation'}\n", " aria-label={isExpanded ? 'Close section navigation' : 'Open section navigation'}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ " <Button\n", " title={'Toggle section navigation'}\n" ], "file_path": "public/app/core/components/PageNew/SectionNavToggle.tsx", "type": "replace", "edit_start_line_idx": 18 }
// Code generated - EDITING IS FUTILE. DO NOT EDIT. // // Generated by: // kinds/gen.go // Using jennies: // CommonSchemaJenny // // Run 'make gen-cue' from repository root to regenerate. package common // Canonically defined in pkg/kindsys/dataquery.cue FOR NOW to avoid having any external imports // in kindsys. Code generation copies this file to the common schemas in packages/grafana-schema/src/common. // // NOTE make gen-cue must be run twice when updating this file // These are the common properties available to all queries in all datasources. // Specific implementations will *extend* this interface, adding the required // properties for the given context. DataQuery: { // A - Z refId: string // true if query is disabled (ie should not be returned to the dashboard) hide?: bool // Unique, guid like, string used in explore mode key?: string // Specify the query flavor // TODO make this required and give it a default queryType?: string // For mixed data sources the selected datasource is on the query level. // For non mixed scenarios this is undefined. // TODO find a better way to do this ^ that's friendly to schema // TODO this shouldn't be unknown but DataSourceRef | null datasource?: _ } @cuetsy(kind="interface") DataSourceRef: { // The plugin type-id type?: string // Specific datasource instance uid?: string } @cuetsy(kind="interface")
packages/grafana-schema/src/common/dataquery_gen.cue
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.00017748246318660676, 0.00017379029304720461, 0.00017101848789025098, 0.00017323068459518254, 0.000002491767418177915 ]
{ "id": 10, "code_window": [ " aria-label={isExpanded ? 'Close section navigation' : 'Open section navigation'}\n", " name={isExpanded ? 'angle-left' : 'angle-right'}\n", " className={classnames(className, styles.icon)}\n", " size=\"xl\"\n", " onClick={onClick}\n", " />\n", " );\n", "};\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " icon=\"arrow-to-right\"\n", " className={classnames(className, styles.icon, {\n", " [styles.iconExpanded]: isExpanded,\n", " })}\n", " variant=\"secondary\"\n", " fill=\"text\"\n", " size=\"md\"\n" ], "file_path": "public/app/core/components/PageNew/SectionNavToggle.tsx", "type": "replace", "edit_start_line_idx": 21 }
import { css } from '@emotion/css'; import classnames from 'classnames'; import React from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { IconButton, useTheme2 } from '@grafana/ui'; export interface Props { className?: string; isExpanded: boolean; onClick: () => void; } export const SectionNavToggle = ({ className, isExpanded, onClick }: Props) => { const theme = useTheme2(); const styles = getStyles(theme); return ( <IconButton tooltip={'Toggle section navigation'} aria-label={isExpanded ? 'Close section navigation' : 'Open section navigation'} name={isExpanded ? 'angle-left' : 'angle-right'} className={classnames(className, styles.icon)} size="xl" onClick={onClick} /> ); }; SectionNavToggle.displayName = 'SectionNavToggle'; const getStyles = (theme: GrafanaTheme2) => ({ icon: css({ backgroundColor: theme.colors.background.secondary, border: `1px solid ${theme.colors.border.weak}`, borderRadius: '50%', marginRight: 0, zIndex: 1, }), });
public/app/core/components/PageNew/SectionNavToggle.tsx
1
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.9945060610771179, 0.1999334841966629, 0.0001771961833583191, 0.001911007915623486, 0.3972872197628021 ]
{ "id": 10, "code_window": [ " aria-label={isExpanded ? 'Close section navigation' : 'Open section navigation'}\n", " name={isExpanded ? 'angle-left' : 'angle-right'}\n", " className={classnames(className, styles.icon)}\n", " size=\"xl\"\n", " onClick={onClick}\n", " />\n", " );\n", "};\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " icon=\"arrow-to-right\"\n", " className={classnames(className, styles.icon, {\n", " [styles.iconExpanded]: isExpanded,\n", " })}\n", " variant=\"secondary\"\n", " fill=\"text\"\n", " size=\"md\"\n" ], "file_path": "public/app/core/components/PageNew/SectionNavToggle.tsx", "type": "replace", "edit_start_line_idx": 21 }
<?xml version="1.0" encoding="utf-8"?> <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi" xmlns:fire="http://schemas.microsoft.com/wix/FirewallExtension"> <Fragment> <ComponentGroup Id="GrafanaFirewallExceptionsGroup"> <Component Id="FirewallGrafanaServer" Guid="7278f07d-de6f-497f-9267-d5feb5216a5c" Directory="INSTALLDIR"> <File KeyPath="yes" Source="SourceDir\grafana\bin\grafana-server.exe"> <fire:FirewallException Id="FWX1" Name="Grafana Server TCP 3000" Port="3000" Profile="all" Protocol="tcp" Scope="any"/> </File> </Component> </ComponentGroup> </Fragment> </Wix>
scripts/build/ci-msi-build/msigenerator/templates/common/grafana-firewall.wxs.j2
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.00017466054123360664, 0.00017315286095254123, 0.0001716451661195606, 0.00017315286095254123, 0.0000015076875570230186 ]
{ "id": 10, "code_window": [ " aria-label={isExpanded ? 'Close section navigation' : 'Open section navigation'}\n", " name={isExpanded ? 'angle-left' : 'angle-right'}\n", " className={classnames(className, styles.icon)}\n", " size=\"xl\"\n", " onClick={onClick}\n", " />\n", " );\n", "};\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " icon=\"arrow-to-right\"\n", " className={classnames(className, styles.icon, {\n", " [styles.iconExpanded]: isExpanded,\n", " })}\n", " variant=\"secondary\"\n", " fill=\"text\"\n", " size=\"md\"\n" ], "file_path": "public/app/core/components/PageNew/SectionNavToggle.tsx", "type": "replace", "edit_start_line_idx": 21 }
// Base classes .label, .badge { display: inline-block; padding: 2px 4px; font-size: $font-size-base * 0.846; font-weight: $font-weight-semi-bold; line-height: 14px; // ensure proper line-height if floated color: $white; vertical-align: baseline; white-space: nowrap; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); background-color: $gray-1; } // Labels & Badges .label-tag { background-color: $purple; color: darken($white, 5%); white-space: nowrap; border-radius: 3px; text-shadow: none; font-size: 12px; padding: 0px 6px; line-height: 20px; height: 20px; svg { margin-bottom: 0; } .icon-tag { position: relative; top: 1px; padding-right: 4px; } &.muted { opacity: 0.85; background-color: darken($purple, 10%); color: $text-muted; } &:hover { opacity: 0.85; background-color: darken($purple, 10%); } &--gray { opacity: 0.85; background-color: $gray-1; border-color: $gray-2; &:hover { background-color: $gray-1; } } }
public/sass/components/_tags.scss
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.00018022207950707525, 0.00017427235434297472, 0.00016419436724390835, 0.00017614438547752798, 0.0000053560856940748636 ]
{ "id": 10, "code_window": [ " aria-label={isExpanded ? 'Close section navigation' : 'Open section navigation'}\n", " name={isExpanded ? 'angle-left' : 'angle-right'}\n", " className={classnames(className, styles.icon)}\n", " size=\"xl\"\n", " onClick={onClick}\n", " />\n", " );\n", "};\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " icon=\"arrow-to-right\"\n", " className={classnames(className, styles.icon, {\n", " [styles.iconExpanded]: isExpanded,\n", " })}\n", " variant=\"secondary\"\n", " fill=\"text\"\n", " size=\"md\"\n" ], "file_path": "public/app/core/components/PageNew/SectionNavToggle.tsx", "type": "replace", "edit_start_line_idx": 21 }
package gpg import ( "encoding/base64" "fmt" "log" "os" "github.com/grafana/grafana/pkg/build/config" "github.com/grafana/grafana/pkg/build/fsutil" ) // LoadGPGKeys loads GPG key pair and password from the environment and writes them to corresponding files. // // The passed config's GPG fields also get updated. Make sure to call RemoveGPGFiles at application exit. func LoadGPGKeys(cfg *config.Config) error { var err error cfg.GPGPrivateKey, err = fsutil.CreateTempFile("priv.key") if err != nil { return err } cfg.GPGPublicKey, err = fsutil.CreateTempFile("pub.key") if err != nil { return err } cfg.GPGPassPath, err = fsutil.CreateTempFile("") if err != nil { return err } gpgPrivKey := os.Getenv("GPG_PRIV_KEY") if gpgPrivKey == "" { return fmt.Errorf("$GPG_PRIV_KEY must be defined") } gpgPubKey := os.Getenv("GPG_PUB_KEY") if gpgPubKey == "" { return fmt.Errorf("$GPG_PUB_KEY must be defined") } gpgPass := os.Getenv("GPG_KEY_PASSWORD") if gpgPass == "" { return fmt.Errorf("$GPG_KEY_PASSWORD must be defined") } gpgPrivKeyB, err := base64.StdEncoding.DecodeString(gpgPrivKey) if err != nil { return fmt.Errorf("couldn't decode $GPG_PRIV_KEY: %w", err) } gpgPubKeyB, err := base64.StdEncoding.DecodeString(gpgPubKey) if err != nil { return fmt.Errorf("couldn't decode $GPG_PUB_KEY: %w", err) } if err := os.WriteFile(cfg.GPGPrivateKey, append(gpgPrivKeyB, '\n'), 0400); err != nil { return fmt.Errorf("failed to write GPG private key file: %w", err) } if err := os.WriteFile(cfg.GPGPublicKey, append(gpgPubKeyB, '\n'), 0400); err != nil { return fmt.Errorf("failed to write GPG public key file: %w", err) } if err := os.WriteFile(cfg.GPGPassPath, []byte(gpgPass+"\n"), 0400); err != nil { return fmt.Errorf("failed to write GPG password file: %w", err) } return nil } // RemoveGPGFiles removes configured GPG files. func RemoveGPGFiles(cfg config.Config) { for _, fpath := range []string{cfg.GPGPrivateKey, cfg.GPGPublicKey, cfg.GPGPassPath} { if err := os.Remove(fpath); err != nil { log.Printf("failed to remove %q", fpath) } } }
pkg/build/gpg/gpg.go
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.000177402762346901, 0.00017279849271290004, 0.00016796891577541828, 0.00017297179147135466, 0.000003373024583197548 ]
{ "id": 11, "code_window": [ "SectionNavToggle.displayName = 'SectionNavToggle';\n", "\n", "const getStyles = (theme: GrafanaTheme2) => ({\n", " icon: css({\n", " backgroundColor: theme.colors.background.secondary,\n", " border: `1px solid ${theme.colors.border.weak}`,\n", " borderRadius: '50%',\n", " marginRight: 0,\n", " zIndex: 1,\n", " }),\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " color: theme.colors.text.secondary,\n" ], "file_path": "public/app/core/components/PageNew/SectionNavToggle.tsx", "type": "replace", "edit_start_line_idx": 33 }
import { css } from '@emotion/css'; import classnames from 'classnames'; import React from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { IconButton, useTheme2 } from '@grafana/ui'; export interface Props { className?: string; isExpanded: boolean; onClick: () => void; } export const SectionNavToggle = ({ className, isExpanded, onClick }: Props) => { const theme = useTheme2(); const styles = getStyles(theme); return ( <IconButton tooltip={'Toggle section navigation'} aria-label={isExpanded ? 'Close section navigation' : 'Open section navigation'} name={isExpanded ? 'angle-left' : 'angle-right'} className={classnames(className, styles.icon)} size="xl" onClick={onClick} /> ); }; SectionNavToggle.displayName = 'SectionNavToggle'; const getStyles = (theme: GrafanaTheme2) => ({ icon: css({ backgroundColor: theme.colors.background.secondary, border: `1px solid ${theme.colors.border.weak}`, borderRadius: '50%', marginRight: 0, zIndex: 1, }), });
public/app/core/components/PageNew/SectionNavToggle.tsx
1
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.9982103109359741, 0.48823294043540955, 0.00017524708528071642, 0.5007665753364563, 0.43410539627075195 ]
{ "id": 11, "code_window": [ "SectionNavToggle.displayName = 'SectionNavToggle';\n", "\n", "const getStyles = (theme: GrafanaTheme2) => ({\n", " icon: css({\n", " backgroundColor: theme.colors.background.secondary,\n", " border: `1px solid ${theme.colors.border.weak}`,\n", " borderRadius: '50%',\n", " marginRight: 0,\n", " zIndex: 1,\n", " }),\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " color: theme.colors.text.secondary,\n" ], "file_path": "public/app/core/components/PageNew/SectionNavToggle.tsx", "type": "replace", "edit_start_line_idx": 33 }
package manager import ( "context" "github.com/prometheus/client_golang/prometheus" ) const ( ExporterName = "grafana" ) var ( // MStatTotalServiceAccounts is a metric gauge for total number of service accounts MStatTotalServiceAccounts prometheus.Gauge // MStatTotalServiceAccountTokens is a metric gauge for total number of service account tokens MStatTotalServiceAccountTokens prometheus.Gauge Initialised bool = false ) func init() { MStatTotalServiceAccounts = prometheus.NewGauge(prometheus.GaugeOpts{ Name: "stat_total_service_accounts", Help: "total amount of service accounts", Namespace: ExporterName, }) MStatTotalServiceAccountTokens = prometheus.NewGauge(prometheus.GaugeOpts{ Name: "stat_total_service_account_tokens", Help: "total amount of service account tokens", Namespace: ExporterName, }) prometheus.MustRegister( MStatTotalServiceAccounts, MStatTotalServiceAccountTokens, ) } func (sa *ServiceAccountsService) getUsageMetrics(ctx context.Context) (map[string]interface{}, error) { stats := map[string]interface{}{} sqlStats, err := sa.store.GetUsageMetrics(ctx) if err != nil { return nil, err } stats["stats.serviceaccounts.count"] = sqlStats.ServiceAccounts stats["stats.serviceaccounts.tokens.count"] = sqlStats.Tokens var secretScanEnabled int64 = 0 if sa.secretScanEnabled { secretScanEnabled = 1 } stats["stats.serviceaccounts.secret_scan.enabled.count"] = secretScanEnabled MStatTotalServiceAccountTokens.Set(float64(sqlStats.Tokens)) MStatTotalServiceAccounts.Set(float64(sqlStats.ServiceAccounts)) return stats, nil }
pkg/services/serviceaccounts/manager/stats.go
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.00035290358937345445, 0.00019942704238928854, 0.00017015202320180833, 0.0001743129687383771, 0.00006268279685173184 ]
{ "id": 11, "code_window": [ "SectionNavToggle.displayName = 'SectionNavToggle';\n", "\n", "const getStyles = (theme: GrafanaTheme2) => ({\n", " icon: css({\n", " backgroundColor: theme.colors.background.secondary,\n", " border: `1px solid ${theme.colors.border.weak}`,\n", " borderRadius: '50%',\n", " marginRight: 0,\n", " zIndex: 1,\n", " }),\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " color: theme.colors.text.secondary,\n" ], "file_path": "public/app/core/components/PageNew/SectionNavToggle.tsx", "type": "replace", "edit_start_line_idx": 33 }
package supportbundlesimpl import ( "github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/org" ) const ( ActionRead = "support.bundles:read" ActionCreate = "support.bundles:create" ActionDelete = "support.bundles:delete" ) var ( bundleReaderRole = accesscontrol.RoleDTO{ Name: "fixed:support.bundles:reader", DisplayName: "Support bundle reader", Description: "List and download support bundles", Group: "Support bundles", Permissions: []accesscontrol.Permission{ {Action: ActionRead}, }, } bundleWriterRole = accesscontrol.RoleDTO{ Name: "fixed:support.bundles:writer", DisplayName: "Support bundle writer", Description: "Create, delete, list and download support bundles", Group: "Support bundles", Permissions: []accesscontrol.Permission{ {Action: ActionRead}, {Action: ActionCreate}, {Action: ActionDelete}, }, } ) func (s *Service) declareFixedRoles(ac accesscontrol.Service) error { grants := []string{string(org.RoleAdmin), accesscontrol.RoleGrafanaAdmin} if s.serverAdminOnly { grants = []string{accesscontrol.RoleGrafanaAdmin} } bundleReader := accesscontrol.RoleRegistration{ Role: bundleReaderRole, Grants: grants, } bundleWriter := accesscontrol.RoleRegistration{ Role: bundleWriterRole, Grants: grants, } return ac.DeclareFixedRoles(bundleWriter, bundleReader) }
pkg/services/supportbundles/supportbundlesimpl/models.go
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.00017426097474526614, 0.00017035110795404762, 0.0001648854959057644, 0.0001712349767331034, 0.000003223904514015885 ]
{ "id": 11, "code_window": [ "SectionNavToggle.displayName = 'SectionNavToggle';\n", "\n", "const getStyles = (theme: GrafanaTheme2) => ({\n", " icon: css({\n", " backgroundColor: theme.colors.background.secondary,\n", " border: `1px solid ${theme.colors.border.weak}`,\n", " borderRadius: '50%',\n", " marginRight: 0,\n", " zIndex: 1,\n", " }),\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " color: theme.colors.text.secondary,\n" ], "file_path": "public/app/core/components/PageNew/SectionNavToggle.tsx", "type": "replace", "edit_start_line_idx": 33 }
{ "plugins": [] }
plugins-bundled/external.json
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.00017004854453261942, 0.00017004854453261942, 0.00017004854453261942, 0.00017004854453261942, 0 ]
{ "id": 12, "code_window": [ " marginRight: 0,\n", " zIndex: 1,\n", " }),\n", "});" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ " iconExpanded: css({\n", " rotate: '180deg',\n", " }),\n" ], "file_path": "public/app/core/components/PageNew/SectionNavToggle.tsx", "type": "add", "edit_start_line_idx": 39 }
import { css, cx } from '@emotion/css'; import React, { useEffect, useState } from 'react'; import { useLocalStorage } from 'react-use'; import { NavModel, GrafanaTheme2 } from '@grafana/data'; import { useStyles2, CustomScrollbar, useTheme2 } from '@grafana/ui'; import { SectionNavItem } from './SectionNavItem'; import { SectionNavToggle } from './SectionNavToggle'; export interface Props { model: NavModel; } export function SectionNav({ model }: Props) { const styles = useStyles2(getStyles); const { isExpanded, onToggleSectionNav } = useSectionNavState(); if (!Boolean(model.main?.children?.length)) { return null; } return ( <> <nav className={cx(styles.nav, { [styles.navExpanded]: isExpanded, })} > <CustomScrollbar showScrollIndicators> <div className={styles.items} role="tablist"> <SectionNavItem item={model.main} isSectionRoot /> </div> </CustomScrollbar> </nav> <SectionNavToggle className={styles.collapseIcon} isExpanded={Boolean(isExpanded)} onClick={onToggleSectionNav} /> </> ); } function useSectionNavState() { const theme = useTheme2(); const isSmallScreen = window.matchMedia(`(max-width: ${theme.breakpoints.values.lg}px)`).matches; const [navExpandedPreference, setNavExpandedPreference] = useLocalStorage<boolean>( 'grafana.sectionNav.expanded', !isSmallScreen ); const [isExpanded, setIsExpanded] = useState(!isSmallScreen && navExpandedPreference); useEffect(() => { const mediaQuery = window.matchMedia(`(max-width: ${theme.breakpoints.values.lg}px)`); const onMediaQueryChange = (e: MediaQueryListEvent) => setIsExpanded(e.matches ? false : navExpandedPreference); mediaQuery.addEventListener('change', onMediaQueryChange); return () => mediaQuery.removeEventListener('change', onMediaQueryChange); }, [navExpandedPreference, theme.breakpoints.values.lg]); const onToggleSectionNav = () => { setNavExpandedPreference(!isExpanded); setIsExpanded(!isExpanded); }; return { isExpanded, onToggleSectionNav }; } const getStyles = (theme: GrafanaTheme2) => { return { nav: css({ display: 'flex', flexDirection: 'column', background: theme.colors.background.canvas, flexShrink: 0, transition: theme.transitions.create(['width', 'max-height']), maxHeight: 0, visibility: 'hidden', [theme.breakpoints.up('md')]: { width: 0, maxHeight: 'unset', }, }), navExpanded: css({ maxHeight: '50vh', visibility: 'visible', [theme.breakpoints.up('md')]: { width: '250px', maxHeight: 'unset', }, }), items: css({ display: 'flex', flexDirection: 'column', padding: theme.spacing(2, 1, 2, 2), minWidth: '250px', [theme.breakpoints.up('md')]: { padding: theme.spacing(4.5, 1, 2, 2), }, }), collapseIcon: css({ border: `1px solid ${theme.colors.border.weak}`, left: '50%', transform: 'translate(-50%, 50%) rotate(90deg)', top: theme.spacing(0), [theme.breakpoints.up('md')]: { transform: 'translateX(50%)', top: theme.spacing(8), left: theme.spacing(1), right: theme.spacing(-1), }, }), }; };
public/app/core/components/PageNew/SectionNav.tsx
1
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.0002331400610273704, 0.00017710014071781188, 0.00016652060730848461, 0.00016840970783960074, 0.000019062279534409754 ]
{ "id": 12, "code_window": [ " marginRight: 0,\n", " zIndex: 1,\n", " }),\n", "});" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ " iconExpanded: css({\n", " rotate: '180deg',\n", " }),\n" ], "file_path": "public/app/core/components/PageNew/SectionNavToggle.tsx", "type": "add", "edit_start_line_idx": 39 }
package migrator import ( "testing" "github.com/stretchr/testify/require" ) func TestUpsertMultiple(t *testing.T) { tests := []struct { name string keyCols []string updateCols []string count int expectedErr bool expectedPostgresQuery string expectedMySQLQuery string expectedSQLiteQuery string }{ { "upsert one", []string{"key1", "key2"}, []string{"key1", "key2", "val1", "val2"}, 1, false, "INSERT INTO test_table (\"key1\", \"key2\", \"val1\", \"val2\") VALUES ($1, $2, $3, $4) ON CONFLICT (\"key1\", \"key2\") DO UPDATE SET \"key1\"=EXCLUDED.\"key1\", \"key2\"=EXCLUDED.\"key2\", \"val1\"=EXCLUDED.\"val1\", \"val2\"=EXCLUDED.\"val2\";", "INSERT INTO test_table (`key1`, `key2`, `val1`, `val2`) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE `key1`=VALUES(`key1`), `key2`=VALUES(`key2`), `val1`=VALUES(`val1`), `val2`=VALUES(`val2`)", "INSERT INTO test_table (`key1`, `key2`, `val1`, `val2`) VALUES (?, ?, ?, ?) ON CONFLICT(`key1`, `key2`) DO UPDATE SET `key1`=excluded.`key1`, `key2`=excluded.`key2`, `val1`=excluded.`val1`, `val2`=excluded.`val2`", }, { "upsert two", []string{"key1", "key2"}, []string{"key1", "key2", "val1", "val2"}, 2, false, "INSERT INTO test_table (\"key1\", \"key2\", \"val1\", \"val2\") VALUES ($1, $2, $3, $4), ($5, $6, $7, $8) ON CONFLICT (\"key1\", \"key2\") DO UPDATE SET \"key1\"=EXCLUDED.\"key1\", \"key2\"=EXCLUDED.\"key2\", \"val1\"=EXCLUDED.\"val1\", \"val2\"=EXCLUDED.\"val2\";", "INSERT INTO test_table (`key1`, `key2`, `val1`, `val2`) VALUES (?, ?, ?, ?), (?, ?, ?, ?) ON DUPLICATE KEY UPDATE `key1`=VALUES(`key1`), `key2`=VALUES(`key2`), `val1`=VALUES(`val1`), `val2`=VALUES(`val2`)", "INSERT INTO test_table (`key1`, `key2`, `val1`, `val2`) VALUES (?, ?, ?, ?), (?, ?, ?, ?) ON CONFLICT(`key1`, `key2`) DO UPDATE SET `key1`=excluded.`key1`, `key2`=excluded.`key2`, `val1`=excluded.`val1`, `val2`=excluded.`val2`", }, { "count error", []string{"key1", "key2"}, []string{"key1", "key2", "val1", "val2"}, 0, true, "", "", "", }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { var db Dialect db = &PostgresDialect{} q, err := db.UpsertMultipleSQL("test_table", tc.keyCols, tc.updateCols, tc.count) require.True(t, (err != nil) == tc.expectedErr) require.Equal(t, tc.expectedPostgresQuery, q, "Postgres query incorrect") db = &MySQLDialect{} q, err = db.UpsertMultipleSQL("test_table", tc.keyCols, tc.updateCols, tc.count) require.True(t, (err != nil) == tc.expectedErr) require.Equal(t, tc.expectedMySQLQuery, q, "MySQL query incorrect") db = &SQLite3{} q, err = db.UpsertMultipleSQL("test_table", tc.keyCols, tc.updateCols, tc.count) require.True(t, (err != nil) == tc.expectedErr) require.Equal(t, tc.expectedSQLiteQuery, q, "SQLite query incorrect") }) } }
pkg/services/sqlstore/migrator/upsert_test.go
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.00019846540817525238, 0.00017170266073662788, 0.00016445464279968292, 0.0001686659816186875, 0.000010337473213439807 ]
{ "id": 12, "code_window": [ " marginRight: 0,\n", " zIndex: 1,\n", " }),\n", "});" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ " iconExpanded: css({\n", " rotate: '180deg',\n", " }),\n" ], "file_path": "public/app/core/components/PageNew/SectionNavToggle.tsx", "type": "add", "edit_start_line_idx": 39 }
package main import ( "flag" "fmt" "log" "os" ) func main() { var version string var whatsNewURL string var releaseNotesURL string var dryRun bool var enterprise bool var nightly bool var apiKey string flag.StringVar(&version, "version", "", "Grafana version (ex: --version v5.2.0-beta1)") flag.StringVar(&whatsNewURL, "wn", "", "What's new url (ex: --wn http://docs.grafana.org/guides/whats-new-in-v5-2/)") flag.StringVar(&releaseNotesURL, "rn", "", "Grafana version (ex: --rn https://community.grafana.com/t/release-notes-v5-2-x/7894)") flag.StringVar(&apiKey, "apikey", "", "Grafana.com API key (ex: --apikey ABCDEF)") flag.BoolVar(&dryRun, "dry-run", false, "--dry-run") flag.BoolVar(&enterprise, "enterprise", false, "--enterprise") flag.BoolVar(&nightly, "nightly", false, "--nightly (default: false)") flag.Parse() if len(os.Args) == 1 { fmt.Println("Usage: go run publisher.go main.go --version <v> --wn <what's new url> --rn <release notes url> --apikey <api key> --dry-run false --enterprise false --nightly false") fmt.Println("example: go run publisher.go main.go --version v5.2.0-beta2 --wn http://docs.grafana.org/guides/whats-new-in-v5-2/ --rn https://community.grafana.com/t/release-notes-v5-2-x/7894 --apikey ASDF123 --dry-run --enterprise") os.Exit(1) } if dryRun { log.Println("Dry-run has been enabled.") } var baseURL string var builder releaseBuilder var product string archiveProviderRoot := "https://dl.grafana.com" buildArtifacts := completeBuildArtifactConfigurations if enterprise { product = "grafana-enterprise" baseURL = createBaseURL(archiveProviderRoot, "enterprise", product, nightly) } else { product = "grafana" baseURL = createBaseURL(archiveProviderRoot, "oss", product, nightly) } builder = releaseFromExternalContent{ getter: getHTTPContents{}, rawVersion: version, artifactConfigurations: buildArtifacts, } p := publisher{ apiKey: apiKey, apiURI: "https://grafana.com/api", product: product, dryRun: dryRun, enterprise: enterprise, baseArchiveURL: baseURL, builder: builder, } if err := p.doRelease(whatsNewURL, releaseNotesURL, nightly); err != nil { log.Fatalf("error: %v", err) } } func createBaseURL(root string, bucketName string, product string, nightly bool) string { var subPath string if nightly { subPath = "main" } else { subPath = "release" } return fmt.Sprintf("%s/%s/%s/%s", root, bucketName, subPath, product) }
scripts/build/release_publisher/main.go
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.00017852935707196593, 0.00017030868912115693, 0.0001669970079092309, 0.0001694912207312882, 0.0000032602140436210902 ]
{ "id": 12, "code_window": [ " marginRight: 0,\n", " zIndex: 1,\n", " }),\n", "});" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ " iconExpanded: css({\n", " rotate: '180deg',\n", " }),\n" ], "file_path": "public/app/core/components/PageNew/SectionNavToggle.tsx", "type": "add", "edit_start_line_idx": 39 }
--- aliases: - ../../http_api/user/ description: Grafana User HTTP API keywords: - grafana - http - documentation - api - user title: User HTTP API --- # User API > If you are running Grafana Enterprise, for some endpoints you'll need to have specific permissions. Refer to [Role-based access control permissions]({{< relref "../../administration/roles-and-permissions/access-control/custom-role-actions-scopes/" >}}) for more information. ## Search Users `GET /api/users?perpage=10&page=1` **Required permissions** See note in the [introduction]({{< ref "#user-api" >}}) for an explanation. | Action | Scope | | ---------- | --------------- | | users:read | global.users:\* | **Example Request**: ```http GET /api/users HTTP/1.1 Accept: application/json Content-Type: application/json Authorization: Basic YWRtaW46YWRtaW4= ``` Default value for the `perpage` parameter is `1000` and for the `page` parameter is `1`. Requires basic authentication and that the authenticated user is a Grafana Admin. **Example Response**: ```http HTTP/1.1 200 Content-Type: application/json [ { "id": 1, "name": "Admin", "login": "admin", "email": "[email protected]", "isAdmin": true, "isDisabled": false, "lastSeenAt": "2020-04-10T20:29:27+03:00", "lastSeenAtAge': "2m", "authLabels": ["OAuth"] }, { "id": 2, "name": "User", "login": "user", "email": "[email protected]", "isAdmin": false, "isDisabled": false, "lastSeenAt": "2020-01-24T12:38:47+02:00", "lastSeenAtAge": "2M", "authLabels": [] } ] ``` ## Search Users with Paging `GET /api/users/search?perpage=10&page=1&query=mygraf` **Required permissions** See note in the [introduction]({{< ref "#user-api" >}}) for an explanation. | Action | Scope | | ---------- | --------------- | | users:read | global.users:\* | **Example Request**: ```http GET /api/users/search?perpage=10&page=1&query=mygraf HTTP/1.1 Accept: application/json Content-Type: application/json Authorization: Basic YWRtaW46YWRtaW4= ``` Default value for the `perpage` parameter is `1000` and for the `page` parameter is `1`. The `totalCount` field in the response can be used for pagination of the user list E.g. if `totalCount` is equal to 100 users and the `perpage` parameter is set to 10 then there are 10 pages of users. The `query` parameter is optional and it will return results where the query value is contained in one of the `name`, `login` or `email` fields. Query values with spaces need to be URL encoded e.g. `query=Jane%20Doe`. Requires basic authentication and that the authenticated user is a Grafana Admin. **Example Response**: ```http HTTP/1.1 200 Content-Type: application/json { "totalCount": 2, "users": [ { "id": 1, "name": "Admin", "login": "admin", "email": "[email protected]", "isAdmin": true, "isDisabled": false, "lastSeenAt": "2020-04-10T20:29:27+03:00", "lastSeenAtAge': "2m", "authLabels": ["OAuth"] }, { "id": 2, "name": "User", "login": "user", "email": "[email protected]", "isAdmin": false, "isDisabled": false, "lastSeenAt": "2020-01-24T12:38:47+02:00", "lastSeenAtAge": "2M", "authLabels": [] } ], "page": 1, "perPage": 10 } ``` ## Get single user by Id `GET /api/users/:id` **Required permissions** See note in the [introduction]({{< ref "#user-api" >}}) for an explanation. | Action | Scope | | ---------- | --------------- | | users:read | global.users:\* | **Example Request**: ```http GET /api/users/1 HTTP/1.1 Accept: application/json Content-Type: application/json Authorization: Basic YWRtaW46YWRtaW4= ``` Requires basic authentication and that the authenticated user is a Grafana Admin. **Example Response**: ```http HTTP/1.1 200 Content-Type: application/json { "id": "1", "email": "[email protected]", "name": "admin", "login": "admin", "theme": "light", "orgId": 1, "isGrafanaAdmin": true, "isDisabled": true, "isExternal": false, "authLabels": [], "updatedAt": "2019-09-09T11:31:26+01:00", "createdAt": "2019-09-09T11:31:26+01:00", "avatarUrl": "" } ``` ## Get single user by Username(login) or Email `GET /api/users/[email protected]` **Required permissions** See note in the [introduction]({{< ref "#user-api" >}}) for an explanation. | Action | Scope | | ---------- | --------------- | | users:read | global.users:\* | **Example Request using the email as option**: ```http GET /api/users/[email protected] HTTP/1.1 Accept: application/json Content-Type: application/json Authorization: Bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk ``` **Example Request using the username as option**: ```http GET /api/users/lookup?loginOrEmail=admin HTTP/1.1 Accept: application/json Content-Type: application/json Authorization: Basic YWRtaW46YWRtaW4= ``` Requires basic authentication and that the authenticated user is a Grafana Admin. **Example Response**: ```http HTTP/1.1 200 Content-Type: application/json { "id": 1, "email": "[email protected]", "name": "admin", "login": "admin", "theme": "light", "orgId": 1, "isGrafanaAdmin": true, "isDisabled": false, "isExternal": false, "authLabels": null, "updatedAt": "2019-09-25T14:44:37+01:00", "createdAt": "2019-09-25T14:44:37+01:00", "avatarUrl":"" } ``` ## User Update `PUT /api/users/:id` **Required permissions** See note in the [introduction]({{< ref "#user-api" >}}) for an explanation. | Action | Scope | | ----------- | --------------- | | users:write | global.users:\* | **Example Request**: ```http PUT /api/users/2 HTTP/1.1 Accept: application/json Content-Type: application/json Authorization: Basic YWRtaW46YWRtaW4= { "email":"[email protected]", "name":"User2", "login":"user", "theme":"light" } ``` Requires basic authentication and that the authenticated user is a Grafana Admin. **Example Response**: ```http HTTP/1.1 200 Content-Type: application/json {"message":"User updated"} ``` ## Get Organizations for user `GET /api/users/:id/orgs` **Required permissions** See note in the [introduction]({{< ref "#user-api" >}}) for an explanation. | Action | Scope | | ---------- | --------------- | | users:read | global.users:\* | **Example Request**: ```http GET /api/users/1/orgs HTTP/1.1 Accept: application/json Content-Type: application/json Authorization: Basic YWRtaW46YWRtaW4= ``` Requires basic authentication and that the authenticated user is a Grafana Admin. **Example Response**: ```http HTTP/1.1 200 Content-Type: application/json [ { "orgId":1, "name":"Main Org.", "role":"Admin" } ] ``` ## Get Teams for user `GET /api/users/:id/teams` **Required permissions** See note in the [introduction]({{< ref "#user-api" >}}) for an explanation. | Action | Scope | | ---------- | --------------- | | users:read | global.users:\* | | teams:read | teams:\* | **Example Request**: ```http GET /api/users/1/teams HTTP/1.1 Accept: application/json Content-Type: application/json Authorization: Basic YWRtaW46YWRtaW4= ``` Requires basic authentication and that the authenticated user is a Grafana Admin. **Example Response**: ```http HTTP/1.1 200 Content-Type: application/json [ { "id":1, "orgId":1, "name":"team1", "email":"", "avatarUrl":"/avatar/3fcfe295eae3bcb67a49349377428a66", "memberCount":1 } ] ``` ## User ## Actual User `GET /api/user` **Example Request**: ```http GET /api/user HTTP/1.1 Accept: application/json Content-Type: application/json Authorization: Basic YWRtaW46YWRtaW4= ``` Requires basic authentication. **Example Response**: ```http HTTP/1.1 200 Content-Type: application/json { "id":1, "email":"[email protected]", "name":"Admin", "login":"admin", "theme":"light", "orgId":1, "isGrafanaAdmin":true, "isDisabled":false "isExternal": false, "authLabels": [], "updatedAt": "2019-09-09T11:31:26+01:00", "createdAt": "2019-09-09T11:31:26+01:00", "avatarUrl": "" } ``` ## Change Password `PUT /api/user/password` Changes the password for the user. Requires basic authentication. **Example Request**: ```http PUT /api/user/password HTTP/1.1 Accept: application/json Content-Type: application/json Authorization: Basic YWRtaW46YWRtaW4= { "oldPassword": "old_password", "newPassword": "new_password" } ``` **Example Response**: ```http HTTP/1.1 200 Content-Type: application/json {"message":"User password changed"} ``` **Change Password with a Script** If you need to change a password with a script, here is an example of changing the Admin password using curl with basic auth: ```bash curl -X PUT -H "Content-Type: application/json" -d '{ "oldPassword": "oldpass", "newPassword": "newpass", "confirmNew": "newpass" }' http://admin:oldpass@<your_grafana_host>:3000/api/user/password ``` ## Switch user context for a specified user `POST /api/users/:userId/using/:organizationId` Switch user context to the given organization. Requires basic authentication and that the authenticated user is a Grafana Admin. **Example Request**: ```http POST /api/users/7/using/2 HTTP/1.1 Authorization: Basic YWRtaW46YWRtaW4= ``` **Example Response**: ```http HTTP/1.1 200 Content-Type: application/json {"message":"Active organization changed"} ``` ## Switch user context for signed in user `POST /api/user/using/:organizationId` Switch user context to the given organization. **Example Request**: ```http POST /api/user/using/2 HTTP/1.1 Accept: application/json Content-Type: application/json Authorization: Bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk ``` **Example Response**: ```http HTTP/1.1 200 Content-Type: application/json {"message":"Active organization changed"} ``` ## Organizations of the actual User `GET /api/user/orgs` Return a list of all organizations of the current user. Requires basic authentication. **Example Request**: ```http GET /api/user/orgs HTTP/1.1 Accept: application/json Content-Type: application/json Authorization: Basic YWRtaW46YWRtaW4= ``` **Example Response**: ```http HTTP/1.1 200 Content-Type: application/json [ { "orgId":1, "name":"Main Org.", "role":"Admin" } ] ``` ## Teams that the actual User is member of `GET /api/user/teams` Return a list of all teams that the current user is member of. **Example Request**: ```http GET /api/user/teams HTTP/1.1 Accept: application/json Content-Type: application/json Authorization: Bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk ``` **Example Response**: ```http HTTP/1.1 200 Content-Type: application/json [ { "id": 1, "orgId": 1, "name": "MyTestTeam", "email": "", "avatarUrl": "\/avatar\/3f49c15916554246daa714b9bd0ee398", "memberCount": 1 } ] ``` ## Star a dashboard `POST /api/user/stars/dashboard/:dashboardId` Stars the given Dashboard for the actual user. **Example Request**: ```http POST /api/user/stars/dashboard/1 HTTP/1.1 Accept: application/json Content-Type: application/json Authorization: Bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk ``` **Example Response**: ```http HTTP/1.1 200 Content-Type: application/json {"message":"Dashboard starred!"} ``` ## Unstar a dashboard `DELETE /api/user/stars/dashboard/:dashboardId` Deletes the starring of the given Dashboard for the actual user. **Example Request**: ```http DELETE /api/user/stars/dashboard/1 HTTP/1.1 Accept: application/json Content-Type: application/json Authorization: Bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk ``` **Example Response**: ```http HTTP/1.1 200 Content-Type: application/json {"message":"Dashboard unstarred"} ``` ## Auth tokens of the actual User `GET /api/user/auth-tokens` Return a list of all auth tokens (devices) that the actual user currently have logged in from. **Example Request**: ```http GET /api/user/auth-tokens HTTP/1.1 Accept: application/json Content-Type: application/json Authorization: Bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk ``` **Example Response**: ```http HTTP/1.1 200 Content-Type: application/json [ { "id": 361, "isActive": true, "clientIp": "127.0.0.1", "browser": "Chrome", "browserVersion": "72.0", "os": "Linux", "osVersion": "", "device": "Other", "createdAt": "2019-03-05T21:22:54+01:00", "seenAt": "2019-03-06T19:41:06+01:00" }, { "id": 364, "isActive": false, "clientIp": "127.0.0.1", "browser": "Mobile Safari", "browserVersion": "11.0", "os": "iOS", "osVersion": "11.0", "device": "iPhone", "createdAt": "2019-03-06T19:41:19+01:00", "seenAt": "2019-03-06T19:41:21+01:00" } ] ``` ## Revoke an auth token of the actual User `POST /api/user/revoke-auth-token` Revokes the given auth token (device) for the actual user. User of issued auth token (device) will no longer be logged in and will be required to authenticate again upon next activity. **Example Request**: ```http POST /api/user/revoke-auth-token HTTP/1.1 Accept: application/json Content-Type: application/json Authorization: Bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk { "authTokenId": 364 } ``` **Example Response**: ```http HTTP/1.1 200 Content-Type: application/json { "message": "User auth token revoked" } ```
docs/sources/developers/http_api/user.md
0
https://github.com/grafana/grafana/commit/253f9657cb8d2a184ab3491323783d709893cb0d
[ 0.00031832046806812286, 0.0001710726210149005, 0.00016311780200339854, 0.00016915299056563526, 0.000018211352653452195 ]
{ "id": 0, "code_window": [ " onClose={handleClose}\n", " TransitionComponent={transition}\n", " message=\"I love snacks\"\n", " />\n", " </div>\n", " );\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " key={transition ? transition.name : ''}\n" ], "file_path": "docs/src/pages/components/snackbars/DirectionSnackbar.js", "type": "add", "edit_start_line_idx": 45 }
import React from 'react'; import Button from '@material-ui/core/Button'; import Snackbar from '@material-ui/core/Snackbar'; import Slide, { SlideProps } from '@material-ui/core/Slide'; type TransitionProps = Omit<SlideProps, 'direction'>; function TransitionLeft(props: TransitionProps) { return <Slide {...props} direction="left" />; } function TransitionUp(props: TransitionProps) { return <Slide {...props} direction="up" />; } function TransitionRight(props: TransitionProps) { return <Slide {...props} direction="right" />; } function TransitionDown(props: TransitionProps) { return <Slide {...props} direction="down" />; } export default function DirectionSnackbar() { const [open, setOpen] = React.useState(false); const [transition, setTransition] = React.useState< React.ComponentType<TransitionProps> | undefined >(undefined); const handleClick = (Transition: React.ComponentType<TransitionProps>) => () => { setTransition(() => Transition); setOpen(true); }; const handleClose = () => { setOpen(false); }; return ( <div> <Button onClick={handleClick(TransitionLeft)}>Right</Button> <Button onClick={handleClick(TransitionUp)}>Up</Button> <Button onClick={handleClick(TransitionRight)}>Left</Button> <Button onClick={handleClick(TransitionDown)}>Down</Button> <Snackbar open={open} onClose={handleClose} TransitionComponent={transition} message="I love snacks" /> </div> ); }
docs/src/pages/components/snackbars/DirectionSnackbar.tsx
1
https://github.com/mui/material-ui/commit/afd485346345d319c062b84e07d97a6e4d41e20c
[ 0.2974858582019806, 0.05404949560761452, 0.0001738515420584008, 0.002518649911507964, 0.10907519608736038 ]
{ "id": 0, "code_window": [ " onClose={handleClose}\n", " TransitionComponent={transition}\n", " message=\"I love snacks\"\n", " />\n", " </div>\n", " );\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " key={transition ? transition.name : ''}\n" ], "file_path": "docs/src/pages/components/snackbars/DirectionSnackbar.js", "type": "add", "edit_start_line_idx": 45 }
--- title: Text Field React-Komponente components: FilledInput, FormControl, FormHelperText, Input, InputAdornment, InputBase, InputLabel, OutlinedInput, TextField --- # Textfeld <p class="description">Text Felder lassen Nutzer Text eingeben und bearbeiten.</p> [Text fields](https://material.io/design/components/text-fields.html) allow users to enter text into a UI. They typically appear in forms and dialogs. ## Textfeld Die `TextField` Wrapper-Komponente ist ein vollständiges Formularsteuerelement, das eine Beschriftung, Eingabe und Hilfetext enthält. It supports standard, outlined and filled styling. {{"demo": "pages/components/text-fields/BasicTextFields.js"}} **Note:** The standard variant of the `TextField` is no longer documented in the [Material Design guidelines](https://material.io/) ([here's why](https://medium.com/google-design/the-evolution-of-material-designs-text-fields-603688b3fe03)), but Material-UI will continue to support it. ## Form props Standard form attributes are supported e.g. `required`, `disabled`, `type`, etc. as well as a `helperText` which is used to give context about a field’s input, such as how the input will be used. {{"demo": "pages/components/text-fields/FormPropsTextFields.js"}} ## Validierung The `error` prop toggles the error state, the `helperText` prop can then be used to provide feedback to the user about the error. {{"demo": "pages/components/text-fields/ValidationTextFields.js"}} ## Mehrzeilig The `multiline` prop transforms the text field into a [textarea](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea) or a [TextareaAutosize](/components/textarea-autosize/). {{"demo": "pages/components/text-fields/MultilineTextFields.js"}} ## Selects (auswähler) The `select` prop makes the text field use the [Select](/components/selects/) component internally. {{"demo": "pages/components/text-fields/SelectTextFields.js"}} ## Icons There are multiple ways to display an icon with a text field. {{"demo": "pages/components/text-fields/InputWithIcon.js"}} ### Eingabeverzierungen The main way is with an `InputAdornment`. This can be used to add a prefix, a suffix or an action to an input. Sie können beispielsweise eine Symbolschaltfläche verwenden, um das Kennwort ein- oder auszublenden. {{"demo": "pages/components/text-fields/InputAdornments.js"}} ## Größen Fancy smaller inputs? Verwenden Sie die `size` Prop. {{"demo": "pages/components/text-fields/TextFieldSizes.js"}} ## Layout `margin` prop can be used to alter the vertical spacing of inputs. Using `none` (default) will not apply margins to the `FormControl`, whereas `dense` and `normal` will. `dense` and `normal` alter other styles to meet the specification. `fullWidth` can be used to make the input take up the full width of its container. {{"demo": "pages/components/text-fields/LayoutTextFields.js"}} ## Uncontrolled vs Controlled The component can be controlled or uncontrolled. {{"demo": "pages/components/text-fields/StateTextFields.js"}} ## Komponenten Das `Textfeld` besteht aus kleineren Komponenten ( [`FormControl`](/api/form-control/), [`Input`](/api/input/), [`FilledInput`](/api/filled-input/), [`InputLabel`](/api/input-label/), [`OutlinedInput`](/api/outlined-input/), und [`FormHelperText`](/api/form-helper-text/) ) welche Sie direkt nutzen können, um Ihre Formulareingaben erheblich anzupassen. Möglicherweise haben Sie auch festgestellt, dass einige native HTML-Eingabeeigenschaften in der Komponente `TextField` fehlen. Das war Absicht. Die Komponente kümmert sich um die am häufigsten verwendeten Eigenschaften. Anschließend muss der Benutzer die darunter liegende Komponente verwenden, die in der folgenden Demo gezeigt wird. Sie können jedoch `inputProps` (und `InputProps`, `InputLabelProps` Eigenschaften) verwenden, wenn Sie einiges an Boilerplate vermeiden möchten. {{"demo": "pages/components/text-fields/ComposedTextField.js"}} ## Eingaben {{"demo": "pages/components/text-fields/Inputs.js"}} ## Farbe (Color) The `color` prop changes the highlight color of the text field when focused. {{"demo": "pages/components/text-fields/ColorTextFields.js"}} ## Benutzerdefinierte Eingabe Hier sind einige Beispiele, wie man die Komponente anpassen kann. Mehr dazu erfahren Sie auf der [Überschreibungsdokumentationsseite](/customization/components/). {{"demo": "pages/components/text-fields/CustomizedInputs.js"}} Die Anpassung endet nicht bei CSS. Sie können Komposition verwenden, um benutzerdefinierte Komponenten zu erstellen und Ihrer App ein einzigartiges Gefühl zu verleihen. Nachfolgend ein Beispiel mit der [`InputBase`](/api/input-base/) Komponente, die von Google Maps inspiriert wurde. {{"demo": "pages/components/text-fields/CustomizedInputBase.js", "bg": true}} 👑 If you are looking for inspiration, you can check [MUI Treasury's customization examples](https://mui-treasury.com/styles/text-field). ## Einschränkungen ### Shrink Der Status des Eingabe-Labels "Verkleinern" ist nicht immer korrekt. Das Eingabeetikett soll schrumpfen, sobald die Eingabe etwas anzeigt. Unter bestimmten Umständen können wir den Status "Schrumpfen" nicht ermitteln (Zahleneingabe, Datumseingabe, Stripe-Eingabe). Sie könnten eine Überlappung bemerken. ![schrumpfen](/static/images/text-fields/shrink.png) Um das Problem zu umgehen, können Sie den Status des Labels "verkleinern" erzwingen. ```jsx <TextField InputLabelProps={{ shrink: true }} /> ``` oder ```jsx <InputLabel shrink>Contagem</InputLabel> ``` ### Floating label The floating label is absolutely positioned, it won't impact the layout of the page. You need to make sure that the input is larger than the label to display correctly. ## Integration with 3rd party input libraries Sie können Bibliotheken von Drittanbietern verwenden, um eine Eingabe zu formatieren. Sie müssen eine benutzerdefinierte Implementierung des `<input>` -Elements mit der `inputComponent` -Eigenschaft bereitstellen. Die folgende Demo verwendet die Bibliotheken [react-text-mask](https://github.com/text-mask/text-mask) und [react-number-format](https://github.com/s-yadav/react-number-format). The same concept could be applied to [e.g. react-stripe-element](https://github.com/mui-org/material-ui/issues/16037). {{"demo": "pages/components/text-fields/FormattedInputs.js"}} Die bereitgestellte Eingabekomponente sollte die Eigenschaft `inputRef` haben. The property should be called with a value that implements the following interface: ```ts interface InputElement { focus(): void; value?: string; } ``` ```jsx function MyInputComponent(props) { const { component: Component, inputRef, ...other } = props; // implement `InputElement` interface React.useImperativeHandle(inputRef, () => ({ focus: () => { // logic to focus the rendered component from 3rd party belongs here }, // hiding the value e.g. react-stripe-elements })); // `Component` will be your `SomeThirdPartyComponent` from below return <Component {...other} />; } // usage <TextField InputProps={{ inputComponent: MyInputComponent, inputProps: { component: SomeThirdPartyComponent }, }} />; ``` ## Barrierefreiheit In order for the text field to be accessible, **the input should be linked to the label and the helper text**. The underlying DOM nodes should have this structure: ```jsx <div class="form-control"> <label for="my-input">E-Mail-Adresse</label> <input id="my-input" aria-describedby="my-helper-text" /> <span id="my-helper-text">Wir werden Ihre E-Mail niemals teilen.</span> </div> ``` - Wenn Sie die Komponente `TextField` verwenden, müssen Sie nur eine eindeutige `Id`angeben. - Wenn Sie die Komponente zusammenstellen: ```jsx <FormControl> <InputLabel htmlFor="my-input">E-mail-Adresse</InputLabel> <Input id="my-input" aria-describedby="my-helper-text" /> <FormHelperText id="my-helper-text">Wir werden Ihre E-Mail niemals teilen.</FormHelperText> </FormControl> ``` ## Ergänzende Projekte Für fortgeschrittenere Anwendungsfälle können Ihnen folgende Projekte helfen: - [formik-material-ui](https://github.com/stackworx/formik-material-ui) Bindings for using Material-UI with [formik](https://jaredpalmer.com/formik). - [redux-form-material-ui](https://github.com/erikras/redux-form-material-ui) Bindings for using Material-UI with [Redux Form](https://redux-form.com/). - [mui-rff](https://github.com/lookfirst/mui-rff) Bindings for using Material-UI with [React Final Form](https://final-form.org/react).
docs/src/pages/components/text-fields/text-fields-de.md
0
https://github.com/mui/material-ui/commit/afd485346345d319c062b84e07d97a6e4d41e20c
[ 0.000192785490071401, 0.00016879558097571135, 0.0001621898845769465, 0.00016685534501448274, 0.000006471350388892461 ]
{ "id": 0, "code_window": [ " onClose={handleClose}\n", " TransitionComponent={transition}\n", " message=\"I love snacks\"\n", " />\n", " </div>\n", " );\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " key={transition ? transition.name : ''}\n" ], "file_path": "docs/src/pages/components/snackbars/DirectionSnackbar.js", "type": "add", "edit_start_line_idx": 45 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM8.75 13.68c-.13.43-.62.63-1.02.45a.749.749 0 01-.4-.9c.12-.41.18-.83.17-1.24-.01-.41-.06-.8-.17-1.18-.1-.36.06-.75.4-.9.42-.19.91.04 1.04.49.15.51.22 1.03.23 1.57 0 .56-.08 1.14-.25 1.71zm3.14 1.59c-.17.41-.67.57-1.06.35-.33-.19-.46-.59-.32-.94.33-.77.49-1.63.49-2.56 0-.96-.18-1.89-.53-2.78-.14-.36.02-.76.36-.94.39-.2.87-.02 1.03.39.42 1.06.63 2.18.63 3.33.02 1.13-.19 2.19-.6 3.15zM15 16.6c-.17.4-.64.58-1.02.39-.35-.17-.52-.59-.37-.95.59-1.39.89-2.75.89-4.06 0-1.31-.3-2.65-.88-4.01-.16-.36.01-.78.36-.95.39-.2.85-.02 1.02.38.66 1.54 1 3.08 1 4.58s-.34 3.06-1 4.62z" /> , 'ContactlessRounded');
packages/material-ui-icons/src/ContactlessRounded.js
0
https://github.com/mui/material-ui/commit/afd485346345d319c062b84e07d97a6e4d41e20c
[ 0.0003036503621842712, 0.0003036503621842712, 0.0003036503621842712, 0.0003036503621842712, 0 ]
{ "id": 0, "code_window": [ " onClose={handleClose}\n", " TransitionComponent={transition}\n", " message=\"I love snacks\"\n", " />\n", " </div>\n", " );\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " key={transition ? transition.name : ''}\n" ], "file_path": "docs/src/pages/components/snackbars/DirectionSnackbar.js", "type": "add", "edit_start_line_idx": 45 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M20 12c0-2.54-1.19-4.81-3.04-6.27l-.68-4.06C16.12.71 15.28 0 14.31 0H9.7c-.98 0-1.82.71-1.98 1.67l-.67 4.06C5.19 7.19 4 9.45 4 12s1.19 4.81 3.05 6.27l.67 4.06c.16.96 1 1.67 1.98 1.67h4.61c.98 0 1.81-.71 1.97-1.67l.68-4.06C18.81 16.81 20 14.54 20 12zM6 12c0-3.31 2.69-6 6-6s6 2.69 6 6-2.69 6-6 6-6-2.69-6-6z" /> , 'WatchRounded');
packages/material-ui-icons/src/WatchRounded.js
0
https://github.com/mui/material-ui/commit/afd485346345d319c062b84e07d97a6e4d41e20c
[ 0.00017026271962095052, 0.00017026271962095052, 0.00017026271962095052, 0.00017026271962095052, 0 ]
{ "id": 1, "code_window": [ " open={open}\n", " onClose={handleClose}\n", " TransitionComponent={transition}\n", " message=\"I love snacks\"\n", " />\n", " </div>\n", " );\n", "}" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " key={transition ? transition.name : ''}\n" ], "file_path": "docs/src/pages/components/snackbars/DirectionSnackbar.tsx", "type": "add", "edit_start_line_idx": 49 }
import React from 'react'; import Button from '@material-ui/core/Button'; import Snackbar from '@material-ui/core/Snackbar'; import Fade from '@material-ui/core/Fade'; import Slide from '@material-ui/core/Slide'; import Grow from '@material-ui/core/Grow'; import { TransitionProps } from '@material-ui/core/transitions'; function SlideTransition(props: TransitionProps) { return <Slide {...props} direction="up" />; } function GrowTransition(props: TransitionProps) { return <Grow {...props} />; } export default function TransitionsSnackbar() { const [state, setState] = React.useState<{ open: boolean; Transition: React.ComponentType<TransitionProps & { children?: React.ReactElement<any, any> }>; }>({ open: false, Transition: Fade, }); const handleClick = ( Transition: React.ComponentType<TransitionProps & { children?: React.ReactElement<any, any> }>, ) => () => { setState({ open: true, Transition, }); }; const handleClose = () => { setState({ ...state, open: false, }); }; return ( <div> <Button onClick={handleClick(GrowTransition)}>Grow Transition</Button> <Button onClick={handleClick(Fade)}>Fade Transition</Button> <Button onClick={handleClick(SlideTransition)}>Slide Transition</Button> <Snackbar open={state.open} onClose={handleClose} TransitionComponent={state.Transition} message="I love snacks" /> </div> ); }
docs/src/pages/components/snackbars/TransitionsSnackbar.tsx
1
https://github.com/mui/material-ui/commit/afd485346345d319c062b84e07d97a6e4d41e20c
[ 0.09738769382238388, 0.018551237881183624, 0.0005441823741421103, 0.0021683271043002605, 0.03532500937581062 ]
{ "id": 1, "code_window": [ " open={open}\n", " onClose={handleClose}\n", " TransitionComponent={transition}\n", " message=\"I love snacks\"\n", " />\n", " </div>\n", " );\n", "}" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " key={transition ? transition.name : ''}\n" ], "file_path": "docs/src/pages/components/snackbars/DirectionSnackbar.tsx", "type": "add", "edit_start_line_idx": 49 }
import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { withStyles } from '@material-ui/core/styles'; import Typography from '../components/Typography'; const styles = (theme) => ({ root: { padding: theme.spacing(2), }, error: { backgroundColor: theme.palette.error.xLight, color: theme.palette.error.dark, }, success: { backgroundColor: theme.palette.success.xLight, color: theme.palette.success.dark, }, }); function FormFeedback(props) { return ( <div className={clsx( props.classes.root, { [props.classes.error]: props.error, [props.classes.success]: props.success }, props.className, )} > <Typography color="inherit">{props.children}</Typography> </div> ); } FormFeedback.propTypes = { children: PropTypes.node, classes: PropTypes.object.isRequired, className: PropTypes.string, error: PropTypes.bool, success: PropTypes.bool, }; export default withStyles(styles)(FormFeedback);
docs/src/pages/premium-themes/onepirate/modules/form/FormFeedback.js
0
https://github.com/mui/material-ui/commit/afd485346345d319c062b84e07d97a6e4d41e20c
[ 0.00017472250328864902, 0.00017065697466023266, 0.00016382592730224133, 0.0001721516455290839, 0.000004217315108689945 ]
{ "id": 1, "code_window": [ " open={open}\n", " onClose={handleClose}\n", " TransitionComponent={transition}\n", " message=\"I love snacks\"\n", " />\n", " </div>\n", " );\n", "}" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " key={transition ? transition.name : ''}\n" ], "file_path": "docs/src/pages/components/snackbars/DirectionSnackbar.tsx", "type": "add", "edit_start_line_idx": 49 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z" /> , 'LaunchOutlined');
packages/material-ui-icons/src/LaunchOutlined.js
0
https://github.com/mui/material-ui/commit/afd485346345d319c062b84e07d97a6e4d41e20c
[ 0.000173605716554448, 0.000173605716554448, 0.000173605716554448, 0.000173605716554448, 0 ]
{ "id": 1, "code_window": [ " open={open}\n", " onClose={handleClose}\n", " TransitionComponent={transition}\n", " message=\"I love snacks\"\n", " />\n", " </div>\n", " );\n", "}" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " key={transition ? transition.name : ''}\n" ], "file_path": "docs/src/pages/components/snackbars/DirectionSnackbar.tsx", "type": "add", "edit_start_line_idx": 49 }
# 活版印刷 <p class="description">用于控制对齐,包装,重量等的常用文本实用程序的文档和示例。</p> ## 文本对齐 {{"demo": "pages/system/typography/TextAlignment.js", "defaultCodeOpen": false}} ```jsx <Box textAlign="left">… <Box textAlign="center">… <Box textAlign="right">… ``` ## 字体高度 {{"demo": "pages/system/typography/FontWeight.js", "defaultCodeOpen": false}} ```jsx <Box fontWeight="fontWeightLight">… <Box fontWeight="fontWeightRegular">… <Box fontWeight="fontWeightMedium">… <Box fontWeight={500}>… <Box fontWeight="fontWeightBold">… ``` ## 字体大小 {{"demo": "pages/system/typography/FontSize.js", "defaultCodeOpen": false}} ```jsx <Box fontSize="fontSize">… <Box fontSize="h6.fontSize">… <Box fontSize={16}>… ``` ## 字体样式 {{"demo": "pages/system/typography/FontStyle.js", "defaultCodeOpen": false}} ```jsx <Box fontStyle="normal">… <Box fontStyle="italic">… <Box fontStyle="oblique">… ``` ## 字体系列 {{"demo": "pages/system/typography/FontFamily.js", "defaultCodeOpen": false}} ```jsx <Box fontFamily="fontFamily">… <Box fontFamily="Monospace">… ``` ## 字符间距 {{"demo": "pages/system/typography/LetterSpacing.js", "defaultCodeOpen": false}} ```jsx <Box letterSpacing={6}>… <Box letterSpacing={10}>… ``` ## 行高 {{"demo": "pages/system/typography/LineHeight.js", "defaultCodeOpen": false}} ```jsx <Box lineHeight="normal">… <Box lineHeight={10}>… ``` ## API ```js import { typography } from '@material-ui/system'; ``` | 导入名称 | Prop | CSS 属性 | Theme key | |:--------------- |:--------------- |:---------------- |:---------------------------------------------------------------------- | | `fontFamily` | `fontFamily` | `font-family` | [`typography`](/customization/default-theme/?expand-path=$.typography) | | `fontSize` | `fontSize` | `font-size` | [`typography`](/customization/default-theme/?expand-path=$.typography) | | `fontStyle` | `fontStyle` | `font-style` | [`typography`](/customization/default-theme/?expand-path=$.typography) | | `fontWeight` | `fontWeight` | `font-weight` | [`typography`](/customization/default-theme/?expand-path=$.typography) | | `letterSpacing` | `letterSpacing` | `letter-spacing` | none | | `lineHeight` | `lineHeight` | `line-height` | none | | `textAlign` | `textAlign` | `text-align` | none |
docs/src/pages/system/typography/typography-zh.md
0
https://github.com/mui/material-ui/commit/afd485346345d319c062b84e07d97a6e4d41e20c
[ 0.00017682014731690288, 0.00017264153575524688, 0.00016750350187066942, 0.00017352924623992294, 0.000002672951040949556 ]
{ "id": 2, "code_window": [ " open={state.open}\n", " onClose={handleClose}\n", " TransitionComponent={state.Transition}\n", " message=\"I love snacks\"\n", " />\n", " </div>\n", " );\n", "}" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " key={state.Transition.name}\n" ], "file_path": "docs/src/pages/components/snackbars/TransitionsSnackbar.js", "type": "add", "edit_start_line_idx": 45 }
import React from 'react'; import Button from '@material-ui/core/Button'; import Snackbar from '@material-ui/core/Snackbar'; import Slide from '@material-ui/core/Slide'; function TransitionLeft(props) { return <Slide {...props} direction="left" />; } function TransitionUp(props) { return <Slide {...props} direction="up" />; } function TransitionRight(props) { return <Slide {...props} direction="right" />; } function TransitionDown(props) { return <Slide {...props} direction="down" />; } export default function DirectionSnackbar() { const [open, setOpen] = React.useState(false); const [transition, setTransition] = React.useState(undefined); const handleClick = (Transition) => () => { setTransition(() => Transition); setOpen(true); }; const handleClose = () => { setOpen(false); }; return ( <div> <Button onClick={handleClick(TransitionLeft)}>Right</Button> <Button onClick={handleClick(TransitionUp)}>Up</Button> <Button onClick={handleClick(TransitionRight)}>Left</Button> <Button onClick={handleClick(TransitionDown)}>Down</Button> <Snackbar open={open} onClose={handleClose} TransitionComponent={transition} message="I love snacks" /> </div> ); }
docs/src/pages/components/snackbars/DirectionSnackbar.js
1
https://github.com/mui/material-ui/commit/afd485346345d319c062b84e07d97a6e4d41e20c
[ 0.0424688346683979, 0.016538381576538086, 0.0016882696654647589, 0.007561917416751385, 0.016167717054486275 ]
{ "id": 2, "code_window": [ " open={state.open}\n", " onClose={handleClose}\n", " TransitionComponent={state.Transition}\n", " message=\"I love snacks\"\n", " />\n", " </div>\n", " );\n", "}" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " key={state.Transition.name}\n" ], "file_path": "docs/src/pages/components/snackbars/TransitionsSnackbar.js", "type": "add", "edit_start_line_idx": 45 }
# Server Rendering <p class="description">The most common use case for server-side rendering is to handle the initial render when a user (or search engine crawler) first requests your app.</p> When the server receives the request, it renders the required component(s) into an HTML string, and then sends it as a response to the client. From that point on, the client takes over rendering duties. ## Material-UI on the server Material-UI was designed from the ground-up with the constraint of rendering on the server, but it's up to you to make sure it's correctly integrated. It's important to provide the page with the required CSS, otherwise the page will render with just the HTML then wait for the CSS to be injected by the client, causing it to flicker (FOUC). To inject the style down to the client, we need to: 1. Create a fresh, new [`ServerStyleSheets`](/styles/api/#serverstylesheets) instance on every request. 2. Render the React tree with the server-side collector. 3. Pull the CSS out. 4. Pass the CSS along to the client. On the client side, the CSS will be injected a second time before removing the server-side injected CSS. ## Setting Up In the following recipe, we are going to look at how to set up server-side rendering. ### The theme Create a theme that will be shared between the client and the server: `theme.js` ```js import { createMuiTheme } from '@material-ui/core/styles'; import red from '@material-ui/core/colors/red'; // Create a theme instance. const theme = createMuiTheme({ palette: { primary: { main: '#556cd6', }, secondary: { main: '#19857b', }, error: { main: red.A400, }, background: { default: '#fff', }, }, }); export default theme; ``` ### The server-side The following is the outline for what the server-side is going to look like. We are going to set up an [Express middleware](https://expressjs.com/en/guide/using-middleware.html) using [app.use](https://expressjs.com/en/api.html) to handle all requests that come in to the server. If you're unfamiliar with Express or middleware, just know that the handleRender function will be called every time the server receives a request. `server.js` ```js import express from 'express'; // We are going to fill these out in the sections to follow. function renderFullPage(html, css) { /* ... */ } function handleRender(req, res) { /* ... */ } const app = express(); // This is fired every time the server-side receives a request. app.use(handleRender); const port = 3000; app.listen(port); ``` ### Handling the Request The first thing that we need to do on every request is create a new `ServerStyleSheets`. When rendering, we will wrap `App`, the root component, inside a [`StylesProvider`](/styles/api/#stylesprovider) and [`ThemeProvider`](/styles/api/#themeprovider) to make the style configuration and the `theme` available to all components in the component tree. The key step in server-side rendering is to render the initial HTML of the component **before** we send it to the client side. To do this, we use [ReactDOMServer.renderToString()](https://reactjs.org/docs/react-dom-server.html). We then get the CSS from the `sheets` using `sheets.toString()`. We will see how this is passed along in the `renderFullPage` function. ```jsx import express from 'express'; import React from 'react'; import ReactDOMServer from 'react-dom/server'; import { ServerStyleSheets, ThemeProvider } from '@material-ui/core/styles'; import App from './App'; import theme from './theme'; function handleRender(req, res) { const sheets = new ServerStyleSheets(); // Render the component to a string. const html = ReactDOMServer.renderToString( sheets.collect( <ThemeProvider theme={theme}> <App /> </ThemeProvider>, ), ); // Grab the CSS from the sheets. const css = sheets.toString(); // Send the rendered page back to the client. res.send(renderFullPage(html, css)); } const app = express(); app.use('/build', express.static('build')); // This is fired every time the server-side receives a request. app.use(handleRender); const port = 3000; app.listen(port); ``` ### Inject Initial Component HTML and CSS The final step on the server-side is to inject the initial component HTML and CSS into a template to be rendered on the client side. ```js function renderFullPage(html, css) { return ` <!DOCTYPE html> <html> <head> <title>My page</title> <style id="jss-server-side">${css}</style> </head> <body> <div id="root">${html}</div> </body> </html> `; } ``` ### The Client Side The client side is straightforward. All we need to do is remove the server-side generated CSS. Let's take a look at the client file: `client.js` ```jsx import React from 'react'; import ReactDOM from 'react-dom'; import { ThemeProvider } from '@material-ui/core/styles'; import App from './App'; import theme from './theme'; function Main() { React.useEffect(() => { const jssStyles = document.querySelector('#jss-server-side'); if (jssStyles) { jssStyles.parentElement.removeChild(jssStyles); } }, []); return ( <ThemeProvider theme={theme}> <App /> </ThemeProvider> ); } ReactDOM.hydrate(<Main />, document.querySelector('#root')); ``` ## Reference implementations We host different reference implementations which you can find in the [GitHub repository](https://github.com/mui-org/material-ui) under the [`/examples`](https://github.com/mui-org/material-ui/tree/master/examples) folder: - [The reference implementation of this tutorial](https://github.com/mui-org/material-ui/tree/master/examples/ssr) - [Gatsby](https://github.com/mui-org/material-ui/tree/master/examples/gatsby) - [Next.js](https://github.com/mui-org/material-ui/tree/master/examples/nextjs) ## Troubleshooting Check out the FAQ answer: [My App doesn't render correctly on the server](/getting-started/faq/#my-app-doesnt-render-correctly-on-the-server).
docs/src/pages/guides/server-rendering/server-rendering.md
0
https://github.com/mui/material-ui/commit/afd485346345d319c062b84e07d97a6e4d41e20c
[ 0.000585090892855078, 0.00019411361427046359, 0.00016354655963368714, 0.0001702366425888613, 0.00009042746387422085 ]
{ "id": 2, "code_window": [ " open={state.open}\n", " onClose={handleClose}\n", " TransitionComponent={state.Transition}\n", " message=\"I love snacks\"\n", " />\n", " </div>\n", " );\n", "}" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " key={state.Transition.name}\n" ], "file_path": "docs/src/pages/components/snackbars/TransitionsSnackbar.js", "type": "add", "edit_start_line_idx": 45 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H3V5h10v4h8v10zm2-16H1v18h22V3zm-2 16H3V5h10v4h8v10z" /> , 'TabSharp');
packages/material-ui-icons/src/TabSharp.js
0
https://github.com/mui/material-ui/commit/afd485346345d319c062b84e07d97a6e4d41e20c
[ 0.00017255132843274623, 0.00017255132843274623, 0.00017255132843274623, 0.00017255132843274623, 0 ]
{ "id": 2, "code_window": [ " open={state.open}\n", " onClose={handleClose}\n", " TransitionComponent={state.Transition}\n", " message=\"I love snacks\"\n", " />\n", " </div>\n", " );\n", "}" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " key={state.Transition.name}\n" ], "file_path": "docs/src/pages/components/snackbars/TransitionsSnackbar.js", "type": "add", "edit_start_line_idx": 45 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fillOpacity=".3" d="M23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7L12 21.5 23.64 7z" /><path d="M4.79 12.52L12 21.5l7.21-8.99C18.85 12.24 16.1 10 12 10s-6.85 2.24-7.21 2.52z" /></React.Fragment> , 'SignalWifi2BarTwoTone');
packages/material-ui-icons/src/SignalWifi2BarTwoTone.js
0
https://github.com/mui/material-ui/commit/afd485346345d319c062b84e07d97a6e4d41e20c
[ 0.00017368716362398118, 0.00017368716362398118, 0.00017368716362398118, 0.00017368716362398118, 0 ]
{ "id": 3, "code_window": [ " open={state.open}\n", " onClose={handleClose}\n", " TransitionComponent={state.Transition}\n", " message=\"I love snacks\"\n", " />\n", " </div>\n", " );\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " key={state.Transition.name}\n" ], "file_path": "docs/src/pages/components/snackbars/TransitionsSnackbar.tsx", "type": "add", "edit_start_line_idx": 51 }
import React from 'react'; import Button from '@material-ui/core/Button'; import Snackbar from '@material-ui/core/Snackbar'; import Fade from '@material-ui/core/Fade'; import Slide from '@material-ui/core/Slide'; import Grow from '@material-ui/core/Grow'; function SlideTransition(props) { return <Slide {...props} direction="up" />; } function GrowTransition(props) { return <Grow {...props} />; } export default function TransitionsSnackbar() { const [state, setState] = React.useState({ open: false, Transition: Fade, }); const handleClick = (Transition) => () => { setState({ open: true, Transition, }); }; const handleClose = () => { setState({ ...state, open: false, }); }; return ( <div> <Button onClick={handleClick(GrowTransition)}>Grow Transition</Button> <Button onClick={handleClick(Fade)}>Fade Transition</Button> <Button onClick={handleClick(SlideTransition)}>Slide Transition</Button> <Snackbar open={state.open} onClose={handleClose} TransitionComponent={state.Transition} message="I love snacks" /> </div> ); }
docs/src/pages/components/snackbars/TransitionsSnackbar.js
1
https://github.com/mui/material-ui/commit/afd485346345d319c062b84e07d97a6e4d41e20c
[ 0.9883729815483093, 0.20001523196697235, 0.00018633624131325632, 0.0022889028768986464, 0.3941851556301117 ]
{ "id": 3, "code_window": [ " open={state.open}\n", " onClose={handleClose}\n", " TransitionComponent={state.Transition}\n", " message=\"I love snacks\"\n", " />\n", " </div>\n", " );\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " key={state.Transition.name}\n" ], "file_path": "docs/src/pages/components/snackbars/TransitionsSnackbar.tsx", "type": "add", "edit_start_line_idx": 51 }
import * as React from 'react'; import { StandardProps } from '..'; import { FormGroupProps, FormGroupClassKey } from '../FormGroup'; export interface RadioGroupProps extends StandardProps<FormGroupProps, RadioGroupClassKey, 'onChange'> { /** * The default `input` element value. Use when the component is not controlled. */ defaultValue?: FormGroupProps['defaultValue']; /** * The name used to reference the value of the control. * If you don't provide this prop, it falls back to a randomly generated name. */ name?: string; /** * Callback fired when a radio button is selected. * * @param {object} event The event source of the callback. * You can pull out the new value by accessing `event.target.value` (string). */ onChange?: (event: React.ChangeEvent<HTMLInputElement>, value: string) => void; /** * Value of the selected radio button. The DOM API casts this to a string. */ value?: any; } export type RadioGroupClassKey = FormGroupClassKey; /** * * Demos: * * - [Radio Buttons](https://material-ui.com/components/radio-buttons/) * * API: * * - [RadioGroup API](https://material-ui.com/api/radio-group/) * - inherits [FormGroup API](https://material-ui.com/api/form-group/) */ export default function RadioGroup(props: RadioGroupProps): JSX.Element;
packages/material-ui/src/RadioGroup/RadioGroup.d.ts
0
https://github.com/mui/material-ui/commit/afd485346345d319c062b84e07d97a6e4d41e20c
[ 0.0001681221037870273, 0.00016630531172268093, 0.00016462455096188933, 0.000166228404850699, 0.0000011112093716292293 ]
{ "id": 3, "code_window": [ " open={state.open}\n", " onClose={handleClose}\n", " TransitionComponent={state.Transition}\n", " message=\"I love snacks\"\n", " />\n", " </div>\n", " );\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " key={state.Transition.name}\n" ], "file_path": "docs/src/pages/components/snackbars/TransitionsSnackbar.tsx", "type": "add", "edit_start_line_idx": 51 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M11 23.59v-3.6c-5.01-.26-9-4.42-9-9.49C2 5.26 6.26 1 11.5 1S21 5.26 21 10.5c0 4.95-3.44 9.93-8.57 12.4l-1.43.69zM11.5 3C7.36 3 4 6.36 4 10.5S7.36 18 11.5 18H13v2.3c3.64-2.3 6-6.08 6-9.8C19 6.36 15.64 3 11.5 3zm-1 11.5h2v2h-2zm2-1.5h-2c0-3.25 3-3 3-5 0-1.1-.9-2-2-2s-2 .9-2 2h-2c0-2.21 1.79-4 4-4s4 1.79 4 4c0 2.5-3 2.75-3 5z" /> , 'ContactSupportOutlined');
packages/material-ui-icons/src/ContactSupportOutlined.js
0
https://github.com/mui/material-ui/commit/afd485346345d319c062b84e07d97a6e4d41e20c
[ 0.00016987498383969069, 0.00016987498383969069, 0.00016987498383969069, 0.00016987498383969069, 0 ]
{ "id": 3, "code_window": [ " open={state.open}\n", " onClose={handleClose}\n", " TransitionComponent={state.Transition}\n", " message=\"I love snacks\"\n", " />\n", " </div>\n", " );\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " key={state.Transition.name}\n" ], "file_path": "docs/src/pages/components/snackbars/TransitionsSnackbar.tsx", "type": "add", "edit_start_line_idx": 51 }
import React from 'react'; import Button from '@material-ui/core/Button'; import Menu from '@material-ui/core/Menu'; import MenuItem from '@material-ui/core/MenuItem'; import PopupState, { bindTrigger, bindMenu } from 'material-ui-popup-state'; export default function MenuPopupState() { return ( <PopupState variant="popover" popupId="demo-popup-menu"> {(popupState) => ( <React.Fragment> <Button variant="contained" color="primary" {...bindTrigger(popupState)}> Open Menu </Button> <Menu {...bindMenu(popupState)}> <MenuItem onClick={popupState.close}>Cake</MenuItem> <MenuItem onClick={popupState.close}>Death</MenuItem> </Menu> </React.Fragment> )} </PopupState> ); }
docs/src/pages/components/menus/MenuPopupState.tsx
0
https://github.com/mui/material-ui/commit/afd485346345d319c062b84e07d97a6e4d41e20c
[ 0.0001724843605188653, 0.0001690171629888937, 0.00016726042667869478, 0.00016730668721720576, 0.0000024517551082681166 ]
{ "id": 0, "code_window": [ " detachedScope.run(() => {})\n", "\n", " expect(getCurrentScope()).toBe(currentScope)\n", " })\n", " })\n", "})" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ "\n", " it('calling .off() of a detached scope inside an active scope should not break currentScope', () => {\n", " const parentScope = new EffectScope()\n", "\n", " parentScope.run(() => {\n", " const childScope = new EffectScope(true)\n", " childScope.on()\n", " childScope.off()\n", " expect(getCurrentScope()).toBe(parentScope)\n", " })\n", " })\n" ], "file_path": "packages/reactivity/__tests__/effectScope.spec.ts", "type": "add", "edit_start_line_idx": 279 }
import { ReactiveEffect } from './effect' import { warn } from './warning' let activeEffectScope: EffectScope | undefined export class EffectScope { /** * @internal */ active = true /** * @internal */ effects: ReactiveEffect[] = [] /** * @internal */ cleanups: (() => void)[] = [] /** * only assigned by undetached scope * @internal */ parent: EffectScope | undefined /** * record undetached scopes * @internal */ scopes: EffectScope[] | undefined /** * track a child scope's index in its parent's scopes array for optimized * removal * @internal */ private index: number | undefined constructor(detached = false) { if (!detached && activeEffectScope) { this.parent = activeEffectScope this.index = (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push( this ) - 1 } } run<T>(fn: () => T): T | undefined { if (this.active) { const currentEffectScope = activeEffectScope try { activeEffectScope = this return fn() } finally { activeEffectScope = currentEffectScope } } else if (__DEV__) { warn(`cannot run an inactive effect scope.`) } } /** * This should only be called on non-detached scopes * @internal */ on() { activeEffectScope = this } /** * This should only be called on non-detached scopes * @internal */ off() { activeEffectScope = this.parent } stop(fromParent?: boolean) { if (this.active) { let i, l for (i = 0, l = this.effects.length; i < l; i++) { this.effects[i].stop() } for (i = 0, l = this.cleanups.length; i < l; i++) { this.cleanups[i]() } if (this.scopes) { for (i = 0, l = this.scopes.length; i < l; i++) { this.scopes[i].stop(true) } } // nested scope, dereference from parent to avoid memory leaks if (this.parent && !fromParent) { // optimized O(1) removal const last = this.parent.scopes!.pop() if (last && last !== this) { this.parent.scopes![this.index!] = last last.index = this.index! } } this.active = false } } } export function effectScope(detached?: boolean) { return new EffectScope(detached) } export function recordEffectScope( effect: ReactiveEffect, scope: EffectScope | undefined = activeEffectScope ) { if (scope && scope.active) { scope.effects.push(effect) } } export function getCurrentScope() { return activeEffectScope } export function onScopeDispose(fn: () => void) { if (activeEffectScope) { activeEffectScope.cleanups.push(fn) } else if (__DEV__) { warn( `onScopeDispose() is called when there is no active effect scope` + ` to be associated with.` ) } }
packages/reactivity/src/effectScope.ts
1
https://github.com/vuejs/core/commit/a71f9ac41af464fdb69220e69c50739dd3a8f365
[ 0.001459868741221726, 0.0005088027683086693, 0.00016933323058765382, 0.0002494117943570018, 0.0004667583270929754 ]
{ "id": 0, "code_window": [ " detachedScope.run(() => {})\n", "\n", " expect(getCurrentScope()).toBe(currentScope)\n", " })\n", " })\n", "})" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ "\n", " it('calling .off() of a detached scope inside an active scope should not break currentScope', () => {\n", " const parentScope = new EffectScope()\n", "\n", " parentScope.run(() => {\n", " const childScope = new EffectScope(true)\n", " childScope.on()\n", " childScope.off()\n", " expect(getCurrentScope()).toBe(parentScope)\n", " })\n", " })\n" ], "file_path": "packages/reactivity/__tests__/effectScope.spec.ts", "type": "add", "edit_start_line_idx": 279 }
import path from 'path' import { setupPuppeteer, E2E_TIMEOUT } from '../../__tests__/e2eUtils' interface TableData { name: string power: number } describe('e2e: grid', () => { const { page, click, text, count, typeValue, clearValue } = setupPuppeteer() const columns = ['name', 'power'] as const async function assertTable(data: TableData[]) { expect(await count('td')).toBe(data.length * columns.length) for (let i = 0; i < data.length; i++) { for (let j = 0; j < columns.length; j++) { expect( await text(`tr:nth-child(${i + 1}) td:nth-child(${j + 1})`) ).toContain(`${data[i][columns[j]]}`) } } } async function testGrid(apiType: 'classic' | 'composition') { const baseUrl = `file://${path.resolve( __dirname, `../${apiType}/grid.html` )}` await page().goto(baseUrl) await page().waitForSelector('table') expect(await count('th')).toBe(2) expect(await count('th.active')).toBe(0) expect(await text('th:nth-child(1)')).toContain('Name') expect(await text('th:nth-child(2)')).toContain('Power') await assertTable([ { name: 'Chuck Norris', power: Infinity }, { name: 'Bruce Lee', power: 9000 }, { name: 'Jackie Chan', power: 7000 }, { name: 'Jet Li', power: 8000 } ]) await click('th:nth-child(1)') expect(await count('th.active:nth-child(1)')).toBe(1) expect(await count('th.active:nth-child(2)')).toBe(0) expect(await count('th:nth-child(1) .arrow.dsc')).toBe(1) expect(await count('th:nth-child(2) .arrow.dsc')).toBe(0) await assertTable([ { name: 'Jet Li', power: 8000 }, { name: 'Jackie Chan', power: 7000 }, { name: 'Chuck Norris', power: Infinity }, { name: 'Bruce Lee', power: 9000 } ]) await click('th:nth-child(2)') expect(await count('th.active:nth-child(1)')).toBe(0) expect(await count('th.active:nth-child(2)')).toBe(1) expect(await count('th:nth-child(1) .arrow.dsc')).toBe(1) expect(await count('th:nth-child(2) .arrow.dsc')).toBe(1) await assertTable([ { name: 'Chuck Norris', power: Infinity }, { name: 'Bruce Lee', power: 9000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jackie Chan', power: 7000 } ]) await click('th:nth-child(2)') expect(await count('th.active:nth-child(1)')).toBe(0) expect(await count('th.active:nth-child(2)')).toBe(1) expect(await count('th:nth-child(1) .arrow.dsc')).toBe(1) expect(await count('th:nth-child(2) .arrow.asc')).toBe(1) await assertTable([ { name: 'Jackie Chan', power: 7000 }, { name: 'Jet Li', power: 8000 }, { name: 'Bruce Lee', power: 9000 }, { name: 'Chuck Norris', power: Infinity } ]) await click('th:nth-child(1)') expect(await count('th.active:nth-child(1)')).toBe(1) expect(await count('th.active:nth-child(2)')).toBe(0) expect(await count('th:nth-child(1) .arrow.asc')).toBe(1) expect(await count('th:nth-child(2) .arrow.asc')).toBe(1) await assertTable([ { name: 'Bruce Lee', power: 9000 }, { name: 'Chuck Norris', power: Infinity }, { name: 'Jackie Chan', power: 7000 }, { name: 'Jet Li', power: 8000 } ]) await typeValue('input[name="query"]', 'j') await assertTable([ { name: 'Jackie Chan', power: 7000 }, { name: 'Jet Li', power: 8000 } ]) await typeValue('input[name="query"]', 'infinity') await assertTable([{ name: 'Chuck Norris', power: Infinity }]) await clearValue('input[name="query"]') expect(await count('p')).toBe(0) await typeValue('input[name="query"]', 'stringthatdoesnotexistanywhere') expect(await count('p')).toBe(1) } test( 'classic', async () => { await testGrid('classic') }, E2E_TIMEOUT ) test( 'composition', async () => { await testGrid('composition') }, E2E_TIMEOUT ) })
packages/vue/examples/__tests__/grid.spec.ts
0
https://github.com/vuejs/core/commit/a71f9ac41af464fdb69220e69c50739dd3a8f365
[ 0.00017835904145613313, 0.000171658510225825, 0.00016780947044026107, 0.00017167544865515083, 0.000002581723492767196 ]
{ "id": 0, "code_window": [ " detachedScope.run(() => {})\n", "\n", " expect(getCurrentScope()).toBe(currentScope)\n", " })\n", " })\n", "})" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ "\n", " it('calling .off() of a detached scope inside an active scope should not break currentScope', () => {\n", " const parentScope = new EffectScope()\n", "\n", " parentScope.run(() => {\n", " const childScope = new EffectScope(true)\n", " childScope.on()\n", " childScope.off()\n", " expect(getCurrentScope()).toBe(parentScope)\n", " })\n", " })\n" ], "file_path": "packages/reactivity/__tests__/effectScope.spec.ts", "type": "add", "edit_start_line_idx": 279 }
# @vue/runtime-test This is for Vue's own internal tests only - it ensures logic tested using this package is DOM-agnostic, and it runs faster than JSDOM. It can also be used as a reference for implementing a custom renderer. ``` js import { h, render, nodeOps, dumpOps } from '@vue/runtime-test' const App = { data () { return { msg: 'Hello World!' } } render () { return h('div', this.msg) } } // root is of type `TestElement` as defined in src/nodeOps.ts const root = nodeOps.createElement('div') render(h(App), root) const ops = dumpOps() console.log(ops) ```
packages/runtime-test/README.md
0
https://github.com/vuejs/core/commit/a71f9ac41af464fdb69220e69c50739dd3a8f365
[ 0.00017435819609090686, 0.0001702406443655491, 0.0001672897778917104, 0.00016907395911403, 0.000003001277491421206 ]
{ "id": 0, "code_window": [ " detachedScope.run(() => {})\n", "\n", " expect(getCurrentScope()).toBe(currentScope)\n", " })\n", " })\n", "})" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ "\n", " it('calling .off() of a detached scope inside an active scope should not break currentScope', () => {\n", " const parentScope = new EffectScope()\n", "\n", " parentScope.run(() => {\n", " const childScope = new EffectScope(true)\n", " childScope.on()\n", " childScope.off()\n", " expect(getCurrentScope()).toBe(parentScope)\n", " })\n", " })\n" ], "file_path": "packages/reactivity/__tests__/effectScope.spec.ts", "type": "add", "edit_start_line_idx": 279 }
const escapeRE = /["'&<>]/ export function escapeHtml(string: unknown) { const str = '' + string const match = escapeRE.exec(str) if (!match) { return str } let html = '' let escaped: string let index: number let lastIndex = 0 for (index = match.index; index < str.length; index++) { switch (str.charCodeAt(index)) { case 34: // " escaped = '&quot;' break case 38: // & escaped = '&amp;' break case 39: // ' escaped = '&#39;' break case 60: // < escaped = '&lt;' break case 62: // > escaped = '&gt;' break default: continue } if (lastIndex !== index) { html += str.slice(lastIndex, index) } lastIndex = index + 1 html += escaped } return lastIndex !== index ? html + str.slice(lastIndex, index) : html } // https://www.w3.org/TR/html52/syntax.html#comments const commentStripRE = /^-?>|<!--|-->|--!>|<!-$/g export function escapeHtmlComment(src: string): string { return src.replace(commentStripRE, '') }
packages/shared/src/escapeHtml.ts
0
https://github.com/vuejs/core/commit/a71f9ac41af464fdb69220e69c50739dd3a8f365
[ 0.0001753440301399678, 0.00017393460439052433, 0.00017043766274582595, 0.00017464402480982244, 0.0000017285326521232491 ]
{ "id": 1, "code_window": [ " */\n", " private index: number | undefined\n", "\n", " constructor(detached = false) {\n", " if (!detached && activeEffectScope) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " constructor(public detached = false) {\n", " this.parent = activeEffectScope\n" ], "file_path": "packages/reactivity/src/effectScope.ts", "type": "replace", "edit_start_line_idx": 36 }
import { ReactiveEffect } from './effect' import { warn } from './warning' let activeEffectScope: EffectScope | undefined export class EffectScope { /** * @internal */ active = true /** * @internal */ effects: ReactiveEffect[] = [] /** * @internal */ cleanups: (() => void)[] = [] /** * only assigned by undetached scope * @internal */ parent: EffectScope | undefined /** * record undetached scopes * @internal */ scopes: EffectScope[] | undefined /** * track a child scope's index in its parent's scopes array for optimized * removal * @internal */ private index: number | undefined constructor(detached = false) { if (!detached && activeEffectScope) { this.parent = activeEffectScope this.index = (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push( this ) - 1 } } run<T>(fn: () => T): T | undefined { if (this.active) { const currentEffectScope = activeEffectScope try { activeEffectScope = this return fn() } finally { activeEffectScope = currentEffectScope } } else if (__DEV__) { warn(`cannot run an inactive effect scope.`) } } /** * This should only be called on non-detached scopes * @internal */ on() { activeEffectScope = this } /** * This should only be called on non-detached scopes * @internal */ off() { activeEffectScope = this.parent } stop(fromParent?: boolean) { if (this.active) { let i, l for (i = 0, l = this.effects.length; i < l; i++) { this.effects[i].stop() } for (i = 0, l = this.cleanups.length; i < l; i++) { this.cleanups[i]() } if (this.scopes) { for (i = 0, l = this.scopes.length; i < l; i++) { this.scopes[i].stop(true) } } // nested scope, dereference from parent to avoid memory leaks if (this.parent && !fromParent) { // optimized O(1) removal const last = this.parent.scopes!.pop() if (last && last !== this) { this.parent.scopes![this.index!] = last last.index = this.index! } } this.active = false } } } export function effectScope(detached?: boolean) { return new EffectScope(detached) } export function recordEffectScope( effect: ReactiveEffect, scope: EffectScope | undefined = activeEffectScope ) { if (scope && scope.active) { scope.effects.push(effect) } } export function getCurrentScope() { return activeEffectScope } export function onScopeDispose(fn: () => void) { if (activeEffectScope) { activeEffectScope.cleanups.push(fn) } else if (__DEV__) { warn( `onScopeDispose() is called when there is no active effect scope` + ` to be associated with.` ) } }
packages/reactivity/src/effectScope.ts
1
https://github.com/vuejs/core/commit/a71f9ac41af464fdb69220e69c50739dd3a8f365
[ 0.9901795387268066, 0.09217100590467453, 0.00017835495236795396, 0.007977692410349846, 0.2541921138763428 ]
{ "id": 1, "code_window": [ " */\n", " private index: number | undefined\n", "\n", " constructor(detached = false) {\n", " if (!detached && activeEffectScope) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " constructor(public detached = false) {\n", " this.parent = activeEffectScope\n" ], "file_path": "packages/reactivity/src/effectScope.ts", "type": "replace", "edit_start_line_idx": 36 }
declare module 'merge-source-map' { export default function merge(oldMap: object, newMap: object): object }
packages/compiler-sfc/src/shims.d.ts
0
https://github.com/vuejs/core/commit/a71f9ac41af464fdb69220e69c50739dd3a8f365
[ 0.00016863440396264195, 0.00016863440396264195, 0.00016863440396264195, 0.00016863440396264195, 0 ]
{ "id": 1, "code_window": [ " */\n", " private index: number | undefined\n", "\n", " constructor(detached = false) {\n", " if (!detached && activeEffectScope) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " constructor(public detached = false) {\n", " this.parent = activeEffectScope\n" ], "file_path": "packages/reactivity/src/effectScope.ts", "type": "replace", "edit_start_line_idx": 36 }
const args = require('minimist')(process.argv.slice(2)) const fs = require('fs') const path = require('path') const chalk = require('chalk') const semver = require('semver') const currentVersion = require('../package.json').version const { prompt } = require('enquirer') const execa = require('execa') const preId = args.preid || (semver.prerelease(currentVersion) && semver.prerelease(currentVersion)[0]) const isDryRun = args.dry const skipTests = args.skipTests const skipBuild = args.skipBuild const packages = fs .readdirSync(path.resolve(__dirname, '../packages')) .filter(p => !p.endsWith('.ts') && !p.startsWith('.')) const skippedPackages = [] const versionIncrements = [ 'patch', 'minor', 'major', ...(preId ? ['prepatch', 'preminor', 'premajor', 'prerelease'] : []) ] const inc = i => semver.inc(currentVersion, i, preId) const bin = name => path.resolve(__dirname, '../node_modules/.bin/' + name) const run = (bin, args, opts = {}) => execa(bin, args, { stdio: 'inherit', ...opts }) const dryRun = (bin, args, opts = {}) => console.log(chalk.blue(`[dryrun] ${bin} ${args.join(' ')}`), opts) const runIfNotDry = isDryRun ? dryRun : run const getPkgRoot = pkg => path.resolve(__dirname, '../packages/' + pkg) const step = msg => console.log(chalk.cyan(msg)) async function main() { let targetVersion = args._[0] if (!targetVersion) { // no explicit version, offer suggestions const { release } = await prompt({ type: 'select', name: 'release', message: 'Select release type', choices: versionIncrements.map(i => `${i} (${inc(i)})`).concat(['custom']) }) if (release === 'custom') { targetVersion = ( await prompt({ type: 'input', name: 'version', message: 'Input custom version', initial: currentVersion }) ).version } else { targetVersion = release.match(/\((.*)\)/)[1] } } if (!semver.valid(targetVersion)) { throw new Error(`invalid target version: ${targetVersion}`) } const { yes } = await prompt({ type: 'confirm', name: 'yes', message: `Releasing v${targetVersion}. Confirm?` }) if (!yes) { return } // run tests before release step('\nRunning tests...') if (!skipTests && !isDryRun) { await run(bin('jest'), ['--clearCache']) await run('pnpm', ['test', '--bail']) } else { console.log(`(skipped)`) } // update all package versions and inter-dependencies step('\nUpdating cross dependencies...') updateVersions(targetVersion) // build all packages with types step('\nBuilding all packages...') if (!skipBuild && !isDryRun) { await run('pnpm', ['run', 'build', '--release']) // test generated dts files step('\nVerifying type declarations...') await run('pnpm', ['run', 'test-dts-only']) } else { console.log(`(skipped)`) } // generate changelog step('\nGenerating changelog...') await run(`pnpm`, ['run', 'changelog']) // update pnpm-lock.yaml step('\nUpdating lockfile...') await run(`pnpm`, ['install', '--prefer-offline']) const { stdout } = await run('git', ['diff'], { stdio: 'pipe' }) if (stdout) { step('\nCommitting changes...') await runIfNotDry('git', ['add', '-A']) await runIfNotDry('git', ['commit', '-m', `release: v${targetVersion}`]) } else { console.log('No changes to commit.') } // publish packages step('\nPublishing packages...') for (const pkg of packages) { await publishPackage(pkg, targetVersion, runIfNotDry) } // push to GitHub step('\nPushing to GitHub...') await runIfNotDry('git', ['tag', `v${targetVersion}`]) await runIfNotDry('git', ['push', 'origin', `refs/tags/v${targetVersion}`]) await runIfNotDry('git', ['push']) if (isDryRun) { console.log(`\nDry run finished - run git diff to see package changes.`) } if (skippedPackages.length) { console.log( chalk.yellow( `The following packages are skipped and NOT published:\n- ${skippedPackages.join( '\n- ' )}` ) ) } console.log() } function updateVersions(version) { // 1. update root package.json updatePackage(path.resolve(__dirname, '..'), version) // 2. update all packages packages.forEach(p => updatePackage(getPkgRoot(p), version)) } function updatePackage(pkgRoot, version) { const pkgPath = path.resolve(pkgRoot, 'package.json') const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')) pkg.version = version updateDeps(pkg, 'dependencies', version) updateDeps(pkg, 'peerDependencies', version) fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n') } function updateDeps(pkg, depType, version) { const deps = pkg[depType] if (!deps) return Object.keys(deps).forEach(dep => { if ( dep === 'vue' || (dep.startsWith('@vue') && packages.includes(dep.replace(/^@vue\//, ''))) ) { console.log( chalk.yellow(`${pkg.name} -> ${depType} -> ${dep}@${version}`) ) deps[dep] = version } }) } async function publishPackage(pkgName, version, runIfNotDry) { if (skippedPackages.includes(pkgName)) { return } const pkgRoot = getPkgRoot(pkgName) const pkgPath = path.resolve(pkgRoot, 'package.json') const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')) if (pkg.private) { return } let releaseTag = null if (args.tag) { releaseTag = args.tag } else if (version.includes('alpha')) { releaseTag = 'alpha' } else if (version.includes('beta')) { releaseTag = 'beta' } else if (version.includes('rc')) { releaseTag = 'rc' } step(`Publishing ${pkgName}...`) try { await runIfNotDry( // note: use of yarn is intentional here as we rely on its publishing // behavior. 'yarn', [ 'publish', '--new-version', version, ...(releaseTag ? ['--tag', releaseTag] : []), '--access', 'public' ], { cwd: pkgRoot, stdio: 'pipe' } ) console.log(chalk.green(`Successfully published ${pkgName}@${version}`)) } catch (e) { if (e.stderr.match(/previously published/)) { console.log(chalk.red(`Skipping already published: ${pkgName}`)) } else { throw e } } } main().catch(err => { updateVersions(currentVersion) console.error(err) })
scripts/release.js
0
https://github.com/vuejs/core/commit/a71f9ac41af464fdb69220e69c50739dd3a8f365
[ 0.00017538231622893363, 0.00017033664335031062, 0.00016721147403586656, 0.0001701443106867373, 0.0000017037873476510867 ]
{ "id": 1, "code_window": [ " */\n", " private index: number | undefined\n", "\n", " constructor(detached = false) {\n", " if (!detached && activeEffectScope) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " constructor(public detached = false) {\n", " this.parent = activeEffectScope\n" ], "file_path": "packages/reactivity/src/effectScope.ts", "type": "replace", "edit_start_line_idx": 36 }
import { onMounted, onErrorCaptured, render, h, nodeOps, watch, ref, nextTick, defineComponent, watchEffect, createApp } from '@vue/runtime-test' describe('error handling', () => { test('propagation', () => { const err = new Error('foo') const fn = jest.fn() const Comp = { setup() { onErrorCaptured((err, instance, info) => { fn(err, info, 'root') return false }) return () => h(Child) } } const Child = { setup() { onErrorCaptured((err, instance, info) => { fn(err, info, 'child') }) return () => h(GrandChild) } } const GrandChild = { setup() { onMounted(() => { throw err }) return () => null } } render(h(Comp), nodeOps.createElement('div')) expect(fn).toHaveBeenCalledTimes(2) expect(fn).toHaveBeenCalledWith(err, 'mounted hook', 'root') expect(fn).toHaveBeenCalledWith(err, 'mounted hook', 'child') }) test('propagation stoppage', () => { const err = new Error('foo') const fn = jest.fn() const Comp = { setup() { onErrorCaptured((err, instance, info) => { fn(err, info, 'root') return false }) return () => h(Child) } } const Child = { setup() { onErrorCaptured((err, instance, info) => { fn(err, info, 'child') return false }) return () => h(GrandChild) } } const GrandChild = { setup() { onMounted(() => { throw err }) return () => null } } render(h(Comp), nodeOps.createElement('div')) expect(fn).toHaveBeenCalledTimes(1) expect(fn).toHaveBeenCalledWith(err, 'mounted hook', 'child') }) test('async error handling', async () => { const err = new Error('foo') const fn = jest.fn() const Comp = { setup() { onErrorCaptured((err, instance, info) => { fn(err, info) return false }) return () => h(Child) } } const Child = { setup() { onMounted(async () => { throw err }) }, render() {} } render(h(Comp), nodeOps.createElement('div')) expect(fn).not.toHaveBeenCalled() await new Promise(r => setTimeout(r)) expect(fn).toHaveBeenCalledWith(err, 'mounted hook') }) test('error thrown in onErrorCaptured', () => { const err = new Error('foo') const err2 = new Error('bar') const fn = jest.fn() const Comp = { setup() { onErrorCaptured((err, instance, info) => { fn(err, info) return false }) return () => h(Child) } } const Child = { setup() { onErrorCaptured(() => { throw err2 }) return () => h(GrandChild) } } const GrandChild = { setup() { onMounted(() => { throw err }) return () => null } } render(h(Comp), nodeOps.createElement('div')) expect(fn).toHaveBeenCalledTimes(2) expect(fn).toHaveBeenCalledWith(err, 'mounted hook') expect(fn).toHaveBeenCalledWith(err2, 'errorCaptured hook') }) test('setup function', () => { const err = new Error('foo') const fn = jest.fn() const Comp = { setup() { onErrorCaptured((err, instance, info) => { fn(err, info) return false }) return () => h(Child) } } const Child = { setup() { throw err }, render() {} } render(h(Comp), nodeOps.createElement('div')) expect(fn).toHaveBeenCalledWith(err, 'setup function') }) // unlike other lifecycle hooks, created/beforeCreate are called as part of // the options API initialization process instead of by the renderer. test('in created/beforeCreate hook', () => { const err = new Error('foo') const fn = jest.fn() const Comp = { setup() { onErrorCaptured((err, instance, info) => { fn(err, info) return false }) return () => [h(Child1), h(Child2)] } } const Child1 = { created() { throw err }, render() {} } const Child2 = { beforeCreate() { throw err }, render() {} } render(h(Comp), nodeOps.createElement('div')) expect(fn).toHaveBeenCalledWith(err, 'created hook') expect(fn).toHaveBeenCalledWith(err, 'beforeCreate hook') }) test('in render function', () => { const err = new Error('foo') const fn = jest.fn() const Comp = { setup() { onErrorCaptured((err, instance, info) => { fn(err, info) return false }) return () => h(Child) } } const Child = { setup() { return () => { throw err } } } render(h(Comp), nodeOps.createElement('div')) expect(fn).toHaveBeenCalledWith(err, 'render function') }) test('in function ref', () => { const err = new Error('foo') const ref = () => { throw err } const fn = jest.fn() const Comp = { setup() { onErrorCaptured((err, instance, info) => { fn(err, info) return false }) return () => h(Child) } } const Child = defineComponent(() => () => h('div', { ref })) render(h(Comp), nodeOps.createElement('div')) expect(fn).toHaveBeenCalledWith(err, 'ref function') }) test('in effect', () => { const err = new Error('foo') const fn = jest.fn() const Comp = { setup() { onErrorCaptured((err, instance, info) => { fn(err, info) return false }) return () => h(Child) } } const Child = { setup() { watchEffect(() => { throw err }) return () => null } } render(h(Comp), nodeOps.createElement('div')) expect(fn).toHaveBeenCalledWith(err, 'watcher callback') }) test('in watch getter', () => { const err = new Error('foo') const fn = jest.fn() const Comp = { setup() { onErrorCaptured((err, instance, info) => { fn(err, info) return false }) return () => h(Child) } } const Child = { setup() { watch( () => { throw err }, () => {} ) return () => null } } render(h(Comp), nodeOps.createElement('div')) expect(fn).toHaveBeenCalledWith(err, 'watcher getter') }) test('in watch callback', async () => { const err = new Error('foo') const fn = jest.fn() const Comp = { setup() { onErrorCaptured((err, instance, info) => { fn(err, info) return false }) return () => h(Child) } } const count = ref(0) const Child = { setup() { watch( () => count.value, () => { throw err } ) return () => null } } render(h(Comp), nodeOps.createElement('div')) count.value++ await nextTick() expect(fn).toHaveBeenCalledWith(err, 'watcher callback') }) test('in effect cleanup', async () => { const err = new Error('foo') const count = ref(0) const fn = jest.fn() const Comp = { setup() { onErrorCaptured((err, instance, info) => { fn(err, info) return false }) return () => h(Child) } } const Child = { setup() { watchEffect(onCleanup => { count.value onCleanup(() => { throw err }) }) return () => null } } render(h(Comp), nodeOps.createElement('div')) count.value++ await nextTick() expect(fn).toHaveBeenCalledWith(err, 'watcher cleanup function') }) test('in component event handler via emit', () => { const err = new Error('foo') const fn = jest.fn() const Comp = { setup() { onErrorCaptured((err, instance, info) => { fn(err, info) return false }) return () => h(Child, { onFoo: () => { throw err } }) } } const Child = { setup(props: any, { emit }: any) { emit('foo') return () => null } } render(h(Comp), nodeOps.createElement('div')) expect(fn).toHaveBeenCalledWith(err, 'component event handler') }) test('in component event handler via emit (async)', async () => { const err = new Error('foo') const fn = jest.fn() const Comp = { setup() { onErrorCaptured((err, instance, info) => { fn(err, info) return false }) return () => h(Child, { async onFoo() { throw err } }) } } const Child = { props: ['onFoo'], setup(props: any, { emit }: any) { emit('foo') return () => null } } render(h(Comp), nodeOps.createElement('div')) await nextTick() expect(fn).toHaveBeenCalledWith(err, 'component event handler') }) test('in component event handler via emit (async + array)', async () => { const err = new Error('foo') const fn = jest.fn() const res: Promise<any>[] = [] const createAsyncHandler = (p: Promise<any>) => () => { res.push(p) return p } const Comp = { setup() { onErrorCaptured((err, instance, info) => { fn(err, info) return false }) return () => h(Child, { onFoo: [ createAsyncHandler(Promise.reject(err)), createAsyncHandler(Promise.resolve(1)) ] }) } } const Child = { setup(props: any, { emit }: any) { emit('foo') return () => null } } render(h(Comp), nodeOps.createElement('div')) try { await Promise.all(res) } catch (e: any) { expect(e).toBe(err) } expect(fn).toHaveBeenCalledWith(err, 'component event handler') }) it('should warn unhandled', () => { const groupCollapsed = jest.spyOn(console, 'groupCollapsed') groupCollapsed.mockImplementation(() => {}) const log = jest.spyOn(console, 'log') log.mockImplementation(() => {}) const err = new Error('foo') const fn = jest.fn() const Comp = { setup() { onErrorCaptured((err, instance, info) => { fn(err, info) }) return () => h(Child) } } const Child = { setup() { throw err }, render() {} } let caughtError try { render(h(Comp), nodeOps.createElement('div')) } catch (caught) { caughtError = caught } expect(fn).toHaveBeenCalledWith(err, 'setup function') expect( `Unhandled error during execution of setup function` ).toHaveBeenWarned() expect(caughtError).toBe(err) groupCollapsed.mockRestore() log.mockRestore() }) //# 3127 test('handle error in watch & watchEffect', async () => { const error1 = new Error('error1') const error2 = new Error('error2') const error3 = new Error('error3') const error4 = new Error('error4') const handler = jest.fn() const app = createApp({ setup() { const count = ref(1) watch( count, () => { throw error1 }, { immediate: true } ) watch( count, async () => { throw error2 }, { immediate: true } ) watchEffect(() => { throw error3 }) watchEffect(async () => { throw error4 }) }, render() {} }) app.config.errorHandler = handler app.mount(nodeOps.createElement('div')) await nextTick() expect(handler).toHaveBeenCalledWith(error1, {}, 'watcher callback') expect(handler).toHaveBeenCalledWith(error2, {}, 'watcher callback') expect(handler).toHaveBeenCalledWith(error3, {}, 'watcher callback') expect(handler).toHaveBeenCalledWith(error4, {}, 'watcher callback') expect(handler).toHaveBeenCalledTimes(4) }) // native event handler handling should be tested in respective renderers })
packages/runtime-core/__tests__/errorHandling.spec.ts
0
https://github.com/vuejs/core/commit/a71f9ac41af464fdb69220e69c50739dd3a8f365
[ 0.0002573997771833092, 0.00017345989181194454, 0.00016691628843545914, 0.00016999895160552114, 0.00001339988739346154 ]
{ "id": 2, "code_window": [ " if (!detached && activeEffectScope) {\n", " this.parent = activeEffectScope\n", " this.index =\n", " (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(\n", " this\n", " ) - 1\n", " }\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/reactivity/src/effectScope.ts", "type": "replace", "edit_start_line_idx": 38 }
import { ReactiveEffect } from './effect' import { warn } from './warning' let activeEffectScope: EffectScope | undefined export class EffectScope { /** * @internal */ active = true /** * @internal */ effects: ReactiveEffect[] = [] /** * @internal */ cleanups: (() => void)[] = [] /** * only assigned by undetached scope * @internal */ parent: EffectScope | undefined /** * record undetached scopes * @internal */ scopes: EffectScope[] | undefined /** * track a child scope's index in its parent's scopes array for optimized * removal * @internal */ private index: number | undefined constructor(detached = false) { if (!detached && activeEffectScope) { this.parent = activeEffectScope this.index = (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push( this ) - 1 } } run<T>(fn: () => T): T | undefined { if (this.active) { const currentEffectScope = activeEffectScope try { activeEffectScope = this return fn() } finally { activeEffectScope = currentEffectScope } } else if (__DEV__) { warn(`cannot run an inactive effect scope.`) } } /** * This should only be called on non-detached scopes * @internal */ on() { activeEffectScope = this } /** * This should only be called on non-detached scopes * @internal */ off() { activeEffectScope = this.parent } stop(fromParent?: boolean) { if (this.active) { let i, l for (i = 0, l = this.effects.length; i < l; i++) { this.effects[i].stop() } for (i = 0, l = this.cleanups.length; i < l; i++) { this.cleanups[i]() } if (this.scopes) { for (i = 0, l = this.scopes.length; i < l; i++) { this.scopes[i].stop(true) } } // nested scope, dereference from parent to avoid memory leaks if (this.parent && !fromParent) { // optimized O(1) removal const last = this.parent.scopes!.pop() if (last && last !== this) { this.parent.scopes![this.index!] = last last.index = this.index! } } this.active = false } } } export function effectScope(detached?: boolean) { return new EffectScope(detached) } export function recordEffectScope( effect: ReactiveEffect, scope: EffectScope | undefined = activeEffectScope ) { if (scope && scope.active) { scope.effects.push(effect) } } export function getCurrentScope() { return activeEffectScope } export function onScopeDispose(fn: () => void) { if (activeEffectScope) { activeEffectScope.cleanups.push(fn) } else if (__DEV__) { warn( `onScopeDispose() is called when there is no active effect scope` + ` to be associated with.` ) } }
packages/reactivity/src/effectScope.ts
1
https://github.com/vuejs/core/commit/a71f9ac41af464fdb69220e69c50739dd3a8f365
[ 0.977888822555542, 0.09175681322813034, 0.00016868491366039962, 0.0071287816390395164, 0.24843508005142212 ]
{ "id": 2, "code_window": [ " if (!detached && activeEffectScope) {\n", " this.parent = activeEffectScope\n", " this.index =\n", " (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(\n", " this\n", " ) - 1\n", " }\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/reactivity/src/effectScope.ts", "type": "replace", "edit_start_line_idx": 38 }
// this the shared base config for all packages. { "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", "apiReport": { "enabled": true, "reportFolder": "<projectFolder>/temp/" }, "docModel": { "enabled": true }, "dtsRollup": { "enabled": true }, "tsdocMetadata": { "enabled": false }, "messages": { "compilerMessageReporting": { "default": { "logLevel": "warning" } }, "extractorMessageReporting": { "default": { "logLevel": "warning", "addToApiReportFile": true }, "ae-missing-release-tag": { "logLevel": "none" } }, "tsdocMessageReporting": { "default": { "logLevel": "warning" }, "tsdoc-undefined-tag": { "logLevel": "none" }, "tsdoc-escape-greater-than": { "logLevel": "none" }, "tsdoc-malformed-inline-tag": { "logLevel": "none" }, "tsdoc-escape-right-brace": { "logLevel": "none" }, "tsdoc-unnecessary-backslash": { "logLevel": "none" } } } }
api-extractor.json
0
https://github.com/vuejs/core/commit/a71f9ac41af464fdb69220e69c50739dd3a8f365
[ 0.00017577959806658328, 0.00017434651090297848, 0.0001716885599307716, 0.00017476566426921636, 0.00000130697571876226 ]
{ "id": 2, "code_window": [ " if (!detached && activeEffectScope) {\n", " this.parent = activeEffectScope\n", " this.index =\n", " (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(\n", " this\n", " ) - 1\n", " }\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/reactivity/src/effectScope.ts", "type": "replace", "edit_start_line_idx": 38 }
import { compile } from '../src' function compileWithWrapper(src: string) { return compile(`<div>${src}</div>`) } describe('ssr: v-show', () => { test('basic as root', () => { expect(compile(`<div v-show="foo"/>`).code).toMatchInlineSnapshot(` "const { mergeProps: _mergeProps } = require(\\"vue\\") const { ssrRenderAttrs: _ssrRenderAttrs } = require(\\"vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { _push(\`<div\${_ssrRenderAttrs(_mergeProps({ style: (_ctx.foo) ? null : { display: \\"none\\" } }, _attrs))}></div>\`) }" `) }) test('basic', () => { expect(compileWithWrapper(`<div v-show="foo"/>`).code) .toMatchInlineSnapshot(` "const { ssrRenderStyle: _ssrRenderStyle, ssrRenderAttrs: _ssrRenderAttrs } = require(\\"vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { _push(\`<div\${ _ssrRenderAttrs(_attrs) }><div style=\\"\${ _ssrRenderStyle((_ctx.foo) ? null : { display: \\"none\\" }) }\\"></div></div>\`) }" `) }) test('with static style', () => { expect(compileWithWrapper(`<div style="color:red" v-show="foo"/>`).code) .toMatchInlineSnapshot(` "const { ssrRenderStyle: _ssrRenderStyle, ssrRenderAttrs: _ssrRenderAttrs } = require(\\"vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { _push(\`<div\${ _ssrRenderAttrs(_attrs) }><div style=\\"\${ _ssrRenderStyle([ {\\"color\\":\\"red\\"}, (_ctx.foo) ? null : { display: \\"none\\" } ]) }\\"></div></div>\`) }" `) }) test('with dynamic style', () => { expect( compileWithWrapper(`<div :style="{ color: 'red' }" v-show="foo"/>`).code ).toMatchInlineSnapshot(` "const { ssrRenderStyle: _ssrRenderStyle, ssrRenderAttrs: _ssrRenderAttrs } = require(\\"vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { _push(\`<div\${ _ssrRenderAttrs(_attrs) }><div style=\\"\${ _ssrRenderStyle([ { color: 'red' }, (_ctx.foo) ? null : { display: \\"none\\" } ]) }\\"></div></div>\`) }" `) }) test('with static + dynamic style', () => { expect( compileWithWrapper( `<div style="color:red" :style="{ fontSize: 14 }" v-show="foo"/>` ).code ).toMatchInlineSnapshot(` "const { ssrRenderStyle: _ssrRenderStyle, ssrRenderAttrs: _ssrRenderAttrs } = require(\\"vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { _push(\`<div\${ _ssrRenderAttrs(_attrs) }><div style=\\"\${ _ssrRenderStyle([ {\\"color\\":\\"red\\"}, { fontSize: 14 }, (_ctx.foo) ? null : { display: \\"none\\" } ]) }\\"></div></div>\`) }" `) }) test('with v-bind', () => { expect( compileWithWrapper( `<div v-bind="baz" style="color:red" :style="{ fontSize: 14 }" v-show="foo"/>` ).code ).toMatchInlineSnapshot(` "const { mergeProps: _mergeProps } = require(\\"vue\\") const { ssrRenderAttrs: _ssrRenderAttrs } = require(\\"vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { _push(\`<div\${ _ssrRenderAttrs(_attrs) }><div\${ _ssrRenderAttrs(_mergeProps(_ctx.baz, { style: [ {\\"color\\":\\"red\\"}, { fontSize: 14 }, (_ctx.foo) ? null : { display: \\"none\\" } ] })) }></div></div>\`) }" `) }) })
packages/compiler-ssr/__tests__/ssrVShow.spec.ts
0
https://github.com/vuejs/core/commit/a71f9ac41af464fdb69220e69c50739dd3a8f365
[ 0.0005643637268804014, 0.00023071841860655695, 0.0001664069714024663, 0.00017261893663089722, 0.00011646020720945671 ]
{ "id": 2, "code_window": [ " if (!detached && activeEffectScope) {\n", " this.parent = activeEffectScope\n", " this.index =\n", " (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(\n", " this\n", " ) - 1\n", " }\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/reactivity/src/effectScope.ts", "type": "replace", "edit_start_line_idx": 38 }
import { NodeTransform } from '../transform' import { NodeTypes, CompoundExpressionNode, createCallExpression, CallExpression, ElementTypes, ConstantTypes, createCompoundExpression } from '../ast' import { isText } from '../utils' import { CREATE_TEXT } from '../runtimeHelpers' import { PatchFlags, PatchFlagNames } from '@vue/shared' import { getConstantType } from './hoistStatic' // Merge adjacent text nodes and expressions into a single expression // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child. export const transformText: NodeTransform = (node, context) => { if ( node.type === NodeTypes.ROOT || node.type === NodeTypes.ELEMENT || node.type === NodeTypes.FOR || node.type === NodeTypes.IF_BRANCH ) { // perform the transform on node exit so that all expressions have already // been processed. return () => { const children = node.children let currentContainer: CompoundExpressionNode | undefined = undefined let hasText = false for (let i = 0; i < children.length; i++) { const child = children[i] if (isText(child)) { hasText = true for (let j = i + 1; j < children.length; j++) { const next = children[j] if (isText(next)) { if (!currentContainer) { currentContainer = children[i] = createCompoundExpression( [child], child.loc ) } // merge adjacent text node into current currentContainer.children.push(` + `, next) children.splice(j, 1) j-- } else { currentContainer = undefined break } } } } if ( !hasText || // if this is a plain element with a single text child, leave it // as-is since the runtime has dedicated fast path for this by directly // setting textContent of the element. // for component root it's always normalized anyway. (children.length === 1 && (node.type === NodeTypes.ROOT || (node.type === NodeTypes.ELEMENT && node.tagType === ElementTypes.ELEMENT && // #3756 // custom directives can potentially add DOM elements arbitrarily, // we need to avoid setting textContent of the element at runtime // to avoid accidentally overwriting the DOM elements added // by the user through custom directives. !node.props.find( p => p.type === NodeTypes.DIRECTIVE && !context.directiveTransforms[p.name] ) && // in compat mode, <template> tags with no special directives // will be rendered as a fragment so its children must be // converted into vnodes. !(__COMPAT__ && node.tag === 'template')))) ) { return } // pre-convert text nodes into createTextVNode(text) calls to avoid // runtime normalization. for (let i = 0; i < children.length; i++) { const child = children[i] if (isText(child) || child.type === NodeTypes.COMPOUND_EXPRESSION) { const callArgs: CallExpression['arguments'] = [] // createTextVNode defaults to single whitespace, so if it is a // single space the code could be an empty call to save bytes. if (child.type !== NodeTypes.TEXT || child.content !== ' ') { callArgs.push(child) } // mark dynamic text with flag so it gets patched inside a block if ( !context.ssr && getConstantType(child, context) === ConstantTypes.NOT_CONSTANT ) { callArgs.push( PatchFlags.TEXT + (__DEV__ ? ` /* ${PatchFlagNames[PatchFlags.TEXT]} */` : ``) ) } children[i] = { type: NodeTypes.TEXT_CALL, content: child, loc: child.loc, codegenNode: createCallExpression( context.helper(CREATE_TEXT), callArgs ) } } } } } }
packages/compiler-core/src/transforms/transformText.ts
0
https://github.com/vuejs/core/commit/a71f9ac41af464fdb69220e69c50739dd3a8f365
[ 0.00017569647752679884, 0.00017193035455420613, 0.00016405478527303785, 0.0001723740715533495, 0.0000031981655865820358 ]
{ "id": 3, "code_window": [ " }\n", " }\n", " // nested scope, dereference from parent to avoid memory leaks\n", " if (this.parent && !fromParent) {\n", " // optimized O(1) removal\n", " const last = this.parent.scopes!.pop()\n", " if (last && last !== this) {\n", " this.parent.scopes![this.index!] = last\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (!this.detached && this.parent && !fromParent) {\n" ], "file_path": "packages/reactivity/src/effectScope.ts", "type": "replace", "edit_start_line_idx": 91 }
import { ReactiveEffect } from './effect' import { warn } from './warning' let activeEffectScope: EffectScope | undefined export class EffectScope { /** * @internal */ active = true /** * @internal */ effects: ReactiveEffect[] = [] /** * @internal */ cleanups: (() => void)[] = [] /** * only assigned by undetached scope * @internal */ parent: EffectScope | undefined /** * record undetached scopes * @internal */ scopes: EffectScope[] | undefined /** * track a child scope's index in its parent's scopes array for optimized * removal * @internal */ private index: number | undefined constructor(detached = false) { if (!detached && activeEffectScope) { this.parent = activeEffectScope this.index = (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push( this ) - 1 } } run<T>(fn: () => T): T | undefined { if (this.active) { const currentEffectScope = activeEffectScope try { activeEffectScope = this return fn() } finally { activeEffectScope = currentEffectScope } } else if (__DEV__) { warn(`cannot run an inactive effect scope.`) } } /** * This should only be called on non-detached scopes * @internal */ on() { activeEffectScope = this } /** * This should only be called on non-detached scopes * @internal */ off() { activeEffectScope = this.parent } stop(fromParent?: boolean) { if (this.active) { let i, l for (i = 0, l = this.effects.length; i < l; i++) { this.effects[i].stop() } for (i = 0, l = this.cleanups.length; i < l; i++) { this.cleanups[i]() } if (this.scopes) { for (i = 0, l = this.scopes.length; i < l; i++) { this.scopes[i].stop(true) } } // nested scope, dereference from parent to avoid memory leaks if (this.parent && !fromParent) { // optimized O(1) removal const last = this.parent.scopes!.pop() if (last && last !== this) { this.parent.scopes![this.index!] = last last.index = this.index! } } this.active = false } } } export function effectScope(detached?: boolean) { return new EffectScope(detached) } export function recordEffectScope( effect: ReactiveEffect, scope: EffectScope | undefined = activeEffectScope ) { if (scope && scope.active) { scope.effects.push(effect) } } export function getCurrentScope() { return activeEffectScope } export function onScopeDispose(fn: () => void) { if (activeEffectScope) { activeEffectScope.cleanups.push(fn) } else if (__DEV__) { warn( `onScopeDispose() is called when there is no active effect scope` + ` to be associated with.` ) } }
packages/reactivity/src/effectScope.ts
1
https://github.com/vuejs/core/commit/a71f9ac41af464fdb69220e69c50739dd3a8f365
[ 0.9986280202865601, 0.07207848131656647, 0.00016527932893950492, 0.00021618581376969814, 0.2569817304611206 ]
{ "id": 3, "code_window": [ " }\n", " }\n", " // nested scope, dereference from parent to avoid memory leaks\n", " if (this.parent && !fromParent) {\n", " // optimized O(1) removal\n", " const last = this.parent.scopes!.pop()\n", " if (last && last !== this) {\n", " this.parent.scopes![this.index!] = last\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (!this.detached && this.parent && !fromParent) {\n" ], "file_path": "packages/reactivity/src/effectScope.ts", "type": "replace", "edit_start_line_idx": 91 }
import { h, provide, inject, InjectionKey, ref, nextTick, Ref, readonly, reactive, defineComponent } from '../src/index' import { render, nodeOps, serialize } from '@vue/runtime-test' // reference: https://vue-composition-api-rfc.netlify.com/api.html#provide-inject describe('api: provide/inject', () => { it('string keys', () => { const Provider = { setup() { provide('foo', 1) return () => h(Middle) } } const Middle = { render: () => h(Consumer) } const Consumer = { setup() { const foo = inject('foo') return () => foo } } const root = nodeOps.createElement('div') render(h(Provider), root) expect(serialize(root)).toBe(`<div>1</div>`) }) it('symbol keys', () => { // also verifies InjectionKey type sync const key: InjectionKey<number> = Symbol() const Provider = { setup() { provide(key, 1) return () => h(Middle) } } const Middle = { render: () => h(Consumer) } const Consumer = { setup() { const foo = inject(key) || 1 return () => foo + 1 } } const root = nodeOps.createElement('div') render(h(Provider), root) expect(serialize(root)).toBe(`<div>2</div>`) }) it('default values', () => { const Provider = { setup() { provide('foo', 'foo') return () => h(Middle) } } const Middle = { render: () => h(Consumer) } const Consumer = { setup() { // default value should be ignored if value is provided const foo = inject('foo', 'fooDefault') // default value should be used if value is not provided const bar = inject('bar', 'bar') return () => foo + bar } } const root = nodeOps.createElement('div') render(h(Provider), root) expect(serialize(root)).toBe(`<div>foobar</div>`) }) it('bound to instance', () => { const Provider = { setup() { return () => h(Consumer) } } const Consumer = defineComponent({ name: 'Consumer', inject: { foo: { from: 'foo', default() { return this!.$options.name } } }, render() { // @ts-ignore return this.foo } }) const root = nodeOps.createElement('div') render(h(Provider), root) expect(serialize(root)).toBe(`<div>Consumer</div>`) }) it('nested providers', () => { const ProviderOne = { setup() { provide('foo', 'foo') provide('bar', 'bar') return () => h(ProviderTwo) } } const ProviderTwo = { setup() { // override parent value provide('foo', 'fooOverride') provide('baz', 'baz') return () => h(Consumer) } } const Consumer = { setup() { const foo = inject('foo') const bar = inject('bar') const baz = inject('baz') return () => [foo, bar, baz].join(',') } } const root = nodeOps.createElement('div') render(h(ProviderOne), root) expect(serialize(root)).toBe(`<div>fooOverride,bar,baz</div>`) }) it('reactivity with refs', async () => { const count = ref(1) const Provider = { setup() { provide('count', count) return () => h(Middle) } } const Middle = { render: () => h(Consumer) } const Consumer = { setup() { const count = inject<Ref<number>>('count')! return () => count.value } } const root = nodeOps.createElement('div') render(h(Provider), root) expect(serialize(root)).toBe(`<div>1</div>`) count.value++ await nextTick() expect(serialize(root)).toBe(`<div>2</div>`) }) it('reactivity with readonly refs', async () => { const count = ref(1) const Provider = { setup() { provide('count', readonly(count)) return () => h(Middle) } } const Middle = { render: () => h(Consumer) } const Consumer = { setup() { const count = inject<Ref<number>>('count')! // should not work count.value++ return () => count.value } } const root = nodeOps.createElement('div') render(h(Provider), root) expect(serialize(root)).toBe(`<div>1</div>`) expect( `Set operation on key "value" failed: target is readonly` ).toHaveBeenWarned() // source mutation should still work count.value++ await nextTick() expect(serialize(root)).toBe(`<div>2</div>`) }) it('reactivity with objects', async () => { const rootState = reactive({ count: 1 }) const Provider = { setup() { provide('state', rootState) return () => h(Middle) } } const Middle = { render: () => h(Consumer) } const Consumer = { setup() { const state = inject<typeof rootState>('state')! return () => state.count } } const root = nodeOps.createElement('div') render(h(Provider), root) expect(serialize(root)).toBe(`<div>1</div>`) rootState.count++ await nextTick() expect(serialize(root)).toBe(`<div>2</div>`) }) it('reactivity with readonly objects', async () => { const rootState = reactive({ count: 1 }) const Provider = { setup() { provide('state', readonly(rootState)) return () => h(Middle) } } const Middle = { render: () => h(Consumer) } const Consumer = { setup() { const state = inject<typeof rootState>('state')! // should not work state.count++ return () => state.count } } const root = nodeOps.createElement('div') render(h(Provider), root) expect(serialize(root)).toBe(`<div>1</div>`) expect( `Set operation on key "count" failed: target is readonly` ).toHaveBeenWarned() rootState.count++ await nextTick() expect(serialize(root)).toBe(`<div>2</div>`) }) it('should warn unfound', () => { const Provider = { setup() { return () => h(Middle) } } const Middle = { render: () => h(Consumer) } const Consumer = { setup() { const foo = inject('foo') expect(foo).toBeUndefined() return () => foo } } const root = nodeOps.createElement('div') render(h(Provider), root) expect(serialize(root)).toBe(`<div><!----></div>`) expect(`injection "foo" not found.`).toHaveBeenWarned() }) it('should not warn when default value is undefined', () => { const Provider = { setup() { return () => h(Middle) } } const Middle = { render: () => h(Consumer) } const Consumer = { setup() { const foo = inject('foo', undefined) return () => foo } } const root = nodeOps.createElement('div') render(h(Provider), root) expect(`injection "foo" not found.`).not.toHaveBeenWarned() }) // #2400 it('should not self-inject', () => { const Comp = { setup() { provide('foo', 'foo') const injection = inject('foo', null) return () => injection } } const root = nodeOps.createElement('div') render(h(Comp), root) expect(serialize(root)).toBe(`<div><!----></div>`) }) })
packages/runtime-core/__tests__/apiInject.spec.ts
0
https://github.com/vuejs/core/commit/a71f9ac41af464fdb69220e69c50739dd3a8f365
[ 0.00023280979075934738, 0.00017340840713586658, 0.00016549315478187054, 0.00017079850658774376, 0.000013761734408035409 ]
{ "id": 3, "code_window": [ " }\n", " }\n", " // nested scope, dereference from parent to avoid memory leaks\n", " if (this.parent && !fromParent) {\n", " // optimized O(1) removal\n", " const last = this.parent.scopes!.pop()\n", " if (last && last !== this) {\n", " this.parent.scopes![this.index!] = last\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (!this.detached && this.parent && !fromParent) {\n" ], "file_path": "packages/reactivity/src/effectScope.ts", "type": "replace", "edit_start_line_idx": 91 }
{ "extends": "../../api-extractor.json", "mainEntryPointFilePath": "./dist/packages/<unscopedPackageName>/src/index.d.ts", "dtsRollup": { "publicTrimmedFilePath": "./dist/<unscopedPackageName>.d.ts" } }
packages/vue/api-extractor.json
0
https://github.com/vuejs/core/commit/a71f9ac41af464fdb69220e69c50739dd3a8f365
[ 0.0001722416200209409, 0.0001722416200209409, 0.0001722416200209409, 0.0001722416200209409, 0 ]
{ "id": 3, "code_window": [ " }\n", " }\n", " // nested scope, dereference from parent to avoid memory leaks\n", " if (this.parent && !fromParent) {\n", " // optimized O(1) removal\n", " const last = this.parent.scopes!.pop()\n", " if (last && last !== this) {\n", " this.parent.scopes![this.index!] = last\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (!this.detached && this.parent && !fromParent) {\n" ], "file_path": "packages/reactivity/src/effectScope.ts", "type": "replace", "edit_start_line_idx": 91 }
import { NodeTransform } from '../transform' import { findDir, makeBlock } from '../utils' import { createCallExpression, createFunctionExpression, ElementTypes, MemoExpression, NodeTypes, PlainElementNode } from '../ast' import { WITH_MEMO } from '../runtimeHelpers' const seen = new WeakSet() export const transformMemo: NodeTransform = (node, context) => { if (node.type === NodeTypes.ELEMENT) { const dir = findDir(node, 'memo') if (!dir || seen.has(node)) { return } seen.add(node) return () => { const codegenNode = node.codegenNode || (context.currentNode as PlainElementNode).codegenNode if (codegenNode && codegenNode.type === NodeTypes.VNODE_CALL) { // non-component sub tree should be turned into a block if (node.tagType !== ElementTypes.COMPONENT) { makeBlock(codegenNode, context) } node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [ dir.exp!, createFunctionExpression(undefined, codegenNode), `_cache`, String(context.cached++) ]) as MemoExpression } } } }
packages/compiler-core/src/transforms/vMemo.ts
0
https://github.com/vuejs/core/commit/a71f9ac41af464fdb69220e69c50739dd3a8f365
[ 0.00022469641407951713, 0.00018278585048392415, 0.00016636904911138117, 0.00017458928050473332, 0.000021187017409829423 ]
{ "id": 4, "code_window": [ " last.index = this.index!\n", " }\n", " }\n", " this.active = false\n", " }\n", " }\n", "}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.parent = undefined\n" ], "file_path": "packages/reactivity/src/effectScope.ts", "type": "add", "edit_start_line_idx": 99 }
import { ReactiveEffect } from './effect' import { warn } from './warning' let activeEffectScope: EffectScope | undefined export class EffectScope { /** * @internal */ active = true /** * @internal */ effects: ReactiveEffect[] = [] /** * @internal */ cleanups: (() => void)[] = [] /** * only assigned by undetached scope * @internal */ parent: EffectScope | undefined /** * record undetached scopes * @internal */ scopes: EffectScope[] | undefined /** * track a child scope's index in its parent's scopes array for optimized * removal * @internal */ private index: number | undefined constructor(detached = false) { if (!detached && activeEffectScope) { this.parent = activeEffectScope this.index = (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push( this ) - 1 } } run<T>(fn: () => T): T | undefined { if (this.active) { const currentEffectScope = activeEffectScope try { activeEffectScope = this return fn() } finally { activeEffectScope = currentEffectScope } } else if (__DEV__) { warn(`cannot run an inactive effect scope.`) } } /** * This should only be called on non-detached scopes * @internal */ on() { activeEffectScope = this } /** * This should only be called on non-detached scopes * @internal */ off() { activeEffectScope = this.parent } stop(fromParent?: boolean) { if (this.active) { let i, l for (i = 0, l = this.effects.length; i < l; i++) { this.effects[i].stop() } for (i = 0, l = this.cleanups.length; i < l; i++) { this.cleanups[i]() } if (this.scopes) { for (i = 0, l = this.scopes.length; i < l; i++) { this.scopes[i].stop(true) } } // nested scope, dereference from parent to avoid memory leaks if (this.parent && !fromParent) { // optimized O(1) removal const last = this.parent.scopes!.pop() if (last && last !== this) { this.parent.scopes![this.index!] = last last.index = this.index! } } this.active = false } } } export function effectScope(detached?: boolean) { return new EffectScope(detached) } export function recordEffectScope( effect: ReactiveEffect, scope: EffectScope | undefined = activeEffectScope ) { if (scope && scope.active) { scope.effects.push(effect) } } export function getCurrentScope() { return activeEffectScope } export function onScopeDispose(fn: () => void) { if (activeEffectScope) { activeEffectScope.cleanups.push(fn) } else if (__DEV__) { warn( `onScopeDispose() is called when there is no active effect scope` + ` to be associated with.` ) } }
packages/reactivity/src/effectScope.ts
1
https://github.com/vuejs/core/commit/a71f9ac41af464fdb69220e69c50739dd3a8f365
[ 0.9935417175292969, 0.07129546254873276, 0.00016665595467202365, 0.00017356309399474412, 0.25578543543815613 ]
{ "id": 4, "code_window": [ " last.index = this.index!\n", " }\n", " }\n", " this.active = false\n", " }\n", " }\n", "}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.parent = undefined\n" ], "file_path": "packages/reactivity/src/effectScope.ts", "type": "add", "edit_start_line_idx": 99 }
import { provide, inject, InjectionKey, expectType } from './index' const key: InjectionKey<number> = Symbol() provide(key, 1) // @ts-expect-error provide(key, 'foo') expectType<number | undefined>(inject(key)) expectType<number>(inject(key, 1)) expectType<number>(inject(key, () => 1, true /* treatDefaultAsFactory */)) expectType<() => number>(inject('foo', () => 1)) expectType<() => number>(inject('foo', () => 1, false)) expectType<number>(inject('foo', () => 1, true))
test-dts/inject.test-d.ts
0
https://github.com/vuejs/core/commit/a71f9ac41af464fdb69220e69c50739dd3a8f365
[ 0.0001728963543428108, 0.00016745354514569044, 0.00016201073594857007, 0.00016745354514569044, 0.0000054428091971203685 ]
{ "id": 4, "code_window": [ " last.index = this.index!\n", " }\n", " }\n", " this.active = false\n", " }\n", " }\n", "}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.parent = undefined\n" ], "file_path": "packages/reactivity/src/effectScope.ts", "type": "add", "edit_start_line_idx": 99 }
import { isArray } from '@vue/shared' import { inject } from '../apiInject' import { ComponentInternalInstance, Data } from '../component' import { ComponentOptions, resolveMergedOptions } from '../componentOptions' import { DeprecationTypes, warnDeprecation } from './compatConfig' export function createPropsDefaultThis( instance: ComponentInternalInstance, rawProps: Data, propKey: string ) { return new Proxy( {}, { get(_, key: string) { __DEV__ && warnDeprecation(DeprecationTypes.PROPS_DEFAULT_THIS, null, propKey) // $options if (key === '$options') { return resolveMergedOptions(instance) } // props if (key in rawProps) { return rawProps[key] } // injections const injections = (instance.type as ComponentOptions).inject if (injections) { if (isArray(injections)) { if (injections.includes(key)) { return inject(key) } } else if (key in injections) { return inject(key) } } } } ) }
packages/runtime-core/src/compat/props.ts
0
https://github.com/vuejs/core/commit/a71f9ac41af464fdb69220e69c50739dd3a8f365
[ 0.00017387921980116516, 0.00017016356287058443, 0.00016696214152034372, 0.00017067980661522597, 0.000002392663873251877 ]
{ "id": 4, "code_window": [ " last.index = this.index!\n", " }\n", " }\n", " this.active = false\n", " }\n", " }\n", "}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.parent = undefined\n" ], "file_path": "packages/reactivity/src/effectScope.ts", "type": "add", "edit_start_line_idx": 99 }
export { ref, shallowRef, isRef, toRef, toRefs, unref, proxyRefs, customRef, triggerRef, Ref, ToRef, ToRefs, UnwrapRef, ShallowRef, ShallowUnwrapRef, RefUnwrapBailTypes, CustomRefFactory } from './ref' export { reactive, readonly, isReactive, isReadonly, isShallow, isProxy, shallowReactive, shallowReadonly, markRaw, toRaw, ReactiveFlags, DeepReadonly, ShallowReactive, UnwrapNestedRefs } from './reactive' export { computed, ComputedRef, WritableComputedRef, WritableComputedOptions, ComputedGetter, ComputedSetter } from './computed' export { deferredComputed } from './deferredComputed' export { effect, stop, trigger, track, enableTracking, pauseTracking, resetTracking, ITERATE_KEY, ReactiveEffect, ReactiveEffectRunner, ReactiveEffectOptions, EffectScheduler, DebuggerOptions, DebuggerEvent, DebuggerEventExtraInfo } from './effect' export { effectScope, EffectScope, getCurrentScope, onScopeDispose } from './effectScope' export { TrackOpTypes, TriggerOpTypes } from './operations'
packages/reactivity/src/index.ts
0
https://github.com/vuejs/core/commit/a71f9ac41af464fdb69220e69c50739dd3a8f365
[ 0.00017242353351321071, 0.00016773086099419743, 0.000161985561135225, 0.00016733795928303152, 0.0000034827637591661187 ]
{ "id": 0, "code_window": [ " },\n", "\n", " build: function () {\n", " spawn(\"babel\", [\"src\", \"--out-dir\", \"lib\"]);\n", " },\n", "\n", " publish: function () {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " spawn(\"babel\", [\"src\", \"--out-dir\", \"lib\", \"--copy-files\"]);\n" ], "file_path": "packages/babel-cli/bin/babel-plugin/index.js", "type": "replace", "edit_start_line_idx": 109 }
import Transformer from "../transformer"; import Plugin from "../plugin"; import * as types from "../../types"; import traverse from "../../types"; import parse from "../../helpers/parse"; var context = { Transformer, Plugin, types, parse, traverse }; import * as messages from "../../messages"; import * as util from "../../util"; export default class PluginManager { static memoisedPlugins = []; static memoisePluginContainer(fn) { for (var i = 0; i < PluginManager.memoisedPlugins.length; i++) { var plugin = PluginManager.memoisedPlugins[i]; if (plugin.container === fn) return plugin.transformer; } var transformer = fn(context); PluginManager.memoisedPlugins.push({ container: fn, transformer: transformer }); return transformer; } static positions = ["before", "after"]; constructor({ file, transformers, before, after } = { transformers: {}, before: [], after: [] }) { this.transformers = transformers; this.file = file; this.before = before; this.after = after; } subnormaliseString(name, position) { // this is a plugin in the form of "foobar" or "foobar:after" // where the optional colon is the delimiter for plugin position in the transformer stack var match = name.match(/^(.*?):(after|before)$/); if (match) [, name, position] = match; var loc = util.resolveRelative(`babel-plugin-${name}`) || util.resolveRelative(name); if (loc) { var plugin = require(loc); return { position: position, plugin: plugin.default || plugin }; } else { throw new ReferenceError(messages.get("pluginUnknown", name)); } } validate(name, plugin) { // validate transformer key var key = plugin.key; if (this.transformers[key]) { throw new ReferenceError(messages.get("pluginKeyCollision", key)); } // validate Transformer instance if (!plugin.buildPass || plugin.constructor.name !== "Plugin") { throw new TypeError(messages.get("pluginNotTransformer", name)); } // register as a plugin plugin.metadata.plugin = true; } add(name) { var position; var plugin; if (name) { if (typeof name === "object" && name.transformer) { ({ transformer: plugin, position } = name); } else if (typeof name !== "string") { // not a string so we'll just assume that it's a direct Transformer instance, if not then // the checks later on will complain plugin = name; } if (typeof name === "string") { ({ plugin, position } = this.subnormaliseString(name, position)); } } else { throw new TypeError(messages.get("pluginIllegalKind", typeof name, name)); } // default position position = position || "before"; // validate position if (PluginManager.positions.indexOf(position) < 0) { throw new TypeError(messages.get("pluginIllegalPosition", position, name)); } // allow plugin containers to be specified so they don't have to manually require if (typeof plugin === "function") { plugin = PluginManager.memoisePluginContainer(plugin); } // this.validate(name, plugin); // build! var pass = this.transformers[plugin.key] = plugin.buildPass(this.file); if (pass.canTransform()) { var stack = position === "before" ? this.before : this.after; stack.push(pass); } } }
src/babel/transformation/file/plugin-manager.js
1
https://github.com/babel/babel/commit/050bcec617117e21e240858edf310ff25bfa8d95
[ 0.0003603331570047885, 0.00018450492643751204, 0.00016690324991941452, 0.00016906234668567777, 0.000050799691962311044 ]
{ "id": 0, "code_window": [ " },\n", "\n", " build: function () {\n", " spawn(\"babel\", [\"src\", \"--out-dir\", \"lib\"]);\n", " },\n", "\n", " publish: function () {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " spawn(\"babel\", [\"src\", \"--out-dir\", \"lib\", \"--copy-files\"]);\n" ], "file_path": "packages/babel-cli/bin/babel-plugin/index.js", "type": "replace", "edit_start_line_idx": 109 }
// comment print("hello"); // comment2 print("hello2");
test/core/fixtures/generation/comments/comment-statement-with-retainlines-option/actual.js
0
https://github.com/babel/babel/commit/050bcec617117e21e240858edf310ff25bfa8d95
[ 0.00017102077254094183, 0.00017102077254094183, 0.00017102077254094183, 0.00017102077254094183, 0 ]
{ "id": 0, "code_window": [ " },\n", "\n", " build: function () {\n", " spawn(\"babel\", [\"src\", \"--out-dir\", \"lib\"]);\n", " },\n", "\n", " publish: function () {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " spawn(\"babel\", [\"src\", \"--out-dir\", \"lib\", \"--copy-files\"]);\n" ], "file_path": "packages/babel-cli/bin/babel-plugin/index.js", "type": "replace", "edit_start_line_idx": 109 }
define(["exports"], function (exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.foo = foo; exports.foo = foo; exports.bar = bar; exports.bar = foo; exports["default"] = foo; exports["default"] = foo; exports.bar = bar; });
test/core/fixtures/transformation/es6.modules-amd/exports-named/expected.js
0
https://github.com/babel/babel/commit/050bcec617117e21e240858edf310ff25bfa8d95
[ 0.00017063913401216269, 0.00016956261242739856, 0.0001684860762907192, 0.00016956261242739856, 0.0000010765288607217371 ]
{ "id": 0, "code_window": [ " },\n", "\n", " build: function () {\n", " spawn(\"babel\", [\"src\", \"--out-dir\", \"lib\"]);\n", " },\n", "\n", " publish: function () {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " spawn(\"babel\", [\"src\", \"--out-dir\", \"lib\", \"--copy-files\"]);\n" ], "file_path": "packages/babel-cli/bin/babel-plugin/index.js", "type": "replace", "edit_start_line_idx": 109 }
function b() { assert.equals(a, 1); } let a = 1; b();
test/core/fixtures/transformation/es6.spec.block-scoping-fail/call-2.js
0
https://github.com/babel/babel/commit/050bcec617117e21e240858edf310ff25bfa8d95
[ 0.0004874615406151861, 0.0004874615406151861, 0.0004874615406151861, 0.0004874615406151861, 0 ]
{ "id": 1, "code_window": [ "import Transformer from \"../transformer\";\n", "import Plugin from \"../plugin\";\n", "import * as types from \"../../types\";\n", "import traverse from \"../../types\";\n", "import parse from \"../../helpers/parse\";\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import * as messages from \"../../messages\";\n" ], "file_path": "src/babel/transformation/file/plugin-manager.js", "type": "add", "edit_start_line_idx": 3 }
import Transformer from "../transformer"; import Plugin from "../plugin"; import * as types from "../../types"; import traverse from "../../types"; import parse from "../../helpers/parse"; var context = { Transformer, Plugin, types, parse, traverse }; import * as messages from "../../messages"; import * as util from "../../util"; export default class PluginManager { static memoisedPlugins = []; static memoisePluginContainer(fn) { for (var i = 0; i < PluginManager.memoisedPlugins.length; i++) { var plugin = PluginManager.memoisedPlugins[i]; if (plugin.container === fn) return plugin.transformer; } var transformer = fn(context); PluginManager.memoisedPlugins.push({ container: fn, transformer: transformer }); return transformer; } static positions = ["before", "after"]; constructor({ file, transformers, before, after } = { transformers: {}, before: [], after: [] }) { this.transformers = transformers; this.file = file; this.before = before; this.after = after; } subnormaliseString(name, position) { // this is a plugin in the form of "foobar" or "foobar:after" // where the optional colon is the delimiter for plugin position in the transformer stack var match = name.match(/^(.*?):(after|before)$/); if (match) [, name, position] = match; var loc = util.resolveRelative(`babel-plugin-${name}`) || util.resolveRelative(name); if (loc) { var plugin = require(loc); return { position: position, plugin: plugin.default || plugin }; } else { throw new ReferenceError(messages.get("pluginUnknown", name)); } } validate(name, plugin) { // validate transformer key var key = plugin.key; if (this.transformers[key]) { throw new ReferenceError(messages.get("pluginKeyCollision", key)); } // validate Transformer instance if (!plugin.buildPass || plugin.constructor.name !== "Plugin") { throw new TypeError(messages.get("pluginNotTransformer", name)); } // register as a plugin plugin.metadata.plugin = true; } add(name) { var position; var plugin; if (name) { if (typeof name === "object" && name.transformer) { ({ transformer: plugin, position } = name); } else if (typeof name !== "string") { // not a string so we'll just assume that it's a direct Transformer instance, if not then // the checks later on will complain plugin = name; } if (typeof name === "string") { ({ plugin, position } = this.subnormaliseString(name, position)); } } else { throw new TypeError(messages.get("pluginIllegalKind", typeof name, name)); } // default position position = position || "before"; // validate position if (PluginManager.positions.indexOf(position) < 0) { throw new TypeError(messages.get("pluginIllegalPosition", position, name)); } // allow plugin containers to be specified so they don't have to manually require if (typeof plugin === "function") { plugin = PluginManager.memoisePluginContainer(plugin); } // this.validate(name, plugin); // build! var pass = this.transformers[plugin.key] = plugin.buildPass(this.file); if (pass.canTransform()) { var stack = position === "before" ? this.before : this.after; stack.push(pass); } } }
src/babel/transformation/file/plugin-manager.js
1
https://github.com/babel/babel/commit/050bcec617117e21e240858edf310ff25bfa8d95
[ 0.9080646634101868, 0.07009868323802948, 0.00016809180669952184, 0.00024115279666148126, 0.24189995229244232 ]
{ "id": 1, "code_window": [ "import Transformer from \"../transformer\";\n", "import Plugin from \"../plugin\";\n", "import * as types from \"../../types\";\n", "import traverse from \"../../types\";\n", "import parse from \"../../helpers/parse\";\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import * as messages from \"../../messages\";\n" ], "file_path": "src/babel/transformation/file/plugin-manager.js", "type": "add", "edit_start_line_idx": 3 }
import DefaultFormatter from "./_default"; import AMDFormatter from "./amd"; import object from "../../helpers/object"; import * as util from "../../util"; import last from "lodash/array/last"; import map from "lodash/collection/map"; import * as t from "../../types"; var hoistVariablesVisitor = { Function() { // nothing inside is accessible this.skip(); }, VariableDeclaration(node, parent, scope, state) { if (node.kind !== "var" && !t.isProgram(parent)) { // let, const // can't be accessed return; } // ignore block hoisted nodes as these can be left in if (state.formatter._canHoist(node)) return; var nodes = []; for (var i = 0; i < node.declarations.length; i++) { var declar = node.declarations[i]; state.hoistDeclarators.push(t.variableDeclarator(declar.id)); if (declar.init) { // no initializer so we can just hoist it as-is var assign = t.expressionStatement(t.assignmentExpression("=", declar.id, declar.init)); nodes.push(assign); } } // for (var i in test) // for (var i = 0;;) if (t.isFor(parent) && (parent.left === node || parent.init === node)) { return node.declarations[0].id; } return nodes; } }; var hoistFunctionsVisitor = { Function() { this.skip(); }, enter(node, parent, scope, state) { if (t.isFunctionDeclaration(node) || state.formatter._canHoist(node)) { state.handlerBody.push(node); this.dangerouslyRemove(); } } }; var runnerSettersVisitor = { enter(node, parent, scope, state) { if (node._importSource === state.source) { if (t.isVariableDeclaration(node)) { for (var declar of (node.declarations: Array)) { state.hoistDeclarators.push(t.variableDeclarator(declar.id)); state.nodes.push(t.expressionStatement( t.assignmentExpression("=", declar.id, declar.init) )); } } else { state.nodes.push(node); } this.dangerouslyRemove(); } } }; export default class SystemFormatter extends AMDFormatter { constructor(file) { super(file); this.exportIdentifier = file.scope.generateUidIdentifier("export"); this.noInteropRequireExport = true; this.noInteropRequireImport = true; } _addImportSource(node, exportNode) { if (node) node._importSource = exportNode.source && exportNode.source.value; return node; } buildExportsWildcard(objectIdentifier, node) { var leftIdentifier = this.scope.generateUidIdentifier("key"); var valIdentifier = t.memberExpression(objectIdentifier, leftIdentifier, true); var left = t.variableDeclaration("var", [ t.variableDeclarator(leftIdentifier) ]); var right = objectIdentifier; var block = t.blockStatement([ t.expressionStatement(this._buildExportCall(leftIdentifier, valIdentifier)) ]); return this._addImportSource(t.forInStatement(left, right, block), node); } buildExportsAssignment(id, init, node) { var call = this._buildExportCall(t.literal(id.name), init, true); return this._addImportSource(call, node); } buildExportsFromAssignment() { return this.buildExportsAssignment(...arguments); } remapExportAssignment(node, exported) { var assign = node; for (var i = 0; i < exported.length; i++) { assign = this._buildExportCall(t.literal(exported[i].name), assign); } return assign; } _buildExportCall(id, init, isStatement) { var call = t.callExpression(this.exportIdentifier, [id, init]); if (isStatement) { return t.expressionStatement(call); } else { return call; } } importSpecifier(specifier, node, nodes) { AMDFormatter.prototype.importSpecifier.apply(this, arguments); for (var name in this.internalRemap) { nodes.push(t.variableDeclaration("var", [ t.variableDeclarator(t.identifier(name), this.internalRemap[name]) ])); } this.internalRemap = object(); this._addImportSource(last(nodes), node); } _buildRunnerSetters(block, hoistDeclarators) { var scope = this.file.scope; return t.arrayExpression(map(this.ids, function (uid, source) { var state = { hoistDeclarators: hoistDeclarators, source: source, nodes: [] }; scope.traverse(block, runnerSettersVisitor, state); return t.functionExpression(null, [uid], t.blockStatement(state.nodes)); })); } _canHoist(node) { return node._blockHoist && !this.file.dynamicImports.length; } transform(program) { DefaultFormatter.prototype.transform.apply(this, arguments); var hoistDeclarators = []; var moduleName = this.getModuleName(); var moduleNameLiteral = t.literal(moduleName); var block = t.blockStatement(program.body); var runner = util.template("system", { MODULE_DEPENDENCIES: t.arrayExpression(this.buildDependencyLiterals()), EXPORT_IDENTIFIER: this.exportIdentifier, MODULE_NAME: moduleNameLiteral, SETTERS: this._buildRunnerSetters(block, hoistDeclarators), EXECUTE: t.functionExpression(null, [], block) }, true); var handlerBody = runner.expression.arguments[2].body.body; if (!moduleName) runner.expression.arguments.shift(); var returnStatement = handlerBody.pop(); // hoist up all variable declarations this.file.scope.traverse(block, hoistVariablesVisitor, { formatter: this, hoistDeclarators: hoistDeclarators }); if (hoistDeclarators.length) { var hoistDeclar = t.variableDeclaration("var", hoistDeclarators); hoistDeclar._blockHoist = true; handlerBody.unshift(hoistDeclar); } // hoist up function declarations for circular references this.file.scope.traverse(block, hoistFunctionsVisitor, { formatter: this, handlerBody: handlerBody }); handlerBody.push(returnStatement); program.body = [runner]; } }
src/babel/transformation/modules/system.js
0
https://github.com/babel/babel/commit/050bcec617117e21e240858edf310ff25bfa8d95
[ 0.0002181286836275831, 0.00017427673446945846, 0.0001625940203666687, 0.0001718824787531048, 0.00001177834565169178 ]
{ "id": 1, "code_window": [ "import Transformer from \"../transformer\";\n", "import Plugin from \"../plugin\";\n", "import * as types from \"../../types\";\n", "import traverse from \"../../types\";\n", "import parse from \"../../helpers/parse\";\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import * as messages from \"../../messages\";\n" ], "file_path": "src/babel/transformation/file/plugin-manager.js", "type": "add", "edit_start_line_idx": 3 }
(function (global, factory) { if (typeof define === "function" && define.amd) { define(["exports"], factory); } else if (typeof exports !== "undefined") { factory(exports); } else { var mod = { exports: {} }; factory(mod.exports); global.actual = mod.exports; } })(this, function (exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var test = 2; exports.test = test; exports.test = test = 5; exports.test = test += 1; (function () { var test = 2; test = 3; test++; })(); var a = 2; exports.a = a; exports.a = a = 3; var b = 2; exports.c = b; exports.c = b = 3; var d = 3; exports.e = d; exports.f = d; exports.f = exports.e = d = 4; });
test/core/fixtures/transformation/es6.modules-umd/remap/expected.js
0
https://github.com/babel/babel/commit/050bcec617117e21e240858edf310ff25bfa8d95
[ 0.00017925907741300762, 0.0001746841735439375, 0.0001693069061730057, 0.00017462973482906818, 0.0000037023448840045603 ]
{ "id": 1, "code_window": [ "import Transformer from \"../transformer\";\n", "import Plugin from \"../plugin\";\n", "import * as types from \"../../types\";\n", "import traverse from \"../../types\";\n", "import parse from \"../../helpers/parse\";\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import * as messages from \"../../messages\";\n" ], "file_path": "src/babel/transformation/file/plugin-manager.js", "type": "add", "edit_start_line_idx": 3 }
"use strict"; var s = Symbol("s"); assert.equal(typeof s === "undefined" ? "undefined" : babelHelpers._typeof(s), "symbol"); assert.equal(babelHelpers._typeof(babelHelpers._typeof(s.foo)), "symbol");
test/core/fixtures/transformation/es6.spec.symbols/typeof/expected.js
0
https://github.com/babel/babel/commit/050bcec617117e21e240858edf310ff25bfa8d95
[ 0.00017301591287832707, 0.00017301591287832707, 0.00017301591287832707, 0.00017301591287832707, 0 ]
{ "id": 2, "code_window": [ "import parse from \"../../helpers/parse\";\n", "\n", "var context = {\n", " Transformer,\n", " Plugin,\n", " types,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " messages,\n" ], "file_path": "src/babel/transformation/file/plugin-manager.js", "type": "add", "edit_start_line_idx": 7 }
import Transformer from "../transformer"; import Plugin from "../plugin"; import * as types from "../../types"; import traverse from "../../types"; import parse from "../../helpers/parse"; var context = { Transformer, Plugin, types, parse, traverse }; import * as messages from "../../messages"; import * as util from "../../util"; export default class PluginManager { static memoisedPlugins = []; static memoisePluginContainer(fn) { for (var i = 0; i < PluginManager.memoisedPlugins.length; i++) { var plugin = PluginManager.memoisedPlugins[i]; if (plugin.container === fn) return plugin.transformer; } var transformer = fn(context); PluginManager.memoisedPlugins.push({ container: fn, transformer: transformer }); return transformer; } static positions = ["before", "after"]; constructor({ file, transformers, before, after } = { transformers: {}, before: [], after: [] }) { this.transformers = transformers; this.file = file; this.before = before; this.after = after; } subnormaliseString(name, position) { // this is a plugin in the form of "foobar" or "foobar:after" // where the optional colon is the delimiter for plugin position in the transformer stack var match = name.match(/^(.*?):(after|before)$/); if (match) [, name, position] = match; var loc = util.resolveRelative(`babel-plugin-${name}`) || util.resolveRelative(name); if (loc) { var plugin = require(loc); return { position: position, plugin: plugin.default || plugin }; } else { throw new ReferenceError(messages.get("pluginUnknown", name)); } } validate(name, plugin) { // validate transformer key var key = plugin.key; if (this.transformers[key]) { throw new ReferenceError(messages.get("pluginKeyCollision", key)); } // validate Transformer instance if (!plugin.buildPass || plugin.constructor.name !== "Plugin") { throw new TypeError(messages.get("pluginNotTransformer", name)); } // register as a plugin plugin.metadata.plugin = true; } add(name) { var position; var plugin; if (name) { if (typeof name === "object" && name.transformer) { ({ transformer: plugin, position } = name); } else if (typeof name !== "string") { // not a string so we'll just assume that it's a direct Transformer instance, if not then // the checks later on will complain plugin = name; } if (typeof name === "string") { ({ plugin, position } = this.subnormaliseString(name, position)); } } else { throw new TypeError(messages.get("pluginIllegalKind", typeof name, name)); } // default position position = position || "before"; // validate position if (PluginManager.positions.indexOf(position) < 0) { throw new TypeError(messages.get("pluginIllegalPosition", position, name)); } // allow plugin containers to be specified so they don't have to manually require if (typeof plugin === "function") { plugin = PluginManager.memoisePluginContainer(plugin); } // this.validate(name, plugin); // build! var pass = this.transformers[plugin.key] = plugin.buildPass(this.file); if (pass.canTransform()) { var stack = position === "before" ? this.before : this.after; stack.push(pass); } } }
src/babel/transformation/file/plugin-manager.js
1
https://github.com/babel/babel/commit/050bcec617117e21e240858edf310ff25bfa8d95
[ 0.9987348914146423, 0.15674400329589844, 0.00018227985128760338, 0.002463249722495675, 0.3588961064815521 ]
{ "id": 2, "code_window": [ "import parse from \"../../helpers/parse\";\n", "\n", "var context = {\n", " Transformer,\n", " Plugin,\n", " types,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " messages,\n" ], "file_path": "src/babel/transformation/file/plugin-manager.js", "type": "add", "edit_start_line_idx": 7 }
"use strict"; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var z = _extends({}, x);
test/core/fixtures/transformation/es7.object-spread/variable-declaration/expected.js
0
https://github.com/babel/babel/commit/050bcec617117e21e240858edf310ff25bfa8d95
[ 0.0001682061265455559, 0.0001682061265455559, 0.0001682061265455559, 0.0001682061265455559, 0 ]