hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
listlengths
5
5
{ "id": 3, "code_window": [ " title: {\n", " label: label || this.props.adhocMetric.label,\n", " hasCustomLabel: !!label,\n", " },\n", " });\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " labelModified: true,\n" ], "file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx", "type": "add", "edit_start_line_idx": 67 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React, { ReactNode } from 'react'; import { Dropdown as AntdDropdown, Tooltip } from 'src/common/components'; import { styled } from '@superset-ui/core'; import kebabCase from 'lodash/kebabCase'; const MenuDots = styled.div` width: ${({ theme }) => theme.gridUnit * 0.75}px; height: ${({ theme }) => theme.gridUnit * 0.75}px; border-radius: 50%; background-color: ${({ theme }) => theme.colors.grayscale.light1}; font-weight: ${({ theme }) => theme.typography.weights.normal}; display: inline-flex; position: relative; &:hover { background-color: ${({ theme }) => theme.colors.primary.base}; &::before, &::after { background-color: ${({ theme }) => theme.colors.primary.base}; } } &::before, &::after { position: absolute; content: ' '; width: ${({ theme }) => theme.gridUnit * 0.75}px; height: ${({ theme }) => theme.gridUnit * 0.75}px; border-radius: 50%; background-color: ${({ theme }) => theme.colors.grayscale.light1}; } &::before { top: ${({ theme }) => theme.gridUnit}px; } &::after { bottom: ${({ theme }) => theme.gridUnit}px; } `; const MenuDotsWrapper = styled.div` display: flex; align-items: center; padding: ${({ theme }) => theme.gridUnit * 2}px; padding-left: ${({ theme }) => theme.gridUnit}px; `; const StyledDropdownButton = styled.div` .ant-btn-group { button.ant-btn { background-color: ${({ theme }) => theme.colors.primary.dark1}; border-color: transparent; color: ${({ theme }) => theme.colors.grayscale.light5}; font-size: 12px; line-height: 13px; outline: none; text-transform: uppercase; &:first-of-type { border-radius: ${({ theme }) => `${theme.gridUnit}px 0 0 ${theme.gridUnit}px`}; margin: 0; width: 120px; } &:last-of-type { margin: 0; border-radius: ${({ theme }) => `0 ${theme.gridUnit}px ${theme.gridUnit}px 0`}; width: ${({ theme }) => theme.gridUnit * 9}px; &:before, &:hover:before { border-left: 1px solid ${({ theme }) => theme.colors.grayscale.light5}; content: ''; display: block; height: 23px; margin: 0; position: absolute; top: ${({ theme }) => theme.gridUnit * 0.75}px; width: ${({ theme }) => theme.gridUnit * 0.25}px; } } } } `; export interface DropdownProps { overlay: React.ReactElement; tooltip?: string; placement?: 'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight'; buttonsRender?: ((buttons: ReactNode[]) => ReactNode[]) | undefined; } export const Dropdown = ({ overlay, ...rest }: DropdownProps) => ( <AntdDropdown overlay={overlay} {...rest}> <MenuDotsWrapper> <MenuDots /> </MenuDotsWrapper> </AntdDropdown> ); export const DropdownButton = ({ overlay, tooltip, placement, ...rest }: DropdownProps) => { const buildButton = ( props: { buttonsRender?: DropdownProps['buttonsRender']; } = {}, ) => ( <StyledDropdownButton> <AntdDropdown.Button overlay={overlay} {...rest} {...props} /> </StyledDropdownButton> ); if (tooltip) { return buildButton({ buttonsRender: ([leftButton, rightButton]) => [ <Tooltip placement={placement} id={`${kebabCase(tooltip)}-tooltip`} title={tooltip} > {leftButton} </Tooltip>, rightButton, ], }); } return buildButton(); };
superset-frontend/src/common/components/Dropdown.tsx
0
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
[ 0.002227670745924115, 0.0003740313113667071, 0.0001657768152654171, 0.00017397123156115413, 0.0005510025657713413 ]
{ "id": 3, "code_window": [ " title: {\n", " label: label || this.props.adhocMetric.label,\n", " hasCustomLabel: !!label,\n", " },\n", " });\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " labelModified: true,\n" ], "file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx", "type": "add", "edit_start_line_idx": 67 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Unit tests for Superset""" import json from copy import deepcopy from superset import app, db from superset.connectors.sqla.models import SqlaTable from superset.utils.core import get_example_database from .base_tests import SupersetTestCase from .fixtures.datasource import datasource_post class TestDatasource(SupersetTestCase): def test_external_metadata_for_physical_table(self): self.login(username="admin") tbl = self.get_table_by_name("birth_names") url = f"/datasource/external_metadata/table/{tbl.id}/" resp = self.get_json_resp(url) col_names = {o.get("name") for o in resp} self.assertEqual( col_names, {"num_boys", "num", "gender", "name", "ds", "state", "num_girls"} ) def test_external_metadata_for_virtual_table(self): self.login(username="admin") session = db.session table = SqlaTable( table_name="dummy_sql_table", database=get_example_database(), sql="select 123 as intcol, 'abc' as strcol", ) session.add(table) session.commit() table = self.get_table_by_name("dummy_sql_table") url = f"/datasource/external_metadata/table/{table.id}/" resp = self.get_json_resp(url) assert {o.get("name") for o in resp} == {"intcol", "strcol"} session.delete(table) session.commit() def test_external_metadata_for_malicious_virtual_table(self): self.login(username="admin") session = db.session table = SqlaTable( table_name="malicious_sql_table", database=get_example_database(), sql="delete table birth_names", ) session.add(table) session.commit() table = self.get_table_by_name("malicious_sql_table") url = f"/datasource/external_metadata/table/{table.id}/" resp = self.get_json_resp(url) assert "error" in resp session.delete(table) session.commit() def test_external_metadata_for_mutistatement_virtual_table(self): self.login(username="admin") session = db.session table = SqlaTable( table_name="multistatement_sql_table", database=get_example_database(), sql="select 123 as intcol, 'abc' as strcol;" "select 123 as intcol, 'abc' as strcol", ) session.add(table) session.commit() table = self.get_table_by_name("multistatement_sql_table") url = f"/datasource/external_metadata/table/{table.id}/" resp = self.get_json_resp(url) assert "error" in resp session.delete(table) session.commit() def compare_lists(self, l1, l2, key): l2_lookup = {o.get(key): o for o in l2} for obj1 in l1: obj2 = l2_lookup.get(obj1.get(key)) for k in obj1: if k not in "id" and obj1.get(k): self.assertEqual(obj1.get(k), obj2.get(k)) def test_save(self): self.login(username="admin") tbl_id = self.get_table_by_name("birth_names").id datasource_post["id"] = tbl_id data = dict(data=json.dumps(datasource_post)) resp = self.get_json_resp("/datasource/save/", data) for k in datasource_post: if k == "columns": self.compare_lists(datasource_post[k], resp[k], "column_name") elif k == "metrics": self.compare_lists(datasource_post[k], resp[k], "metric_name") elif k == "database": self.assertEqual(resp[k]["id"], datasource_post[k]["id"]) else: self.assertEqual(resp[k], datasource_post[k]) def save_datasource_from_dict(self, datasource_dict): data = dict(data=json.dumps(datasource_post)) resp = self.get_json_resp("/datasource/save/", data) return resp def test_change_database(self): self.login(username="admin") tbl = self.get_table_by_name("birth_names") tbl_id = tbl.id db_id = tbl.database_id datasource_post["id"] = tbl_id new_db = self.create_fake_db() datasource_post["database"]["id"] = new_db.id resp = self.save_datasource_from_dict(datasource_post) self.assertEqual(resp["database"]["id"], new_db.id) datasource_post["database"]["id"] = db_id resp = self.save_datasource_from_dict(datasource_post) self.assertEqual(resp["database"]["id"], db_id) self.delete_fake_db() def test_save_duplicate_key(self): self.login(username="admin") tbl_id = self.get_table_by_name("birth_names").id datasource_post_copy = deepcopy(datasource_post) datasource_post_copy["id"] = tbl_id datasource_post_copy["columns"].extend( [ { "column_name": "<new column>", "filterable": True, "groupby": True, "expression": "<enter SQL expression here>", "id": "somerandomid", }, { "column_name": "<new column>", "filterable": True, "groupby": True, "expression": "<enter SQL expression here>", "id": "somerandomid2", }, ] ) data = dict(data=json.dumps(datasource_post_copy)) resp = self.get_json_resp("/datasource/save/", data, raise_on_error=False) self.assertIn("Duplicate column name(s): <new column>", resp["error"]) def test_get_datasource(self): self.login(username="admin") tbl = self.get_table_by_name("birth_names") url = f"/datasource/get/{tbl.type}/{tbl.id}/" resp = self.get_json_resp(url) self.assertEqual(resp.get("type"), "table") col_names = {o.get("column_name") for o in resp["columns"]} self.assertEqual( col_names, { "num_boys", "num", "gender", "name", "ds", "state", "num_girls", "num_california", }, ) def test_get_datasource_with_health_check(self): def my_check(datasource): return "Warning message!" app.config["DATASET_HEALTH_CHECK"] = my_check my_check.version = 0.1 self.login(username="admin") tbl = self.get_table_by_name("birth_names") url = f"/datasource/get/{tbl.type}/{tbl.id}/" tbl.health_check(commit=True, force=True) resp = self.get_json_resp(url) self.assertEqual(resp["health_check_message"], "Warning message!") del app.config["DATASET_HEALTH_CHECK"] def test_get_datasource_failed(self): self.login(username="admin") url = f"/datasource/get/druid/500000/" resp = self.get_json_resp(url) self.assertEqual(resp.get("error"), "This datasource does not exist")
tests/datasource_tests.py
0
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
[ 0.00017618398123886436, 0.00017168294289149344, 0.00016683545254636556, 0.00017203141760546714, 0.0000025533270218147663 ]
{ "id": 4, "code_window": [ "\n", " closePopover() {\n", " this.togglePopover(false);\n", " }\n", "\n", " togglePopover(visible: boolean) {\n", " this.setState({\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.setState({\n", " labelModified: false,\n", " });\n" ], "file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx", "type": "add", "edit_start_line_idx": 76 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React, { ReactNode } from 'react'; import Popover from 'src/common/components/Popover'; import AdhocMetricEditPopoverTitle from 'src/explore/components/AdhocMetricEditPopoverTitle'; import AdhocMetricEditPopover from './AdhocMetricEditPopover'; import AdhocMetric from '../AdhocMetric'; import { savedMetricType } from '../types'; export type AdhocMetricPopoverTriggerProps = { adhocMetric: AdhocMetric; onMetricEdit: () => void; columns: { column_name: string; type: string }[]; savedMetrics: savedMetricType[]; savedMetric: savedMetricType; datasourceType: string; children: ReactNode; createNew?: boolean; }; export type AdhocMetricPopoverTriggerState = { popoverVisible: boolean; title: { label: string; hasCustomLabel: boolean }; }; class AdhocMetricPopoverTrigger extends React.PureComponent< AdhocMetricPopoverTriggerProps, AdhocMetricPopoverTriggerState > { constructor(props: AdhocMetricPopoverTriggerProps) { super(props); this.onPopoverResize = this.onPopoverResize.bind(this); this.onLabelChange = this.onLabelChange.bind(this); this.closePopover = this.closePopover.bind(this); this.togglePopover = this.togglePopover.bind(this); this.state = { popoverVisible: false, title: { label: props.adhocMetric.label, hasCustomLabel: props.adhocMetric.hasCustomLabel, }, }; } onLabelChange(e: any) { const label = e.target.value; this.setState({ title: { label: label || this.props.adhocMetric.label, hasCustomLabel: !!label, }, }); } onPopoverResize() { this.forceUpdate(); } closePopover() { this.togglePopover(false); } togglePopover(visible: boolean) { this.setState({ popoverVisible: visible, }); } render() { const { adhocMetric } = this.props; const overlayContent = ( <AdhocMetricEditPopover adhocMetric={adhocMetric} title={this.state.title} columns={this.props.columns} savedMetrics={this.props.savedMetrics} savedMetric={this.props.savedMetric} datasourceType={this.props.datasourceType} onResize={this.onPopoverResize} onClose={this.closePopover} onChange={this.props.onMetricEdit} /> ); const popoverTitle = ( <AdhocMetricEditPopoverTitle title={this.state.title} defaultLabel={adhocMetric.label} onChange={this.onLabelChange} /> ); return ( <Popover placement="right" trigger="click" content={overlayContent} defaultVisible={this.state.popoverVisible} visible={this.state.popoverVisible} onVisibleChange={this.togglePopover} title={popoverTitle} destroyTooltipOnHide={this.props.createNew} > {this.props.children} </Popover> ); } } export default AdhocMetricPopoverTrigger;
superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx
1
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
[ 0.9987093210220337, 0.3402681350708008, 0.00016704924928490072, 0.0009703753748908639, 0.44988924264907837 ]
{ "id": 4, "code_window": [ "\n", " closePopover() {\n", " this.togglePopover(false);\n", " }\n", "\n", " togglePopover(visible: boolean) {\n", " this.setState({\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.setState({\n", " labelModified: false,\n", " });\n" ], "file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx", "type": "add", "edit_start_line_idx": 76 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """fix data access permissions for virtual datasets Revision ID: 3fbbc6e8d654 Revises: e5ef6828ac4e Create Date: 2020-09-24 12:04:33.827436 """ # revision identifiers, used by Alembic. revision = "3fbbc6e8d654" down_revision = "e5ef6828ac4e" import re from alembic import op from sqlalchemy import ( Column, ForeignKey, Integer, orm, Sequence, String, Table, UniqueConstraint, ) from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import backref, relationship Base = declarative_base() # Partial freeze of the current metadata db schema class Permission(Base): __tablename__ = "ab_permission" id = Column(Integer, Sequence("ab_permission_id_seq"), primary_key=True) name = Column(String(100), unique=True, nullable=False) class ViewMenu(Base): __tablename__ = "ab_view_menu" id = Column(Integer, Sequence("ab_view_menu_id_seq"), primary_key=True) name = Column(String(250), unique=True, nullable=False) def __eq__(self, other): return (isinstance(other, self.__class__)) and (self.name == other.name) def __neq__(self, other): return self.name != other.name assoc_permissionview_role = Table( "ab_permission_view_role", Base.metadata, Column("id", Integer, Sequence("ab_permission_view_role_id_seq"), primary_key=True), Column("permission_view_id", Integer, ForeignKey("ab_permission_view.id")), Column("role_id", Integer, ForeignKey("ab_role.id")), UniqueConstraint("permission_view_id", "role_id"), ) class Role(Base): __tablename__ = "ab_role" id = Column(Integer, Sequence("ab_role_id_seq"), primary_key=True) name = Column(String(64), unique=True, nullable=False) permissions = relationship( "PermissionView", secondary=assoc_permissionview_role, backref="role" ) class PermissionView(Base): __tablename__ = "ab_permission_view" __table_args__ = (UniqueConstraint("permission_id", "view_menu_id"),) id = Column(Integer, Sequence("ab_permission_view_id_seq"), primary_key=True) permission_id = Column(Integer, ForeignKey("ab_permission.id")) permission = relationship("Permission") view_menu_id = Column(Integer, ForeignKey("ab_view_menu.id")) view_menu = relationship("ViewMenu") sqlatable_user = Table( "sqlatable_user", Base.metadata, Column("id", Integer, primary_key=True), Column("user_id", Integer, ForeignKey("ab_user.id")), Column("table_id", Integer, ForeignKey("tables.id")), ) class Database(Base): # pylint: disable=too-many-public-methods """An ORM object that stores Database related information""" __tablename__ = "dbs" __table_args__ = (UniqueConstraint("database_name"),) id = Column(Integer, primary_key=True) verbose_name = Column(String(250), unique=True) # short unique name, used in permissions database_name = Column(String(250), unique=True, nullable=False) def __repr__(self) -> str: return self.name @property def name(self) -> str: return self.verbose_name if self.verbose_name else self.database_name class SqlaTable(Base): __tablename__ = "tables" __table_args__ = (UniqueConstraint("database_id", "table_name"),) # Base columns from Basedatasource id = Column(Integer, primary_key=True) table_name = Column(String(250), nullable=False) database_id = Column(Integer, ForeignKey("dbs.id"), nullable=False) database = relationship( "Database", backref=backref("tables", cascade="all, delete-orphan"), foreign_keys=[database_id], ) def get_perm(self) -> str: return f"[{self.database}].[{self.table_name}](id:{self.id})" def upgrade(): """ Previous sqla_viz behaviour when creating a virtual dataset was faulty by creating an associated data access permission with [None] on the database name. This migration revision, fixes all faulty permissions that may exist on the db Only fixes permissions that still have an associated dataset (fetch by id) and replaces them with the current (correct) permission name """ bind = op.get_bind() session = orm.Session(bind=bind) faulty_view_menus = ( session.query(ViewMenu) .join(PermissionView) .join(Permission) .filter(ViewMenu.name.ilike("[None].[%](id:%)")) .filter(Permission.name == "datasource_access") .all() ) orphaned_faulty_view_menus = [] for faulty_view_menu in faulty_view_menus: # Get the dataset id from the view_menu name match_ds_id = re.match("\[None\]\.\[.*\]\(id:(\d+)\)", faulty_view_menu.name) if match_ds_id: dataset_id = int(match_ds_id.group(1)) dataset = session.query(SqlaTable).get(dataset_id) if dataset: try: new_view_menu = dataset.get_perm() except Exception: # This can fail on differing SECRET_KEYS return existing_view_menu = ( session.query(ViewMenu) .filter(ViewMenu.name == new_view_menu) .one_or_none() ) # A view_menu permission with the right name already exists, # so delete the faulty one later if existing_view_menu: orphaned_faulty_view_menus.append(faulty_view_menu) # No view_menu permission with this name exists # so safely change this one else: faulty_view_menu.name = new_view_menu # Commit all view_menu updates try: session.commit() except SQLAlchemyError: session.rollback() # Delete all orphaned faulty permissions for orphaned_faulty_view_menu in orphaned_faulty_view_menus: pvm = ( session.query(PermissionView) .filter(PermissionView.view_menu == orphaned_faulty_view_menu) .one_or_none() ) if pvm: # Removes orphaned pvm from all roles roles = session.query(Role).filter(Role.permissions.contains(pvm)).all() for role in roles: if pvm in role.permissions: role.permissions.remove(pvm) # Now it's safe to remove the pvm pair session.delete(pvm) # finally remove the orphaned view_menu permission session.delete(orphaned_faulty_view_menu) try: session.commit() except SQLAlchemyError: session.rollback() def downgrade(): pass
superset/migrations/versions/3fbbc6e8d654_fix_data_access_permissions_for_virtual_.py
0
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
[ 0.00018016743706539273, 0.0001711907534627244, 0.0001645865704631433, 0.00017095866496674716, 0.0000037309571325749857 ]
{ "id": 4, "code_window": [ "\n", " closePopover() {\n", " this.togglePopover(false);\n", " }\n", "\n", " togglePopover(visible: boolean) {\n", " this.setState({\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.setState({\n", " labelModified: false,\n", " });\n" ], "file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx", "type": "add", "edit_start_line_idx": 76 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { t, styled } from '@superset-ui/core'; import React, { useState } from 'react'; import { FormGroup, FormControl, FormControlProps } from 'react-bootstrap'; import Modal from 'src/common/components/Modal'; import FormLabel from 'src/components/FormLabel'; const StyleFormGroup = styled(FormGroup)` padding-top: 8px; width: 50%; label { color: ${({ theme }) => theme.colors.grayscale.light1}; text-transform: uppercase; } `; const DescriptionContainer = styled.div` line-height: 40px; padding-top: 16px; `; interface DeleteModalProps { description: React.ReactNode; onConfirm: () => void; onHide: () => void; open: boolean; title: React.ReactNode; } export default function DeleteModal({ description, onConfirm, onHide, open, title, }: DeleteModalProps) { const [disableChange, setDisableChange] = useState(true); return ( <Modal disablePrimaryButton={disableChange} onHide={onHide} onHandledPrimaryAction={onConfirm} primaryButtonName={t('delete')} primaryButtonType="danger" show={open} title={title} > <DescriptionContainer>{description}</DescriptionContainer> <StyleFormGroup> <FormLabel htmlFor="delete"> {t('Type "%s" to confirm', t('DELETE'))} </FormLabel> <FormControl data-test="delete-modal-input" id="delete" type="text" bsSize="sm" autoComplete="off" onChange={( event: React.FormEvent<FormControl & FormControlProps>, ) => { const targetValue = (event.currentTarget?.value as string) ?? ''; setDisableChange(targetValue.toUpperCase() !== t('DELETE')); }} /> </StyleFormGroup> </Modal> ); }
superset-frontend/src/components/DeleteModal.tsx
0
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
[ 0.00017855421174317598, 0.0001720835716696456, 0.00016603544645477086, 0.0001723403693176806, 0.0000034769427657010965 ]
{ "id": 4, "code_window": [ "\n", " closePopover() {\n", " this.togglePopover(false);\n", " }\n", "\n", " togglePopover(visible: boolean) {\n", " this.setState({\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.setState({\n", " labelModified: false,\n", " });\n" ], "file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx", "type": "add", "edit_start_line_idx": 76 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { TABS_TYPE } from './componentTypes'; import { DASHBOARD_ROOT_ID } from './constants'; export default function findFirstParentContainerId(layout = {}) { // DASHBOARD_GRID_TYPE or TABS_TYPE? let parent = layout[DASHBOARD_ROOT_ID]; if ( parent && parent.children.length && layout[parent.children[0]].type === TABS_TYPE ) { const tabs = layout[parent.children[0]]; parent = layout[tabs.children[0]]; } else { parent = layout[parent.children[0]]; } return parent.id; }
superset-frontend/src/dashboard/util/findFirstParentContainer.js
0
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
[ 0.00017855096666608006, 0.0001733271637931466, 0.00016871499246917665, 0.00017302135529462248, 0.0000036992787499912083 ]
{ "id": 5, "code_window": [ " }\n", "\n", " render() {\n", " const { adhocMetric } = this.props;\n", "\n", " const overlayContent = (\n", " <AdhocMetricEditPopover\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const { label, hasCustomLabel } = adhocMetric;\n", " const title = this.state.labelModified\n", " ? this.state.title\n", " : { label, hasCustomLabel };\n" ], "file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx", "type": "add", "edit_start_line_idx": 86 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React, { ReactNode } from 'react'; import Popover from 'src/common/components/Popover'; import AdhocMetricEditPopoverTitle from 'src/explore/components/AdhocMetricEditPopoverTitle'; import AdhocMetricEditPopover from './AdhocMetricEditPopover'; import AdhocMetric from '../AdhocMetric'; import { savedMetricType } from '../types'; export type AdhocMetricPopoverTriggerProps = { adhocMetric: AdhocMetric; onMetricEdit: () => void; columns: { column_name: string; type: string }[]; savedMetrics: savedMetricType[]; savedMetric: savedMetricType; datasourceType: string; children: ReactNode; createNew?: boolean; }; export type AdhocMetricPopoverTriggerState = { popoverVisible: boolean; title: { label: string; hasCustomLabel: boolean }; }; class AdhocMetricPopoverTrigger extends React.PureComponent< AdhocMetricPopoverTriggerProps, AdhocMetricPopoverTriggerState > { constructor(props: AdhocMetricPopoverTriggerProps) { super(props); this.onPopoverResize = this.onPopoverResize.bind(this); this.onLabelChange = this.onLabelChange.bind(this); this.closePopover = this.closePopover.bind(this); this.togglePopover = this.togglePopover.bind(this); this.state = { popoverVisible: false, title: { label: props.adhocMetric.label, hasCustomLabel: props.adhocMetric.hasCustomLabel, }, }; } onLabelChange(e: any) { const label = e.target.value; this.setState({ title: { label: label || this.props.adhocMetric.label, hasCustomLabel: !!label, }, }); } onPopoverResize() { this.forceUpdate(); } closePopover() { this.togglePopover(false); } togglePopover(visible: boolean) { this.setState({ popoverVisible: visible, }); } render() { const { adhocMetric } = this.props; const overlayContent = ( <AdhocMetricEditPopover adhocMetric={adhocMetric} title={this.state.title} columns={this.props.columns} savedMetrics={this.props.savedMetrics} savedMetric={this.props.savedMetric} datasourceType={this.props.datasourceType} onResize={this.onPopoverResize} onClose={this.closePopover} onChange={this.props.onMetricEdit} /> ); const popoverTitle = ( <AdhocMetricEditPopoverTitle title={this.state.title} defaultLabel={adhocMetric.label} onChange={this.onLabelChange} /> ); return ( <Popover placement="right" trigger="click" content={overlayContent} defaultVisible={this.state.popoverVisible} visible={this.state.popoverVisible} onVisibleChange={this.togglePopover} title={popoverTitle} destroyTooltipOnHide={this.props.createNew} > {this.props.children} </Popover> ); } } export default AdhocMetricPopoverTrigger;
superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx
1
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
[ 0.9992432594299316, 0.31570154428482056, 0.0001696588733466342, 0.017442116513848305, 0.4555456340312958 ]
{ "id": 5, "code_window": [ " }\n", "\n", " render() {\n", " const { adhocMetric } = this.props;\n", "\n", " const overlayContent = (\n", " <AdhocMetricEditPopover\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const { label, hasCustomLabel } = adhocMetric;\n", " const title = this.state.labelModified\n", " ? this.state.title\n", " : { label, hasCustomLabel };\n" ], "file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx", "type": "add", "edit_start_line_idx": 86 }
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M7.29 11.29L11.29 7.29C11.5437 7.03634 11.9134 6.93728 12.2599 7.03012C12.6064 7.12297 12.877 7.39362 12.9699 7.74012C13.0627 8.08663 12.9637 8.45634 12.71 8.71L10.41 11H19C19.5523 11 20 11.4477 20 12C20 12.5523 19.5523 13 19 13H10.41L12.71 15.29C12.8993 15.4778 13.0058 15.7334 13.0058 16C13.0058 16.2666 12.8993 16.5222 12.71 16.71C12.5222 16.8993 12.2666 17.0058 12 17.0058C11.7334 17.0058 11.4778 16.8993 11.29 16.71L7.29 12.71C7.19896 12.6149 7.12759 12.5028 7.08 12.38C6.97998 12.1365 6.97998 11.8635 7.08 11.62C7.12759 11.4972 7.19896 11.3851 7.29 11.29ZM4 4C4.55229 4 5 4.44772 5 5V19C5 19.5523 4.55229 20 4 20C3.44772 20 3 19.5523 3 19V5C3 4.44772 3.44772 4 4 4Z" fill="currentColor"/> </svg>
superset-frontend/images/icons/expand.svg
0
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
[ 0.0034361339639872313, 0.0012636358151212335, 0.00017643178580328822, 0.00017834169557318091, 0.0015361884143203497 ]
{ "id": 5, "code_window": [ " }\n", "\n", " render() {\n", " const { adhocMetric } = this.props;\n", "\n", " const overlayContent = (\n", " <AdhocMetricEditPopover\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const { label, hasCustomLabel } = adhocMetric;\n", " const title = this.state.labelModified\n", " ? this.state.title\n", " : { label, hasCustomLabel };\n" ], "file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx", "type": "add", "edit_start_line_idx": 86 }
#!/usr/bin/env ruby require "json" require "octokit" json = File.read(ENV.fetch("GITHUB_EVENT_PATH")) event = JSON.parse(json) github = Octokit::Client.new(access_token: ENV["GITHUB_TOKEN"]) if !ENV["GITHUB_TOKEN"] puts "Missing GITHUB_TOKEN" exit(1) end if ARGV.empty? puts "Missing message argument." exit(1) end repo = event["repository"]["full_name"] if ENV.fetch("GITHUB_EVENT_NAME") == "pull_request" pr_number = event["number"] else pulls = github.pull_requests(repo, state: "open") push_head = event["after"] pr = pulls.find { |pr| pr["head"]["sha"] == push_head } if !pr puts "Couldn't find an open pull request for branch with head at #{push_head}." exit(1) end pr_number = pr["number"] end message = ARGV.join(' ') coms = github.issue_comments(repo, pr_number) duplicate = coms.find { |c| c["user"]["login"] == "github-actions[bot]" && c["body"] == message } if duplicate puts "The PR already contains a database change notification" exit(0) end github.add_comment(repo, pr_number, message)
.github/actions/comment-on-pr/entrypoint.sh
0
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
[ 0.0001750002702465281, 0.00017346497043035924, 0.00017111831402871758, 0.00017327064415439963, 0.0000014374844568010303 ]
{ "id": 5, "code_window": [ " }\n", "\n", " render() {\n", " const { adhocMetric } = this.props;\n", "\n", " const overlayContent = (\n", " <AdhocMetricEditPopover\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const { label, hasCustomLabel } = adhocMetric;\n", " const title = this.state.labelModified\n", " ? this.state.title\n", " : { label, hasCustomLabel };\n" ], "file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx", "type": "add", "edit_start_line_idx": 86 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Add slack to the schedule Revision ID: 743a117f0d98 Revises: 620241d1153f Create Date: 2020-05-13 21:01:26.163478 """ # revision identifiers, used by Alembic. revision = "743a117f0d98" down_revision = "620241d1153f" import sqlalchemy as sa from alembic import op def upgrade(): op.add_column( "dashboard_email_schedules", sa.Column("slack_channel", sa.Text(), nullable=True), ) op.add_column( "slice_email_schedules", sa.Column("slack_channel", sa.Text(), nullable=True) ) def downgrade(): op.drop_column("dashboard_email_schedules", "slack_channel") op.drop_column("slice_email_schedules", "slack_channel")
superset/migrations/versions/743a117f0d98_add_slack_to_the_schedule.py
0
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
[ 0.00017714938439894468, 0.00017250460223294795, 0.0001664674491621554, 0.00017214377294294536, 0.000004175889444013592 ]
{ "id": 6, "code_window": [ "\n", " const overlayContent = (\n", " <AdhocMetricEditPopover\n", " adhocMetric={adhocMetric}\n", " title={this.state.title}\n", " columns={this.props.columns}\n", " savedMetrics={this.props.savedMetrics}\n", " savedMetric={this.props.savedMetric}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " title={title}\n" ], "file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx", "type": "replace", "edit_start_line_idx": 90 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React, { ReactNode } from 'react'; import Popover from 'src/common/components/Popover'; import AdhocMetricEditPopoverTitle from 'src/explore/components/AdhocMetricEditPopoverTitle'; import AdhocMetricEditPopover from './AdhocMetricEditPopover'; import AdhocMetric from '../AdhocMetric'; import { savedMetricType } from '../types'; export type AdhocMetricPopoverTriggerProps = { adhocMetric: AdhocMetric; onMetricEdit: () => void; columns: { column_name: string; type: string }[]; savedMetrics: savedMetricType[]; savedMetric: savedMetricType; datasourceType: string; children: ReactNode; createNew?: boolean; }; export type AdhocMetricPopoverTriggerState = { popoverVisible: boolean; title: { label: string; hasCustomLabel: boolean }; }; class AdhocMetricPopoverTrigger extends React.PureComponent< AdhocMetricPopoverTriggerProps, AdhocMetricPopoverTriggerState > { constructor(props: AdhocMetricPopoverTriggerProps) { super(props); this.onPopoverResize = this.onPopoverResize.bind(this); this.onLabelChange = this.onLabelChange.bind(this); this.closePopover = this.closePopover.bind(this); this.togglePopover = this.togglePopover.bind(this); this.state = { popoverVisible: false, title: { label: props.adhocMetric.label, hasCustomLabel: props.adhocMetric.hasCustomLabel, }, }; } onLabelChange(e: any) { const label = e.target.value; this.setState({ title: { label: label || this.props.adhocMetric.label, hasCustomLabel: !!label, }, }); } onPopoverResize() { this.forceUpdate(); } closePopover() { this.togglePopover(false); } togglePopover(visible: boolean) { this.setState({ popoverVisible: visible, }); } render() { const { adhocMetric } = this.props; const overlayContent = ( <AdhocMetricEditPopover adhocMetric={adhocMetric} title={this.state.title} columns={this.props.columns} savedMetrics={this.props.savedMetrics} savedMetric={this.props.savedMetric} datasourceType={this.props.datasourceType} onResize={this.onPopoverResize} onClose={this.closePopover} onChange={this.props.onMetricEdit} /> ); const popoverTitle = ( <AdhocMetricEditPopoverTitle title={this.state.title} defaultLabel={adhocMetric.label} onChange={this.onLabelChange} /> ); return ( <Popover placement="right" trigger="click" content={overlayContent} defaultVisible={this.state.popoverVisible} visible={this.state.popoverVisible} onVisibleChange={this.togglePopover} title={popoverTitle} destroyTooltipOnHide={this.props.createNew} > {this.props.children} </Popover> ); } } export default AdhocMetricPopoverTrigger;
superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx
1
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
[ 0.9983041286468506, 0.23411162197589874, 0.00016652903286740184, 0.020767971873283386, 0.3864765763282776 ]
{ "id": 6, "code_window": [ "\n", " const overlayContent = (\n", " <AdhocMetricEditPopover\n", " adhocMetric={adhocMetric}\n", " title={this.state.title}\n", " columns={this.props.columns}\n", " savedMetrics={this.props.savedMetrics}\n", " savedMetric={this.props.savedMetric}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " title={title}\n" ], "file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx", "type": "replace", "edit_start_line_idx": 90 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Add Parent ids in dashboard layout metadata Revision ID: 80aa3f04bc82 Revises: 45e7da7cfeba Create Date: 2019-04-09 16:27:03.392872 """ import json import logging import sqlalchemy as sa from alembic import op from sqlalchemy import Column, Integer, Text from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from superset import db # revision identifiers, used by Alembic. revision = "80aa3f04bc82" down_revision = "45e7da7cfeba" Base = declarative_base() class Dashboard(Base): """Declarative class to do query in upgrade""" __tablename__ = "dashboards" id = Column(Integer, primary_key=True) position_json = Column(Text) def add_parent_ids(node, layout): if node: current_id = node.get("id") parents = list(node.get("parents") or []) child_ids = node.get("children") if child_ids and len(child_ids) > 0: parents.append(current_id) for child_id in child_ids: child_node = layout.get(child_id) child_node["parents"] = parents add_parent_ids(child_node, layout) def upgrade(): bind = op.get_bind() session = db.Session(bind=bind) dashboards = session.query(Dashboard).all() for i, dashboard in enumerate(dashboards): print( "adding parents for dashboard layout, id = {} ({}/{}) >>>>".format( dashboard.id, i + 1, len(dashboards) ) ) try: layout = json.loads(dashboard.position_json or "{}") if layout and layout["ROOT_ID"]: add_parent_ids(layout["ROOT_ID"], layout) dashboard.position_json = json.dumps( layout, indent=None, separators=(",", ":"), sort_keys=True ) session.merge(dashboard) except Exception as ex: logging.exception(ex) session.commit() session.close() def downgrade(): bind = op.get_bind() session = db.Session(bind=bind) dashboards = session.query(Dashboard).all() for i, dashboard in enumerate(dashboards): print( "remove parents from dashboard layout, id = {} ({}/{}) >>>>".format( dashboard.id, i + 1, len(dashboards) ) ) try: layout = json.loads(dashboard.position_json or "{}") for key, item in layout.items(): if not isinstance(item, dict): continue item.pop("parents", None) layout[key] = item dashboard.position_json = json.dumps( layout, indent=None, separators=(",", ":"), sort_keys=True ) session.merge(dashboard) except Exception as ex: logging.exception(ex) session.commit() session.close()
superset/migrations/versions/80aa3f04bc82_add_parent_ids_in_dashboard_layout.py
0
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
[ 0.0003991459379903972, 0.0002133897360181436, 0.00016768518253229558, 0.00017436666530556977, 0.00008380658982787281 ]
{ "id": 6, "code_window": [ "\n", " const overlayContent = (\n", " <AdhocMetricEditPopover\n", " adhocMetric={adhocMetric}\n", " title={this.state.title}\n", " columns={this.props.columns}\n", " savedMetrics={this.props.savedMetrics}\n", " savedMetric={this.props.savedMetric}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " title={title}\n" ], "file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx", "type": "replace", "edit_start_line_idx": 90 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { CHART_LIST } from './chart_list.helper'; describe('chart list view', () => { beforeEach(() => { cy.login(); cy.server(); cy.visit(CHART_LIST); cy.get('[data-test="list-view"]').click(); }); it('should load rows', () => { cy.get('[data-test="listview-table"]').should('be.visible'); // check chart list view header cy.get('[data-test="sort-header"]').eq(1).contains('Chart'); cy.get('[data-test="sort-header"]').eq(2).contains('Visualization Type'); cy.get('[data-test="sort-header"]').eq(3).contains('Dataset'); cy.get('[data-test="sort-header"]').eq(4).contains('Modified By'); cy.get('[data-test="sort-header"]').eq(5).contains('Last Modified'); cy.get('[data-test="sort-header"]').eq(6).contains('Created By'); cy.get('[data-test="sort-header"]').eq(7).contains('Actions'); cy.get('[data-test="table-row"]').should('have.length', 25); }); it('should sort correctly', () => { cy.get('[data-test="sort-header"]').eq(2).click(); cy.get('[data-test="sort-header"]').eq(2).click(); cy.get('[data-test="table-row"]') .first() .find('[data-test="table-row-cell"]') .find('[data-test="cell-text"]') .contains('Country of Citizenship'); }); });
superset-frontend/cypress-base/cypress/integration/chart_list/list_view.test.ts
0
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
[ 0.00017778394976630807, 0.00017618686251807958, 0.00017465304699726403, 0.00017655742703936994, 0.0000011395504770916887 ]
{ "id": 6, "code_window": [ "\n", " const overlayContent = (\n", " <AdhocMetricEditPopover\n", " adhocMetric={adhocMetric}\n", " title={this.state.title}\n", " columns={this.props.columns}\n", " savedMetrics={this.props.savedMetrics}\n", " savedMetric={this.props.savedMetric}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " title={title}\n" ], "file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx", "type": "replace", "edit_start_line_idx": 90 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import PropTypes from 'prop-types'; import { ClassNames } from '@emotion/core'; import { styled, useTheme } from '@superset-ui/core'; import { Tooltip } from 'src/common/components/Tooltip'; const propTypes = { column: PropTypes.object.isRequired, }; const StyledTooltip = (props: any) => { const theme = useTheme(); return ( <ClassNames> {({ css }) => ( <Tooltip overlayClassName={css` .ant-tooltip-inner { max-width: ${theme.gridUnit * 125}px; word-wrap: break-word; text-align: center; pre { background: transparent; border: none; text-align: left; color: ${theme.colors.grayscale.light5}; font-size: ${theme.typography.sizes.xs}px; } } `} {...props} /> )} </ClassNames> ); }; const Hr = styled.hr` margin-top: ${({ theme }) => theme.gridUnit * 1.5}px; `; const iconMap = { pk: 'fa-key', fk: 'fa-link', index: 'fa-bookmark', }; const tooltipTitleMap = { pk: 'Primary Key', fk: 'Foreign Key', index: 'Index', }; export type ColumnKeyTypeType = keyof typeof tooltipTitleMap; interface ColumnElementProps { column: { name: string; keys?: { type: ColumnKeyTypeType }[]; type: string; }; } export default function ColumnElement({ column }: ColumnElementProps) { let columnName: React.ReactNode = column.name; let icons; if (column.keys && column.keys.length > 0) { columnName = <strong>{column.name}</strong>; icons = column.keys.map((key, i) => ( <span key={i} className="ColumnElement"> <StyledTooltip placement="right" title={ <> <strong>{tooltipTitleMap[key.type]}</strong> <Hr /> <pre className="text-small"> {JSON.stringify(key, null, ' ')} </pre> </> } > <i className={`fa text-muted m-l-2 ${iconMap[key.type]}`} /> </StyledTooltip> </span> )); } return ( <div className="clearfix table-column"> <div className="pull-left m-l-10 col-name"> {columnName} {icons} </div> <div className="pull-right text-muted"> <small> {column.type}</small> </div> </div> ); } ColumnElement.propTypes = propTypes;
superset-frontend/src/SqlLab/components/ColumnElement.tsx
0
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
[ 0.0001768226793501526, 0.00017189061327371746, 0.00016625058196950704, 0.00017246701463591307, 0.000003862056018988369 ]
{ "id": 7, "code_window": [ " );\n", "\n", " const popoverTitle = (\n", " <AdhocMetricEditPopoverTitle\n", " title={this.state.title}\n", " defaultLabel={adhocMetric.label}\n", " onChange={this.onLabelChange}\n", " />\n", " );\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " title={title}\n" ], "file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx", "type": "replace", "edit_start_line_idx": 103 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React, { ReactNode } from 'react'; import Popover from 'src/common/components/Popover'; import AdhocMetricEditPopoverTitle from 'src/explore/components/AdhocMetricEditPopoverTitle'; import AdhocMetricEditPopover from './AdhocMetricEditPopover'; import AdhocMetric from '../AdhocMetric'; import { savedMetricType } from '../types'; export type AdhocMetricPopoverTriggerProps = { adhocMetric: AdhocMetric; onMetricEdit: () => void; columns: { column_name: string; type: string }[]; savedMetrics: savedMetricType[]; savedMetric: savedMetricType; datasourceType: string; children: ReactNode; createNew?: boolean; }; export type AdhocMetricPopoverTriggerState = { popoverVisible: boolean; title: { label: string; hasCustomLabel: boolean }; }; class AdhocMetricPopoverTrigger extends React.PureComponent< AdhocMetricPopoverTriggerProps, AdhocMetricPopoverTriggerState > { constructor(props: AdhocMetricPopoverTriggerProps) { super(props); this.onPopoverResize = this.onPopoverResize.bind(this); this.onLabelChange = this.onLabelChange.bind(this); this.closePopover = this.closePopover.bind(this); this.togglePopover = this.togglePopover.bind(this); this.state = { popoverVisible: false, title: { label: props.adhocMetric.label, hasCustomLabel: props.adhocMetric.hasCustomLabel, }, }; } onLabelChange(e: any) { const label = e.target.value; this.setState({ title: { label: label || this.props.adhocMetric.label, hasCustomLabel: !!label, }, }); } onPopoverResize() { this.forceUpdate(); } closePopover() { this.togglePopover(false); } togglePopover(visible: boolean) { this.setState({ popoverVisible: visible, }); } render() { const { adhocMetric } = this.props; const overlayContent = ( <AdhocMetricEditPopover adhocMetric={adhocMetric} title={this.state.title} columns={this.props.columns} savedMetrics={this.props.savedMetrics} savedMetric={this.props.savedMetric} datasourceType={this.props.datasourceType} onResize={this.onPopoverResize} onClose={this.closePopover} onChange={this.props.onMetricEdit} /> ); const popoverTitle = ( <AdhocMetricEditPopoverTitle title={this.state.title} defaultLabel={adhocMetric.label} onChange={this.onLabelChange} /> ); return ( <Popover placement="right" trigger="click" content={overlayContent} defaultVisible={this.state.popoverVisible} visible={this.state.popoverVisible} onVisibleChange={this.togglePopover} title={popoverTitle} destroyTooltipOnHide={this.props.createNew} > {this.props.children} </Popover> ); } } export default AdhocMetricPopoverTrigger;
superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx
1
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
[ 0.9985253214836121, 0.16059698164463043, 0.00016936827159952372, 0.007864337414503098, 0.35735204815864563 ]
{ "id": 7, "code_window": [ " );\n", "\n", " const popoverTitle = (\n", " <AdhocMetricEditPopoverTitle\n", " title={this.state.title}\n", " defaultLabel={adhocMetric.label}\n", " onChange={this.onLabelChange}\n", " />\n", " );\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " title={title}\n" ], "file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx", "type": "replace", "edit_start_line_idx": 103 }
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M12 13C11.3765 12.9927 10.8143 13.3745 10.5912 13.9568C10.3681 14.5391 10.5312 15.1988 11 15.61V17C11 17.5523 11.4477 18 12 18C12.5523 18 13 17.5523 13 17V15.61C13.4688 15.1988 13.6319 14.5391 13.4088 13.9568C13.1857 13.3745 12.6235 12.9927 12 13ZM17 9V7C17 4.23858 14.7614 2 12 2C9.23858 2 7 4.23858 7 7V9C5.34315 9 4 10.3431 4 12V19C4 20.6569 5.34315 22 7 22H17C18.6569 22 20 20.6569 20 19V12C20 10.3431 18.6569 9 17 9ZM9 7C9 5.34315 10.3431 4 12 4C13.6569 4 15 5.34315 15 7V9H9V7ZM18 19C18 19.5523 17.5523 20 17 20H7C6.44772 20 6 19.5523 6 19V12C6 11.4477 6.44772 11 7 11H17C17.5523 11 18 11.4477 18 12V19Z" fill="currentColor"/> </svg>
superset-frontend/images/icons/lock_locked.svg
0
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
[ 0.00020800305355805904, 0.00018672551959753036, 0.0001738780556479469, 0.00017829543503466994, 0.000015153185813687742 ]
{ "id": 7, "code_window": [ " );\n", "\n", " const popoverTitle = (\n", " <AdhocMetricEditPopoverTitle\n", " title={this.state.title}\n", " defaultLabel={adhocMetric.label}\n", " onChange={this.onLabelChange}\n", " />\n", " );\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " title={title}\n" ], "file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx", "type": "replace", "edit_start_line_idx": 103 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ export const cacheWrapper = <T extends Array<any>, U>( fn: (...args: T) => U, cache: Map<string, any>, keyFn: (...args: T) => string = (...args: T) => JSON.stringify([...args]), ) => { return (...args: T): U => { const key = keyFn(...args); if (cache.has(key)) { return cache.get(key); } const result = fn(...args); cache.set(key, result); return result; }; };
superset-frontend/src/utils/cacheWrapper.ts
0
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
[ 0.00017628833302296698, 0.0001742303866194561, 0.00017074248171411455, 0.00017494535131845623, 0.0000021943326373730088 ]
{ "id": 7, "code_window": [ " );\n", "\n", " const popoverTitle = (\n", " <AdhocMetricEditPopoverTitle\n", " title={this.state.title}\n", " defaultLabel={adhocMetric.label}\n", " onChange={this.onLabelChange}\n", " />\n", " );\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " title={title}\n" ], "file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx", "type": "replace", "edit_start_line_idx": 103 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ @import './../../../stylesheets/less/variables.less'; @import './builder.less'; @import './builder-sidepane.less'; @import './buttons.less'; @import './dashboard.less'; @import './dnd.less'; @import './filter-scope-selector.less'; @import './grid.less'; @import './hover-menu.less'; @import './popover-menu.less'; @import './resizable.less'; @import './components/index.less';
superset-frontend/src/dashboard/stylesheets/index.less
0
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
[ 0.0001766457426128909, 0.00017498341912869364, 0.0001738869905238971, 0.0001747004862409085, 0.0000011340291621309007 ]
{ "id": 0, "code_window": [ " * @todo Use the options import-path to tree-shake composables in a safer way.\n", " */\n", " const composableNames = Object.values(options.composables).flat()\n", " const COMPOSABLE_RE = new RegExp(`($\\\\s+)(${composableNames.join('|')})(?=\\\\()`, 'gm')\n", "\n", " return {\n", " name: 'nuxt:tree-shake-composables:transform',\n", " enforce: 'post',\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " const regexp = `(^\\\\s*)(${composableNames.join('|')})(?=\\\\((?!\\\\) \\\\{))`\n", " const COMPOSABLE_RE = new RegExp(regexp, 'm')\n", " const COMPOSABLE_RE_GLOBAL = new RegExp(regexp, 'gm')\n" ], "file_path": "packages/nuxt/src/core/plugins/tree-shake.ts", "type": "replace", "edit_start_line_idx": 17 }
import { stripLiteral } from 'strip-literal' import MagicString from 'magic-string' import { createUnplugin } from 'unplugin' import { isJS, isVue } from '../utils' type ImportPath = string export interface TreeShakeComposablesPluginOptions { sourcemap?: boolean composables: Record<ImportPath, string[]> } export const TreeShakeComposablesPlugin = createUnplugin((options: TreeShakeComposablesPluginOptions) => { /** * @todo Use the options import-path to tree-shake composables in a safer way. */ const composableNames = Object.values(options.composables).flat() const COMPOSABLE_RE = new RegExp(`($\\s+)(${composableNames.join('|')})(?=\\()`, 'gm') return { name: 'nuxt:tree-shake-composables:transform', enforce: 'post', transformInclude (id) { return isVue(id, { type: ['script'] }) || isJS(id) }, transform (code) { if (!code.match(COMPOSABLE_RE)) { return } const s = new MagicString(code) const strippedCode = stripLiteral(code) for (const match of strippedCode.matchAll(COMPOSABLE_RE) || []) { s.overwrite(match.index!, match.index! + match[0].length, `${match[1]} /*#__PURE__*/ false && ${match[2]}`) } if (s.hasChanged()) { return { code: s.toString(), map: options.sourcemap ? s.generateMap({ hires: true }) : undefined } } } } })
packages/nuxt/src/core/plugins/tree-shake.ts
1
https://github.com/nuxt/nuxt/commit/80d7899f49a6f0da6b79676f3c7b0a6795899763
[ 0.9992597699165344, 0.6019245386123657, 0.00017080664110835642, 0.9985450506210327, 0.486323744058609 ]
{ "id": 0, "code_window": [ " * @todo Use the options import-path to tree-shake composables in a safer way.\n", " */\n", " const composableNames = Object.values(options.composables).flat()\n", " const COMPOSABLE_RE = new RegExp(`($\\\\s+)(${composableNames.join('|')})(?=\\\\()`, 'gm')\n", "\n", " return {\n", " name: 'nuxt:tree-shake-composables:transform',\n", " enforce: 'post',\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " const regexp = `(^\\\\s*)(${composableNames.join('|')})(?=\\\\((?!\\\\) \\\\{))`\n", " const COMPOSABLE_RE = new RegExp(regexp, 'm')\n", " const COMPOSABLE_RE_GLOBAL = new RegExp(regexp, 'gm')\n" ], "file_path": "packages/nuxt/src/core/plugins/tree-shake.ts", "type": "replace", "edit_start_line_idx": 17 }
--- navigation: false redirect: /guide/concepts/auto-imports ---
docs/2.guide/index.md
0
https://github.com/nuxt/nuxt/commit/80d7899f49a6f0da6b79676f3c7b0a6795899763
[ 0.00017488334560766816, 0.00017488334560766816, 0.00017488334560766816, 0.00017488334560766816, 0 ]
{ "id": 0, "code_window": [ " * @todo Use the options import-path to tree-shake composables in a safer way.\n", " */\n", " const composableNames = Object.values(options.composables).flat()\n", " const COMPOSABLE_RE = new RegExp(`($\\\\s+)(${composableNames.join('|')})(?=\\\\()`, 'gm')\n", "\n", " return {\n", " name: 'nuxt:tree-shake-composables:transform',\n", " enforce: 'post',\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " const regexp = `(^\\\\s*)(${composableNames.join('|')})(?=\\\\((?!\\\\) \\\\{))`\n", " const COMPOSABLE_RE = new RegExp(regexp, 'm')\n", " const COMPOSABLE_RE_GLOBAL = new RegExp(regexp, 'gm')\n" ], "file_path": "packages/nuxt/src/core/plugins/tree-shake.ts", "type": "replace", "edit_start_line_idx": 17 }
--- toc: false navigation.icon: heroicons-outline:newspaper description: Discover the latest Nuxt 3 updates. --- # Releases Discover the latest Nuxt updates. ::releases ::
docs/5.community/7.changelog.md
0
https://github.com/nuxt/nuxt/commit/80d7899f49a6f0da6b79676f3c7b0a6795899763
[ 0.00017490469326730818, 0.0001707297924440354, 0.00016655490617267787, 0.0001707297924440354, 0.0000041748935473151505 ]
{ "id": 0, "code_window": [ " * @todo Use the options import-path to tree-shake composables in a safer way.\n", " */\n", " const composableNames = Object.values(options.composables).flat()\n", " const COMPOSABLE_RE = new RegExp(`($\\\\s+)(${composableNames.join('|')})(?=\\\\()`, 'gm')\n", "\n", " return {\n", " name: 'nuxt:tree-shake-composables:transform',\n", " enforce: 'post',\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " const regexp = `(^\\\\s*)(${composableNames.join('|')})(?=\\\\((?!\\\\) \\\\{))`\n", " const COMPOSABLE_RE = new RegExp(regexp, 'm')\n", " const COMPOSABLE_RE_GLOBAL = new RegExp(regexp, 'gm')\n" ], "file_path": "packages/nuxt/src/core/plugins/tree-shake.ts", "type": "replace", "edit_start_line_idx": 17 }
--- toc: false --- # Hello World A minimal Nuxt 3 application only requires the `app.vue` and `nuxt.config.js` files. ::ReadMore{link="/docs/getting-started/introduction"} :: ::sandbox{repo="nuxt/nuxt" branch="main" dir="examples/essentials/hello-world" file="app.vue"} ::
docs/4.examples/0.essentials/hello-world.md
0
https://github.com/nuxt/nuxt/commit/80d7899f49a6f0da6b79676f3c7b0a6795899763
[ 0.00016780802980065346, 0.00016664742724969983, 0.00016548683925066143, 0.00016664742724969983, 0.0000011605952749960124 ]
{ "id": 1, "code_window": [ " transformInclude (id) {\n", " return isVue(id, { type: ['script'] }) || isJS(id)\n", " },\n", " transform (code) {\n", " if (!code.match(COMPOSABLE_RE)) { return }\n", "\n", " const s = new MagicString(code)\n", " const strippedCode = stripLiteral(code)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if (!COMPOSABLE_RE.test(code)) { return }\n" ], "file_path": "packages/nuxt/src/core/plugins/tree-shake.ts", "type": "replace", "edit_start_line_idx": 26 }
import { stripLiteral } from 'strip-literal' import MagicString from 'magic-string' import { createUnplugin } from 'unplugin' import { isJS, isVue } from '../utils' type ImportPath = string export interface TreeShakeComposablesPluginOptions { sourcemap?: boolean composables: Record<ImportPath, string[]> } export const TreeShakeComposablesPlugin = createUnplugin((options: TreeShakeComposablesPluginOptions) => { /** * @todo Use the options import-path to tree-shake composables in a safer way. */ const composableNames = Object.values(options.composables).flat() const COMPOSABLE_RE = new RegExp(`($\\s+)(${composableNames.join('|')})(?=\\()`, 'gm') return { name: 'nuxt:tree-shake-composables:transform', enforce: 'post', transformInclude (id) { return isVue(id, { type: ['script'] }) || isJS(id) }, transform (code) { if (!code.match(COMPOSABLE_RE)) { return } const s = new MagicString(code) const strippedCode = stripLiteral(code) for (const match of strippedCode.matchAll(COMPOSABLE_RE) || []) { s.overwrite(match.index!, match.index! + match[0].length, `${match[1]} /*#__PURE__*/ false && ${match[2]}`) } if (s.hasChanged()) { return { code: s.toString(), map: options.sourcemap ? s.generateMap({ hires: true }) : undefined } } } } })
packages/nuxt/src/core/plugins/tree-shake.ts
1
https://github.com/nuxt/nuxt/commit/80d7899f49a6f0da6b79676f3c7b0a6795899763
[ 0.9981551766395569, 0.3999570906162262, 0.0001697663392405957, 0.0018890853971242905, 0.4883176386356354 ]
{ "id": 1, "code_window": [ " transformInclude (id) {\n", " return isVue(id, { type: ['script'] }) || isJS(id)\n", " },\n", " transform (code) {\n", " if (!code.match(COMPOSABLE_RE)) { return }\n", "\n", " const s = new MagicString(code)\n", " const strippedCode = stripLiteral(code)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if (!COMPOSABLE_RE.test(code)) { return }\n" ], "file_path": "packages/nuxt/src/core/plugins/tree-shake.ts", "type": "replace", "edit_start_line_idx": 26 }
shamefully-hoist=true strict-peer-dependencies=false shell-emulator=true
.npmrc
0
https://github.com/nuxt/nuxt/commit/80d7899f49a6f0da6b79676f3c7b0a6795899763
[ 0.00016919006884563714, 0.00016919006884563714, 0.00016919006884563714, 0.00016919006884563714, 0 ]
{ "id": 1, "code_window": [ " transformInclude (id) {\n", " return isVue(id, { type: ['script'] }) || isJS(id)\n", " },\n", " transform (code) {\n", " if (!code.match(COMPOSABLE_RE)) { return }\n", "\n", " const s = new MagicString(code)\n", " const strippedCode = stripLiteral(code)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if (!COMPOSABLE_RE.test(code)) { return }\n" ], "file_path": "packages/nuxt/src/core/plugins/tree-shake.ts", "type": "replace", "edit_start_line_idx": 26 }
<template> <div> stateful test {{ state }} <NuxtClientFallback> <BreakInSetup class="clientfallback-stateful" /> </NuxtClientFallback> </div> </template> <script> export default defineNuxtComponent({ name: 'ClientFallbackStateful', setup () { const state = ref(0) return { state } } }) </script>
test/fixtures/basic/components/clientFallback/Stateful.vue
0
https://github.com/nuxt/nuxt/commit/80d7899f49a6f0da6b79676f3c7b0a6795899763
[ 0.0001749652437865734, 0.00016970834985841066, 0.00016692743520252407, 0.0001672323705861345, 0.0000037192694435361773 ]
{ "id": 1, "code_window": [ " transformInclude (id) {\n", " return isVue(id, { type: ['script'] }) || isJS(id)\n", " },\n", " transform (code) {\n", " if (!code.match(COMPOSABLE_RE)) { return }\n", "\n", " const s = new MagicString(code)\n", " const strippedCode = stripLiteral(code)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if (!COMPOSABLE_RE.test(code)) { return }\n" ], "file_path": "packages/nuxt/src/core/plugins/tree-shake.ts", "type": "replace", "edit_start_line_idx": 26 }
navigation.icon: uil:wrench image: '/socials/configuration.jpg'
docs/3.api/6.configuration/_dir.yml
0
https://github.com/nuxt/nuxt/commit/80d7899f49a6f0da6b79676f3c7b0a6795899763
[ 0.00017078286327887326, 0.00017078286327887326, 0.00017078286327887326, 0.00017078286327887326, 0 ]
{ "id": 2, "code_window": [ "\n", " const s = new MagicString(code)\n", " const strippedCode = stripLiteral(code)\n", " for (const match of strippedCode.matchAll(COMPOSABLE_RE) || []) {\n", " s.overwrite(match.index!, match.index! + match[0].length, `${match[1]} /*#__PURE__*/ false && ${match[2]}`)\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " for (const match of strippedCode.matchAll(COMPOSABLE_RE_GLOBAL) || []) {\n" ], "file_path": "packages/nuxt/src/core/plugins/tree-shake.ts", "type": "replace", "edit_start_line_idx": 30 }
import '~/assets/plugin.css' export default defineNuxtPlugin(() => { // })
test/fixtures/basic/plugins/style.ts
1
https://github.com/nuxt/nuxt/commit/80d7899f49a6f0da6b79676f3c7b0a6795899763
[ 0.00017499877139925957, 0.00017499877139925957, 0.00017499877139925957, 0.00017499877139925957, 0 ]
{ "id": 2, "code_window": [ "\n", " const s = new MagicString(code)\n", " const strippedCode = stripLiteral(code)\n", " for (const match of strippedCode.matchAll(COMPOSABLE_RE) || []) {\n", " s.overwrite(match.index!, match.index! + match[0].length, `${match[1]} /*#__PURE__*/ false && ${match[2]}`)\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " for (const match of strippedCode.matchAll(COMPOSABLE_RE_GLOBAL) || []) {\n" ], "file_path": "packages/nuxt/src/core/plugins/tree-shake.ts", "type": "replace", "edit_start_line_idx": 30 }
import { existsSync, readdirSync } from 'node:fs' import { addComponent, addPlugin, addTemplate, addVitePlugin, addWebpackPlugin, defineNuxtModule, findPath, updateTemplates } from '@nuxt/kit' import { join, relative, resolve } from 'pathe' import { genImport, genObjectFromRawEntries, genString } from 'knitwork' import escapeRE from 'escape-string-regexp' import { joinURL } from 'ufo' import type { NuxtApp, NuxtPage } from 'nuxt/schema' import { distDir } from '../dirs' import { normalizeRoutes, resolvePagesRoutes } from './utils' import type { PageMetaPluginOptions } from './page-meta' import { PageMetaPlugin } from './page-meta' export default defineNuxtModule({ meta: { name: 'pages' }, setup (_options, nuxt) { const pagesDirs = nuxt.options._layers.map( layer => resolve(layer.config.srcDir, layer.config.dir?.pages || 'pages') ) // Disable module (and use universal router) if pages dir do not exists or user has disabled it const isNonEmptyDir = (dir: string) => existsSync(dir) && readdirSync(dir).length const userPreference = nuxt.options.pages const isPagesEnabled = () => { if (typeof userPreference === 'boolean') { return userPreference } if (nuxt.options._layers.some(layer => existsSync(resolve(layer.config.srcDir, 'app/router.options.ts')))) { return true } if (pagesDirs.some(dir => isNonEmptyDir(dir))) { return true } return false } nuxt.options.pages = isPagesEnabled() // Restart Nuxt when pages dir is added or removed const restartPaths = nuxt.options._layers.flatMap(layer => [ join(layer.config.srcDir, 'app/router.options.ts'), join(layer.config.srcDir, layer.config.dir?.pages || 'pages') ]) nuxt.hooks.hook('builder:watch', (event, path) => { const fullPath = join(nuxt.options.srcDir, path) if (restartPaths.some(path => path === fullPath || fullPath.startsWith(path + '/'))) { const newSetting = isPagesEnabled() if (nuxt.options.pages !== newSetting) { console.info('Pages', newSetting ? 'enabled' : 'disabled') return nuxt.callHook('restart') } } }) if (!nuxt.options.pages) { addPlugin(resolve(distDir, 'app/plugins/router')) addTemplate({ filename: 'pages.mjs', getContents: () => 'export { useRoute } from \'#app\'' }) addComponent({ name: 'NuxtPage', priority: 10, // built-in that we do not expect the user to override filePath: resolve(distDir, 'pages/runtime/page-placeholder') }) return } const runtimeDir = resolve(distDir, 'pages/runtime') // Add $router types nuxt.hook('prepare:types', ({ references }) => { references.push({ types: 'vue-router' }) }) // Add vue-router route guard imports nuxt.hook('imports:sources', (sources) => { const routerImports = sources.find(s => s.from === '#app' && s.imports.includes('onBeforeRouteLeave')) if (routerImports) { routerImports.from = 'vue-router' } }) // Regenerate templates when adding or removing pages nuxt.hook('builder:watch', async (event, path) => { const dirs = [ nuxt.options.dir.pages, nuxt.options.dir.layouts, nuxt.options.dir.middleware ].filter(Boolean) const pathPattern = new RegExp(`(^|\\/)(${dirs.map(escapeRE).join('|')})/`) if (event !== 'change' && path.match(pathPattern)) { await updateTemplates({ filter: template => template.filename === 'routes.mjs' }) } }) nuxt.hook('app:resolve', (app) => { // Add default layout for pages if (app.mainComponent!.includes('@nuxt/ui-templates')) { app.mainComponent = resolve(runtimeDir, 'app.vue') } app.middleware.unshift({ name: 'validate', path: resolve(runtimeDir, 'validate'), global: true }) }) // Prerender all non-dynamic page routes when generating app if (!nuxt.options.dev && nuxt.options._generate) { const prerenderRoutes = new Set<string>() nuxt.hook('modules:done', () => { nuxt.hook('pages:extend', (pages) => { prerenderRoutes.clear() const processPages = (pages: NuxtPage[], currentPath = '/') => { for (const page of pages) { // Add root of optional dynamic paths and catchalls if (page.path.match(/^\/?:.*(\?|\(\.\*\)\*)$/) && !page.children?.length) { prerenderRoutes.add(currentPath) } // Skip dynamic paths if (page.path.includes(':')) { continue } const route = joinURL(currentPath, page.path) prerenderRoutes.add(route) if (page.children) { processPages(page.children, route) } } } processPages(pages) }) }) nuxt.hook('nitro:build:before', (nitro) => { for (const route of nitro.options.prerender.routes || []) { // Skip default route value as we only generate it if it is already // in the detected routes from `~/pages`. if (route === '/') { continue } prerenderRoutes.add(route) } nitro.options.prerender.routes = Array.from(prerenderRoutes) }) } nuxt.hook('imports:extend', (imports) => { imports.push( { name: 'definePageMeta', as: 'definePageMeta', from: resolve(runtimeDir, 'composables') }, { name: 'useLink', as: 'useLink', from: 'vue-router' } ) }) // Extract macros from pages const pageMetaOptions: PageMetaPluginOptions = { dev: nuxt.options.dev, sourcemap: nuxt.options.sourcemap.server || nuxt.options.sourcemap.client } nuxt.hook('modules:done', () => { addVitePlugin(() => PageMetaPlugin.vite(pageMetaOptions)) addWebpackPlugin(() => PageMetaPlugin.webpack(pageMetaOptions)) }) // Add prefetching support for middleware & layouts addPlugin(resolve(runtimeDir, 'plugins/prefetch.client')) // Add router plugin addPlugin(resolve(runtimeDir, 'plugins/router')) const getSources = (pages: NuxtPage[]): string[] => pages .filter(p => Boolean(p.file)) .flatMap(p => [relative(nuxt.options.srcDir, p.file as string), ...getSources(p.children || [])] ) // Do not prefetch page chunks nuxt.hook('build:manifest', async (manifest) => { if (nuxt.options.dev) { return } const pages = await resolvePagesRoutes() await nuxt.callHook('pages:extend', pages) const sourceFiles = getSources(pages) for (const key in manifest) { if (manifest[key].isEntry) { manifest[key].dynamicImports = manifest[key].dynamicImports?.filter(i => !sourceFiles.includes(i)) } } }) // Add routes template addTemplate({ filename: 'routes.mjs', async getContents () { const pages = await resolvePagesRoutes() await nuxt.callHook('pages:extend', pages) const { routes, imports } = normalizeRoutes(pages) return [...imports, `export default ${routes}`].join('\n') } }) // Add vue-router import for `<NuxtLayout>` integration addTemplate({ filename: 'pages.mjs', getContents: () => 'export { useRoute } from \'vue-router\'' }) // Optimize vue-router to ensure we share the same injection symbol nuxt.options.vite.optimizeDeps = nuxt.options.vite.optimizeDeps || {} nuxt.options.vite.optimizeDeps.include = nuxt.options.vite.optimizeDeps.include || [] nuxt.options.vite.optimizeDeps.include.push('vue-router') nuxt.options.vite.resolve = nuxt.options.vite.resolve || {} nuxt.options.vite.resolve.dedupe = nuxt.options.vite.resolve.dedupe || [] nuxt.options.vite.resolve.dedupe.push('vue-router') // Add router options template addTemplate({ filename: 'router.options.mjs', getContents: async () => { // Scan and register app/router.options files const routerOptionsFiles = (await Promise.all(nuxt.options._layers.map( async layer => await findPath(resolve(layer.config.srcDir, 'app/router.options')) ))).filter(Boolean) as string[] // Add default options routerOptionsFiles.push(resolve(runtimeDir, 'router.options')) const configRouterOptions = genObjectFromRawEntries(Object.entries(nuxt.options.router.options) .map(([key, value]) => [key, genString(value as string)])) return [ ...routerOptionsFiles.map((file, index) => genImport(file, `routerOptions${index}`)), `const configRouterOptions = ${configRouterOptions}`, 'export default {', '...configRouterOptions,', // We need to reverse spreading order to respect layers priority ...routerOptionsFiles.map((_, index) => `...routerOptions${index},`).reverse(), '}' ].join('\n') } }) addTemplate({ filename: 'types/middleware.d.ts', getContents: ({ app }: { app: NuxtApp }) => { const composablesFile = resolve(runtimeDir, 'composables') const namedMiddleware = app.middleware.filter(mw => !mw.global) return [ 'import type { NavigationGuard } from \'vue-router\'', `export type MiddlewareKey = ${namedMiddleware.map(mw => genString(mw.name)).join(' | ') || 'string'}`, `declare module ${genString(composablesFile)} {`, ' interface PageMeta {', ' middleware?: MiddlewareKey | NavigationGuard | Array<MiddlewareKey | NavigationGuard>', ' }', '}' ].join('\n') } }) addTemplate({ filename: 'types/layouts.d.ts', getContents: ({ app }: { app: NuxtApp }) => { const composablesFile = resolve(runtimeDir, 'composables') return [ 'import { ComputedRef, Ref } from \'vue\'', `export type LayoutKey = ${Object.keys(app.layouts).map(name => genString(name)).join(' | ') || 'string'}`, `declare module ${genString(composablesFile)} {`, ' interface PageMeta {', ' layout?: false | LayoutKey | Ref<LayoutKey> | ComputedRef<LayoutKey>', ' }', '}' ].join('\n') } }) // Add <NuxtPage> addComponent({ name: 'NuxtPage', priority: 10, // built-in that we do not expect the user to override filePath: resolve(distDir, 'pages/runtime/page') }) // Add declarations for middleware keys nuxt.hook('prepare:types', ({ references }) => { references.push({ path: resolve(nuxt.options.buildDir, 'types/middleware.d.ts') }) references.push({ path: resolve(nuxt.options.buildDir, 'types/layouts.d.ts') }) }) } })
packages/nuxt/src/pages/module.ts
0
https://github.com/nuxt/nuxt/commit/80d7899f49a6f0da6b79676f3c7b0a6795899763
[ 0.00017699542513582855, 0.00017306885274592787, 0.00016508842236362398, 0.00017329526599496603, 0.0000025478400402789703 ]
{ "id": 2, "code_window": [ "\n", " const s = new MagicString(code)\n", " const strippedCode = stripLiteral(code)\n", " for (const match of strippedCode.matchAll(COMPOSABLE_RE) || []) {\n", " s.overwrite(match.index!, match.index! + match[0].length, `${match[1]} /*#__PURE__*/ false && ${match[2]}`)\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " for (const match of strippedCode.matchAll(COMPOSABLE_RE_GLOBAL) || []) {\n" ], "file_path": "packages/nuxt/src/core/plugins/tree-shake.ts", "type": "replace", "edit_start_line_idx": 30 }
import { parseURL } from 'ufo' import { defineNuxtPlugin } from '#app/nuxt' import { isPrerendered, loadPayload } from '#app/composables/payload' import { useRouter } from '#app/composables/router' export default defineNuxtPlugin({ name: 'nuxt:payload', setup (nuxtApp) { // Only enable behavior if initial page is prerendered // TODO: Support hybrid and dev if (!isPrerendered()) { return } // Load payload into cache nuxtApp.hooks.hook('link:prefetch', async (url) => { if (!parseURL(url).protocol) { await loadPayload(url) } }) // Load payload after middleware & once final route is resolved useRouter().beforeResolve(async (to, from) => { if (to.path === from.path) { return } const payload = await loadPayload(to.path) if (!payload) { return } Object.assign(nuxtApp.static.data, payload.data) }) } })
packages/nuxt/src/app/plugins/payload.client.ts
0
https://github.com/nuxt/nuxt/commit/80d7899f49a6f0da6b79676f3c7b0a6795899763
[ 0.0001760805316735059, 0.0001739601430017501, 0.0001713549136184156, 0.00017420254880562425, 0.0000017871882391773397 ]
{ "id": 2, "code_window": [ "\n", " const s = new MagicString(code)\n", " const strippedCode = stripLiteral(code)\n", " for (const match of strippedCode.matchAll(COMPOSABLE_RE) || []) {\n", " s.overwrite(match.index!, match.index! + match[0].length, `${match[1]} /*#__PURE__*/ false && ${match[2]}`)\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " for (const match of strippedCode.matchAll(COMPOSABLE_RE_GLOBAL) || []) {\n" ], "file_path": "packages/nuxt/src/core/plugins/tree-shake.ts", "type": "replace", "edit_start_line_idx": 30 }
// We set __webpack_public_path via this import with webpack builder import { createApp, createSSRApp, nextTick } from 'vue' import { $fetch } from 'ofetch' import type { $Fetch, NitroFetchRequest } from 'nitropack' // This file must be imported first for webpack as we set __webpack_public_path__ there // @ts-expect-error virtual file import { baseURL } from '#build/paths.mjs' import type { CreateOptions } from '#app' import { applyPlugins, createNuxtApp, normalizePlugins } from '#app/nuxt' import '#build/css' // @ts-expect-error virtual file import _plugins from '#build/plugins' // @ts-expect-error virtual file import RootComponent from '#build/root-component.mjs' // @ts-expect-error virtual file import { appRootId } from '#build/nuxt.config.mjs' if (!globalThis.$fetch) { globalThis.$fetch = $fetch.create({ baseURL: baseURL() }) as $Fetch<unknown, NitroFetchRequest> } let entry: Function const plugins = normalizePlugins(_plugins) if (process.server) { entry = async function createNuxtAppServer (ssrContext: CreateOptions['ssrContext']) { const vueApp = createApp(RootComponent) const nuxt = createNuxtApp({ vueApp, ssrContext }) try { await applyPlugins(nuxt, plugins) await nuxt.hooks.callHook('app:created', vueApp) } catch (err) { await nuxt.hooks.callHook('app:error', err) nuxt.payload.error = (nuxt.payload.error || err) as any } return vueApp } } if (process.client) { // TODO: temporary webpack 5 HMR fix // https://github.com/webpack-contrib/webpack-hot-middleware/issues/390 if (process.dev && import.meta.webpackHot) { import.meta.webpackHot.accept() } // eslint-disable-next-line let vueAppPromise: Promise<any> entry = async function initApp () { if (vueAppPromise) { return vueAppPromise } const isSSR = Boolean( window.__NUXT__?.serverRendered || document.getElementById('__NUXT_DATA__')?.dataset.ssr === 'true' ) const vueApp = isSSR ? createSSRApp(RootComponent) : createApp(RootComponent) const nuxt = createNuxtApp({ vueApp }) try { await applyPlugins(nuxt, plugins) } catch (err) { await nuxt.callHook('app:error', err) nuxt.payload.error = (nuxt.payload.error || err) as any } try { await nuxt.hooks.callHook('app:created', vueApp) await nuxt.hooks.callHook('app:beforeMount', vueApp) vueApp.mount('#' + appRootId) await nuxt.hooks.callHook('app:mounted', vueApp) await nextTick() } catch (err) { await nuxt.callHook('app:error', err) nuxt.payload.error = (nuxt.payload.error || err) as any } return vueApp } vueAppPromise = entry().catch((error: unknown) => { console.error('Error while mounting app:', error) }) } export default (ctx?: CreateOptions['ssrContext']) => entry(ctx)
packages/nuxt/src/app/entry.ts
0
https://github.com/nuxt/nuxt/commit/80d7899f49a6f0da6b79676f3c7b0a6795899763
[ 0.0001776202698238194, 0.00017534205107949674, 0.00017216314154211432, 0.0001754744880599901, 0.0000016833602103361045 ]
{ "id": 3, "code_window": [ "import '~/assets/plugin.css'\n", "\n", "export default defineNuxtPlugin(() => {\n", " //\n", "})" ], "labels": [ "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "export class OnMountedMethod {\n", " public onMounted () {\n", " console.log('public onMounted')\n", " }\n", "\n", " onBeforeMount () {\n", " console.log('onBeforeMount')\n", " }\n", "}\n" ], "file_path": "test/fixtures/basic/plugins/style.ts", "type": "add", "edit_start_line_idx": 2 }
import { stripLiteral } from 'strip-literal' import MagicString from 'magic-string' import { createUnplugin } from 'unplugin' import { isJS, isVue } from '../utils' type ImportPath = string export interface TreeShakeComposablesPluginOptions { sourcemap?: boolean composables: Record<ImportPath, string[]> } export const TreeShakeComposablesPlugin = createUnplugin((options: TreeShakeComposablesPluginOptions) => { /** * @todo Use the options import-path to tree-shake composables in a safer way. */ const composableNames = Object.values(options.composables).flat() const COMPOSABLE_RE = new RegExp(`($\\s+)(${composableNames.join('|')})(?=\\()`, 'gm') return { name: 'nuxt:tree-shake-composables:transform', enforce: 'post', transformInclude (id) { return isVue(id, { type: ['script'] }) || isJS(id) }, transform (code) { if (!code.match(COMPOSABLE_RE)) { return } const s = new MagicString(code) const strippedCode = stripLiteral(code) for (const match of strippedCode.matchAll(COMPOSABLE_RE) || []) { s.overwrite(match.index!, match.index! + match[0].length, `${match[1]} /*#__PURE__*/ false && ${match[2]}`) } if (s.hasChanged()) { return { code: s.toString(), map: options.sourcemap ? s.generateMap({ hires: true }) : undefined } } } } })
packages/nuxt/src/core/plugins/tree-shake.ts
1
https://github.com/nuxt/nuxt/commit/80d7899f49a6f0da6b79676f3c7b0a6795899763
[ 0.0002914667420554906, 0.00019430328393355012, 0.00016653792408760637, 0.00017110265616793185, 0.00004862081186729483 ]
{ "id": 3, "code_window": [ "import '~/assets/plugin.css'\n", "\n", "export default defineNuxtPlugin(() => {\n", " //\n", "})" ], "labels": [ "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "export class OnMountedMethod {\n", " public onMounted () {\n", " console.log('public onMounted')\n", " }\n", "\n", " onBeforeMount () {\n", " console.log('onBeforeMount')\n", " }\n", "}\n" ], "file_path": "test/fixtures/basic/plugins/style.ts", "type": "add", "edit_start_line_idx": 2 }
<script> export default { data () { return { open: false } } } </script> <template> <NButton @click="open = true"> Open Modal </NButton> <Teleport to="body"> <NCard v-if="open" class="modal p4"> <p>Hello from the modal!</p> <NButton @click="open = false"> Close </NButton> </NCard> </Teleport> </template> <style scoped> .modal { position: fixed; z-index: 999; top: 20%; left: 50%; width: 300px; margin-left: -150px; } </style>
examples/app/teleport/components/MyModal.vue
0
https://github.com/nuxt/nuxt/commit/80d7899f49a6f0da6b79676f3c7b0a6795899763
[ 0.003513963660225272, 0.0010094339959323406, 0.00017294712597504258, 0.0001754126715241, 0.0014459913363680243 ]
{ "id": 3, "code_window": [ "import '~/assets/plugin.css'\n", "\n", "export default defineNuxtPlugin(() => {\n", " //\n", "})" ], "labels": [ "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "export class OnMountedMethod {\n", " public onMounted () {\n", " console.log('public onMounted')\n", " }\n", "\n", " onBeforeMount () {\n", " console.log('onBeforeMount')\n", " }\n", "}\n" ], "file_path": "test/fixtures/basic/plugins/style.ts", "type": "add", "edit_start_line_idx": 2 }
{ "name": "example-components", "private": true, "scripts": { "build": "nuxi build", "dev": "nuxi dev", "start": "nuxi preview" }, "devDependencies": { "@nuxt/ui": "^0.3.3", "nuxt": "^3.0.0" } }
examples/auto-imports/components/package.json
0
https://github.com/nuxt/nuxt/commit/80d7899f49a6f0da6b79676f3c7b0a6795899763
[ 0.00016780484293121845, 0.00016718663391657174, 0.0001665684103500098, 0.00016718663391657174, 6.182162906043231e-7 ]
{ "id": 3, "code_window": [ "import '~/assets/plugin.css'\n", "\n", "export default defineNuxtPlugin(() => {\n", " //\n", "})" ], "labels": [ "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "export class OnMountedMethod {\n", " public onMounted () {\n", " console.log('public onMounted')\n", " }\n", "\n", " onBeforeMount () {\n", " console.log('onBeforeMount')\n", " }\n", "}\n" ], "file_path": "test/fixtures/basic/plugins/style.ts", "type": "add", "edit_start_line_idx": 2 }
function defineNuxtConfig (config) { return config } export { defineNuxtConfig }
packages/nuxt/config.js
0
https://github.com/nuxt/nuxt/commit/80d7899f49a6f0da6b79676f3c7b0a6795899763
[ 0.03744310885667801, 0.03744310885667801, 0.03744310885667801, 0.03744310885667801, 0 ]
{ "id": 0, "code_window": [ "@code-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;\n", "@text-color: fade(@black, 65%);\n", "@text-color-secondary: fade(@black, 45%);\n", "@text-color-warning: @gold-7;\n", "@text-color-danger: @red-7;\n", "@text-color-inverse: @white;\n", "@icon-color: inherit;\n", "@icon-color-hover: fade(@black, 75%);\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "components/style/themes/default.less", "type": "replace", "edit_start_line_idx": 49 }
/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */ @import '../color/colors'; // The prefix to use on all css classes from ant. @ant-prefix: ant; // An override for the html selector for theme prefixes @html-selector: html; // -------- Colors ----------- @primary-color: @blue-6; @info-color: @blue-6; @success-color: @green-6; @processing-color: @blue-6; @error-color: @red-6; @highlight-color: @red-6; @warning-color: @gold-6; @normal-color: #d9d9d9; @white: #fff; @black: #000; // Color used by default to control hover and active backgrounds and for // alert info backgrounds. @primary-1: color(~`colorPalette('@{primary-color}', 1) `); // replace tint(@primary-color, 90%) @primary-2: color(~`colorPalette('@{primary-color}', 2) `); // replace tint(@primary-color, 80%) @primary-3: color(~`colorPalette('@{primary-color}', 3) `); // unused @primary-4: color(~`colorPalette('@{primary-color}', 4) `); // unused @primary-5: color( ~`colorPalette('@{primary-color}', 5) ` ); // color used to control the text color in many active and hover states, replace tint(@primary-color, 20%) @primary-6: @primary-color; // color used to control the text color of active buttons, don't use, use @primary-color @primary-7: color(~`colorPalette('@{primary-color}', 7) `); // replace shade(@primary-color, 5%) @primary-8: color(~`colorPalette('@{primary-color}', 8) `); // unused @primary-9: color(~`colorPalette('@{primary-color}', 9) `); // unused @primary-10: color(~`colorPalette('@{primary-color}', 10) `); // unused // Base Scaffolding Variables // --- // Background color for `<body>` @body-background: #fff; // Base background color for most components @component-background: #fff; @font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'; @code-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace; @text-color: fade(@black, 65%); @text-color-secondary: fade(@black, 45%); @text-color-warning: @gold-7; @text-color-danger: @red-7; @text-color-inverse: @white; @icon-color: inherit; @icon-color-hover: fade(@black, 75%); @heading-color: fade(#000, 85%); @heading-color-dark: fade(@white, 100%); @text-color-dark: fade(@white, 85%); @text-color-secondary-dark: fade(@white, 65%); @text-selection-bg: @primary-color; @font-variant-base: tabular-nums; @font-feature-settings-base: 'tnum'; @font-size-base: 14px; @font-size-lg: @font-size-base + 2px; @font-size-sm: 12px; @heading-1-size: ceil(@font-size-base * 2.71); @heading-2-size: ceil(@font-size-base * 2.14); @heading-3-size: ceil(@font-size-base * 1.71); @heading-4-size: ceil(@font-size-base * 1.42); @line-height-base: 1.5; @border-radius-base: 4px; @border-radius-sm: 2px; // vertical paddings @padding-lg: 24px; // containers @padding-md: 16px; // small containers and buttons @padding-sm: 12px; // Form controls and items @padding-xs: 8px; // small items // vertical padding for all form controls @control-padding-horizontal: @padding-sm; @control-padding-horizontal-sm: @padding-xs; // The background colors for active and hover states for things like // list items or table cells. @item-active-bg: @primary-1; @item-hover-bg: @primary-1; // ICONFONT @iconfont-css-prefix: anticon; // LINK @link-color: @primary-color; @link-hover-color: color(~`colorPalette('@{link-color}', 5) `); @link-active-color: color(~`colorPalette('@{link-color}', 7) `); @link-decoration: none; @link-hover-decoration: none; // Animation @ease-base-out: cubic-bezier(0.7, 0.3, 0.1, 1); @ease-base-in: cubic-bezier(0.9, 0, 0.3, 0.7); @ease-out: cubic-bezier(0.215, 0.61, 0.355, 1); @ease-in: cubic-bezier(0.55, 0.055, 0.675, 0.19); @ease-in-out: cubic-bezier(0.645, 0.045, 0.355, 1); @ease-out-back: cubic-bezier(0.12, 0.4, 0.29, 1.46); @ease-in-back: cubic-bezier(0.71, -0.46, 0.88, 0.6); @ease-in-out-back: cubic-bezier(0.71, -0.46, 0.29, 1.46); @ease-out-circ: cubic-bezier(0.08, 0.82, 0.17, 1); @ease-in-circ: cubic-bezier(0.6, 0.04, 0.98, 0.34); @ease-in-out-circ: cubic-bezier(0.78, 0.14, 0.15, 0.86); @ease-out-quint: cubic-bezier(0.23, 1, 0.32, 1); @ease-in-quint: cubic-bezier(0.755, 0.05, 0.855, 0.06); @ease-in-out-quint: cubic-bezier(0.86, 0, 0.07, 1); // Border color @border-color-base: hsv(0, 0, 85%); // base border outline a component @border-color-split: hsv(0, 0, 91%); // split border inside a component @border-color-inverse: @white; @border-width-base: 1px; // width of the border for a component @border-style-base: solid; // style of a components border // Outline @outline-blur-size: 0; @outline-width: 2px; @outline-color: @primary-color; @background-color-light: hsv(0, 0, 98%); // background of header and selected item @background-color-base: hsv(0, 0, 96%); // Default grey background color // Disabled states @disabled-color: fade(#000, 25%); @disabled-bg: @background-color-base; @disabled-color-dark: fade(#fff, 35%); // Shadow @shadow-color: rgba(0, 0, 0, 0.15); @shadow-color-inverse: @component-background; @box-shadow-base: @shadow-1-down; @shadow-1-up: 0 -2px 8px @shadow-color; @shadow-1-down: 0 2px 8px @shadow-color; @shadow-1-left: -2px 0 8px @shadow-color; @shadow-1-right: 2px 0 8px @shadow-color; @shadow-2: 0 4px 12px @shadow-color; // Buttons @btn-font-weight: 400; @btn-border-radius-base: @border-radius-base; @btn-border-radius-sm: @border-radius-base; @btn-border-width: @border-width-base; @btn-border-style: @border-style-base; @btn-shadow: 0 2px 0 rgba(0, 0, 0, 0.015); @btn-primary-shadow: 0 2px 0 rgba(0, 0, 0, 0.045); @btn-text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.12); @btn-primary-color: #fff; @btn-primary-bg: @primary-color; @btn-default-color: @text-color; @btn-default-bg: #fff; @btn-default-border: @border-color-base; @btn-danger-color: @error-color; @btn-danger-bg: @background-color-base; @btn-danger-border: @border-color-base; @btn-disable-color: @disabled-color; @btn-disable-bg: @disabled-bg; @btn-disable-border: @border-color-base; @btn-padding-base: 0 @padding-md - 1px; @btn-font-size-lg: @font-size-lg; @btn-font-size-sm: @font-size-base; @btn-padding-lg: @btn-padding-base; @btn-padding-sm: 0 @padding-xs - 1px; @btn-height-base: 32px; @btn-height-lg: 40px; @btn-height-sm: 24px; @btn-circle-size: @btn-height-base; @btn-circle-size-lg: @btn-height-lg; @btn-circle-size-sm: @btn-height-sm; @btn-group-border: @primary-5; // Checkbox @checkbox-size: 16px; @checkbox-color: @primary-color; @checkbox-check-color: #fff; @checkbox-border-width: @border-width-base; // Empty @empty-font-size: @font-size-base; // Radio @radio-size: 16px; @radio-dot-color: @primary-color; // Radio buttons @radio-button-bg: @btn-default-bg; @radio-button-checked-bg: @btn-default-bg; @radio-button-color: @btn-default-color; @radio-button-hover-color: @primary-5; @radio-button-active-color: @primary-7; // Media queries breakpoints // Extra small screen / phone @screen-xs: 480px; @screen-xs-min: @screen-xs; // Small screen / tablet @screen-sm: 576px; @screen-sm-min: @screen-sm; // Medium screen / desktop @screen-md: 768px; @screen-md-min: @screen-md; // Large screen / wide desktop @screen-lg: 992px; @screen-lg-min: @screen-lg; // Extra large screen / full hd @screen-xl: 1200px; @screen-xl-min: @screen-xl; // Extra extra large screen / large desktop @screen-xxl: 1600px; @screen-xxl-min: @screen-xxl; // provide a maximum @screen-xs-max: (@screen-sm-min - 1px); @screen-sm-max: (@screen-md-min - 1px); @screen-md-max: (@screen-lg-min - 1px); @screen-lg-max: (@screen-xl-min - 1px); @screen-xl-max: (@screen-xxl-min - 1px); // Grid system @grid-columns: 24; @grid-gutter-width: 0; // Layout @layout-body-background: #f0f2f5; @layout-header-background: #001529; @layout-footer-background: @layout-body-background; @layout-header-height: 64px; @layout-header-padding: 0 50px; @layout-footer-padding: 24px 50px; @layout-sider-background: @layout-header-background; @layout-trigger-height: 48px; @layout-trigger-background: #002140; @layout-trigger-color: #fff; @layout-zero-trigger-width: 36px; @layout-zero-trigger-height: 42px; // Layout light theme @layout-sider-background-light: #fff; @layout-trigger-background-light: #fff; @layout-trigger-color-light: @text-color; // z-index list, order by `z-index` @zindex-table-fixed: auto; @zindex-affix: 10; @zindex-back-top: 10; @zindex-badge: 10; @zindex-picker-panel: 10; @zindex-popup-close: 10; @zindex-modal: 1000; @zindex-modal-mask: 1000; @zindex-message: 1010; @zindex-notification: 1010; @zindex-popover: 1030; @zindex-dropdown: 1050; @zindex-picker: 1050; @zindex-tooltip: 1060; // Animation @animation-duration-slow: 0.3s; // Modal @animation-duration-base: 0.2s; @animation-duration-fast: 0.1s; // Tooltip // Form // --- @label-required-color: @highlight-color; @label-color: @heading-color; @form-warning-input-bg: @input-bg; @form-item-margin-bottom: 24px; @form-item-trailing-colon: true; @form-vertical-label-padding: 0 0 8px; @form-vertical-label-margin: 0; @form-error-input-bg: @input-bg; // Input // --- @input-height-base: 32px; @input-height-lg: 40px; @input-height-sm: 24px; @input-padding-horizontal: @control-padding-horizontal - 1px; @input-padding-horizontal-base: @input-padding-horizontal; @input-padding-horizontal-sm: @control-padding-horizontal-sm - 1px; @input-padding-horizontal-lg: @input-padding-horizontal; @input-padding-vertical-base: 4px; @input-padding-vertical-sm: 1px; @input-padding-vertical-lg: 6px; @input-placeholder-color: hsv(0, 0, 75%); @input-color: @text-color; @input-border-color: @border-color-base; @input-bg: #fff; @input-number-handler-active-bg: #f4f4f4; @input-addon-bg: @background-color-light; @input-hover-border-color: @primary-color; @input-disabled-bg: @disabled-bg; @input-outline-offset: 0 0; // Select // --- @select-border-color: @border-color-base; @select-item-selected-font-weight: 600; // Tooltip // --- // Tooltip max width @tooltip-max-width: 250px; // Tooltip text color @tooltip-color: #fff; // Tooltip background color @tooltip-bg: rgba(0, 0, 0, 0.75); // Tooltip arrow width @tooltip-arrow-width: 5px; // Tooltip distance with trigger @tooltip-distance: @tooltip-arrow-width - 1px + 4px; // Tooltip arrow color @tooltip-arrow-color: @tooltip-bg; // Popover // --- // Popover body background color @popover-bg: #fff; // Popover text color @popover-color: @text-color; // Popover maximum width @popover-min-width: 177px; // Popover arrow width @popover-arrow-width: 6px; // Popover arrow color @popover-arrow-color: @popover-bg; // Popover outer arrow width // Popover outer arrow color @popover-arrow-outer-color: @popover-bg; // Popover distance with trigger @popover-distance: @popover-arrow-width + 4px; // Modal // -- @modal-body-padding: 24px; @modal-header-bg: @component-background; @modal-footer-bg: transparent; @modal-mask-bg: fade(@black, 65%); // Progress // -- @progress-default-color: @processing-color; @progress-remaining-color: @background-color-base; @progress-text-color: @text-color; // Menu // --- @menu-inline-toplevel-item-height: 40px; @menu-item-height: 40px; @menu-collapsed-width: 80px; @menu-bg: @component-background; @menu-popup-bg: @component-background; @menu-item-color: @text-color; @menu-highlight-color: @primary-color; @menu-item-active-bg: @item-active-bg; @menu-item-active-border-width: 3px; @menu-item-group-title-color: @text-color-secondary; // dark theme @menu-dark-color: @text-color-secondary-dark; @menu-dark-bg: @layout-header-background; @menu-dark-arrow-color: #fff; @menu-dark-submenu-bg: #000c17; @menu-dark-highlight-color: #fff; @menu-dark-item-active-bg: @primary-color; // Spin // --- @spin-dot-size-sm: 14px; @spin-dot-size: 20px; @spin-dot-size-lg: 32px; // Table // -- @table-header-bg: @background-color-light; @table-header-color: @heading-color; @table-header-sort-bg: @background-color-base; @table-body-sort-bg: rgba(0, 0, 0, 0.01); @table-row-hover-bg: @primary-1; @table-selected-row-color: inherit; @table-selected-row-bg: #fafafa; @table-expanded-row-bg: #fbfbfb; @table-padding-vertical: 16px; @table-padding-horizontal: 16px; @table-border-radius-base: @border-radius-base; // Tag // -- @tag-default-bg: @background-color-light; @tag-default-color: @text-color; @tag-font-size: @font-size-sm; // TimePicker // --- @time-picker-panel-column-width: 56px; @time-picker-panel-width: @time-picker-panel-column-width * 3; @time-picker-selected-bg: @background-color-base; // Carousel // --- @carousel-dot-width: 16px; @carousel-dot-height: 3px; @carousel-dot-active-width: 24px; // Badge // --- @badge-height: 20px; @badge-dot-size: 6px; @badge-font-size: @font-size-sm; @badge-font-weight: normal; @badge-status-size: 6px; @badge-text-color: @component-background; // Rate // --- @rate-star-color: @yellow-6; @rate-star-bg: @border-color-split; // Card // --- @card-head-color: @heading-color; @card-head-background: transparent; @card-head-padding: 16px; @card-inner-head-padding: 12px; @card-padding-base: 24px; @card-actions-background: @background-color-light; @card-background: #cfd8dc; @card-shadow: 0 2px 8px rgba(0, 0, 0, 0.09); @card-radius: @border-radius-sm; // Comment // --- @comment-padding-base: 16px 0; @comment-nest-indent: 44px; @comment-author-name-color: @text-color-secondary; @comment-author-time-color: #ccc; @comment-action-color: @text-color-secondary; @comment-action-hover-color: #595959; // Tabs // --- @tabs-card-head-background: @background-color-light; @tabs-card-height: 40px; @tabs-card-active-color: @primary-color; @tabs-title-font-size: @font-size-base; @tabs-title-font-size-lg: @font-size-lg; @tabs-title-font-size-sm: @font-size-base; @tabs-ink-bar-color: @primary-color; @tabs-bar-margin: 0 0 16px 0; @tabs-horizontal-margin: 0 32px 0 0; @tabs-horizontal-padding: 12px 16px; @tabs-horizontal-padding-lg: 16px; @tabs-horizontal-padding-sm: 8px 16px; @tabs-vertical-padding: 8px 24px; @tabs-vertical-margin: 0 0 16px 0; @tabs-scrolling-size: 32px; @tabs-highlight-color: @primary-color; @tabs-hover-color: @primary-5; @tabs-active-color: @primary-7; // BackTop // --- @back-top-color: #fff; @back-top-bg: @text-color-secondary; @back-top-hover-bg: @text-color; // Avatar // --- @avatar-size-base: 32px; @avatar-size-lg: 40px; @avatar-size-sm: 24px; @avatar-font-size-base: 18px; @avatar-font-size-lg: 24px; @avatar-font-size-sm: 14px; @avatar-bg: #ccc; @avatar-color: #fff; @avatar-border-radius: @border-radius-base; // Switch // --- @switch-height: 22px; @switch-sm-height: 16px; @switch-sm-checked-margin-left: -(@switch-sm-height - 3px); @switch-disabled-opacity: 0.4; @switch-color: @primary-color; @switch-shadow-color: fade(#00230b, 20%); // Pagination // --- @pagination-item-size: 32px; @pagination-item-size-sm: 24px; @pagination-font-family: Arial; @pagination-font-weight-active: 500; @pagination-item-bg-active: @component-background; // PageHeader // --- @page-header-padding-horizontal: 24px; @page-header-padding-vertical: 16px; // Breadcrumb // --- @breadcrumb-base-color: @text-color-secondary; @breadcrumb-last-item-color: @text-color; @breadcrumb-font-size: @font-size-base; @breadcrumb-icon-font-size: @font-size-base; @breadcrumb-link-color: @text-color-secondary; @breadcrumb-link-color-hover: @primary-5; @breadcrumb-separator-color: @text-color-secondary; @breadcrumb-separator-margin: 0 @padding-xs; // Slider // --- @slider-margin: 14px 6px 10px; @slider-rail-background-color: @background-color-base; @slider-rail-background-color-hover: #e1e1e1; @slider-track-background-color: @primary-3; @slider-track-background-color-hover: @primary-4; @slider-handle-color: @primary-3; @slider-handle-color-hover: @primary-4; @slider-handle-color-focus: tint(@primary-color, 20%); @slider-handle-color-focus-shadow: fade(@primary-color, 20%); @slider-handle-color-tooltip-open: @primary-color; @slider-dot-border-color: @border-color-split; @slider-dot-border-color-active: tint(@primary-color, 50%); @slider-disabled-color: @disabled-color; @slider-disabled-background-color: @component-background; // Tree // --- @tree-title-height: 24px; @tree-child-padding: 18px; @tree-directory-selected-color: #fff; @tree-directory-selected-bg: @primary-color; // Collapse // --- @collapse-header-padding: 12px 16px; @collapse-header-padding-extra: 40px; @collapse-header-bg: @background-color-light; @collapse-content-padding: @padding-md; @collapse-content-bg: @component-background; // Skeleton // --- @skeleton-color: #f2f2f2; // Transfer // --- @transfer-header-height: 40px; @transfer-disabled-bg: @disabled-bg; @transfer-list-height: 200px; // Message // --- @message-notice-content-padding: 10px 16px; // Motion // --- @wave-animation-width: 6px; // Alert // --- @alert-success-border-color: ~`colorPalette('@{success-color}', 3) `; @alert-success-bg-color: ~`colorPalette('@{success-color}', 1) `; @alert-success-icon-color: @success-color; @alert-info-border-color: ~`colorPalette('@{info-color}', 3) `; @alert-info-bg-color: ~`colorPalette('@{info-color}', 1) `; @alert-info-icon-color: @info-color; @alert-warning-border-color: ~`colorPalette('@{warning-color}', 3) `; @alert-warning-bg-color: ~`colorPalette('@{warning-color}', 1) `; @alert-warning-icon-color: @warning-color; @alert-error-border-color: ~`colorPalette('@{error-color}', 3) `; @alert-error-bg-color: ~`colorPalette('@{error-color}', 1) `; @alert-error-icon-color: @error-color; // List // --- @list-header-background: transparent; @list-footer-background: transparent; @list-empty-text-padding: @padding-md; @list-item-padding: @padding-sm 0; @list-item-meta-margin-bottom: @padding-md; @list-item-meta-avatar-margin-right: @padding-md; @list-item-meta-title-margin-bottom: @padding-sm; // Statistic // --- @statistic-title-font-size: @font-size-base; @statistic-content-font-size: 24px; @statistic-unit-font-size: 16px; @statistic-font-family: Tahoma, 'Helvetica Neue', @font-family; // Drawer // --- @drawer-header-padding: 16px 24px; @drawer-body-padding: 24px;
components/style/themes/default.less
1
https://github.com/ant-design/ant-design/commit/239c472c388a6210e71822bd30a383c26348bf48
[ 0.993583619594574, 0.016740182414650917, 0.00016289987252093852, 0.00017353263683617115, 0.12511363625526428 ]
{ "id": 0, "code_window": [ "@code-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;\n", "@text-color: fade(@black, 65%);\n", "@text-color-secondary: fade(@black, 45%);\n", "@text-color-warning: @gold-7;\n", "@text-color-danger: @red-7;\n", "@text-color-inverse: @white;\n", "@icon-color: inherit;\n", "@icon-color-hover: fade(@black, 75%);\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "components/style/themes/default.less", "type": "replace", "edit_start_line_idx": 49 }
import React from 'react'; import { Alert } from 'antd'; export default class ErrorBoundary extends React.Component { state = { error: null, }; componentDidCatch(error, info) { this.setState({ error, info }); } render() { const { children } = this.props; const { error, info } = this.state; if (error) { // You can render any custom fallback UI return <Alert type="error" message={error.toString()} description={info.componentStack} />; } return children; } }
site/theme/template/Content/ErrorBoundary.js
0
https://github.com/ant-design/ant-design/commit/239c472c388a6210e71822bd30a383c26348bf48
[ 0.00017502614355180413, 0.00017480911628808826, 0.00017469917656853795, 0.00017470199964009225, 1.5347264081810863e-7 ]
{ "id": 0, "code_window": [ "@code-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;\n", "@text-color: fade(@black, 65%);\n", "@text-color-secondary: fade(@black, 45%);\n", "@text-color-warning: @gold-7;\n", "@text-color-danger: @red-7;\n", "@text-color-inverse: @white;\n", "@icon-color: inherit;\n", "@icon-color-hover: fade(@black, 75%);\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "components/style/themes/default.less", "type": "replace", "edit_start_line_idx": 49 }
--- category: Components subtitle: 固钉 type: 导航 title: Affix --- 将页面元素钉在可视范围。 ## 何时使用 当内容区域比较长,需要滚动页面时,这部分内容对应的操作或者导航需要在滚动范围内始终展现。常用于侧边菜单和按钮组合。 页面可视范围过小时,慎用此功能以免遮挡页面内容。 ## API | 成员 | 说明 | 类型 | 默认值 | | --- | --- | --- | --- | | offsetBottom | 距离窗口底部达到指定偏移量后触发 | number | | | offsetTop | 距离窗口顶部达到指定偏移量后触发 | number | | | target | 设置 `Affix` 需要监听其滚动事件的元素,值为一个返回对应 DOM 元素的函数 | () => HTMLElement | () => window | | onChange | 固定状态改变时触发的回调函数 | Function(affixed) | 无 | **注意:**`Affix` 内的元素不要使用绝对定位,如需要绝对定位的效果,可以直接设置 `Affix` 为绝对定位: ```jsx <Affix style={{ position: 'absolute', top: y, left: x }}>...</Affix> ``` ## FAQ ### Affix 使用 `target` 绑定容器时,元素会跑到容器外。 从性能角度考虑,我们只监听容器滚动事件。如果希望任意滚动,你可以在窗体添加滚动监听:<https://codesandbox.io/s/2xyj5zr85p> 相关 issue:[#3938](https://github.com/ant-design/ant-design/issues/3938) [#5642](https://github.com/ant-design/ant-design/issues/5642) [#16120](https://github.com/ant-design/ant-design/issues/16120)
components/affix/index.zh-CN.md
0
https://github.com/ant-design/ant-design/commit/239c472c388a6210e71822bd30a383c26348bf48
[ 0.00017413689056411386, 0.00016870960826054215, 0.00016442248306702822, 0.00016813952242955565, 0.000003488349420877057 ]
{ "id": 0, "code_window": [ "@code-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;\n", "@text-color: fade(@black, 65%);\n", "@text-color-secondary: fade(@black, 45%);\n", "@text-color-warning: @gold-7;\n", "@text-color-danger: @red-7;\n", "@text-color-inverse: @white;\n", "@icon-color: inherit;\n", "@icon-color-hover: fade(@black, 75%);\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "components/style/themes/default.less", "type": "replace", "edit_start_line_idx": 49 }
--- order: 4 title: zh-CN: 清除 en-US: Clear star --- ## zh-CN 支持允许或者禁用清除。 ## en-US Support set allow to clear star when click again. ```jsx import { Rate } from 'antd'; ReactDOM.render( <div> <Rate defaultValue={3} /> allowClear: true <br /> <Rate allowClear={false} defaultValue={3} /> allowClear: false </div>, mountNode, ); ```
components/rate/demo/clear.md
0
https://github.com/ant-design/ant-design/commit/239c472c388a6210e71822bd30a383c26348bf48
[ 0.00017617896082811058, 0.00017506105359643698, 0.0001739208382787183, 0.00017508340533822775, 9.220099741469312e-7 ]
{ "id": 1, "code_window": [ " }\n", "\n", " &&-warning {\n", " color: @text-color-warning;\n", " }\n", "\n", " &&-danger {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " color: @warning-color;\n" ], "file_path": "components/typography/style/index.less", "type": "replace", "edit_start_line_idx": 41 }
/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */ @import '../color/colors'; // The prefix to use on all css classes from ant. @ant-prefix: ant; // An override for the html selector for theme prefixes @html-selector: html; // -------- Colors ----------- @primary-color: @blue-6; @info-color: @blue-6; @success-color: @green-6; @processing-color: @blue-6; @error-color: @red-6; @highlight-color: @red-6; @warning-color: @gold-6; @normal-color: #d9d9d9; @white: #fff; @black: #000; // Color used by default to control hover and active backgrounds and for // alert info backgrounds. @primary-1: color(~`colorPalette('@{primary-color}', 1) `); // replace tint(@primary-color, 90%) @primary-2: color(~`colorPalette('@{primary-color}', 2) `); // replace tint(@primary-color, 80%) @primary-3: color(~`colorPalette('@{primary-color}', 3) `); // unused @primary-4: color(~`colorPalette('@{primary-color}', 4) `); // unused @primary-5: color( ~`colorPalette('@{primary-color}', 5) ` ); // color used to control the text color in many active and hover states, replace tint(@primary-color, 20%) @primary-6: @primary-color; // color used to control the text color of active buttons, don't use, use @primary-color @primary-7: color(~`colorPalette('@{primary-color}', 7) `); // replace shade(@primary-color, 5%) @primary-8: color(~`colorPalette('@{primary-color}', 8) `); // unused @primary-9: color(~`colorPalette('@{primary-color}', 9) `); // unused @primary-10: color(~`colorPalette('@{primary-color}', 10) `); // unused // Base Scaffolding Variables // --- // Background color for `<body>` @body-background: #fff; // Base background color for most components @component-background: #fff; @font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'; @code-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace; @text-color: fade(@black, 65%); @text-color-secondary: fade(@black, 45%); @text-color-warning: @gold-7; @text-color-danger: @red-7; @text-color-inverse: @white; @icon-color: inherit; @icon-color-hover: fade(@black, 75%); @heading-color: fade(#000, 85%); @heading-color-dark: fade(@white, 100%); @text-color-dark: fade(@white, 85%); @text-color-secondary-dark: fade(@white, 65%); @text-selection-bg: @primary-color; @font-variant-base: tabular-nums; @font-feature-settings-base: 'tnum'; @font-size-base: 14px; @font-size-lg: @font-size-base + 2px; @font-size-sm: 12px; @heading-1-size: ceil(@font-size-base * 2.71); @heading-2-size: ceil(@font-size-base * 2.14); @heading-3-size: ceil(@font-size-base * 1.71); @heading-4-size: ceil(@font-size-base * 1.42); @line-height-base: 1.5; @border-radius-base: 4px; @border-radius-sm: 2px; // vertical paddings @padding-lg: 24px; // containers @padding-md: 16px; // small containers and buttons @padding-sm: 12px; // Form controls and items @padding-xs: 8px; // small items // vertical padding for all form controls @control-padding-horizontal: @padding-sm; @control-padding-horizontal-sm: @padding-xs; // The background colors for active and hover states for things like // list items or table cells. @item-active-bg: @primary-1; @item-hover-bg: @primary-1; // ICONFONT @iconfont-css-prefix: anticon; // LINK @link-color: @primary-color; @link-hover-color: color(~`colorPalette('@{link-color}', 5) `); @link-active-color: color(~`colorPalette('@{link-color}', 7) `); @link-decoration: none; @link-hover-decoration: none; // Animation @ease-base-out: cubic-bezier(0.7, 0.3, 0.1, 1); @ease-base-in: cubic-bezier(0.9, 0, 0.3, 0.7); @ease-out: cubic-bezier(0.215, 0.61, 0.355, 1); @ease-in: cubic-bezier(0.55, 0.055, 0.675, 0.19); @ease-in-out: cubic-bezier(0.645, 0.045, 0.355, 1); @ease-out-back: cubic-bezier(0.12, 0.4, 0.29, 1.46); @ease-in-back: cubic-bezier(0.71, -0.46, 0.88, 0.6); @ease-in-out-back: cubic-bezier(0.71, -0.46, 0.29, 1.46); @ease-out-circ: cubic-bezier(0.08, 0.82, 0.17, 1); @ease-in-circ: cubic-bezier(0.6, 0.04, 0.98, 0.34); @ease-in-out-circ: cubic-bezier(0.78, 0.14, 0.15, 0.86); @ease-out-quint: cubic-bezier(0.23, 1, 0.32, 1); @ease-in-quint: cubic-bezier(0.755, 0.05, 0.855, 0.06); @ease-in-out-quint: cubic-bezier(0.86, 0, 0.07, 1); // Border color @border-color-base: hsv(0, 0, 85%); // base border outline a component @border-color-split: hsv(0, 0, 91%); // split border inside a component @border-color-inverse: @white; @border-width-base: 1px; // width of the border for a component @border-style-base: solid; // style of a components border // Outline @outline-blur-size: 0; @outline-width: 2px; @outline-color: @primary-color; @background-color-light: hsv(0, 0, 98%); // background of header and selected item @background-color-base: hsv(0, 0, 96%); // Default grey background color // Disabled states @disabled-color: fade(#000, 25%); @disabled-bg: @background-color-base; @disabled-color-dark: fade(#fff, 35%); // Shadow @shadow-color: rgba(0, 0, 0, 0.15); @shadow-color-inverse: @component-background; @box-shadow-base: @shadow-1-down; @shadow-1-up: 0 -2px 8px @shadow-color; @shadow-1-down: 0 2px 8px @shadow-color; @shadow-1-left: -2px 0 8px @shadow-color; @shadow-1-right: 2px 0 8px @shadow-color; @shadow-2: 0 4px 12px @shadow-color; // Buttons @btn-font-weight: 400; @btn-border-radius-base: @border-radius-base; @btn-border-radius-sm: @border-radius-base; @btn-border-width: @border-width-base; @btn-border-style: @border-style-base; @btn-shadow: 0 2px 0 rgba(0, 0, 0, 0.015); @btn-primary-shadow: 0 2px 0 rgba(0, 0, 0, 0.045); @btn-text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.12); @btn-primary-color: #fff; @btn-primary-bg: @primary-color; @btn-default-color: @text-color; @btn-default-bg: #fff; @btn-default-border: @border-color-base; @btn-danger-color: @error-color; @btn-danger-bg: @background-color-base; @btn-danger-border: @border-color-base; @btn-disable-color: @disabled-color; @btn-disable-bg: @disabled-bg; @btn-disable-border: @border-color-base; @btn-padding-base: 0 @padding-md - 1px; @btn-font-size-lg: @font-size-lg; @btn-font-size-sm: @font-size-base; @btn-padding-lg: @btn-padding-base; @btn-padding-sm: 0 @padding-xs - 1px; @btn-height-base: 32px; @btn-height-lg: 40px; @btn-height-sm: 24px; @btn-circle-size: @btn-height-base; @btn-circle-size-lg: @btn-height-lg; @btn-circle-size-sm: @btn-height-sm; @btn-group-border: @primary-5; // Checkbox @checkbox-size: 16px; @checkbox-color: @primary-color; @checkbox-check-color: #fff; @checkbox-border-width: @border-width-base; // Empty @empty-font-size: @font-size-base; // Radio @radio-size: 16px; @radio-dot-color: @primary-color; // Radio buttons @radio-button-bg: @btn-default-bg; @radio-button-checked-bg: @btn-default-bg; @radio-button-color: @btn-default-color; @radio-button-hover-color: @primary-5; @radio-button-active-color: @primary-7; // Media queries breakpoints // Extra small screen / phone @screen-xs: 480px; @screen-xs-min: @screen-xs; // Small screen / tablet @screen-sm: 576px; @screen-sm-min: @screen-sm; // Medium screen / desktop @screen-md: 768px; @screen-md-min: @screen-md; // Large screen / wide desktop @screen-lg: 992px; @screen-lg-min: @screen-lg; // Extra large screen / full hd @screen-xl: 1200px; @screen-xl-min: @screen-xl; // Extra extra large screen / large desktop @screen-xxl: 1600px; @screen-xxl-min: @screen-xxl; // provide a maximum @screen-xs-max: (@screen-sm-min - 1px); @screen-sm-max: (@screen-md-min - 1px); @screen-md-max: (@screen-lg-min - 1px); @screen-lg-max: (@screen-xl-min - 1px); @screen-xl-max: (@screen-xxl-min - 1px); // Grid system @grid-columns: 24; @grid-gutter-width: 0; // Layout @layout-body-background: #f0f2f5; @layout-header-background: #001529; @layout-footer-background: @layout-body-background; @layout-header-height: 64px; @layout-header-padding: 0 50px; @layout-footer-padding: 24px 50px; @layout-sider-background: @layout-header-background; @layout-trigger-height: 48px; @layout-trigger-background: #002140; @layout-trigger-color: #fff; @layout-zero-trigger-width: 36px; @layout-zero-trigger-height: 42px; // Layout light theme @layout-sider-background-light: #fff; @layout-trigger-background-light: #fff; @layout-trigger-color-light: @text-color; // z-index list, order by `z-index` @zindex-table-fixed: auto; @zindex-affix: 10; @zindex-back-top: 10; @zindex-badge: 10; @zindex-picker-panel: 10; @zindex-popup-close: 10; @zindex-modal: 1000; @zindex-modal-mask: 1000; @zindex-message: 1010; @zindex-notification: 1010; @zindex-popover: 1030; @zindex-dropdown: 1050; @zindex-picker: 1050; @zindex-tooltip: 1060; // Animation @animation-duration-slow: 0.3s; // Modal @animation-duration-base: 0.2s; @animation-duration-fast: 0.1s; // Tooltip // Form // --- @label-required-color: @highlight-color; @label-color: @heading-color; @form-warning-input-bg: @input-bg; @form-item-margin-bottom: 24px; @form-item-trailing-colon: true; @form-vertical-label-padding: 0 0 8px; @form-vertical-label-margin: 0; @form-error-input-bg: @input-bg; // Input // --- @input-height-base: 32px; @input-height-lg: 40px; @input-height-sm: 24px; @input-padding-horizontal: @control-padding-horizontal - 1px; @input-padding-horizontal-base: @input-padding-horizontal; @input-padding-horizontal-sm: @control-padding-horizontal-sm - 1px; @input-padding-horizontal-lg: @input-padding-horizontal; @input-padding-vertical-base: 4px; @input-padding-vertical-sm: 1px; @input-padding-vertical-lg: 6px; @input-placeholder-color: hsv(0, 0, 75%); @input-color: @text-color; @input-border-color: @border-color-base; @input-bg: #fff; @input-number-handler-active-bg: #f4f4f4; @input-addon-bg: @background-color-light; @input-hover-border-color: @primary-color; @input-disabled-bg: @disabled-bg; @input-outline-offset: 0 0; // Select // --- @select-border-color: @border-color-base; @select-item-selected-font-weight: 600; // Tooltip // --- // Tooltip max width @tooltip-max-width: 250px; // Tooltip text color @tooltip-color: #fff; // Tooltip background color @tooltip-bg: rgba(0, 0, 0, 0.75); // Tooltip arrow width @tooltip-arrow-width: 5px; // Tooltip distance with trigger @tooltip-distance: @tooltip-arrow-width - 1px + 4px; // Tooltip arrow color @tooltip-arrow-color: @tooltip-bg; // Popover // --- // Popover body background color @popover-bg: #fff; // Popover text color @popover-color: @text-color; // Popover maximum width @popover-min-width: 177px; // Popover arrow width @popover-arrow-width: 6px; // Popover arrow color @popover-arrow-color: @popover-bg; // Popover outer arrow width // Popover outer arrow color @popover-arrow-outer-color: @popover-bg; // Popover distance with trigger @popover-distance: @popover-arrow-width + 4px; // Modal // -- @modal-body-padding: 24px; @modal-header-bg: @component-background; @modal-footer-bg: transparent; @modal-mask-bg: fade(@black, 65%); // Progress // -- @progress-default-color: @processing-color; @progress-remaining-color: @background-color-base; @progress-text-color: @text-color; // Menu // --- @menu-inline-toplevel-item-height: 40px; @menu-item-height: 40px; @menu-collapsed-width: 80px; @menu-bg: @component-background; @menu-popup-bg: @component-background; @menu-item-color: @text-color; @menu-highlight-color: @primary-color; @menu-item-active-bg: @item-active-bg; @menu-item-active-border-width: 3px; @menu-item-group-title-color: @text-color-secondary; // dark theme @menu-dark-color: @text-color-secondary-dark; @menu-dark-bg: @layout-header-background; @menu-dark-arrow-color: #fff; @menu-dark-submenu-bg: #000c17; @menu-dark-highlight-color: #fff; @menu-dark-item-active-bg: @primary-color; // Spin // --- @spin-dot-size-sm: 14px; @spin-dot-size: 20px; @spin-dot-size-lg: 32px; // Table // -- @table-header-bg: @background-color-light; @table-header-color: @heading-color; @table-header-sort-bg: @background-color-base; @table-body-sort-bg: rgba(0, 0, 0, 0.01); @table-row-hover-bg: @primary-1; @table-selected-row-color: inherit; @table-selected-row-bg: #fafafa; @table-expanded-row-bg: #fbfbfb; @table-padding-vertical: 16px; @table-padding-horizontal: 16px; @table-border-radius-base: @border-radius-base; // Tag // -- @tag-default-bg: @background-color-light; @tag-default-color: @text-color; @tag-font-size: @font-size-sm; // TimePicker // --- @time-picker-panel-column-width: 56px; @time-picker-panel-width: @time-picker-panel-column-width * 3; @time-picker-selected-bg: @background-color-base; // Carousel // --- @carousel-dot-width: 16px; @carousel-dot-height: 3px; @carousel-dot-active-width: 24px; // Badge // --- @badge-height: 20px; @badge-dot-size: 6px; @badge-font-size: @font-size-sm; @badge-font-weight: normal; @badge-status-size: 6px; @badge-text-color: @component-background; // Rate // --- @rate-star-color: @yellow-6; @rate-star-bg: @border-color-split; // Card // --- @card-head-color: @heading-color; @card-head-background: transparent; @card-head-padding: 16px; @card-inner-head-padding: 12px; @card-padding-base: 24px; @card-actions-background: @background-color-light; @card-background: #cfd8dc; @card-shadow: 0 2px 8px rgba(0, 0, 0, 0.09); @card-radius: @border-radius-sm; // Comment // --- @comment-padding-base: 16px 0; @comment-nest-indent: 44px; @comment-author-name-color: @text-color-secondary; @comment-author-time-color: #ccc; @comment-action-color: @text-color-secondary; @comment-action-hover-color: #595959; // Tabs // --- @tabs-card-head-background: @background-color-light; @tabs-card-height: 40px; @tabs-card-active-color: @primary-color; @tabs-title-font-size: @font-size-base; @tabs-title-font-size-lg: @font-size-lg; @tabs-title-font-size-sm: @font-size-base; @tabs-ink-bar-color: @primary-color; @tabs-bar-margin: 0 0 16px 0; @tabs-horizontal-margin: 0 32px 0 0; @tabs-horizontal-padding: 12px 16px; @tabs-horizontal-padding-lg: 16px; @tabs-horizontal-padding-sm: 8px 16px; @tabs-vertical-padding: 8px 24px; @tabs-vertical-margin: 0 0 16px 0; @tabs-scrolling-size: 32px; @tabs-highlight-color: @primary-color; @tabs-hover-color: @primary-5; @tabs-active-color: @primary-7; // BackTop // --- @back-top-color: #fff; @back-top-bg: @text-color-secondary; @back-top-hover-bg: @text-color; // Avatar // --- @avatar-size-base: 32px; @avatar-size-lg: 40px; @avatar-size-sm: 24px; @avatar-font-size-base: 18px; @avatar-font-size-lg: 24px; @avatar-font-size-sm: 14px; @avatar-bg: #ccc; @avatar-color: #fff; @avatar-border-radius: @border-radius-base; // Switch // --- @switch-height: 22px; @switch-sm-height: 16px; @switch-sm-checked-margin-left: -(@switch-sm-height - 3px); @switch-disabled-opacity: 0.4; @switch-color: @primary-color; @switch-shadow-color: fade(#00230b, 20%); // Pagination // --- @pagination-item-size: 32px; @pagination-item-size-sm: 24px; @pagination-font-family: Arial; @pagination-font-weight-active: 500; @pagination-item-bg-active: @component-background; // PageHeader // --- @page-header-padding-horizontal: 24px; @page-header-padding-vertical: 16px; // Breadcrumb // --- @breadcrumb-base-color: @text-color-secondary; @breadcrumb-last-item-color: @text-color; @breadcrumb-font-size: @font-size-base; @breadcrumb-icon-font-size: @font-size-base; @breadcrumb-link-color: @text-color-secondary; @breadcrumb-link-color-hover: @primary-5; @breadcrumb-separator-color: @text-color-secondary; @breadcrumb-separator-margin: 0 @padding-xs; // Slider // --- @slider-margin: 14px 6px 10px; @slider-rail-background-color: @background-color-base; @slider-rail-background-color-hover: #e1e1e1; @slider-track-background-color: @primary-3; @slider-track-background-color-hover: @primary-4; @slider-handle-color: @primary-3; @slider-handle-color-hover: @primary-4; @slider-handle-color-focus: tint(@primary-color, 20%); @slider-handle-color-focus-shadow: fade(@primary-color, 20%); @slider-handle-color-tooltip-open: @primary-color; @slider-dot-border-color: @border-color-split; @slider-dot-border-color-active: tint(@primary-color, 50%); @slider-disabled-color: @disabled-color; @slider-disabled-background-color: @component-background; // Tree // --- @tree-title-height: 24px; @tree-child-padding: 18px; @tree-directory-selected-color: #fff; @tree-directory-selected-bg: @primary-color; // Collapse // --- @collapse-header-padding: 12px 16px; @collapse-header-padding-extra: 40px; @collapse-header-bg: @background-color-light; @collapse-content-padding: @padding-md; @collapse-content-bg: @component-background; // Skeleton // --- @skeleton-color: #f2f2f2; // Transfer // --- @transfer-header-height: 40px; @transfer-disabled-bg: @disabled-bg; @transfer-list-height: 200px; // Message // --- @message-notice-content-padding: 10px 16px; // Motion // --- @wave-animation-width: 6px; // Alert // --- @alert-success-border-color: ~`colorPalette('@{success-color}', 3) `; @alert-success-bg-color: ~`colorPalette('@{success-color}', 1) `; @alert-success-icon-color: @success-color; @alert-info-border-color: ~`colorPalette('@{info-color}', 3) `; @alert-info-bg-color: ~`colorPalette('@{info-color}', 1) `; @alert-info-icon-color: @info-color; @alert-warning-border-color: ~`colorPalette('@{warning-color}', 3) `; @alert-warning-bg-color: ~`colorPalette('@{warning-color}', 1) `; @alert-warning-icon-color: @warning-color; @alert-error-border-color: ~`colorPalette('@{error-color}', 3) `; @alert-error-bg-color: ~`colorPalette('@{error-color}', 1) `; @alert-error-icon-color: @error-color; // List // --- @list-header-background: transparent; @list-footer-background: transparent; @list-empty-text-padding: @padding-md; @list-item-padding: @padding-sm 0; @list-item-meta-margin-bottom: @padding-md; @list-item-meta-avatar-margin-right: @padding-md; @list-item-meta-title-margin-bottom: @padding-sm; // Statistic // --- @statistic-title-font-size: @font-size-base; @statistic-content-font-size: 24px; @statistic-unit-font-size: 16px; @statistic-font-family: Tahoma, 'Helvetica Neue', @font-family; // Drawer // --- @drawer-header-padding: 16px 24px; @drawer-body-padding: 24px;
components/style/themes/default.less
1
https://github.com/ant-design/ant-design/commit/239c472c388a6210e71822bd30a383c26348bf48
[ 0.0006915801204741001, 0.0001833968417486176, 0.00016537390183657408, 0.00016927764227148145, 0.00006886473420308903 ]
{ "id": 1, "code_window": [ " }\n", "\n", " &&-warning {\n", " color: @text-color-warning;\n", " }\n", "\n", " &&-danger {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " color: @warning-color;\n" ], "file_path": "components/typography/style/index.less", "type": "replace", "edit_start_line_idx": 41 }
--- category: Components type: 导航 title: PageHeader cols: 1 subtitle: 页头 --- 页头可用于声明页面主题、展示用户所关注的页面重要信息,以及承载与当前页相关的操作项(包含页面级操作,页面间导航等) ## 何时使用 当需要使用户快速理解当前页是什么以及方便用户使用页面功能时使用,通常也可被用作页面间导航。 ## API | 参数 | 说明 | 类型 | 默认值 | | --- | --- | --- | --- | | title | 自定义标题文字 | ReactNode | - | | subTitle | 自定义的二级标题文字 | ReactNode | - | | backIcon | 自定义 back icon ,如果为 false 不渲染 back icon | ReactNode | `<Icon type="arrow-left" />` | | tags | title 旁的 tag 列表 | [Tag](https://ant.design/components/tag-cn/)[] \| [Tag](https://ant.design/components/tag-cn/) | - | | extra | 操作区,位于 title 行的行尾 | ReactNode | - | | breadcrumb | 面包屑的配置 | [breadcrumb](https://ant.design/components/breadcrumb-cn/) | - | | footer | PageHeader 的页脚,一般用于渲染 TabBar | ReactNode | - | | onBack | 返回按钮的点击事件 | `()=>void` | `()=>history.back()` |
components/page-header/index.zh-CN.md
0
https://github.com/ant-design/ant-design/commit/239c472c388a6210e71822bd30a383c26348bf48
[ 0.00016638617671560496, 0.000165698686032556, 0.00016491599672008306, 0.00016579387011006474, 6.039608138053154e-7 ]
{ "id": 1, "code_window": [ " }\n", "\n", " &&-warning {\n", " color: @text-color-warning;\n", " }\n", "\n", " &&-danger {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " color: @warning-color;\n" ], "file_path": "components/typography/style/index.less", "type": "replace", "edit_start_line_idx": 41 }
--- order: 5 title: zh-CN: 其他字符 en-US: Other Character --- ## zh-CN 可以将星星替换为其他字符,比如字母,数字,字体图标甚至中文。 ## en-US Replace the default star to other character like alphabet, digit, iconfont or even Chinese word. ```jsx import { Rate, Icon } from 'antd'; ReactDOM.render( <div> <Rate character={<Icon type="heart" />} allowHalf /> <br /> <Rate character="A" allowHalf style={{ fontSize: 36 }} /> <br /> <Rate character="好" allowHalf /> </div>, mountNode, ); ```
components/rate/demo/character.md
0
https://github.com/ant-design/ant-design/commit/239c472c388a6210e71822bd30a383c26348bf48
[ 0.00017433208995498717, 0.00017199141439050436, 0.00017075598589144647, 0.00017088613822124898, 0.0000016559671394134057 ]
{ "id": 1, "code_window": [ " }\n", "\n", " &&-warning {\n", " color: @text-color-warning;\n", " }\n", "\n", " &&-danger {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " color: @warning-color;\n" ], "file_path": "components/typography/style/index.less", "type": "replace", "edit_start_line_idx": 41 }
import * as React from 'react'; import * as PropTypes from 'prop-types'; import classNames from 'classnames'; import { polyfill } from 'react-lifecycles-compat'; import Group from './button-group'; import omit from 'omit.js'; import Icon from '../icon'; import { ConfigConsumer, ConfigConsumerProps } from '../config-provider'; import Wave from '../_util/wave'; import { Omit, tuple } from '../_util/type'; const rxTwoCNChar = /^[\u4e00-\u9fa5]{2}$/; const isTwoCNChar = rxTwoCNChar.test.bind(rxTwoCNChar); function isString(str: any) { return typeof str === 'string'; } function spaceChildren(children: React.ReactNode, needInserted: boolean) { let isPrevChildPure: boolean = false; const childList: React.ReactNode[] = []; React.Children.forEach(children, child => { const type = typeof child; const isCurrentChildPure = type === 'string' || type === 'number'; if (isPrevChildPure && isCurrentChildPure) { const lastIndex = childList.length - 1; const lastChild = childList[lastIndex]; childList[lastIndex] = `${lastChild}${child}`; } else { childList.push(child); } isPrevChildPure = isCurrentChildPure; }); // Pass to React.Children.map to auto fill key return React.Children.map(childList, child => insertSpace(child as React.ReactChild, needInserted), ); } // Insert one space between two chinese characters automatically. function insertSpace(child: React.ReactChild, needInserted: boolean) { // Check the child if is undefined or null. if (child == null) { return; } const SPACE = needInserted ? ' ' : ''; // strictNullChecks oops. if ( typeof child !== 'string' && typeof child !== 'number' && isString(child.type) && isTwoCNChar(child.props.children) ) { return React.cloneElement(child, {}, child.props.children.split('').join(SPACE)); } if (typeof child === 'string') { if (isTwoCNChar(child)) { child = child.split('').join(SPACE); } return <span>{child}</span>; } return child; } const ButtonTypes = tuple('default', 'primary', 'ghost', 'dashed', 'danger', 'link'); export type ButtonType = (typeof ButtonTypes)[number]; const ButtonShapes = tuple('circle', 'circle-outline', 'round'); export type ButtonShape = (typeof ButtonShapes)[number]; const ButtonSizes = tuple('large', 'default', 'small'); export type ButtonSize = (typeof ButtonSizes)[number]; const ButtonHTMLTypes = tuple('submit', 'button', 'reset'); export type ButtonHTMLType = (typeof ButtonHTMLTypes)[number]; export interface BaseButtonProps { type?: ButtonType; icon?: string; shape?: ButtonShape; size?: ButtonSize; loading?: boolean | { delay?: number }; prefixCls?: string; className?: string; ghost?: boolean; block?: boolean; children?: React.ReactNode; } // Typescript will make optional not optional if use Pick with union. // Should change to `AnchorButtonProps | NativeButtonProps` and `any` to `HTMLAnchorElement | HTMLButtonElement` if it fixed. // ref: https://github.com/ant-design/ant-design/issues/15930 export type AnchorButtonProps = { href: string; target?: string; onClick?: React.MouseEventHandler<any>; } & BaseButtonProps & Omit<React.AnchorHTMLAttributes<any>, 'type'>; export type NativeButtonProps = { htmlType?: ButtonHTMLType; onClick?: React.MouseEventHandler<any>; } & BaseButtonProps & Omit<React.ButtonHTMLAttributes<any>, 'type'>; export type ButtonProps = Partial<AnchorButtonProps & NativeButtonProps>; interface ButtonState { loading?: boolean | { delay?: number }; hasTwoCNChar: boolean; } class Button extends React.Component<ButtonProps, ButtonState> { static Group: typeof Group; static __ANT_BUTTON = true; static defaultProps = { loading: false, ghost: false, block: false, htmlType: 'button', }; static propTypes = { type: PropTypes.string, shape: PropTypes.oneOf(ButtonShapes), size: PropTypes.oneOf(ButtonSizes), htmlType: PropTypes.oneOf(ButtonHTMLTypes), onClick: PropTypes.func, loading: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]), className: PropTypes.string, icon: PropTypes.string, block: PropTypes.bool, }; static getDerivedStateFromProps(nextProps: ButtonProps, prevState: ButtonState) { if (nextProps.loading instanceof Boolean) { return { ...prevState, loading: nextProps.loading, }; } return null; } private delayTimeout: number; private buttonNode: HTMLElement | null; constructor(props: ButtonProps) { super(props); this.state = { loading: props.loading, hasTwoCNChar: false, }; } componentDidMount() { this.fixTwoCNChar(); } componentDidUpdate(prevProps: ButtonProps) { this.fixTwoCNChar(); if (prevProps.loading && typeof prevProps.loading !== 'boolean') { clearTimeout(this.delayTimeout); } const { loading } = this.props; if (loading && typeof loading !== 'boolean' && loading.delay) { this.delayTimeout = window.setTimeout(() => this.setState({ loading }), loading.delay); } else if (prevProps.loading === this.props.loading) { return; } else { this.setState({ loading }); } } componentWillUnmount() { if (this.delayTimeout) { clearTimeout(this.delayTimeout); } } saveButtonRef = (node: HTMLElement | null) => { this.buttonNode = node; }; fixTwoCNChar() { // Fix for HOC usage like <FormatMessage /> if (!this.buttonNode) { return; } const buttonText = this.buttonNode.textContent || this.buttonNode.innerText; if (this.isNeedInserted() && isTwoCNChar(buttonText)) { if (!this.state.hasTwoCNChar) { this.setState({ hasTwoCNChar: true, }); } } else if (this.state.hasTwoCNChar) { this.setState({ hasTwoCNChar: false, }); } } handleClick: React.MouseEventHandler<HTMLButtonElement | HTMLAnchorElement> = e => { const { loading } = this.state; const { onClick } = this.props; if (!!loading) { return; } if (onClick) { (onClick as React.MouseEventHandler<HTMLButtonElement | HTMLAnchorElement>)(e); } }; isNeedInserted() { const { icon, children } = this.props; return React.Children.count(children) === 1 && !icon; } renderButton = ({ getPrefixCls, autoInsertSpaceInButton }: ConfigConsumerProps) => { const { prefixCls: customizePrefixCls, type, shape, size, className, children, icon, ghost, loading: _loadingProp, block, ...rest } = this.props; const { loading, hasTwoCNChar } = this.state; const prefixCls = getPrefixCls('btn', customizePrefixCls); const autoInsertSpace = autoInsertSpaceInButton !== false; // large => lg // small => sm let sizeCls = ''; switch (size) { case 'large': sizeCls = 'lg'; break; case 'small': sizeCls = 'sm'; break; default: break; } const classes = classNames(prefixCls, className, { [`${prefixCls}-${type}`]: type, [`${prefixCls}-${shape}`]: shape, [`${prefixCls}-${sizeCls}`]: sizeCls, [`${prefixCls}-icon-only`]: !children && children !== 0 && icon, [`${prefixCls}-loading`]: loading, [`${prefixCls}-background-ghost`]: ghost, [`${prefixCls}-two-chinese-chars`]: hasTwoCNChar && autoInsertSpace, [`${prefixCls}-block`]: block, }); const iconType = loading ? 'loading' : icon; const iconNode = iconType ? <Icon type={iconType} /> : null; const kids = children || children === 0 ? spaceChildren(children, this.isNeedInserted() && autoInsertSpace) : null; const linkButtonRestProps = omit(rest as AnchorButtonProps, ['htmlType']); if (linkButtonRestProps.href !== undefined) { return ( <a {...linkButtonRestProps} className={classes} onClick={this.handleClick} ref={this.saveButtonRef} > {iconNode} {kids} </a> ); } // React does not recognize the `htmlType` prop on a DOM element. Here we pick it out of `rest`. const { htmlType, ...otherProps } = rest as NativeButtonProps; const buttonNode = ( <button {...otherProps as NativeButtonProps} type={htmlType} className={classes} onClick={this.handleClick} ref={this.saveButtonRef} > {iconNode} {kids} </button> ); if (type === 'link') { return buttonNode; } return <Wave>{buttonNode}</Wave>; }; render() { return <ConfigConsumer>{this.renderButton}</ConfigConsumer>; } } polyfill(Button); export default Button;
components/button/button.tsx
0
https://github.com/ant-design/ant-design/commit/239c472c388a6210e71822bd30a383c26348bf48
[ 0.00023796585446689278, 0.00017437853966839612, 0.00016531431174371392, 0.00017143369768746197, 0.000012393258657539263 ]
{ "id": 2, "code_window": [ " }\n", "\n", " &&-danger {\n", " color: @text-color-danger;\n", " }\n", "\n", " &&-disabled {\n", " color: @disabled-color;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " color: @error-color;\n" ], "file_path": "components/typography/style/index.less", "type": "replace", "edit_start_line_idx": 45 }
@import '../../style/themes/index'; @import '../../style/mixins/index'; @typography-prefix-cls: ~'@{ant-prefix}-typography'; @typography-title-margin-top: 1.2em; // =============== Common =============== .typography-paragraph() { margin-bottom: 1em; } .typography-title(@fontSize; @lineHeight) { margin-bottom: 0.5em; color: @heading-color; font-weight: 600; font-size: @fontSize; line-height: @lineHeight; } .typography-title-1() { .typography-title(@heading-1-size, 1.23); } .typography-title-2() { .typography-title(@heading-2-size, 1.35); } .typography-title-3() { .typography-title(@heading-3-size, 1.35); } .typography-title-4() { .typography-title(@heading-4-size, 1.4); } // =============== Basic =============== .@{typography-prefix-cls} { color: @text-color; &&-secondary { color: @text-color-secondary; } &&-warning { color: @text-color-warning; } &&-danger { color: @text-color-danger; } &&-disabled { color: @disabled-color; cursor: not-allowed; user-select: none; } // Tag div&, p { .typography-paragraph(); } h1&, h1 { .typography-title-1(); } h2&, h2 { .typography-title-2(); } h3&, h3 { .typography-title-3(); } h4&, h4 { .typography-title-4(); } h1&, h2&, h3&, h4& { .@{typography-prefix-cls} + & { margin-top: @typography-title-margin-top; } } div, ul, li, p, h1, h2, h3, h4 { + h1, + h2, + h3, + h4 { margin-top: @typography-title-margin-top; } } span&-ellipsis { display: inline-block; } a { .operation-unit(); &:active, &:hover { text-decoration: @link-hover-decoration; } &[disabled] { color: @disabled-color; cursor: not-allowed; pointer-events: none; } } code { margin: 0 0.2em; padding: 0.2em 0.4em 0.1em; font-size: 85%; background: rgba(0, 0, 0, 0.06); border: 1px solid rgba(0, 0, 0, 0.06); border-radius: 3px; } mark { padding: 0; background-color: @gold-3; } u, ins { text-decoration: underline; text-decoration-skip-ink: auto; } s, del { text-decoration: line-through; } strong { font-weight: 600; } // Operation &-expand, &-edit, &-copy { .operation-unit(); margin-left: 8px; } &-copy-success { &, &:hover, &:focus { color: @success-color; } } // Text input area &-edit-content { position: relative; div& { left: -@input-padding-horizontal - 1px; margin-top: -@input-padding-vertical-base - 1px; margin-bottom: calc(1em - @input-padding-vertical-base - 2px); } &-confirm { position: absolute; right: 10px; bottom: 8px; color: @text-color-secondary; pointer-events: none; } } // list ul, ol { margin: 0 0 1em 0; padding: 0; li { margin: 0 0 0 20px; padding: 0 0 0 4px; } } ul li { list-style-type: circle; li { list-style-type: disc; } } ol li { list-style-type: decimal; } // ============ Ellipsis ============ &-ellipsis-single-line { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } &-ellipsis-multiple-line { display: -webkit-box; -webkit-line-clamp: 3; /*! autoprefixer: ignore next */ -webkit-box-orient: vertical; overflow: hidden; } }
components/typography/style/index.less
1
https://github.com/ant-design/ant-design/commit/239c472c388a6210e71822bd30a383c26348bf48
[ 0.9906827211380005, 0.04325258731842041, 0.00016462375060655177, 0.00016994595353025943, 0.20199277997016907 ]
{ "id": 2, "code_window": [ " }\n", "\n", " &&-danger {\n", " color: @text-color-danger;\n", " }\n", "\n", " &&-disabled {\n", " color: @disabled-color;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " color: @error-color;\n" ], "file_path": "components/typography/style/index.less", "type": "replace", "edit_start_line_idx": 45 }
import es_ES from '../../date-picker/locale/es_ES'; export default es_ES;
components/calendar/locale/es_ES.tsx
0
https://github.com/ant-design/ant-design/commit/239c472c388a6210e71822bd30a383c26348bf48
[ 0.0001755648700054735, 0.0001755648700054735, 0.0001755648700054735, 0.0001755648700054735, 0 ]
{ "id": 2, "code_window": [ " }\n", "\n", " &&-danger {\n", " color: @text-color-danger;\n", " }\n", "\n", " &&-disabled {\n", " color: @disabled-color;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " color: @error-color;\n" ], "file_path": "components/typography/style/index.less", "type": "replace", "edit_start_line_idx": 45 }
import demoTest from '../../../tests/shared/demoTest'; demoTest('tree-select');
components/tree-select/__tests__/demo.test.js
0
https://github.com/ant-design/ant-design/commit/239c472c388a6210e71822bd30a383c26348bf48
[ 0.00017669002409093082, 0.00017669002409093082, 0.00017669002409093082, 0.00017669002409093082, 0 ]
{ "id": 2, "code_window": [ " }\n", "\n", " &&-danger {\n", " color: @text-color-danger;\n", " }\n", "\n", " &&-disabled {\n", " color: @disabled-color;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " color: @error-color;\n" ], "file_path": "components/typography/style/index.less", "type": "replace", "edit_start_line_idx": 45 }
--- order: 1 title: zh-CN: 选择图片 en-US: Chose image --- ## zh-CN 可以通过设置 `image` 为 `Empty.PRESENTED_IMAGE_SIMPLE` 选择另一种风格的图片。 ## en-US You can choose another style of `image` by setting image to `Empty.PRESENTED_IMAGE_SIMPLE`. ```jsx import { Empty } from 'antd'; ReactDOM.render(<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />, mountNode); ```
components/empty/demo/simple.md
0
https://github.com/ant-design/ant-design/commit/239c472c388a6210e71822bd30a383c26348bf48
[ 0.0001796176948118955, 0.0001742728491080925, 0.00017042970284819603, 0.00017277110600844026, 0.000003898392151313601 ]
{ "id": 0, "code_window": [ "export interface Props {\n", " title: string;\n", " description?: string;\n", " keywords?: string[];\n", " sponsor?: SponsorType;\n", "}\n", "\n", "const {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " noIndex?: boolean;\n" ], "file_path": "src/layouts/BaseLayout.astro", "type": "add", "edit_start_line_idx": 14 }
--- import InteractiveRoadamp from '../../components/InteractiveRoadmap/InteractiveRoadmap.astro'; import MarkdownRoadmap from '../../components/MarkdownRoadmap.astro'; import RoadmapHeader from '../../components/RoadmapHeader.astro'; import BaseLayout from '../../layouts/BaseLayout.astro'; import { getRoadmapIds, RoadmapFrontmatter } from '../../lib/roadmap'; export async function getStaticPaths() { const roadmapIds = await getRoadmapIds(); return roadmapIds.map((roadmapId) => ({ params: { roadmapId }, })); } interface Params extends Record<string, string | undefined> { roadmapId: string; } const { roadmapId } = Astro.params as Params; const roadmapFile = await import(`../../roadmaps/${roadmapId}/${roadmapId}.md`); const roadmapData = roadmapFile.frontmatter as RoadmapFrontmatter; --- <BaseLayout title={roadmapData?.seo?.title} description={roadmapData.seo.description} keywords={roadmapData.seo.keywords} sponsor={roadmapData.sponsor} > <RoadmapHeader description={roadmapData.description} title={roadmapData.title} roadmapPermalink={`/${roadmapId}`} hasTopics={roadmapData.hasTopics} /> { roadmapData.jsonUrl && ( <InteractiveRoadamp roadmapId={roadmapId} description={roadmapData.description} roadmapPermalink={`/${roadmapId}`} jsonUrl={roadmapData.jsonUrl} dimensions={roadmapData.dimensions} /> ) } { !roadmapData.jsonUrl && ( <MarkdownRoadmap> <roadmapFile.Content /> </MarkdownRoadmap> ) } </BaseLayout>
src/pages/[roadmapId]/index.astro
1
https://github.com/kamranahmedse/developer-roadmap/commit/9dbb2d05c929d4927e0c79654d8dfb462412759b
[ 0.0004681671562138945, 0.00024814545758999884, 0.00017177335394080728, 0.0001751093368511647, 0.00011268491653027013 ]
{ "id": 0, "code_window": [ "export interface Props {\n", " title: string;\n", " description?: string;\n", " keywords?: string[];\n", " sponsor?: SponsorType;\n", "}\n", "\n", "const {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " noIndex?: boolean;\n" ], "file_path": "src/layouts/BaseLayout.astro", "type": "add", "edit_start_line_idx": 14 }
# Enterprise Level Architecture The highest level of architecture. Focus on multiple solutions. High level, abstract design, which needs to be detailed out by solution or application architects. Communication is across the organization. Visit the following resources to learn more: - [Enterprise Software Architecture](https://medium.com/@hsienwei/enterprise-software-architecture-957288829daa) - [Enterprise Architect vs Software Architect](https://www.linkedin.com/pulse/enterprise-architect-vs-software-who-you-luigi-saggese/)
src/roadmaps/software-architect/content/100-software-architect-basics/102-levels-of-architecture/102-enterprise-architecture.md
0
https://github.com/kamranahmedse/developer-roadmap/commit/9dbb2d05c929d4927e0c79654d8dfb462412759b
[ 0.00017209223005920649, 0.00017209223005920649, 0.00017209223005920649, 0.00017209223005920649, 0 ]
{ "id": 0, "code_window": [ "export interface Props {\n", " title: string;\n", " description?: string;\n", " keywords?: string[];\n", " sponsor?: SponsorType;\n", "}\n", "\n", "const {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " noIndex?: boolean;\n" ], "file_path": "src/layouts/BaseLayout.astro", "type": "add", "edit_start_line_idx": 14 }
# Intellij idea
src/roadmaps/flutter/content/101-setup-development-environment/101-ides/102-intellij-idea.md
0
https://github.com/kamranahmedse/developer-roadmap/commit/9dbb2d05c929d4927e0c79654d8dfb462412759b
[ 0.00017785991076380014, 0.00017785991076380014, 0.00017785991076380014, 0.00017785991076380014, 0 ]
{ "id": 0, "code_window": [ "export interface Props {\n", " title: string;\n", " description?: string;\n", " keywords?: string[];\n", " sponsor?: SponsorType;\n", "}\n", "\n", "const {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " noIndex?: boolean;\n" ], "file_path": "src/layouts/BaseLayout.astro", "type": "add", "edit_start_line_idx": 14 }
# Loki Loki is a horizontally scalable, highly available, multi-tenant log aggregation system inspired by Prometheus. It is designed to be very cost-effective and easy to operate. It does not index the contents of the logs, but rather a set of labels for each log stream. Visit the following resources to learn more: - [Loki Website](https://grafana.com/oss/loki/) - [Official Documentation](https://grafana.com/docs/loki/latest/?pg=oss-loki&plcmt=quick-links)
src/roadmaps/devops/content/107-monitoring/102-logs-management/103-loki.md
0
https://github.com/kamranahmedse/developer-roadmap/commit/9dbb2d05c929d4927e0c79654d8dfb462412759b
[ 0.0001745939371176064, 0.0001745939371176064, 0.0001745939371176064, 0.0001745939371176064, 0 ]
{ "id": 1, "code_window": [ " title = siteConfig.title,\n", " description = siteConfig.description,\n", " keywords = siteConfig.keywords,\n", " sponsor,\n", "} = Astro.props;\n", "---\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " noIndex = false,\n" ], "file_path": "src/layouts/BaseLayout.astro", "type": "add", "edit_start_line_idx": 21 }
--- import '../styles/global.css'; import Navigation from '../components/Navigation/Navigation.astro'; import OpenSourceBanner from '../components/OpenSourceBanner.astro'; import Footer from '../components/Footer.astro'; import type { SponsorType } from '../components/Sponsor/Sponsor.astro'; import Sponsor from '../components/Sponsor/Sponsor.astro'; import YouTubeBanner from '../components/YouTubeBanner.astro'; import { siteConfig } from '../lib/config'; export interface Props { title: string; description?: string; keywords?: string[]; sponsor?: SponsorType; } const { title = siteConfig.title, description = siteConfig.description, keywords = siteConfig.keywords, sponsor, } = Astro.props; --- <!DOCTYPE html> <html lang='en'> <head> <meta charset='UTF-8' /> <meta name='generator' content={Astro.generator} /> <title>{title}</title> <meta name='description' content={description} /> <meta name='author' content='Kamran Ahmed' /> <meta name='keywords' content={keywords.join(', ')} /> <meta name='viewport' content='width=device-width, user-scalable=yes, initial-scale=1.0, maximum-scale=3.0, minimum-scale=1.0' /> <meta http-equiv='Content-Language' content='en' /> <meta name='twitter:card' content='summary_large_image' /> <meta name='twitter:creator' content='@kamranahmedse' /> <meta property='og:image:width' content='1200' /> <meta property='og:image:height' content='630' /> <meta property='og:image' content='https://roadmap.sh/og-img.png' /> <meta property='og:image:alt' content='roadmap.sh' /> <meta property='og:site_name' content='roadmap.sh' /> <meta property='og:title' content={title} /> <meta property='og:description' content={description} /> <meta property='og:type' content='website' /> <meta property='og:url' content='https://roadmap.sh' /> <meta name='mobile-web-app-capable' content='yes' /> <meta name='apple-mobile-web-app-capable' content='yes' /> <meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' /> <meta name='apple-mobile-web-app-title' content='roadmap.sh' /> <meta name='application-name' content='roadmap.sh' /> <link rel='apple-touch-icon' sizes='180x180' href='/manifest/apple-touch-icon.png' /> <meta name='msapplication-TileColor' content='#101010' /> <meta name='theme-color' content='#848a9a' /> <link rel='manifest' href='/manifest/manifest.json' /> <link rel='icon' type='image/png' sizes='32x32' href='/manifest/icon32.png' /> <link rel='icon' type='image/png' sizes='16x16' href='/manifest/icon16.png' /> <link rel='shortcut icon' href='/manifest/favicon.ico' type='image/x-icon' /> <link rel='icon' href='/manifest/favicon.ico' type='image/x-icon' /> <slot name='after-header' /> </head> <body> <YouTubeBanner /> <Navigation /> <slot /> <OpenSourceBanner /> <Footer /> {sponsor && <Sponsor sponsor={sponsor} />} <slot name='after-footer' /> </body> </html>
src/layouts/BaseLayout.astro
1
https://github.com/kamranahmedse/developer-roadmap/commit/9dbb2d05c929d4927e0c79654d8dfb462412759b
[ 0.9974097609519958, 0.18095256388187408, 0.00016634682833682746, 0.00017804690287448466, 0.38246679306030273 ]
{ "id": 1, "code_window": [ " title = siteConfig.title,\n", " description = siteConfig.description,\n", " keywords = siteConfig.keywords,\n", " sponsor,\n", "} = Astro.props;\n", "---\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " noIndex = false,\n" ], "file_path": "src/layouts/BaseLayout.astro", "type": "add", "edit_start_line_idx": 21 }
# Nuke
src/roadmaps/aspnet-core/content/118-good-to-know-libraries/103-nuke.md
0
https://github.com/kamranahmedse/developer-roadmap/commit/9dbb2d05c929d4927e0c79654d8dfb462412759b
[ 0.00017932061746250838, 0.00017932061746250838, 0.00017932061746250838, 0.00017932061746250838, 0 ]
{ "id": 1, "code_window": [ " title = siteConfig.title,\n", " description = siteConfig.description,\n", " keywords = siteConfig.keywords,\n", " sponsor,\n", "} = Astro.props;\n", "---\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " noIndex = false,\n" ], "file_path": "src/layouts/BaseLayout.astro", "type": "add", "edit_start_line_idx": 21 }
# pnpm PNPM is an alternative package manager for Node. js which stands for “Performant NPM”. The main purpose of PNPM is to hold all the packages at a global (centralized) store and use them if needed by other projects too by creating hard links to it. Visit the following resources to learn more: - [Official Website](https://pnpm.io) - [Meet PNPM: The Faster, More Performant NPM](https://blog.bitsrc.io/pnpm-javascript-package-manager-4b5abd59dc9)
src/roadmaps/frontend/content/107-package-managers/102-pnpm.md
0
https://github.com/kamranahmedse/developer-roadmap/commit/9dbb2d05c929d4927e0c79654d8dfb462412759b
[ 0.00016791399684734643, 0.00016791399684734643, 0.00016791399684734643, 0.00016791399684734643, 0 ]
{ "id": 1, "code_window": [ " title = siteConfig.title,\n", " description = siteConfig.description,\n", " keywords = siteConfig.keywords,\n", " sponsor,\n", "} = Astro.props;\n", "---\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " noIndex = false,\n" ], "file_path": "src/layouts/BaseLayout.astro", "type": "add", "edit_start_line_idx": 21 }
<DedicatedRoadmap href='/python' title='Python Roadmap' description='Click to check the detailed Python Roadmap.' /> # Python Python is a well known programming language which is both a strongly typed and a dynamically typed language. Being an interpreted language, code is executed as soon as it is written and the Python syntax allows for writing code in functional, procedural or object-oriented programmatic ways. Visit the following resources to learn more: - [Visit Dedicated Python Roadmap](/python) - [Python Website](https://www.python.org/) - [Python Getting Started](https://www.python.org/about/gettingstarted/) - [Automate the Boring Stuff](https://automatetheboringstuff.com/) - [FreeCodeCamp.org - How to Learn Python ? ](https://www.freecodecamp.org/news/how-to-learn-python/) - [Python principles - Python basics](https://pythonprinciples.com/) - [W3Schools - Python Tutorial ](https://www.w3schools.com/python/) - [Python Crash Course](https://ehmatthes.github.io/pcc/) - [Codecademy - Learn Python 2](https://www.codecademy.com/learn/learn-python) - [An Introduction to Python for Non-Programmers](https://thenewstack.io/an-introduction-to-python-for-non-programmers/) - [Getting Started with Python and InfluxDB](https://thenewstack.io/getting-started-with-python-and-influxdb/)
src/roadmaps/backend/content/103-learn-a-language/106-python.md
0
https://github.com/kamranahmedse/developer-roadmap/commit/9dbb2d05c929d4927e0c79654d8dfb462412759b
[ 0.0001704054739093408, 0.00016828184016048908, 0.00016587894060648978, 0.00016856110596563667, 0.0000018584704548629816 ]
{ "id": 2, "code_window": [ " <meta name='generator' content={Astro.generator} />\n", " <title>{title}</title>\n", " <meta name='description' content={description} />\n", " <meta name='author' content='Kamran Ahmed' />\n", " <meta name='keywords' content={keywords.join(', ')} />\n", " <meta\n", " name='viewport'\n", " content='width=device-width, user-scalable=yes, initial-scale=1.0, maximum-scale=3.0, minimum-scale=1.0'\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " {noIndex && <meta name='robots' content='noindex' />}\n" ], "file_path": "src/layouts/BaseLayout.astro", "type": "add", "edit_start_line_idx": 34 }
--- import '../styles/global.css'; import Navigation from '../components/Navigation/Navigation.astro'; import OpenSourceBanner from '../components/OpenSourceBanner.astro'; import Footer from '../components/Footer.astro'; import type { SponsorType } from '../components/Sponsor/Sponsor.astro'; import Sponsor from '../components/Sponsor/Sponsor.astro'; import YouTubeBanner from '../components/YouTubeBanner.astro'; import { siteConfig } from '../lib/config'; export interface Props { title: string; description?: string; keywords?: string[]; sponsor?: SponsorType; } const { title = siteConfig.title, description = siteConfig.description, keywords = siteConfig.keywords, sponsor, } = Astro.props; --- <!DOCTYPE html> <html lang='en'> <head> <meta charset='UTF-8' /> <meta name='generator' content={Astro.generator} /> <title>{title}</title> <meta name='description' content={description} /> <meta name='author' content='Kamran Ahmed' /> <meta name='keywords' content={keywords.join(', ')} /> <meta name='viewport' content='width=device-width, user-scalable=yes, initial-scale=1.0, maximum-scale=3.0, minimum-scale=1.0' /> <meta http-equiv='Content-Language' content='en' /> <meta name='twitter:card' content='summary_large_image' /> <meta name='twitter:creator' content='@kamranahmedse' /> <meta property='og:image:width' content='1200' /> <meta property='og:image:height' content='630' /> <meta property='og:image' content='https://roadmap.sh/og-img.png' /> <meta property='og:image:alt' content='roadmap.sh' /> <meta property='og:site_name' content='roadmap.sh' /> <meta property='og:title' content={title} /> <meta property='og:description' content={description} /> <meta property='og:type' content='website' /> <meta property='og:url' content='https://roadmap.sh' /> <meta name='mobile-web-app-capable' content='yes' /> <meta name='apple-mobile-web-app-capable' content='yes' /> <meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' /> <meta name='apple-mobile-web-app-title' content='roadmap.sh' /> <meta name='application-name' content='roadmap.sh' /> <link rel='apple-touch-icon' sizes='180x180' href='/manifest/apple-touch-icon.png' /> <meta name='msapplication-TileColor' content='#101010' /> <meta name='theme-color' content='#848a9a' /> <link rel='manifest' href='/manifest/manifest.json' /> <link rel='icon' type='image/png' sizes='32x32' href='/manifest/icon32.png' /> <link rel='icon' type='image/png' sizes='16x16' href='/manifest/icon16.png' /> <link rel='shortcut icon' href='/manifest/favicon.ico' type='image/x-icon' /> <link rel='icon' href='/manifest/favicon.ico' type='image/x-icon' /> <slot name='after-header' /> </head> <body> <YouTubeBanner /> <Navigation /> <slot /> <OpenSourceBanner /> <Footer /> {sponsor && <Sponsor sponsor={sponsor} />} <slot name='after-footer' /> </body> </html>
src/layouts/BaseLayout.astro
1
https://github.com/kamranahmedse/developer-roadmap/commit/9dbb2d05c929d4927e0c79654d8dfb462412759b
[ 0.38064122200012207, 0.035391759127378464, 0.0001696870313026011, 0.00017818956985138357, 0.109189473092556 ]
{ "id": 2, "code_window": [ " <meta name='generator' content={Astro.generator} />\n", " <title>{title}</title>\n", " <meta name='description' content={description} />\n", " <meta name='author' content='Kamran Ahmed' />\n", " <meta name='keywords' content={keywords.join(', ')} />\n", " <meta\n", " name='viewport'\n", " content='width=device-width, user-scalable=yes, initial-scale=1.0, maximum-scale=3.0, minimum-scale=1.0'\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " {noIndex && <meta name='robots' content='noindex' />}\n" ], "file_path": "src/layouts/BaseLayout.astro", "type": "add", "edit_start_line_idx": 34 }
# Unary Operators JavaScript Unary Operators are the special operators that consider a single operand and perform all the types of operations on that single operand. These operators include unary plus, unary minus, prefix increments, postfix increments, prefix decrements, and postfix decrements. Visit the following resources to learn more: - [Unary Operators in JavaScript](https://www.educba.com/unary-operators-in-javascript/) - [Unary Operators - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#unary_operators)
src/roadmaps/javascript/content/108-javascript-expressions-and-operators/109-unary-operators.md
0
https://github.com/kamranahmedse/developer-roadmap/commit/9dbb2d05c929d4927e0c79654d8dfb462412759b
[ 0.00016027476522140205, 0.00016027476522140205, 0.00016027476522140205, 0.00016027476522140205, 0 ]
{ "id": 2, "code_window": [ " <meta name='generator' content={Astro.generator} />\n", " <title>{title}</title>\n", " <meta name='description' content={description} />\n", " <meta name='author' content='Kamran Ahmed' />\n", " <meta name='keywords' content={keywords.join(', ')} />\n", " <meta\n", " name='viewport'\n", " content='width=device-width, user-scalable=yes, initial-scale=1.0, maximum-scale=3.0, minimum-scale=1.0'\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " {noIndex && <meta name='robots' content='noindex' />}\n" ], "file_path": "src/layouts/BaseLayout.astro", "type": "add", "edit_start_line_idx": 34 }
# Testing Testing smart contracts is one of the most important measures for improving smart contract security. Unlike traditional software, smart contracts cannot typically be updated after launching, making it imperative to test rigorously before deploying contracts onto mainnet. Visit the following resources to learn more: - [Testing Smart Contracts](https://ethereum.org/en/developers/docs/smart-contracts/testing/) - [How to Test Ethereum Smart Contracts](https://betterprogramming.pub/how-to-test-ethereum-smart-contracts-35abc8fa199d) - [Writing automated smart contract tests](https://docs.openzeppelin.com/learn/writing-automated-tests)
src/roadmaps/blockchain/content/103-smart-contracts/101-testing/index.md
0
https://github.com/kamranahmedse/developer-roadmap/commit/9dbb2d05c929d4927e0c79654d8dfb462412759b
[ 0.00016749264614190906, 0.00016749264614190906, 0.00016749264614190906, 0.00016749264614190906, 0 ]
{ "id": 2, "code_window": [ " <meta name='generator' content={Astro.generator} />\n", " <title>{title}</title>\n", " <meta name='description' content={description} />\n", " <meta name='author' content='Kamran Ahmed' />\n", " <meta name='keywords' content={keywords.join(', ')} />\n", " <meta\n", " name='viewport'\n", " content='width=device-width, user-scalable=yes, initial-scale=1.0, maximum-scale=3.0, minimum-scale=1.0'\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " {noIndex && <meta name='robots' content='noindex' />}\n" ], "file_path": "src/layouts/BaseLayout.astro", "type": "add", "edit_start_line_idx": 34 }
# Nightwatch Nightwatch.js is an open-source automated testing framework that is powered by Node.js and provides complete E2E (end to end) solutions to automation testing with Selenium Javascript be it for web apps, browser apps, and websites. Visit the following resources to learn more: - [Nightwatch.js Website](https://nightwatchjs.org/) - [NightwatchJS Tutorial: Get Started with Automation Testing](https://www.browserstack.com/guide/nightwatch-framework-tutorial)
src/roadmaps/qa/content/103-qa-automated-testing/100-frontend-automation/102-automation-frameworks/nightwatch.md
0
https://github.com/kamranahmedse/developer-roadmap/commit/9dbb2d05c929d4927e0c79654d8dfb462412759b
[ 0.0001709128700895235, 0.0001709128700895235, 0.0001709128700895235, 0.0001709128700895235, 0 ]
{ "id": 3, "code_window": [ "\n", "const { topicId } = Astro.params;\n", "const { file, breadcrumbs, roadmapId, roadmap, heading } = Astro.props as TopicFileType;\n", "---\n", "\n", "<BaseLayout title={`${heading} - roadmap.sh`} description={`Free resources to learn ${heading} in ${roadmap.featuredTitle}. Everything you need to know about ${heading} and how it realtes to ${roadmap.featuredTitle}.`}>\n", " <RoadmapBanner roadmapId={roadmapId} roadmap={roadmap} />\n", " <div class=\"bg-gray-50\">\n", " <Breadcrumbs breadcrumbs={breadcrumbs} roadmapId={roadmapId} />\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "<BaseLayout title={`${heading} - roadmap.sh`} description={`Free resources to learn ${heading} in ${roadmap.featuredTitle}. Everything you need to know about ${heading} and how it realtes to ${roadmap.featuredTitle}.`} noIndex={true}>\n" ], "file_path": "src/pages/[...topicId].astro", "type": "replace", "edit_start_line_idx": 20 }
--- import '../styles/global.css'; import Navigation from '../components/Navigation/Navigation.astro'; import OpenSourceBanner from '../components/OpenSourceBanner.astro'; import Footer from '../components/Footer.astro'; import type { SponsorType } from '../components/Sponsor/Sponsor.astro'; import Sponsor from '../components/Sponsor/Sponsor.astro'; import YouTubeBanner from '../components/YouTubeBanner.astro'; import { siteConfig } from '../lib/config'; export interface Props { title: string; description?: string; keywords?: string[]; sponsor?: SponsorType; } const { title = siteConfig.title, description = siteConfig.description, keywords = siteConfig.keywords, sponsor, } = Astro.props; --- <!DOCTYPE html> <html lang='en'> <head> <meta charset='UTF-8' /> <meta name='generator' content={Astro.generator} /> <title>{title}</title> <meta name='description' content={description} /> <meta name='author' content='Kamran Ahmed' /> <meta name='keywords' content={keywords.join(', ')} /> <meta name='viewport' content='width=device-width, user-scalable=yes, initial-scale=1.0, maximum-scale=3.0, minimum-scale=1.0' /> <meta http-equiv='Content-Language' content='en' /> <meta name='twitter:card' content='summary_large_image' /> <meta name='twitter:creator' content='@kamranahmedse' /> <meta property='og:image:width' content='1200' /> <meta property='og:image:height' content='630' /> <meta property='og:image' content='https://roadmap.sh/og-img.png' /> <meta property='og:image:alt' content='roadmap.sh' /> <meta property='og:site_name' content='roadmap.sh' /> <meta property='og:title' content={title} /> <meta property='og:description' content={description} /> <meta property='og:type' content='website' /> <meta property='og:url' content='https://roadmap.sh' /> <meta name='mobile-web-app-capable' content='yes' /> <meta name='apple-mobile-web-app-capable' content='yes' /> <meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' /> <meta name='apple-mobile-web-app-title' content='roadmap.sh' /> <meta name='application-name' content='roadmap.sh' /> <link rel='apple-touch-icon' sizes='180x180' href='/manifest/apple-touch-icon.png' /> <meta name='msapplication-TileColor' content='#101010' /> <meta name='theme-color' content='#848a9a' /> <link rel='manifest' href='/manifest/manifest.json' /> <link rel='icon' type='image/png' sizes='32x32' href='/manifest/icon32.png' /> <link rel='icon' type='image/png' sizes='16x16' href='/manifest/icon16.png' /> <link rel='shortcut icon' href='/manifest/favicon.ico' type='image/x-icon' /> <link rel='icon' href='/manifest/favicon.ico' type='image/x-icon' /> <slot name='after-header' /> </head> <body> <YouTubeBanner /> <Navigation /> <slot /> <OpenSourceBanner /> <Footer /> {sponsor && <Sponsor sponsor={sponsor} />} <slot name='after-footer' /> </body> </html>
src/layouts/BaseLayout.astro
1
https://github.com/kamranahmedse/developer-roadmap/commit/9dbb2d05c929d4927e0c79654d8dfb462412759b
[ 0.000633551215287298, 0.0002224212948931381, 0.0001642491843085736, 0.00017387789557687938, 0.00013158467481844127 ]
{ "id": 3, "code_window": [ "\n", "const { topicId } = Astro.params;\n", "const { file, breadcrumbs, roadmapId, roadmap, heading } = Astro.props as TopicFileType;\n", "---\n", "\n", "<BaseLayout title={`${heading} - roadmap.sh`} description={`Free resources to learn ${heading} in ${roadmap.featuredTitle}. Everything you need to know about ${heading} and how it realtes to ${roadmap.featuredTitle}.`}>\n", " <RoadmapBanner roadmapId={roadmapId} roadmap={roadmap} />\n", " <div class=\"bg-gray-50\">\n", " <Breadcrumbs breadcrumbs={breadcrumbs} roadmapId={roadmapId} />\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "<BaseLayout title={`${heading} - roadmap.sh`} description={`Free resources to learn ${heading} in ${roadmap.featuredTitle}. Everything you need to know about ${heading} and how it realtes to ${roadmap.featuredTitle}.`} noIndex={true}>\n" ], "file_path": "src/pages/[...topicId].astro", "type": "replace", "edit_start_line_idx": 20 }
# Design and development principles
src/roadmaps/backend/content/114-design-and-development-principles/index.md
0
https://github.com/kamranahmedse/developer-roadmap/commit/9dbb2d05c929d4927e0c79654d8dfb462412759b
[ 0.00016469316324219108, 0.00016469316324219108, 0.00016469316324219108, 0.00016469316324219108, 0 ]
{ "id": 3, "code_window": [ "\n", "const { topicId } = Astro.params;\n", "const { file, breadcrumbs, roadmapId, roadmap, heading } = Astro.props as TopicFileType;\n", "---\n", "\n", "<BaseLayout title={`${heading} - roadmap.sh`} description={`Free resources to learn ${heading} in ${roadmap.featuredTitle}. Everything you need to know about ${heading} and how it realtes to ${roadmap.featuredTitle}.`}>\n", " <RoadmapBanner roadmapId={roadmapId} roadmap={roadmap} />\n", " <div class=\"bg-gray-50\">\n", " <Breadcrumbs breadcrumbs={breadcrumbs} roadmapId={roadmapId} />\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "<BaseLayout title={`${heading} - roadmap.sh`} description={`Free resources to learn ${heading} in ${roadmap.featuredTitle}. Everything you need to know about ${heading} and how it realtes to ${roadmap.featuredTitle}.`} noIndex={true}>\n" ], "file_path": "src/pages/[...topicId].astro", "type": "replace", "edit_start_line_idx": 20 }
# Images Apps can include both code and assets. Flutter uses the pubspec.yaml file, located at the root of your project, to identify assets required by an app. Visit the following resources to learn more: - [Adding assets and images](https://docs.flutter.dev/development/ui/assets-and-images)
src/roadmaps/flutter/content/103-working-with-assets/101-images.md
0
https://github.com/kamranahmedse/developer-roadmap/commit/9dbb2d05c929d4927e0c79654d8dfb462412759b
[ 0.00016645743744447827, 0.00016645743744447827, 0.00016645743744447827, 0.00016645743744447827, 0 ]
{ "id": 3, "code_window": [ "\n", "const { topicId } = Astro.params;\n", "const { file, breadcrumbs, roadmapId, roadmap, heading } = Astro.props as TopicFileType;\n", "---\n", "\n", "<BaseLayout title={`${heading} - roadmap.sh`} description={`Free resources to learn ${heading} in ${roadmap.featuredTitle}. Everything you need to know about ${heading} and how it realtes to ${roadmap.featuredTitle}.`}>\n", " <RoadmapBanner roadmapId={roadmapId} roadmap={roadmap} />\n", " <div class=\"bg-gray-50\">\n", " <Breadcrumbs breadcrumbs={breadcrumbs} roadmapId={roadmapId} />\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "<BaseLayout title={`${heading} - roadmap.sh`} description={`Free resources to learn ${heading} in ${roadmap.featuredTitle}. Everything you need to know about ${heading} and how it realtes to ${roadmap.featuredTitle}.`} noIndex={true}>\n" ], "file_path": "src/pages/[...topicId].astro", "type": "replace", "edit_start_line_idx": 20 }
# Vuelidate Simple, lightweight model-based validation for Vue.js. Visit the following resources to learn more: - [Official Website: Vuelidate](https://vuelidate.js.org/) - [vuelidate/vuelidate](https://github.com/vuelidate/vuelidate)
src/roadmaps/vue/content/102-ecosystem/101-forms/102-vuelidate.md
0
https://github.com/kamranahmedse/developer-roadmap/commit/9dbb2d05c929d4927e0c79654d8dfb462412759b
[ 0.00017318293976131827, 0.00017318293976131827, 0.00017318293976131827, 0.00017318293976131827, 0 ]
{ "id": 4, "code_window": [ "<BaseLayout\n", " title={roadmapData?.seo?.title}\n", " description={roadmapData.seo.description}\n", " keywords={roadmapData.seo.keywords}\n", " sponsor={roadmapData.sponsor}\n", ">\n", " <RoadmapHeader\n", " description={roadmapData.description}\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " noIndex={roadmapData.isUpcoming}\n" ], "file_path": "src/pages/[roadmapId]/index.astro", "type": "add", "edit_start_line_idx": 29 }
--- import '../styles/global.css'; import Navigation from '../components/Navigation/Navigation.astro'; import OpenSourceBanner from '../components/OpenSourceBanner.astro'; import Footer from '../components/Footer.astro'; import type { SponsorType } from '../components/Sponsor/Sponsor.astro'; import Sponsor from '../components/Sponsor/Sponsor.astro'; import YouTubeBanner from '../components/YouTubeBanner.astro'; import { siteConfig } from '../lib/config'; export interface Props { title: string; description?: string; keywords?: string[]; sponsor?: SponsorType; } const { title = siteConfig.title, description = siteConfig.description, keywords = siteConfig.keywords, sponsor, } = Astro.props; --- <!DOCTYPE html> <html lang='en'> <head> <meta charset='UTF-8' /> <meta name='generator' content={Astro.generator} /> <title>{title}</title> <meta name='description' content={description} /> <meta name='author' content='Kamran Ahmed' /> <meta name='keywords' content={keywords.join(', ')} /> <meta name='viewport' content='width=device-width, user-scalable=yes, initial-scale=1.0, maximum-scale=3.0, minimum-scale=1.0' /> <meta http-equiv='Content-Language' content='en' /> <meta name='twitter:card' content='summary_large_image' /> <meta name='twitter:creator' content='@kamranahmedse' /> <meta property='og:image:width' content='1200' /> <meta property='og:image:height' content='630' /> <meta property='og:image' content='https://roadmap.sh/og-img.png' /> <meta property='og:image:alt' content='roadmap.sh' /> <meta property='og:site_name' content='roadmap.sh' /> <meta property='og:title' content={title} /> <meta property='og:description' content={description} /> <meta property='og:type' content='website' /> <meta property='og:url' content='https://roadmap.sh' /> <meta name='mobile-web-app-capable' content='yes' /> <meta name='apple-mobile-web-app-capable' content='yes' /> <meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' /> <meta name='apple-mobile-web-app-title' content='roadmap.sh' /> <meta name='application-name' content='roadmap.sh' /> <link rel='apple-touch-icon' sizes='180x180' href='/manifest/apple-touch-icon.png' /> <meta name='msapplication-TileColor' content='#101010' /> <meta name='theme-color' content='#848a9a' /> <link rel='manifest' href='/manifest/manifest.json' /> <link rel='icon' type='image/png' sizes='32x32' href='/manifest/icon32.png' /> <link rel='icon' type='image/png' sizes='16x16' href='/manifest/icon16.png' /> <link rel='shortcut icon' href='/manifest/favicon.ico' type='image/x-icon' /> <link rel='icon' href='/manifest/favicon.ico' type='image/x-icon' /> <slot name='after-header' /> </head> <body> <YouTubeBanner /> <Navigation /> <slot /> <OpenSourceBanner /> <Footer /> {sponsor && <Sponsor sponsor={sponsor} />} <slot name='after-footer' /> </body> </html>
src/layouts/BaseLayout.astro
1
https://github.com/kamranahmedse/developer-roadmap/commit/9dbb2d05c929d4927e0c79654d8dfb462412759b
[ 0.0017936143558472395, 0.0003425238246563822, 0.00016238377429544926, 0.00017185218166559935, 0.00046533255954273045 ]
{ "id": 4, "code_window": [ "<BaseLayout\n", " title={roadmapData?.seo?.title}\n", " description={roadmapData.seo.description}\n", " keywords={roadmapData.seo.keywords}\n", " sponsor={roadmapData.sponsor}\n", ">\n", " <RoadmapHeader\n", " description={roadmapData.description}\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " noIndex={roadmapData.isUpcoming}\n" ], "file_path": "src/pages/[roadmapId]/index.astro", "type": "add", "edit_start_line_idx": 29 }
--- title: "HTTP Caching" description: "Everything you need to know about web caching" author: name: "Kamran Ahmed" url: "https://twitter.com/kamranahmedse" imageUrl: "/authors/kamranahmedse.jpeg" seo: title: "HTTP Caching - roadmap.sh" description: "Everything you need to know about web caching" isNew: false type: "textual" date: 2018-11-29 sitemap: priority: 0.7 changefreq: "weekly" tags: - "guide" - "textual-guide" - "guide-sitemap" --- As users, we easily get frustrated by the buffering of videos, the images that take seconds to load, and pages that got stuck because the content is being loaded. Loading the resources from some cache is much faster than fetching the same from the originating server. It reduces latency, speeds up the loading of resources, decreases the load on the server, cuts down the bandwidth costs etc. ### Introduction What is a web cache? It is something that sits somewhere between the client and the server, continuously looking at the requests and their responses, looking for any responses that can be cached. So that there is less time consumed when the same request is made again. ![Web Cache](https://i.imgur.com/mJYVvTh.png) > Note that this image is just to give you an idea. Depending upon the type of cache, the place where it is implemented could vary. More on this later. Before we get into further details, let me give you an overview of the terms that will be used, further in the article - **Client** could be your browser or any application requesting the server for some resource - **Origin Server**, the source of truth, houses all the content required by the client and is responsible for fulfilling the client's requests. - **Stale Content** is cached but expired content - **Fresh Content** is the content available in the cache that hasn't expired yet - **Cache Validation** is the process of contacting the server to check the validity of the cached content and get it updated for when it is going to expire - **Cache Invalidation** is the process of removing any stale content available in the cache ![](https://i.imgur.com/9MjlzvW.png) ### Caching Locations Web cache can be shared or private depending upon the location where it exists. Here is the list of different caching locations - [Browser Cache](#browser-cache) - [Proxy Cache](#proxy-cache) - [Reverse Proxy Cache](#reverse-proxy-cache) #### Browser Cache You might have noticed that when you click the back button in your browser it takes less time to load the page than the time that it took during the first load; this is the browser cache in play. Browser cache is the most common location for caching and browsers usually reserve some space for it. ![Web Cache](https://i.imgur.com/mJYVvTh.png) A browser cache is limited to just one user and unlike other caches, it can store the "private" responses. More on it later. #### Proxy Cache Unlike browser cache which serves a single user, proxy caches may serve hundreds of different users accessing the same content. They are usually implemented on a broader level by ISPs or any other independent entities for example. ![Proxy Cache](https://i.imgur.com/3mj6e1O.png) #### Reverse Proxy Cache A Reverse proxy cache or surrogate cache is implemented close to the origin servers in order to reduce the load on the server. Unlike proxy caches which are implemented by ISPs etc to reduce the bandwidth usage in a network, surrogates or reverse proxy caches are implemented near the origin servers by the server administrators to reduce the load on the server. ![Reverse Proxy Cache](http://i.imgur.com/Eg4Cru3.png) Although you can control the reverse proxy caches (since it is implemented by you on your server) you can not avoid or control browser and proxy caches. And if your website is not configured to use these caches properly, it will still be cached using whatever defaults are set on these caches. ### Caching Headers So, how do we control the web cache? Whenever the server emits some response, it is accompanied by some HTTP headers to guide the caches on whether and how to cache this response. The content provider is the one that has to make sure to return proper HTTP headers to force the caches on how to cache the content. - [Expires](#expires) - [Pragma](#pragma) - [Cache-Control](#cache-control) - [private](#private) - [public](#public) - [no-store](#no-store) - [no-cache](#no-cache) - [max-age: seconds](#max-age) - [s-maxage: seconds](#s-maxage) - [must-revalidate](#must-revalidate) - [proxy-revalidate](#proxy-revalidate) - [Mixing Values](#mixing-values) - [Validators](#validators) - [ETag](#etag) - [Last-Modified](#last-modified) #### Expires Before HTTP/1.1 and the introduction of `Cache-Control`, there was an `Expires` header which is simply a timestamp telling the caches how long should some content be considered fresh. A possible value to this header is the absolute expiry date; where a date has to be in GMT. Below is the sample header ```html Expires: Mon, 13 Mar 2017 12:22:00 GMT ``` It should be noted that the date cannot be more than a year and if the date format is wrong, the content will be considered stale. Also, the clock on the cache has to be in sync with the clock on the server, otherwise, the desired results might not be achieved. Although the `Expires` header is still valid and is supported widely by the caches, preference should be given to HTTP/1.1 successor of it i.e. `Cache-Control`. #### Pragma Another one from the old, pre HTTP/1.1 days, is `Pragma`. Everything that it could do is now possible using the cache-control header given below. However, one thing I would like to point out about it is, that you might see `Pragma: no-cache` being used here and there in hopes of stopping the response from being cached. It might not necessarily work; as HTTP specification discusses it in the request headers and there is no mention of it in the response headers. Rather `Cache-Control` header should be used to control the caching. #### Cache-Control Cache-Control specifies how long and in what manner should the content be cached. This family of headers was introduced in HTTP/1.1 to overcome the limitations of the `Expires` header. Value for the `Cache-Control` header is composite i.e. it can have multiple directive/values. Let's look at the possible values that this header may contain. ##### private Setting the cache to `private` means that the content will not be cached in any of the proxies and it will only be cached by the client (i.e. browser) ```html Cache-Control: private ``` Having said that, don't let it fool you into thinking that setting this header will make your data any secure; you still have to use SSL for that purpose. ##### public If set to `public`, apart from being cached by the client, it can also be cached by the proxies; serving many other users ```html Cache-Control: public ``` ##### no-store **`no-store`** specifies that the content is not to be cached by any of the caches ```html Cache-Control: no-store ``` ##### no-cache **`no-cache`** indicates that the cache can be maintained but the cached content is to be re-validated (using `ETag` for example) from the server before being served. That is, there is still a request to server but for validation and not to download the cached content. ```html Cache-Control: max-age=3600, no-cache, public ``` ##### max-age: seconds **`max-age`** specifies the number of seconds for which the content will be cached. For example, if the `cache-control` looks like below: ```html Cache-Control: max-age=3600, public ``` it would mean that the content is publicly cacheable and will be considered stale after 60 minutes ##### s-maxage: seconds **`s-maxage`** here `s-` prefix stands for shared. This directive specifically targets the shared caches. Like `max-age` it also gets the number of seconds for which something is to be cached. If present, it will override `max-age` and `expires` headers for shared caching. ```html Cache-Control: s-maxage=3600, public ``` ##### must-revalidate **`must-revalidate`** it might happen sometimes that if you have network problems and the content cannot be retrieved from the server, the browser may serve stale content without validation. `must-revalidate` avoids that. If this directive is present, it means that stale content cannot be served in any case and the data must be re-validated from the server before serving. ```html Cache-Control: max-age=3600, public, must-revalidate ``` ##### proxy-revalidate **`proxy-revalidate`** is similar to `must-revalidate` but it specifies the same for shared or proxy caches. In other words `proxy-revalidate` is to `must-revalidate` as `s-maxage` is to `max-age`. But why did they not call it `s-revalidate`?. I have no idea why, if you have any clue please leave a comment below. ##### Mixing Values You can combine these directives in different ways to achieve different caching behaviors, however `no-cache/no-store` and `public/private` are mutually exclusive. If you specify both `no-store` and `no-cache`, `no-store` will be given precedence over `no-cache`. ```html ; If specified both Cache-Control: no-store, no-cache ; Below will be considered Cache-Control: no-store ``` For `private/public`, for any unauthenticated requests cache is considered `public` and for any authenticated ones cache is considered `private`. ### Validators Up until now we only discussed how the content is cached and how long the cached content is to be considered fresh but we did not discuss how the client does the validation from the server. Below we discuss the headers used for this purpose. #### ETag Etag or "entity tag" was introduced in HTTP/1.1 specs. Etag is just a unique identifier that the server attaches with some resource. This ETag is later on used by the client to make conditional HTTP requests stating `"give me this resource if ETag is not same as the ETag that I have"` and the content is downloaded only if the etags do not match. Method by which ETag is generated is not specified in the HTTP docs and usually some collision-resistant hash function is used to assign etags to each version of a resource. There could be two types of etags i.e. strong and weak ```html ETag: "j82j8232ha7sdh0q2882" - Strong Etag ETag: W/"j82j8232ha7sdh0q2882" - Weak Etag (prefixed with `W/`) ``` A strong validating ETag means that two resources are **exactly** same and there is no difference between them at all. While a weak ETag means that two resources although not strictly the same but could be considered the same. Weak etags might be useful for dynamic content, for example. Now you know what etags are but how does the browser make this request? by making a request to server while sending the available Etag in `If-None-Match` header. Consider the scenario, you opened a web page which loaded a logo image with caching period of 60 seconds and ETag of `abc123xyz`. After about 30 minutes you reload the page, browser will notice that the logo which was fresh for 60 seconds is now stale; it will trigger a request to server, sending the ETag of the stale logo image in `if-none-match` header ```html If-None-Match: "abc123xyz" ``` Server will then compare this ETag with the ETag of the current version of resource. If both etags are matched, server will send back the response of `304 Not Modified` which will tell the client that the copy that it has is still good and it will be considered fresh for another 60 seconds. If both the etags do not match i.e. the logo has likely changed and client will be sent the new logo which it will use to replace the stale logo that it has. #### Last-Modified Server might include the `Last-Modified` header indicating the date and time at which some content was last modified on. ```html Last-Modified: Wed, 15 Mar 2017 12:30:26 GMT ``` When the content gets stale, client will make a conditional request including the last modified date that it has inside the header called `If-Modified-Since` to server to get the updated `Last-Modified` date; if it matches the date that the client has, `Last-Modified` date for the content is updated to be considered fresh for another `n` seconds. If the received `Last-Modified` date does not match the one that the client has, content is reloaded from the server and replaced with the content that client has. ```html If-Modified-Since: Wed, 15 Mar 2017 12:30:26 GMT ``` You might be questioning now, what if the cached content has both the `Last-Modified` and `ETag` assigned to it? Well, in that case both are to be used i.e. there will not be any re-downloading of the resource if and only if `ETag` matches the newly retrieved one and so does the `Last-Modified` date. If either the `ETag` does not match or the `Last-Modified` is greater than the one from the server, content has to be downloaded again. ### Where do I start? Now that we have got *everything* covered, let us put everything in perspective and see how you can use this information. #### Utilizing Server Before we get into the possible caching strategies , let me add the fact that most of the servers including Apache and Nginx allow you to implement your caching policy through the server so that you don't have to juggle with headers in your code. **For example**, if you are using Apache and you have your static content placed at `/static`, you can put below `.htaccess` file in the directory to make all the content in it be cached for an year using below ```html # Cache everything for an year Header set Cache-Control "max-age=31536000, public" ``` You can further use `filesMatch` directive to add conditionals and use different caching strategy for different kinds of files e.g. ```html # Cache any images for one year <filesMatch ".(png|jpg|jpeg|gif)$"> Header set Cache-Control "max-age=31536000, public" </filesMatch> # Cache any CSS and JS files for a month <filesMatch ".(css|js)$"> Header set Cache-Control "max-age=2628000, public" </filesMatch> ``` Or if you don't want to use the `.htaccess` file you can modify Apache's configuration file `http.conf`. Same goes for Nginx, you can add the caching information in the location or server block. #### Caching Recommendations There is no golden rule or set standards about how your caching policy should look like, each of the application is different and you have to look and find what suits your application the best. However, just to give you a rough idea - You can have aggressive caching (e.g. cache for an year) on any static content and use fingerprinted filenames (e.g. `style.ju2i90.css`) so that the cache is automatically rejected whenever the files are updated. Also it should be noted that you should not cross the upper limit of one year as it [might not be honored](https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9) - Look and decide do you even need caching for any dynamic content, if yes how long it should be. For example, in case of some RSS feed of a blog there could be the caching of a few hours but there couldn't be any caching for inventory items in an ERP. - Always add the validators (preferably ETags) in your response. - Pay attention while choosing the visibility (private or public) of the cached content. Make sure that you do not accidentally cache any user-specific or sensitive content in any public proxies. When in doubt, do not use cache at all. - Separate the content that changes often from the content that doesn't change that often (e.g. in javascript bundles) so that when it is updated it doesn't need to make the whole cached content stale. - Test and monitor the caching headers being served by your site. You can use the browser console or `curl -I http://some-url.com` for that purpose. And that about wraps it up. Stay tuned for more!
src/guides/http-caching.md
0
https://github.com/kamranahmedse/developer-roadmap/commit/9dbb2d05c929d4927e0c79654d8dfb462412759b
[ 0.00022610535961575806, 0.00017155958630610257, 0.00016118789790198207, 0.00016821658937260509, 0.000012143437743361574 ]
{ "id": 4, "code_window": [ "<BaseLayout\n", " title={roadmapData?.seo?.title}\n", " description={roadmapData.seo.description}\n", " keywords={roadmapData.seo.keywords}\n", " sponsor={roadmapData.sponsor}\n", ">\n", " <RoadmapHeader\n", " description={roadmapData.description}\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " noIndex={roadmapData.isUpcoming}\n" ], "file_path": "src/pages/[roadmapId]/index.astro", "type": "add", "edit_start_line_idx": 29 }
# Service Mesh A service mesh, like the open source project Istio, is a way to control how different parts of an application share data with one another. Unlike other systems for managing this communication, a service mesh is a dedicated infrastructure layer built right into an app. This visible infrastructure layer can document how well (or not) different parts of an app interact, so it becomes easier to optimize communication and avoid downtime as an app grows. Visit the following resources to learn more: - [Whats a service mesh?](https://www.redhat.com/en/topics/microservices/what-is-a-service-mesh) - [The latest news about service mesh (TNS)](https://thenewstack.io/category/service-mesh/)
src/roadmaps/devops/content/105-infrastructure-as-code/100-service-mesh/index.md
0
https://github.com/kamranahmedse/developer-roadmap/commit/9dbb2d05c929d4927e0c79654d8dfb462412759b
[ 0.00016957720799837261, 0.00016957720799837261, 0.00016957720799837261, 0.00016957720799837261, 0 ]
{ "id": 4, "code_window": [ "<BaseLayout\n", " title={roadmapData?.seo?.title}\n", " description={roadmapData.seo.description}\n", " keywords={roadmapData.seo.keywords}\n", " sponsor={roadmapData.sponsor}\n", ">\n", " <RoadmapHeader\n", " description={roadmapData.description}\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " noIndex={roadmapData.isUpcoming}\n" ], "file_path": "src/pages/[roadmapId]/index.astro", "type": "add", "edit_start_line_idx": 29 }
# Quasar Quasar Framework is an open-source Vue.js based framework for building apps, with a single codebase, and deploy it on the Web as a SPA, PWA, SSR, to a Mobile App, using Cordova for iOS & Android, and to a Desktop App, using Electron for Mac, Windows, and Linux. Visit the following resources to learn more: - [Official Website: Quasar](https://quasar.dev/) - [Quasar Framework: Vue.js Cross Platform App](https://www.youtube.com/watch?v=opmng7llVJ0&list=PLAiDzIdBfy8iu_MZrq3IPuSFcRgCQ0iL0) - [How to Build an App using Quasar Framework](https://www.youtube.com/watch?v=czJIuHyPPXo)
src/roadmaps/vue/content/102-ecosystem/102-ssr/100-quasar.md
0
https://github.com/kamranahmedse/developer-roadmap/commit/9dbb2d05c929d4927e0c79654d8dfb462412759b
[ 0.00017526930605527014, 0.00017149900668300688, 0.0001677286927588284, 0.00017149900668300688, 0.000003770306648220867 ]
{ "id": 0, "code_window": [ "* The app root with the navigation links.\n", "* The list of heroes.\n", "* The hero editor.\n", "\n", "You define a component's application logic&mdash;what it does to support the view&mdash;inside a class. The class interacts with the view through an API of properties and methods.\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "You define a component's application logic&mdash;what it does to support the view&mdash;inside a class.\n", "The class interacts with the view through an API of properties and methods.\n" ], "file_path": "aio/content/guide/architecture-components.md", "type": "replace", "edit_start_line_idx": 10 }
# Introduction to modules <img src="generated/images/guide/architecture/module.png" alt="Module" class="left"> Angular apps are modular and Angular has its own modularity system called _NgModules_. An NgModule is a container for a cohesive block of code dedicated to an application domain, a workflow, or a closely related set of capabilities. It can contain components, service providers, and other code files whose scope is defined by the containing NgModule. It can import functionality that is exported from other NgModules, and export selected functionality for use by other NgModules. Every Angular app has at least one NgModule class, [the _root module_](guide/bootstrapping), which is conventionally named `AppModule` and resides in a file named `app.module.ts`. You launch your app by *bootstrapping* the root NgModule. While a small application might have only one NgModule, most apps have many more _feature modules_. The _root_ NgModule for an app is so named because it can include child NgModules in a hierarchy of any depth. ## NgModule metadata An NgModule is defined as a class decorated with `@NgModule`. The `@NgModule` decorator is a function that takes a single metadata object, whose properties describe the module. The most important properties are as follows. * `declarations`&mdash;The [components](guide/architecture-components), _directives_, and _pipes_ that belong to this NgModule. * `exports`&mdash;The subset of declarations that should be visible and usable in the _component templates_ of other NgModules. * `imports`&mdash;Other modules whose exported classes are needed by component templates declared in _this_ NgModule. * `providers`&mdash;Creators of [services](guide/architecture-services) that this NgModule contributes to the global collection of services; they become accessible in all parts of the app. (You can also specify providers at the component level, which is often preferred.) * `bootstrap`&mdash;The main application view, called the _root component_, which hosts all other app views. Only the _root NgModule_ should set this `bootstrap` property. Here's a simple root NgModule definition: <code-example path="architecture/src/app/mini-app.ts" region="module" title="src/app/app.module.ts" linenums="false"></code-example> <div class="l-sub-section"> The `export` of `AppComponent` is just to show how to export; it isn't actually necessary in this example. A root NgModule has no reason to _export_ anything because other modules don't need to _import_ the root NgModule. </div> ## NgModules and components NgModules provide a _compilation context_ for their components. A root NgModule always has a root component that is created during bootstrap, but any NgModule can include any number of additional components, which can be loaded through the router or created through the template. The components that belong to an NgModule share a compilation context. <figure> <img src="generated/images/guide/architecture/compilation-context.png" alt="Component compilation context" class="left"> </figure> <br class="clear"> A component and its template together define a _view_. A component can contain a _view hierarchy_, which allows you to define arbitrarily complex areas of the screen that can be created, modified, and destroyed as a unit. A view hierarchy can mix views defined in components that belong to different NgModules. This is often the case, especially for UI libraries. <figure> <img src="generated/images/guide/architecture/view-hierarchy.png" alt="View hierarchy" class="left"> </figure> <br class="clear"> When you create a component, it is associated directly with a single view, called the _host view_. The host view can be the root of a view hierarchy, which can contain _embedded views_, which are in turn the host views of other components. Those components can be in the same NgModule, or can be imported from other NgModules. Views in the tree can be nested to any depth. <div class="l-sub-section"> The hierarchical structure of views is a key factor in the way Angular detects and responds to changes in the DOM and app data. </div> ## NgModules and JavaScript modules The NgModule system is different from and unrelated to the JavaScript (ES2015) module system for managing collections of JavaScript objects. These are two different and _complementary_ module systems. You can use them both to write your apps. In JavaScript each _file_ is a module and all objects defined in the file belong to that module. The module declares some objects to be public by marking them with the `export` key word. Other JavaScript modules use *import statements* to access public objects from other modules. <code-example path="architecture/src/app/app.module.ts" region="imports" linenums="false"></code-example> <code-example path="architecture/src/app/app.module.ts" region="export" linenums="false"></code-example> <div class="l-sub-section"> <a href="http://exploringjs.com/es6/ch_modules.html">Learn more about the JavaScript module system on the web.</a> </div> ## Angular libraries <img src="generated/images/guide/architecture/library-module.png" alt="Component" class="left"> Angular ships as a collection of JavaScript modules. You can think of them as library modules. Each Angular library name begins with the `@angular` prefix. Install them with the `npm` package manager and import parts of them with JavaScript `import` statements. <br class="clear"> For example, import Angular's `Component` decorator from the `@angular/core` library like this: <code-example path="architecture/src/app/app.component.ts" region="import" linenums="false"></code-example> You also import NgModules from Angular _libraries_ using JavaScript import statements: <code-example path="architecture/src/app/mini-app.ts" region="import-browser-module" linenums="false"></code-example> In the example of the simple root module above, the application module needs material from within the `BrowserModule`. To access that material, add it to the `@NgModule` metadata `imports` like this. <code-example path="architecture/src/app/mini-app.ts" region="ngmodule-imports" linenums="false"></code-example> In this way you're using both the Angular and JavaScript module systems _together_. Although it's easy to confuse the two systems, which share the common vocabulary of "imports" and "exports", you will become familiar with the different contexts in which they are used. <div class="l-sub-section"> Learn more from the [NgModules](guide/ngmodules) page. </div> <hr/>
aio/content/guide/architecture-modules.md
1
https://github.com/angular/angular/commit/e1146f3d066e653b9b40799cc436034e44af9160
[ 0.00023448478896170855, 0.00017966162704396993, 0.00016330875223502517, 0.00016662353300489485, 0.000023511105609941296 ]
{ "id": 0, "code_window": [ "* The app root with the navigation links.\n", "* The list of heroes.\n", "* The hero editor.\n", "\n", "You define a component's application logic&mdash;what it does to support the view&mdash;inside a class. The class interacts with the view through an API of properties and methods.\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "You define a component's application logic&mdash;what it does to support the view&mdash;inside a class.\n", "The class interacts with the view through an API of properties and methods.\n" ], "file_path": "aio/content/guide/architecture-components.md", "type": "replace", "edit_start_line_idx": 10 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // This file is not used to build this module. It is only used during editing // by the TypeScript language service and during build for verification. `ngc` // replaces this file with production index.ts when it rewrites private symbol // names. export * from './public_api';
packages/core/testing/index.ts
0
https://github.com/angular/angular/commit/e1146f3d066e653b9b40799cc436034e44af9160
[ 0.00016823597252368927, 0.00016750278882682323, 0.00016676961968187243, 0.00016750278882682323, 7.331764209084213e-7 ]
{ "id": 0, "code_window": [ "* The app root with the navigation links.\n", "* The list of heroes.\n", "* The hero editor.\n", "\n", "You define a component's application logic&mdash;what it does to support the view&mdash;inside a class. The class interacts with the view through an API of properties and methods.\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "You define a component's application logic&mdash;what it does to support the view&mdash;inside a class.\n", "The class interacts with the view through an API of properties and methods.\n" ], "file_path": "aio/content/guide/architecture-components.md", "type": "replace", "edit_start_line_idx": 10 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {animate, style, transition, trigger} from '@angular/animations'; import {ɵAnimationEngine} from '@angular/animations/browser'; import {Component} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {NoopAnimationsModule} from '../src/module'; { describe('NoopAnimationsModule', () => { beforeEach(() => { TestBed.configureTestingModule({imports: [NoopAnimationsModule]}); }); it('should flush and fire callbacks when the zone becomes stable', (async) => { @Component({ selector: 'my-cmp', template: '<div [@myAnimation]="exp" (@myAnimation.start)="onStart($event)" (@myAnimation.done)="onDone($event)"></div>', animations: [trigger( 'myAnimation', [transition( '* => state', [style({'opacity': '0'}), animate(500, style({'opacity': '1'}))])])], }) class Cmp { exp: any; startEvent: any; doneEvent: any; onStart(event: any) { this.startEvent = event; } onDone(event: any) { this.doneEvent = event; } } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = 'state'; fixture.detectChanges(); fixture.whenStable().then(() => { expect(cmp.startEvent.triggerName).toEqual('myAnimation'); expect(cmp.startEvent.phaseName).toEqual('start'); expect(cmp.doneEvent.triggerName).toEqual('myAnimation'); expect(cmp.doneEvent.phaseName).toEqual('done'); async(); }); }); it('should handle leave animation callbacks even if the element is destroyed in the process', (async) => { @Component({ selector: 'my-cmp', template: '<div *ngIf="exp" @myAnimation (@myAnimation.start)="onStart($event)" (@myAnimation.done)="onDone($event)"></div>', animations: [trigger( 'myAnimation', [transition( ':leave', [style({'opacity': '0'}), animate(500, style({'opacity': '1'}))])])], }) class Cmp { exp: any; startEvent: any; doneEvent: any; onStart(event: any) { this.startEvent = event; } onDone(event: any) { this.doneEvent = event; } } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.get(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = true; fixture.detectChanges(); fixture.whenStable().then(() => { cmp.startEvent = null; cmp.doneEvent = null; cmp.exp = false; fixture.detectChanges(); fixture.whenStable().then(() => { expect(cmp.startEvent.triggerName).toEqual('myAnimation'); expect(cmp.startEvent.phaseName).toEqual('start'); expect(cmp.startEvent.toState).toEqual('void'); expect(cmp.doneEvent.triggerName).toEqual('myAnimation'); expect(cmp.doneEvent.phaseName).toEqual('done'); expect(cmp.doneEvent.toState).toEqual('void'); async(); }); }); }); }); }
packages/platform-browser/animations/test/noop_animations_module_spec.ts
0
https://github.com/angular/angular/commit/e1146f3d066e653b9b40799cc436034e44af9160
[ 0.00017232540994882584, 0.00016849454550538212, 0.00016566966951359063, 0.00016798860451672226, 0.0000021981159079587087 ]
{ "id": 0, "code_window": [ "* The app root with the navigation links.\n", "* The list of heroes.\n", "* The hero editor.\n", "\n", "You define a component's application logic&mdash;what it does to support the view&mdash;inside a class. The class interacts with the view through an API of properties and methods.\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "You define a component's application logic&mdash;what it does to support the view&mdash;inside a class.\n", "The class interacts with the view through an API of properties and methods.\n" ], "file_path": "aio/content/guide/architecture-components.md", "type": "replace", "edit_start_line_idx": 10 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; export default [];
packages/common/locales/extra/fo.ts
0
https://github.com/angular/angular/commit/e1146f3d066e653b9b40799cc436034e44af9160
[ 0.00017031938477884978, 0.00016890265396796167, 0.00016748592315707356, 0.00016890265396796167, 0.0000014167308108881116 ]
{ "id": 1, "code_window": [ "\n", "For example, the `HeroListComponent` has a `heroes` property that returns an array of heroes that it acquires from a service. `HeroListComponent` also has a `selectHero()` method that sets a `selectedHero` property when the user clicks to choose a hero from that list.\n", "\n", "<code-example path=\"architecture/src/app/hero-list.component.ts\" linenums=\"false\" title=\"src/app/hero-list.component.ts (class)\" region=\"class\"></code-example>\n", "\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "For example, the `HeroListComponent` has a `heroes` property that holds an array of heroes. It also has a `selectHero()` method that sets a `selectedHero` property when the user clicks to choose a hero from that list. The component acquires the heroes from a service, which is a TypeScript [parameter property[(http://www.typescriptlang.org/docs/handbook/classes.html#parameter-properties) on the constructor. The service is provided to the component through the dependency injection system.\n" ], "file_path": "aio/content/guide/architecture-components.md", "type": "replace", "edit_start_line_idx": 12 }
# Introduction to components <img src="generated/images/guide/architecture/hero-component.png" alt="Component" class="left"> A _component_ controls a patch of screen called a *view*. For example, individual components define and control each of the following views from the [Tutorial](tutorial/index): * The app root with the navigation links. * The list of heroes. * The hero editor. You define a component's application logic&mdash;what it does to support the view&mdash;inside a class. The class interacts with the view through an API of properties and methods. For example, the `HeroListComponent` has a `heroes` property that returns an array of heroes that it acquires from a service. `HeroListComponent` also has a `selectHero()` method that sets a `selectedHero` property when the user clicks to choose a hero from that list. <code-example path="architecture/src/app/hero-list.component.ts" linenums="false" title="src/app/hero-list.component.ts (class)" region="class"></code-example> Angular creates, updates, and destroys components as the user moves through the application. Your app can take action at each moment in this lifecycle through optional [lifecycle hooks](guide/lifecycle-hooks), like `ngOnInit()`. <hr/> ## Component metadata <img src="generated/images/guide/architecture/metadata.png" alt="Metadata" class="left"> The `@Component` decorator identifies the class immediately below it as a component class, and specifies its metadata. In the example code below, you can see that `HeroListComponent` is just a class, with no special Angular notation or syntax at all. It's not a component until you mark it as one with the `@Component` decorator. The metadata for a component tells Angular where to get the major building blocks it needs to create and present the component and its view. In particular, it associates a _template_ with the component, either directly with inline code, or by reference. Together, the component and its template describe a _view_. In addition to containing or pointing to the template, the `@Component` metadata configures, for example, how the component can be referenced in HTML and what services it requires. Here's an example of basic metadata for `HeroListComponent`: <code-example path="architecture/src/app/hero-list.component.ts" linenums="false" title="src/app/hero-list.component.ts (metadata)" region="metadata"></code-example> This example shows some of the most useful `@Component` configuration options: * `selector`: A CSS selector that tells Angular to create and insert an instance of this component wherever it finds the corresponding tag in template HTML. For example, if an app's HTML contains `<app-hero-list></app-hero-list>`, then Angular inserts an instance of the `HeroListComponent` view between those tags. * `templateUrl`: The module-relative address of this component's HTML template. Alternatively, you can provide the HTML template inline, as the value of the `template` property. This template defines the component's _host view_. * `providers`: An array of **dependency injection providers** for services that the component requires. In the example, this tells Angular that the component's constructor requires a `HeroService` instance in order to get the list of heroes to display. <hr/> ## Templates and views <img src="generated/images/guide/architecture/template.png" alt="Template" class="left"> You define a component's view with its companion template. A template is a form of HTML that tells Angular how to render the component. Views are typically arranged hierarchically, allowing you to modify or show and hide entire UI sections or pages as a unit. The template immediately associated with a component defines that component's _host view_. The component can also define a _view hierarchy_, which contains _embedded views_, hosted by other components. <figure> <img src="generated/images/guide/architecture/component-tree.png" alt="Component tree" class="left"> </figure> A view hierarchy can include views from components in the same NgModule, but it also can (and often does) include views from components that are defined in different NgModules. ## Template syntax A template looks like regular HTML, except that it also contains Angular [template syntax](guide/template-syntax), which alters the HTML based on your app's logic and the state of app and DOM data. Your template can use _data binding_ to coordinate the app and DOM data, _pipes_ to transform data before it is displayed, and _directives_ to apply app logic to what gets displayed. For example, here is a template for the Tutorial's `HeroListComponent`: <code-example path="architecture/src/app/hero-list.component.html" title="src/app/hero-list.component.html"></code-example> This template uses typical HTML elements like `<h2>` and `<p>`, and also includes Angular template-syntax elements, `*ngFor`, `{{hero.name}}`, `(click)`, `[hero]`, and `<app-hero-detail>`. The template-syntax elements tell Angular how to render the HTML to the screen, using program logic and data. * The `*ngFor` directive tells Angular to iterate over a list. * The `{{hero.name}}`, `(click)`, and `[hero]` bind program data to and from the DOM, responding to user input. See more about [data binding](#data-binding) below. * The `<app-hero-detail>` tag in the example is an element that represents a new component, `HeroDetailComponent`. The `HeroDetailComponent` (code not shown) is a child component of the `HeroListComponent` that defines the Hero-detail view. Notice how custom components like this mix seamlessly with native HTML in the same layouts. ### Data binding Without a framework, you would be responsible for pushing data values into the HTML controls and turning user responses into actions and value updates. Writing such push/pull logic by hand is tedious, error-prone, and a nightmare to read, as any experienced jQuery programmer can attest. Angular supports *two-way data binding*, a mechanism for coordinating parts of a template with parts of a component. Add binding markup to the template HTML to tell Angular how to connect both sides. The following diagram shows the four forms of data binding markup. Each form has a direction&mdash;to the DOM, from the DOM, or in both directions. <figure> <img src="generated/images/guide/architecture/databinding.png" alt="Data Binding" class="left"> </figure> This example from the `HeroListComponent` template uses three of these forms: <code-example path="architecture/src/app/hero-list.component.1.html" linenums="false" title="src/app/hero-list.component.html (binding)" region="binding"></code-example> * The `{{hero.name}}` [*interpolation*](guide/displaying-data#interpolation) displays the component's `hero.name` property value within the `<li>` element. * The `[hero]` [*property binding*](guide/template-syntax#property-binding) passes the value of `selectedHero` from the parent `HeroListComponent` to the `hero` property of the child `HeroDetailComponent`. * The `(click)` [*event binding*](guide/user-input#binding-to-user-input-events) calls the component's `selectHero` method when the user clicks a hero's name. **Two-way data binding** is an important fourth form that combines property and event binding in a single notation. Here's an example from the `HeroDetailComponent` template that uses two-way data binding with the `ngModel` directive: <code-example path="architecture/src/app/hero-detail.component.html" linenums="false" title="src/app/hero-detail.component.html (ngModel)" region="ngModel"></code-example> In two-way binding, a data property value flows to the input box from the component as with property binding. The user's changes also flow back to the component, resetting the property to the latest value, as with event binding. Angular processes *all* data bindings once per JavaScript event cycle, from the root of the application component tree through all child components. <figure> <img src="generated/images/guide/architecture/component-databinding.png" alt="Data Binding" class="left"> </figure> Data binding plays an important role in communication between a template and its component, and is also important for communication between parent and child components. <figure> <img src="generated/images/guide/architecture/parent-child-binding.png" alt="Parent/Child binding" class="left"> </figure> ### Pipes Angular pipes let you declare display-value transformations in your template HTML. A class with the `@Pipe` decorator defines a function that transforms input values to output values for display in a view. Angular defines various pipes, such as the [date](https://angular.io/api/common/DatePipe) pipe and [currency](https://angular.io/api/common/CurrencyPipe) pipe; for a complete list, see the [Pipes API list](https://angular.io/api?type=pipe). You can also define new pipes. To specify a value transformation in an HTML template, use the [pipe operator (|)](https://angular.io/guide/template-syntax#pipe): `{{interpolated_value | pipe_name}}` You can chain pipes, sending the output of one pipe function to be transformed by another pipe function. A pipe can also take arguments that control how it performs its transformation. For example, you can pass the desired format to the `date` pipe: ``` <!-- Default format: output 'Jun 15, 2015'--> <p>Today is {{today | date}}</p> <!-- fullDate format: output 'Monday, June 15, 2015'--> <p>The date is {{today | date:'fullDate'}}</p> <!-- shortTime format: output '9:43 AM'--> <p>The time is {{today | date:'shortTime'}}</p> ``` <hr/> ### Directives <img src="generated/images/guide/architecture/directive.png" alt="Directives" class="left"> Angular templates are *dynamic*. When Angular renders them, it transforms the DOM according to the instructions given by *directives*. A directive is a class with a `@Directive` decorator. A component is technically a directive - but components are so distinctive and central to Angular applications that Angular defines the `@Component` decorator, which extends the `@Directive` decorator with template-oriented features. There are two kinds of directives besides components: _structural_ and _attribute_ directives. Just as for components, the metadata for a directive associates the class with a `selector` that you use to insert it into HTML. In templates, directives typically appear within an element tag as attributes, either by name or as the target of an assignment or a binding. #### Structural directives Structural directives alter layout by adding, removing, and replacing elements in DOM. The example template uses two built-in structural directives to add application logic to how the view is rendered: <code-example path="architecture/src/app/hero-list.component.1.html" linenums="false" title="src/app/hero-list.component.html (structural)" region="structural"></code-example> * [`*ngFor`](guide/displaying-data#ngFor) is an iterative; it tells Angular to stamp out one `<li>` per hero in the `heroes` list. * [`*ngIf`](guide/displaying-data#ngIf) is a conditional; it includes the `HeroDetail` component only if a selected hero exists. #### Attribute directives Attribute directives alter the appearance or behavior of an existing element. In templates they look like regular HTML attributes, hence the name. The `ngModel` directive, which implements two-way data binding, is an example of an attribute directive. `ngModel` modifies the behavior of an existing element (typically an `<input>`) by setting its display value property and responding to change events. <code-example path="architecture/src/app/hero-detail.component.html" linenums="false" title="src/app/hero-detail.component.html (ngModel)" region="ngModel"></code-example> Angular has more pre-defined directives that either alter the layout structure (for example, [ngSwitch](guide/template-syntax#ngSwitch)) or modify aspects of DOM elements and components (for example, [ngStyle](guide/template-syntax#ngStyle) and [ngClass](guide/template-syntax#ngClass)). You can also write your own directives. Components such as `HeroListComponent` are one kind of custom directive. You can also create custom structural and attribute directives. <!-- PENDING: link to where to learn more about other kinds! -->
aio/content/guide/architecture-components.md
1
https://github.com/angular/angular/commit/e1146f3d066e653b9b40799cc436034e44af9160
[ 0.899592399597168, 0.04930252954363823, 0.00016079585475381464, 0.0007572777685709298, 0.20043209195137024 ]
{ "id": 1, "code_window": [ "\n", "For example, the `HeroListComponent` has a `heroes` property that returns an array of heroes that it acquires from a service. `HeroListComponent` also has a `selectHero()` method that sets a `selectedHero` property when the user clicks to choose a hero from that list.\n", "\n", "<code-example path=\"architecture/src/app/hero-list.component.ts\" linenums=\"false\" title=\"src/app/hero-list.component.ts (class)\" region=\"class\"></code-example>\n", "\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "For example, the `HeroListComponent` has a `heroes` property that holds an array of heroes. It also has a `selectHero()` method that sets a `selectedHero` property when the user clicks to choose a hero from that list. The component acquires the heroes from a service, which is a TypeScript [parameter property[(http://www.typescriptlang.org/docs/handbook/classes.html#parameter-properties) on the constructor. The service is provided to the component through the dependency injection system.\n" ], "file_path": "aio/content/guide/architecture-components.md", "type": "replace", "edit_start_line_idx": 12 }
<h3>Download the textfile</h3> <button (click)="download()">Download</button> <button (click)="clear()">clear</button> <p *ngIf="contents">Contents: "{{contents}}"</p>
aio/content/examples/http/src/app/downloader/downloader.component.html
0
https://github.com/angular/angular/commit/e1146f3d066e653b9b40799cc436034e44af9160
[ 0.00017700418538879603, 0.00017700418538879603, 0.00017700418538879603, 0.00017700418538879603, 0 ]
{ "id": 1, "code_window": [ "\n", "For example, the `HeroListComponent` has a `heroes` property that returns an array of heroes that it acquires from a service. `HeroListComponent` also has a `selectHero()` method that sets a `selectedHero` property when the user clicks to choose a hero from that list.\n", "\n", "<code-example path=\"architecture/src/app/hero-list.component.ts\" linenums=\"false\" title=\"src/app/hero-list.component.ts (class)\" region=\"class\"></code-example>\n", "\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "For example, the `HeroListComponent` has a `heroes` property that holds an array of heroes. It also has a `selectHero()` method that sets a `selectedHero` property when the user clicks to choose a hero from that list. The component acquires the heroes from a service, which is a TypeScript [parameter property[(http://www.typescriptlang.org/docs/handbook/classes.html#parameter-properties) on the constructor. The service is provided to the component through the dependency injection system.\n" ], "file_path": "aio/content/guide/architecture-components.md", "type": "replace", "edit_start_line_idx": 12 }
// #docregion import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; import { environment } from './environments/environment'; if (environment.production) { enableProdMode(); } platformBrowserDynamic().bootstrapModule(AppModule);
aio/content/examples/hierarchical-dependency-injection/src/main.ts
0
https://github.com/angular/angular/commit/e1146f3d066e653b9b40799cc436034e44af9160
[ 0.0001772029499989003, 0.00017403419769834727, 0.00017086544539779425, 0.00017403419769834727, 0.000003168752300553024 ]
{ "id": 1, "code_window": [ "\n", "For example, the `HeroListComponent` has a `heroes` property that returns an array of heroes that it acquires from a service. `HeroListComponent` also has a `selectHero()` method that sets a `selectedHero` property when the user clicks to choose a hero from that list.\n", "\n", "<code-example path=\"architecture/src/app/hero-list.component.ts\" linenums=\"false\" title=\"src/app/hero-list.component.ts (class)\" region=\"class\"></code-example>\n", "\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "For example, the `HeroListComponent` has a `heroes` property that holds an array of heroes. It also has a `selectHero()` method that sets a `selectedHero` property when the user clicks to choose a hero from that list. The component acquires the heroes from a service, which is a TypeScript [parameter property[(http://www.typescriptlang.org/docs/handbook/classes.html#parameter-properties) on the constructor. The service is provided to the component through the dependency injection system.\n" ], "file_path": "aio/content/guide/architecture-components.md", "type": "replace", "edit_start_line_idx": 12 }
// #docplaster // #docregion // TODO: Feature Componetized like CrisisCenter // #docregion rxjs-imports import { Observable } from 'rxjs'; import { switchMap } from 'rxjs/operators'; // #enddocregion rxjs-imports import { Component, OnInit } from '@angular/core'; // #docregion import-router import { ActivatedRoute, ParamMap } from '@angular/router'; // #enddocregion import-router import { Hero, HeroService } from './hero.service'; @Component({ // #docregion template template: ` <h2>HEROES</h2> <ul class="items"> <li *ngFor="let hero of heroes$ | async" [class.selected]="hero.id === selectedId"> <a [routerLink]="['/hero', hero.id]"> <span class="badge">{{ hero.id }}</span>{{ hero.name }} </a> </li> </ul> <button routerLink="/sidekicks">Go to sidekicks</button> ` // #enddocregion template }) // #docregion ctor export class HeroListComponent implements OnInit { heroes$: Observable<Hero[]>; private selectedId: number; constructor( private service: HeroService, private route: ActivatedRoute ) {} ngOnInit() { this.heroes$ = this.route.paramMap.pipe( switchMap((params: ParamMap) => { // (+) before `params.get()` turns the string into a number this.selectedId = +params.get('id'); return this.service.getHeroes(); }) ); } // #enddocregion ctor // #docregion ctor } // #enddocregion
aio/content/examples/router/src/app/heroes/hero-list.component.ts
0
https://github.com/angular/angular/commit/e1146f3d066e653b9b40799cc436034e44af9160
[ 0.006284099072217941, 0.0019721745047718287, 0.00017141374701168388, 0.0013454280560836196, 0.0021638860926032066 ]
{ "id": 2, "code_window": [ "\n", "* `templateUrl`: The module-relative address of this component's HTML template. Alternatively, you can provide the HTML template inline, as the value of the `template` property. This template defines the component's _host view_.\n", "\n", "* `providers`: An array of **dependency injection providers** for services that the component requires. In the example, this tells Angular that the component's constructor requires a `HeroService` instance\n", "in order to get the list of heroes to display.\n", "\n", "<hr/>\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "* `providers`: An array of **dependency injection providers** for services that the component requires. In the example, this tells Angular how provide the `HeroService` instance that the component's constructor uses to get the list of heroes to display.\n" ], "file_path": "aio/content/guide/architecture-components.md", "type": "replace", "edit_start_line_idx": 41 }
# Introduction to components <img src="generated/images/guide/architecture/hero-component.png" alt="Component" class="left"> A _component_ controls a patch of screen called a *view*. For example, individual components define and control each of the following views from the [Tutorial](tutorial/index): * The app root with the navigation links. * The list of heroes. * The hero editor. You define a component's application logic&mdash;what it does to support the view&mdash;inside a class. The class interacts with the view through an API of properties and methods. For example, the `HeroListComponent` has a `heroes` property that returns an array of heroes that it acquires from a service. `HeroListComponent` also has a `selectHero()` method that sets a `selectedHero` property when the user clicks to choose a hero from that list. <code-example path="architecture/src/app/hero-list.component.ts" linenums="false" title="src/app/hero-list.component.ts (class)" region="class"></code-example> Angular creates, updates, and destroys components as the user moves through the application. Your app can take action at each moment in this lifecycle through optional [lifecycle hooks](guide/lifecycle-hooks), like `ngOnInit()`. <hr/> ## Component metadata <img src="generated/images/guide/architecture/metadata.png" alt="Metadata" class="left"> The `@Component` decorator identifies the class immediately below it as a component class, and specifies its metadata. In the example code below, you can see that `HeroListComponent` is just a class, with no special Angular notation or syntax at all. It's not a component until you mark it as one with the `@Component` decorator. The metadata for a component tells Angular where to get the major building blocks it needs to create and present the component and its view. In particular, it associates a _template_ with the component, either directly with inline code, or by reference. Together, the component and its template describe a _view_. In addition to containing or pointing to the template, the `@Component` metadata configures, for example, how the component can be referenced in HTML and what services it requires. Here's an example of basic metadata for `HeroListComponent`: <code-example path="architecture/src/app/hero-list.component.ts" linenums="false" title="src/app/hero-list.component.ts (metadata)" region="metadata"></code-example> This example shows some of the most useful `@Component` configuration options: * `selector`: A CSS selector that tells Angular to create and insert an instance of this component wherever it finds the corresponding tag in template HTML. For example, if an app's HTML contains `<app-hero-list></app-hero-list>`, then Angular inserts an instance of the `HeroListComponent` view between those tags. * `templateUrl`: The module-relative address of this component's HTML template. Alternatively, you can provide the HTML template inline, as the value of the `template` property. This template defines the component's _host view_. * `providers`: An array of **dependency injection providers** for services that the component requires. In the example, this tells Angular that the component's constructor requires a `HeroService` instance in order to get the list of heroes to display. <hr/> ## Templates and views <img src="generated/images/guide/architecture/template.png" alt="Template" class="left"> You define a component's view with its companion template. A template is a form of HTML that tells Angular how to render the component. Views are typically arranged hierarchically, allowing you to modify or show and hide entire UI sections or pages as a unit. The template immediately associated with a component defines that component's _host view_. The component can also define a _view hierarchy_, which contains _embedded views_, hosted by other components. <figure> <img src="generated/images/guide/architecture/component-tree.png" alt="Component tree" class="left"> </figure> A view hierarchy can include views from components in the same NgModule, but it also can (and often does) include views from components that are defined in different NgModules. ## Template syntax A template looks like regular HTML, except that it also contains Angular [template syntax](guide/template-syntax), which alters the HTML based on your app's logic and the state of app and DOM data. Your template can use _data binding_ to coordinate the app and DOM data, _pipes_ to transform data before it is displayed, and _directives_ to apply app logic to what gets displayed. For example, here is a template for the Tutorial's `HeroListComponent`: <code-example path="architecture/src/app/hero-list.component.html" title="src/app/hero-list.component.html"></code-example> This template uses typical HTML elements like `<h2>` and `<p>`, and also includes Angular template-syntax elements, `*ngFor`, `{{hero.name}}`, `(click)`, `[hero]`, and `<app-hero-detail>`. The template-syntax elements tell Angular how to render the HTML to the screen, using program logic and data. * The `*ngFor` directive tells Angular to iterate over a list. * The `{{hero.name}}`, `(click)`, and `[hero]` bind program data to and from the DOM, responding to user input. See more about [data binding](#data-binding) below. * The `<app-hero-detail>` tag in the example is an element that represents a new component, `HeroDetailComponent`. The `HeroDetailComponent` (code not shown) is a child component of the `HeroListComponent` that defines the Hero-detail view. Notice how custom components like this mix seamlessly with native HTML in the same layouts. ### Data binding Without a framework, you would be responsible for pushing data values into the HTML controls and turning user responses into actions and value updates. Writing such push/pull logic by hand is tedious, error-prone, and a nightmare to read, as any experienced jQuery programmer can attest. Angular supports *two-way data binding*, a mechanism for coordinating parts of a template with parts of a component. Add binding markup to the template HTML to tell Angular how to connect both sides. The following diagram shows the four forms of data binding markup. Each form has a direction&mdash;to the DOM, from the DOM, or in both directions. <figure> <img src="generated/images/guide/architecture/databinding.png" alt="Data Binding" class="left"> </figure> This example from the `HeroListComponent` template uses three of these forms: <code-example path="architecture/src/app/hero-list.component.1.html" linenums="false" title="src/app/hero-list.component.html (binding)" region="binding"></code-example> * The `{{hero.name}}` [*interpolation*](guide/displaying-data#interpolation) displays the component's `hero.name` property value within the `<li>` element. * The `[hero]` [*property binding*](guide/template-syntax#property-binding) passes the value of `selectedHero` from the parent `HeroListComponent` to the `hero` property of the child `HeroDetailComponent`. * The `(click)` [*event binding*](guide/user-input#binding-to-user-input-events) calls the component's `selectHero` method when the user clicks a hero's name. **Two-way data binding** is an important fourth form that combines property and event binding in a single notation. Here's an example from the `HeroDetailComponent` template that uses two-way data binding with the `ngModel` directive: <code-example path="architecture/src/app/hero-detail.component.html" linenums="false" title="src/app/hero-detail.component.html (ngModel)" region="ngModel"></code-example> In two-way binding, a data property value flows to the input box from the component as with property binding. The user's changes also flow back to the component, resetting the property to the latest value, as with event binding. Angular processes *all* data bindings once per JavaScript event cycle, from the root of the application component tree through all child components. <figure> <img src="generated/images/guide/architecture/component-databinding.png" alt="Data Binding" class="left"> </figure> Data binding plays an important role in communication between a template and its component, and is also important for communication between parent and child components. <figure> <img src="generated/images/guide/architecture/parent-child-binding.png" alt="Parent/Child binding" class="left"> </figure> ### Pipes Angular pipes let you declare display-value transformations in your template HTML. A class with the `@Pipe` decorator defines a function that transforms input values to output values for display in a view. Angular defines various pipes, such as the [date](https://angular.io/api/common/DatePipe) pipe and [currency](https://angular.io/api/common/CurrencyPipe) pipe; for a complete list, see the [Pipes API list](https://angular.io/api?type=pipe). You can also define new pipes. To specify a value transformation in an HTML template, use the [pipe operator (|)](https://angular.io/guide/template-syntax#pipe): `{{interpolated_value | pipe_name}}` You can chain pipes, sending the output of one pipe function to be transformed by another pipe function. A pipe can also take arguments that control how it performs its transformation. For example, you can pass the desired format to the `date` pipe: ``` <!-- Default format: output 'Jun 15, 2015'--> <p>Today is {{today | date}}</p> <!-- fullDate format: output 'Monday, June 15, 2015'--> <p>The date is {{today | date:'fullDate'}}</p> <!-- shortTime format: output '9:43 AM'--> <p>The time is {{today | date:'shortTime'}}</p> ``` <hr/> ### Directives <img src="generated/images/guide/architecture/directive.png" alt="Directives" class="left"> Angular templates are *dynamic*. When Angular renders them, it transforms the DOM according to the instructions given by *directives*. A directive is a class with a `@Directive` decorator. A component is technically a directive - but components are so distinctive and central to Angular applications that Angular defines the `@Component` decorator, which extends the `@Directive` decorator with template-oriented features. There are two kinds of directives besides components: _structural_ and _attribute_ directives. Just as for components, the metadata for a directive associates the class with a `selector` that you use to insert it into HTML. In templates, directives typically appear within an element tag as attributes, either by name or as the target of an assignment or a binding. #### Structural directives Structural directives alter layout by adding, removing, and replacing elements in DOM. The example template uses two built-in structural directives to add application logic to how the view is rendered: <code-example path="architecture/src/app/hero-list.component.1.html" linenums="false" title="src/app/hero-list.component.html (structural)" region="structural"></code-example> * [`*ngFor`](guide/displaying-data#ngFor) is an iterative; it tells Angular to stamp out one `<li>` per hero in the `heroes` list. * [`*ngIf`](guide/displaying-data#ngIf) is a conditional; it includes the `HeroDetail` component only if a selected hero exists. #### Attribute directives Attribute directives alter the appearance or behavior of an existing element. In templates they look like regular HTML attributes, hence the name. The `ngModel` directive, which implements two-way data binding, is an example of an attribute directive. `ngModel` modifies the behavior of an existing element (typically an `<input>`) by setting its display value property and responding to change events. <code-example path="architecture/src/app/hero-detail.component.html" linenums="false" title="src/app/hero-detail.component.html (ngModel)" region="ngModel"></code-example> Angular has more pre-defined directives that either alter the layout structure (for example, [ngSwitch](guide/template-syntax#ngSwitch)) or modify aspects of DOM elements and components (for example, [ngStyle](guide/template-syntax#ngStyle) and [ngClass](guide/template-syntax#ngClass)). You can also write your own directives. Components such as `HeroListComponent` are one kind of custom directive. You can also create custom structural and attribute directives. <!-- PENDING: link to where to learn more about other kinds! -->
aio/content/guide/architecture-components.md
1
https://github.com/angular/angular/commit/e1146f3d066e653b9b40799cc436034e44af9160
[ 0.008220365270972252, 0.0010006780503317714, 0.00016774388495832682, 0.0004154711787123233, 0.0018120653694495559 ]
{ "id": 2, "code_window": [ "\n", "* `templateUrl`: The module-relative address of this component's HTML template. Alternatively, you can provide the HTML template inline, as the value of the `template` property. This template defines the component's _host view_.\n", "\n", "* `providers`: An array of **dependency injection providers** for services that the component requires. In the example, this tells Angular that the component's constructor requires a `HeroService` instance\n", "in order to get the list of heroes to display.\n", "\n", "<hr/>\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "* `providers`: An array of **dependency injection providers** for services that the component requires. In the example, this tells Angular how provide the `HeroService` instance that the component's constructor uses to get the list of heroes to display.\n" ], "file_path": "aio/content/guide/architecture-components.md", "type": "replace", "edit_start_line_idx": 41 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Pipe, PipeTransform} from '@angular/core'; /** * @ngModule CommonModule * @description * * Converts a value into its JSON-format representation. Useful for debugging. * * @usageNotes * * The following component uses a JSON pipe to convert an object * to JSON format, and displays the string in both formats for comparison. * {@example common/pipes/ts/json_pipe.ts region='JsonPipe'} * * */ @Pipe({name: 'json', pure: false}) export class JsonPipe implements PipeTransform { /** * @param value A value of any type to convert into a JSON-format string. */ transform(value: any): string { return JSON.stringify(value, null, 2); } }
packages/common/src/pipes/json_pipe.ts
0
https://github.com/angular/angular/commit/e1146f3d066e653b9b40799cc436034e44af9160
[ 0.0001946926349774003, 0.00017504309653304517, 0.0001673291699262336, 0.00016907531244214624, 0.000011369322237442248 ]
{ "id": 2, "code_window": [ "\n", "* `templateUrl`: The module-relative address of this component's HTML template. Alternatively, you can provide the HTML template inline, as the value of the `template` property. This template defines the component's _host view_.\n", "\n", "* `providers`: An array of **dependency injection providers** for services that the component requires. In the example, this tells Angular that the component's constructor requires a `HeroService` instance\n", "in order to get the list of heroes to display.\n", "\n", "<hr/>\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "* `providers`: An array of **dependency injection providers** for services that the component requires. In the example, this tells Angular how provide the `HeroService` instance that the component's constructor uses to get the list of heroes to display.\n" ], "file_path": "aio/content/guide/architecture-components.md", "type": "replace", "edit_start_line_idx": 41 }
{ "extends": "../tsconfig-build.json", "compilerOptions": { "baseUrl": ".", "rootDir": "../", "paths": { "@angular/common": ["../../../dist/packages/common"], "@angular/core": ["../../../dist/packages/core"] }, "outDir": "../../../dist/packages/common" }, "files": [ "public_api.ts" ], "angularCompilerOptions": { "annotateForClosureCompiler": true, "strictMetadataEmit": false, "skipTemplateCodegen": true, "flatModuleOutFile": "http.js", "flatModuleId": "@angular/common/http" } }
packages/common/http/tsconfig-build.json
0
https://github.com/angular/angular/commit/e1146f3d066e653b9b40799cc436034e44af9160
[ 0.0001767016656231135, 0.0001701085566310212, 0.00016635445354040712, 0.00016726952162571251, 0.00000467698237116565 ]
{ "id": 2, "code_window": [ "\n", "* `templateUrl`: The module-relative address of this component's HTML template. Alternatively, you can provide the HTML template inline, as the value of the `template` property. This template defines the component's _host view_.\n", "\n", "* `providers`: An array of **dependency injection providers** for services that the component requires. In the example, this tells Angular that the component's constructor requires a `HeroService` instance\n", "in order to get the list of heroes to display.\n", "\n", "<hr/>\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "* `providers`: An array of **dependency injection providers** for services that the component requires. In the example, this tells Angular how provide the `HeroService` instance that the component's constructor uses to get the list of heroes to display.\n" ], "file_path": "aio/content/guide/architecture-components.md", "type": "replace", "edit_start_line_idx": 41 }
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Hero, HeroService } from './hero.service'; @Component({ template: ` <h3 highlight>Hero Detail</h3> <div *ngIf="hero"> <div>Id: {{hero.id}}</div><br> <label>Name: <input [(ngModel)]="hero.name"> </label> </div> <br> <a routerLink="../">Hero List</a> ` }) export class HeroDetailComponent implements OnInit { hero: Hero; constructor( private route: ActivatedRoute, private heroService: HeroService) { } ngOnInit() { let id = parseInt(this.route.snapshot.paramMap.get('id'), 10); this.heroService.getHero(id).subscribe(hero => this.hero = hero); } }
aio/content/examples/ngmodule-faq/src/app/hero/hero-detail.component.ts
0
https://github.com/angular/angular/commit/e1146f3d066e653b9b40799cc436034e44af9160
[ 0.00028575077885761857, 0.00023920195235405117, 0.00016799069999251515, 0.0002515331725589931, 0.000044826101657235995 ]
{ "id": 3, "code_window": [ "\n", "For example, import Angular's `Component` decorator from the `@angular/core` library like this:\n", "\n", "<code-example path=\"architecture/src/app/app.component.ts\" region=\"import\" linenums=\"false\"></code-example>\n", "\n", "You also import NgModules from Angular _libraries_ using JavaScript import statements:\n", "\n", "<code-example path=\"architecture/src/app/mini-app.ts\" region=\"import-browser-module\" linenums=\"false\"></code-example>\n", "\n", "In the example of the simple root module above, the application module needs material from within the `BrowserModule`. To access that material, add it to the `@NgModule` metadata `imports` like this.\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "You also import NgModules from Angular _libraries_ using JavaScript import statements. \n", "For example, the following code imports the `BrowserModule` NgModule from the `platform-browser` library:\n" ], "file_path": "aio/content/guide/architecture-modules.md", "type": "replace", "edit_start_line_idx": 90 }
# Introduction to components <img src="generated/images/guide/architecture/hero-component.png" alt="Component" class="left"> A _component_ controls a patch of screen called a *view*. For example, individual components define and control each of the following views from the [Tutorial](tutorial/index): * The app root with the navigation links. * The list of heroes. * The hero editor. You define a component's application logic&mdash;what it does to support the view&mdash;inside a class. The class interacts with the view through an API of properties and methods. For example, the `HeroListComponent` has a `heroes` property that returns an array of heroes that it acquires from a service. `HeroListComponent` also has a `selectHero()` method that sets a `selectedHero` property when the user clicks to choose a hero from that list. <code-example path="architecture/src/app/hero-list.component.ts" linenums="false" title="src/app/hero-list.component.ts (class)" region="class"></code-example> Angular creates, updates, and destroys components as the user moves through the application. Your app can take action at each moment in this lifecycle through optional [lifecycle hooks](guide/lifecycle-hooks), like `ngOnInit()`. <hr/> ## Component metadata <img src="generated/images/guide/architecture/metadata.png" alt="Metadata" class="left"> The `@Component` decorator identifies the class immediately below it as a component class, and specifies its metadata. In the example code below, you can see that `HeroListComponent` is just a class, with no special Angular notation or syntax at all. It's not a component until you mark it as one with the `@Component` decorator. The metadata for a component tells Angular where to get the major building blocks it needs to create and present the component and its view. In particular, it associates a _template_ with the component, either directly with inline code, or by reference. Together, the component and its template describe a _view_. In addition to containing or pointing to the template, the `@Component` metadata configures, for example, how the component can be referenced in HTML and what services it requires. Here's an example of basic metadata for `HeroListComponent`: <code-example path="architecture/src/app/hero-list.component.ts" linenums="false" title="src/app/hero-list.component.ts (metadata)" region="metadata"></code-example> This example shows some of the most useful `@Component` configuration options: * `selector`: A CSS selector that tells Angular to create and insert an instance of this component wherever it finds the corresponding tag in template HTML. For example, if an app's HTML contains `<app-hero-list></app-hero-list>`, then Angular inserts an instance of the `HeroListComponent` view between those tags. * `templateUrl`: The module-relative address of this component's HTML template. Alternatively, you can provide the HTML template inline, as the value of the `template` property. This template defines the component's _host view_. * `providers`: An array of **dependency injection providers** for services that the component requires. In the example, this tells Angular that the component's constructor requires a `HeroService` instance in order to get the list of heroes to display. <hr/> ## Templates and views <img src="generated/images/guide/architecture/template.png" alt="Template" class="left"> You define a component's view with its companion template. A template is a form of HTML that tells Angular how to render the component. Views are typically arranged hierarchically, allowing you to modify or show and hide entire UI sections or pages as a unit. The template immediately associated with a component defines that component's _host view_. The component can also define a _view hierarchy_, which contains _embedded views_, hosted by other components. <figure> <img src="generated/images/guide/architecture/component-tree.png" alt="Component tree" class="left"> </figure> A view hierarchy can include views from components in the same NgModule, but it also can (and often does) include views from components that are defined in different NgModules. ## Template syntax A template looks like regular HTML, except that it also contains Angular [template syntax](guide/template-syntax), which alters the HTML based on your app's logic and the state of app and DOM data. Your template can use _data binding_ to coordinate the app and DOM data, _pipes_ to transform data before it is displayed, and _directives_ to apply app logic to what gets displayed. For example, here is a template for the Tutorial's `HeroListComponent`: <code-example path="architecture/src/app/hero-list.component.html" title="src/app/hero-list.component.html"></code-example> This template uses typical HTML elements like `<h2>` and `<p>`, and also includes Angular template-syntax elements, `*ngFor`, `{{hero.name}}`, `(click)`, `[hero]`, and `<app-hero-detail>`. The template-syntax elements tell Angular how to render the HTML to the screen, using program logic and data. * The `*ngFor` directive tells Angular to iterate over a list. * The `{{hero.name}}`, `(click)`, and `[hero]` bind program data to and from the DOM, responding to user input. See more about [data binding](#data-binding) below. * The `<app-hero-detail>` tag in the example is an element that represents a new component, `HeroDetailComponent`. The `HeroDetailComponent` (code not shown) is a child component of the `HeroListComponent` that defines the Hero-detail view. Notice how custom components like this mix seamlessly with native HTML in the same layouts. ### Data binding Without a framework, you would be responsible for pushing data values into the HTML controls and turning user responses into actions and value updates. Writing such push/pull logic by hand is tedious, error-prone, and a nightmare to read, as any experienced jQuery programmer can attest. Angular supports *two-way data binding*, a mechanism for coordinating parts of a template with parts of a component. Add binding markup to the template HTML to tell Angular how to connect both sides. The following diagram shows the four forms of data binding markup. Each form has a direction&mdash;to the DOM, from the DOM, or in both directions. <figure> <img src="generated/images/guide/architecture/databinding.png" alt="Data Binding" class="left"> </figure> This example from the `HeroListComponent` template uses three of these forms: <code-example path="architecture/src/app/hero-list.component.1.html" linenums="false" title="src/app/hero-list.component.html (binding)" region="binding"></code-example> * The `{{hero.name}}` [*interpolation*](guide/displaying-data#interpolation) displays the component's `hero.name` property value within the `<li>` element. * The `[hero]` [*property binding*](guide/template-syntax#property-binding) passes the value of `selectedHero` from the parent `HeroListComponent` to the `hero` property of the child `HeroDetailComponent`. * The `(click)` [*event binding*](guide/user-input#binding-to-user-input-events) calls the component's `selectHero` method when the user clicks a hero's name. **Two-way data binding** is an important fourth form that combines property and event binding in a single notation. Here's an example from the `HeroDetailComponent` template that uses two-way data binding with the `ngModel` directive: <code-example path="architecture/src/app/hero-detail.component.html" linenums="false" title="src/app/hero-detail.component.html (ngModel)" region="ngModel"></code-example> In two-way binding, a data property value flows to the input box from the component as with property binding. The user's changes also flow back to the component, resetting the property to the latest value, as with event binding. Angular processes *all* data bindings once per JavaScript event cycle, from the root of the application component tree through all child components. <figure> <img src="generated/images/guide/architecture/component-databinding.png" alt="Data Binding" class="left"> </figure> Data binding plays an important role in communication between a template and its component, and is also important for communication between parent and child components. <figure> <img src="generated/images/guide/architecture/parent-child-binding.png" alt="Parent/Child binding" class="left"> </figure> ### Pipes Angular pipes let you declare display-value transformations in your template HTML. A class with the `@Pipe` decorator defines a function that transforms input values to output values for display in a view. Angular defines various pipes, such as the [date](https://angular.io/api/common/DatePipe) pipe and [currency](https://angular.io/api/common/CurrencyPipe) pipe; for a complete list, see the [Pipes API list](https://angular.io/api?type=pipe). You can also define new pipes. To specify a value transformation in an HTML template, use the [pipe operator (|)](https://angular.io/guide/template-syntax#pipe): `{{interpolated_value | pipe_name}}` You can chain pipes, sending the output of one pipe function to be transformed by another pipe function. A pipe can also take arguments that control how it performs its transformation. For example, you can pass the desired format to the `date` pipe: ``` <!-- Default format: output 'Jun 15, 2015'--> <p>Today is {{today | date}}</p> <!-- fullDate format: output 'Monday, June 15, 2015'--> <p>The date is {{today | date:'fullDate'}}</p> <!-- shortTime format: output '9:43 AM'--> <p>The time is {{today | date:'shortTime'}}</p> ``` <hr/> ### Directives <img src="generated/images/guide/architecture/directive.png" alt="Directives" class="left"> Angular templates are *dynamic*. When Angular renders them, it transforms the DOM according to the instructions given by *directives*. A directive is a class with a `@Directive` decorator. A component is technically a directive - but components are so distinctive and central to Angular applications that Angular defines the `@Component` decorator, which extends the `@Directive` decorator with template-oriented features. There are two kinds of directives besides components: _structural_ and _attribute_ directives. Just as for components, the metadata for a directive associates the class with a `selector` that you use to insert it into HTML. In templates, directives typically appear within an element tag as attributes, either by name or as the target of an assignment or a binding. #### Structural directives Structural directives alter layout by adding, removing, and replacing elements in DOM. The example template uses two built-in structural directives to add application logic to how the view is rendered: <code-example path="architecture/src/app/hero-list.component.1.html" linenums="false" title="src/app/hero-list.component.html (structural)" region="structural"></code-example> * [`*ngFor`](guide/displaying-data#ngFor) is an iterative; it tells Angular to stamp out one `<li>` per hero in the `heroes` list. * [`*ngIf`](guide/displaying-data#ngIf) is a conditional; it includes the `HeroDetail` component only if a selected hero exists. #### Attribute directives Attribute directives alter the appearance or behavior of an existing element. In templates they look like regular HTML attributes, hence the name. The `ngModel` directive, which implements two-way data binding, is an example of an attribute directive. `ngModel` modifies the behavior of an existing element (typically an `<input>`) by setting its display value property and responding to change events. <code-example path="architecture/src/app/hero-detail.component.html" linenums="false" title="src/app/hero-detail.component.html (ngModel)" region="ngModel"></code-example> Angular has more pre-defined directives that either alter the layout structure (for example, [ngSwitch](guide/template-syntax#ngSwitch)) or modify aspects of DOM elements and components (for example, [ngStyle](guide/template-syntax#ngStyle) and [ngClass](guide/template-syntax#ngClass)). You can also write your own directives. Components such as `HeroListComponent` are one kind of custom directive. You can also create custom structural and attribute directives. <!-- PENDING: link to where to learn more about other kinds! -->
aio/content/guide/architecture-components.md
1
https://github.com/angular/angular/commit/e1146f3d066e653b9b40799cc436034e44af9160
[ 0.0015505944611504674, 0.0002837700303643942, 0.00016252782370429486, 0.00017932507034856826, 0.00030559315928258 ]
{ "id": 3, "code_window": [ "\n", "For example, import Angular's `Component` decorator from the `@angular/core` library like this:\n", "\n", "<code-example path=\"architecture/src/app/app.component.ts\" region=\"import\" linenums=\"false\"></code-example>\n", "\n", "You also import NgModules from Angular _libraries_ using JavaScript import statements:\n", "\n", "<code-example path=\"architecture/src/app/mini-app.ts\" region=\"import-browser-module\" linenums=\"false\"></code-example>\n", "\n", "In the example of the simple root module above, the application module needs material from within the `BrowserModule`. To access that material, add it to the `@NgModule` metadata `imports` like this.\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "You also import NgModules from Angular _libraries_ using JavaScript import statements. \n", "For example, the following code imports the `BrowserModule` NgModule from the `platform-browser` library:\n" ], "file_path": "aio/content/guide/architecture-modules.md", "type": "replace", "edit_start_line_idx": 90 }
{ "compilerOptions": { "outDir": "../built/e2e", "types": ["jasmine"], // TODO(alexeagle): was required for Protractor 4.0.11 "skipLibCheck": true } }
integration/platform-server/e2e/tsconfig.json
0
https://github.com/angular/angular/commit/e1146f3d066e653b9b40799cc436034e44af9160
[ 0.00017309033137280494, 0.00017309033137280494, 0.00017309033137280494, 0.00017309033137280494, 0 ]
{ "id": 3, "code_window": [ "\n", "For example, import Angular's `Component` decorator from the `@angular/core` library like this:\n", "\n", "<code-example path=\"architecture/src/app/app.component.ts\" region=\"import\" linenums=\"false\"></code-example>\n", "\n", "You also import NgModules from Angular _libraries_ using JavaScript import statements:\n", "\n", "<code-example path=\"architecture/src/app/mini-app.ts\" region=\"import-browser-module\" linenums=\"false\"></code-example>\n", "\n", "In the example of the simple root module above, the application module needs material from within the `BrowserModule`. To access that material, add it to the `@NgModule` metadata `imports` like this.\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "You also import NgModules from Angular _libraries_ using JavaScript import statements. \n", "For example, the following code imports the `BrowserModule` NgModule from the `platform-browser` library:\n" ], "file_path": "aio/content/guide/architecture-modules.md", "type": "replace", "edit_start_line_idx": 90 }
# Hierarchical Dependency Injectors You learned the basics of Angular Dependency injection in the [Dependency Injection](guide/dependency-injection) guide. Angular has a _Hierarchical Dependency Injection_ system. There is actually a tree of injectors that parallel an application's component tree. You can reconfigure the injectors at any level of that component tree. This guide explores this system and how to use it to your advantage. Try the <live-example></live-example>. ## The injector tree In the [Dependency Injection](guide/dependency-injection) guide, you learned how to configure a dependency injector and how to retrieve dependencies where you need them. In fact, there is no such thing as ***the*** injector. An application may have multiple injectors. An Angular application is a tree of components. Each component instance has its own injector. The tree of components parallels the tree of injectors. <div class="l-sub-section"> The component's injector may be a _proxy_ for an ancestor injector higher in the component tree. That's an implementation detail that improves efficiency. You won't notice the difference and your mental model should be that every component has its own injector. </div> Consider this guide's variation on the Tour of Heroes application. At the top is the `AppComponent` which has some sub-components. One of them is the `HeroesListComponent`. The `HeroesListComponent` holds and manages multiple instances of the `HeroTaxReturnComponent`. The following diagram represents the state of the this guide's three-level component tree when there are three instances of `HeroTaxReturnComponent` open simultaneously. <figure> <img src="generated/images/guide/dependency-injection/component-hierarchy.png" alt="injector tree"> </figure> ### Injector bubbling When a component requests a dependency, Angular tries to satisfy that dependency with a provider registered in that component's own injector. If the component's injector lacks the provider, it passes the request up to its parent component's injector. If that injector can't satisfy the request, it passes it along to *its* parent injector. The requests keep bubbling up until Angular finds an injector that can handle the request or runs out of ancestor injectors. If it runs out of ancestors, Angular throws an error. <div class="l-sub-section"> You can cap the bubbling. An intermediate component can declare that it is the "host" component. The hunt for providers will climb no higher than the injector for that host component. This is a topic for another day. </div> ### Re-providing a service at different levels You can re-register a provider for a particular dependency token at multiple levels of the injector tree. You don't *have* to re-register providers. You shouldn't do so unless you have a good reason. But you *can*. As the resolution logic works upwards, the first provider encountered wins. Thus, a provider in an intermediate injector intercepts a request for a service from something lower in the tree. It effectively "reconfigures" and "shadows" a provider at a higher level in the tree. If you only specify providers at the top level (typically the root `AppModule`), the tree of injectors appears to be flat. All requests bubble up to the root <code>NgModule</code> injector that you configured with the `bootstrapModule` method. ## Component injectors The ability to configure one or more providers at different levels opens up interesting and useful possibilities. ### Scenario: service isolation Architectural reasons may lead you to restrict access to a service to the application domain where it belongs. The guide sample includes a `VillainsListComponent` that displays a list of villains. It gets those villains from a `VillainsService`. While you _could_ provide `VillainsService` in the root `AppModule` (that's where you'll find the `HeroesService`), that would make the `VillainsService` available everywhere in the application, including the _Hero_ workflows. If you later modified the `VillainsService`, you could break something in a hero component somewhere. That's not supposed to happen but providing the service in the root `AppModule` creates that risk. Instead, provide the `VillainsService` in the `providers` metadata of the `VillainsListComponent` like this: <code-example path="hierarchical-dependency-injection/src/app/villains-list.component.ts" linenums="false" title="src/app/villains-list.component.ts (metadata)" region="metadata"> </code-example> By providing `VillainsService` in the `VillainsListComponent` metadata and nowhere else, the service becomes available only in the `VillainsListComponent` and its sub-component tree. It's still a singleton, but it's a singleton that exist solely in the _villain_ domain. Now you know that a hero component can't access it. You've reduced your exposure to error. ### Scenario: multiple edit sessions Many applications allow users to work on several open tasks at the same time. For example, in a tax preparation application, the preparer could be working on several tax returns, switching from one to the other throughout the day. This guide demonstrates that scenario with an example in the Tour of Heroes theme. Imagine an outer `HeroListComponent` that displays a list of super heroes. To open a hero's tax return, the preparer clicks on a hero name, which opens a component for editing that return. Each selected hero tax return opens in its own component and multiple returns can be open at the same time. Each tax return component has the following characteristics: * Is its own tax return editing session. * Can change a tax return without affecting a return in another component. * Has the ability to save the changes to its tax return or cancel them. <figure> <img src="generated/images/guide/dependency-injection/hid-heroes-anim.gif" alt="Heroes in action"> </figure> One might suppose that the `HeroTaxReturnComponent` has logic to manage and restore changes. That would be a pretty easy task for a simple hero tax return. In the real world, with a rich tax return data model, the change management would be tricky. You might delegate that management to a helper service, as this example does. Here is the `HeroTaxReturnService`. It caches a single `HeroTaxReturn`, tracks changes to that return, and can save or restore it. It also delegates to the application-wide singleton `HeroService`, which it gets by injection. <code-example path="hierarchical-dependency-injection/src/app/hero-tax-return.service.ts" title="src/app/hero-tax-return.service.ts"> </code-example> Here is the `HeroTaxReturnComponent` that makes use of it. <code-example path="hierarchical-dependency-injection/src/app/hero-tax-return.component.ts" title="src/app/hero-tax-return.component.ts"> </code-example> The _tax-return-to-edit_ arrives via the input property which is implemented with getters and setters. The setter initializes the component's own instance of the `HeroTaxReturnService` with the incoming return. The getter always returns what that service says is the current state of the hero. The component also asks the service to save and restore this tax return. There'd be big trouble if _this_ service were an application-wide singleton. Every component would share the same service instance. Each component would overwrite the tax return that belonged to another hero. What a mess! Look closely at the metadata for the `HeroTaxReturnComponent`. Notice the `providers` property. <code-example path="hierarchical-dependency-injection/src/app/hero-tax-return.component.ts" linenums="false" title="src/app/hero-tax-return.component.ts (providers)" region="providers"> </code-example> The `HeroTaxReturnComponent` has its own provider of the `HeroTaxReturnService`. Recall that every component _instance_ has its own injector. Providing the service at the component level ensures that _every_ instance of the component gets its own, private instance of the service. No tax return overwriting. No mess. <div class="l-sub-section"> The rest of the scenario code relies on other Angular features and techniques that you can learn about elsewhere in the documentation. You can review it and download it from the <live-example></live-example>. </div> ### Scenario: specialized providers Another reason to re-provide a service is to substitute a _more specialized_ implementation of that service, deeper in the component tree. Consider again the Car example from the [Dependency Injection](guide/dependency-injection) guide. Suppose you configured the root injector (marked as A) with _generic_ providers for `CarService`, `EngineService` and `TiresService`. You create a car component (A) that displays a car constructed from these three generic services. Then you create a child component (B) that defines its own, _specialized_ providers for `CarService` and `EngineService` that have special capabilities suitable for whatever is going on in component (B). Component (B) is the parent of another component (C) that defines its own, even _more specialized_ provider for `CarService`. <figure> <img src="generated/images/guide/dependency-injection/car-components.png" alt="car components"> </figure> Behind the scenes, each component sets up its own injector with zero, one, or more providers defined for that component itself. When you resolve an instance of `Car` at the deepest component (C), its injector produces an instance of `Car` resolved by injector (C) with an `Engine` resolved by injector (B) and `Tires` resolved by the root injector (A). <figure> <img src="generated/images/guide/dependency-injection/injector-tree.png" alt="car injector tree"> </figure> <div class="l-sub-section"> The code for this _cars_ scenario is in the `car.components.ts` and `car.services.ts` files of the sample which you can review and download from the <live-example></live-example>. </div>
aio/content/guide/hierarchical-dependency-injection.md
0
https://github.com/angular/angular/commit/e1146f3d066e653b9b40799cc436034e44af9160
[ 0.0007491480209864676, 0.00019719568081200123, 0.0001593847555341199, 0.0001684172311797738, 0.00011410668957978487 ]
{ "id": 3, "code_window": [ "\n", "For example, import Angular's `Component` decorator from the `@angular/core` library like this:\n", "\n", "<code-example path=\"architecture/src/app/app.component.ts\" region=\"import\" linenums=\"false\"></code-example>\n", "\n", "You also import NgModules from Angular _libraries_ using JavaScript import statements:\n", "\n", "<code-example path=\"architecture/src/app/mini-app.ts\" region=\"import-browser-module\" linenums=\"false\"></code-example>\n", "\n", "In the example of the simple root module above, the application module needs material from within the `BrowserModule`. To access that material, add it to the `@NgModule` metadata `imports` like this.\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "You also import NgModules from Angular _libraries_ using JavaScript import statements. \n", "For example, the following code imports the `BrowserModule` NgModule from the `platform-browser` library:\n" ], "file_path": "aio/content/guide/architecture-modules.md", "type": "replace", "edit_start_line_idx": 90 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; function plural(n: number): number { if (n === 1) return 1; return 5; } export default [ 'es-BZ', [['a. m.', 'p. m.'], ['a.m.', 'p.m.'], u], [['a.m.', 'p.m.'], u, u], [ ['d', 'l', 'm', 'm', 'j', 'v', 's'], ['dom.', 'lun.', 'mar.', 'mié.', 'jue.', 'vie.', 'sáb.'], ['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'], ['DO', 'LU', 'MA', 'MI', 'JU', 'VI', 'SA'] ], [ ['D', 'L', 'M', 'M', 'J', 'V', 'S'], ['dom.', 'lun.', 'mar.', 'mié.', 'jue.', 'vie.', 'sáb.'], ['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'], ['DO', 'LU', 'MA', 'MI', 'JU', 'VI', 'SA'] ], [ ['E', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], [ 'ene.', 'feb.', 'mar.', 'abr.', 'may.', 'jun.', 'jul.', 'ago.', 'sep.', 'oct.', 'nov.', 'dic.' ], [ 'enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre' ] ], u, [['a. C.', 'd. C.'], u, ['antes de Cristo', 'después de Cristo']], 0, [6, 0], ['d/M/yy', 'd MMM y', 'd \'de\' MMMM \'de\' y', 'EEEE, d \'de\' MMMM \'de\' y'], ['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{1} {0}', u, '{1}, {0}', u], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0 %', '¤#,##0.00', '#E0'], '$', 'dólar beliceño', { 'AUD': [u, '$'], 'BRL': [u, 'R$'], 'BZD': ['$'], 'CAD': [u, '$'], 'CNY': [u, '¥'], 'ESP': ['₧'], 'EUR': [u, '€'], 'FKP': [u, 'FK£'], 'GBP': [u, '£'], 'HKD': [u, '$'], 'ILS': [u, '₪'], 'INR': [u, '₹'], 'JPY': [u, '¥'], 'KRW': [u, '₩'], 'MXN': [u, '$'], 'NZD': [u, '$'], 'RON': [u, 'L'], 'SSP': [u, 'SD£'], 'SYP': [u, 'S£'], 'TWD': [u, 'NT$'], 'USD': [u, '$'], 'VEF': [u, 'BsF'], 'VND': [u, '₫'], 'XAF': [], 'XCD': [u, '$'], 'XOF': [] }, plural ];
packages/common/locales/es-BZ.ts
0
https://github.com/angular/angular/commit/e1146f3d066e653b9b40799cc436034e44af9160
[ 0.00017555197700858116, 0.0001727768685668707, 0.00016756770492065698, 0.00017405071412213147, 0.000002636845692904899 ]
{ "id": 0, "code_window": [ " }\n", "\n", " if (withFieldConfig) {\n", " // Apply field defaults & overrides\n", " const fieldConfig = this.dataConfigSource.getFieldOverrideOptions();\n", " if (fieldConfig) {\n", " processedData = {\n", " ...processedData,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const timeZone = data.request?.timezone ?? 'browser';\n", "\n" ], "file_path": "public/app/features/dashboard/state/PanelQueryRunner.ts", "type": "add", "edit_start_line_idx": 95 }
// Libraries import { cloneDeep } from 'lodash'; import { ReplaySubject, Unsubscribable, Observable } from 'rxjs'; import { map } from 'rxjs/operators'; // Services & Utils import { getDatasourceSrv } from 'app/features/plugins/datasource_srv'; import templateSrv from 'app/features/templating/template_srv'; import { runRequest, preProcessPanelData } from './runRequest'; import { runSharedRequest, isSharedDashboardQuery } from '../../../plugins/datasource/dashboard'; // Types import { PanelData, DataQuery, CoreApp, DataQueryRequest, DataSourceApi, DataSourceJsonData, TimeRange, DataTransformerConfig, transformDataFrame, ScopedVars, applyFieldOverrides, DataConfigSource, TimeZone, LoadingState, rangeUtil, } from '@grafana/data'; export interface QueryRunnerOptions< TQuery extends DataQuery = DataQuery, TOptions extends DataSourceJsonData = DataSourceJsonData > { datasource: string | DataSourceApi<TQuery, TOptions> | null; queries: TQuery[]; panelId: number; dashboardId?: number; timezone: TimeZone; timeRange: TimeRange; timeInfo?: string; // String description of time range for display maxDataPoints: number; minInterval: string | undefined | null; scopedVars?: ScopedVars; cacheTimeout?: string; delayStateNotification?: number; // default 100ms. transformations?: DataTransformerConfig[]; } let counter = 100; function getNextRequestId() { return 'Q' + counter++; } export interface GetDataOptions { withTransforms: boolean; withFieldConfig: boolean; } export class PanelQueryRunner { private subject: ReplaySubject<PanelData>; private subscription?: Unsubscribable; private lastResult?: PanelData; private dataConfigSource: DataConfigSource; constructor(dataConfigSource: DataConfigSource) { this.subject = new ReplaySubject(1); this.dataConfigSource = dataConfigSource; } /** * Returns an observable that subscribes to the shared multi-cast subject (that reply last result). */ getData(options: GetDataOptions): Observable<PanelData> { const { withFieldConfig, withTransforms } = options; return this.subject.pipe( map((data: PanelData) => { let processedData = data; // Apply transformation if (withTransforms) { const transformations = this.dataConfigSource.getTransformations(); if (transformations && transformations.length > 0) { processedData = { ...processedData, series: transformDataFrame(transformations, data.series), }; } } if (withFieldConfig) { // Apply field defaults & overrides const fieldConfig = this.dataConfigSource.getFieldOverrideOptions(); if (fieldConfig) { processedData = { ...processedData, series: applyFieldOverrides({ timeZone: data.request!.timezone, autoMinMax: true, data: processedData.series, ...fieldConfig, }), }; } } return processedData; }) ); } async run(options: QueryRunnerOptions) { const { queries, timezone, datasource, panelId, dashboardId, timeRange, timeInfo, cacheTimeout, maxDataPoints, scopedVars, minInterval, } = options; if (isSharedDashboardQuery(datasource)) { this.pipeToSubject(runSharedRequest(options)); return; } const request: DataQueryRequest = { app: CoreApp.Dashboard, requestId: getNextRequestId(), timezone, panelId, dashboardId, range: timeRange, timeInfo, interval: '', intervalMs: 0, targets: cloneDeep(queries), maxDataPoints: maxDataPoints, scopedVars: scopedVars || {}, cacheTimeout, startTime: Date.now(), }; // Add deprecated property (request as any).rangeRaw = timeRange.raw; try { const ds = await getDataSource(datasource, request.scopedVars); // Attach the datasource name to each query request.targets = request.targets.map(query => { if (!query.datasource) { query.datasource = ds.name; } return query; }); const lowerIntervalLimit = minInterval ? templateSrv.replace(minInterval, request.scopedVars) : ds.interval; const norm = rangeUtil.calculateInterval(timeRange, maxDataPoints, lowerIntervalLimit); // make shallow copy of scoped vars, // and add built in variables interval and interval_ms request.scopedVars = Object.assign({}, request.scopedVars, { __interval: { text: norm.interval, value: norm.interval }, __interval_ms: { text: norm.intervalMs.toString(), value: norm.intervalMs }, }); request.interval = norm.interval; request.intervalMs = norm.intervalMs; this.pipeToSubject(runRequest(ds, request)); } catch (err) { console.error('PanelQueryRunner Error', err); } } private pipeToSubject(observable: Observable<PanelData>) { if (this.subscription) { this.subscription.unsubscribe(); } this.subscription = observable.subscribe({ next: (data: PanelData) => { this.lastResult = preProcessPanelData(data, this.lastResult); // Store preprocessed query results for applying overrides later on in the pipeline this.subject.next(this.lastResult); }, }); } cancelQuery() { if (!this.subscription) { return; } this.subscription.unsubscribe(); // If we have an old result with loading state, send it with done state if (this.lastResult && this.lastResult.state === LoadingState.Loading) { this.subject.next({ ...this.lastResult, state: LoadingState.Done, }); } } resendLastResult = () => { if (this.lastResult) { this.subject.next(this.lastResult); } }; /** * Called when the panel is closed */ destroy() { // Tell anyone listening that we are done if (this.subject) { this.subject.complete(); } if (this.subscription) { this.subscription.unsubscribe(); } } useLastResultFrom(runner: PanelQueryRunner) { this.lastResult = runner.getLastResult(); if (this.lastResult) { // The subject is a replay subject so anyone subscribing will get this last result this.subject.next(this.lastResult); } } getLastResult(): PanelData | undefined { return this.lastResult; } } async function getDataSource( datasource: string | DataSourceApi | null, scopedVars: ScopedVars ): Promise<DataSourceApi> { if (datasource && (datasource as any).query) { return datasource as DataSourceApi; } return await getDatasourceSrv().get(datasource as string, scopedVars); }
public/app/features/dashboard/state/PanelQueryRunner.ts
1
https://github.com/grafana/grafana/commit/31e2b7e7c82870294b0a2c96a5740eb07969ec60
[ 0.9990655779838562, 0.11072693765163422, 0.0001624773140065372, 0.000172218176885508, 0.30439770221710205 ]
{ "id": 0, "code_window": [ " }\n", "\n", " if (withFieldConfig) {\n", " // Apply field defaults & overrides\n", " const fieldConfig = this.dataConfigSource.getFieldOverrideOptions();\n", " if (fieldConfig) {\n", " processedData = {\n", " ...processedData,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const timeZone = data.request?.timezone ?? 'browser';\n", "\n" ], "file_path": "public/app/features/dashboard/state/PanelQueryRunner.ts", "type": "add", "edit_start_line_idx": 95 }
+++ # ----------------------------------------------------------------------- # Do not edit this file. It is automatically generated by API Documenter. # ----------------------------------------------------------------------- title = "KeyValue" keywords = ["grafana","documentation","sdk","@grafana/data"] type = "docs" +++ ## KeyValue type ### KeyValue type <b>Signature</b> ```typescript export declare type KeyValue<T = any> = { [s: string]: T; }; ``` <b>Import</b> ```typescript import { KeyValue } from '@grafana/data'; ```
docs/sources/packages_api/data/keyvalue.md
0
https://github.com/grafana/grafana/commit/31e2b7e7c82870294b0a2c96a5740eb07969ec60
[ 0.00017796523752622306, 0.00017343013314530253, 0.00016902625793591142, 0.00017329890397377312, 0.0000036505027765088016 ]
{ "id": 0, "code_window": [ " }\n", "\n", " if (withFieldConfig) {\n", " // Apply field defaults & overrides\n", " const fieldConfig = this.dataConfigSource.getFieldOverrideOptions();\n", " if (fieldConfig) {\n", " processedData = {\n", " ...processedData,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const timeZone = data.request?.timezone ?? 'browser';\n", "\n" ], "file_path": "public/app/features/dashboard/state/PanelQueryRunner.ts", "type": "add", "edit_start_line_idx": 95 }
import _ from 'lodash'; import coreModule from 'app/core/core_module'; // @ts-ignore import Drop from 'tether-drop'; export function infoPopover() { return { restrict: 'E', template: `<icon name="'info-circle'" style="margin-left: 10px;" size="'xs'"></icon>`, transclude: true, link: (scope: any, elem: any, attrs: any, ctrl: any, transclude: any) => { const offset = attrs.offset || '0 -10px'; const position = attrs.position || 'right middle'; let classes = 'drop-help drop-hide-out-of-bounds'; const openOn = 'hover'; elem.addClass('gf-form-help-icon'); if (attrs.wide) { classes += ' drop-wide'; } if (attrs.mode) { elem.addClass('gf-form-help-icon--' + attrs.mode); } transclude((clone: any, newScope: any) => { const content = document.createElement('div'); content.className = 'markdown-html'; _.each(clone, node => { content.appendChild(node); }); const dropOptions = { target: elem[0], content: content, position: position, classes: classes, openOn: openOn, hoverOpenDelay: 400, tetherOptions: { offset: offset, constraints: [ { to: 'window', attachment: 'together', pin: true, }, ], }, }; // Create drop in next digest after directive content is rendered. scope.$applyAsync(() => { const drop = new Drop(dropOptions); const unbind = scope.$on('$destroy', () => { drop.destroy(); unbind(); }); }); }); }, }; } coreModule.directive('infoPopover', infoPopover);
public/app/core/components/info_popover.ts
0
https://github.com/grafana/grafana/commit/31e2b7e7c82870294b0a2c96a5740eb07969ec60
[ 0.00017485316493548453, 0.0001696414838079363, 0.00016575214976910502, 0.00016932451399043202, 0.0000027906071409233846 ]
{ "id": 0, "code_window": [ " }\n", "\n", " if (withFieldConfig) {\n", " // Apply field defaults & overrides\n", " const fieldConfig = this.dataConfigSource.getFieldOverrideOptions();\n", " if (fieldConfig) {\n", " processedData = {\n", " ...processedData,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const timeZone = data.request?.timezone ?? 'browser';\n", "\n" ], "file_path": "public/app/features/dashboard/state/PanelQueryRunner.ts", "type": "add", "edit_start_line_idx": 95 }
Format the legend keys any way you want by using alias patterns. - Example for Azure Monitor: `dimension: {{dimensionvalue}}` - Example for Application Insights: `server: {{groupbyvalue}}` #### Alias Patterns for Application Insights - {{groupbyvalue}} = replaced with the value of the group by - {{groupbyname}} = replaced with the name/label of the group by - {{metric}} = replaced with metric name (e.g. requests/count) #### Alias Patterns for Azure Monitor - {{resourcegroup}} = replaced with the value of the Resource Group - {{namespace}} = replaced with the value of the Namespace (e.g. Microsoft.Compute/virtualMachines) - {{resourcename}} = replaced with the value of the Resource Name - {{metric}} = replaced with metric name (e.g. Percentage CPU) - {{dimensionname}} = replaced with dimension key/label (e.g. blobtype) - {{dimensionvalue}} = replaced with dimension value (e.g. BlockBlob) #### Filter Expressions for Application Insights The filter field takes an OData filter expression. Examples: - `client/city eq 'Boydton'` - `client/city ne 'Boydton'` - `client/city ne 'Boydton' and client/city ne 'Dublin'` - `client/city eq 'Boydton' or client/city eq 'Dublin'` #### Writing Queries for Template Variables See the [docs](https://github.com/grafana/azure-monitor-datasource#templating-with-variables) for details and examples.
public/app/plugins/datasource/grafana-azure-monitor-datasource/query_help.md
0
https://github.com/grafana/grafana/commit/31e2b7e7c82870294b0a2c96a5740eb07969ec60
[ 0.00016917959146667272, 0.0001654792868066579, 0.00015866132162045687, 0.00016703811706975102, 0.000004045952664455399 ]
{ "id": 1, "code_window": [ " if (fieldConfig) {\n", " processedData = {\n", " ...processedData,\n", " series: applyFieldOverrides({\n", " timeZone: data.request!.timezone,\n", " autoMinMax: true,\n", " data: processedData.series,\n", " ...fieldConfig,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " timeZone: timeZone,\n" ], "file_path": "public/app/features/dashboard/state/PanelQueryRunner.ts", "type": "replace", "edit_start_line_idx": 99 }
import { Observable } from 'rxjs'; import { QueryRunnerOptions } from 'app/features/dashboard/state/PanelQueryRunner'; import { DashboardQuery, SHARED_DASHBODARD_QUERY } from './types'; import { getDashboardSrv } from 'app/features/dashboard/services/DashboardSrv'; import { LoadingState, DefaultTimeRange, DataQuery, PanelData, DataSourceApi } from '@grafana/data'; export function isSharedDashboardQuery(datasource: string | DataSourceApi | null) { if (!datasource) { // default datasource return false; } if (datasource === SHARED_DASHBODARD_QUERY) { return true; } const ds = datasource as DataSourceApi; return ds.meta && ds.meta.name === SHARED_DASHBODARD_QUERY; } export function runSharedRequest(options: QueryRunnerOptions): Observable<PanelData> { return new Observable<PanelData>(subscriber => { const dashboard = getDashboardSrv().getCurrent(); const listenToPanelId = getPanelIdFromQuery(options.queries); if (!listenToPanelId) { subscriber.next(getQueryError('Missing panel reference ID')); return undefined; } const listenToPanel = dashboard.getPanelById(listenToPanelId); if (!listenToPanel) { subscriber.next(getQueryError('Unknown Panel: ' + listenToPanelId)); return undefined; } const listenToRunner = listenToPanel.getQueryRunner(); const subscription = listenToRunner.getData({ withTransforms: false, withFieldConfig: false }).subscribe({ next: (data: PanelData) => { subscriber.next(data); }, }); // If we are in fullscreen the other panel will not execute any queries // So we have to trigger it from here if (!listenToPanel.isInView) { const { datasource, targets } = listenToPanel; const modified = { ...options, datasource, panelId: listenToPanelId, queries: targets, }; listenToRunner.run(modified); } return () => { subscription.unsubscribe(); }; }); } function getPanelIdFromQuery(queries: DataQuery[]): number | undefined { if (!queries || !queries.length) { return undefined; } return (queries[0] as DashboardQuery).panelId; } function getQueryError(msg: string): PanelData { return { state: LoadingState.Error, series: [], error: { message: msg }, timeRange: DefaultTimeRange, }; }
public/app/plugins/datasource/dashboard/runSharedRequest.ts
1
https://github.com/grafana/grafana/commit/31e2b7e7c82870294b0a2c96a5740eb07969ec60
[ 0.00017359941557515413, 0.0001693827216513455, 0.00016453211719635874, 0.00016933601000346243, 0.000002741388016147539 ]
{ "id": 1, "code_window": [ " if (fieldConfig) {\n", " processedData = {\n", " ...processedData,\n", " series: applyFieldOverrides({\n", " timeZone: data.request!.timezone,\n", " autoMinMax: true,\n", " data: processedData.series,\n", " ...fieldConfig,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " timeZone: timeZone,\n" ], "file_path": "public/app/features/dashboard/state/PanelQueryRunner.ts", "type": "replace", "edit_start_line_idx": 99 }
#!/bin/bash # When not limiting the open file descriptors limit, the memory consumption of # slapd is absurdly high. See https://github.com/docker/docker/issues/8231 ulimit -n 8192 set -e chown -R openldap:openldap /var/lib/ldap/ if [[ ! -d /etc/ldap/slapd.d ]]; then if [[ -z "$SLAPD_PASSWORD" ]]; then echo -n >&2 "Error: Container not configured and SLAPD_PASSWORD not set. " echo >&2 "Did you forget to add -e SLAPD_PASSWORD=... ?" exit 1 fi if [[ -z "$SLAPD_DOMAIN" ]]; then echo -n >&2 "Error: Container not configured and SLAPD_DOMAIN not set. " echo >&2 "Did you forget to add -e SLAPD_DOMAIN=... ?" exit 1 fi SLAPD_ORGANIZATION="${SLAPD_ORGANIZATION:-${SLAPD_DOMAIN}}" cp -a /etc/ldap.dist/* /etc/ldap cat <<-EOF | debconf-set-selections slapd slapd/no_configuration boolean false slapd slapd/password1 password $SLAPD_PASSWORD slapd slapd/password2 password $SLAPD_PASSWORD slapd shared/organization string $SLAPD_ORGANIZATION slapd slapd/domain string $SLAPD_DOMAIN slapd slapd/backend select HDB slapd slapd/allow_ldap_v2 boolean false slapd slapd/purge_database boolean false slapd slapd/move_old_database boolean true EOF dpkg-reconfigure -f noninteractive slapd >/dev/null 2>&1 dc_string="" IFS="."; declare -a dc_parts=($SLAPD_DOMAIN) for dc_part in "${dc_parts[@]}"; do dc_string="$dc_string,dc=$dc_part" done base_string="BASE ${dc_string:1}" sed -i "s/^#BASE.*/${base_string}/g" /etc/ldap/ldap.conf if [[ -n "$SLAPD_CONFIG_PASSWORD" ]]; then password_hash=`slappasswd -s "${SLAPD_CONFIG_PASSWORD}"` sed_safe_password_hash=${password_hash//\//\\\/} slapcat -n0 -F /etc/ldap/slapd.d -l /tmp/config.ldif sed -i "s/\(olcRootDN: cn=admin,cn=config\)/\1\nolcRootPW: ${sed_safe_password_hash}/g" /tmp/config.ldif rm -rf /etc/ldap/slapd.d/* slapadd -n0 -F /etc/ldap/slapd.d -l /tmp/config.ldif >/dev/null 2>&1 fi if [[ -n "$SLAPD_ADDITIONAL_SCHEMAS" ]]; then IFS=","; declare -a schemas=($SLAPD_ADDITIONAL_SCHEMAS); unset IFS for schema in "${schemas[@]}"; do slapadd -n0 -F /etc/ldap/slapd.d -l "/etc/ldap/schema/${schema}.ldif" >/dev/null 2>&1 done fi if [[ -n "$SLAPD_ADDITIONAL_MODULES" ]]; then IFS=","; declare -a modules=($SLAPD_ADDITIONAL_MODULES); unset IFS for module in "${modules[@]}"; do echo "Adding module ${module}" slapadd -n0 -F /etc/ldap/slapd.d -l "/etc/ldap/modules/${module}.ldif" >/dev/null 2>&1 done fi # This needs to run in background # Will prepopulate entries after ldap daemon has started ./prepopulate.sh & chown -R openldap:openldap /etc/ldap/slapd.d/ /var/lib/ldap/ /var/run/slapd/ else slapd_configs_in_env=`env | grep 'SLAPD_'` if [ -n "${slapd_configs_in_env:+x}" ]; then echo "Info: Container already configured, therefore ignoring SLAPD_xxx environment variables" fi fi exec "$@"
devenv/docker/blocks/multiple-openldap/entrypoint.sh
0
https://github.com/grafana/grafana/commit/31e2b7e7c82870294b0a2c96a5740eb07969ec60
[ 0.00017536173982080072, 0.00017058462253771722, 0.000166446014191024, 0.00017102494894061238, 0.000002392485384916654 ]
{ "id": 1, "code_window": [ " if (fieldConfig) {\n", " processedData = {\n", " ...processedData,\n", " series: applyFieldOverrides({\n", " timeZone: data.request!.timezone,\n", " autoMinMax: true,\n", " data: processedData.series,\n", " ...fieldConfig,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " timeZone: timeZone,\n" ], "file_path": "public/app/features/dashboard/state/PanelQueryRunner.ts", "type": "replace", "edit_start_line_idx": 99 }
import coreModule from 'app/core/core_module'; import templateSrv from './template_srv'; coreModule.factory('templateSrv', () => templateSrv);
public/app/features/templating/all.ts
0
https://github.com/grafana/grafana/commit/31e2b7e7c82870294b0a2c96a5740eb07969ec60
[ 0.0001728024217300117, 0.0001728024217300117, 0.0001728024217300117, 0.0001728024217300117, 0 ]
{ "id": 1, "code_window": [ " if (fieldConfig) {\n", " processedData = {\n", " ...processedData,\n", " series: applyFieldOverrides({\n", " timeZone: data.request!.timezone,\n", " autoMinMax: true,\n", " data: processedData.series,\n", " ...fieldConfig,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " timeZone: timeZone,\n" ], "file_path": "public/app/features/dashboard/state/PanelQueryRunner.ts", "type": "replace", "edit_start_line_idx": 99 }
import { uiSegmentSrv } from 'app/core/services/segment_srv'; import gfunc from '../gfunc'; import { GraphiteQueryCtrl } from '../query_ctrl'; import { TemplateSrvStub } from 'test/specs/helpers'; jest.mock('app/core/utils/promiseToDigest', () => ({ promiseToDigest: (scope: any) => { return (p: Promise<any>) => p; }, })); describe('GraphiteQueryCtrl', () => { const ctx = { datasource: { metricFindQuery: jest.fn(() => Promise.resolve([])), getFuncDefs: jest.fn(() => Promise.resolve(gfunc.getFuncDefs('1.0'))), getFuncDef: gfunc.getFuncDef, waitForFuncDefsLoaded: jest.fn(() => Promise.resolve(null)), createFuncInstance: gfunc.createFuncInstance, }, target: { target: 'aliasByNode(scaleToSeconds(test.prod.*,1),2)' }, panelCtrl: { refresh: jest.fn(), }, } as any; ctx.panelCtrl.panel = { targets: [ctx.target], }; beforeEach(() => { GraphiteQueryCtrl.prototype.target = ctx.target; GraphiteQueryCtrl.prototype.datasource = ctx.datasource; GraphiteQueryCtrl.prototype.panelCtrl = ctx.panelCtrl; ctx.ctrl = new GraphiteQueryCtrl( {}, {} as any, //@ts-ignore new uiSegmentSrv({ trustAsHtml: html => html }, { highlightVariablesAsHtml: () => {} }), //@ts-ignore new TemplateSrvStub(), {} ); }); describe('init', () => { it('should validate metric key exists', () => { expect(ctx.datasource.metricFindQuery.mock.calls[0][0]).toBe('test.prod.*'); }); it('should not delete last segment if no metrics are found', () => { expect(ctx.ctrl.segments[2].value).not.toBe('select metric'); expect(ctx.ctrl.segments[2].value).toBe('*'); }); it('should parse expression and build function model', () => { expect(ctx.ctrl.queryModel.functions.length).toBe(2); }); }); describe('when toggling edit mode to raw and back again', () => { beforeEach(() => { ctx.ctrl.toggleEditorMode(); ctx.ctrl.toggleEditorMode(); }); it('should validate metric key exists', () => { const lastCallIndex = ctx.datasource.metricFindQuery.mock.calls.length - 1; expect(ctx.datasource.metricFindQuery.mock.calls[lastCallIndex][0]).toBe('test.prod.*'); }); it('should delete last segment if no metrics are found', () => { expect(ctx.ctrl.segments[0].value).toBe('test'); expect(ctx.ctrl.segments[1].value).toBe('prod'); expect(ctx.ctrl.segments[2].value).toBe('select metric'); }); it('should parse expression and build function model', () => { expect(ctx.ctrl.queryModel.functions.length).toBe(2); }); }); describe('when middle segment value of test.prod.* is changed', () => { beforeEach(() => { const segment = { type: 'segment', value: 'test', expandable: true }; ctx.ctrl.segmentValueChanged(segment, 1); }); it('should validate metric key exists', () => { const lastCallIndex = ctx.datasource.metricFindQuery.mock.calls.length - 1; expect(ctx.datasource.metricFindQuery.mock.calls[lastCallIndex][0]).toBe('test.test.*'); }); it('should delete last segment if no metrics are found', () => { expect(ctx.ctrl.segments[0].value).toBe('test'); expect(ctx.ctrl.segments[1].value).toBe('test'); expect(ctx.ctrl.segments[2].value).toBe('select metric'); }); it('should parse expression and build function model', () => { expect(ctx.ctrl.queryModel.functions.length).toBe(2); }); }); describe('when adding function', () => { beforeEach(() => { ctx.ctrl.target.target = 'test.prod.*.count'; ctx.ctrl.datasource.metricFindQuery = () => Promise.resolve([{ expandable: false }]); ctx.ctrl.parseTarget(); ctx.ctrl.addFunction(gfunc.getFuncDef('aliasByNode')); }); it('should add function with correct node number', () => { expect(ctx.ctrl.queryModel.functions[0].params[0]).toBe(2); }); it('should update target', () => { expect(ctx.ctrl.target.target).toBe('aliasByNode(test.prod.*.count, 2)'); }); it('should call refresh', () => { expect(ctx.panelCtrl.refresh).toHaveBeenCalled(); }); }); describe('when adding function before any metric segment', () => { beforeEach(() => { ctx.ctrl.target.target = ''; ctx.ctrl.datasource.metricFindQuery = () => Promise.resolve([{ expandable: true }]); ctx.ctrl.parseTarget(); ctx.ctrl.addFunction(gfunc.getFuncDef('asPercent')); }); it('should add function and remove select metric link', () => { expect(ctx.ctrl.segments.length).toBe(0); }); }); describe('when initializing a target with single param func using variable', () => { beforeEach(() => { ctx.ctrl.target.target = 'movingAverage(prod.count, $var)'; ctx.ctrl.datasource.metricFindQuery = () => Promise.resolve([]); ctx.ctrl.parseTarget(); }); it('should add 2 segments', () => { expect(ctx.ctrl.segments.length).toBe(2); }); it('should add function param', () => { expect(ctx.ctrl.queryModel.functions[0].params.length).toBe(1); }); }); describe('when initializing target without metric expression and function with series-ref', () => { beforeEach(() => { ctx.ctrl.target.target = 'asPercent(metric.node.count, #A)'; ctx.ctrl.datasource.metricFindQuery = () => Promise.resolve([]); ctx.ctrl.parseTarget(); }); it('should add segments', () => { expect(ctx.ctrl.segments.length).toBe(3); }); it('should have correct func params', () => { expect(ctx.ctrl.queryModel.functions[0].params.length).toBe(1); }); }); describe('when getting altSegments and metricFindQuery returns empty array', () => { beforeEach(() => { ctx.ctrl.target.target = 'test.count'; ctx.ctrl.datasource.metricFindQuery = () => Promise.resolve([]); ctx.ctrl.parseTarget(); ctx.ctrl.getAltSegments(1).then((results: any) => { ctx.altSegments = results; }); }); it('should have no segments', () => { expect(ctx.altSegments.length).toBe(0); }); }); describe('targetChanged', () => { beforeEach(() => { ctx.ctrl.target.target = 'aliasByNode(scaleToSeconds(test.prod.*, 1), 2)'; ctx.ctrl.datasource.metricFindQuery = () => Promise.resolve([{ expandable: false }]); ctx.ctrl.parseTarget(); ctx.ctrl.target.target = ''; ctx.ctrl.targetChanged(); }); it('should rebuild target after expression model', () => { expect(ctx.ctrl.target.target).toBe('aliasByNode(scaleToSeconds(test.prod.*, 1), 2)'); }); it('should call panelCtrl.refresh', () => { expect(ctx.panelCtrl.refresh).toHaveBeenCalled(); }); }); describe('when updating targets with nested query', () => { beforeEach(() => { ctx.ctrl.target.target = 'scaleToSeconds(#A, 60)'; ctx.ctrl.datasource.metricFindQuery = () => Promise.resolve([{ expandable: false }]); ctx.ctrl.parseTarget(); }); it('should add function params', () => { expect(ctx.ctrl.queryModel.segments.length).toBe(1); expect(ctx.ctrl.queryModel.segments[0].value).toBe('#A'); expect(ctx.ctrl.queryModel.functions[0].params.length).toBe(1); expect(ctx.ctrl.queryModel.functions[0].params[0]).toBe(60); }); it('target should remain the same', () => { expect(ctx.ctrl.target.target).toBe('scaleToSeconds(#A, 60)'); }); it('targetFull should include nested queries', () => { ctx.ctrl.panelCtrl.panel.targets = [ { target: 'nested.query.count', refId: 'A', }, ]; ctx.ctrl.updateModelTarget(); expect(ctx.ctrl.target.target).toBe('scaleToSeconds(#A, 60)'); expect(ctx.ctrl.target.targetFull).toBe('scaleToSeconds(nested.query.count, 60)'); }); }); describe('when updating target used in other query', () => { beforeEach(() => { ctx.ctrl.target.target = 'metrics.a.count'; ctx.ctrl.target.refId = 'A'; ctx.ctrl.datasource.metricFindQuery = () => Promise.resolve([{ expandable: false }]); ctx.ctrl.parseTarget(); ctx.ctrl.panelCtrl.panel.targets = [ctx.ctrl.target, { target: 'sumSeries(#A)', refId: 'B' }]; ctx.ctrl.updateModelTarget(); }); it('targetFull of other query should update', () => { expect(ctx.ctrl.panel.targets[1].targetFull).toBe('sumSeries(metrics.a.count)'); }); }); describe('when adding seriesByTag function', () => { beforeEach(() => { ctx.ctrl.target.target = ''; ctx.ctrl.datasource.metricFindQuery = () => Promise.resolve([{ expandable: false }]); ctx.ctrl.parseTarget(); ctx.ctrl.addFunction(gfunc.getFuncDef('seriesByTag')); }); it('should update functions', () => { expect(ctx.ctrl.queryModel.getSeriesByTagFuncIndex()).toBe(0); }); it('should update seriesByTagUsed flag', () => { expect(ctx.ctrl.queryModel.seriesByTagUsed).toBe(true); }); it('should update target', () => { expect(ctx.ctrl.target.target).toBe('seriesByTag()'); }); it('should call refresh', () => { expect(ctx.panelCtrl.refresh).toHaveBeenCalled(); }); }); describe('when parsing seriesByTag function', () => { beforeEach(() => { ctx.ctrl.target.target = "seriesByTag('tag1=value1', 'tag2!=~value2')"; ctx.ctrl.datasource.metricFindQuery = () => Promise.resolve([{ expandable: false }]); ctx.ctrl.parseTarget(); }); it('should add tags', () => { const expected = [ { key: 'tag1', operator: '=', value: 'value1' }, { key: 'tag2', operator: '!=~', value: 'value2' }, ]; expect(ctx.ctrl.queryModel.tags).toEqual(expected); }); it('should add plus button', () => { expect(ctx.ctrl.addTagSegments.length).toBe(1); }); }); describe('when tag added', () => { beforeEach(() => { ctx.ctrl.target.target = 'seriesByTag()'; ctx.ctrl.datasource.metricFindQuery = () => Promise.resolve([{ expandable: false }]); ctx.ctrl.parseTarget(); ctx.ctrl.addNewTag({ value: 'tag1' }); }); it('should update tags with default value', () => { const expected = [{ key: 'tag1', operator: '=', value: '' }]; expect(ctx.ctrl.queryModel.tags).toEqual(expected); }); it('should update target', () => { const expected = "seriesByTag('tag1=')"; expect(ctx.ctrl.target.target).toEqual(expected); }); }); describe('when tag changed', () => { beforeEach(() => { ctx.ctrl.target.target = "seriesByTag('tag1=value1', 'tag2!=~value2')"; ctx.ctrl.datasource.metricFindQuery = () => Promise.resolve([{ expandable: false }]); ctx.ctrl.parseTarget(); ctx.ctrl.tagChanged({ key: 'tag1', operator: '=', value: 'new_value' }, 0); }); it('should update tags', () => { const expected = [ { key: 'tag1', operator: '=', value: 'new_value' }, { key: 'tag2', operator: '!=~', value: 'value2' }, ]; expect(ctx.ctrl.queryModel.tags).toEqual(expected); }); it('should update target', () => { const expected = "seriesByTag('tag1=new_value', 'tag2!=~value2')"; expect(ctx.ctrl.target.target).toEqual(expected); }); }); describe('when tag removed', () => { beforeEach(() => { ctx.ctrl.target.target = "seriesByTag('tag1=value1', 'tag2!=~value2')"; ctx.ctrl.datasource.metricFindQuery = () => Promise.resolve([{ expandable: false }]); ctx.ctrl.parseTarget(); ctx.ctrl.tagChanged({ key: ctx.ctrl.removeTagValue }); }); it('should update tags', () => { const expected = [{ key: 'tag2', operator: '!=~', value: 'value2' }]; expect(ctx.ctrl.queryModel.tags).toEqual(expected); }); it('should update target', () => { const expected = "seriesByTag('tag2!=~value2')"; expect(ctx.ctrl.target.target).toEqual(expected); }); }); });
public/app/plugins/datasource/graphite/specs/query_ctrl.test.ts
0
https://github.com/grafana/grafana/commit/31e2b7e7c82870294b0a2c96a5740eb07969ec60
[ 0.00017480066162534058, 0.0001711373624857515, 0.00016614742344245315, 0.00017134037625510246, 0.0000019535550563887227 ]
{ "id": 2, "code_window": [ "import { Observable } from 'rxjs';\n", "import { QueryRunnerOptions } from 'app/features/dashboard/state/PanelQueryRunner';\n", "import { DashboardQuery, SHARED_DASHBODARD_QUERY } from './types';\n", "import { getDashboardSrv } from 'app/features/dashboard/services/DashboardSrv';\n", "import { LoadingState, DefaultTimeRange, DataQuery, PanelData, DataSourceApi } from '@grafana/data';\n", "\n", "export function isSharedDashboardQuery(datasource: string | DataSourceApi | null) {\n", " if (!datasource) {\n", " // default datasource\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { LoadingState, DefaultTimeRange, DataQuery, PanelData, DataSourceApi, DataQueryRequest } from '@grafana/data';\n" ], "file_path": "public/app/plugins/datasource/dashboard/runSharedRequest.ts", "type": "replace", "edit_start_line_idx": 4 }
import { Observable } from 'rxjs'; import { QueryRunnerOptions } from 'app/features/dashboard/state/PanelQueryRunner'; import { DashboardQuery, SHARED_DASHBODARD_QUERY } from './types'; import { getDashboardSrv } from 'app/features/dashboard/services/DashboardSrv'; import { LoadingState, DefaultTimeRange, DataQuery, PanelData, DataSourceApi } from '@grafana/data'; export function isSharedDashboardQuery(datasource: string | DataSourceApi | null) { if (!datasource) { // default datasource return false; } if (datasource === SHARED_DASHBODARD_QUERY) { return true; } const ds = datasource as DataSourceApi; return ds.meta && ds.meta.name === SHARED_DASHBODARD_QUERY; } export function runSharedRequest(options: QueryRunnerOptions): Observable<PanelData> { return new Observable<PanelData>(subscriber => { const dashboard = getDashboardSrv().getCurrent(); const listenToPanelId = getPanelIdFromQuery(options.queries); if (!listenToPanelId) { subscriber.next(getQueryError('Missing panel reference ID')); return undefined; } const listenToPanel = dashboard.getPanelById(listenToPanelId); if (!listenToPanel) { subscriber.next(getQueryError('Unknown Panel: ' + listenToPanelId)); return undefined; } const listenToRunner = listenToPanel.getQueryRunner(); const subscription = listenToRunner.getData({ withTransforms: false, withFieldConfig: false }).subscribe({ next: (data: PanelData) => { subscriber.next(data); }, }); // If we are in fullscreen the other panel will not execute any queries // So we have to trigger it from here if (!listenToPanel.isInView) { const { datasource, targets } = listenToPanel; const modified = { ...options, datasource, panelId: listenToPanelId, queries: targets, }; listenToRunner.run(modified); } return () => { subscription.unsubscribe(); }; }); } function getPanelIdFromQuery(queries: DataQuery[]): number | undefined { if (!queries || !queries.length) { return undefined; } return (queries[0] as DashboardQuery).panelId; } function getQueryError(msg: string): PanelData { return { state: LoadingState.Error, series: [], error: { message: msg }, timeRange: DefaultTimeRange, }; }
public/app/plugins/datasource/dashboard/runSharedRequest.ts
1
https://github.com/grafana/grafana/commit/31e2b7e7c82870294b0a2c96a5740eb07969ec60
[ 0.9970249533653259, 0.1373998522758484, 0.00016464699001517147, 0.004460470750927925, 0.3259899318218231 ]
{ "id": 2, "code_window": [ "import { Observable } from 'rxjs';\n", "import { QueryRunnerOptions } from 'app/features/dashboard/state/PanelQueryRunner';\n", "import { DashboardQuery, SHARED_DASHBODARD_QUERY } from './types';\n", "import { getDashboardSrv } from 'app/features/dashboard/services/DashboardSrv';\n", "import { LoadingState, DefaultTimeRange, DataQuery, PanelData, DataSourceApi } from '@grafana/data';\n", "\n", "export function isSharedDashboardQuery(datasource: string | DataSourceApi | null) {\n", " if (!datasource) {\n", " // default datasource\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { LoadingState, DefaultTimeRange, DataQuery, PanelData, DataSourceApi, DataQueryRequest } from '@grafana/data';\n" ], "file_path": "public/app/plugins/datasource/dashboard/runSharedRequest.ts", "type": "replace", "edit_start_line_idx": 4 }
import includes from 'lodash/includes'; import isDate from 'lodash/isDate'; import { DateTime, dateTime, dateTimeForTimeZone, ISO_8601, isDateTime, DurationUnit } from './moment_wrapper'; import { TimeZone } from '../types/index'; const units: DurationUnit[] = ['y', 'M', 'w', 'd', 'h', 'm', 's']; export function isMathString(text: string | DateTime | Date): boolean { if (!text) { return false; } if (typeof text === 'string' && (text.substring(0, 3) === 'now' || text.includes('||'))) { return true; } else { return false; } } /** * Parses different types input to a moment instance. There is a specific formatting language that can be used * if text arg is string. See unit tests for examples. * @param text * @param roundUp See parseDateMath function. * @param timezone Only string 'utc' is acceptable here, for anything else, local timezone is used. */ export function parse( text?: string | DateTime | Date | null, roundUp?: boolean, timezone?: TimeZone ): DateTime | undefined { if (!text) { return undefined; } if (typeof text !== 'string') { if (isDateTime(text)) { return text; } if (isDate(text)) { return dateTime(text); } // We got some non string which is not a moment nor Date. TS should be able to check for that but not always. return undefined; } else { let time; let mathString = ''; let index; let parseString; if (text.substring(0, 3) === 'now') { time = dateTimeForTimeZone(timezone); mathString = text.substring('now'.length); } else { index = text.indexOf('||'); if (index === -1) { parseString = text; mathString = ''; // nothing else } else { parseString = text.substring(0, index); mathString = text.substring(index + 2); } // We're going to just require ISO8601 timestamps, k? time = dateTime(parseString, ISO_8601); } if (!mathString.length) { return time; } return parseDateMath(mathString, time, roundUp); } } /** * Checks if text is a valid date which in this context means that it is either a Moment instance or it can be parsed * by parse function. See parse function to see what is considered acceptable. * @param text */ export function isValid(text: string | DateTime): boolean { const date = parse(text); if (!date) { return false; } if (isDateTime(date)) { return date.isValid(); } return false; } /** * Parses math part of the time string and shifts supplied time according to that math. See unit tests for examples. * @param mathString * @param time * @param roundUp If true it will round the time to endOf time unit, otherwise to startOf time unit. */ // TODO: Had to revert Andrejs `time: moment.Moment` to `time: any` export function parseDateMath(mathString: string, time: any, roundUp?: boolean): DateTime | undefined { const strippedMathString = mathString.replace(/\s/g, ''); const dateTime = time; let i = 0; const len = strippedMathString.length; while (i < len) { const c = strippedMathString.charAt(i++); let type; let num; let unit; if (c === '/') { type = 0; } else if (c === '+') { type = 1; } else if (c === '-') { type = 2; } else { return undefined; } if (isNaN(parseInt(strippedMathString.charAt(i), 10))) { num = 1; } else if (strippedMathString.length === 2) { num = strippedMathString.charAt(i); } else { const numFrom = i; while (!isNaN(parseInt(strippedMathString.charAt(i), 10))) { i++; if (i > 10) { return undefined; } } num = parseInt(strippedMathString.substring(numFrom, i), 10); } if (type === 0) { // rounding is only allowed on whole, single, units (eg M or 1M, not 0.5M or 2M) if (num !== 1) { return undefined; } } unit = strippedMathString.charAt(i++); if (!includes(units, unit)) { return undefined; } else { if (type === 0) { if (roundUp) { dateTime.endOf(unit); } else { dateTime.startOf(unit); } } else if (type === 1) { dateTime.add(num, unit); } else if (type === 2) { dateTime.subtract(num, unit); } } } return dateTime; }
packages/grafana-data/src/datetime/datemath.ts
0
https://github.com/grafana/grafana/commit/31e2b7e7c82870294b0a2c96a5740eb07969ec60
[ 0.00017512647900730371, 0.00017131856293417513, 0.0001646788587095216, 0.00017237455176655203, 0.0000029665325200767256 ]
{ "id": 2, "code_window": [ "import { Observable } from 'rxjs';\n", "import { QueryRunnerOptions } from 'app/features/dashboard/state/PanelQueryRunner';\n", "import { DashboardQuery, SHARED_DASHBODARD_QUERY } from './types';\n", "import { getDashboardSrv } from 'app/features/dashboard/services/DashboardSrv';\n", "import { LoadingState, DefaultTimeRange, DataQuery, PanelData, DataSourceApi } from '@grafana/data';\n", "\n", "export function isSharedDashboardQuery(datasource: string | DataSourceApi | null) {\n", " if (!datasource) {\n", " // default datasource\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { LoadingState, DefaultTimeRange, DataQuery, PanelData, DataSourceApi, DataQueryRequest } from '@grafana/data';\n" ], "file_path": "public/app/plugins/datasource/dashboard/runSharedRequest.ts", "type": "replace", "edit_start_line_idx": 4 }
#!/bin/bash ## # gget # A script to get and install grafana versions # for usage information see "show_help" below. # latest=$(wget -O - 'https://raw.githubusercontent.com/grafana/grafana/master/latest.json' | jq -r '.stable') canary=$(wget -O - "https://grafana.com/api/grafana/versions" | jq ".items[0].version" | tr -d '"') show_help() { echo "Usage: gget <version>" echo "" echo "where <version> can be:" echo " 1) A version from https://grafana.com/grafana/download (ex x.y.z)" echo " 2) latest (currently $latest)" echo " 3) canary (currently $canary)" echo "" echo " -h, --help: Display this help message" echo "" exit 0 } opts=$(getopt -o h --long help -n 'gget' -- "$@") [ $? -eq 0 ] || { show_help } eval set -- "$opts" while true; do case "$1" in -h | --help) show_help ;; --) shift break ;; *) break ;; esac shift done [ -z "$1" ] && show_help # Make sure the script is being run as root if [ $EUID -ne 0 ]; then echo "This script must be run as root" exit 1 fi ## # MAIN # # Enough setup, let's actually do something # version=$1 if [ "$version" == "latest" ]; then version="$latest" wget -O - "https://dl.grafana.com/oss/release/grafana-${version}.linux-amd64.tar.gz" | tar -C /opt -zxf - elif [ "$version" == "canary" ]; then version="$canary" wget -O - "https://dl.grafana.com/oss/master/grafana-${version}.linux-amd64.tar.gz" | tar -C /opt -zxf - fi /bin/rm -rf /opt/grafana > /dev/null 2>&1 || true ln -s /opt/grafana-${version} /opt/grafana # nohup /opt/grafana/bin/grafana-server -config /opt/grafana/conf/defaults.ini -homepath /opt/grafana >/dev/null 2>&1 &
packages/grafana-toolkit/docker/grafana-plugin-ci-e2e/install/ginstall
0
https://github.com/grafana/grafana/commit/31e2b7e7c82870294b0a2c96a5740eb07969ec60
[ 0.00017651962116360664, 0.00017084844876080751, 0.000165152974659577, 0.00017148017650470138, 0.0000039617784750589635 ]
{ "id": 2, "code_window": [ "import { Observable } from 'rxjs';\n", "import { QueryRunnerOptions } from 'app/features/dashboard/state/PanelQueryRunner';\n", "import { DashboardQuery, SHARED_DASHBODARD_QUERY } from './types';\n", "import { getDashboardSrv } from 'app/features/dashboard/services/DashboardSrv';\n", "import { LoadingState, DefaultTimeRange, DataQuery, PanelData, DataSourceApi } from '@grafana/data';\n", "\n", "export function isSharedDashboardQuery(datasource: string | DataSourceApi | null) {\n", " if (!datasource) {\n", " // default datasource\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { LoadingState, DefaultTimeRange, DataQuery, PanelData, DataSourceApi, DataQueryRequest } from '@grafana/data';\n" ], "file_path": "public/app/plugins/datasource/dashboard/runSharedRequest.ts", "type": "replace", "edit_start_line_idx": 4 }
import React, { PropsWithChildren } from 'react'; import { css, cx } from 'emotion'; import { GrafanaTheme, SelectableValue, getTimeZoneInfo } from '@grafana/data'; import { useTheme } from '../../../themes/ThemeContext'; import { stylesFactory } from '../../../themes/stylesFactory'; import { Icon } from '../../Icon/Icon'; import { TimeZoneOffset } from './TimeZoneOffset'; import { TimeZoneDescription } from './TimeZoneDescription'; import { TimeZoneTitle } from './TimeZoneTitle'; import isString from 'lodash/isString'; interface Props { isFocused: boolean; isSelected: boolean; innerProps: any; data: SelectableZone; } const offsetClassName = 'tz-utc-offset'; export interface SelectableZone extends SelectableValue<string> { searchIndex: string; } export const WideTimeZoneOption: React.FC<PropsWithChildren<Props>> = (props, ref) => { const { children, innerProps, data, isSelected, isFocused } = props; const theme = useTheme(); const styles = getStyles(theme); const timestamp = Date.now(); const containerStyles = cx(styles.container, isFocused && styles.containerFocused); if (!isString(data.value)) { return null; } return ( <div className={containerStyles} {...innerProps} aria-label="Select option"> <div className={cx(styles.leftColumn, styles.row)}> <div className={cx(styles.leftColumn, styles.wideRow)}> <TimeZoneTitle title={children} /> <div className={styles.spacer} /> <TimeZoneDescription info={getTimeZoneInfo(data.value, timestamp)} /> </div> <div className={styles.rightColumn}> <TimeZoneOffset timeZone={data.value} timestamp={timestamp} className={offsetClassName} /> {isSelected && ( <span> <Icon name="check" /> </span> )} </div> </div> </div> ); }; export const CompactTimeZoneOption: React.FC<PropsWithChildren<Props>> = (props, ref) => { const { children, innerProps, data, isSelected, isFocused } = props; const theme = useTheme(); const styles = getStyles(theme); const timestamp = Date.now(); const containerStyles = cx(styles.container, isFocused && styles.containerFocused); if (!isString(data.value)) { return null; } return ( <div className={containerStyles} {...innerProps} aria-label="Select option"> <div className={styles.body}> <div className={styles.row}> <div className={styles.leftColumn}> <TimeZoneTitle title={children} /> </div> <div className={styles.rightColumn}> {isSelected && ( <span> <Icon name="check" /> </span> )} </div> </div> <div className={styles.row}> <div className={styles.leftColumn}> <TimeZoneDescription info={getTimeZoneInfo(data.value, timestamp)} /> </div> <div className={styles.rightColumn}> <TimeZoneOffset timestamp={timestamp} timeZone={data.value} className={offsetClassName} /> </div> </div> </div> </div> ); }; const getStyles = stylesFactory((theme: GrafanaTheme) => { const offsetHoverBg = theme.isDark ? theme.palette.gray05 : theme.palette.white; return { container: css` display: flex; align-items: center; flex-direction: row; flex-shrink: 0; white-space: nowrap; cursor: pointer; border-left: 2px solid transparent; padding: 6px 8px 4px; &:hover { background: ${theme.colors.dropdownOptionHoverBg}; span.${offsetClassName} { background: ${offsetHoverBg}; } } `, containerFocused: css` background: ${theme.colors.dropdownOptionHoverBg}; border-image: linear-gradient(#f05a28 30%, #fbca0a 99%); border-image-slice: 1; border-style: solid; border-top: 0; border-right: 0; border-bottom: 0; border-left-width: 2px; span.${offsetClassName} { background: ${offsetHoverBg}; } `, body: css` display: flex; font-weight: ${theme.typography.weight.semibold}; flex-direction: column; flex-grow: 1; `, row: css` display: flex; flex-direction: row; `, leftColumn: css` flex-grow: 1; text-overflow: ellipsis; `, rightColumn: css` justify-content: flex-end; align-items: center; `, wideRow: css` display: flex; flex-direction: row; align-items: baseline; `, spacer: css` margin-left: 6px; `, }; });
packages/grafana-ui/src/components/TimePicker/TimeZonePicker/TimeZoneOption.tsx
0
https://github.com/grafana/grafana/commit/31e2b7e7c82870294b0a2c96a5740eb07969ec60
[ 0.0001793134433683008, 0.00017426637350581586, 0.0001692956138867885, 0.0001748483336996287, 0.000003379765757927089 ]
{ "id": 3, "code_window": [ " return {\n", " state: LoadingState.Error,\n", " series: [],\n", " error: { message: msg },\n", " timeRange: DefaultTimeRange,\n", " };\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " request: {} as DataQueryRequest,\n" ], "file_path": "public/app/plugins/datasource/dashboard/runSharedRequest.ts", "type": "add", "edit_start_line_idx": 72 }
// Libraries import { cloneDeep } from 'lodash'; import { ReplaySubject, Unsubscribable, Observable } from 'rxjs'; import { map } from 'rxjs/operators'; // Services & Utils import { getDatasourceSrv } from 'app/features/plugins/datasource_srv'; import templateSrv from 'app/features/templating/template_srv'; import { runRequest, preProcessPanelData } from './runRequest'; import { runSharedRequest, isSharedDashboardQuery } from '../../../plugins/datasource/dashboard'; // Types import { PanelData, DataQuery, CoreApp, DataQueryRequest, DataSourceApi, DataSourceJsonData, TimeRange, DataTransformerConfig, transformDataFrame, ScopedVars, applyFieldOverrides, DataConfigSource, TimeZone, LoadingState, rangeUtil, } from '@grafana/data'; export interface QueryRunnerOptions< TQuery extends DataQuery = DataQuery, TOptions extends DataSourceJsonData = DataSourceJsonData > { datasource: string | DataSourceApi<TQuery, TOptions> | null; queries: TQuery[]; panelId: number; dashboardId?: number; timezone: TimeZone; timeRange: TimeRange; timeInfo?: string; // String description of time range for display maxDataPoints: number; minInterval: string | undefined | null; scopedVars?: ScopedVars; cacheTimeout?: string; delayStateNotification?: number; // default 100ms. transformations?: DataTransformerConfig[]; } let counter = 100; function getNextRequestId() { return 'Q' + counter++; } export interface GetDataOptions { withTransforms: boolean; withFieldConfig: boolean; } export class PanelQueryRunner { private subject: ReplaySubject<PanelData>; private subscription?: Unsubscribable; private lastResult?: PanelData; private dataConfigSource: DataConfigSource; constructor(dataConfigSource: DataConfigSource) { this.subject = new ReplaySubject(1); this.dataConfigSource = dataConfigSource; } /** * Returns an observable that subscribes to the shared multi-cast subject (that reply last result). */ getData(options: GetDataOptions): Observable<PanelData> { const { withFieldConfig, withTransforms } = options; return this.subject.pipe( map((data: PanelData) => { let processedData = data; // Apply transformation if (withTransforms) { const transformations = this.dataConfigSource.getTransformations(); if (transformations && transformations.length > 0) { processedData = { ...processedData, series: transformDataFrame(transformations, data.series), }; } } if (withFieldConfig) { // Apply field defaults & overrides const fieldConfig = this.dataConfigSource.getFieldOverrideOptions(); if (fieldConfig) { processedData = { ...processedData, series: applyFieldOverrides({ timeZone: data.request!.timezone, autoMinMax: true, data: processedData.series, ...fieldConfig, }), }; } } return processedData; }) ); } async run(options: QueryRunnerOptions) { const { queries, timezone, datasource, panelId, dashboardId, timeRange, timeInfo, cacheTimeout, maxDataPoints, scopedVars, minInterval, } = options; if (isSharedDashboardQuery(datasource)) { this.pipeToSubject(runSharedRequest(options)); return; } const request: DataQueryRequest = { app: CoreApp.Dashboard, requestId: getNextRequestId(), timezone, panelId, dashboardId, range: timeRange, timeInfo, interval: '', intervalMs: 0, targets: cloneDeep(queries), maxDataPoints: maxDataPoints, scopedVars: scopedVars || {}, cacheTimeout, startTime: Date.now(), }; // Add deprecated property (request as any).rangeRaw = timeRange.raw; try { const ds = await getDataSource(datasource, request.scopedVars); // Attach the datasource name to each query request.targets = request.targets.map(query => { if (!query.datasource) { query.datasource = ds.name; } return query; }); const lowerIntervalLimit = minInterval ? templateSrv.replace(minInterval, request.scopedVars) : ds.interval; const norm = rangeUtil.calculateInterval(timeRange, maxDataPoints, lowerIntervalLimit); // make shallow copy of scoped vars, // and add built in variables interval and interval_ms request.scopedVars = Object.assign({}, request.scopedVars, { __interval: { text: norm.interval, value: norm.interval }, __interval_ms: { text: norm.intervalMs.toString(), value: norm.intervalMs }, }); request.interval = norm.interval; request.intervalMs = norm.intervalMs; this.pipeToSubject(runRequest(ds, request)); } catch (err) { console.error('PanelQueryRunner Error', err); } } private pipeToSubject(observable: Observable<PanelData>) { if (this.subscription) { this.subscription.unsubscribe(); } this.subscription = observable.subscribe({ next: (data: PanelData) => { this.lastResult = preProcessPanelData(data, this.lastResult); // Store preprocessed query results for applying overrides later on in the pipeline this.subject.next(this.lastResult); }, }); } cancelQuery() { if (!this.subscription) { return; } this.subscription.unsubscribe(); // If we have an old result with loading state, send it with done state if (this.lastResult && this.lastResult.state === LoadingState.Loading) { this.subject.next({ ...this.lastResult, state: LoadingState.Done, }); } } resendLastResult = () => { if (this.lastResult) { this.subject.next(this.lastResult); } }; /** * Called when the panel is closed */ destroy() { // Tell anyone listening that we are done if (this.subject) { this.subject.complete(); } if (this.subscription) { this.subscription.unsubscribe(); } } useLastResultFrom(runner: PanelQueryRunner) { this.lastResult = runner.getLastResult(); if (this.lastResult) { // The subject is a replay subject so anyone subscribing will get this last result this.subject.next(this.lastResult); } } getLastResult(): PanelData | undefined { return this.lastResult; } } async function getDataSource( datasource: string | DataSourceApi | null, scopedVars: ScopedVars ): Promise<DataSourceApi> { if (datasource && (datasource as any).query) { return datasource as DataSourceApi; } return await getDatasourceSrv().get(datasource as string, scopedVars); }
public/app/features/dashboard/state/PanelQueryRunner.ts
1
https://github.com/grafana/grafana/commit/31e2b7e7c82870294b0a2c96a5740eb07969ec60
[ 0.000718785566277802, 0.00022143899695947766, 0.00016389545635320246, 0.00017091329209506512, 0.00014128988550510257 ]
{ "id": 3, "code_window": [ " return {\n", " state: LoadingState.Error,\n", " series: [],\n", " error: { message: msg },\n", " timeRange: DefaultTimeRange,\n", " };\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " request: {} as DataQueryRequest,\n" ], "file_path": "public/app/plugins/datasource/dashboard/runSharedRequest.ts", "type": "add", "edit_start_line_idx": 72 }
import { DashboardModel, PanelModel } from '../state'; import { getPanelMenu } from './getPanelMenu'; import { describe } from '../../../../test/lib/common'; describe('getPanelMenu', () => { it('should return the correct panel menu items', () => { const panel = new PanelModel({}); const dashboard = new DashboardModel({}); const menuItems = getPanelMenu(dashboard, panel); expect(menuItems).toMatchInlineSnapshot(` Array [ Object { "iconClassName": "eye", "onClick": [Function], "shortcut": "v", "text": "View", }, Object { "iconClassName": "edit", "onClick": [Function], "shortcut": "e", "text": "Edit", }, Object { "iconClassName": "share-alt", "onClick": [Function], "shortcut": "p s", "text": "Share", }, Object { "iconClassName": "info-circle", "onClick": [Function], "shortcut": "i", "subMenu": Array [ Object { "onClick": [Function], "text": "Panel JSON", }, ], "text": "Inspect", "type": "submenu", }, Object { "iconClassName": "cube", "onClick": [Function], "subMenu": Array [ Object { "onClick": [Function], "shortcut": "p d", "text": "Duplicate", }, Object { "onClick": [Function], "text": "Copy", }, ], "text": "More...", "type": "submenu", }, Object { "text": "", "type": "divider", }, Object { "iconClassName": "trash-alt", "onClick": [Function], "shortcut": "p r", "text": "Remove", }, ] `); }); describe('when panel is in view mode', () => { it('should return the correct panel menu items', () => { const getExtendedMenu = () => [{ text: 'Toggle legend', shortcut: 'p l', click: jest.fn() }]; const ctrl: any = { getExtendedMenu }; const scope: any = { $$childHead: { ctrl } }; const angularComponent: any = { getScope: () => scope }; const panel = new PanelModel({ isViewing: true }); const dashboard = new DashboardModel({}); const menuItems = getPanelMenu(dashboard, panel, angularComponent); expect(menuItems).toMatchInlineSnapshot(` Array [ Object { "iconClassName": "eye", "onClick": [Function], "shortcut": "v", "text": "View", }, Object { "iconClassName": "edit", "onClick": [Function], "shortcut": "e", "text": "Edit", }, Object { "iconClassName": "share-alt", "onClick": [Function], "shortcut": "p s", "text": "Share", }, Object { "iconClassName": "info-circle", "onClick": [Function], "shortcut": "i", "subMenu": Array [ Object { "onClick": [Function], "text": "Panel JSON", }, ], "text": "Inspect", "type": "submenu", }, Object { "iconClassName": "cube", "onClick": [Function], "subMenu": Array [ Object { "href": undefined, "onClick": [Function], "shortcut": "p l", "text": "Toggle legend", }, ], "text": "More...", "type": "submenu", }, Object { "text": "", "type": "divider", }, Object { "iconClassName": "trash-alt", "onClick": [Function], "shortcut": "p r", "text": "Remove", }, ] `); }); }); });
public/app/features/dashboard/utils/getPanelMenu.test.ts
0
https://github.com/grafana/grafana/commit/31e2b7e7c82870294b0a2c96a5740eb07969ec60
[ 0.00017194493557326496, 0.00016906838573049754, 0.00016555865295231342, 0.0001687003532424569, 0.000001651546654102276 ]
{ "id": 3, "code_window": [ " return {\n", " state: LoadingState.Error,\n", " series: [],\n", " error: { message: msg },\n", " timeRange: DefaultTimeRange,\n", " };\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " request: {} as DataQueryRequest,\n" ], "file_path": "public/app/plugins/datasource/dashboard/runSharedRequest.ts", "type": "add", "edit_start_line_idx": 72 }
# Filter variables with regex Using the Regex Query option, you filter the list of options returned by the variable query or modify the options returned. This page shows how to use regex to filter/modify values in the variable dropdown Using the Regex Query Option, you filter the list of options returned by the Variable query or modify the options returned. For more information, refer to the Mozilla guide on [Regular expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions). Examples of filtering on the following list of options: ```text backend_01 backend_02 backend_03 backend_04 ``` ## Filter so that only the options that end with `01` or `02` are returned: Regex: ```regex /.*[01|02]/ ``` Result: ```text backend_01 backend_02 ``` ## Filter and modify the options using a regex capture group to return part of the text: Regex: ```regex /.*(01|02)/ ``` Result: ```text 01 02 ``` ## Filter and modify - Prometheus Example List of options: ```text up{instance="demo.robustperception.io:9090",job="prometheus"} 1 1521630638000 up{instance="demo.robustperception.io:9093",job="alertmanager"} 1 1521630638000 up{instance="demo.robustperception.io:9100",job="node"} 1 1521630638000 ``` Regex: ```regex /.*instance="([^"]*).*/ ``` Result: ```text demo.robustperception.io:9090 demo.robustperception.io:9093 demo.robustperception.io:9100 ``` ```
docs/sources/variables/filter-variables-with-regex.md
0
https://github.com/grafana/grafana/commit/31e2b7e7c82870294b0a2c96a5740eb07969ec60
[ 0.00017619290156289935, 0.00016971628065221012, 0.00016609577869530767, 0.0001692721270956099, 0.000002985131231980631 ]
{ "id": 3, "code_window": [ " return {\n", " state: LoadingState.Error,\n", " series: [],\n", " error: { message: msg },\n", " timeRange: DefaultTimeRange,\n", " };\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " request: {} as DataQueryRequest,\n" ], "file_path": "public/app/plugins/datasource/dashboard/runSharedRequest.ts", "type": "add", "edit_start_line_idx": 72 }
# Using this docker image Uploaded to dockerhub as grafana/grafana-plugin-ci:latest-alpine Based off of `circleci/node:12-browsers` ## User The user will be `circleci` The home directory will be `/home/circleci` ## Node - node 12 is installed - yarn is installed globally - npm is installed globally ## Go - Go is installed in `/usr/local/bin/go` - golangci-lint is installed in `/usr/local/bin/golangci-lint` - mage is installed in `/home/circleci/go/bin/mage` All of the above directories are in the path, so there is no need to specify fully qualified paths. ## Grafana - Installed in `/home/circleci/src/grafana` - `yarn install` has been run ## Integration/Release Testing There are 4 previous versions pre-downloaded to /usr/local/grafana. These versions are: 1. 6.6.2 2. 6.5.3 3. 6.4.5 4. 6.3.7 To test, your CircleCI config will need a run section with something similar to the following ``` - run: name: Setup Grafana (local install) command: | sudo dpkg -i /usr/local/grafana/deb/grafana_6.6.2_amd64.deb sudo cp ci/grafana-test-env/custom.ini /usr/share/grafana/conf/custom.ini sudo cp ci/grafana-test-env/custom.ini /etc/grafana/grafana.ini sudo service grafana-server start grafana-cli --version ``` # Building To build, cd to `<srcroot>/packages/grafana-toolkit/docker/grafana-plugin-ci-alpine` ``` ./build.sh ``` # Developing/Testing To test, you should have docker-compose installed. ``` cd test ./start.sh ``` You will be in /home/circleci/test with the buildscripts installed to the local directory. Do your edits/run tests. When saving, your edits will be available in the container immediately.
packages/grafana-toolkit/docker/grafana-plugin-ci-alpine/README.md
0
https://github.com/grafana/grafana/commit/31e2b7e7c82870294b0a2c96a5740eb07969ec60
[ 0.0001714078534860164, 0.0001696545077720657, 0.00016748480265960097, 0.00016976422921288759, 0.0000014261290743888821 ]
{ "id": 0, "code_window": [ "import { globalSceneState } from \"../scene\";\n", "\n", "export class LinearElementEditor {\n", " public elementId: ExcalidrawElement[\"id\"];\n", " public activePointIndex: number | null;\n", " public draggingElementPointIndex: number | null;\n", " public lastUncommittedPoint: Point | null;\n", "\n", " constructor(element: NonDeleted<ExcalidrawLinearElement>) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " public elementId: ExcalidrawElement[\"id\"] & {\n", " _brand: \"excalidrawLinearElementId\";\n", " };\n" ], "file_path": "src/element/linearElementEditor.ts", "type": "replace", "edit_start_line_idx": 14 }
import { RoughCanvas } from "roughjs/bin/canvas"; import { RoughSVG } from "roughjs/bin/svg"; import oc from "open-color"; import { FlooredNumber, AppState } from "../types"; import { ExcalidrawElement, NonDeletedExcalidrawElement, ExcalidrawLinearElement, NonDeleted, GroupId, } from "../element/types"; import { getElementAbsoluteCoords, OMIT_SIDES_FOR_MULTIPLE_ELEMENTS, handlerRectanglesFromCoords, handlerRectangles, getElementBounds, getCommonBounds, } from "../element"; import { roundRect } from "./roundRect"; import { SceneState } from "../scene/types"; import { getScrollBars, SCROLLBAR_COLOR, SCROLLBAR_WIDTH, } from "../scene/scrollbars"; import { getSelectedElements } from "../scene/selection"; import { renderElement, renderElementToSvg } from "./renderElement"; import { getClientColors } from "../clients"; import { isLinearElement } from "../element/typeChecks"; import { LinearElementEditor } from "../element/linearElementEditor"; import { isSelectedViaGroup, getSelectedGroupIds, getElementsInGroup, } from "../groups"; type HandlerRectanglesRet = keyof ReturnType<typeof handlerRectangles>; const strokeRectWithRotation = ( context: CanvasRenderingContext2D, x: number, y: number, width: number, height: number, cx: number, cy: number, angle: number, fill?: boolean, ) => { context.translate(cx, cy); context.rotate(angle); if (fill) { context.fillRect(x - cx, y - cy, width, height); } context.strokeRect(x - cx, y - cy, width, height); context.rotate(-angle); context.translate(-cx, -cy); }; const strokeCircle = ( context: CanvasRenderingContext2D, x: number, y: number, width: number, height: number, ) => { context.beginPath(); context.arc(x + width / 2, y + height / 2, width / 2, 0, Math.PI * 2); context.fill(); context.stroke(); }; const strokeGrid = ( context: CanvasRenderingContext2D, gridSize: number, offsetX: number, offsetY: number, width: number, height: number, ) => { const origStrokeStyle = context.strokeStyle; context.strokeStyle = "rgba(0,0,0,0.1)"; context.beginPath(); for (let x = offsetX; x < offsetX + width + gridSize * 2; x += gridSize) { context.moveTo(x, offsetY - gridSize); context.lineTo(x, offsetY + height + gridSize * 2); } for (let y = offsetY; y < offsetY + height + gridSize * 2; y += gridSize) { context.moveTo(offsetX - gridSize, y); context.lineTo(offsetX + width + gridSize * 2, y); } context.stroke(); context.strokeStyle = origStrokeStyle; }; const renderLinearPointHandles = ( context: CanvasRenderingContext2D, appState: AppState, sceneState: SceneState, element: NonDeleted<ExcalidrawLinearElement>, ) => { context.translate(sceneState.scrollX, sceneState.scrollY); const origStrokeStyle = context.strokeStyle; const lineWidth = context.lineWidth; context.lineWidth = 1 / sceneState.zoom; LinearElementEditor.getPointsGlobalCoordinates(element).forEach( (point, idx) => { context.strokeStyle = "red"; context.setLineDash([]); context.fillStyle = appState.editingLinearElement?.activePointIndex === idx ? "rgba(255, 127, 127, 0.9)" : "rgba(255, 255, 255, 0.9)"; const { POINT_HANDLE_SIZE } = LinearElementEditor; strokeCircle( context, point[0] - POINT_HANDLE_SIZE / 2 / sceneState.zoom, point[1] - POINT_HANDLE_SIZE / 2 / sceneState.zoom, POINT_HANDLE_SIZE / sceneState.zoom, POINT_HANDLE_SIZE / sceneState.zoom, ); }, ); context.setLineDash([]); context.lineWidth = lineWidth; context.translate(-sceneState.scrollX, -sceneState.scrollY); context.strokeStyle = origStrokeStyle; }; export const renderScene = ( elements: readonly NonDeletedExcalidrawElement[], appState: AppState, selectionElement: NonDeletedExcalidrawElement | null, scale: number, rc: RoughCanvas, canvas: HTMLCanvasElement, sceneState: SceneState, // extra options, currently passed by export helper { renderScrollbars = true, renderSelection = true, // Whether to employ render optimizations to improve performance. // Should not be turned on for export operations and similar, because it // doesn't guarantee pixel-perfect output. renderOptimizations = false, renderGrid = true, }: { renderScrollbars?: boolean; renderSelection?: boolean; renderOptimizations?: boolean; renderGrid?: boolean; } = {}, ) => { if (!canvas) { return { atLeastOneVisibleElement: false }; } const context = canvas.getContext("2d")!; context.scale(scale, scale); // When doing calculations based on canvas width we should used normalized one const normalizedCanvasWidth = canvas.width / scale; const normalizedCanvasHeight = canvas.height / scale; // Paint background if (typeof sceneState.viewBackgroundColor === "string") { const hasTransparence = sceneState.viewBackgroundColor === "transparent" || sceneState.viewBackgroundColor.length === 5 || // #RGBA sceneState.viewBackgroundColor.length === 9 || // #RRGGBBA /(hsla|rgba)\(/.test(sceneState.viewBackgroundColor); if (hasTransparence) { context.clearRect(0, 0, normalizedCanvasWidth, normalizedCanvasHeight); } const fillStyle = context.fillStyle; context.fillStyle = sceneState.viewBackgroundColor; context.fillRect(0, 0, normalizedCanvasWidth, normalizedCanvasHeight); context.fillStyle = fillStyle; } else { context.clearRect(0, 0, normalizedCanvasWidth, normalizedCanvasHeight); } // Apply zoom const zoomTranslationX = (-normalizedCanvasWidth * (sceneState.zoom - 1)) / 2; const zoomTranslationY = (-normalizedCanvasHeight * (sceneState.zoom - 1)) / 2; context.translate(zoomTranslationX, zoomTranslationY); context.scale(sceneState.zoom, sceneState.zoom); // Grid if (renderGrid && appState.gridSize) { strokeGrid( context, appState.gridSize, -Math.ceil(zoomTranslationX / sceneState.zoom / appState.gridSize) * appState.gridSize + (sceneState.scrollX % appState.gridSize), -Math.ceil(zoomTranslationY / sceneState.zoom / appState.gridSize) * appState.gridSize + (sceneState.scrollY % appState.gridSize), normalizedCanvasWidth / sceneState.zoom, normalizedCanvasHeight / sceneState.zoom, ); } // Paint visible elements const visibleElements = elements.filter((element) => isVisibleElement( element, normalizedCanvasWidth, normalizedCanvasHeight, sceneState, ), ); visibleElements.forEach((element) => { renderElement(element, rc, context, renderOptimizations, sceneState); if ( isLinearElement(element) && appState.editingLinearElement && appState.editingLinearElement.elementId === element.id ) { renderLinearPointHandles(context, appState, sceneState, element); } }); // Paint selection element if (selectionElement) { renderElement( selectionElement, rc, context, renderOptimizations, sceneState, ); } // Paint selected elements if ( renderSelection && !appState.multiElement && !appState.editingLinearElement ) { context.translate(sceneState.scrollX, sceneState.scrollY); const selections = elements.reduce((acc, element) => { const selectionColors = []; // local user if ( appState.selectedElementIds[element.id] && !isSelectedViaGroup(appState, element) ) { selectionColors.push(oc.black); } // remote users if (sceneState.remoteSelectedElementIds[element.id]) { selectionColors.push( ...sceneState.remoteSelectedElementIds[element.id].map((socketId) => { const { background } = getClientColors(socketId); return background; }), ); } if (selectionColors.length) { const [ elementX1, elementY1, elementX2, elementY2, ] = getElementAbsoluteCoords(element); acc.push({ angle: element.angle, elementX1, elementY1, elementX2, elementY2, selectionColors, }); } return acc; }, [] as { angle: number; elementX1: number; elementY1: number; elementX2: number; elementY2: number; selectionColors: string[] }[]); function addSelectionForGroupId(groupId: GroupId) { const groupElements = getElementsInGroup(elements, groupId); const [elementX1, elementY1, elementX2, elementY2] = getCommonBounds( groupElements, ); selections.push({ angle: 0, elementX1, elementX2, elementY1, elementY2, selectionColors: [oc.black], }); } for (const groupId of getSelectedGroupIds(appState)) { // TODO: support multiplayer selected group IDs addSelectionForGroupId(groupId); } if (appState.editingGroupId) { addSelectionForGroupId(appState.editingGroupId); } selections.forEach( ({ angle, elementX1, elementY1, elementX2, elementY2, selectionColors, }) => { const elementWidth = elementX2 - elementX1; const elementHeight = elementY2 - elementY1; const initialLineDash = context.getLineDash(); const lineWidth = context.lineWidth; const lineDashOffset = context.lineDashOffset; const strokeStyle = context.strokeStyle; const dashedLinePadding = 4 / sceneState.zoom; const dashWidth = 8 / sceneState.zoom; const spaceWidth = 4 / sceneState.zoom; context.lineWidth = 1 / sceneState.zoom; const count = selectionColors.length; for (var i = 0; i < count; ++i) { context.strokeStyle = selectionColors[i]; context.setLineDash([ dashWidth, spaceWidth + (dashWidth + spaceWidth) * (count - 1), ]); context.lineDashOffset = (dashWidth + spaceWidth) * i; strokeRectWithRotation( context, elementX1 - dashedLinePadding, elementY1 - dashedLinePadding, elementWidth + dashedLinePadding * 2, elementHeight + dashedLinePadding * 2, elementX1 + elementWidth / 2, elementY1 + elementHeight / 2, angle, ); } context.lineDashOffset = lineDashOffset; context.strokeStyle = strokeStyle; context.lineWidth = lineWidth; context.setLineDash(initialLineDash); }, ); context.translate(-sceneState.scrollX, -sceneState.scrollY); const locallySelectedElements = getSelectedElements(elements, appState); // Paint resize handlers if (locallySelectedElements.length === 1) { context.translate(sceneState.scrollX, sceneState.scrollY); context.fillStyle = oc.white; const handlers = handlerRectangles( locallySelectedElements[0], sceneState.zoom, ); Object.keys(handlers).forEach((key) => { const handler = handlers[key as HandlerRectanglesRet]; if (handler !== undefined) { const lineWidth = context.lineWidth; context.lineWidth = 1 / sceneState.zoom; if (key === "rotation") { strokeCircle( context, handler[0], handler[1], handler[2], handler[3], ); } else { strokeRectWithRotation( context, handler[0], handler[1], handler[2], handler[3], handler[0] + handler[2] / 2, handler[1] + handler[3] / 2, locallySelectedElements[0].angle, true, // fill before stroke ); } context.lineWidth = lineWidth; } }); context.translate(-sceneState.scrollX, -sceneState.scrollY); } else if (locallySelectedElements.length > 1 && !appState.isRotating) { const dashedLinePadding = 4 / sceneState.zoom; context.translate(sceneState.scrollX, sceneState.scrollY); context.fillStyle = oc.white; const [x1, y1, x2, y2] = getCommonBounds(locallySelectedElements); const initialLineDash = context.getLineDash(); context.setLineDash([2 / sceneState.zoom]); const lineWidth = context.lineWidth; context.lineWidth = 1 / sceneState.zoom; strokeRectWithRotation( context, x1 - dashedLinePadding, y1 - dashedLinePadding, x2 - x1 + dashedLinePadding * 2, y2 - y1 + dashedLinePadding * 2, (x1 + x2) / 2, (y1 + y2) / 2, 0, ); context.lineWidth = lineWidth; context.setLineDash(initialLineDash); const handlers = handlerRectanglesFromCoords( [x1, y1, x2, y2], 0, sceneState.zoom, undefined, OMIT_SIDES_FOR_MULTIPLE_ELEMENTS, ); Object.keys(handlers).forEach((key) => { const handler = handlers[key as HandlerRectanglesRet]; if (handler !== undefined) { const lineWidth = context.lineWidth; context.lineWidth = 1 / sceneState.zoom; if (key === "rotation") { strokeCircle( context, handler[0], handler[1], handler[2], handler[3], ); } else { strokeRectWithRotation( context, handler[0], handler[1], handler[2], handler[3], handler[0] + handler[2] / 2, handler[1] + handler[3] / 2, 0, true, // fill before stroke ); } context.lineWidth = lineWidth; } }); context.translate(-sceneState.scrollX, -sceneState.scrollY); } } // Reset zoom context.scale(1 / sceneState.zoom, 1 / sceneState.zoom); context.translate(-zoomTranslationX, -zoomTranslationY); // Paint remote pointers for (const clientId in sceneState.remotePointerViewportCoords) { let { x, y } = sceneState.remotePointerViewportCoords[clientId]; const username = sceneState.remotePointerUsernames[clientId]; const width = 9; const height = 14; const isOutOfBounds = x < 0 || x > normalizedCanvasWidth - width || y < 0 || y > normalizedCanvasHeight - height; x = Math.max(x, 0); x = Math.min(x, normalizedCanvasWidth - width); y = Math.max(y, 0); y = Math.min(y, normalizedCanvasHeight - height); const { background, stroke } = getClientColors(clientId); const strokeStyle = context.strokeStyle; const fillStyle = context.fillStyle; const globalAlpha = context.globalAlpha; context.strokeStyle = stroke; context.fillStyle = background; if (isOutOfBounds) { context.globalAlpha = 0.2; } if ( sceneState.remotePointerButton && sceneState.remotePointerButton[clientId] === "down" ) { context.beginPath(); context.arc(x, y, 15, 0, 2 * Math.PI, false); context.lineWidth = 3; context.strokeStyle = "#ffffff88"; context.stroke(); context.closePath(); context.beginPath(); context.arc(x, y, 15, 0, 2 * Math.PI, false); context.lineWidth = 1; context.strokeStyle = stroke; context.stroke(); context.closePath(); } context.beginPath(); context.moveTo(x, y); context.lineTo(x + 1, y + 14); context.lineTo(x + 4, y + 9); context.lineTo(x + 9, y + 10); context.lineTo(x, y); context.fill(); context.stroke(); if (!isOutOfBounds && username) { const offsetX = x + width; const offsetY = y + height; const paddingHorizontal = 4; const paddingVertical = 4; const measure = context.measureText(username); const measureHeight = measure.actualBoundingBoxDescent + measure.actualBoundingBoxAscent; // Border context.fillStyle = stroke; context.globalAlpha = globalAlpha; context.fillRect( offsetX - 1, offsetY - 1, measure.width + 2 * paddingHorizontal + 2, measureHeight + 2 * paddingVertical + 2, ); // Background context.fillStyle = background; context.fillRect( offsetX, offsetY, measure.width + 2 * paddingHorizontal, measureHeight + 2 * paddingVertical, ); context.fillStyle = oc.white; context.fillText( username, offsetX + paddingHorizontal, offsetY + paddingVertical + measure.actualBoundingBoxAscent, ); } context.strokeStyle = strokeStyle; context.fillStyle = fillStyle; context.globalAlpha = globalAlpha; context.closePath(); } // Paint scrollbars let scrollBars; if (renderScrollbars) { scrollBars = getScrollBars( elements, normalizedCanvasWidth, normalizedCanvasHeight, sceneState, ); const fillStyle = context.fillStyle; const strokeStyle = context.strokeStyle; context.fillStyle = SCROLLBAR_COLOR; context.strokeStyle = "rgba(255,255,255,0.8)"; [scrollBars.horizontal, scrollBars.vertical].forEach((scrollBar) => { if (scrollBar) { roundRect( context, scrollBar.x, scrollBar.y, scrollBar.width, scrollBar.height, SCROLLBAR_WIDTH / 2, ); } }); context.fillStyle = fillStyle; context.strokeStyle = strokeStyle; } context.scale(1 / scale, 1 / scale); return { atLeastOneVisibleElement: visibleElements.length > 0, scrollBars }; }; const isVisibleElement = ( element: ExcalidrawElement, viewportWidth: number, viewportHeight: number, { scrollX, scrollY, zoom, }: { scrollX: FlooredNumber; scrollY: FlooredNumber; zoom: number; }, ) => { const [x1, y1, x2, y2] = getElementBounds(element); // Apply zoom const viewportWidthWithZoom = viewportWidth / zoom; const viewportHeightWithZoom = viewportHeight / zoom; const viewportWidthDiff = viewportWidth - viewportWidthWithZoom; const viewportHeightDiff = viewportHeight - viewportHeightWithZoom; return ( x2 + scrollX - viewportWidthDiff / 2 >= 0 && x1 + scrollX - viewportWidthDiff / 2 <= viewportWidthWithZoom && y2 + scrollY - viewportHeightDiff / 2 >= 0 && y1 + scrollY - viewportHeightDiff / 2 <= viewportHeightWithZoom ); }; // This should be only called for exporting purposes export const renderSceneToSvg = ( elements: readonly NonDeletedExcalidrawElement[], rsvg: RoughSVG, svgRoot: SVGElement, { offsetX = 0, offsetY = 0, }: { offsetX?: number; offsetY?: number; } = {}, ) => { if (!svgRoot) { return; } // render elements elements.forEach((element) => { if (!element.isDeleted) { renderElementToSvg( element, rsvg, svgRoot, element.x + offsetX, element.y + offsetY, ); } }); };
src/renderer/renderScene.ts
1
https://github.com/excalidraw/excalidraw/commit/f295550940c7ee03f61cead395080a09ad27b599
[ 0.9992871880531311, 0.031069736927747726, 0.00016402866458520293, 0.00017864865367300808, 0.17116029560565948 ]
{ "id": 0, "code_window": [ "import { globalSceneState } from \"../scene\";\n", "\n", "export class LinearElementEditor {\n", " public elementId: ExcalidrawElement[\"id\"];\n", " public activePointIndex: number | null;\n", " public draggingElementPointIndex: number | null;\n", " public lastUncommittedPoint: Point | null;\n", "\n", " constructor(element: NonDeleted<ExcalidrawLinearElement>) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " public elementId: ExcalidrawElement[\"id\"] & {\n", " _brand: \"excalidrawLinearElementId\";\n", " };\n" ], "file_path": "src/element/linearElementEditor.ts", "type": "replace", "edit_start_line_idx": 14 }
import React from "react"; import * as i18n from "../i18n"; export const LanguageList = ({ onChange, languages = i18n.languages, currentLanguage = i18n.getLanguage().lng, floating, }: { languages?: { lng: string; label: string }[]; onChange: (value: string) => void; currentLanguage?: string; floating?: boolean; }) => ( <React.Fragment> <select className={`dropdown-select dropdown-select__language${ floating ? " dropdown-select--floating" : "" }`} onChange={({ target }) => onChange(target.value)} value={currentLanguage} aria-label={i18n.t("buttons.selectLanguage")} > {languages.map((language) => ( <option key={language.lng} value={language.lng}> {language.label} </option> ))} </select> </React.Fragment> );
src/components/LanguageList.tsx
0
https://github.com/excalidraw/excalidraw/commit/f295550940c7ee03f61cead395080a09ad27b599
[ 0.00017717524315230548, 0.00017496485088486224, 0.0001733613753458485, 0.0001746613997966051, 0.0000015189788200586918 ]