hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 3, "code_window": [ "\n", "export FormGroup from './FormGroup';\n", "export FormLabel from './FormLabel';\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "export FormControl from './FormControl';" ], "file_path": "src/Form/index.js", "type": "add", "edit_start_line_idx": 4 }
/* eslint-disable flowtype/require-valid-file-annotation */ export default from './Input'; export Input from './Input'; export InputLabel from './InputLabel';
src/Input/index.js
0
https://github.com/mui/material-ui/commit/2d6ca998076cf8300683165867c615c34cb76846
[ 0.00024573047994636, 0.00024573047994636, 0.00024573047994636, 0.00024573047994636, 0 ]
{ "id": 3, "code_window": [ "\n", "export FormGroup from './FormGroup';\n", "export FormLabel from './FormLabel';\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "export FormControl from './FormControl';" ], "file_path": "src/Form/index.js", "type": "add", "edit_start_line_idx": 4 }
// @flow weak import React from 'react'; import { ListSubheader } from 'material-ui/List'; export default function SimpleListSubheader() { return ( <ListSubheader>Title</ListSubheader> ); }
test/regressions/site/src/tests/ListSubheader/SimpleListSubheader.js
0
https://github.com/mui/material-ui/commit/2d6ca998076cf8300683165867c615c34cb76846
[ 0.0001793843985069543, 0.00017418406787328422, 0.0001689837226876989, 0.00017418406787328422, 0.000005200337909627706 ]
{ "id": 0, "code_window": [ " )\n", " logging.info(sql)\n", " sql = sqlparse.format(sql, reindent=True)\n", " sql = self.database.db_engine_spec.sql_preprocessor(sql)\n", " return sql\n", "\n", " def query(self, query_obj):\n", " qry_start_dttm = datetime.now()\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "superset/connectors/sqla/models.py", "type": "replace", "edit_start_line_idx": 519 }
from datetime import datetime import logging import sqlparse import pandas as pd from sqlalchemy import ( Column, Integer, String, ForeignKey, Text, Boolean, DateTime, ) import sqlalchemy as sa from sqlalchemy import asc, and_, desc, select from sqlalchemy.ext.compiler import compiles from sqlalchemy.sql.expression import ColumnClause, TextAsFrom from sqlalchemy.orm import backref, relationship from sqlalchemy.sql import table, literal_column, text, column from flask import escape, Markup from flask_appbuilder import Model from flask_babel import lazy_gettext as _ from superset import db, utils, import_util from superset.connectors.base import BaseDatasource, BaseColumn, BaseMetric from superset.utils import ( wrap_clause_in_parens, DTTM_ALIAS, QueryStatus ) from superset.models.helpers import QueryResult from superset.models.core import Database from superset.jinja_context import get_template_processor from superset.models.helpers import set_perm class TableColumn(Model, BaseColumn): """ORM object for table columns, each table can have multiple columns""" __tablename__ = 'table_columns' table_id = Column(Integer, ForeignKey('tables.id')) table = relationship( 'SqlaTable', backref=backref('columns', cascade='all, delete-orphan'), foreign_keys=[table_id]) is_dttm = Column(Boolean, default=False) expression = Column(Text, default='') python_date_format = Column(String(255)) database_expression = Column(String(255)) export_fields = ( 'table_id', 'column_name', 'verbose_name', 'is_dttm', 'is_active', 'type', 'groupby', 'count_distinct', 'sum', 'avg', 'max', 'min', 'filterable', 'expression', 'description', 'python_date_format', 'database_expression' ) @property def sqla_col(self): name = self.column_name if not self.expression: col = column(self.column_name).label(name) else: col = literal_column(self.expression).label(name) return col def get_time_filter(self, start_dttm, end_dttm): col = self.sqla_col.label('__time') return and_( col >= text(self.dttm_sql_literal(start_dttm)), col <= text(self.dttm_sql_literal(end_dttm)), ) def get_timestamp_expression(self, time_grain): """Getting the time component of the query""" expr = self.expression or self.column_name if not self.expression and not time_grain: return column(expr, type_=DateTime).label(DTTM_ALIAS) if time_grain: pdf = self.python_date_format if pdf in ('epoch_s', 'epoch_ms'): # if epoch, translate to DATE using db specific conf db_spec = self.table.database.db_engine_spec if pdf == 'epoch_s': expr = db_spec.epoch_to_dttm().format(col=expr) elif pdf == 'epoch_ms': expr = db_spec.epoch_ms_to_dttm().format(col=expr) grain = self.table.database.grains_dict().get(time_grain, '{col}') expr = grain.function.format(col=expr) return literal_column(expr, type_=DateTime).label(DTTM_ALIAS) @classmethod def import_obj(cls, i_column): def lookup_obj(lookup_column): return db.session.query(TableColumn).filter( TableColumn.table_id == lookup_column.table_id, TableColumn.column_name == lookup_column.column_name).first() return import_util.import_simple_obj(db.session, i_column, lookup_obj) def dttm_sql_literal(self, dttm): """Convert datetime object to a SQL expression string If database_expression is empty, the internal dttm will be parsed as the string with the pattern that the user inputted (python_date_format) If database_expression is not empty, the internal dttm will be parsed as the sql sentence for the database to convert """ tf = self.python_date_format or '%Y-%m-%d %H:%M:%S.%f' if self.database_expression: return self.database_expression.format(dttm.strftime('%Y-%m-%d %H:%M:%S')) elif tf == 'epoch_s': return str((dttm - datetime(1970, 1, 1)).total_seconds()) elif tf == 'epoch_ms': return str((dttm - datetime(1970, 1, 1)).total_seconds() * 1000.0) else: s = self.table.database.db_engine_spec.convert_dttm( self.type, dttm) return s or "'{}'".format(dttm.strftime(tf)) class SqlMetric(Model, BaseMetric): """ORM object for metrics, each table can have multiple metrics""" __tablename__ = 'sql_metrics' table_id = Column(Integer, ForeignKey('tables.id')) table = relationship( 'SqlaTable', backref=backref('metrics', cascade='all, delete-orphan'), foreign_keys=[table_id]) expression = Column(Text) export_fields = ( 'metric_name', 'verbose_name', 'metric_type', 'table_id', 'expression', 'description', 'is_restricted', 'd3format') @property def sqla_col(self): name = self.metric_name return literal_column(self.expression).label(name) @property def perm(self): return ( "{parent_name}.[{obj.metric_name}](id:{obj.id})" ).format(obj=self, parent_name=self.table.full_name) if self.table else None @classmethod def import_obj(cls, i_metric): def lookup_obj(lookup_metric): return db.session.query(SqlMetric).filter( SqlMetric.table_id == lookup_metric.table_id, SqlMetric.metric_name == lookup_metric.metric_name).first() return import_util.import_simple_obj(db.session, i_metric, lookup_obj) class SqlaTable(Model, BaseDatasource): """An ORM object for SqlAlchemy table references""" type = "table" query_language = 'sql' metric_class = SqlMetric __tablename__ = 'tables' id = Column(Integer, primary_key=True) table_name = Column(String(250)) main_dttm_col = Column(String(250)) description = Column(Text) default_endpoint = Column(Text) database_id = Column(Integer, ForeignKey('dbs.id'), nullable=False) is_featured = Column(Boolean, default=False) filter_select_enabled = Column(Boolean, default=False) user_id = Column(Integer, ForeignKey('ab_user.id')) owner = relationship('User', backref='tables', foreign_keys=[user_id]) database = relationship( 'Database', backref=backref('tables', cascade='all, delete-orphan'), foreign_keys=[database_id]) offset = Column(Integer, default=0) cache_timeout = Column(Integer) schema = Column(String(255)) sql = Column(Text) params = Column(Text) perm = Column(String(1000)) baselink = "tablemodelview" column_cls = TableColumn metric_cls = SqlMetric export_fields = ( 'table_name', 'main_dttm_col', 'description', 'default_endpoint', 'database_id', 'is_featured', 'offset', 'cache_timeout', 'schema', 'sql', 'params') __table_args__ = ( sa.UniqueConstraint( 'database_id', 'schema', 'table_name', name='_customer_location_uc'),) def __repr__(self): return self.name @property def description_markeddown(self): return utils.markdown(self.description) @property def link(self): name = escape(self.name) return Markup( '<a href="{self.explore_url}">{name}</a>'.format(**locals())) @property def schema_perm(self): """Returns schema permission if present, database one otherwise.""" return utils.get_schema_perm(self.database, self.schema) def get_perm(self): return ( "[{obj.database}].[{obj.table_name}]" "(id:{obj.id})").format(obj=self) @property def name(self): if not self.schema: return self.table_name return "{}.{}".format(self.schema, self.table_name) @property def full_name(self): return utils.get_datasource_full_name( self.database, self.table_name, schema=self.schema) @property def dttm_cols(self): l = [c.column_name for c in self.columns if c.is_dttm] if self.main_dttm_col and self.main_dttm_col not in l: l.append(self.main_dttm_col) return l @property def num_cols(self): return [c.column_name for c in self.columns if c.is_num] @property def any_dttm_col(self): cols = self.dttm_cols if cols: return cols[0] @property def html(self): t = ((c.column_name, c.type) for c in self.columns) df = pd.DataFrame(t) df.columns = ['field', 'type'] return df.to_html( index=False, classes=( "dataframe table table-striped table-bordered " "table-condensed")) @property def metrics_combo(self): return sorted( [ (m.metric_name, m.verbose_name or m.metric_name) for m in self.metrics], key=lambda x: x[1]) @property def sql_url(self): return self.database.sql_url + "?table_name=" + str(self.table_name) @property def time_column_grains(self): return { "time_columns": self.dttm_cols, "time_grains": [grain.name for grain in self.database.grains()] } def get_col(self, col_name): columns = self.columns for col in columns: if col_name == col.column_name: return col def values_for_column(self, column_name, from_dttm, to_dttm, limit=500): """Runs query against sqla to retrieve some sample values for the given column. """ granularity = self.main_dttm_col cols = {col.column_name: col for col in self.columns} target_col = cols[column_name] tbl = table(self.table_name) qry = sa.select([target_col.sqla_col]) qry = qry.select_from(tbl) qry = qry.distinct(column_name) qry = qry.limit(limit) if granularity: dttm_col = cols[granularity] timestamp = dttm_col.sqla_col.label('timestamp') time_filter = [ timestamp >= text(dttm_col.dttm_sql_literal(from_dttm)), timestamp <= text(dttm_col.dttm_sql_literal(to_dttm)), ] qry = qry.where(and_(*time_filter)) engine = self.database.get_sqla_engine() sql = "{}".format( qry.compile( engine, compile_kwargs={"literal_binds": True}, ), ) return pd.read_sql_query( sql=sql, con=engine ) def get_query_str( # sqla self, engine, qry_start_dttm, groupby, metrics, granularity, from_dttm, to_dttm, filter=None, # noqa is_timeseries=True, timeseries_limit=15, timeseries_limit_metric=None, row_limit=None, inner_from_dttm=None, inner_to_dttm=None, orderby=None, extras=None, columns=None): """Querying any sqla table from this common interface""" template_kwargs = { 'from_dttm': from_dttm, 'groupby': groupby, 'metrics': metrics, 'row_limit': row_limit, 'to_dttm': to_dttm, } template_processor = get_template_processor( table=self, database=self.database, **template_kwargs) # For backward compatibility if granularity not in self.dttm_cols: granularity = self.main_dttm_col cols = {col.column_name: col for col in self.columns} metrics_dict = {m.metric_name: m for m in self.metrics} if not granularity and is_timeseries: raise Exception(_( "Datetime column not provided as part table configuration " "and is required by this type of chart")) for m in metrics: if m not in metrics_dict: raise Exception(_("Metric '{}' is not valid".format(m))) metrics_exprs = [metrics_dict.get(m).sqla_col for m in metrics] timeseries_limit_metric = metrics_dict.get(timeseries_limit_metric) timeseries_limit_metric_expr = None if timeseries_limit_metric: timeseries_limit_metric_expr = \ timeseries_limit_metric.sqla_col if metrics: main_metric_expr = metrics_exprs[0] else: main_metric_expr = literal_column("COUNT(*)").label("ccount") select_exprs = [] groupby_exprs = [] if groupby: select_exprs = [] inner_select_exprs = [] inner_groupby_exprs = [] for s in groupby: col = cols[s] outer = col.sqla_col inner = col.sqla_col.label(col.column_name + '__') groupby_exprs.append(outer) select_exprs.append(outer) inner_groupby_exprs.append(inner) inner_select_exprs.append(inner) elif columns: for s in columns: select_exprs.append(cols[s].sqla_col) metrics_exprs = [] if granularity: @compiles(ColumnClause) def visit_column(element, compiler, **kw): """Patch for sqlalchemy bug TODO: sqlalchemy 1.2 release should be doing this on its own. Patch only if the column clause is specific for DateTime set and granularity is selected. """ text = compiler.visit_column(element, **kw) try: if ( element.is_literal and hasattr(element.type, 'python_type') and type(element.type) is DateTime ): text = text.replace('%%', '%') except NotImplementedError: # Some elements raise NotImplementedError for python_type pass return text dttm_col = cols[granularity] time_grain = extras.get('time_grain_sqla') if is_timeseries: timestamp = dttm_col.get_timestamp_expression(time_grain) select_exprs += [timestamp] groupby_exprs += [timestamp] time_filter = dttm_col.get_time_filter(from_dttm, to_dttm) select_exprs += metrics_exprs qry = sa.select(select_exprs) tbl = table(self.table_name) if self.schema: tbl.schema = self.schema # Supporting arbitrary SQL statements in place of tables if self.sql: from_sql = template_processor.process_template(self.sql) tbl = TextAsFrom(sa.text(from_sql), []).alias('expr_qry') if not columns: qry = qry.group_by(*groupby_exprs) where_clause_and = [] having_clause_and = [] for flt in filter: if not all([flt.get(s) for s in ['col', 'op', 'val']]): continue col = flt['col'] op = flt['op'] eq = flt['val'] col_obj = cols.get(col) if col_obj and op in ('in', 'not in'): values = [types.strip("'").strip('"') for types in eq] if col_obj.is_num: values = [utils.js_string_to_num(s) for s in values] cond = col_obj.sqla_col.in_(values) if op == 'not in': cond = ~cond where_clause_and.append(cond) if extras: where = extras.get('where') if where: where_clause_and += [wrap_clause_in_parens( template_processor.process_template(where))] having = extras.get('having') if having: having_clause_and += [wrap_clause_in_parens( template_processor.process_template(having))] if granularity: qry = qry.where(and_(*([time_filter] + where_clause_and))) else: qry = qry.where(and_(*where_clause_and)) qry = qry.having(and_(*having_clause_and)) if groupby: qry = qry.order_by(desc(main_metric_expr)) elif orderby: for col, ascending in orderby: direction = asc if ascending else desc qry = qry.order_by(direction(col)) qry = qry.limit(row_limit) if is_timeseries and timeseries_limit and groupby: # some sql dialects require for order by expressions # to also be in the select clause -- others, e.g. vertica, # require a unique inner alias inner_main_metric_expr = main_metric_expr.label('mme_inner__') inner_select_exprs += [inner_main_metric_expr] subq = select(inner_select_exprs) subq = subq.select_from(tbl) inner_time_filter = dttm_col.get_time_filter( inner_from_dttm or from_dttm, inner_to_dttm or to_dttm, ) subq = subq.where(and_(*(where_clause_and + [inner_time_filter]))) subq = subq.group_by(*inner_groupby_exprs) ob = inner_main_metric_expr if timeseries_limit_metric_expr is not None: ob = timeseries_limit_metric_expr subq = subq.order_by(desc(ob)) subq = subq.limit(timeseries_limit) on_clause = [] for i, gb in enumerate(groupby): on_clause.append( groupby_exprs[i] == column(gb + '__')) tbl = tbl.join(subq.alias(), and_(*on_clause)) qry = qry.select_from(tbl) sql = "{}".format( qry.compile( engine, compile_kwargs={"literal_binds": True},), ) logging.info(sql) sql = sqlparse.format(sql, reindent=True) sql = self.database.db_engine_spec.sql_preprocessor(sql) return sql def query(self, query_obj): qry_start_dttm = datetime.now() engine = self.database.get_sqla_engine() sql = self.get_query_str(engine, qry_start_dttm, **query_obj) status = QueryStatus.SUCCESS error_message = None df = None try: df = pd.read_sql_query(sql, con=engine) except Exception as e: status = QueryStatus.FAILED error_message = str(e) return QueryResult( status=status, df=df, duration=datetime.now() - qry_start_dttm, query=sql, error_message=error_message) def get_sqla_table_object(self): return self.database.get_table(self.table_name, schema=self.schema) def fetch_metadata(self): """Fetches the metadata for the table and merges it in""" try: table = self.get_sqla_table_object() except Exception: raise Exception( "Table doesn't seem to exist in the specified database, " "couldn't fetch column information") TC = TableColumn # noqa shortcut to class M = SqlMetric # noqa metrics = [] any_date_col = None for col in table.columns: try: datatype = "{}".format(col.type).upper() except Exception as e: datatype = "UNKNOWN" logging.error( "Unrecognized data type in {}.{}".format(table, col.name)) logging.exception(e) dbcol = ( db.session .query(TC) .filter(TC.table == self) .filter(TC.column_name == col.name) .first() ) db.session.flush() if not dbcol: dbcol = TableColumn(column_name=col.name, type=datatype) dbcol.groupby = dbcol.is_string dbcol.filterable = dbcol.is_string dbcol.sum = dbcol.is_num dbcol.avg = dbcol.is_num dbcol.is_dttm = dbcol.is_time db.session.merge(self) self.columns.append(dbcol) if not any_date_col and dbcol.is_time: any_date_col = col.name quoted = "{}".format( column(dbcol.column_name).compile(dialect=db.engine.dialect)) if dbcol.sum: metrics.append(M( metric_name='sum__' + dbcol.column_name, verbose_name='sum__' + dbcol.column_name, metric_type='sum', expression="SUM({})".format(quoted) )) if dbcol.avg: metrics.append(M( metric_name='avg__' + dbcol.column_name, verbose_name='avg__' + dbcol.column_name, metric_type='avg', expression="AVG({})".format(quoted) )) if dbcol.max: metrics.append(M( metric_name='max__' + dbcol.column_name, verbose_name='max__' + dbcol.column_name, metric_type='max', expression="MAX({})".format(quoted) )) if dbcol.min: metrics.append(M( metric_name='min__' + dbcol.column_name, verbose_name='min__' + dbcol.column_name, metric_type='min', expression="MIN({})".format(quoted) )) if dbcol.count_distinct: metrics.append(M( metric_name='count_distinct__' + dbcol.column_name, verbose_name='count_distinct__' + dbcol.column_name, metric_type='count_distinct', expression="COUNT(DISTINCT {})".format(quoted) )) dbcol.type = datatype db.session.merge(self) db.session.commit() metrics.append(M( metric_name='count', verbose_name='COUNT(*)', metric_type='count', expression="COUNT(*)" )) for metric in metrics: m = ( db.session.query(M) .filter(M.metric_name == metric.metric_name) .filter(M.table_id == self.id) .first() ) metric.table_id = self.id if not m: db.session.add(metric) db.session.commit() if not self.main_dttm_col: self.main_dttm_col = any_date_col @classmethod def import_obj(cls, i_datasource, import_time=None): """Imports the datasource from the object to the database. Metrics and columns and datasource will be overrided if exists. This function can be used to import/export dashboards between multiple superset instances. Audit metadata isn't copies over. """ def lookup_sqlatable(table): return db.session.query(SqlaTable).join(Database).filter( SqlaTable.table_name == table.table_name, SqlaTable.schema == table.schema, Database.id == table.database_id, ).first() def lookup_database(table): return db.session.query(Database).filter_by( database_name=table.params_dict['database_name']).one() return import_util.import_datasource( db.session, i_datasource, lookup_database, lookup_sqlatable, import_time) sa.event.listen(SqlaTable, 'after_insert', set_perm) sa.event.listen(SqlaTable, 'after_update', set_perm)
superset/connectors/sqla/models.py
1
https://github.com/apache/superset/commit/3107152f5bb973b8b1a9c5cf3bc2bee1d7f47e0d
[ 0.9993413090705872, 0.060001928359270096, 0.00016533542657271028, 0.0004473504959605634, 0.2342710942029953 ]
{ "id": 0, "code_window": [ " )\n", " logging.info(sql)\n", " sql = sqlparse.format(sql, reindent=True)\n", " sql = self.database.db_engine_spec.sql_preprocessor(sql)\n", " return sql\n", "\n", " def query(self, query_obj):\n", " qry_start_dttm = datetime.now()\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "superset/connectors/sqla/models.py", "type": "replace", "edit_start_line_idx": 519 }
import React from 'react'; import { expect } from 'chai'; import { describe, it } from 'mocha'; import { shallow } from 'enzyme'; import ExploreActionButtons from '../../../../javascripts/explorev2/components/ExploreActionButtons'; describe('ExploreActionButtons', () => { const defaultProps = { canDownload: 'True', slice: { data: { csv_endpoint: '', json_endpoint: '', }, }, }; it('renders', () => { expect( React.isValidElement(<ExploreActionButtons {...defaultProps} />) ).to.equal(true); }); it('should render 5 children/buttons', () => { const wrapper = shallow(<ExploreActionButtons {...defaultProps} />); expect(wrapper.children()).to.have.length(5); }); });
superset/assets/spec/javascripts/explorev2/components/ExploreActionButtons_spec.jsx
0
https://github.com/apache/superset/commit/3107152f5bb973b8b1a9c5cf3bc2bee1d7f47e0d
[ 0.00017597027181182057, 0.00017390039283782244, 0.0001710923679638654, 0.00017463855328969657, 0.000002058663312709541 ]
{ "id": 0, "code_window": [ " )\n", " logging.info(sql)\n", " sql = sqlparse.format(sql, reindent=True)\n", " sql = self.database.db_engine_spec.sql_preprocessor(sql)\n", " return sql\n", "\n", " def query(self, query_obj):\n", " qry_start_dttm = datetime.now()\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "superset/connectors/sqla/models.py", "type": "replace", "edit_start_line_idx": 519 }
import unittest from sqlalchemy.engine.url import make_url from superset.models.core import Database class DatabaseModelTestCase(unittest.TestCase): def test_database_for_various_backend(self): sqlalchemy_uri = 'presto://presto.airbnb.io:8080/hive/default' model = Database(sqlalchemy_uri=sqlalchemy_uri) url = make_url(model.sqlalchemy_uri) db = model.get_database_for_various_backend(url, None) assert db == 'hive/default' db = model.get_database_for_various_backend(url, 'raw_data') assert db == 'hive/raw_data' sqlalchemy_uri = 'redshift+psycopg2://superset:[email protected]:5439/prod' model = Database(sqlalchemy_uri=sqlalchemy_uri) url = make_url(model.sqlalchemy_uri) db = model.get_database_for_various_backend(url, None) assert db == 'prod' db = model.get_database_for_various_backend(url, 'test') assert db == 'prod' sqlalchemy_uri = 'postgresql+psycopg2://superset:[email protected]:5439/prod' model = Database(sqlalchemy_uri=sqlalchemy_uri) url = make_url(model.sqlalchemy_uri) db = model.get_database_for_various_backend(url, None) assert db == 'prod' db = model.get_database_for_various_backend(url, 'adhoc') assert db == 'prod' sqlalchemy_uri = 'hive://[email protected]:10000/raw_data' model = Database(sqlalchemy_uri=sqlalchemy_uri) url = make_url(model.sqlalchemy_uri) db = model.get_database_for_various_backend(url, None) assert db == 'raw_data' db = model.get_database_for_various_backend(url, 'adhoc') assert db == 'adhoc' sqlalchemy_uri = 'mysql://superset:[email protected]/superset' model = Database(sqlalchemy_uri=sqlalchemy_uri) url = make_url(model.sqlalchemy_uri) db = model.get_database_for_various_backend(url, None) assert db == 'superset' db = model.get_database_for_various_backend(url, 'adhoc') assert db == 'adhoc'
tests/model_tests.py
0
https://github.com/apache/superset/commit/3107152f5bb973b8b1a9c5cf3bc2bee1d7f47e0d
[ 0.0004875579325016588, 0.0003094918793067336, 0.00016981911903712898, 0.000273208279395476, 0.0001319224975304678 ]
{ "id": 0, "code_window": [ " )\n", " logging.info(sql)\n", " sql = sqlparse.format(sql, reindent=True)\n", " sql = self.database.db_engine_spec.sql_preprocessor(sql)\n", " return sql\n", "\n", " def query(self, query_obj):\n", " qry_start_dttm = datetime.now()\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "superset/connectors/sqla/models.py", "type": "replace", "edit_start_line_idx": 519 }
{% extends "superset/basic.html" %} {% block body %} <body role="document"> <!-- Fixed navbar --> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Bootstrap theme</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> <li class="dropdown"> <a href="#"></span></a> <ul class="dropdown-menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li role="separator" class="divider"></li> <li class="dropdown-header">Nav header</li> <li><a href="#">Separated link</a></li> <li><a href="#">One more separated link</a></li> </ul> </li> </ul> </div><!--/.nav-collapse --> </div> </nav> <div class="container theme-showcase" role="main"> <!-- Main jumbotron for a primary marketing message or call to action --> <div class="jumbotron"> <h1>Theme example</h1> <p>This is a template showcasing the optional theme stylesheet included in Bootstrap. Use it as a starting point to create something more unique by building on or modifying it.</p> </div> <div class="page-header"> <h1>Buttons</h1> </div> <p> <button type="button" class="btn btn-lg btn-default">Default</button> <button type="button" class="btn btn-lg btn-primary">Primary</button> <button type="button" class="btn btn-lg btn-success">Success</button> <button type="button" class="btn btn-lg btn-info">Info</button> <button type="button" class="btn btn-lg btn-warning">Warning</button> <button type="button" class="btn btn-lg btn-danger">Danger</button> <button type="button" class="btn btn-lg btn-link">Link</button> </p> <p> <button type="button" class="btn btn-default">Default</button> <button type="button" class="btn btn-primary">Primary</button> <button type="button" class="btn btn-success">Success</button> <button type="button" class="btn btn-info">Info</button> <button type="button" class="btn btn-warning">Warning</button> <button type="button" class="btn btn-danger">Danger</button> <button type="button" class="btn btn-link">Link</button> </p> <p> <button type="button" class="btn btn-sm btn-default">Default</button> <button type="button" class="btn btn-sm btn-primary">Primary</button> <button type="button" class="btn btn-sm btn-success">Success</button> <button type="button" class="btn btn-sm btn-info">Info</button> <button type="button" class="btn btn-sm btn-warning">Warning</button> <button type="button" class="btn btn-sm btn-danger">Danger</button> <button type="button" class="btn btn-sm btn-link">Link</button> </p> <p> <button type="button" class="btn btn-xs btn-default">Default</button> <button type="button" class="btn btn-xs btn-primary">Primary</button> <button type="button" class="btn btn-xs btn-success">Success</button> <button type="button" class="btn btn-xs btn-info">Info</button> <button type="button" class="btn btn-xs btn-warning">Warning</button> <button type="button" class="btn btn-xs btn-danger">Danger</button> <button type="button" class="btn btn-xs btn-link">Link</button> </p> <div class="page-header"> <h1>Tables</h1> </div> <div class="row"> <div class="col-md-6"> <table class="table"> <thead> <tr> <th>#</th> <th>First Name</th> <th>Last Name</th> <th>Username</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Mark</td> <td>Otto</td> <td>@mdo</td> </tr> <tr> <td>2</td> <td>Jacob</td> <td>Thornton</td> <td>@fat</td> </tr> <tr> <td>3</td> <td>Larry</td> <td>the Bird</td> <td>@twitter</td> </tr> </tbody> </table> </div> <div class="col-md-6"> <table class="table table-striped"> <thead> <tr> <th>#</th> <th>First Name</th> <th>Last Name</th> <th>Username</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Mark</td> <td>Otto</td> <td>@mdo</td> </tr> <tr> <td>2</td> <td>Jacob</td> <td>Thornton</td> <td>@fat</td> </tr> <tr> <td>3</td> <td>Larry</td> <td>the Bird</td> <td>@twitter</td> </tr> </tbody> </table> </div> </div> <div class="row"> <div class="col-md-6"> <table class="table table-bordered"> <thead> <tr> <th>#</th> <th>First Name</th> <th>Last Name</th> <th>Username</th> </tr> </thead> <tbody> <tr> <td rowspan="2">1</td> <td>Mark</td> <td>Otto</td> <td>@mdo</td> </tr> <tr> <td>Mark</td> <td>Otto</td> <td>@TwBootstrap</td> </tr> <tr> <td>2</td> <td>Jacob</td> <td>Thornton</td> <td>@fat</td> </tr> <tr> <td>3</td> <td colspan="2">Larry the Bird</td> <td>@twitter</td> </tr> </tbody> </table> </div> <div class="col-md-6"> <table class="table table-condensed"> <thead> <tr> <th>#</th> <th>First Name</th> <th>Last Name</th> <th>Username</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Mark</td> <td>Otto</td> <td>@mdo</td> </tr> <tr> <td>2</td> <td>Jacob</td> <td>Thornton</td> <td>@fat</td> </tr> <tr> <td>3</td> <td colspan="2">Larry the Bird</td> <td>@twitter</td> </tr> </tbody> </table> </div> </div> <div class="page-header"> <h1>Thumbnails</h1> </div> <img data-src="holder.js/200x200" class="img-thumbnail" alt="200x200" style="width: 200px; height: 200px;" src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9InllcyI/PjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgdmlld0JveD0iMCAwIDIwMCAyMDAiIHByZXNlcnZlQXNwZWN0UmF0aW89Im5vbmUiPjwhLS0KU291cmNlIFVSTDogaG9sZGVyLmpzLzIwMHgyMDAKQ3JlYXRlZCB3aXRoIEhvbGRlci5qcyAyLjYuMC4KTGVhcm4gbW9yZSBhdCBodHRwOi8vaG9sZGVyanMuY29tCihjKSAyMDEyLTIwMTUgSXZhbiBNYWxvcGluc2t5IC0gaHR0cDovL2ltc2t5LmNvCi0tPjxkZWZzPjxzdHlsZSB0eXBlPSJ0ZXh0L2NzcyI+PCFbQ0RBVEFbI2hvbGRlcl8xNTYwZTAxMWI3ZCB0ZXh0IHsgZmlsbDojQUFBQUFBO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1mYW1pbHk6QXJpYWwsIEhlbHZldGljYSwgT3BlbiBTYW5zLCBzYW5zLXNlcmlmLCBtb25vc3BhY2U7Zm9udC1zaXplOjEwcHQgfSBdXT48L3N0eWxlPjwvZGVmcz48ZyBpZD0iaG9sZGVyXzE1NjBlMDExYjdkIj48cmVjdCB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgZmlsbD0iI0VFRUVFRSIvPjxnPjx0ZXh0IHg9Ijc0LjA1NDY4NzUiIHk9IjEwNC41Ij4yMDB4MjAwPC90ZXh0PjwvZz48L2c+PC9zdmc+" data-holder-rendered="true"> <div class="page-header"> <h1>Labels</h1> </div> <h1> <span class="label label-default">Default</span> <span class="label label-primary">Primary</span> <span class="label label-success">Success</span> <span class="label label-info">Info</span> <span class="label label-warning">Warning</span> <span class="label label-danger">Danger</span> </h1> <h2> <span class="label label-default">Default</span> <span class="label label-primary">Primary</span> <span class="label label-success">Success</span> <span class="label label-info">Info</span> <span class="label label-warning">Warning</span> <span class="label label-danger">Danger</span> </h2> <h3> <span class="label label-default">Default</span> <span class="label label-primary">Primary</span> <span class="label label-success">Success</span> <span class="label label-info">Info</span> <span class="label label-warning">Warning</span> <span class="label label-danger">Danger</span> </h3> <h4> <span class="label label-default">Default</span> <span class="label label-primary">Primary</span> <span class="label label-success">Success</span> <span class="label label-info">Info</span> <span class="label label-warning">Warning</span> <span class="label label-danger">Danger</span> </h4> <h5> <span class="label label-default">Default</span> <span class="label label-primary">Primary</span> <span class="label label-success">Success</span> <span class="label label-info">Info</span> <span class="label label-warning">Warning</span> <span class="label label-danger">Danger</span> </h5> <h6> <span class="label label-default">Default</span> <span class="label label-primary">Primary</span> <span class="label label-success">Success</span> <span class="label label-info">Info</span> <span class="label label-warning">Warning</span> <span class="label label-danger">Danger</span> </h6> <p> <span class="label label-default">Default</span> <span class="label label-primary">Primary</span> <span class="label label-success">Success</span> <span class="label label-info">Info</span> <span class="label label-warning">Warning</span> <span class="label label-danger">Danger</span> </p> <div class="page-header"> <h1>Badges</h1> </div> <p> <a href="#">42</span></a> </p> <ul class="nav nav-pills" role="tablist"> <li role="presentation" class="active"><a href="#">42</span></a></li> <li role="presentation"><a href="#">Profile</a></li> <li role="presentation"><a href="#">3</span></a></li> </ul> <div class="page-header"> <h1>Dropdown menus</h1> </div> <div class="dropdown theme-dropdown clearfix"> <a id="dropdownMenu1" href="#"></span></a> <ul class="dropdown-menu" aria-labelledby="dropdownMenu1"> <li class="active"><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li role="separator" class="divider"></li> <li><a href="#">Separated link</a></li> </ul> </div> <div class="page-header"> <h1>Navs</h1> </div> <ul class="nav nav-tabs" role="tablist"> <li role="presentation" class="active"><a href="#">Home</a></li> <li role="presentation"><a href="#">Profile</a></li> <li role="presentation"><a href="#">Messages</a></li> </ul> <ul class="nav nav-pills" role="tablist"> <li role="presentation" class="active"><a href="#">Home</a></li> <li role="presentation"><a href="#">Profile</a></li> <li role="presentation"><a href="#">Messages</a></li> </ul> <div class="page-header"> <h1>Navbars</h1> </div> <nav class="navbar navbar-default"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Project name</a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> <li class="dropdown"> <a href="#"></span></a> <ul class="dropdown-menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li role="separator" class="divider"></li> <li class="dropdown-header">Nav header</li> <li><a href="#">Separated link</a></li> <li><a href="#">One more separated link</a></li> </ul> </li> </ul> </div><!--/.nav-collapse --> </div> </nav> <nav class="navbar navbar-inverse"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Project name</a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> <li class="dropdown"> <a href="#"></span></a> <ul class="dropdown-menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li role="separator" class="divider"></li> <li class="dropdown-header">Nav header</li> <li><a href="#">Separated link</a></li> <li><a href="#">One more separated link</a></li> </ul> </li> </ul> </div><!--/.nav-collapse --> </div> </nav> <div class="page-header"> <h1>Alerts</h1> </div> <div class="alert alert-success" role="alert"> <strong>Well done!</strong> You successfully read this important alert message. With a <a href="#">link</a>. </div> <div class="alert alert-info" role="alert"> <strong>Heads up!</strong> This alert needs your attention, but it's not super important. </div> <div class="alert alert-warning" role="alert"> <strong>Warning!</strong> Best check yo self, you're not looking too good. </div> <div class="alert alert-danger" role="alert"> <strong>Oh snap!</strong> Change a few things up and try submitting again. </div> <div class="page-header"> <h1>Progress bars</h1> </div> <div class="progress"> <div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%;"><span class="sr-only">60% Complete</span></div> </div> <div class="progress"> <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%"><span class="sr-only">40% Complete (success)</span></div> </div> <div class="progress"> <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 20%"><span class="sr-only">20% Complete</span></div> </div> <div class="progress"> <div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%"><span class="sr-only">60% Complete (warning)</span></div> </div> <div class="progress"> <div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width: 80%"><span class="sr-only">80% Complete (danger)</span></div> </div> <div class="progress"> <div class="progress-bar progress-bar-striped" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%"><span class="sr-only">60% Complete</span></div> </div> <div class="progress"> <div class="progress-bar progress-bar-success" style="width: 35%"><span class="sr-only">35% Complete (success)</span></div> <div class="progress-bar progress-bar-warning" style="width: 20%"><span class="sr-only">20% Complete (warning)</span></div> <div class="progress-bar progress-bar-danger" style="width: 10%"><span class="sr-only">10% Complete (danger)</span></div> </div> <div class="page-header"> <h1>List groups</h1> </div> <div class="row"> <div class="col-sm-4"> <ul class="list-group"> <li class="list-group-item">Cras justo odio</li> <li class="list-group-item">Dapibus ac facilisis in</li> <li class="list-group-item">Morbi leo risus</li> <li class="list-group-item">Porta ac consectetur ac</li> <li class="list-group-item">Vestibulum at eros</li> </ul> </div><!-- /.col-sm-4 --> <div class="col-sm-4"> <div class="list-group"> <a href="#"> Cras justo odio </a> <a href="#">Dapibus ac facilisis in</a> <a href="#">Morbi leo risus</a> <a href="#">Porta ac consectetur ac</a> <a href="#">Vestibulum at eros</a> </div> </div><!-- /.col-sm-4 --> <div class="col-sm-4"> <div class="list-group"> <a href="#"> <h4 class="list-group-item-heading">List group item heading</h4> <p class="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p> </a> <a href="#"> <h4 class="list-group-item-heading">List group item heading</h4> <p class="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p> </a> <a href="#"> <h4 class="list-group-item-heading">List group item heading</h4> <p class="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p> </a> </div> </div><!-- /.col-sm-4 --> </div> <div class="page-header"> <h1>Panels</h1> </div> <div class="row"> <div class="col-sm-4"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Panel title</h3> </div> <div class="panel-body"> Panel content </div> </div> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">Panel title</h3> </div> <div class="panel-body"> Panel content </div> </div> </div><!-- /.col-sm-4 --> <div class="col-sm-4"> <div class="panel panel-success"> <div class="panel-heading"> <h3 class="panel-title">Panel title</h3> </div> <div class="panel-body"> Panel content </div> </div> <div class="panel panel-info"> <div class="panel-heading"> <h3 class="panel-title">Panel title</h3> </div> <div class="panel-body"> Panel content </div> </div> </div><!-- /.col-sm-4 --> <div class="col-sm-4"> <div class="panel panel-warning"> <div class="panel-heading"> <h3 class="panel-title">Panel title</h3> </div> <div class="panel-body"> Panel content </div> </div> <div class="panel panel-danger"> <div class="panel-heading"> <h3 class="panel-title">Panel title</h3> </div> <div class="panel-body"> Panel content </div> </div> </div><!-- /.col-sm-4 --> </div> <div class="page-header"> <h1>Wells</h1> </div> <div class="well"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sed diam eget risus varius blandit sit amet non magna. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Cras mattis consectetur purus sit amet fermentum. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Aenean lacinia bibendum nulla sed consectetur.</p> </div> <ul class="nav nav-tabs"> <li role="presentation" class="active"><a href="#">Home</a></li> <li role="presentation"><a href="#">Profile</a></li> <li role="presentation"><a href="#">Messages</a></li> </ul> This is tabs above here </div> <!-- /container --> {% endblock %}
superset/templates/superset/paper-theme.html
0
https://github.com/apache/superset/commit/3107152f5bb973b8b1a9c5cf3bc2bee1d7f47e0d
[ 0.00019787228666245937, 0.00017147640755865723, 0.0001675541279837489, 0.00017088996537495404, 0.000004014647402073024 ]
{ "id": 1, "code_window": [ "\n", " @classmethod\n", " def sql_preprocessor(cls, sql):\n", " \"\"\"If the SQL needs to be altered prior to running it\n", "\n", " For example db api needs to double `%` characters\n", " \"\"\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " For example Presto needs to double `%` characters\n" ], "file_path": "superset/db_engine_specs.py", "type": "replace", "edit_start_line_idx": 117 }
from datetime import datetime import logging import sqlparse import pandas as pd from sqlalchemy import ( Column, Integer, String, ForeignKey, Text, Boolean, DateTime, ) import sqlalchemy as sa from sqlalchemy import asc, and_, desc, select from sqlalchemy.ext.compiler import compiles from sqlalchemy.sql.expression import ColumnClause, TextAsFrom from sqlalchemy.orm import backref, relationship from sqlalchemy.sql import table, literal_column, text, column from flask import escape, Markup from flask_appbuilder import Model from flask_babel import lazy_gettext as _ from superset import db, utils, import_util from superset.connectors.base import BaseDatasource, BaseColumn, BaseMetric from superset.utils import ( wrap_clause_in_parens, DTTM_ALIAS, QueryStatus ) from superset.models.helpers import QueryResult from superset.models.core import Database from superset.jinja_context import get_template_processor from superset.models.helpers import set_perm class TableColumn(Model, BaseColumn): """ORM object for table columns, each table can have multiple columns""" __tablename__ = 'table_columns' table_id = Column(Integer, ForeignKey('tables.id')) table = relationship( 'SqlaTable', backref=backref('columns', cascade='all, delete-orphan'), foreign_keys=[table_id]) is_dttm = Column(Boolean, default=False) expression = Column(Text, default='') python_date_format = Column(String(255)) database_expression = Column(String(255)) export_fields = ( 'table_id', 'column_name', 'verbose_name', 'is_dttm', 'is_active', 'type', 'groupby', 'count_distinct', 'sum', 'avg', 'max', 'min', 'filterable', 'expression', 'description', 'python_date_format', 'database_expression' ) @property def sqla_col(self): name = self.column_name if not self.expression: col = column(self.column_name).label(name) else: col = literal_column(self.expression).label(name) return col def get_time_filter(self, start_dttm, end_dttm): col = self.sqla_col.label('__time') return and_( col >= text(self.dttm_sql_literal(start_dttm)), col <= text(self.dttm_sql_literal(end_dttm)), ) def get_timestamp_expression(self, time_grain): """Getting the time component of the query""" expr = self.expression or self.column_name if not self.expression and not time_grain: return column(expr, type_=DateTime).label(DTTM_ALIAS) if time_grain: pdf = self.python_date_format if pdf in ('epoch_s', 'epoch_ms'): # if epoch, translate to DATE using db specific conf db_spec = self.table.database.db_engine_spec if pdf == 'epoch_s': expr = db_spec.epoch_to_dttm().format(col=expr) elif pdf == 'epoch_ms': expr = db_spec.epoch_ms_to_dttm().format(col=expr) grain = self.table.database.grains_dict().get(time_grain, '{col}') expr = grain.function.format(col=expr) return literal_column(expr, type_=DateTime).label(DTTM_ALIAS) @classmethod def import_obj(cls, i_column): def lookup_obj(lookup_column): return db.session.query(TableColumn).filter( TableColumn.table_id == lookup_column.table_id, TableColumn.column_name == lookup_column.column_name).first() return import_util.import_simple_obj(db.session, i_column, lookup_obj) def dttm_sql_literal(self, dttm): """Convert datetime object to a SQL expression string If database_expression is empty, the internal dttm will be parsed as the string with the pattern that the user inputted (python_date_format) If database_expression is not empty, the internal dttm will be parsed as the sql sentence for the database to convert """ tf = self.python_date_format or '%Y-%m-%d %H:%M:%S.%f' if self.database_expression: return self.database_expression.format(dttm.strftime('%Y-%m-%d %H:%M:%S')) elif tf == 'epoch_s': return str((dttm - datetime(1970, 1, 1)).total_seconds()) elif tf == 'epoch_ms': return str((dttm - datetime(1970, 1, 1)).total_seconds() * 1000.0) else: s = self.table.database.db_engine_spec.convert_dttm( self.type, dttm) return s or "'{}'".format(dttm.strftime(tf)) class SqlMetric(Model, BaseMetric): """ORM object for metrics, each table can have multiple metrics""" __tablename__ = 'sql_metrics' table_id = Column(Integer, ForeignKey('tables.id')) table = relationship( 'SqlaTable', backref=backref('metrics', cascade='all, delete-orphan'), foreign_keys=[table_id]) expression = Column(Text) export_fields = ( 'metric_name', 'verbose_name', 'metric_type', 'table_id', 'expression', 'description', 'is_restricted', 'd3format') @property def sqla_col(self): name = self.metric_name return literal_column(self.expression).label(name) @property def perm(self): return ( "{parent_name}.[{obj.metric_name}](id:{obj.id})" ).format(obj=self, parent_name=self.table.full_name) if self.table else None @classmethod def import_obj(cls, i_metric): def lookup_obj(lookup_metric): return db.session.query(SqlMetric).filter( SqlMetric.table_id == lookup_metric.table_id, SqlMetric.metric_name == lookup_metric.metric_name).first() return import_util.import_simple_obj(db.session, i_metric, lookup_obj) class SqlaTable(Model, BaseDatasource): """An ORM object for SqlAlchemy table references""" type = "table" query_language = 'sql' metric_class = SqlMetric __tablename__ = 'tables' id = Column(Integer, primary_key=True) table_name = Column(String(250)) main_dttm_col = Column(String(250)) description = Column(Text) default_endpoint = Column(Text) database_id = Column(Integer, ForeignKey('dbs.id'), nullable=False) is_featured = Column(Boolean, default=False) filter_select_enabled = Column(Boolean, default=False) user_id = Column(Integer, ForeignKey('ab_user.id')) owner = relationship('User', backref='tables', foreign_keys=[user_id]) database = relationship( 'Database', backref=backref('tables', cascade='all, delete-orphan'), foreign_keys=[database_id]) offset = Column(Integer, default=0) cache_timeout = Column(Integer) schema = Column(String(255)) sql = Column(Text) params = Column(Text) perm = Column(String(1000)) baselink = "tablemodelview" column_cls = TableColumn metric_cls = SqlMetric export_fields = ( 'table_name', 'main_dttm_col', 'description', 'default_endpoint', 'database_id', 'is_featured', 'offset', 'cache_timeout', 'schema', 'sql', 'params') __table_args__ = ( sa.UniqueConstraint( 'database_id', 'schema', 'table_name', name='_customer_location_uc'),) def __repr__(self): return self.name @property def description_markeddown(self): return utils.markdown(self.description) @property def link(self): name = escape(self.name) return Markup( '<a href="{self.explore_url}">{name}</a>'.format(**locals())) @property def schema_perm(self): """Returns schema permission if present, database one otherwise.""" return utils.get_schema_perm(self.database, self.schema) def get_perm(self): return ( "[{obj.database}].[{obj.table_name}]" "(id:{obj.id})").format(obj=self) @property def name(self): if not self.schema: return self.table_name return "{}.{}".format(self.schema, self.table_name) @property def full_name(self): return utils.get_datasource_full_name( self.database, self.table_name, schema=self.schema) @property def dttm_cols(self): l = [c.column_name for c in self.columns if c.is_dttm] if self.main_dttm_col and self.main_dttm_col not in l: l.append(self.main_dttm_col) return l @property def num_cols(self): return [c.column_name for c in self.columns if c.is_num] @property def any_dttm_col(self): cols = self.dttm_cols if cols: return cols[0] @property def html(self): t = ((c.column_name, c.type) for c in self.columns) df = pd.DataFrame(t) df.columns = ['field', 'type'] return df.to_html( index=False, classes=( "dataframe table table-striped table-bordered " "table-condensed")) @property def metrics_combo(self): return sorted( [ (m.metric_name, m.verbose_name or m.metric_name) for m in self.metrics], key=lambda x: x[1]) @property def sql_url(self): return self.database.sql_url + "?table_name=" + str(self.table_name) @property def time_column_grains(self): return { "time_columns": self.dttm_cols, "time_grains": [grain.name for grain in self.database.grains()] } def get_col(self, col_name): columns = self.columns for col in columns: if col_name == col.column_name: return col def values_for_column(self, column_name, from_dttm, to_dttm, limit=500): """Runs query against sqla to retrieve some sample values for the given column. """ granularity = self.main_dttm_col cols = {col.column_name: col for col in self.columns} target_col = cols[column_name] tbl = table(self.table_name) qry = sa.select([target_col.sqla_col]) qry = qry.select_from(tbl) qry = qry.distinct(column_name) qry = qry.limit(limit) if granularity: dttm_col = cols[granularity] timestamp = dttm_col.sqla_col.label('timestamp') time_filter = [ timestamp >= text(dttm_col.dttm_sql_literal(from_dttm)), timestamp <= text(dttm_col.dttm_sql_literal(to_dttm)), ] qry = qry.where(and_(*time_filter)) engine = self.database.get_sqla_engine() sql = "{}".format( qry.compile( engine, compile_kwargs={"literal_binds": True}, ), ) return pd.read_sql_query( sql=sql, con=engine ) def get_query_str( # sqla self, engine, qry_start_dttm, groupby, metrics, granularity, from_dttm, to_dttm, filter=None, # noqa is_timeseries=True, timeseries_limit=15, timeseries_limit_metric=None, row_limit=None, inner_from_dttm=None, inner_to_dttm=None, orderby=None, extras=None, columns=None): """Querying any sqla table from this common interface""" template_kwargs = { 'from_dttm': from_dttm, 'groupby': groupby, 'metrics': metrics, 'row_limit': row_limit, 'to_dttm': to_dttm, } template_processor = get_template_processor( table=self, database=self.database, **template_kwargs) # For backward compatibility if granularity not in self.dttm_cols: granularity = self.main_dttm_col cols = {col.column_name: col for col in self.columns} metrics_dict = {m.metric_name: m for m in self.metrics} if not granularity and is_timeseries: raise Exception(_( "Datetime column not provided as part table configuration " "and is required by this type of chart")) for m in metrics: if m not in metrics_dict: raise Exception(_("Metric '{}' is not valid".format(m))) metrics_exprs = [metrics_dict.get(m).sqla_col for m in metrics] timeseries_limit_metric = metrics_dict.get(timeseries_limit_metric) timeseries_limit_metric_expr = None if timeseries_limit_metric: timeseries_limit_metric_expr = \ timeseries_limit_metric.sqla_col if metrics: main_metric_expr = metrics_exprs[0] else: main_metric_expr = literal_column("COUNT(*)").label("ccount") select_exprs = [] groupby_exprs = [] if groupby: select_exprs = [] inner_select_exprs = [] inner_groupby_exprs = [] for s in groupby: col = cols[s] outer = col.sqla_col inner = col.sqla_col.label(col.column_name + '__') groupby_exprs.append(outer) select_exprs.append(outer) inner_groupby_exprs.append(inner) inner_select_exprs.append(inner) elif columns: for s in columns: select_exprs.append(cols[s].sqla_col) metrics_exprs = [] if granularity: @compiles(ColumnClause) def visit_column(element, compiler, **kw): """Patch for sqlalchemy bug TODO: sqlalchemy 1.2 release should be doing this on its own. Patch only if the column clause is specific for DateTime set and granularity is selected. """ text = compiler.visit_column(element, **kw) try: if ( element.is_literal and hasattr(element.type, 'python_type') and type(element.type) is DateTime ): text = text.replace('%%', '%') except NotImplementedError: # Some elements raise NotImplementedError for python_type pass return text dttm_col = cols[granularity] time_grain = extras.get('time_grain_sqla') if is_timeseries: timestamp = dttm_col.get_timestamp_expression(time_grain) select_exprs += [timestamp] groupby_exprs += [timestamp] time_filter = dttm_col.get_time_filter(from_dttm, to_dttm) select_exprs += metrics_exprs qry = sa.select(select_exprs) tbl = table(self.table_name) if self.schema: tbl.schema = self.schema # Supporting arbitrary SQL statements in place of tables if self.sql: from_sql = template_processor.process_template(self.sql) tbl = TextAsFrom(sa.text(from_sql), []).alias('expr_qry') if not columns: qry = qry.group_by(*groupby_exprs) where_clause_and = [] having_clause_and = [] for flt in filter: if not all([flt.get(s) for s in ['col', 'op', 'val']]): continue col = flt['col'] op = flt['op'] eq = flt['val'] col_obj = cols.get(col) if col_obj and op in ('in', 'not in'): values = [types.strip("'").strip('"') for types in eq] if col_obj.is_num: values = [utils.js_string_to_num(s) for s in values] cond = col_obj.sqla_col.in_(values) if op == 'not in': cond = ~cond where_clause_and.append(cond) if extras: where = extras.get('where') if where: where_clause_and += [wrap_clause_in_parens( template_processor.process_template(where))] having = extras.get('having') if having: having_clause_and += [wrap_clause_in_parens( template_processor.process_template(having))] if granularity: qry = qry.where(and_(*([time_filter] + where_clause_and))) else: qry = qry.where(and_(*where_clause_and)) qry = qry.having(and_(*having_clause_and)) if groupby: qry = qry.order_by(desc(main_metric_expr)) elif orderby: for col, ascending in orderby: direction = asc if ascending else desc qry = qry.order_by(direction(col)) qry = qry.limit(row_limit) if is_timeseries and timeseries_limit and groupby: # some sql dialects require for order by expressions # to also be in the select clause -- others, e.g. vertica, # require a unique inner alias inner_main_metric_expr = main_metric_expr.label('mme_inner__') inner_select_exprs += [inner_main_metric_expr] subq = select(inner_select_exprs) subq = subq.select_from(tbl) inner_time_filter = dttm_col.get_time_filter( inner_from_dttm or from_dttm, inner_to_dttm or to_dttm, ) subq = subq.where(and_(*(where_clause_and + [inner_time_filter]))) subq = subq.group_by(*inner_groupby_exprs) ob = inner_main_metric_expr if timeseries_limit_metric_expr is not None: ob = timeseries_limit_metric_expr subq = subq.order_by(desc(ob)) subq = subq.limit(timeseries_limit) on_clause = [] for i, gb in enumerate(groupby): on_clause.append( groupby_exprs[i] == column(gb + '__')) tbl = tbl.join(subq.alias(), and_(*on_clause)) qry = qry.select_from(tbl) sql = "{}".format( qry.compile( engine, compile_kwargs={"literal_binds": True},), ) logging.info(sql) sql = sqlparse.format(sql, reindent=True) sql = self.database.db_engine_spec.sql_preprocessor(sql) return sql def query(self, query_obj): qry_start_dttm = datetime.now() engine = self.database.get_sqla_engine() sql = self.get_query_str(engine, qry_start_dttm, **query_obj) status = QueryStatus.SUCCESS error_message = None df = None try: df = pd.read_sql_query(sql, con=engine) except Exception as e: status = QueryStatus.FAILED error_message = str(e) return QueryResult( status=status, df=df, duration=datetime.now() - qry_start_dttm, query=sql, error_message=error_message) def get_sqla_table_object(self): return self.database.get_table(self.table_name, schema=self.schema) def fetch_metadata(self): """Fetches the metadata for the table and merges it in""" try: table = self.get_sqla_table_object() except Exception: raise Exception( "Table doesn't seem to exist in the specified database, " "couldn't fetch column information") TC = TableColumn # noqa shortcut to class M = SqlMetric # noqa metrics = [] any_date_col = None for col in table.columns: try: datatype = "{}".format(col.type).upper() except Exception as e: datatype = "UNKNOWN" logging.error( "Unrecognized data type in {}.{}".format(table, col.name)) logging.exception(e) dbcol = ( db.session .query(TC) .filter(TC.table == self) .filter(TC.column_name == col.name) .first() ) db.session.flush() if not dbcol: dbcol = TableColumn(column_name=col.name, type=datatype) dbcol.groupby = dbcol.is_string dbcol.filterable = dbcol.is_string dbcol.sum = dbcol.is_num dbcol.avg = dbcol.is_num dbcol.is_dttm = dbcol.is_time db.session.merge(self) self.columns.append(dbcol) if not any_date_col and dbcol.is_time: any_date_col = col.name quoted = "{}".format( column(dbcol.column_name).compile(dialect=db.engine.dialect)) if dbcol.sum: metrics.append(M( metric_name='sum__' + dbcol.column_name, verbose_name='sum__' + dbcol.column_name, metric_type='sum', expression="SUM({})".format(quoted) )) if dbcol.avg: metrics.append(M( metric_name='avg__' + dbcol.column_name, verbose_name='avg__' + dbcol.column_name, metric_type='avg', expression="AVG({})".format(quoted) )) if dbcol.max: metrics.append(M( metric_name='max__' + dbcol.column_name, verbose_name='max__' + dbcol.column_name, metric_type='max', expression="MAX({})".format(quoted) )) if dbcol.min: metrics.append(M( metric_name='min__' + dbcol.column_name, verbose_name='min__' + dbcol.column_name, metric_type='min', expression="MIN({})".format(quoted) )) if dbcol.count_distinct: metrics.append(M( metric_name='count_distinct__' + dbcol.column_name, verbose_name='count_distinct__' + dbcol.column_name, metric_type='count_distinct', expression="COUNT(DISTINCT {})".format(quoted) )) dbcol.type = datatype db.session.merge(self) db.session.commit() metrics.append(M( metric_name='count', verbose_name='COUNT(*)', metric_type='count', expression="COUNT(*)" )) for metric in metrics: m = ( db.session.query(M) .filter(M.metric_name == metric.metric_name) .filter(M.table_id == self.id) .first() ) metric.table_id = self.id if not m: db.session.add(metric) db.session.commit() if not self.main_dttm_col: self.main_dttm_col = any_date_col @classmethod def import_obj(cls, i_datasource, import_time=None): """Imports the datasource from the object to the database. Metrics and columns and datasource will be overrided if exists. This function can be used to import/export dashboards between multiple superset instances. Audit metadata isn't copies over. """ def lookup_sqlatable(table): return db.session.query(SqlaTable).join(Database).filter( SqlaTable.table_name == table.table_name, SqlaTable.schema == table.schema, Database.id == table.database_id, ).first() def lookup_database(table): return db.session.query(Database).filter_by( database_name=table.params_dict['database_name']).one() return import_util.import_datasource( db.session, i_datasource, lookup_database, lookup_sqlatable, import_time) sa.event.listen(SqlaTable, 'after_insert', set_perm) sa.event.listen(SqlaTable, 'after_update', set_perm)
superset/connectors/sqla/models.py
1
https://github.com/apache/superset/commit/3107152f5bb973b8b1a9c5cf3bc2bee1d7f47e0d
[ 0.9205329418182373, 0.030954083427786827, 0.00016843515913933516, 0.0005729220574721694, 0.15217292308807373 ]
{ "id": 1, "code_window": [ "\n", " @classmethod\n", " def sql_preprocessor(cls, sql):\n", " \"\"\"If the SQL needs to be altered prior to running it\n", "\n", " For example db api needs to double `%` characters\n", " \"\"\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " For example Presto needs to double `%` characters\n" ], "file_path": "superset/db_engine_specs.py", "type": "replace", "edit_start_line_idx": 117 }
import shortid from 'shortid'; import * as actions from './actions'; import { now } from '../modules/dates'; import { addToObject, alterInObject, alterInArr, removeFromArr, getFromArr, addToArr } from '../reduxUtils.js'; export function getInitialState(defaultDbId) { const defaultQueryEditor = { id: shortid.generate(), title: 'Untitled Query', sql: 'SELECT *\nFROM\nWHERE', selectedText: null, latestQueryId: null, autorun: false, dbId: defaultDbId, }; return { alerts: [], networkOn: true, queries: {}, databases: {}, queryEditors: [defaultQueryEditor], tabHistory: [defaultQueryEditor.id], tables: [], queriesLastUpdate: 0, activeSouthPaneTab: 'Results', }; } export const sqlLabReducer = function (state, action) { const actionHandlers = { [actions.ADD_QUERY_EDITOR]() { const tabHistory = state.tabHistory.slice(); tabHistory.push(action.queryEditor.id); const newState = Object.assign({}, state, { tabHistory }); return addToArr(newState, 'queryEditors', action.queryEditor); }, [actions.CLONE_QUERY_TO_NEW_TAB]() { const progenitor = state.queryEditors.find((qe) => qe.id === state.tabHistory[state.tabHistory.length - 1]); const qe = { id: shortid.generate(), title: `Copy of ${progenitor.title}`, dbId: (action.query.dbId) ? action.query.dbId : null, schema: (action.query.schema) ? action.query.schema : null, autorun: true, sql: action.query.sql, }; return sqlLabReducer(state, actions.addQueryEditor(qe)); }, [actions.REMOVE_QUERY_EDITOR]() { let newState = removeFromArr(state, 'queryEditors', action.queryEditor); // List of remaining queryEditor ids const qeIds = newState.queryEditors.map((qe) => qe.id); const queries = {}; Object.keys(state.queries).forEach((k) => { const query = state.queries[k]; if (qeIds.indexOf(query.sqlEditorId) > -1) { queries[k] = query; } }); let tabHistory = state.tabHistory.slice(); tabHistory = tabHistory.filter((id) => qeIds.indexOf(id) > -1); newState = Object.assign({}, newState, { tabHistory, queries }); return newState; }, [actions.REMOVE_QUERY]() { const newQueries = Object.assign({}, state.queries); delete newQueries[action.query.id]; return Object.assign({}, state, { queries: newQueries }); }, [actions.RESET_STATE]() { return Object.assign({}, getInitialState()); }, [actions.MERGE_TABLE]() { const at = Object.assign({}, action.table); let existingTable; state.tables.forEach((t) => { if ( t.dbId === at.dbId && t.queryEditorId === at.queryEditorId && t.schema === at.schema && t.name === at.name) { existingTable = t; } }); if (existingTable) { if (action.query) { at.dataPreviewQueryId = action.query.id; } return alterInArr(state, 'tables', existingTable, at); } at.id = shortid.generate(); // for new table, associate Id of query for data preview at.dataPreviewQueryId = null; let newState = addToArr(state, 'tables', at); if (action.query) { newState = alterInArr(newState, 'tables', at, { dataPreviewQueryId: action.query.id }); } return newState; }, [actions.EXPAND_TABLE]() { return alterInArr(state, 'tables', action.table, { expanded: true }); }, [actions.REMOVE_DATA_PREVIEW]() { const queries = Object.assign({}, state.queries); delete queries[action.table.dataPreviewQueryId]; const newState = alterInArr(state, 'tables', action.table, { dataPreviewQueryId: null }); return Object.assign( {}, newState, { queries }); }, [actions.CHANGE_DATA_PREVIEW_ID]() { const queries = Object.assign({}, state.queries); delete queries[action.oldQueryId]; const newTables = []; state.tables.forEach((t) => { if (t.dataPreviewQueryId === action.oldQueryId) { newTables.push(Object.assign({}, t, { dataPreviewQueryId: action.newQuery.id })); } else { newTables.push(t); } }); return Object.assign( {}, state, { queries, tables: newTables, activeSouthPaneTab: action.newQuery.id }); }, [actions.COLLAPSE_TABLE]() { return alterInArr(state, 'tables', action.table, { expanded: false }); }, [actions.REMOVE_TABLE]() { return removeFromArr(state, 'tables', action.table); }, [actions.START_QUERY]() { let newState = Object.assign({}, state); if (action.query.sqlEditorId) { const qe = getFromArr(state.queryEditors, action.query.sqlEditorId); if (qe.latestQueryId && state.queries[qe.latestQueryId]) { const newResults = Object.assign( {}, state.queries[qe.latestQueryId].results, { data: [], query: null }); const q = Object.assign({}, state.queries[qe.latestQueryId], { results: newResults }); const queries = Object.assign({}, state.queries, { [q.id]: q }); newState = Object.assign({}, state, { queries }); } } else { newState.activeSouthPaneTab = action.query.id; } newState = addToObject(newState, 'queries', action.query); const sqlEditor = { id: action.query.sqlEditorId }; return alterInArr(newState, 'queryEditors', sqlEditor, { latestQueryId: action.query.id }); }, [actions.STOP_QUERY]() { return alterInObject(state, 'queries', action.query, { state: 'stopped', results: [] }); }, [actions.CLEAR_QUERY_RESULTS]() { const newResults = Object.assign({}, action.query.results); newResults.data = []; return alterInObject(state, 'queries', action.query, { results: newResults, cached: true }); }, [actions.REQUEST_QUERY_RESULTS]() { return alterInObject(state, 'queries', action.query, { state: 'fetching' }); }, [actions.QUERY_SUCCESS]() { if (action.query.state === 'stopped') { return state; } let rows; if (action.results.data) { rows = action.results.data.length; } const alts = { endDttm: now(), progress: 100, results: action.results, rows, state: 'success', errorMessage: null, cached: false, }; return alterInObject(state, 'queries', action.query, alts); }, [actions.QUERY_FAILED]() { if (action.query.state === 'stopped') { return state; } const alts = { state: 'failed', errorMessage: action.msg, endDttm: now() }; return alterInObject(state, 'queries', action.query, alts); }, [actions.SET_ACTIVE_QUERY_EDITOR]() { const qeIds = state.queryEditors.map((qe) => qe.id); if (qeIds.indexOf(action.queryEditor.id) > -1) { const tabHistory = state.tabHistory.slice(); tabHistory.push(action.queryEditor.id); return Object.assign({}, state, { tabHistory }); } return state; }, [actions.SET_ACTIVE_SOUTHPANE_TAB]() { return Object.assign({}, state, { activeSouthPaneTab: action.tabId }); }, [actions.QUERY_EDITOR_SETDB]() { return alterInArr(state, 'queryEditors', action.queryEditor, { dbId: action.dbId }); }, [actions.QUERY_EDITOR_SET_SCHEMA]() { return alterInArr(state, 'queryEditors', action.queryEditor, { schema: action.schema }); }, [actions.QUERY_EDITOR_SET_TITLE]() { return alterInArr(state, 'queryEditors', action.queryEditor, { title: action.title }); }, [actions.QUERY_EDITOR_SET_SQL]() { return alterInArr(state, 'queryEditors', action.queryEditor, { sql: action.sql }); }, [actions.QUERY_EDITOR_SET_SELECTED_TEXT]() { return alterInArr(state, 'queryEditors', action.queryEditor, { selectedText: action.sql }); }, [actions.QUERY_EDITOR_SET_AUTORUN]() { return alterInArr(state, 'queryEditors', action.queryEditor, { autorun: action.autorun }); }, [actions.ADD_ALERT]() { return addToArr(state, 'alerts', action.alert); }, [actions.SET_DATABASES]() { const databases = {}; action.databases.forEach((db) => { databases[db.id] = db; }); return Object.assign({}, state, { databases }); }, [actions.REMOVE_ALERT]() { return removeFromArr(state, 'alerts', action.alert); }, [actions.SET_NETWORK_STATUS]() { if (state.networkOn !== action.networkOn) { return Object.assign({}, state, { networkOn: action.networkOn }); } return state; }, [actions.REFRESH_QUERIES]() { let newQueries = Object.assign({}, state.queries); // Fetch the updates to the queries present in the store. let change = false; for (const id in action.alteredQueries) { const changedQuery = action.alteredQueries[id]; if (!state.queries.hasOwnProperty(id) || (state.queries[id].changedOn !== changedQuery.changedOn && state.queries[id].state !== 'stopped')) { newQueries[id] = Object.assign({}, state.queries[id], changedQuery); change = true; } } if (!change) { newQueries = state.queries; } const queriesLastUpdate = now(); return Object.assign({}, state, { queries: newQueries, queriesLastUpdate }); }, }; if (action.type in actionHandlers) { return actionHandlers[action.type](); } return state; };
superset/assets/javascripts/SqlLab/reducers.js
0
https://github.com/apache/superset/commit/3107152f5bb973b8b1a9c5cf3bc2bee1d7f47e0d
[ 0.0008255721186287701, 0.00023166077153291553, 0.00016469898400828242, 0.00017052088514901698, 0.0001450808485969901 ]
{ "id": 1, "code_window": [ "\n", " @classmethod\n", " def sql_preprocessor(cls, sql):\n", " \"\"\"If the SQL needs to be altered prior to running it\n", "\n", " For example db api needs to double `%` characters\n", " \"\"\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " For example Presto needs to double `%` characters\n" ], "file_path": "superset/db_engine_specs.py", "type": "replace", "edit_start_line_idx": 117 }
{% if slice %} {% if slice.slice_name %} <h2> {{ slice.slice_name }} <small class="star-edit-icons"> <span class="favstar" class_name="Slice" obj_id="{{ slice.id }}"></span> <span> <a href="/slicemodelview/edit/{{ slice.id }}" data-toggle="tooltip" title="Edit Description" class="edit-slice-description-icon" > {% if slice.description %} <i class="fa fa-question-circle-o" data-toggle="tooltip" data-placement="bottom" title="{{ slice.description }}"> </i> {% endif %} <i class="fa fa-edit"></i> </a> </span> </small> </h2> {% endif %} {% else %} <h3>[{{ viz.datasource.table_name }}] - untitled</h3> {% endif %}
superset/templates/superset/partials/_explore_title.html
0
https://github.com/apache/superset/commit/3107152f5bb973b8b1a9c5cf3bc2bee1d7f47e0d
[ 0.00017625153122935444, 0.00017248137737624347, 0.00017022245447151363, 0.0001717257546260953, 0.00000241919997279183 ]
{ "id": 1, "code_window": [ "\n", " @classmethod\n", " def sql_preprocessor(cls, sql):\n", " \"\"\"If the SQL needs to be altered prior to running it\n", "\n", " For example db api needs to double `%` characters\n", " \"\"\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " For example Presto needs to double `%` characters\n" ], "file_path": "superset/db_engine_specs.py", "type": "replace", "edit_start_line_idx": 117 }
body { overflow: hidden; } .inlineBlock { display: inline-block; } .valignTop { vertical-align: top; } .inline { display: inline; } .nopadding { padding: 0px; } .panel.nopadding .panel-body { padding: 0px; } .loading { width: 50px; margin-top: 15px; } .pane-cell { padding: 10px; overflow: auto; width: 100%; height: 100%; } .SqlEditor .header { padding-top: 5px; padding-bottom: 5px; } .scrollbar-container { position: relative; overflow: hidden; width: 100%; height: 100%; } .scrollbar-content { position: absolute; top: 0px; left: 0px; right: 0px; bottom: 0px; overflow: scroll; margin-right: 0px; margin-bottom: 0px; } .Workspace .btn-sm { box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1); margin-top: 2px; padding: 4px; } .Workspace hr { margin-top: 10px; margin-bottom: 10px; } div.Workspace { height: 100%; margin: 0px; } .SqlEditor .clock { background-color: orange; padding: 5px; } .padded { padding: 10px; } .p-t-10 { padding-top: 10px; } .p-t-5 { padding-top: 5px; } .m-r-5 { margin-right: 5px; } .m-r-3 { margin-right: 3px; } .m-l-1 { margin-left: 1px; } .m-l-2 { margin-left: 2px; } .m-r-10 { margin-right: 10px; } .m-l-10 { margin-left: 10px; } .m-l-5 { margin-left: 5px; } .m-b-10 { margin-bottom: 10px; } .m-t-5 { margin-top: 5px; } .m-t-10 { margin-top: 10px; } .p-t-10 { padding-top: 10px; } .sqllab-toolbar { padding-top: 5px; border-bottom: 1px solid #DDD; } .no-shadow { box-shadow: none; background-color: transparent; } .pane-west { height: 100%; overflow: auto; } .circle { border-radius: 50%; width: 10px; height: 10px; display: inline-block; background-color: #ccc; } .Pane2 { width: 0; } .running { background-color: lime; color: black; } .success { background-color: #4AC15F; } .failed { background-color: red; } .handle { cursor: move; } .window { z-index: 1000; position: absolute; width: 300px; opacity: 0.85; border: 1px solid #AAA; max-height: 600px; box-shadow: rgba(0, 0, 0, 0.8) 5px 5px 25px } .SqlLab pre { padding: 0px !important; margin: 0px; border: none; font-size: 12px; line-height: @line-height-base; background-color: transparent !important; } .Resizer { background: #000; opacity: .2; z-index: 1; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; -moz-background-clip: padding; -webkit-background-clip: padding; background-clip: padding-box; } .Resizer:hover { -webkit-transition: all 2s ease; transition: all 2s ease; } .Resizer.horizontal { height: 10px; margin: -5px 0; border-top: 5px solid rgba(255, 255, 255, 0); border-bottom: 5px solid rgba(255, 255, 255, 0); cursor: row-resize; width: 100%; padding: 1px; } .Resizer.horizontal:hover { border-top: 5px solid rgba(0, 0, 0, 0.5); border-bottom: 5px solid rgba(0, 0, 0, 0.5); } .Resizer.vertical { width: 9px; margin: 0 -5px; border-left: 5px solid rgba(255, 255, 255, 0); border-right: 5px solid rgba(255, 255, 255, 0); cursor: col-resize; } .Resizer.vertical:hover { border-left: 5px solid rgba(0, 0, 0, 0.5); border-right: 5px solid rgba(0, 0, 0, 0.5); } .Resizer.disabled { cursor: not-allowed; } .Resizer.disabled:hover { border-color: transparent; } .popover{ max-width:400px; } .Select-menu-outer { z-index: 1000; } .table-label { margin-top: 5px; margin-right: 10px; float: left; } div.tablePopover { opacity: 0.7 !important; } div.tablePopover:hover { opacity: 1 !important; } .ResultSetControls { padding-bottom: 3px; padding-top: 3px; } .ace_editor { border: 1px solid #ccc; margin: 0px 0px 10px 0px; } .Select-menu-outer { min-width: 100%; width: inherit; } .ace_content { background-color: #f4f4f4; } .SouthPane .tab-content { padding-top: 10px; } .TableElement { margin-right: 10px; } .TableElement .well { margin-top: 5px; margin-bottom: 5px; padding: 5px 10px; } .QueryTable .label { margin-top: 5px; } .ResultsModal .modal-body { min-height: 600px; } .modal-body { overflow: auto; } a.Link { cursor: pointer; } .QueryTable .well { padding: 3px 5px; margin: 3px 5px; } .tooltip pre { background: transparent; border: none; text-align: left; color: white; font-size: 10px; } .tooltip-inner { max-width: 500px; }
superset/assets/javascripts/SqlLab/main.css
0
https://github.com/apache/superset/commit/3107152f5bb973b8b1a9c5cf3bc2bee1d7f47e0d
[ 0.0001755497942212969, 0.00017101195408031344, 0.000162804702995345, 0.00017203425522893667, 0.000003216295226593502 ]
{ "id": 2, "code_window": [ " \"\"\"\n", " return sql.replace('%', '%%')\n", "\n", " @classmethod\n", " def patch(cls):\n", " pass\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return sql\n" ], "file_path": "superset/db_engine_specs.py", "type": "replace", "edit_start_line_idx": 119 }
"""Compatibility layer for different database engines This modules stores logic specific to different database engines. Things like time-related functions that are similar but not identical, or information as to expose certain features or not and how to expose them. For instance, Hive/Presto supports partitions and have a specific API to list partitions. Other databases like Vertica also support partitions but have different API to get to them. Other databases don't support partitions at all. The classes here will use a common interface to specify all this. The general idea is to use static classes and an inheritance scheme. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from collections import namedtuple, defaultdict from superset import utils import inspect import re import sqlparse import textwrap import time from superset import cache_util from sqlalchemy import select from sqlalchemy.sql import text from superset.utils import SupersetTemplateException from superset.utils import QueryStatus from flask_babel import lazy_gettext as _ Grain = namedtuple('Grain', 'name label function') class LimitMethod(object): """Enum the ways that limits can be applied""" FETCH_MANY = 'fetch_many' WRAP_SQL = 'wrap_sql' class BaseEngineSpec(object): engine = 'base' # str as defined in sqlalchemy.engine.engine cursor_execute_kwargs = {} time_grains = tuple() limit_method = LimitMethod.FETCH_MANY @classmethod def fetch_data(cls, cursor, limit): if cls.limit_method == LimitMethod.FETCH_MANY: return cursor.fetchmany(limit) return cursor.fetchall() @classmethod def epoch_to_dttm(cls): raise NotImplementedError() @classmethod def epoch_ms_to_dttm(cls): return cls.epoch_to_dttm().replace('{col}', '({col}/1000.0)') @classmethod def extra_table_metadata(cls, database, table_name, schema_name): """Returns engine-specific table metadata""" return {} @classmethod def convert_dttm(cls, target_type, dttm): return "'{}'".format(dttm.strftime('%Y-%m-%d %H:%M:%S')) @classmethod @cache_util.memoized_func( timeout=600, key=lambda *args, **kwargs: 'db:{}:{}'.format(args[0].id, args[1])) def fetch_result_sets(cls, db, datasource_type, force=False): """Returns the dictionary {schema : [result_set_name]}. Datasource_type can be 'table' or 'view'. Empty schema corresponds to the list of full names of the all tables or views: <schema>.<result_set_name>. """ schemas = db.inspector.get_schema_names() result_sets = {} all_result_sets = [] for schema in schemas: if datasource_type == 'table': result_sets[schema] = sorted( db.inspector.get_table_names(schema)) elif datasource_type == 'view': result_sets[schema] = sorted( db.inspector.get_view_names(schema)) all_result_sets += [ '{}.{}'.format(schema, t) for t in result_sets[schema]] if all_result_sets: result_sets[""] = all_result_sets return result_sets @classmethod def handle_cursor(cls, cursor, query, session): """Handle a live cursor between the execute and fetchall calls The flow works without this method doing anything, but it allows for handling the cursor and updating progress information in the query object""" pass @classmethod def extract_error_message(cls, e): """Extract error message for queries""" return utils.error_msg_from_exception(e) @classmethod def sql_preprocessor(cls, sql): """If the SQL needs to be altered prior to running it For example db api needs to double `%` characters """ return sql.replace('%', '%%') @classmethod def patch(cls): pass @classmethod def where_latest_partition( cls, table_name, schema, database, qry, columns=None): return False @classmethod def select_star(cls, my_db, table_name, schema=None, limit=100, show_cols=False, indent=True): fields = '*' table = my_db.get_table(table_name, schema=schema) if show_cols: fields = [my_db.get_quoter()(c.name) for c in table.columns] full_table_name = table_name if schema: full_table_name = schema + '.' + table_name qry = select(fields) if limit: qry = qry.limit(limit) partition_query = cls.where_latest_partition( table_name, schema, my_db, qry, columns=table.columns) # if not partition_query condition fails. if partition_query == False: # noqa qry = qry.select_from(text(full_table_name)) else: qry = partition_query sql = my_db.compile_sqla_query(qry) if indent: sql = sqlparse.format(sql, reindent=True) return sql class PostgresEngineSpec(BaseEngineSpec): engine = 'postgresql' time_grains = ( Grain("Time Column", _('Time Column'), "{col}"), Grain("second", _('second'), "DATE_TRUNC('second', {col})"), Grain("minute", _('minute'), "DATE_TRUNC('minute', {col})"), Grain("hour", _('hour'), "DATE_TRUNC('hour', {col})"), Grain("day", _('day'), "DATE_TRUNC('day', {col})"), Grain("week", _('week'), "DATE_TRUNC('week', {col})"), Grain("month", _('month'), "DATE_TRUNC('month', {col})"), Grain("quarter", _('quarter'), "DATE_TRUNC('quarter', {col})"), Grain("year", _('year'), "DATE_TRUNC('year', {col})"), ) @classmethod def fetch_data(cls, cursor, limit): if not cursor.description: return [] if cls.limit_method == LimitMethod.FETCH_MANY: return cursor.fetchmany(limit) return cursor.fetchall() @classmethod def epoch_to_dttm(cls): return "(timestamp 'epoch' + {col} * interval '1 second')" @classmethod def convert_dttm(cls, target_type, dttm): return "'{}'".format(dttm.strftime('%Y-%m-%d %H:%M:%S')) class SqliteEngineSpec(BaseEngineSpec): engine = 'sqlite' time_grains = ( Grain('Time Column', _('Time Column'), '{col}'), Grain('day', _('day'), 'DATE({col})'), Grain("week", _('week'), "DATE({col}, -strftime('%w', {col}) || ' days')"), Grain("month", _('month'), "DATE({col}, -strftime('%d', {col}) || ' days', '+1 day')"), ) @classmethod def epoch_to_dttm(cls): return "datetime({col}, 'unixepoch')" @classmethod def convert_dttm(cls, target_type, dttm): iso = dttm.isoformat().replace('T', ' ') if '.' not in iso: iso += '.000000' return "'{}'".format(iso) class MySQLEngineSpec(BaseEngineSpec): engine = 'mysql' time_grains = ( Grain('Time Column', _('Time Column'), '{col}'), Grain("second", _('second'), "DATE_ADD(DATE({col}), " "INTERVAL (HOUR({col})*60*60 + MINUTE({col})*60" " + SECOND({col})) SECOND)"), Grain("minute", _('minute'), "DATE_ADD(DATE({col}), " "INTERVAL (HOUR({col})*60 + MINUTE({col})) MINUTE)"), Grain("hour", _('hour'), "DATE_ADD(DATE({col}), " "INTERVAL HOUR({col}) HOUR)"), Grain('day', _('day'), 'DATE({col})'), Grain("week", _('week'), "DATE(DATE_SUB({col}, " "INTERVAL DAYOFWEEK({col}) - 1 DAY))"), Grain("month", _('month'), "DATE(DATE_SUB({col}, " "INTERVAL DAYOFMONTH({col}) - 1 DAY))"), Grain("quarter", _('quarter'), "MAKEDATE(YEAR({col}), 1) " "+ INTERVAL QUARTER({col}) QUARTER - INTERVAL 1 QUARTER"), Grain("year", _('year'), "DATE(DATE_SUB({col}, " "INTERVAL DAYOFYEAR({col}) - 1 DAY))"), Grain("week_start_monday", _('week_start_monday'), "DATE(DATE_SUB({col}, " "INTERVAL DAYOFWEEK(DATE_SUB({col}, INTERVAL 1 DAY)) - 1 DAY))"), ) @classmethod def convert_dttm(cls, target_type, dttm): if target_type.upper() in ('DATETIME', 'DATE'): return "STR_TO_DATE('{}', '%Y-%m-%d %H:%i:%s')".format( dttm.strftime('%Y-%m-%d %H:%M:%S')) return "'{}'".format(dttm.strftime('%Y-%m-%d %H:%M:%S')) @classmethod def epoch_to_dttm(cls): return "from_unixtime({col})" class PrestoEngineSpec(BaseEngineSpec): engine = 'presto' time_grains = ( Grain('Time Column', _('Time Column'), '{col}'), Grain('second', _('second'), "date_trunc('second', CAST({col} AS TIMESTAMP))"), Grain('minute', _('minute'), "date_trunc('minute', CAST({col} AS TIMESTAMP))"), Grain('hour', _('hour'), "date_trunc('hour', CAST({col} AS TIMESTAMP))"), Grain('day', _('day'), "date_trunc('day', CAST({col} AS TIMESTAMP))"), Grain('week', _('week'), "date_trunc('week', CAST({col} AS TIMESTAMP))"), Grain('month', _('month'), "date_trunc('month', CAST({col} AS TIMESTAMP))"), Grain('quarter', _('quarter'), "date_trunc('quarter', CAST({col} AS TIMESTAMP))"), Grain("week_ending_saturday", _('week_ending_saturday'), "date_add('day', 5, date_trunc('week', date_add('day', 1, " "CAST({col} AS TIMESTAMP))))"), Grain("week_start_sunday", _('week_start_sunday'), "date_add('day', -1, date_trunc('week', " "date_add('day', 1, CAST({col} AS TIMESTAMP))))"), ) @classmethod def patch(cls): from pyhive import presto from superset.db_engines import presto as patched_presto presto.Cursor.cancel = patched_presto.cancel @classmethod def convert_dttm(cls, target_type, dttm): tt = target_type.upper() if tt == 'DATE': return "from_iso8601_date('{}')".format(dttm.isoformat()[:10]) if tt == 'TIMESTAMP': return "from_iso8601_timestamp('{}')".format(dttm.isoformat()) return "'{}'".format(dttm.strftime('%Y-%m-%d %H:%M:%S')) @classmethod def epoch_to_dttm(cls): return "from_unixtime({col})" @classmethod @cache_util.memoized_func( timeout=600, key=lambda *args, **kwargs: 'db:{}:{}'.format(args[0].id, args[1])) def fetch_result_sets(cls, db, datasource_type, force=False): """Returns the dictionary {schema : [result_set_name]}. Datasource_type can be 'table' or 'view'. Empty schema corresponds to the list of full names of the all tables or views: <schema>.<result_set_name>. """ result_set_df = db.get_df( """SELECT table_schema, table_name FROM INFORMATION_SCHEMA.{}S ORDER BY concat(table_schema, '.', table_name)""".format( datasource_type.upper()), None) result_sets = defaultdict(list) for unused, row in result_set_df.iterrows(): result_sets[row['table_schema']].append(row['table_name']) result_sets[""].append('{}.{}'.format( row['table_schema'], row['table_name'])) return result_sets @classmethod def extra_table_metadata(cls, database, table_name, schema_name): indexes = database.get_indexes(table_name, schema_name) if not indexes: return {} cols = indexes[0].get('column_names', []) full_table_name = table_name if schema_name and '.' not in table_name: full_table_name = "{}.{}".format(schema_name, table_name) pql = cls._partition_query(full_table_name) col_name, latest_part = cls.latest_partition( table_name, schema_name, database) return { 'partitions': { 'cols': cols, 'latest': {col_name: latest_part}, 'partitionQuery': pql, } } @classmethod def handle_cursor(cls, cursor, query, session): """Updates progress information""" polled = cursor.poll() # poll returns dict -- JSON status information or ``None`` # if the query is done # https://github.com/dropbox/PyHive/blob/ # b34bdbf51378b3979eaf5eca9e956f06ddc36ca0/pyhive/presto.py#L178 while polled: # Update the object and wait for the kill signal. stats = polled.get('stats', {}) query = session.query(type(query)).filter_by(id=query.id).one() if query.status == QueryStatus.STOPPED: cursor.cancel() break if stats: completed_splits = float(stats.get('completedSplits')) total_splits = float(stats.get('totalSplits')) if total_splits and completed_splits: progress = 100 * (completed_splits / total_splits) if progress > query.progress: query.progress = progress session.commit() time.sleep(1) polled = cursor.poll() @classmethod def extract_error_message(cls, e): if hasattr(e, 'orig') \ and type(e.orig).__name__ == 'DatabaseError' \ and isinstance(e.orig[0], dict): error_dict = e.orig[0] e = '{} at {}: {}'.format( error_dict['errorName'], error_dict['errorLocation'], error_dict['message'] ) return utils.error_msg_from_exception(e) @classmethod def _partition_query( cls, table_name, limit=0, order_by=None, filters=None): """Returns a partition query :param table_name: the name of the table to get partitions from :type table_name: str :param limit: the number of partitions to be returned :type limit: int :param order_by: a list of tuples of field name and a boolean that determines if that field should be sorted in descending order :type order_by: list of (str, bool) tuples :param filters: a list of filters to apply :param filters: dict of field name and filter value combinations """ limit_clause = "LIMIT {}".format(limit) if limit else '' order_by_clause = '' if order_by: l = [] for field, desc in order_by: l.append(field + ' DESC' if desc else '') order_by_clause = 'ORDER BY ' + ', '.join(l) where_clause = '' if filters: l = [] for field, value in filters.items(): l.append("{field} = '{value}'".format(**locals())) where_clause = 'WHERE ' + ' AND '.join(l) sql = textwrap.dedent("""\ SHOW PARTITIONS FROM {table_name} {where_clause} {order_by_clause} {limit_clause} """).format(**locals()) return sql @classmethod def _latest_partition_from_df(cls, df): return df.to_records(index=False)[0][0] @classmethod def latest_partition(cls, table_name, schema, database): """Returns col name and the latest (max) partition value for a table :param table_name: the name of the table :type table_name: str :param schema: schema / database / namespace :type schema: str :param database: database query will be run against :type database: models.Database >>> latest_partition('foo_table') '2018-01-01' """ indexes = database.get_indexes(table_name, schema) if len(indexes[0]['column_names']) < 1: raise SupersetTemplateException( "The table should have one partitioned field") elif len(indexes[0]['column_names']) > 1: raise SupersetTemplateException( "The table should have a single partitioned field " "to use this function. You may want to use " "`presto.latest_sub_partition`") part_field = indexes[0]['column_names'][0] sql = cls._partition_query(table_name, 1, [(part_field, True)]) df = database.get_df(sql, schema) return part_field, cls._latest_partition_from_df(df) @classmethod def latest_sub_partition(cls, table_name, schema, database, **kwargs): """Returns the latest (max) partition value for a table A filtering criteria should be passed for all fields that are partitioned except for the field to be returned. For example, if a table is partitioned by (``ds``, ``event_type`` and ``event_category``) and you want the latest ``ds``, you'll want to provide a filter as keyword arguments for both ``event_type`` and ``event_category`` as in ``latest_sub_partition('my_table', event_category='page', event_type='click')`` :param table_name: the name of the table, can be just the table name or a fully qualified table name as ``schema_name.table_name`` :type table_name: str :param schema: schema / database / namespace :type schema: str :param database: database query will be run against :type database: models.Database :param kwargs: keyword arguments define the filtering criteria on the partition list. There can be many of these. :type kwargs: str >>> latest_sub_partition('sub_partition_table', event_type='click') '2018-01-01' """ indexes = database.get_indexes(table_name, schema) part_fields = indexes[0]['column_names'] for k in kwargs.keys(): if k not in k in part_fields: msg = "Field [{k}] is not part of the portioning key" raise SupersetTemplateException(msg) if len(kwargs.keys()) != len(part_fields) - 1: msg = ( "A filter needs to be specified for {} out of the " "{} fields." ).format(len(part_fields)-1, len(part_fields)) raise SupersetTemplateException(msg) for field in part_fields: if field not in kwargs.keys(): field_to_return = field sql = cls._partition_query( table_name, 1, [(field_to_return, True)], kwargs) df = database.get_df(sql, schema) if df.empty: return '' return df.to_dict()[field_to_return][0] class HiveEngineSpec(PrestoEngineSpec): """Reuses PrestoEngineSpec functionality.""" engine = 'hive' cursor_execute_kwargs = {'async': True} @classmethod def patch(cls): from pyhive import hive from superset.db_engines import hive as patched_hive from pythrifthiveapi.TCLIService import ( constants as patched_constants, ttypes as patched_ttypes, TCLIService as patched_TCLIService) hive.TCLIService = patched_TCLIService hive.constants = patched_constants hive.ttypes = patched_ttypes hive.Cursor.fetch_logs = patched_hive.fetch_logs @classmethod @cache_util.memoized_func( timeout=600, key=lambda *args, **kwargs: 'db:{}:{}'.format(args[0].id, args[1])) def fetch_result_sets(cls, db, datasource_type, force=False): return BaseEngineSpec.fetch_result_sets( db, datasource_type, force=force) @classmethod def progress(cls, logs): # 17/02/07 19:36:38 INFO ql.Driver: Total jobs = 5 jobs_stats_r = re.compile( r'.*INFO.*Total jobs = (?P<max_jobs>[0-9]+)') # 17/02/07 19:37:08 INFO ql.Driver: Launching Job 2 out of 5 launching_job_r = re.compile( '.*INFO.*Launching Job (?P<job_number>[0-9]+) out of ' '(?P<max_jobs>[0-9]+)') # 17/02/07 19:36:58 INFO exec.Task: 2017-02-07 19:36:58,152 Stage-18 # map = 0%, reduce = 0% stage_progress = re.compile( r'.*INFO.*Stage-(?P<stage_number>[0-9]+).*' r'map = (?P<map_progress>[0-9]+)%.*' r'reduce = (?P<reduce_progress>[0-9]+)%.*') total_jobs = None current_job = None stages = {} lines = logs.splitlines() for line in lines: match = jobs_stats_r.match(line) if match: total_jobs = int(match.groupdict()['max_jobs']) match = launching_job_r.match(line) if match: current_job = int(match.groupdict()['job_number']) stages = {} match = stage_progress.match(line) if match: stage_number = int(match.groupdict()['stage_number']) map_progress = int(match.groupdict()['map_progress']) reduce_progress = int(match.groupdict()['reduce_progress']) stages[stage_number] = (map_progress + reduce_progress) / 2 if not total_jobs or not current_job: return 0 stage_progress = sum( stages.values()) / len(stages.values()) if stages else 0 progress = ( 100 * (current_job - 1) / total_jobs + stage_progress / total_jobs ) return int(progress) @classmethod def handle_cursor(cls, cursor, query, session): """Updates progress information""" from pyhive import hive unfinished_states = ( hive.ttypes.TOperationState.INITIALIZED_STATE, hive.ttypes.TOperationState.RUNNING_STATE, ) polled = cursor.poll() while polled.operationState in unfinished_states: query = session.query(type(query)).filter_by(id=query.id) if query.status == QueryStatus.STOPPED: cursor.cancel() break resp = cursor.fetch_logs() if resp and resp.log: progress = cls.progress(resp.log) if progress > query.progress: query.progress = progress session.commit() time.sleep(5) polled = cursor.poll() @classmethod def where_latest_partition( cls, table_name, schema, database, qry, columns=None): try: col_name, value = cls.latest_partition( table_name, schema, database) except Exception: # table is not partitioned return False for c in columns: if str(c.name) == str(col_name): return qry.where(c == str(value)) return False @classmethod def latest_sub_partition(cls, table_name, **kwargs): # TODO(bogdan): implement` pass @classmethod def _latest_partition_from_df(cls, df): """Hive partitions look like ds={partition name}""" return df.ix[:, 0].max().split('=')[1] @classmethod def _partition_query( cls, table_name, limit=0, order_by=None, filters=None): return "SHOW PARTITIONS {table_name}".format(**locals()) class MssqlEngineSpec(BaseEngineSpec): engine = 'mssql' epoch_to_dttm = "dateadd(S, {col}, '1970-01-01')" time_grains = ( Grain("Time Column", _('Time Column'), "{col}"), Grain("second", _('second'), "DATEADD(second, " "DATEDIFF(second, '2000-01-01', {col}), '2000-01-01')"), Grain("minute", _('minute'), "DATEADD(minute, " "DATEDIFF(minute, 0, {col}), 0)"), Grain("5 minute", _('5 minute'), "DATEADD(minute, " "DATEDIFF(minute, 0, {col}) / 5 * 5, 0)"), Grain("half hour", _('half hour'), "DATEADD(minute, " "DATEDIFF(minute, 0, {col}) / 30 * 30, 0)"), Grain("hour", _('hour'), "DATEADD(hour, " "DATEDIFF(hour, 0, {col}), 0)"), Grain("day", _('day'), "DATEADD(day, " "DATEDIFF(day, 0, {col}), 0)"), Grain("week", _('week'), "DATEADD(week, " "DATEDIFF(week, 0, {col}), 0)"), Grain("month", _('month'), "DATEADD(month, " "DATEDIFF(month, 0, {col}), 0)"), Grain("quarter", _('quarter'), "DATEADD(quarter, " "DATEDIFF(quarter, 0, {col}), 0)"), Grain("year", _('year'), "DATEADD(year, " "DATEDIFF(year, 0, {col}), 0)"), ) @classmethod def convert_dttm(cls, target_type, dttm): return "CONVERT(DATETIME, '{}', 126)".format(dttm.isoformat()) class RedshiftEngineSpec(PostgresEngineSpec): engine = 'redshift' class OracleEngineSpec(PostgresEngineSpec): engine = 'oracle' time_grains = ( Grain('Time Column', _('Time Column'), '{col}'), Grain('minute', _('minute'), "TRUNC(TO_DATE({col}), 'MI')"), Grain('hour', _('hour'), "TRUNC(TO_DATE({col}), 'HH')"), Grain('day', _('day'), "TRUNC(TO_DATE({col}), 'DDD')"), Grain('week', _('week'), "TRUNC(TO_DATE({col}), 'WW')"), Grain('month', _('month'), "TRUNC(TO_DATE({col}), 'MONTH')"), Grain('quarter', _('quarter'), "TRUNC(TO_DATE({col}), 'Q')"), Grain('year', _('year'), "TRUNC(TO_DATE({col}), 'YEAR')"), ) @classmethod def convert_dttm(cls, target_type, dttm): return ( """TO_TIMESTAMP('{}', 'YYYY-MM-DD"T"HH24:MI:SS.ff6')""" ).format(dttm.isoformat()) class VerticaEngineSpec(PostgresEngineSpec): engine = 'vertica' engines = { o.engine: o for o in globals().values() if inspect.isclass(o) and issubclass(o, BaseEngineSpec)}
superset/db_engine_specs.py
1
https://github.com/apache/superset/commit/3107152f5bb973b8b1a9c5cf3bc2bee1d7f47e0d
[ 0.08355212211608887, 0.0030227091629058123, 0.00016278591647278517, 0.00018131615070160478, 0.010990409180521965 ]
{ "id": 2, "code_window": [ " \"\"\"\n", " return sql.replace('%', '%%')\n", "\n", " @classmethod\n", " def patch(cls):\n", " pass\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return sql\n" ], "file_path": "superset/db_engine_specs.py", "type": "replace", "edit_start_line_idx": 119 }
"""database options for sql lab Revision ID: 41f6a59a61f2 Revises: 3c3ffe173e4f Create Date: 2016-08-31 10:26:37.969107 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '41f6a59a61f2' down_revision = '3c3ffe173e4f' def upgrade(): op.add_column('dbs', sa.Column('allow_ctas', sa.Boolean(), nullable=True)) op.add_column( 'dbs', sa.Column('expose_in_sqllab', sa.Boolean(), nullable=True)) op.add_column( 'dbs', sa.Column('force_ctas_schema', sa.String(length=250), nullable=True)) def downgrade(): op.drop_column('dbs', 'force_ctas_schema') op.drop_column('dbs', 'expose_in_sqllab') op.drop_column('dbs', 'allow_ctas')
superset/migrations/versions/41f6a59a61f2_database_options_for_sql_lab.py
0
https://github.com/apache/superset/commit/3107152f5bb973b8b1a9c5cf3bc2bee1d7f47e0d
[ 0.0004035306046716869, 0.00024713631137274206, 0.00016730651259422302, 0.0001705717877484858, 0.00011059550161007792 ]
{ "id": 2, "code_window": [ " \"\"\"\n", " return sql.replace('%', '%%')\n", "\n", " @classmethod\n", " def patch(cls):\n", " pass\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return sql\n" ], "file_path": "superset/db_engine_specs.py", "type": "replace", "edit_start_line_idx": 119 }
import React from 'react'; import QueryTable from '../../../javascripts/SqlLab/components/QueryTable'; import { queries } from './fixtures'; import { mount } from 'enzyme'; import { describe, it } from 'mocha'; import { expect } from 'chai'; describe('QueryTable', () => { const mockedProps = { queries, }; it('is valid', () => { expect(React.isValidElement(<QueryTable />)).to.equal(true); }); it('is valid with props', () => { expect( React.isValidElement(<QueryTable {...mockedProps} />) ).to.equal(true); }); it('renders a proper table', () => { const wrapper = mount(<QueryTable {...mockedProps} />); expect(wrapper.find('table')).to.have.length(1); expect(wrapper.find('tr')).to.have.length(4); }); });
superset/assets/spec/javascripts/sqllab/QueryTable_spec.jsx
0
https://github.com/apache/superset/commit/3107152f5bb973b8b1a9c5cf3bc2bee1d7f47e0d
[ 0.00017361927893944085, 0.00016980560030788183, 0.00016539724310860038, 0.0001704002934275195, 0.0000033828696359705646 ]
{ "id": 2, "code_window": [ " \"\"\"\n", " return sql.replace('%', '%%')\n", "\n", " @classmethod\n", " def patch(cls):\n", " pass\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return sql\n" ], "file_path": "superset/db_engine_specs.py", "type": "replace", "edit_start_line_idx": 119 }
const $ = window.$ = require('jquery'); const jQuery = window.jQuery = $; // eslint-disable-line require('bootstrap'); import React from 'react'; import { render } from 'react-dom'; import { getInitialState, sqlLabReducer } from './reducers'; import { initEnhancer } from '../reduxUtils'; import { createStore, compose, applyMiddleware } from 'redux'; import { Provider } from 'react-redux'; import thunkMiddleware from 'redux-thunk'; import App from './components/App'; require('./main.css'); const appContainer = document.getElementById('app'); const bootstrapData = JSON.parse(appContainer.getAttribute('data-bootstrap')); const state = Object.assign({}, getInitialState(bootstrapData.defaultDbId), bootstrapData); let store = createStore( sqlLabReducer, state, compose(applyMiddleware(thunkMiddleware), initEnhancer())); // jquery hack to highlight the navbar menu $('a:contains("SQL Lab")').parent().addClass('active'); render( <Provider store={store}> <App /> </Provider>, appContainer );
superset/assets/javascripts/SqlLab/index.jsx
0
https://github.com/apache/superset/commit/3107152f5bb973b8b1a9c5cf3bc2bee1d7f47e0d
[ 0.00017332898278255016, 0.00017056002980098128, 0.00016815977869555354, 0.00017037568613886833, 0.0000023260320176632376 ]
{ "id": 3, "code_window": [ " from pyhive import presto\n", " from superset.db_engines import presto as patched_presto\n", " presto.Cursor.cancel = patched_presto.cancel\n", "\n", " @classmethod\n", " def convert_dttm(cls, target_type, dttm):\n", " tt = target_type.upper()\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " @classmethod\n", " def sql_preprocessor(cls, sql):\n", " return sql.replace('%', '%%')\n", "\n" ], "file_path": "superset/db_engine_specs.py", "type": "add", "edit_start_line_idx": 281 }
"""Compatibility layer for different database engines This modules stores logic specific to different database engines. Things like time-related functions that are similar but not identical, or information as to expose certain features or not and how to expose them. For instance, Hive/Presto supports partitions and have a specific API to list partitions. Other databases like Vertica also support partitions but have different API to get to them. Other databases don't support partitions at all. The classes here will use a common interface to specify all this. The general idea is to use static classes and an inheritance scheme. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from collections import namedtuple, defaultdict from superset import utils import inspect import re import sqlparse import textwrap import time from superset import cache_util from sqlalchemy import select from sqlalchemy.sql import text from superset.utils import SupersetTemplateException from superset.utils import QueryStatus from flask_babel import lazy_gettext as _ Grain = namedtuple('Grain', 'name label function') class LimitMethod(object): """Enum the ways that limits can be applied""" FETCH_MANY = 'fetch_many' WRAP_SQL = 'wrap_sql' class BaseEngineSpec(object): engine = 'base' # str as defined in sqlalchemy.engine.engine cursor_execute_kwargs = {} time_grains = tuple() limit_method = LimitMethod.FETCH_MANY @classmethod def fetch_data(cls, cursor, limit): if cls.limit_method == LimitMethod.FETCH_MANY: return cursor.fetchmany(limit) return cursor.fetchall() @classmethod def epoch_to_dttm(cls): raise NotImplementedError() @classmethod def epoch_ms_to_dttm(cls): return cls.epoch_to_dttm().replace('{col}', '({col}/1000.0)') @classmethod def extra_table_metadata(cls, database, table_name, schema_name): """Returns engine-specific table metadata""" return {} @classmethod def convert_dttm(cls, target_type, dttm): return "'{}'".format(dttm.strftime('%Y-%m-%d %H:%M:%S')) @classmethod @cache_util.memoized_func( timeout=600, key=lambda *args, **kwargs: 'db:{}:{}'.format(args[0].id, args[1])) def fetch_result_sets(cls, db, datasource_type, force=False): """Returns the dictionary {schema : [result_set_name]}. Datasource_type can be 'table' or 'view'. Empty schema corresponds to the list of full names of the all tables or views: <schema>.<result_set_name>. """ schemas = db.inspector.get_schema_names() result_sets = {} all_result_sets = [] for schema in schemas: if datasource_type == 'table': result_sets[schema] = sorted( db.inspector.get_table_names(schema)) elif datasource_type == 'view': result_sets[schema] = sorted( db.inspector.get_view_names(schema)) all_result_sets += [ '{}.{}'.format(schema, t) for t in result_sets[schema]] if all_result_sets: result_sets[""] = all_result_sets return result_sets @classmethod def handle_cursor(cls, cursor, query, session): """Handle a live cursor between the execute and fetchall calls The flow works without this method doing anything, but it allows for handling the cursor and updating progress information in the query object""" pass @classmethod def extract_error_message(cls, e): """Extract error message for queries""" return utils.error_msg_from_exception(e) @classmethod def sql_preprocessor(cls, sql): """If the SQL needs to be altered prior to running it For example db api needs to double `%` characters """ return sql.replace('%', '%%') @classmethod def patch(cls): pass @classmethod def where_latest_partition( cls, table_name, schema, database, qry, columns=None): return False @classmethod def select_star(cls, my_db, table_name, schema=None, limit=100, show_cols=False, indent=True): fields = '*' table = my_db.get_table(table_name, schema=schema) if show_cols: fields = [my_db.get_quoter()(c.name) for c in table.columns] full_table_name = table_name if schema: full_table_name = schema + '.' + table_name qry = select(fields) if limit: qry = qry.limit(limit) partition_query = cls.where_latest_partition( table_name, schema, my_db, qry, columns=table.columns) # if not partition_query condition fails. if partition_query == False: # noqa qry = qry.select_from(text(full_table_name)) else: qry = partition_query sql = my_db.compile_sqla_query(qry) if indent: sql = sqlparse.format(sql, reindent=True) return sql class PostgresEngineSpec(BaseEngineSpec): engine = 'postgresql' time_grains = ( Grain("Time Column", _('Time Column'), "{col}"), Grain("second", _('second'), "DATE_TRUNC('second', {col})"), Grain("minute", _('minute'), "DATE_TRUNC('minute', {col})"), Grain("hour", _('hour'), "DATE_TRUNC('hour', {col})"), Grain("day", _('day'), "DATE_TRUNC('day', {col})"), Grain("week", _('week'), "DATE_TRUNC('week', {col})"), Grain("month", _('month'), "DATE_TRUNC('month', {col})"), Grain("quarter", _('quarter'), "DATE_TRUNC('quarter', {col})"), Grain("year", _('year'), "DATE_TRUNC('year', {col})"), ) @classmethod def fetch_data(cls, cursor, limit): if not cursor.description: return [] if cls.limit_method == LimitMethod.FETCH_MANY: return cursor.fetchmany(limit) return cursor.fetchall() @classmethod def epoch_to_dttm(cls): return "(timestamp 'epoch' + {col} * interval '1 second')" @classmethod def convert_dttm(cls, target_type, dttm): return "'{}'".format(dttm.strftime('%Y-%m-%d %H:%M:%S')) class SqliteEngineSpec(BaseEngineSpec): engine = 'sqlite' time_grains = ( Grain('Time Column', _('Time Column'), '{col}'), Grain('day', _('day'), 'DATE({col})'), Grain("week", _('week'), "DATE({col}, -strftime('%w', {col}) || ' days')"), Grain("month", _('month'), "DATE({col}, -strftime('%d', {col}) || ' days', '+1 day')"), ) @classmethod def epoch_to_dttm(cls): return "datetime({col}, 'unixepoch')" @classmethod def convert_dttm(cls, target_type, dttm): iso = dttm.isoformat().replace('T', ' ') if '.' not in iso: iso += '.000000' return "'{}'".format(iso) class MySQLEngineSpec(BaseEngineSpec): engine = 'mysql' time_grains = ( Grain('Time Column', _('Time Column'), '{col}'), Grain("second", _('second'), "DATE_ADD(DATE({col}), " "INTERVAL (HOUR({col})*60*60 + MINUTE({col})*60" " + SECOND({col})) SECOND)"), Grain("minute", _('minute'), "DATE_ADD(DATE({col}), " "INTERVAL (HOUR({col})*60 + MINUTE({col})) MINUTE)"), Grain("hour", _('hour'), "DATE_ADD(DATE({col}), " "INTERVAL HOUR({col}) HOUR)"), Grain('day', _('day'), 'DATE({col})'), Grain("week", _('week'), "DATE(DATE_SUB({col}, " "INTERVAL DAYOFWEEK({col}) - 1 DAY))"), Grain("month", _('month'), "DATE(DATE_SUB({col}, " "INTERVAL DAYOFMONTH({col}) - 1 DAY))"), Grain("quarter", _('quarter'), "MAKEDATE(YEAR({col}), 1) " "+ INTERVAL QUARTER({col}) QUARTER - INTERVAL 1 QUARTER"), Grain("year", _('year'), "DATE(DATE_SUB({col}, " "INTERVAL DAYOFYEAR({col}) - 1 DAY))"), Grain("week_start_monday", _('week_start_monday'), "DATE(DATE_SUB({col}, " "INTERVAL DAYOFWEEK(DATE_SUB({col}, INTERVAL 1 DAY)) - 1 DAY))"), ) @classmethod def convert_dttm(cls, target_type, dttm): if target_type.upper() in ('DATETIME', 'DATE'): return "STR_TO_DATE('{}', '%Y-%m-%d %H:%i:%s')".format( dttm.strftime('%Y-%m-%d %H:%M:%S')) return "'{}'".format(dttm.strftime('%Y-%m-%d %H:%M:%S')) @classmethod def epoch_to_dttm(cls): return "from_unixtime({col})" class PrestoEngineSpec(BaseEngineSpec): engine = 'presto' time_grains = ( Grain('Time Column', _('Time Column'), '{col}'), Grain('second', _('second'), "date_trunc('second', CAST({col} AS TIMESTAMP))"), Grain('minute', _('minute'), "date_trunc('minute', CAST({col} AS TIMESTAMP))"), Grain('hour', _('hour'), "date_trunc('hour', CAST({col} AS TIMESTAMP))"), Grain('day', _('day'), "date_trunc('day', CAST({col} AS TIMESTAMP))"), Grain('week', _('week'), "date_trunc('week', CAST({col} AS TIMESTAMP))"), Grain('month', _('month'), "date_trunc('month', CAST({col} AS TIMESTAMP))"), Grain('quarter', _('quarter'), "date_trunc('quarter', CAST({col} AS TIMESTAMP))"), Grain("week_ending_saturday", _('week_ending_saturday'), "date_add('day', 5, date_trunc('week', date_add('day', 1, " "CAST({col} AS TIMESTAMP))))"), Grain("week_start_sunday", _('week_start_sunday'), "date_add('day', -1, date_trunc('week', " "date_add('day', 1, CAST({col} AS TIMESTAMP))))"), ) @classmethod def patch(cls): from pyhive import presto from superset.db_engines import presto as patched_presto presto.Cursor.cancel = patched_presto.cancel @classmethod def convert_dttm(cls, target_type, dttm): tt = target_type.upper() if tt == 'DATE': return "from_iso8601_date('{}')".format(dttm.isoformat()[:10]) if tt == 'TIMESTAMP': return "from_iso8601_timestamp('{}')".format(dttm.isoformat()) return "'{}'".format(dttm.strftime('%Y-%m-%d %H:%M:%S')) @classmethod def epoch_to_dttm(cls): return "from_unixtime({col})" @classmethod @cache_util.memoized_func( timeout=600, key=lambda *args, **kwargs: 'db:{}:{}'.format(args[0].id, args[1])) def fetch_result_sets(cls, db, datasource_type, force=False): """Returns the dictionary {schema : [result_set_name]}. Datasource_type can be 'table' or 'view'. Empty schema corresponds to the list of full names of the all tables or views: <schema>.<result_set_name>. """ result_set_df = db.get_df( """SELECT table_schema, table_name FROM INFORMATION_SCHEMA.{}S ORDER BY concat(table_schema, '.', table_name)""".format( datasource_type.upper()), None) result_sets = defaultdict(list) for unused, row in result_set_df.iterrows(): result_sets[row['table_schema']].append(row['table_name']) result_sets[""].append('{}.{}'.format( row['table_schema'], row['table_name'])) return result_sets @classmethod def extra_table_metadata(cls, database, table_name, schema_name): indexes = database.get_indexes(table_name, schema_name) if not indexes: return {} cols = indexes[0].get('column_names', []) full_table_name = table_name if schema_name and '.' not in table_name: full_table_name = "{}.{}".format(schema_name, table_name) pql = cls._partition_query(full_table_name) col_name, latest_part = cls.latest_partition( table_name, schema_name, database) return { 'partitions': { 'cols': cols, 'latest': {col_name: latest_part}, 'partitionQuery': pql, } } @classmethod def handle_cursor(cls, cursor, query, session): """Updates progress information""" polled = cursor.poll() # poll returns dict -- JSON status information or ``None`` # if the query is done # https://github.com/dropbox/PyHive/blob/ # b34bdbf51378b3979eaf5eca9e956f06ddc36ca0/pyhive/presto.py#L178 while polled: # Update the object and wait for the kill signal. stats = polled.get('stats', {}) query = session.query(type(query)).filter_by(id=query.id).one() if query.status == QueryStatus.STOPPED: cursor.cancel() break if stats: completed_splits = float(stats.get('completedSplits')) total_splits = float(stats.get('totalSplits')) if total_splits and completed_splits: progress = 100 * (completed_splits / total_splits) if progress > query.progress: query.progress = progress session.commit() time.sleep(1) polled = cursor.poll() @classmethod def extract_error_message(cls, e): if hasattr(e, 'orig') \ and type(e.orig).__name__ == 'DatabaseError' \ and isinstance(e.orig[0], dict): error_dict = e.orig[0] e = '{} at {}: {}'.format( error_dict['errorName'], error_dict['errorLocation'], error_dict['message'] ) return utils.error_msg_from_exception(e) @classmethod def _partition_query( cls, table_name, limit=0, order_by=None, filters=None): """Returns a partition query :param table_name: the name of the table to get partitions from :type table_name: str :param limit: the number of partitions to be returned :type limit: int :param order_by: a list of tuples of field name and a boolean that determines if that field should be sorted in descending order :type order_by: list of (str, bool) tuples :param filters: a list of filters to apply :param filters: dict of field name and filter value combinations """ limit_clause = "LIMIT {}".format(limit) if limit else '' order_by_clause = '' if order_by: l = [] for field, desc in order_by: l.append(field + ' DESC' if desc else '') order_by_clause = 'ORDER BY ' + ', '.join(l) where_clause = '' if filters: l = [] for field, value in filters.items(): l.append("{field} = '{value}'".format(**locals())) where_clause = 'WHERE ' + ' AND '.join(l) sql = textwrap.dedent("""\ SHOW PARTITIONS FROM {table_name} {where_clause} {order_by_clause} {limit_clause} """).format(**locals()) return sql @classmethod def _latest_partition_from_df(cls, df): return df.to_records(index=False)[0][0] @classmethod def latest_partition(cls, table_name, schema, database): """Returns col name and the latest (max) partition value for a table :param table_name: the name of the table :type table_name: str :param schema: schema / database / namespace :type schema: str :param database: database query will be run against :type database: models.Database >>> latest_partition('foo_table') '2018-01-01' """ indexes = database.get_indexes(table_name, schema) if len(indexes[0]['column_names']) < 1: raise SupersetTemplateException( "The table should have one partitioned field") elif len(indexes[0]['column_names']) > 1: raise SupersetTemplateException( "The table should have a single partitioned field " "to use this function. You may want to use " "`presto.latest_sub_partition`") part_field = indexes[0]['column_names'][0] sql = cls._partition_query(table_name, 1, [(part_field, True)]) df = database.get_df(sql, schema) return part_field, cls._latest_partition_from_df(df) @classmethod def latest_sub_partition(cls, table_name, schema, database, **kwargs): """Returns the latest (max) partition value for a table A filtering criteria should be passed for all fields that are partitioned except for the field to be returned. For example, if a table is partitioned by (``ds``, ``event_type`` and ``event_category``) and you want the latest ``ds``, you'll want to provide a filter as keyword arguments for both ``event_type`` and ``event_category`` as in ``latest_sub_partition('my_table', event_category='page', event_type='click')`` :param table_name: the name of the table, can be just the table name or a fully qualified table name as ``schema_name.table_name`` :type table_name: str :param schema: schema / database / namespace :type schema: str :param database: database query will be run against :type database: models.Database :param kwargs: keyword arguments define the filtering criteria on the partition list. There can be many of these. :type kwargs: str >>> latest_sub_partition('sub_partition_table', event_type='click') '2018-01-01' """ indexes = database.get_indexes(table_name, schema) part_fields = indexes[0]['column_names'] for k in kwargs.keys(): if k not in k in part_fields: msg = "Field [{k}] is not part of the portioning key" raise SupersetTemplateException(msg) if len(kwargs.keys()) != len(part_fields) - 1: msg = ( "A filter needs to be specified for {} out of the " "{} fields." ).format(len(part_fields)-1, len(part_fields)) raise SupersetTemplateException(msg) for field in part_fields: if field not in kwargs.keys(): field_to_return = field sql = cls._partition_query( table_name, 1, [(field_to_return, True)], kwargs) df = database.get_df(sql, schema) if df.empty: return '' return df.to_dict()[field_to_return][0] class HiveEngineSpec(PrestoEngineSpec): """Reuses PrestoEngineSpec functionality.""" engine = 'hive' cursor_execute_kwargs = {'async': True} @classmethod def patch(cls): from pyhive import hive from superset.db_engines import hive as patched_hive from pythrifthiveapi.TCLIService import ( constants as patched_constants, ttypes as patched_ttypes, TCLIService as patched_TCLIService) hive.TCLIService = patched_TCLIService hive.constants = patched_constants hive.ttypes = patched_ttypes hive.Cursor.fetch_logs = patched_hive.fetch_logs @classmethod @cache_util.memoized_func( timeout=600, key=lambda *args, **kwargs: 'db:{}:{}'.format(args[0].id, args[1])) def fetch_result_sets(cls, db, datasource_type, force=False): return BaseEngineSpec.fetch_result_sets( db, datasource_type, force=force) @classmethod def progress(cls, logs): # 17/02/07 19:36:38 INFO ql.Driver: Total jobs = 5 jobs_stats_r = re.compile( r'.*INFO.*Total jobs = (?P<max_jobs>[0-9]+)') # 17/02/07 19:37:08 INFO ql.Driver: Launching Job 2 out of 5 launching_job_r = re.compile( '.*INFO.*Launching Job (?P<job_number>[0-9]+) out of ' '(?P<max_jobs>[0-9]+)') # 17/02/07 19:36:58 INFO exec.Task: 2017-02-07 19:36:58,152 Stage-18 # map = 0%, reduce = 0% stage_progress = re.compile( r'.*INFO.*Stage-(?P<stage_number>[0-9]+).*' r'map = (?P<map_progress>[0-9]+)%.*' r'reduce = (?P<reduce_progress>[0-9]+)%.*') total_jobs = None current_job = None stages = {} lines = logs.splitlines() for line in lines: match = jobs_stats_r.match(line) if match: total_jobs = int(match.groupdict()['max_jobs']) match = launching_job_r.match(line) if match: current_job = int(match.groupdict()['job_number']) stages = {} match = stage_progress.match(line) if match: stage_number = int(match.groupdict()['stage_number']) map_progress = int(match.groupdict()['map_progress']) reduce_progress = int(match.groupdict()['reduce_progress']) stages[stage_number] = (map_progress + reduce_progress) / 2 if not total_jobs or not current_job: return 0 stage_progress = sum( stages.values()) / len(stages.values()) if stages else 0 progress = ( 100 * (current_job - 1) / total_jobs + stage_progress / total_jobs ) return int(progress) @classmethod def handle_cursor(cls, cursor, query, session): """Updates progress information""" from pyhive import hive unfinished_states = ( hive.ttypes.TOperationState.INITIALIZED_STATE, hive.ttypes.TOperationState.RUNNING_STATE, ) polled = cursor.poll() while polled.operationState in unfinished_states: query = session.query(type(query)).filter_by(id=query.id) if query.status == QueryStatus.STOPPED: cursor.cancel() break resp = cursor.fetch_logs() if resp and resp.log: progress = cls.progress(resp.log) if progress > query.progress: query.progress = progress session.commit() time.sleep(5) polled = cursor.poll() @classmethod def where_latest_partition( cls, table_name, schema, database, qry, columns=None): try: col_name, value = cls.latest_partition( table_name, schema, database) except Exception: # table is not partitioned return False for c in columns: if str(c.name) == str(col_name): return qry.where(c == str(value)) return False @classmethod def latest_sub_partition(cls, table_name, **kwargs): # TODO(bogdan): implement` pass @classmethod def _latest_partition_from_df(cls, df): """Hive partitions look like ds={partition name}""" return df.ix[:, 0].max().split('=')[1] @classmethod def _partition_query( cls, table_name, limit=0, order_by=None, filters=None): return "SHOW PARTITIONS {table_name}".format(**locals()) class MssqlEngineSpec(BaseEngineSpec): engine = 'mssql' epoch_to_dttm = "dateadd(S, {col}, '1970-01-01')" time_grains = ( Grain("Time Column", _('Time Column'), "{col}"), Grain("second", _('second'), "DATEADD(second, " "DATEDIFF(second, '2000-01-01', {col}), '2000-01-01')"), Grain("minute", _('minute'), "DATEADD(minute, " "DATEDIFF(minute, 0, {col}), 0)"), Grain("5 minute", _('5 minute'), "DATEADD(minute, " "DATEDIFF(minute, 0, {col}) / 5 * 5, 0)"), Grain("half hour", _('half hour'), "DATEADD(minute, " "DATEDIFF(minute, 0, {col}) / 30 * 30, 0)"), Grain("hour", _('hour'), "DATEADD(hour, " "DATEDIFF(hour, 0, {col}), 0)"), Grain("day", _('day'), "DATEADD(day, " "DATEDIFF(day, 0, {col}), 0)"), Grain("week", _('week'), "DATEADD(week, " "DATEDIFF(week, 0, {col}), 0)"), Grain("month", _('month'), "DATEADD(month, " "DATEDIFF(month, 0, {col}), 0)"), Grain("quarter", _('quarter'), "DATEADD(quarter, " "DATEDIFF(quarter, 0, {col}), 0)"), Grain("year", _('year'), "DATEADD(year, " "DATEDIFF(year, 0, {col}), 0)"), ) @classmethod def convert_dttm(cls, target_type, dttm): return "CONVERT(DATETIME, '{}', 126)".format(dttm.isoformat()) class RedshiftEngineSpec(PostgresEngineSpec): engine = 'redshift' class OracleEngineSpec(PostgresEngineSpec): engine = 'oracle' time_grains = ( Grain('Time Column', _('Time Column'), '{col}'), Grain('minute', _('minute'), "TRUNC(TO_DATE({col}), 'MI')"), Grain('hour', _('hour'), "TRUNC(TO_DATE({col}), 'HH')"), Grain('day', _('day'), "TRUNC(TO_DATE({col}), 'DDD')"), Grain('week', _('week'), "TRUNC(TO_DATE({col}), 'WW')"), Grain('month', _('month'), "TRUNC(TO_DATE({col}), 'MONTH')"), Grain('quarter', _('quarter'), "TRUNC(TO_DATE({col}), 'Q')"), Grain('year', _('year'), "TRUNC(TO_DATE({col}), 'YEAR')"), ) @classmethod def convert_dttm(cls, target_type, dttm): return ( """TO_TIMESTAMP('{}', 'YYYY-MM-DD"T"HH24:MI:SS.ff6')""" ).format(dttm.isoformat()) class VerticaEngineSpec(PostgresEngineSpec): engine = 'vertica' engines = { o.engine: o for o in globals().values() if inspect.isclass(o) and issubclass(o, BaseEngineSpec)}
superset/db_engine_specs.py
1
https://github.com/apache/superset/commit/3107152f5bb973b8b1a9c5cf3bc2bee1d7f47e0d
[ 0.9968624114990234, 0.04686625301837921, 0.0001620561524759978, 0.0001738852879498154, 0.20031709969043732 ]
{ "id": 3, "code_window": [ " from pyhive import presto\n", " from superset.db_engines import presto as patched_presto\n", " presto.Cursor.cancel = patched_presto.cancel\n", "\n", " @classmethod\n", " def convert_dttm(cls, target_type, dttm):\n", " tt = target_type.upper()\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " @classmethod\n", " def sql_preprocessor(cls, sql):\n", " return sql.replace('%', '%%')\n", "\n" ], "file_path": "superset/db_engine_specs.py", "type": "add", "edit_start_line_idx": 281 }
/* eslint-disable no-param-reassign */ import d3 from 'd3'; require('./directed_force.css'); /* Modified from http://bl.ocks.org/d3noob/5141278 */ const directedForceVis = function (slice, json) { const div = d3.select(slice.selector); const width = slice.width(); const height = slice.height() - 25; const fd = slice.formData; const linkLength = fd.link_length || 200; const charge = fd.charge || -500; const links = json.data; const nodes = {}; // Compute the distinct nodes from the links. links.forEach(function (link) { link.source = nodes[link.source] || (nodes[link.source] = { name: link.source, }); link.target = nodes[link.target] || (nodes[link.target] = { name: link.target, }); link.value = Number(link.value); const targetName = link.target.name; const sourceName = link.source.name; if (nodes[targetName].total === undefined) { nodes[targetName].total = link.value; } if (nodes[sourceName].total === undefined) { nodes[sourceName].total = 0; } if (nodes[targetName].max === undefined) { nodes[targetName].max = 0; } if (link.value > nodes[targetName].max) { nodes[targetName].max = link.value; } if (nodes[targetName].min === undefined) { nodes[targetName].min = 0; } if (link.value > nodes[targetName].min) { nodes[targetName].min = link.value; } nodes[targetName].total += link.value; }); /* eslint-disable no-use-before-define */ // add the curvy lines function tick() { path.attr('d', function (d) { const dx = d.target.x - d.source.x; const dy = d.target.y - d.source.y; const dr = Math.sqrt(dx * dx + dy * dy); return ( 'M' + d.source.x + ',' + d.source.y + 'A' + dr + ',' + dr + ' 0 0,1 ' + d.target.x + ',' + d.target.y ); }); node.attr('transform', function (d) { return 'translate(' + d.x + ',' + d.y + ')'; }); } /* eslint-enable no-use-before-define */ const force = d3.layout.force() .nodes(d3.values(nodes)) .links(links) .size([width, height]) .linkDistance(linkLength) .charge(charge) .on('tick', tick) .start(); div.selectAll('*').remove(); const svg = div.append('svg') .attr('width', width) .attr('height', height); // build the arrow. svg.append('svg:defs').selectAll('marker') .data(['end']) // Different link/path types can be defined here .enter() .append('svg:marker') // This section adds in the arrows .attr('id', String) .attr('viewBox', '0 -5 10 10') .attr('refX', 15) .attr('refY', -1.5) .attr('markerWidth', 6) .attr('markerHeight', 6) .attr('orient', 'auto') .append('svg:path') .attr('d', 'M0,-5L10,0L0,5'); const edgeScale = d3.scale.linear() .range([0.1, 0.5]); // add the links and the arrows const path = svg.append('svg:g').selectAll('path') .data(force.links()) .enter() .append('svg:path') .attr('class', 'link') .style('opacity', function (d) { return edgeScale(d.value / d.target.max); }) .attr('marker-end', 'url(#end)'); // define the nodes const node = svg.selectAll('.node') .data(force.nodes()) .enter() .append('g') .attr('class', 'node') .on('mouseenter', function () { d3.select(this) .select('circle') .transition() .style('stroke-width', 5); d3.select(this) .select('text') .transition() .style('font-size', 25); }) .on('mouseleave', function () { d3.select(this) .select('circle') .transition() .style('stroke-width', 1.5); d3.select(this) .select('text') .transition() .style('font-size', 12); }) .call(force.drag); // add the nodes const ext = d3.extent(d3.values(nodes), function (d) { return Math.sqrt(d.total); }); const circleScale = d3.scale.linear() .domain(ext) .range([3, 30]); node.append('circle') .attr('r', function (d) { return circleScale(Math.sqrt(d.total)); }); // add the text node.append('text') .attr('x', 6) .attr('dy', '.35em') .text(function (d) { return d.name; }); }; module.exports = directedForceVis;
superset/assets/visualizations/directed_force.js
0
https://github.com/apache/superset/commit/3107152f5bb973b8b1a9c5cf3bc2bee1d7f47e0d
[ 0.0001787911751307547, 0.00017507275333628058, 0.00017083888815250248, 0.0001748149807099253, 0.000002091835767714656 ]
{ "id": 3, "code_window": [ " from pyhive import presto\n", " from superset.db_engines import presto as patched_presto\n", " presto.Cursor.cancel = patched_presto.cancel\n", "\n", " @classmethod\n", " def convert_dttm(cls, target_type, dttm):\n", " tt = target_type.upper()\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " @classmethod\n", " def sql_preprocessor(cls, sql):\n", " return sql.replace('%', '%%')\n", "\n" ], "file_path": "superset/db_engine_specs.py", "type": "add", "edit_start_line_idx": 281 }
"""empty message Revision ID: 43df8de3a5f4 Revises: 7dbf98566af7 Create Date: 2016-01-18 23:43:16.073483 """ # revision identifiers, used by Alembic. revision = '43df8de3a5f4' down_revision = '7dbf98566af7' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('dashboards', sa.Column('json_metadata', sa.Text(), nullable=True)) def downgrade(): op.drop_column('dashboards', 'json_metadata')
superset/migrations/versions/43df8de3a5f4_dash_json.py
0
https://github.com/apache/superset/commit/3107152f5bb973b8b1a9c5cf3bc2bee1d7f47e0d
[ 0.00017123486031778157, 0.00016631209291517735, 0.00016318188863806427, 0.0001645195734454319, 0.0000035234900224168086 ]
{ "id": 3, "code_window": [ " from pyhive import presto\n", " from superset.db_engines import presto as patched_presto\n", " presto.Cursor.cancel = patched_presto.cancel\n", "\n", " @classmethod\n", " def convert_dttm(cls, target_type, dttm):\n", " tt = target_type.upper()\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " @classmethod\n", " def sql_preprocessor(cls, sql):\n", " return sql.replace('%', '%%')\n", "\n" ], "file_path": "superset/db_engine_specs.py", "type": "add", "edit_start_line_idx": 281 }
import $ from 'jquery'; import React, { PropTypes } from 'react'; import { Responsive, WidthProvider } from 'react-grid-layout'; import SliceCell from './SliceCell'; require('react-grid-layout/css/styles.css'); require('react-resizable/css/styles.css'); const ResponsiveReactGridLayout = WidthProvider(Responsive); const propTypes = { dashboard: PropTypes.object.isRequired, }; class GridLayout extends React.Component { componentWillMount() { const layout = []; this.props.dashboard.slices.forEach((slice, index) => { const sliceId = slice.slice_id; let pos = this.props.dashboard.posDict[sliceId]; if (!pos) { pos = { col: (index * 4 + 1) % 12, row: Math.floor((index) / 3) * 4, size_x: 4, size_y: 4, }; } layout.push({ i: String(sliceId), x: pos.col - 1, y: pos.row, w: pos.size_x, minW: 2, h: pos.size_y, }); }); this.setState({ layout, slices: this.props.dashboard.slices, }); } onResizeStop(layout, oldItem, newItem) { const newSlice = this.props.dashboard.getSlice(newItem.i); if (oldItem.w !== newItem.w || oldItem.h !== newItem.h) { this.setState({ layout }, () => newSlice.resize()); } this.props.dashboard.onChange(); } onDragStop(layout) { this.setState({ layout }); this.props.dashboard.onChange(); } removeSlice(sliceId) { $('[data-toggle=tooltip]').tooltip('hide'); this.setState({ layout: this.state.layout.filter(function (reactPos) { return reactPos.i !== String(sliceId); }), slices: this.state.slices.filter(function (slice) { return slice.slice_id !== sliceId; }), }); this.props.dashboard.onChange(); } serialize() { return this.state.layout.map(reactPos => ({ slice_id: reactPos.i, col: reactPos.x + 1, row: reactPos.y, size_x: reactPos.w, size_y: reactPos.h, })); } render() { return ( <ResponsiveReactGridLayout className="layout" layouts={{ lg: this.state.layout }} onResizeStop={this.onResizeStop.bind(this)} onDragStop={this.onDragStop.bind(this)} cols={{ lg: 12, md: 12, sm: 10, xs: 8, xxs: 6 }} rowHeight={100} autoSize margin={[20, 20]} useCSSTransforms draggableHandle=".drag" > {this.state.slices.map(slice => ( <div id={'slice_' + slice.slice_id} key={slice.slice_id} data-slice-id={slice.slice_id} className={`widget ${slice.form_data.viz_type}`} > <SliceCell slice={slice} removeSlice={this.removeSlice.bind(this, slice.slice_id)} expandedSlices={this.props.dashboard.metadata.expanded_slices} /> </div> ))} </ResponsiveReactGridLayout> ); } } GridLayout.propTypes = propTypes; export default GridLayout;
superset/assets/javascripts/dashboard/components/GridLayout.jsx
0
https://github.com/apache/superset/commit/3107152f5bb973b8b1a9c5cf3bc2bee1d7f47e0d
[ 0.00017754982400219887, 0.00017304303764831275, 0.00016650743782520294, 0.0001740578154567629, 0.0000036726505641127005 ]
{ "id": 0, "code_window": [ "\n", "\tconst style = document.createElement('style');\n", "\tstyle.classList.add('markdown-style');\n", "\tstyle.textContent = `\n", "\t\timg {\n", "\t\t\tmax-width: 100%;\n", "\t\t\tmax-height: 100%;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t.emptyMarkdownCell::before {\n", "\t\t\tcontent: \"${document.documentElement.style.getPropertyValue('--notebook-cell-markup-empty-content')}\";\n", "\t\t\tfont-style: italic;\n", "\t\t\topacity: 0.6;\n", "\t\t}\n", "\n" ], "file_path": "extensions/markdown-language-features/notebook/index.ts", "type": "add", "edit_start_line_idx": 15 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IAction } from 'vs/base/common/actions'; import { coalesce } from 'vs/base/common/arrays'; import { VSBuffer } from 'vs/base/common/buffer'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable } from 'vs/base/common/lifecycle'; import { getExtensionForMimeType } from 'vs/base/common/mime'; import { FileAccess, Schemas } from 'vs/base/common/network'; import { isMacintosh, isWeb } from 'vs/base/common/platform'; import { dirname, joinPath } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import * as UUID from 'vs/base/common/uuid'; import * as nls from 'vs/nls'; import { createAndFillInContextMenuActions } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { IMenuService, MenuId } from 'vs/platform/actions/common/actions'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IFileDialogService } from 'vs/platform/dialogs/common/dialogs'; import { IFileService } from 'vs/platform/files/common/files'; import { IOpenerService, matchesScheme } from 'vs/platform/opener/common/opener'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { asWebviewUri } from 'vs/workbench/api/common/shared/webview'; import { CellEditState, ICellOutputViewModel, ICommonCellInfo, ICommonNotebookEditor, IDisplayOutputLayoutUpdateRequest, IDisplayOutputViewModel, IGenericCellViewModel, IInsetRenderOutput, RenderOutputType } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { preloadsScriptStr, RendererMetadata } from 'vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads'; import { transformWebviewThemeVars } from 'vs/workbench/contrib/notebook/browser/view/renderers/webviewThemeMapping'; import { MarkdownCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/markdownCellViewModel'; import { INotebookKernel, INotebookRendererInfo, RendererMessagingSpec } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { IScopedRendererMessaging } from 'vs/workbench/contrib/notebook/common/notebookRendererMessagingService'; import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService'; import { IWebviewService, WebviewContentPurpose, WebviewElement } from 'vs/workbench/contrib/webview/browser/webview'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { ICreationRequestMessage, IMarkdownCellInitialization, FromWebviewMessage, IClickedDataUrlMessage, IContentWidgetTopRequest, IControllerPreload, ToWebviewMessage } from './webviewMessages'; export interface ICachedInset<K extends ICommonCellInfo> { outputId: string; cellInfo: K; renderer?: INotebookRendererInfo; cachedCreation: ICreationRequestMessage; } function html(strings: TemplateStringsArray, ...values: any[]): string { let str = ''; strings.forEach((string, i) => { str += string + (values[i] || ''); }); return str; } export interface INotebookWebviewMessage { message: unknown; } export interface IResolvedBackLayerWebview { webview: WebviewElement; } export class BackLayerWebView<T extends ICommonCellInfo> extends Disposable { element: HTMLElement; webview: WebviewElement | undefined = undefined; insetMapping: Map<IDisplayOutputViewModel, ICachedInset<T>> = new Map(); readonly markdownPreviewMapping = new Map<string, IMarkdownCellInitialization>(); hiddenInsetMapping: Set<IDisplayOutputViewModel> = new Set(); reversedInsetMapping: Map<string, IDisplayOutputViewModel> = new Map(); localResourceRootsCache: URI[] | undefined = undefined; rendererRootsCache: URI[] = []; private readonly _onMessage = this._register(new Emitter<INotebookWebviewMessage>()); private readonly _preloadsCache = new Set<string>(); public readonly onMessage: Event<INotebookWebviewMessage> = this._onMessage.event; private _initalized?: Promise<void>; private _disposed = false; private _currentKernel?: INotebookKernel; constructor( public readonly notebookEditor: ICommonNotebookEditor, public readonly id: string, public readonly documentUri: URI, private options: { outputNodePadding: number, outputNodeLeftPadding: number, previewNodePadding: number, markdownLeftMargin: number, leftMargin: number, rightMargin: number, runGutter: number, dragAndDropEnabled: boolean, fontSize: number }, private readonly rendererMessaging: IScopedRendererMessaging | undefined, @IWebviewService readonly webviewService: IWebviewService, @IOpenerService readonly openerService: IOpenerService, @INotebookService private readonly notebookService: INotebookService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService, @IFileDialogService private readonly fileDialogService: IFileDialogService, @IFileService private readonly fileService: IFileService, @IContextMenuService private readonly contextMenuService: IContextMenuService, @IMenuService private readonly menuService: IMenuService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @ITelemetryService private readonly telemetryService: ITelemetryService, ) { super(); this.element = document.createElement('div'); this.element.style.height = '1400px'; this.element.style.position = 'absolute'; if (rendererMessaging) { this._register(rendererMessaging.onDidReceiveMessage(evt => { this._sendMessageToWebview({ __vscode_notebook_message: true, type: 'customRendererMessage', rendererId: evt.rendererId, message: evt.message }); })); } } updateOptions(options: { outputNodePadding: number, outputNodeLeftPadding: number, previewNodePadding: number, markdownLeftMargin: number, leftMargin: number, rightMargin: number, runGutter: number, dragAndDropEnabled: boolean, fontSize: number }) { this.options = options; this._updateStyles(); this._updateOptions(); } private _updateStyles() { this._sendMessageToWebview({ type: 'notebookStyles', styles: this._generateStyles() }); } private _updateOptions() { this._sendMessageToWebview({ type: 'notebookOptions', options: { dragAndDropEnabled: this.options.dragAndDropEnabled } }); } private _generateStyles() { return { 'notebook-output-left-margin': `${this.options.leftMargin + this.options.runGutter}px`, 'notebook-output-width': `calc(100% - ${this.options.leftMargin + this.options.rightMargin + this.options.runGutter}px)`, 'notebook-output-node-padding': `${this.options.outputNodePadding}px`, 'notebook-run-gutter': `${this.options.runGutter}px`, 'notebook-preivew-node-padding': `${this.options.previewNodePadding}px`, 'notebook-markdown-left-margin': `${this.options.markdownLeftMargin}px`, 'notebook-output-node-left-padding': `${this.options.outputNodeLeftPadding}px`, 'notebook-markdown-min-height': `${this.options.previewNodePadding * 2}px`, 'notebook-cell-output-font-size': `${this.options.fontSize}px` }; } private generateContent(coreDependencies: string, baseUrl: string) { const renderersData = this.getRendererData(); return html` <html lang="en"> <head> <meta charset="UTF-8"> <base href="${baseUrl}/"/> <style> #container .cell_container { width: 100%; } #container .output_container { width: 100%; } #container > div > div > div.output { font-size: var(--notebook-cell-output-font-size); width: var(--notebook-output-width); margin-left: var(--notebook-output-left-margin); padding-top: var(--notebook-output-node-padding); padding-right: var(--notebook-output-node-padding); padding-bottom: var(--notebook-output-node-padding); padding-left: var(--notebook-output-node-left-padding); box-sizing: border-box; background-color: var(--theme-notebook-output-background); } /* markdown */ #container > div.preview { width: 100%; padding-right: var(--notebook-preivew-node-padding); padding-left: var(--notebook-markdown-left-margin); padding-top: var(--notebook-preivew-node-padding); padding-bottom: var(--notebook-preivew-node-padding); box-sizing: border-box; white-space: nowrap; overflow: hidden; white-space: initial; color: var(--theme-ui-foreground); } #container > div.preview.draggable { user-select: none; -webkit-user-select: none; -ms-user-select: none; cursor: grab; } #container > div.preview.emptyMarkdownCell::before { content: "${nls.localize('notebook.emptyMarkdownPlaceholder', "Empty markdown cell, double click or press enter to edit.")}"; font-style: italic; opacity: 0.6; } #container > div.preview.selected { background: var(--theme-notebook-cell-selected-background); } #container > div.preview.dragging { background-color: var(--theme-background); } .monaco-workbench.vs-dark .notebookOverlay .cell.markdown .latex img, .monaco-workbench.vs-dark .notebookOverlay .cell.markdown .latex-block img { filter: brightness(0) invert(1) } #container > div.nb-symbolHighlight { background-color: var(--theme-notebook-symbol-highlight-background); } #container > div.nb-cellDeleted { background-color: var(--theme-notebook-diff-removed-background); } #container > div.nb-cellAdded { background-color: var(--theme-notebook-diff-inserted-background); } #container > div > div:not(.preview) > div { overflow-x: scroll; } body { padding: 0px; height: 100%; width: 100%; } table, thead, tr, th, td, tbody { border: none !important; border-color: transparent; border-spacing: 0; border-collapse: collapse; } table { width: 100%; } table, th, tr { text-align: left !important; } thead { font-weight: bold; background-color: rgba(130, 130, 130, 0.16); } th, td { padding: 4px 8px; } tr:nth-child(even) { background-color: rgba(130, 130, 130, 0.08); } tbody th { font-weight: normal; } </style> </head> <body style="overflow: hidden;"> <script> self.require = {}; </script> ${coreDependencies} <div id='container' class="widgetarea" style="position: absolute;width:100%;top: 0px"></div> <script type="module">${preloadsScriptStr(this.options, { dragAndDropEnabled: this.options.dragAndDropEnabled }, renderersData)}</script> </body> </html>`; } private getRendererData(): RendererMetadata[] { return this.notebookService.getRenderers().map((renderer): RendererMetadata => { const entrypoint = this.asWebviewUri(renderer.entrypoint, renderer.extensionLocation).toString(); return { id: renderer.id, entrypoint, mimeTypes: renderer.mimeTypes, extends: renderer.extends, messaging: renderer.messaging !== RendererMessagingSpec.Never, }; }); } private asWebviewUri(uri: URI, fromExtension: URI | undefined) { return asWebviewUri(uri, fromExtension?.scheme === Schemas.vscodeRemote ? { isRemote: true, authority: fromExtension.authority } : undefined); } postKernelMessage(message: any) { this._sendMessageToWebview({ __vscode_notebook_message: true, type: 'customKernelMessage', message, }); } private resolveOutputId(id: string): { cellInfo: T, output: ICellOutputViewModel } | undefined { const output = this.reversedInsetMapping.get(id); if (!output) { return; } const cellInfo = this.insetMapping.get(output)!.cellInfo; return { cellInfo, output }; } isResolved(): this is IResolvedBackLayerWebview { return !!this.webview; } async createWebview(): Promise<void> { const baseUrl = this.asWebviewUri(dirname(this.documentUri), undefined); // Python hasn't moved to use a preload to load require support yet. // For all other notebooks, we no longer want to include our loader. if (!this.documentUri.path.toLowerCase().endsWith('.ipynb')) { const htmlContent = this.generateContent('', baseUrl.toString()); this._initialize(htmlContent); return; } let coreDependencies = ''; let resolveFunc: () => void; this._initalized = new Promise<void>((resolve, reject) => { resolveFunc = resolve; }); if (!isWeb) { const loaderUri = FileAccess.asFileUri('vs/loader.js', require); const loader = this.asWebviewUri(loaderUri, undefined); coreDependencies = `<script src="${loader}"></script><script> var requirejs = (function() { return require; }()); </script>`; const htmlContent = this.generateContent(coreDependencies, baseUrl.toString()); this._initialize(htmlContent); resolveFunc!(); } else { const loaderUri = FileAccess.asBrowserUri('vs/loader.js', require); fetch(loaderUri.toString(true)).then(async response => { if (response.status !== 200) { throw new Error(response.statusText); } const loaderJs = await response.text(); coreDependencies = ` <script> ${loaderJs} </script> <script> var requirejs = (function() { return require; }()); </script> `; const htmlContent = this.generateContent(coreDependencies, baseUrl.toString()); this._initialize(htmlContent); resolveFunc!(); }, error => { // the fetch request is rejected const htmlContent = this.generateContent(coreDependencies, baseUrl.toString()); this._initialize(htmlContent); resolveFunc!(); }); } await this._initalized; } private _initialize(content: string) { if (!document.body.contains(this.element)) { throw new Error('Element is already detached from the DOM tree'); } this.webview = this._createInset(this.webviewService, content); this.webview.mountTo(this.element); this._register(this.webview); this._register(this.webview.onDidClickLink(link => { if (this._disposed) { return; } if (!link) { return; } if (matchesScheme(link, Schemas.command)) { console.warn('Command links are deprecated and will be removed, use messag passing instead: https://github.com/microsoft/vscode/issues/123601'); } if (matchesScheme(link, Schemas.http) || matchesScheme(link, Schemas.https) || matchesScheme(link, Schemas.mailto) || matchesScheme(link, Schemas.command)) { this.openerService.open(link, { fromUserGesture: true, allowContributedOpeners: true, allowCommands: true }); } })); this._register(this.webview.onMessage((message) => { const data: FromWebviewMessage | { readonly __vscode_notebook_message: undefined } = message.message; if (this._disposed) { return; } if (!data.__vscode_notebook_message) { return; } switch (data.type) { case 'initialized': this.initializeWebViewState(); break; case 'dimension': { for (const update of data.updates) { const height = update.height; if (update.isOutput) { const resolvedResult = this.resolveOutputId(update.id); if (resolvedResult) { const { cellInfo, output } = resolvedResult; this.notebookEditor.updateOutputHeight(cellInfo, output, height, !!update.init, 'webview#dimension'); this.notebookEditor.scheduleOutputHeightAck(cellInfo, update.id, height); } } else { this.notebookEditor.updateMarkdownCellHeight(update.id, height, !!update.init); } } break; } case 'mouseenter': { const resolvedResult = this.resolveOutputId(data.id); if (resolvedResult) { const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo); if (latestCell) { latestCell.outputIsHovered = true; } } break; } case 'mouseleave': { const resolvedResult = this.resolveOutputId(data.id); if (resolvedResult) { const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo); if (latestCell) { latestCell.outputIsHovered = false; } } break; } case 'outputFocus': { const resolvedResult = this.resolveOutputId(data.id); if (resolvedResult) { const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo); if (latestCell) { latestCell.outputIsFocused = true; } } break; } case 'outputBlur': { const resolvedResult = this.resolveOutputId(data.id); if (resolvedResult) { const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo); if (latestCell) { latestCell.outputIsFocused = false; } } break; } case 'scroll-ack': { // const date = new Date(); // const top = data.data.top; // console.log('ack top ', top, ' version: ', data.version, ' - ', date.getMinutes() + ':' + date.getSeconds() + ':' + date.getMilliseconds()); break; } case 'did-scroll-wheel': { this.notebookEditor.triggerScroll({ ...data.payload, preventDefault: () => { }, stopPropagation: () => { } }); break; } case 'focus-editor': { const resolvedResult = this.resolveOutputId(data.id); if (resolvedResult) { const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo); if (!latestCell) { return; } if (data.focusNext) { this.notebookEditor.focusNextNotebookCell(latestCell, 'editor'); } else { this.notebookEditor.focusNotebookCell(latestCell, 'editor'); } } break; } case 'clicked-data-url': { this._onDidClickDataLink(data); break; } case 'customKernelMessage': { this._onMessage.fire({ message: data.message }); break; } case 'customRendererMessage': { this.rendererMessaging?.postMessage(data.rendererId, data.message); break; } case 'clickMarkdownPreview': { const cell = this.notebookEditor.getCellById(data.cellId); if (cell) { if (data.shiftKey || (isMacintosh ? data.metaKey : data.ctrlKey)) { // Modify selection this.notebookEditor.toggleNotebookCellSelection(cell, /* fromPrevious */ data.shiftKey); } else { // Normal click this.notebookEditor.focusNotebookCell(cell, 'container', { skipReveal: true }); } } break; } case 'contextMenuMarkdownPreview': { const cell = this.notebookEditor.getCellById(data.cellId); if (cell) { // Focus the cell first this.notebookEditor.focusNotebookCell(cell, 'container', { skipReveal: true }); // Then show the context menu const webviewRect = this.element.getBoundingClientRect(); this.contextMenuService.showContextMenu({ getActions: () => { const result: IAction[] = []; const menu = this.menuService.createMenu(MenuId.NotebookCellTitle, this.contextKeyService); createAndFillInContextMenuActions(menu, undefined, result); menu.dispose(); return result; }, getAnchor: () => ({ x: webviewRect.x + data.clientX, y: webviewRect.y + data.clientY }) }); } break; } case 'toggleMarkdownPreview': { const cell = this.notebookEditor.getCellById(data.cellId); if (cell) { this.notebookEditor.setMarkdownCellEditState(data.cellId, CellEditState.Editing); this.notebookEditor.focusNotebookCell(cell, 'editor', { skipReveal: true }); } break; } case 'mouseEnterMarkdownPreview': { const cell = this.notebookEditor.getCellById(data.cellId); if (cell instanceof MarkdownCellViewModel) { cell.cellIsHovered = true; } break; } case 'mouseLeaveMarkdownPreview': { const cell = this.notebookEditor.getCellById(data.cellId); if (cell instanceof MarkdownCellViewModel) { cell.cellIsHovered = false; } break; } case 'cell-drag-start': { this.notebookEditor.markdownCellDragStart(data.cellId, data); break; } case 'cell-drag': { this.notebookEditor.markdownCellDrag(data.cellId, data); break; } case 'cell-drop': { this.notebookEditor.markdownCellDrop(data.cellId, { dragOffsetY: data.dragOffsetY, ctrlKey: data.ctrlKey, altKey: data.altKey, }); break; } case 'cell-drag-end': { this.notebookEditor.markdownCellDragEnd(data.cellId); break; } case 'telemetryFoundRenderedMarkdownMath': { this.telemetryService.publicLog2<{}, {}>('notebook/markdown/renderedLatex', {}); break; } case 'telemetryFoundUnrenderedMarkdownMath': { type Classification = { latexDirective: { classification: 'SystemMetaData', purpose: 'FeatureInsight'; }; }; type TelemetryEvent = { latexDirective: string; }; this.telemetryService.publicLog2<TelemetryEvent, Classification>('notebook/markdown/foundUnrenderedLatex', { latexDirective: data.latexDirective }); break; } } })); } private async _onDidClickDataLink(event: IClickedDataUrlMessage): Promise<void> { if (typeof event.data !== 'string') { return; } const [splitStart, splitData] = event.data.split(';base64,'); if (!splitData || !splitStart) { return; } const defaultDir = dirname(this.documentUri); let defaultName: string; if (event.downloadName) { defaultName = event.downloadName; } else { const mimeType = splitStart.replace(/^data:/, ''); const candidateExtension = mimeType && getExtensionForMimeType(mimeType); defaultName = candidateExtension ? `download${candidateExtension}` : 'download'; } const defaultUri = joinPath(defaultDir, defaultName); const newFileUri = await this.fileDialogService.showSaveDialog({ defaultUri }); if (!newFileUri) { return; } const decoded = atob(splitData); const typedArray = new Uint8Array(decoded.length); for (let i = 0; i < decoded.length; i++) { typedArray[i] = decoded.charCodeAt(i); } const buff = VSBuffer.wrap(typedArray); await this.fileService.writeFile(newFileUri, buff); await this.openerService.open(newFileUri); } private _createInset(webviewService: IWebviewService, content: string) { const rootPath = isWeb ? FileAccess.asBrowserUri('', require) : FileAccess.asFileUri('', require); const workspaceFolders = this.contextService.getWorkspace().folders.map(x => x.uri); this.localResourceRootsCache = [ ...this.notebookService.getNotebookProviderResourceRoots(), ...this.notebookService.getRenderers().map(x => dirname(x.entrypoint)), ...workspaceFolders, rootPath, ]; const webview = webviewService.createWebviewElement(this.id, { purpose: WebviewContentPurpose.NotebookRenderer, enableFindWidget: false, transformCssVariables: transformWebviewThemeVars, }, { allowMultipleAPIAcquire: true, allowScripts: true, localResourceRoots: this.localResourceRootsCache, }, undefined); webview.html = content; return webview; } private initializeWebViewState() { const renderers = new Set<INotebookRendererInfo>(); for (const inset of this.insetMapping.values()) { if (inset.renderer) { renderers.add(inset.renderer); } } this._preloadsCache.clear(); if (this._currentKernel) { this._updatePreloadsFromKernel(this._currentKernel); } for (const [output, inset] of this.insetMapping.entries()) { this._sendMessageToWebview({ ...inset.cachedCreation, initiallyHidden: this.hiddenInsetMapping.has(output) }); } const mdCells = [...this.markdownPreviewMapping.values()]; this.markdownPreviewMapping.clear(); this.initializeMarkdown(mdCells); this._updateStyles(); this._updateOptions(); } private shouldUpdateInset(cell: IGenericCellViewModel, output: ICellOutputViewModel, cellTop: number, outputOffset: number): boolean { if (this._disposed) { return false; } if (cell.metadata.outputCollapsed) { return false; } if (this.hiddenInsetMapping.has(output)) { return true; } const outputCache = this.insetMapping.get(output); if (!outputCache) { return false; } if (outputOffset === outputCache.cachedCreation.outputOffset && cellTop === outputCache.cachedCreation.cellTop) { return false; } return true; } ackHeight(cellId: string, id: string, height: number): void { this._sendMessageToWebview({ type: 'ack-dimension', cellId: cellId, outputId: id, height: height }); } updateScrollTops(outputRequests: IDisplayOutputLayoutUpdateRequest[], markdownPreviews: { id: string, top: number }[]) { if (this._disposed) { return; } const widgets = coalesce(outputRequests.map((request): IContentWidgetTopRequest | undefined => { const outputCache = this.insetMapping.get(request.output); if (!outputCache) { return; } if (!request.forceDisplay && !this.shouldUpdateInset(request.cell, request.output, request.cellTop, request.outputOffset)) { return; } const id = outputCache.outputId; outputCache.cachedCreation.cellTop = request.cellTop; outputCache.cachedCreation.outputOffset = request.outputOffset; this.hiddenInsetMapping.delete(request.output); return { outputId: id, cellTop: request.cellTop, outputOffset: request.outputOffset, forceDisplay: request.forceDisplay, }; })); if (!widgets.length && !markdownPreviews.length) { return; } this._sendMessageToWebview({ type: 'view-scroll', widgets: widgets, markdownPreviews, }); } private async createMarkdownPreview(initialization: IMarkdownCellInitialization) { if (this._disposed) { return; } if (this.markdownPreviewMapping.has(initialization.cellId)) { console.error('Trying to create markdown preview that already exists'); return; } this.markdownPreviewMapping.set(initialization.cellId, initialization); this._sendMessageToWebview({ type: 'createMarkupCell', cell: initialization }); } async showMarkdownPreview(initialization: IMarkdownCellInitialization) { if (this._disposed) { return; } const entry = this.markdownPreviewMapping.get(initialization.cellId); if (!entry) { return this.createMarkdownPreview(initialization); } const sameContent = initialization.content === entry.content; if (!sameContent || !entry.visible) { this._sendMessageToWebview({ type: 'showMarkupCell', id: initialization.cellId, handle: initialization.cellHandle, // If the content has not changed, we still want to make sure the // preview is visible but don't need to send anything over content: sameContent ? undefined : initialization.content, top: initialization.offset }); } entry.content = initialization.content; entry.offset = initialization.offset; entry.visible = true; } async hideMarkdownPreviews(cellIds: readonly string[]) { if (this._disposed) { return; } const cellsToHide: string[] = []; for (const cellId of cellIds) { const entry = this.markdownPreviewMapping.get(cellId); if (entry) { if (entry.visible) { cellsToHide.push(cellId); entry.visible = false; } } } if (cellsToHide.length) { this._sendMessageToWebview({ type: 'hideMarkupCells', ids: cellsToHide }); } } async unhideMarkdownPreviews(cellIds: readonly string[]) { if (this._disposed) { return; } const toUnhide: string[] = []; for (const cellId of cellIds) { const entry = this.markdownPreviewMapping.get(cellId); if (entry) { if (!entry.visible) { entry.visible = true; toUnhide.push(cellId); } } else { console.error(`Trying to unhide a preview that does not exist: ${cellId}`); } } this._sendMessageToWebview({ type: 'unhideMarkupCells', ids: toUnhide, }); } async deleteMarkdownPreviews(cellIds: readonly string[]) { if (this._disposed) { return; } for (const id of cellIds) { if (!this.markdownPreviewMapping.has(id)) { console.error(`Trying to delete a preview that does not exist: ${id}`); } this.markdownPreviewMapping.delete(id); } if (cellIds.length) { this._sendMessageToWebview({ type: 'deleteMarkupCell', ids: cellIds }); } } async updateMarkdownPreviewSelections(selectedCellsIds: string[]) { if (this._disposed) { return; } this._sendMessageToWebview({ type: 'updateSelectedMarkupCells', selectedCellIds: selectedCellsIds.filter(id => this.markdownPreviewMapping.has(id)), }); } async initializeMarkdown(cells: ReadonlyArray<IMarkdownCellInitialization>) { if (this._disposed) { return; } // TODO: use proper handler const p = new Promise<void>(resolve => { this.webview?.onMessage(e => { if (e.message.type === 'initializedMarkdownPreview') { resolve(); } }); }); for (const cell of cells) { this.markdownPreviewMapping.set(cell.cellId, { ...cell, visible: false }); } this._sendMessageToWebview({ type: 'initializeMarkup', cells, }); await p; } async createOutput(cellInfo: T, content: IInsetRenderOutput, cellTop: number, offset: number) { if (this._disposed) { return; } if (this.insetMapping.has(content.source)) { const outputCache = this.insetMapping.get(content.source); if (outputCache) { this.hiddenInsetMapping.delete(content.source); this._sendMessageToWebview({ type: 'showOutput', cellId: outputCache.cellInfo.cellId, outputId: outputCache.outputId, cellTop: cellTop, outputOffset: offset }); return; } } const messageBase = { type: 'html', cellId: cellInfo.cellId, cellTop: cellTop, outputOffset: offset, left: 0, requiredPreloads: [], } as const; let message: ICreationRequestMessage; let renderer: INotebookRendererInfo | undefined; if (content.type === RenderOutputType.Extension) { const output = content.source.model; renderer = content.renderer; const outputDto = output.outputs.find(op => op.mime === content.mimeType); // TODO@notebook - the message can contain "bytes" and those are transferable // which improves IPC performance and therefore should be used. However, it does // means that the bytes cannot be used here anymore message = { ...messageBase, outputId: output.outputId, rendererId: content.renderer.id, content: { type: RenderOutputType.Extension, outputId: output.outputId, mimeType: content.mimeType, valueBytes: new Uint8Array(outputDto?.valueBytes ?? []), metadata: output.metadata, metadata2: output.metadata }, }; } else { message = { ...messageBase, outputId: UUID.generateUuid(), content: { type: content.type, htmlContent: content.htmlContent, } }; } this._sendMessageToWebview(message); this.insetMapping.set(content.source, { outputId: message.outputId, cellInfo: cellInfo, renderer, cachedCreation: message }); this.hiddenInsetMapping.delete(content.source); this.reversedInsetMapping.set(message.outputId, content.source); } removeInsets(outputs: readonly ICellOutputViewModel[]) { if (this._disposed) { return; } for (const output of outputs) { const outputCache = this.insetMapping.get(output); if (!outputCache) { continue; } const id = outputCache.outputId; this._sendMessageToWebview({ type: 'clearOutput', rendererId: outputCache.cachedCreation.rendererId, cellUri: outputCache.cellInfo.cellUri.toString(), outputId: id, cellId: outputCache.cellInfo.cellId }); this.insetMapping.delete(output); this.reversedInsetMapping.delete(id); } } hideInset(output: ICellOutputViewModel) { if (this._disposed) { return; } const outputCache = this.insetMapping.get(output); if (!outputCache) { return; } this.hiddenInsetMapping.add(output); this._sendMessageToWebview({ type: 'hideOutput', outputId: outputCache.outputId, cellId: outputCache.cellInfo.cellId, }); } clearInsets() { if (this._disposed) { return; } this._sendMessageToWebview({ type: 'clear' }); this.insetMapping = new Map(); this.reversedInsetMapping = new Map(); } focusWebview() { if (this._disposed) { return; } this.webview?.focus(); } focusOutput(cellId: string) { if (this._disposed) { return; } this.webview?.focus(); setTimeout(() => { // Need this, or focus decoration is not shown. No clue. this._sendMessageToWebview({ type: 'focus-output', cellId, }); }, 50); } deltaCellOutputContainerClassNames(cellId: string, added: string[], removed: string[]) { this._sendMessageToWebview({ type: 'decorations', cellId, addedClassNames: added, removedClassNames: removed }); } async updateKernelPreloads(kernel: INotebookKernel | undefined) { if (this._disposed || kernel === this._currentKernel) { return; } const previousKernel = this._currentKernel; this._currentKernel = kernel; if (previousKernel && previousKernel.preloadUris.length > 0) { this.webview?.reload(); // preloads will be restored after reload } else if (kernel) { this._updatePreloadsFromKernel(kernel); } } private _updatePreloadsFromKernel(kernel: INotebookKernel) { const resources: IControllerPreload[] = []; for (const preload of kernel.preloadUris) { const uri = this.environmentService.isExtensionDevelopment && (preload.scheme === 'http' || preload.scheme === 'https') ? preload : this.asWebviewUri(preload, undefined); if (!this._preloadsCache.has(uri.toString())) { resources.push({ uri: uri.toString(), originalUri: preload.toString() }); this._preloadsCache.add(uri.toString()); } } if (!resources.length) { return; } this._updatePreloads(resources); } private _updatePreloads(resources: IControllerPreload[]) { if (!this.webview) { return; } const mixedResourceRoots = [ ...(this.localResourceRootsCache || []), ...this.rendererRootsCache, ...(this._currentKernel ? [this._currentKernel.localResourceRoot] : []), ]; this.webview.localResourcesRoot = mixedResourceRoots; this._sendMessageToWebview({ type: 'preload', resources: resources, }); } private _sendMessageToWebview(message: ToWebviewMessage) { if (this._disposed) { return; } this.webview?.postMessage(message); } clearPreloadsCache() { this._preloadsCache.clear(); } override dispose() { this._disposed = true; this.webview?.dispose(); super.dispose(); } }
src/vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView.ts
1
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.0018226930405944586, 0.00021153391571715474, 0.0001629623438930139, 0.0001702689623925835, 0.00021684562670998275 ]
{ "id": 0, "code_window": [ "\n", "\tconst style = document.createElement('style');\n", "\tstyle.classList.add('markdown-style');\n", "\tstyle.textContent = `\n", "\t\timg {\n", "\t\t\tmax-width: 100%;\n", "\t\t\tmax-height: 100%;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t.emptyMarkdownCell::before {\n", "\t\t\tcontent: \"${document.documentElement.style.getPropertyValue('--notebook-cell-markup-empty-content')}\";\n", "\t\t\tfont-style: italic;\n", "\t\t\topacity: 0.6;\n", "\t\t}\n", "\n" ], "file_path": "extensions/markdown-language-features/notebook/index.ts", "type": "add", "edit_start_line_idx": 15 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/workbench/services/keybinding/browser/keyboardLayouts/en.darwin'; // 15% import 'vs/workbench/services/keybinding/browser/keyboardLayouts/zh-hans.darwin'; import 'vs/workbench/services/keybinding/browser/keyboardLayouts/en-uk.darwin'; import 'vs/workbench/services/keybinding/browser/keyboardLayouts/es.darwin'; import 'vs/workbench/services/keybinding/browser/keyboardLayouts/jp-roman.darwin'; import 'vs/workbench/services/keybinding/browser/keyboardLayouts/de.darwin'; import 'vs/workbench/services/keybinding/browser/keyboardLayouts/en-intl.darwin'; import 'vs/workbench/services/keybinding/browser/keyboardLayouts/en-ext.darwin'; import 'vs/workbench/services/keybinding/browser/keyboardLayouts/fr.darwin'; import 'vs/workbench/services/keybinding/browser/keyboardLayouts/jp.darwin'; import 'vs/workbench/services/keybinding/browser/keyboardLayouts/pl.darwin'; import 'vs/workbench/services/keybinding/browser/keyboardLayouts/it.darwin'; import 'vs/workbench/services/keybinding/browser/keyboardLayouts/ru.darwin'; import 'vs/workbench/services/keybinding/browser/keyboardLayouts/pt.darwin'; import 'vs/workbench/services/keybinding/browser/keyboardLayouts/ko.darwin'; import 'vs/workbench/services/keybinding/browser/keyboardLayouts/dvorak.darwin'; export { KeyboardLayoutContribution } from 'vs/workbench/services/keybinding/browser/keyboardLayouts/_.contribution';
src/vs/workbench/services/keybinding/browser/keyboardLayouts/layout.contribution.darwin.ts
0
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.0001733919489197433, 0.00017150526400655508, 0.00016935534949880093, 0.00017176846449729055, 0.0000016584115201112581 ]
{ "id": 0, "code_window": [ "\n", "\tconst style = document.createElement('style');\n", "\tstyle.classList.add('markdown-style');\n", "\tstyle.textContent = `\n", "\t\timg {\n", "\t\t\tmax-width: 100%;\n", "\t\t\tmax-height: 100%;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t.emptyMarkdownCell::before {\n", "\t\t\tcontent: \"${document.documentElement.style.getPropertyValue('--notebook-cell-markup-empty-content')}\";\n", "\t\t\tfont-style: italic;\n", "\t\t\topacity: 0.6;\n", "\t\t}\n", "\n" ], "file_path": "extensions/markdown-language-features/notebook/index.ts", "type": "add", "edit_start_line_idx": 15 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-editor .snippet-placeholder { min-width: 2px; outline-style: solid; outline-width: 1px; } .monaco-editor .finish-snippet-placeholder { outline-style: solid; outline-width: 1px; }
src/vs/editor/contrib/snippet/snippetSession.css
0
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.00017428673163522035, 0.00016981785302050412, 0.00016534898895770311, 0.00016981785302050412, 0.000004468871338758618 ]
{ "id": 0, "code_window": [ "\n", "\tconst style = document.createElement('style');\n", "\tstyle.classList.add('markdown-style');\n", "\tstyle.textContent = `\n", "\t\timg {\n", "\t\t\tmax-width: 100%;\n", "\t\t\tmax-height: 100%;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t.emptyMarkdownCell::before {\n", "\t\t\tcontent: \"${document.documentElement.style.getPropertyValue('--notebook-cell-markup-empty-content')}\";\n", "\t\t\tfont-style: italic;\n", "\t\t\topacity: 0.6;\n", "\t\t}\n", "\n" ], "file_path": "extensions/markdown-language-features/notebook/index.ts", "type": "add", "edit_start_line_idx": 15 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from 'vs/nls'; import { Event } from 'vs/base/common/event'; import { onUnexpectedError } from 'vs/base/common/errors'; import { Disposable } from 'vs/base/common/lifecycle'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IExtensionManagementService, ILocalExtension, IExtensionIdentifier, InstallOperation } from 'vs/platform/extensionManagement/common/extensionManagement'; import { IWorkbenchExtensionEnablementService, EnablementState } from 'vs/workbench/services/extensionManagement/common/extensionManagement'; import { IExtensionRecommendationsService } from 'vs/workbench/services/extensionRecommendations/common/extensionRecommendations'; import { ILifecycleService } from 'vs/workbench/services/lifecycle/common/lifecycle'; import { IWorkbenchContribution } from 'vs/workbench/common/contributions'; import { ServicesAccessor, IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { areSameExtensions } from 'vs/platform/extensionManagement/common/extensionManagementUtil'; import { Severity, INotificationService } from 'vs/platform/notification/common/notification'; export interface IExtensionStatus { identifier: IExtensionIdentifier; local: ILocalExtension; globallyEnabled: boolean; } export class KeymapExtensions extends Disposable implements IWorkbenchContribution { constructor( @IInstantiationService private readonly instantiationService: IInstantiationService, @IWorkbenchExtensionEnablementService private readonly extensionEnablementService: IWorkbenchExtensionEnablementService, @IExtensionRecommendationsService private readonly tipsService: IExtensionRecommendationsService, @ILifecycleService lifecycleService: ILifecycleService, @INotificationService private readonly notificationService: INotificationService, @ITelemetryService private readonly telemetryService: ITelemetryService, ) { super(); this._register(lifecycleService.onDidShutdown(() => this.dispose())); this._register(instantiationService.invokeFunction(onExtensionChanged)((identifiers => { Promise.all(identifiers.map(identifier => this.checkForOtherKeymaps(identifier))) .then(undefined, onUnexpectedError); }))); } private checkForOtherKeymaps(extensionIdentifier: IExtensionIdentifier): Promise<void> { return this.instantiationService.invokeFunction(getInstalledExtensions).then(extensions => { const keymaps = extensions.filter(extension => isKeymapExtension(this.tipsService, extension)); const extension = keymaps.find(extension => areSameExtensions(extension.identifier, extensionIdentifier)); if (extension && extension.globallyEnabled) { const otherKeymaps = keymaps.filter(extension => !areSameExtensions(extension.identifier, extensionIdentifier) && extension.globallyEnabled); if (otherKeymaps.length) { return this.promptForDisablingOtherKeymaps(extension, otherKeymaps); } } return undefined; }); } private promptForDisablingOtherKeymaps(newKeymap: IExtensionStatus, oldKeymaps: IExtensionStatus[]): void { const onPrompt = (confirmed: boolean) => { const telemetryData: { [key: string]: any; } = { newKeymap: newKeymap.identifier, oldKeymaps: oldKeymaps.map(k => k.identifier), confirmed }; /* __GDPR__ "disableOtherKeymaps" : { "newKeymap": { "${inline}": [ "${ExtensionIdentifier}" ] }, "oldKeymaps": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "confirmed" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ this.telemetryService.publicLog('disableOtherKeymaps', telemetryData); if (confirmed) { this.extensionEnablementService.setEnablement(oldKeymaps.map(keymap => keymap.local), EnablementState.DisabledGlobally); } }; this.notificationService.prompt(Severity.Info, localize('disableOtherKeymapsConfirmation', "Disable other keymaps ({0}) to avoid conflicts between keybindings?", oldKeymaps.map(k => `'${k.local.manifest.displayName}'`).join(', ')), [{ label: localize('yes', "Yes"), run: () => onPrompt(true) }, { label: localize('no', "No"), run: () => onPrompt(false) }] ); } } export function onExtensionChanged(accessor: ServicesAccessor): Event<IExtensionIdentifier[]> { const extensionService = accessor.get(IExtensionManagementService); const extensionEnablementService = accessor.get(IWorkbenchExtensionEnablementService); const onDidInstallExtension = Event.chain(extensionService.onDidInstallExtension) .filter(e => e.operation === InstallOperation.Install) .event; return Event.debounce<IExtensionIdentifier[], IExtensionIdentifier[]>(Event.any( Event.chain(Event.any(onDidInstallExtension, extensionService.onDidUninstallExtension)) .map(e => [e.identifier]) .event, Event.map(extensionEnablementService.onEnablementChanged, extensions => extensions.map(e => e.identifier)) ), (result: IExtensionIdentifier[] | undefined, identifiers: IExtensionIdentifier[]) => { result = result || []; for (const identifier of identifiers) { if (result.some(l => !areSameExtensions(l, identifier))) { result.push(identifier); } } return result; }); } export async function getInstalledExtensions(accessor: ServicesAccessor): Promise<IExtensionStatus[]> { const extensionService = accessor.get(IExtensionManagementService); const extensionEnablementService = accessor.get(IWorkbenchExtensionEnablementService); const extensions = await extensionService.getInstalled(); return extensions.map(extension => { return { identifier: extension.identifier, local: extension, globallyEnabled: extensionEnablementService.isEnabled(extension) }; }); } export function isKeymapExtension(tipsService: IExtensionRecommendationsService, extension: IExtensionStatus): boolean { const cats = extension.local.manifest.categories; return cats && cats.indexOf('Keymaps') !== -1 || tipsService.getKeymapRecommendations().some(extensionId => areSameExtensions({ id: extensionId }, extension.local.identifier)); }
src/vs/workbench/contrib/extensions/common/extensionsUtils.ts
0
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.00017595499230083078, 0.0001717393461149186, 0.00016864744247868657, 0.0001719975844025612, 0.00000229571287491126 ]
{ "id": 1, "code_window": [ "\t\t\t} else {\n", "\t\t\t\tpreviewNode = element.shadowRoot.getElementById('preview')!;\n", "\t\t\t}\n", "\n", "\t\t\tconst rendered = markdownIt.render(outputInfo.text());\n", "\t\t\tpreviewNode.innerHTML = rendered;\n", "\t\t},\n", "\t\textendMarkdownIt: (f: (md: typeof markdownIt) => void) => {\n", "\t\t\tf(markdownIt);\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst text = outputInfo.text();\n", "\t\t\tif (text.trim().length === 0) {\n", "\t\t\t\tpreviewNode.innerText = '';\n", "\t\t\t\tpreviewNode.classList.add('emptyMarkdownCell');\n", "\t\t\t} else {\n", "\t\t\t\tpreviewNode.classList.remove('emptyMarkdownCell');\n", "\n", "\t\t\t\tconst rendered = markdownIt.render(text);\n", "\t\t\t\tpreviewNode.innerHTML = rendered;\n", "\t\t\t}\n" ], "file_path": "extensions/markdown-language-features/notebook/index.ts", "type": "replace", "edit_start_line_idx": 155 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import type { Event } from 'vs/base/common/event'; import type { IDisposable } from 'vs/base/common/lifecycle'; import { RenderOutputType } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import type * as webviewMessages from 'vs/workbench/contrib/notebook/browser/view/renderers/webviewMessages'; // !! IMPORTANT !! everything must be in-line within the webviewPreloads // function. Imports are not allowed. This is stringified and injected into // the webview. declare module globalThis { const acquireVsCodeApi: () => ({ getState(): { [key: string]: unknown; }; setState(data: { [key: string]: unknown; }): void; postMessage: (msg: unknown) => void; }); } declare class ResizeObserver { constructor(onChange: (entries: { target: HTMLElement, contentRect?: ClientRect; }[]) => void); observe(element: Element): void; disconnect(): void; } type Listener<T> = { fn: (evt: T) => void; thisArg: unknown; }; interface EmitterLike<T> { fire(data: T): void; event: Event<T>; } interface PreloadStyles { readonly outputNodePadding: number; readonly outputNodeLeftPadding: number; } export interface PreloadOptions { dragAndDropEnabled: boolean; } declare function __import(path: string): Promise<any>; async function webviewPreloads(style: PreloadStyles, options: PreloadOptions, rendererData: readonly RendererMetadata[]) { let currentOptions = options; const acquireVsCodeApi = globalThis.acquireVsCodeApi; const vscode = acquireVsCodeApi(); delete (globalThis as any).acquireVsCodeApi; const handleInnerClick = (event: MouseEvent) => { if (!event || !event.view || !event.view.document) { return; } for (const node of event.composedPath()) { if (node instanceof HTMLAnchorElement && node.href) { if (node.href.startsWith('blob:')) { handleBlobUrlClick(node.href, node.download); } else if (node.href.startsWith('data:')) { handleDataUrl(node.href, node.download); } event.preventDefault(); return; } } }; const handleDataUrl = async (data: string | ArrayBuffer | null, downloadName: string) => { postNotebookMessage<webviewMessages.IClickedDataUrlMessage>('clicked-data-url', { data, downloadName }); }; const handleBlobUrlClick = async (url: string, downloadName: string) => { try { const response = await fetch(url); const blob = await response.blob(); const reader = new FileReader(); reader.addEventListener('load', () => { handleDataUrl(reader.result, downloadName); }); reader.readAsDataURL(blob); } catch (e) { console.error(e.message); } }; document.body.addEventListener('click', handleInnerClick); const preservedScriptAttributes: (keyof HTMLScriptElement)[] = [ 'type', 'src', 'nonce', 'noModule', 'async', ]; // derived from https://github.com/jquery/jquery/blob/d0ce00cdfa680f1f0c38460bc51ea14079ae8b07/src/core/DOMEval.js const domEval = (container: Element) => { const arr = Array.from(container.getElementsByTagName('script')); for (let n = 0; n < arr.length; n++) { const node = arr[n]; const scriptTag = document.createElement('script'); const trustedScript = ttPolicy?.createScript(node.innerText) ?? node.innerText; scriptTag.text = trustedScript as string; for (const key of preservedScriptAttributes) { const val = node[key] || node.getAttribute && node.getAttribute(key); if (val) { scriptTag.setAttribute(key, val as any); } } // TODO@connor4312: should script with src not be removed? container.appendChild(scriptTag).parentNode!.removeChild(scriptTag); } }; async function loadScriptSource(url: string, originalUri = url): Promise<string> { const res = await fetch(url); const text = await res.text(); if (!res.ok) { throw new Error(`Unexpected ${res.status} requesting ${originalUri}: ${text || res.statusText}`); } return text; } interface RendererContext { getState<T>(): T | undefined; setState<T>(newState: T): void; getRenderer(id: string): Promise<any | undefined>; postMessage?(message: unknown): void; onDidReceiveMessage?: Event<unknown>; } interface ScriptModule { activate(ctx?: RendererContext): Promise<RendererApi | undefined | any> | RendererApi | undefined | any; } const invokeSourceWithGlobals = (functionSrc: string, globals: { [name: string]: unknown }) => { const args = Object.entries(globals); return new Function(...args.map(([k]) => k), functionSrc)(...args.map(([, v]) => v)); }; const runPreload = async (url: string, originalUri: string): Promise<ScriptModule> => { const text = await loadScriptSource(url, originalUri); return { activate: () => { try { return invokeSourceWithGlobals(text, { ...kernelPreloadGlobals, scriptUrl: url }); } catch (e) { console.error(e); throw e; } } }; }; const runRenderScript = async (url: string, rendererId: string): Promise<ScriptModule> => { const text = await loadScriptSource(url); // TODO: Support both the new module based renderers and the old style global renderers const isModule = !text.includes('acquireNotebookRendererApi'); if (isModule) { return __import(url); } else { return createBackCompatModule(rendererId, url, text); } }; const createBackCompatModule = (rendererId: string, scriptUrl: string, scriptText: string): ScriptModule => ({ activate: (): RendererApi => { const onDidCreateOutput = createEmitter<IOutputItem>(); const onWillDestroyOutput = createEmitter<undefined | IDestroyCellInfo>(); const globals = { scriptUrl, acquireNotebookRendererApi: <T>(): GlobalNotebookRendererApi<T> => ({ onDidCreateOutput: onDidCreateOutput.event, onWillDestroyOutput: onWillDestroyOutput.event, setState: newState => vscode.setState({ ...vscode.getState(), [rendererId]: newState }), getState: () => { const state = vscode.getState(); return typeof state === 'object' && state ? state[rendererId] as T : undefined; }, }), }; invokeSourceWithGlobals(scriptText, globals); return { renderOutputItem(outputItem) { onDidCreateOutput.fire({ ...outputItem, outputId: outputItem.id }); }, disposeOutputItem(id) { onWillDestroyOutput.fire(id ? { outputId: id } : undefined); } }; } }); const dimensionUpdater = new class { private readonly pending = new Map<string, webviewMessages.DimensionUpdate>(); update(id: string, height: number, options: { init?: boolean; isOutput?: boolean }) { if (!this.pending.size) { setTimeout(() => { this.updateImmediately(); }, 0); } this.pending.set(id, { id, height, ...options, }); } updateImmediately() { if (!this.pending.size) { return; } postNotebookMessage<webviewMessages.IDimensionMessage>('dimension', { updates: Array.from(this.pending.values()) }); this.pending.clear(); } }; const resizeObserver = new class { private readonly _observer: ResizeObserver; private readonly _observedElements = new WeakMap<Element, { id: string, output: boolean }>(); constructor() { this._observer = new ResizeObserver(entries => { for (const entry of entries) { if (!document.body.contains(entry.target)) { continue; } const observedElementInfo = this._observedElements.get(entry.target); if (!observedElementInfo) { continue; } if (entry.target.id === observedElementInfo.id && entry.contentRect) { if (observedElementInfo.output) { let height = 0; if (entry.contentRect.height !== 0) { entry.target.style.padding = `${style.outputNodePadding}px ${style.outputNodePadding}px ${style.outputNodePadding}px ${style.outputNodeLeftPadding}px`; height = entry.contentRect.height + style.outputNodePadding * 2; } else { entry.target.style.padding = `0px`; } dimensionUpdater.update(observedElementInfo.id, height, { isOutput: true }); } else { dimensionUpdater.update(observedElementInfo.id, entry.target.clientHeight, { isOutput: false }); } } } }); } public observe(container: Element, id: string, output: boolean) { if (this._observedElements.has(container)) { return; } this._observedElements.set(container, { id, output }); this._observer.observe(container); } }; function scrollWillGoToParent(event: WheelEvent) { for (let node = event.target as Node | null; node; node = node.parentNode) { if (!(node instanceof Element) || node.id === 'container' || node.classList.contains('cell_container') || node.classList.contains('output_container')) { return false; } if (event.deltaY < 0 && node.scrollTop > 0) { return true; } if (event.deltaY > 0 && node.scrollTop + node.clientHeight < node.scrollHeight) { return true; } } return false; } const handleWheel = (event: WheelEvent) => { if (event.defaultPrevented || scrollWillGoToParent(event)) { return; } postNotebookMessage<webviewMessages.IWheelMessage>('did-scroll-wheel', { payload: { deltaMode: event.deltaMode, deltaX: event.deltaX, deltaY: event.deltaY, deltaZ: event.deltaZ, detail: event.detail, type: event.type } }); }; function focusFirstFocusableInCell(cellId: string) { const cellOutputContainer = document.getElementById(cellId); if (cellOutputContainer) { const focusableElement = cellOutputContainer.querySelector('[tabindex="0"], [href], button, input, option, select, textarea') as HTMLElement | null; focusableElement?.focus(); } } function createFocusSink(cellId: string, outputId: string, focusNext?: boolean) { const element = document.createElement('div'); element.tabIndex = 0; element.addEventListener('focus', () => { postNotebookMessage<webviewMessages.IBlurOutputMessage>('focus-editor', { id: outputId, focusNext }); }); return element; } function addMouseoverListeners(element: HTMLElement, outputId: string): void { element.addEventListener('mouseenter', () => { postNotebookMessage<webviewMessages.IMouseEnterMessage>('mouseenter', { id: outputId, }); }); element.addEventListener('mouseleave', () => { postNotebookMessage<webviewMessages.IMouseLeaveMessage>('mouseleave', { id: outputId, }); }); } function isAncestor(testChild: Node | null, testAncestor: Node | null): boolean { while (testChild) { if (testChild === testAncestor) { return true; } testChild = testChild.parentNode; } return false; } class FocusTracker { private _outputId: string; private _hasFocus: boolean = false; private _loosingFocus: boolean = false; private _element: HTMLElement | Window; constructor(element: HTMLElement | Window, outputId: string) { this._element = element; this._outputId = outputId; this._hasFocus = isAncestor(document.activeElement, <HTMLElement>element); this._loosingFocus = false; element.addEventListener('focus', this._onFocus.bind(this), true); element.addEventListener('blur', this._onBlur.bind(this), true); } private _onFocus() { this._loosingFocus = false; if (!this._hasFocus) { this._hasFocus = true; postNotebookMessage<webviewMessages.IOutputFocusMessage>('outputFocus', { id: this._outputId, }); } } private _onBlur() { if (this._hasFocus) { this._loosingFocus = true; window.setTimeout(() => { if (this._loosingFocus) { this._loosingFocus = false; this._hasFocus = false; postNotebookMessage<webviewMessages.IOutputBlurMessage>('outputBlur', { id: this._outputId, }); } }, 0); } } dispose() { if (this._element) { this._element.removeEventListener('focus', this._onFocus, true); this._element.removeEventListener('blur', this._onBlur, true); } } } const focusTrackers = new Map<string, FocusTracker>(); function addFocusTracker(element: HTMLElement, outputId: string): void { if (focusTrackers.has(outputId)) { focusTrackers.get(outputId)?.dispose(); } focusTrackers.set(outputId, new FocusTracker(element, outputId)); } function createEmitter<T>(listenerChange: (listeners: Set<Listener<T>>) => void = () => undefined): EmitterLike<T> { const listeners = new Set<Listener<T>>(); return { fire(data) { for (const listener of [...listeners]) { listener.fn.call(listener.thisArg, data); } }, event(fn, thisArg, disposables) { const listenerObj = { fn, thisArg }; const disposable: IDisposable = { dispose: () => { listeners.delete(listenerObj); listenerChange(listeners); }, }; listeners.add(listenerObj); listenerChange(listeners); if (disposables instanceof Array) { disposables.push(disposable); } else if (disposables) { disposables.add(disposable); } return disposable; }, }; } function showPreloadErrors(outputNode: HTMLElement, ...errors: readonly Error[]) { outputNode.innerText = `Error loading preloads:`; const errList = document.createElement('ul'); for (const result of errors) { console.error(result); const item = document.createElement('li'); item.innerText = result.message; errList.appendChild(item); } outputNode.appendChild(errList); } interface IOutputItem { readonly id: string; /** @deprecated */ readonly outputId?: string; /** @deprecated */ readonly element: HTMLElement; readonly mime: string; metadata: unknown; metadata2: unknown; text(): string; json(): any; data(): Uint8Array; blob(): Blob; /** @deprecated */ bytes(): Uint8Array; } interface IDestroyCellInfo { outputId: string; } const onDidReceiveKernelMessage = createEmitter<unknown>(); /** @deprecated */ interface GlobalNotebookRendererApi<T> { setState: (newState: T) => void; getState(): T | undefined; readonly onWillDestroyOutput: Event<undefined | IDestroyCellInfo>; readonly onDidCreateOutput: Event<IOutputItem>; } const kernelPreloadGlobals = { acquireVsCodeApi, onDidReceiveKernelMessage: onDidReceiveKernelMessage.event, postKernelMessage: (data: unknown) => postNotebookMessage('customKernelMessage', { message: data }), }; const ttPolicy = window.trustedTypes?.createPolicy('notebookRenderer', { createHTML: value => value, createScript: value => value, }); window.addEventListener('wheel', handleWheel); window.addEventListener('message', async rawEvent => { const event = rawEvent as ({ data: webviewMessages.ToWebviewMessage; }); switch (event.data.type) { case 'initializeMarkup': { await ensureMarkdownPreviewCells(event.data.cells); dimensionUpdater.updateImmediately(); postNotebookMessage('initializedMarkdownPreview', {}); } break; case 'createMarkupCell': ensureMarkdownPreviewCells([event.data.cell]); break; case 'showMarkupCell': { const data = event.data; const cellContainer = document.getElementById(data.id); if (cellContainer) { cellContainer.style.visibility = 'visible'; cellContainer.style.top = `${data.top}px`; updateMarkdownPreview(cellContainer, data.id, data.content); } } break; case 'hideMarkupCells': { for (const id of event.data.ids) { const cellContainer = document.getElementById(id); if (cellContainer) { cellContainer.style.visibility = 'hidden'; } } } break; case 'unhideMarkupCells': { for (const id of event.data.ids) { const cellContainer = document.getElementById(id); if (cellContainer) { cellContainer.style.visibility = 'visible'; updateMarkdownPreview(cellContainer, id, undefined); } } } break; case 'deleteMarkupCell': { for (const id of event.data.ids) { const cellContainer = document.getElementById(id); cellContainer?.remove(); } } break; case 'updateSelectedMarkupCells': { const selectedCellIds = new Set<string>(event.data.selectedCellIds); for (const oldSelected of document.querySelectorAll('.preview.selected')) { const id = oldSelected.id; if (!selectedCellIds.has(id)) { oldSelected.classList.remove('selected'); } } for (const newSelected of selectedCellIds) { const previewContainer = document.getElementById(newSelected); if (previewContainer) { previewContainer.classList.add('selected'); } } } break; case 'html': { const data = event.data; outputs.enqueue(event.data.outputId, async (state) => { const preloadsAndErrors = await Promise.all<unknown>([ data.rendererId ? renderers.load(data.rendererId) : undefined, ...data.requiredPreloads.map(p => kernelPreloads.waitFor(p.uri)), ].map(p => p?.catch(err => err))); if (state.cancelled) { return; } let cellOutputContainer = document.getElementById(data.cellId); const outputId = data.outputId; if (!cellOutputContainer) { const container = document.getElementById('container')!; const upperWrapperElement = createFocusSink(data.cellId, outputId); container.appendChild(upperWrapperElement); const newElement = document.createElement('div'); newElement.id = data.cellId; newElement.classList.add('cell_container'); container.appendChild(newElement); cellOutputContainer = newElement; const lowerWrapperElement = createFocusSink(data.cellId, outputId, true); container.appendChild(lowerWrapperElement); } cellOutputContainer.style.position = 'absolute'; cellOutputContainer.style.top = data.cellTop + 'px'; const outputContainer = document.createElement('div'); outputContainer.classList.add('output_container'); outputContainer.style.position = 'absolute'; outputContainer.style.overflow = 'hidden'; outputContainer.style.maxHeight = '0px'; outputContainer.style.top = `${data.outputOffset}px`; const outputNode = document.createElement('div'); outputNode.classList.add('output'); outputNode.style.position = 'absolute'; outputNode.style.top = `0px`; outputNode.style.left = data.left + 'px'; // outputNode.style.width = 'calc(100% - ' + data.left + 'px)'; // outputNode.style.minHeight = '32px'; outputNode.style.padding = '0px'; outputNode.id = outputId; addMouseoverListeners(outputNode, outputId); addFocusTracker(outputNode, outputId); const content = data.content; if (content.type === RenderOutputType.Html) { const trustedHtml = ttPolicy?.createHTML(content.htmlContent) ?? content.htmlContent; outputNode.innerHTML = trustedHtml as string; domEval(outputNode); } else if (preloadsAndErrors.some(e => e instanceof Error)) { const errors = preloadsAndErrors.filter((e): e is Error => e instanceof Error); showPreloadErrors(outputNode, ...errors); } else { const rendererApi = preloadsAndErrors[0] as RendererApi; try { rendererApi.renderOutputItem({ id: outputId, element: outputNode, mime: content.mimeType, metadata: content.metadata, metadata2: content.metadata2, data() { return content.valueBytes; }, bytes() { return this.data(); }, text() { return new TextDecoder().decode(content.valueBytes); }, json() { return JSON.parse(this.text()); }, blob() { return new Blob([content.valueBytes], { type: content.mimeType }); } }, outputNode); } catch (e) { showPreloadErrors(outputNode, e); } } cellOutputContainer.appendChild(outputContainer); outputContainer.appendChild(outputNode); resizeObserver.observe(outputNode, outputId, true); if (content.type === RenderOutputType.Html) { domEval(outputNode); } const clientHeight = outputNode.clientHeight; const cps = document.defaultView!.getComputedStyle(outputNode); if (clientHeight !== 0 && cps.padding === '0px') { // we set padding to zero if the output height is zero (then we can have a zero-height output DOM node) // thus we need to ensure the padding is accounted when updating the init height of the output dimensionUpdater.update(outputId, clientHeight + style.outputNodePadding * 2, { isOutput: true, init: true, }); outputNode.style.padding = `${style.outputNodePadding}px ${style.outputNodePadding}px ${style.outputNodePadding}px ${style.outputNodeLeftPadding}px`; } else { dimensionUpdater.update(outputId, outputNode.clientHeight, { isOutput: true, init: true, }); } // don't hide until after this step so that the height is right cellOutputContainer.style.visibility = data.initiallyHidden ? 'hidden' : 'visible'; }); break; } case 'view-scroll': { // const date = new Date(); // console.log('----- will scroll ---- ', date.getMinutes() + ':' + date.getSeconds() + ':' + date.getMilliseconds()); for (const request of event.data.widgets) { const widget = document.getElementById(request.outputId); if (widget) { widget.parentElement!.parentElement!.style.top = `${request.cellTop}px`; widget.parentElement!.style.top = `${request.outputOffset}px`; if (request.forceDisplay) { widget.parentElement!.parentElement!.style.visibility = 'visible'; } } } for (const cell of event.data.markdownPreviews) { const container = document.getElementById(cell.id); if (container) { container.style.top = `${cell.top}px`; } } break; } case 'clear': renderers.clearAll(); document.getElementById('container')!.innerText = ''; focusTrackers.forEach(ft => { ft.dispose(); }); focusTrackers.clear(); break; case 'clearOutput': { const output = document.getElementById(event.data.outputId); const { rendererId, outputId } = event.data; outputs.cancelOutput(outputId); if (output && output.parentNode) { if (rendererId) { renderers.clearOutput(rendererId, outputId); } output.parentNode.removeChild(output); } break; } case 'hideOutput': { const { outputId } = event.data; outputs.enqueue(event.data.outputId, () => { const container = document.getElementById(outputId)?.parentElement?.parentElement; if (container) { container.style.visibility = 'hidden'; } }); break; } case 'showOutput': { const { outputId, cellTop: top } = event.data; outputs.enqueue(event.data.outputId, () => { const output = document.getElementById(outputId); if (output) { output.parentElement!.parentElement!.style.visibility = 'visible'; output.parentElement!.parentElement!.style.top = top + 'px'; dimensionUpdater.update(outputId, output.clientHeight, { isOutput: true, }); } }); break; } case 'ack-dimension': { const { outputId, height } = event.data; const output = document.getElementById(outputId); if (output) { output.parentElement!.style.maxHeight = `${height}px`; output.parentElement!.style.height = `${height}px`; } break; } case 'preload': const resources = event.data.resources; for (const { uri, originalUri } of resources) { kernelPreloads.load(uri, originalUri); } break; case 'focus-output': focusFirstFocusableInCell(event.data.cellId); break; case 'decorations': { const outputContainer = document.getElementById(event.data.cellId); outputContainer?.classList.add(...event.data.addedClassNames); outputContainer?.classList.remove(...event.data.removedClassNames); } break; case 'customKernelMessage': onDidReceiveKernelMessage.fire(event.data.message); break; case 'customRendererMessage': renderers.getRenderer(event.data.rendererId)?.receiveMessage(event.data.message); break; case 'notebookStyles': const documentStyle = document.documentElement.style; for (let i = documentStyle.length - 1; i >= 0; i--) { const property = documentStyle[i]; // Don't remove properties that the webview might have added separately if (property && property.startsWith('--notebook-')) { documentStyle.removeProperty(property); } } // Re-add new properties for (const variable of Object.keys(event.data.styles)) { documentStyle.setProperty(`--${variable}`, event.data.styles[variable]); } break; case 'notebookOptions': currentOptions = event.data.options; // Update markdown previews for (const markdownContainer of document.querySelectorAll('.preview')) { setMarkdownContainerDraggable(markdownContainer, currentOptions.dragAndDropEnabled); } break; } }); interface RendererApi { renderOutputItem: (outputItem: IOutputItem, element: HTMLElement) => void; disposeOutputItem?: (id?: string) => void; } class Renderer { constructor( public readonly data: RendererMetadata, private readonly loadExtension: (id: string) => Promise<void>, ) { } private _onMessageEvent = createEmitter(); private _loadPromise?: Promise<RendererApi | undefined>; private _api: RendererApi | undefined; public get api() { return this._api; } public load(): Promise<RendererApi | undefined> { if (!this._loadPromise) { this._loadPromise = this._load(); } return this._loadPromise; } public receiveMessage(message: unknown) { this._onMessageEvent.fire(message); } private createRendererContext(): RendererContext { const { id, messaging } = this.data; const context: RendererContext = { setState: newState => vscode.setState({ ...vscode.getState(), [id]: newState }), getState: <T>() => { const state = vscode.getState(); return typeof state === 'object' && state ? state[id] as T : undefined; }, // TODO: This is async so that we can return a promise to the API in the future. // Currently the API is always resolved before we call `createRendererContext`. getRenderer: async (id: string) => renderers.getRenderer(id)?.api, }; if (messaging) { context.onDidReceiveMessage = this._onMessageEvent.event; context.postMessage = message => postNotebookMessage('customRendererMessage', { rendererId: id, message }); } return context; } /** Inner function cached in the _loadPromise(). */ private async _load(): Promise<RendererApi | undefined> { const module = await runRenderScript(this.data.entrypoint, this.data.id); if (!module) { return; } const api = await module.activate(this.createRendererContext()); this._api = api; // Squash any errors extends errors. They won't prevent the renderer // itself from working, so just log them. await Promise.all(rendererData .filter(d => d.extends === this.data.id) .map(d => this.loadExtension(d.id).catch(console.error)), ); return api; } } const kernelPreloads = new class { private readonly preloads = new Map<string /* uri */, Promise<unknown>>(); /** * Returns a promise that resolves when the given preload is activated. */ public waitFor(uri: string) { return this.preloads.get(uri) || Promise.resolve(new Error(`Preload not ready: ${uri}`)); } /** * Loads a preload. * @param uri URI to load from * @param originalUri URI to show in an error message if the preload is invalid. */ public load(uri: string, originalUri: string) { const promise = Promise.all([ runPreload(uri, originalUri), this.waitForAllCurrent(), ]).then(([module]) => module.activate()); this.preloads.set(uri, promise); return promise; } /** * Returns a promise that waits for all currently-registered preloads to * activate before resolving. */ private waitForAllCurrent() { return Promise.all([...this.preloads.values()].map(p => p.catch(err => err))); } }; const outputs = new class { private outputs = new Map<string, { cancelled: boolean; queue: Promise<unknown> }>(); /** * Pushes the action onto the list of actions for the given output ID, * ensuring that it's run in-order. */ public enqueue(outputId: string, action: (record: { cancelled: boolean }) => unknown) { const record = this.outputs.get(outputId); if (!record) { this.outputs.set(outputId, { cancelled: false, queue: new Promise(r => r(action({ cancelled: false }))) }); } else { record.queue = record.queue.then(r => !record.cancelled && action(record)); } } /** * Cancels the rendering of all outputs. */ public cancelAll() { for (const record of this.outputs.values()) { record.cancelled = true; } this.outputs.clear(); } /** * Cancels any ongoing rendering out an output. */ public cancelOutput(outputId: string) { const output = this.outputs.get(outputId); if (output) { output.cancelled = true; this.outputs.delete(outputId); } } }; const renderers = new class { private readonly _renderers = new Map</* id */ string, Renderer>(); constructor() { for (const renderer of rendererData) { this._renderers.set(renderer.id, new Renderer(renderer, async (extensionId) => { const ext = this._renderers.get(extensionId); if (!ext) { throw new Error(`Could not find extending renderer: ${extensionId}`); } await ext.load(); })); } } public getRenderer(id: string) { return this._renderers.get(id); } public async load(id: string) { const renderer = this._renderers.get(id); if (!renderer) { throw new Error('Could not find renderer'); } return renderer.load(); } public clearAll() { outputs.cancelAll(); for (const renderer of this._renderers.values()) { renderer.api?.disposeOutputItem?.(); } } public clearOutput(rendererId: string, outputId: string) { outputs.cancelOutput(outputId); this._renderers.get(rendererId)?.api?.disposeOutputItem?.(outputId); } public async render(info: IOutputItem, element: HTMLElement) { const renderers = Array.from(this._renderers.values()) .filter(renderer => renderer.data.mimeTypes.includes(info.mime) && !renderer.data.extends); if (!renderers.length) { throw new Error('Could not find renderer'); } await Promise.all(renderers.map(x => x.load())); renderers[0].api?.renderOutputItem(info, element); } }(); vscode.postMessage({ __vscode_notebook_message: true, type: 'initialized' }); function setMarkdownContainerDraggable(element: Element, isDraggable: boolean) { if (isDraggable) { element.classList.add('draggable'); element.setAttribute('draggable', 'true'); } else { element.classList.remove('draggable'); element.removeAttribute('draggable'); } } async function createMarkdownPreview(cellId: string, content: string, top: number): Promise<HTMLElement> { const container = document.getElementById('container')!; const cellContainer = document.createElement('div'); const existing = document.getElementById(cellId); if (existing) { console.error(`Trying to create markdown preview that already exists: ${cellId}`); return existing; } cellContainer.id = cellId; cellContainer.classList.add('preview'); cellContainer.style.position = 'absolute'; cellContainer.style.top = top + 'px'; container.appendChild(cellContainer); cellContainer.addEventListener('dblclick', () => { postNotebookMessage<webviewMessages.IToggleMarkdownPreviewMessage>('toggleMarkdownPreview', { cellId }); }); cellContainer.addEventListener('click', e => { postNotebookMessage<webviewMessages.IClickMarkdownPreviewMessage>('clickMarkdownPreview', { cellId, altKey: e.altKey, ctrlKey: e.ctrlKey, metaKey: e.metaKey, shiftKey: e.shiftKey, }); }); cellContainer.addEventListener('contextmenu', e => { postNotebookMessage<webviewMessages.IContextMenuMarkdownPreviewMessage>('contextMenuMarkdownPreview', { cellId, clientX: e.clientX, clientY: e.clientY, }); }); cellContainer.addEventListener('mouseenter', () => { postNotebookMessage<webviewMessages.IMouseEnterMarkdownPreviewMessage>('mouseEnterMarkdownPreview', { cellId }); }); cellContainer.addEventListener('mouseleave', () => { postNotebookMessage<webviewMessages.IMouseLeaveMarkdownPreviewMessage>('mouseLeaveMarkdownPreview', { cellId }); }); setMarkdownContainerDraggable(cellContainer, currentOptions.dragAndDropEnabled); cellContainer.addEventListener('dragstart', e => { markdownPreviewDragManager.startDrag(e, cellId); }); cellContainer.addEventListener('drag', e => { markdownPreviewDragManager.updateDrag(e, cellId); }); cellContainer.addEventListener('dragend', e => { markdownPreviewDragManager.endDrag(e, cellId); }); await updateMarkdownPreview(cellContainer, cellId, content); resizeObserver.observe(cellContainer, cellId, false); return cellContainer; } async function ensureMarkdownPreviewCells(update: readonly webviewMessages.IMarkdownCellInitialization[]): Promise<void> { await Promise.all(update.map(async cell => { let container = document.getElementById(cell.cellId); if (container) { await updateMarkdownPreview(container, cell.cellId, cell.content); } else { container = await createMarkdownPreview(cell.cellId, cell.content, cell.offset); } container.style.visibility = cell.visible ? 'visible' : 'hidden'; })); } function postNotebookMessage<T extends webviewMessages.FromWebviewMessage>( type: T['type'], properties: Omit<T, '__vscode_notebook_message' | 'type'> ) { vscode.postMessage({ __vscode_notebook_message: true, type, ...properties }); } let hasPostedRenderedMathTelemetry = false; const unsupportedKatexTermsRegex = /(\\(?:abovewithdelims|array|Arrowvert|arrowvert|atopwithdelims|bbox|bracevert|buildrel|cancelto|cases|class|cssId|ddddot|dddot|DeclareMathOperator|definecolor|displaylines|enclose|eqalign|eqalignno|eqref|hfil|hfill|idotsint|iiiint|label|leftarrowtail|leftroot|leqalignno|lower|mathtip|matrix|mbox|mit|mmlToken|moveleft|moveright|mspace|newenvironment|Newextarrow|notag|oldstyle|overparen|overwithdelims|pmatrix|raise|ref|renewenvironment|require|root|Rule|scr|shoveleft|shoveright|sideset|skew|Space|strut|style|texttip|Tiny|toggle|underparen|unicode|uproot)\b)/gi; async function updateMarkdownPreview(previewContainerNode: HTMLElement, cellId: string, content: string | undefined) { if (typeof content === 'string') { if (content.trim().length === 0) { previewContainerNode.classList.add('emptyMarkdownCell'); previewContainerNode.innerText = ''; } else { previewContainerNode.classList.remove('emptyMarkdownCell'); await renderers.render(createMarkdownOutputItem(cellId, previewContainerNode, content), previewContainerNode); if (!hasPostedRenderedMathTelemetry) { const hasRenderedMath = previewContainerNode.querySelector('.katex'); if (hasRenderedMath) { hasPostedRenderedMathTelemetry = true; postNotebookMessage<webviewMessages.ITelemetryFoundRenderedMarkdownMath>('telemetryFoundRenderedMarkdownMath', {}); } } const matches = previewContainerNode.innerText.match(unsupportedKatexTermsRegex); if (matches) { postNotebookMessage<webviewMessages.ITelemetryFoundUnrenderedMarkdownMath>('telemetryFoundUnrenderedMarkdownMath', { latexDirective: matches[0], }); } } } dimensionUpdater.update(cellId, previewContainerNode.clientHeight, { isOutput: false }); } const markdownPreviewDragManager = new class MarkdownPreviewDragManager { private currentDrag: { cellId: string, clientY: number } | undefined; constructor() { document.addEventListener('dragover', e => { // Allow dropping dragged markdown cells e.preventDefault(); }); document.addEventListener('drop', e => { e.preventDefault(); const drag = this.currentDrag; if (!drag) { return; } this.currentDrag = undefined; postNotebookMessage<webviewMessages.ICellDropMessage>('cell-drop', { cellId: drag.cellId, ctrlKey: e.ctrlKey, altKey: e.altKey, dragOffsetY: e.clientY, }); }); } startDrag(e: DragEvent, cellId: string) { if (!e.dataTransfer) { return; } if (!currentOptions.dragAndDropEnabled) { return; } this.currentDrag = { cellId, clientY: e.clientY }; (e.target as HTMLElement).classList.add('dragging'); postNotebookMessage<webviewMessages.ICellDragStartMessage>('cell-drag-start', { cellId: cellId, dragOffsetY: e.clientY, }); // Continuously send updates while dragging instead of relying on `updateDrag`. // This lets us scroll the list based on drag position. const trySendDragUpdate = () => { if (this.currentDrag?.cellId !== cellId) { return; } postNotebookMessage<webviewMessages.ICellDragMessage>('cell-drag', { cellId: cellId, dragOffsetY: this.currentDrag.clientY, }); requestAnimationFrame(trySendDragUpdate); }; requestAnimationFrame(trySendDragUpdate); } updateDrag(e: DragEvent, cellId: string) { if (cellId !== this.currentDrag?.cellId) { this.currentDrag = undefined; } this.currentDrag = { cellId, clientY: e.clientY }; } endDrag(e: DragEvent, cellId: string) { this.currentDrag = undefined; (e.target as HTMLElement).classList.remove('dragging'); postNotebookMessage<webviewMessages.ICellDragEndMessage>('cell-drag-end', { cellId: cellId }); } }(); function createMarkdownOutputItem(id: string, element: HTMLElement, content: string): IOutputItem { return { id, element, mime: 'text/markdown', metadata: undefined, metadata2: undefined, outputId: undefined, text() { return content; }, json() { return undefined; }, bytes() { return this.data(); }, data() { return new TextEncoder().encode(content); }, blob() { return new Blob([this.data()], { type: this.mime }); }, }; } } export interface RendererMetadata { readonly id: string; readonly entrypoint: string; readonly mimeTypes: readonly string[]; readonly extends: string | undefined; readonly messaging: boolean; } export function preloadsScriptStr(styleValues: PreloadStyles, options: PreloadOptions, renderers: readonly RendererMetadata[]) { // TS will try compiling `import()` in webviePreloads, so use an helper function instead // of using `import(...)` directly return ` const __import = (x) => import(x); (${webviewPreloads})( JSON.parse(decodeURIComponent("${encodeURIComponent(JSON.stringify(styleValues))}")), JSON.parse(decodeURIComponent("${encodeURIComponent(JSON.stringify(options))}")), JSON.parse(decodeURIComponent("${encodeURIComponent(JSON.stringify(renderers))}")) )\n//# sourceURL=notebookWebviewPreloads.js\n`; }
src/vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads.ts
1
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.004023169633001089, 0.00032111149630509317, 0.0001621158153284341, 0.00017193920211866498, 0.0004840393958147615 ]
{ "id": 1, "code_window": [ "\t\t\t} else {\n", "\t\t\t\tpreviewNode = element.shadowRoot.getElementById('preview')!;\n", "\t\t\t}\n", "\n", "\t\t\tconst rendered = markdownIt.render(outputInfo.text());\n", "\t\t\tpreviewNode.innerHTML = rendered;\n", "\t\t},\n", "\t\textendMarkdownIt: (f: (md: typeof markdownIt) => void) => {\n", "\t\t\tf(markdownIt);\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst text = outputInfo.text();\n", "\t\t\tif (text.trim().length === 0) {\n", "\t\t\t\tpreviewNode.innerText = '';\n", "\t\t\t\tpreviewNode.classList.add('emptyMarkdownCell');\n", "\t\t\t} else {\n", "\t\t\t\tpreviewNode.classList.remove('emptyMarkdownCell');\n", "\n", "\t\t\t\tconst rendered = markdownIt.render(text);\n", "\t\t\t\tpreviewNode.innerHTML = rendered;\n", "\t\t\t}\n" ], "file_path": "extensions/markdown-language-features/notebook/index.ts", "type": "replace", "edit_start_line_idx": 155 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CharCode } from 'vs/base/common/charCode'; import * as strings from 'vs/base/common/strings'; import { WordCharacterClass, WordCharacterClassifier, getMapForWordSeparators } from 'vs/editor/common/controller/wordCharacterClassifier'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { EndOfLinePreference, FindMatch } from 'vs/editor/common/model'; import { TextModel } from 'vs/editor/common/model/textModel'; const LIMIT_FIND_COUNT = 999; export class SearchParams { public readonly searchString: string; public readonly isRegex: boolean; public readonly matchCase: boolean; public readonly wordSeparators: string | null; constructor(searchString: string, isRegex: boolean, matchCase: boolean, wordSeparators: string | null) { this.searchString = searchString; this.isRegex = isRegex; this.matchCase = matchCase; this.wordSeparators = wordSeparators; } public parseSearchRequest(): SearchData | null { if (this.searchString === '') { return null; } // Try to create a RegExp out of the params let multiline: boolean; if (this.isRegex) { multiline = isMultilineRegexSource(this.searchString); } else { multiline = (this.searchString.indexOf('\n') >= 0); } let regex: RegExp | null = null; try { regex = strings.createRegExp(this.searchString, this.isRegex, { matchCase: this.matchCase, wholeWord: false, multiline: multiline, global: true, unicode: true }); } catch (err) { return null; } if (!regex) { return null; } let canUseSimpleSearch = (!this.isRegex && !multiline); if (canUseSimpleSearch && this.searchString.toLowerCase() !== this.searchString.toUpperCase()) { // casing might make a difference canUseSimpleSearch = this.matchCase; } return new SearchData(regex, this.wordSeparators ? getMapForWordSeparators(this.wordSeparators) : null, canUseSimpleSearch ? this.searchString : null); } } export function isMultilineRegexSource(searchString: string): boolean { if (!searchString || searchString.length === 0) { return false; } for (let i = 0, len = searchString.length; i < len; i++) { const chCode = searchString.charCodeAt(i); if (chCode === CharCode.Backslash) { // move to next char i++; if (i >= len) { // string ends with a \ break; } const nextChCode = searchString.charCodeAt(i); if (nextChCode === CharCode.n || nextChCode === CharCode.r || nextChCode === CharCode.W || nextChCode === CharCode.w) { return true; } } } return false; } export class SearchData { /** * The regex to search for. Always defined. */ public readonly regex: RegExp; /** * The word separator classifier. */ public readonly wordSeparators: WordCharacterClassifier | null; /** * The simple string to search for (if possible). */ public readonly simpleSearch: string | null; constructor(regex: RegExp, wordSeparators: WordCharacterClassifier | null, simpleSearch: string | null) { this.regex = regex; this.wordSeparators = wordSeparators; this.simpleSearch = simpleSearch; } } export function createFindMatch(range: Range, rawMatches: RegExpExecArray, captureMatches: boolean): FindMatch { if (!captureMatches) { return new FindMatch(range, null); } let matches: string[] = []; for (let i = 0, len = rawMatches.length; i < len; i++) { matches[i] = rawMatches[i]; } return new FindMatch(range, matches); } class LineFeedCounter { private readonly _lineFeedsOffsets: number[]; constructor(text: string) { let lineFeedsOffsets: number[] = []; let lineFeedsOffsetsLen = 0; for (let i = 0, textLen = text.length; i < textLen; i++) { if (text.charCodeAt(i) === CharCode.LineFeed) { lineFeedsOffsets[lineFeedsOffsetsLen++] = i; } } this._lineFeedsOffsets = lineFeedsOffsets; } public findLineFeedCountBeforeOffset(offset: number): number { const lineFeedsOffsets = this._lineFeedsOffsets; let min = 0; let max = lineFeedsOffsets.length - 1; if (max === -1) { // no line feeds return 0; } if (offset <= lineFeedsOffsets[0]) { // before first line feed return 0; } while (min < max) { const mid = min + ((max - min) / 2 >> 0); if (lineFeedsOffsets[mid] >= offset) { max = mid - 1; } else { if (lineFeedsOffsets[mid + 1] >= offset) { // bingo! min = mid; max = mid; } else { min = mid + 1; } } } return min + 1; } } export class TextModelSearch { public static findMatches(model: TextModel, searchParams: SearchParams, searchRange: Range, captureMatches: boolean, limitResultCount: number): FindMatch[] { const searchData = searchParams.parseSearchRequest(); if (!searchData) { return []; } if (searchData.regex.multiline) { return this._doFindMatchesMultiline(model, searchRange, new Searcher(searchData.wordSeparators, searchData.regex), captureMatches, limitResultCount); } return this._doFindMatchesLineByLine(model, searchRange, searchData, captureMatches, limitResultCount); } /** * Multiline search always executes on the lines concatenated with \n. * We must therefore compensate for the count of \n in case the model is CRLF */ private static _getMultilineMatchRange(model: TextModel, deltaOffset: number, text: string, lfCounter: LineFeedCounter | null, matchIndex: number, match0: string): Range { let startOffset: number; let lineFeedCountBeforeMatch = 0; if (lfCounter) { lineFeedCountBeforeMatch = lfCounter.findLineFeedCountBeforeOffset(matchIndex); startOffset = deltaOffset + matchIndex + lineFeedCountBeforeMatch /* add as many \r as there were \n */; } else { startOffset = deltaOffset + matchIndex; } let endOffset: number; if (lfCounter) { let lineFeedCountBeforeEndOfMatch = lfCounter.findLineFeedCountBeforeOffset(matchIndex + match0.length); let lineFeedCountInMatch = lineFeedCountBeforeEndOfMatch - lineFeedCountBeforeMatch; endOffset = startOffset + match0.length + lineFeedCountInMatch /* add as many \r as there were \n */; } else { endOffset = startOffset + match0.length; } const startPosition = model.getPositionAt(startOffset); const endPosition = model.getPositionAt(endOffset); return new Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column); } private static _doFindMatchesMultiline(model: TextModel, searchRange: Range, searcher: Searcher, captureMatches: boolean, limitResultCount: number): FindMatch[] { const deltaOffset = model.getOffsetAt(searchRange.getStartPosition()); // We always execute multiline search over the lines joined with \n // This makes it that \n will match the EOL for both CRLF and LF models // We compensate for offset errors in `_getMultilineMatchRange` const text = model.getValueInRange(searchRange, EndOfLinePreference.LF); const lfCounter = (model.getEOL() === '\r\n' ? new LineFeedCounter(text) : null); const result: FindMatch[] = []; let counter = 0; let m: RegExpExecArray | null; searcher.reset(0); while ((m = searcher.next(text))) { result[counter++] = createFindMatch(this._getMultilineMatchRange(model, deltaOffset, text, lfCounter, m.index, m[0]), m, captureMatches); if (counter >= limitResultCount) { return result; } } return result; } private static _doFindMatchesLineByLine(model: TextModel, searchRange: Range, searchData: SearchData, captureMatches: boolean, limitResultCount: number): FindMatch[] { const result: FindMatch[] = []; let resultLen = 0; // Early case for a search range that starts & stops on the same line number if (searchRange.startLineNumber === searchRange.endLineNumber) { const text = model.getLineContent(searchRange.startLineNumber).substring(searchRange.startColumn - 1, searchRange.endColumn - 1); resultLen = this._findMatchesInLine(searchData, text, searchRange.startLineNumber, searchRange.startColumn - 1, resultLen, result, captureMatches, limitResultCount); return result; } // Collect results from first line const text = model.getLineContent(searchRange.startLineNumber).substring(searchRange.startColumn - 1); resultLen = this._findMatchesInLine(searchData, text, searchRange.startLineNumber, searchRange.startColumn - 1, resultLen, result, captureMatches, limitResultCount); // Collect results from middle lines for (let lineNumber = searchRange.startLineNumber + 1; lineNumber < searchRange.endLineNumber && resultLen < limitResultCount; lineNumber++) { resultLen = this._findMatchesInLine(searchData, model.getLineContent(lineNumber), lineNumber, 0, resultLen, result, captureMatches, limitResultCount); } // Collect results from last line if (resultLen < limitResultCount) { const text = model.getLineContent(searchRange.endLineNumber).substring(0, searchRange.endColumn - 1); resultLen = this._findMatchesInLine(searchData, text, searchRange.endLineNumber, 0, resultLen, result, captureMatches, limitResultCount); } return result; } private static _findMatchesInLine(searchData: SearchData, text: string, lineNumber: number, deltaOffset: number, resultLen: number, result: FindMatch[], captureMatches: boolean, limitResultCount: number): number { const wordSeparators = searchData.wordSeparators; if (!captureMatches && searchData.simpleSearch) { const searchString = searchData.simpleSearch; const searchStringLen = searchString.length; const textLength = text.length; let lastMatchIndex = -searchStringLen; while ((lastMatchIndex = text.indexOf(searchString, lastMatchIndex + searchStringLen)) !== -1) { if (!wordSeparators || isValidMatch(wordSeparators, text, textLength, lastMatchIndex, searchStringLen)) { result[resultLen++] = new FindMatch(new Range(lineNumber, lastMatchIndex + 1 + deltaOffset, lineNumber, lastMatchIndex + 1 + searchStringLen + deltaOffset), null); if (resultLen >= limitResultCount) { return resultLen; } } } return resultLen; } const searcher = new Searcher(searchData.wordSeparators, searchData.regex); let m: RegExpExecArray | null; // Reset regex to search from the beginning searcher.reset(0); do { m = searcher.next(text); if (m) { result[resultLen++] = createFindMatch(new Range(lineNumber, m.index + 1 + deltaOffset, lineNumber, m.index + 1 + m[0].length + deltaOffset), m, captureMatches); if (resultLen >= limitResultCount) { return resultLen; } } } while (m); return resultLen; } public static findNextMatch(model: TextModel, searchParams: SearchParams, searchStart: Position, captureMatches: boolean): FindMatch | null { const searchData = searchParams.parseSearchRequest(); if (!searchData) { return null; } const searcher = new Searcher(searchData.wordSeparators, searchData.regex); if (searchData.regex.multiline) { return this._doFindNextMatchMultiline(model, searchStart, searcher, captureMatches); } return this._doFindNextMatchLineByLine(model, searchStart, searcher, captureMatches); } private static _doFindNextMatchMultiline(model: TextModel, searchStart: Position, searcher: Searcher, captureMatches: boolean): FindMatch | null { const searchTextStart = new Position(searchStart.lineNumber, 1); const deltaOffset = model.getOffsetAt(searchTextStart); const lineCount = model.getLineCount(); // We always execute multiline search over the lines joined with \n // This makes it that \n will match the EOL for both CRLF and LF models // We compensate for offset errors in `_getMultilineMatchRange` const text = model.getValueInRange(new Range(searchTextStart.lineNumber, searchTextStart.column, lineCount, model.getLineMaxColumn(lineCount)), EndOfLinePreference.LF); const lfCounter = (model.getEOL() === '\r\n' ? new LineFeedCounter(text) : null); searcher.reset(searchStart.column - 1); let m = searcher.next(text); if (m) { return createFindMatch( this._getMultilineMatchRange(model, deltaOffset, text, lfCounter, m.index, m[0]), m, captureMatches ); } if (searchStart.lineNumber !== 1 || searchStart.column !== 1) { // Try again from the top return this._doFindNextMatchMultiline(model, new Position(1, 1), searcher, captureMatches); } return null; } private static _doFindNextMatchLineByLine(model: TextModel, searchStart: Position, searcher: Searcher, captureMatches: boolean): FindMatch | null { const lineCount = model.getLineCount(); const startLineNumber = searchStart.lineNumber; // Look in first line const text = model.getLineContent(startLineNumber); const r = this._findFirstMatchInLine(searcher, text, startLineNumber, searchStart.column, captureMatches); if (r) { return r; } for (let i = 1; i <= lineCount; i++) { const lineIndex = (startLineNumber + i - 1) % lineCount; const text = model.getLineContent(lineIndex + 1); const r = this._findFirstMatchInLine(searcher, text, lineIndex + 1, 1, captureMatches); if (r) { return r; } } return null; } private static _findFirstMatchInLine(searcher: Searcher, text: string, lineNumber: number, fromColumn: number, captureMatches: boolean): FindMatch | null { // Set regex to search from column searcher.reset(fromColumn - 1); const m: RegExpExecArray | null = searcher.next(text); if (m) { return createFindMatch( new Range(lineNumber, m.index + 1, lineNumber, m.index + 1 + m[0].length), m, captureMatches ); } return null; } public static findPreviousMatch(model: TextModel, searchParams: SearchParams, searchStart: Position, captureMatches: boolean): FindMatch | null { const searchData = searchParams.parseSearchRequest(); if (!searchData) { return null; } const searcher = new Searcher(searchData.wordSeparators, searchData.regex); if (searchData.regex.multiline) { return this._doFindPreviousMatchMultiline(model, searchStart, searcher, captureMatches); } return this._doFindPreviousMatchLineByLine(model, searchStart, searcher, captureMatches); } private static _doFindPreviousMatchMultiline(model: TextModel, searchStart: Position, searcher: Searcher, captureMatches: boolean): FindMatch | null { const matches = this._doFindMatchesMultiline(model, new Range(1, 1, searchStart.lineNumber, searchStart.column), searcher, captureMatches, 10 * LIMIT_FIND_COUNT); if (matches.length > 0) { return matches[matches.length - 1]; } const lineCount = model.getLineCount(); if (searchStart.lineNumber !== lineCount || searchStart.column !== model.getLineMaxColumn(lineCount)) { // Try again with all content return this._doFindPreviousMatchMultiline(model, new Position(lineCount, model.getLineMaxColumn(lineCount)), searcher, captureMatches); } return null; } private static _doFindPreviousMatchLineByLine(model: TextModel, searchStart: Position, searcher: Searcher, captureMatches: boolean): FindMatch | null { const lineCount = model.getLineCount(); const startLineNumber = searchStart.lineNumber; // Look in first line const text = model.getLineContent(startLineNumber).substring(0, searchStart.column - 1); const r = this._findLastMatchInLine(searcher, text, startLineNumber, captureMatches); if (r) { return r; } for (let i = 1; i <= lineCount; i++) { const lineIndex = (lineCount + startLineNumber - i - 1) % lineCount; const text = model.getLineContent(lineIndex + 1); const r = this._findLastMatchInLine(searcher, text, lineIndex + 1, captureMatches); if (r) { return r; } } return null; } private static _findLastMatchInLine(searcher: Searcher, text: string, lineNumber: number, captureMatches: boolean): FindMatch | null { let bestResult: FindMatch | null = null; let m: RegExpExecArray | null; searcher.reset(0); while ((m = searcher.next(text))) { bestResult = createFindMatch(new Range(lineNumber, m.index + 1, lineNumber, m.index + 1 + m[0].length), m, captureMatches); } return bestResult; } } function leftIsWordBounday(wordSeparators: WordCharacterClassifier, text: string, textLength: number, matchStartIndex: number, matchLength: number): boolean { if (matchStartIndex === 0) { // Match starts at start of string return true; } const charBefore = text.charCodeAt(matchStartIndex - 1); if (wordSeparators.get(charBefore) !== WordCharacterClass.Regular) { // The character before the match is a word separator return true; } if (charBefore === CharCode.CarriageReturn || charBefore === CharCode.LineFeed) { // The character before the match is line break or carriage return. return true; } if (matchLength > 0) { const firstCharInMatch = text.charCodeAt(matchStartIndex); if (wordSeparators.get(firstCharInMatch) !== WordCharacterClass.Regular) { // The first character inside the match is a word separator return true; } } return false; } function rightIsWordBounday(wordSeparators: WordCharacterClassifier, text: string, textLength: number, matchStartIndex: number, matchLength: number): boolean { if (matchStartIndex + matchLength === textLength) { // Match ends at end of string return true; } const charAfter = text.charCodeAt(matchStartIndex + matchLength); if (wordSeparators.get(charAfter) !== WordCharacterClass.Regular) { // The character after the match is a word separator return true; } if (charAfter === CharCode.CarriageReturn || charAfter === CharCode.LineFeed) { // The character after the match is line break or carriage return. return true; } if (matchLength > 0) { const lastCharInMatch = text.charCodeAt(matchStartIndex + matchLength - 1); if (wordSeparators.get(lastCharInMatch) !== WordCharacterClass.Regular) { // The last character in the match is a word separator return true; } } return false; } export function isValidMatch(wordSeparators: WordCharacterClassifier, text: string, textLength: number, matchStartIndex: number, matchLength: number): boolean { return ( leftIsWordBounday(wordSeparators, text, textLength, matchStartIndex, matchLength) && rightIsWordBounday(wordSeparators, text, textLength, matchStartIndex, matchLength) ); } export class Searcher { public readonly _wordSeparators: WordCharacterClassifier | null; private readonly _searchRegex: RegExp; private _prevMatchStartIndex: number; private _prevMatchLength: number; constructor(wordSeparators: WordCharacterClassifier | null, searchRegex: RegExp,) { this._wordSeparators = wordSeparators; this._searchRegex = searchRegex; this._prevMatchStartIndex = -1; this._prevMatchLength = 0; } public reset(lastIndex: number): void { this._searchRegex.lastIndex = lastIndex; this._prevMatchStartIndex = -1; this._prevMatchLength = 0; } public next(text: string): RegExpExecArray | null { const textLength = text.length; let m: RegExpExecArray | null; do { if (this._prevMatchStartIndex + this._prevMatchLength === textLength) { // Reached the end of the line return null; } m = this._searchRegex.exec(text); if (!m) { return null; } const matchStartIndex = m.index; const matchLength = m[0].length; if (matchStartIndex === this._prevMatchStartIndex && matchLength === this._prevMatchLength) { if (matchLength === 0) { // the search result is an empty string and won't advance `regex.lastIndex`, so `regex.exec` will stuck here // we attempt to recover from that by advancing by two if surrogate pair found and by one otherwise if (strings.getNextCodePoint(text, textLength, this._searchRegex.lastIndex) > 0xFFFF) { this._searchRegex.lastIndex += 2; } else { this._searchRegex.lastIndex += 1; } continue; } // Exit early if the regex matches the same range twice return null; } this._prevMatchStartIndex = matchStartIndex; this._prevMatchLength = matchLength; if (!this._wordSeparators || isValidMatch(this._wordSeparators, text, textLength, matchStartIndex, matchLength)) { return m; } } while (m); return null; } }
src/vs/editor/common/model/textModelSearch.ts
0
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.000288156617898494, 0.0001746151247061789, 0.00016822169709485024, 0.00017283743363805115, 0.000015153623280639295 ]
{ "id": 1, "code_window": [ "\t\t\t} else {\n", "\t\t\t\tpreviewNode = element.shadowRoot.getElementById('preview')!;\n", "\t\t\t}\n", "\n", "\t\t\tconst rendered = markdownIt.render(outputInfo.text());\n", "\t\t\tpreviewNode.innerHTML = rendered;\n", "\t\t},\n", "\t\textendMarkdownIt: (f: (md: typeof markdownIt) => void) => {\n", "\t\t\tf(markdownIt);\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst text = outputInfo.text();\n", "\t\t\tif (text.trim().length === 0) {\n", "\t\t\t\tpreviewNode.innerText = '';\n", "\t\t\t\tpreviewNode.classList.add('emptyMarkdownCell');\n", "\t\t\t} else {\n", "\t\t\t\tpreviewNode.classList.remove('emptyMarkdownCell');\n", "\n", "\t\t\t\tconst rendered = markdownIt.render(text);\n", "\t\t\t\tpreviewNode.innerHTML = rendered;\n", "\t\t\t}\n" ], "file_path": "extensions/markdown-language-features/notebook/index.ts", "type": "replace", "edit_start_line_idx": 155 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Code } from './code'; import { QuickAccess } from './quickaccess'; const activeRowSelector = `.notebook-editor .monaco-list-row.focused`; export class Notebook { constructor( private readonly quickAccess: QuickAccess, private readonly code: Code) { } async openNotebook() { await this.quickAccess.runCommand('vscode-notebook-tests.createNewNotebook'); await this.code.waitForElement(activeRowSelector); await this.focusFirstCell(); await this.waitForActiveCellEditorContents('code()'); } async focusNextCell() { await this.code.dispatchKeybinding('down'); } async focusFirstCell() { await this.quickAccess.runCommand('notebook.focusTop'); } async editCell() { await this.code.dispatchKeybinding('enter'); } async stopEditingCell() { await this.quickAccess.runCommand('notebook.cell.quitEdit'); } async waitForTypeInEditor(text: string): Promise<any> { const editor = `${activeRowSelector} .monaco-editor`; await this.code.waitForElement(editor); const textarea = `${editor} textarea`; await this.code.waitForActiveElement(textarea); await this.code.waitForTypeInEditor(textarea, text); await this._waitForActiveCellEditorContents(c => c.indexOf(text) > -1); } async waitForActiveCellEditorContents(contents: string): Promise<any> { return this._waitForActiveCellEditorContents(str => str === contents); } private async _waitForActiveCellEditorContents(accept: (contents: string) => boolean): Promise<any> { const selector = `${activeRowSelector} .monaco-editor .view-lines`; return this.code.waitForTextContent(selector, undefined, c => accept(c.replace(/\u00a0/g, ' '))); } async waitForMarkdownContents(markdownSelector: string, text: string): Promise<void> { const selector = `${activeRowSelector} .markdown ${markdownSelector}`; await this.code.waitForTextContent(selector, text); } async insertNotebookCell(kind: 'markdown' | 'code'): Promise<void> { if (kind === 'markdown') { await this.quickAccess.runCommand('notebook.cell.insertMarkdownCellBelow'); } else { await this.quickAccess.runCommand('notebook.cell.insertCodeCellBelow'); } } async deleteActiveCell(): Promise<void> { await this.quickAccess.runCommand('notebook.cell.delete'); } async focusInCellOutput(): Promise<void> { await this.quickAccess.runCommand('notebook.cell.focusInOutput'); await this.code.waitForActiveElement('webview, .webview'); } async focusOutCellOutput(): Promise<void> { await this.quickAccess.runCommand('notebook.cell.focusOutOutput'); } async executeActiveCell(): Promise<void> { await this.quickAccess.runCommand('notebook.cell.execute'); } async executeCellAction(selector: string): Promise<void> { await this.code.waitAndClick(selector); } }
test/automation/src/notebook.ts
0
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.00033626958611421287, 0.00018888631893787533, 0.00016823579790070653, 0.0001731172378640622, 0.00004919909770251252 ]
{ "id": 1, "code_window": [ "\t\t\t} else {\n", "\t\t\t\tpreviewNode = element.shadowRoot.getElementById('preview')!;\n", "\t\t\t}\n", "\n", "\t\t\tconst rendered = markdownIt.render(outputInfo.text());\n", "\t\t\tpreviewNode.innerHTML = rendered;\n", "\t\t},\n", "\t\textendMarkdownIt: (f: (md: typeof markdownIt) => void) => {\n", "\t\t\tf(markdownIt);\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst text = outputInfo.text();\n", "\t\t\tif (text.trim().length === 0) {\n", "\t\t\t\tpreviewNode.innerText = '';\n", "\t\t\t\tpreviewNode.classList.add('emptyMarkdownCell');\n", "\t\t\t} else {\n", "\t\t\t\tpreviewNode.classList.remove('emptyMarkdownCell');\n", "\n", "\t\t\t\tconst rendered = markdownIt.render(text);\n", "\t\t\t\tpreviewNode.innerHTML = rendered;\n", "\t\t\t}\n" ], "file_path": "extensions/markdown-language-features/notebook/index.ts", "type": "replace", "edit_start_line_idx": 155 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IMarkerService, IMarker, MarkerSeverity, MarkerTag } from 'vs/platform/markers/common/markers'; import { Disposable, toDisposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { IModelDeltaDecoration, ITextModel, IModelDecorationOptions, TrackedRangeStickiness, OverviewRulerLane, IModelDecoration, MinimapPosition, IModelDecorationMinimapOptions } from 'vs/editor/common/model'; import { ClassName } from 'vs/editor/common/model/intervalTree'; import { themeColorFromId, ThemeColor } from 'vs/platform/theme/common/themeService'; import { overviewRulerWarning, overviewRulerInfo, overviewRulerError } from 'vs/editor/common/view/editorColorRegistry'; import { IModelService } from 'vs/editor/common/services/modelService'; import { Range } from 'vs/editor/common/core/range'; import { IMarkerDecorationsService } from 'vs/editor/common/services/markersDecorationService'; import { Schemas } from 'vs/base/common/network'; import { Emitter, Event } from 'vs/base/common/event'; import { minimapWarning, minimapError } from 'vs/platform/theme/common/colorRegistry'; function MODEL_ID(resource: URI): string { return resource.toString(); } class MarkerDecorations extends Disposable { private readonly _markersData: Map<string, IMarker> = new Map<string, IMarker>(); constructor( readonly model: ITextModel ) { super(); this._register(toDisposable(() => { this.model.deltaDecorations([...this._markersData.keys()], []); this._markersData.clear(); })); } public update(markers: IMarker[], newDecorations: IModelDeltaDecoration[]): boolean { const oldIds = [...this._markersData.keys()]; this._markersData.clear(); const ids = this.model.deltaDecorations(oldIds, newDecorations); for (let index = 0; index < ids.length; index++) { this._markersData.set(ids[index], markers[index]); } return oldIds.length !== 0 || ids.length !== 0; } getMarker(decoration: IModelDecoration): IMarker | undefined { return this._markersData.get(decoration.id); } getMarkers(): [Range, IMarker][] { const res: [Range, IMarker][] = []; this._markersData.forEach((marker, id) => { let range = this.model.getDecorationRange(id); if (range) { res.push([range, marker]); } }); return res; } } export class MarkerDecorationsService extends Disposable implements IMarkerDecorationsService { declare readonly _serviceBrand: undefined; private readonly _onDidChangeMarker = this._register(new Emitter<ITextModel>()); readonly onDidChangeMarker: Event<ITextModel> = this._onDidChangeMarker.event; private readonly _markerDecorations = new Map<string, MarkerDecorations>(); constructor( @IModelService modelService: IModelService, @IMarkerService private readonly _markerService: IMarkerService ) { super(); modelService.getModels().forEach(model => this._onModelAdded(model)); this._register(modelService.onModelAdded(this._onModelAdded, this)); this._register(modelService.onModelRemoved(this._onModelRemoved, this)); this._register(this._markerService.onMarkerChanged(this._handleMarkerChange, this)); } override dispose() { super.dispose(); this._markerDecorations.forEach(value => value.dispose()); this._markerDecorations.clear(); } getMarker(uri: URI, decoration: IModelDecoration): IMarker | null { const markerDecorations = this._markerDecorations.get(MODEL_ID(uri)); return markerDecorations ? (markerDecorations.getMarker(decoration) || null) : null; } getLiveMarkers(uri: URI): [Range, IMarker][] { const markerDecorations = this._markerDecorations.get(MODEL_ID(uri)); return markerDecorations ? markerDecorations.getMarkers() : []; } private _handleMarkerChange(changedResources: readonly URI[]): void { changedResources.forEach((resource) => { const markerDecorations = this._markerDecorations.get(MODEL_ID(resource)); if (markerDecorations) { this._updateDecorations(markerDecorations); } }); } private _onModelAdded(model: ITextModel): void { const markerDecorations = new MarkerDecorations(model); this._markerDecorations.set(MODEL_ID(model.uri), markerDecorations); this._updateDecorations(markerDecorations); } private _onModelRemoved(model: ITextModel): void { const markerDecorations = this._markerDecorations.get(MODEL_ID(model.uri)); if (markerDecorations) { markerDecorations.dispose(); this._markerDecorations.delete(MODEL_ID(model.uri)); } // clean up markers for internal, transient models if (model.uri.scheme === Schemas.inMemory || model.uri.scheme === Schemas.internal || model.uri.scheme === Schemas.vscode) { if (this._markerService) { this._markerService.read({ resource: model.uri }).map(marker => marker.owner).forEach(owner => this._markerService.remove(owner, [model.uri])); } } } private _updateDecorations(markerDecorations: MarkerDecorations): void { // Limit to the first 500 errors/warnings const markers = this._markerService.read({ resource: markerDecorations.model.uri, take: 500 }); let newModelDecorations: IModelDeltaDecoration[] = markers.map((marker) => { return { range: this._createDecorationRange(markerDecorations.model, marker), options: this._createDecorationOption(marker) }; }); if (markerDecorations.update(markers, newModelDecorations)) { this._onDidChangeMarker.fire(markerDecorations.model); } } private _createDecorationRange(model: ITextModel, rawMarker: IMarker): Range { let ret = Range.lift(rawMarker); if (rawMarker.severity === MarkerSeverity.Hint && !this._hasMarkerTag(rawMarker, MarkerTag.Unnecessary) && !this._hasMarkerTag(rawMarker, MarkerTag.Deprecated)) { // * never render hints on multiple lines // * make enough space for three dots ret = ret.setEndPosition(ret.startLineNumber, ret.startColumn + 2); } ret = model.validateRange(ret); if (ret.isEmpty()) { let word = model.getWordAtPosition(ret.getStartPosition()); if (word) { ret = new Range(ret.startLineNumber, word.startColumn, ret.endLineNumber, word.endColumn); } else { let maxColumn = model.getLineLastNonWhitespaceColumn(ret.startLineNumber) || model.getLineMaxColumn(ret.startLineNumber); if (maxColumn === 1) { // empty line // console.warn('marker on empty line:', marker); } else if (ret.endColumn >= maxColumn) { // behind eol ret = new Range(ret.startLineNumber, maxColumn - 1, ret.endLineNumber, maxColumn); } else { // extend marker to width = 1 ret = new Range(ret.startLineNumber, ret.startColumn, ret.endLineNumber, ret.endColumn + 1); } } } else if (rawMarker.endColumn === Number.MAX_VALUE && rawMarker.startColumn === 1 && ret.startLineNumber === ret.endLineNumber) { let minColumn = model.getLineFirstNonWhitespaceColumn(rawMarker.startLineNumber); if (minColumn < ret.endColumn) { ret = new Range(ret.startLineNumber, minColumn, ret.endLineNumber, ret.endColumn); rawMarker.startColumn = minColumn; } } return ret; } private _createDecorationOption(marker: IMarker): IModelDecorationOptions { let className: string | undefined; let color: ThemeColor | undefined = undefined; let zIndex: number; let inlineClassName: string | undefined = undefined; let minimap: IModelDecorationMinimapOptions | undefined; switch (marker.severity) { case MarkerSeverity.Hint: if (this._hasMarkerTag(marker, MarkerTag.Deprecated)) { className = undefined; } else if (this._hasMarkerTag(marker, MarkerTag.Unnecessary)) { className = ClassName.EditorUnnecessaryDecoration; } else { className = ClassName.EditorHintDecoration; } zIndex = 0; break; case MarkerSeverity.Warning: className = ClassName.EditorWarningDecoration; color = themeColorFromId(overviewRulerWarning); zIndex = 20; minimap = { color: themeColorFromId(minimapWarning), position: MinimapPosition.Inline }; break; case MarkerSeverity.Info: className = ClassName.EditorInfoDecoration; color = themeColorFromId(overviewRulerInfo); zIndex = 10; break; case MarkerSeverity.Error: default: className = ClassName.EditorErrorDecoration; color = themeColorFromId(overviewRulerError); zIndex = 30; minimap = { color: themeColorFromId(minimapError), position: MinimapPosition.Inline }; break; } if (marker.tags) { if (marker.tags.indexOf(MarkerTag.Unnecessary) !== -1) { inlineClassName = ClassName.EditorUnnecessaryInlineDecoration; } if (marker.tags.indexOf(MarkerTag.Deprecated) !== -1) { inlineClassName = ClassName.EditorDeprecatedInlineDecoration; } } return { description: 'marker-decoration', stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges, className, showIfCollapsed: true, overviewRuler: { color, position: OverviewRulerLane.Right }, minimap, zIndex, inlineClassName, }; } private _hasMarkerTag(marker: IMarker, tag: MarkerTag): boolean { if (marker.tags) { return marker.tags.indexOf(tag) >= 0; } return false; } }
src/vs/editor/common/services/markerDecorationsServiceImpl.ts
0
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.000754573498852551, 0.00019360218720976263, 0.00016603624681010842, 0.00017110933549702168, 0.00011014658957719803 ]
{ "id": 2, "code_window": [ "\t\t\t'notebook-run-gutter': `${this.options.runGutter}px`,\n", "\t\t\t'notebook-preivew-node-padding': `${this.options.previewNodePadding}px`,\n", "\t\t\t'notebook-markdown-left-margin': `${this.options.markdownLeftMargin}px`,\n", "\t\t\t'notebook-output-node-left-padding': `${this.options.outputNodeLeftPadding}px`,\n", "\t\t\t'notebook-markdown-min-height': `${this.options.previewNodePadding * 2}px`,\n", "\t\t\t'notebook-cell-output-font-size': `${this.options.fontSize}px`\n", "\t\t};\n", "\t}\n", "\n", "\tprivate generateContent(coreDependencies: string, baseUrl: string) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t'notebook-cell-output-font-size': `${this.options.fontSize}px`,\n", "\t\t\t'notebook-cell-markup-empty-content': nls.localize('notebook.emptyMarkdownPlaceholder', \"Empty markdown cell, double click or press enter to edit.\"),\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView.ts", "type": "replace", "edit_start_line_idx": 166 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import type { Event } from 'vs/base/common/event'; import type { IDisposable } from 'vs/base/common/lifecycle'; import { RenderOutputType } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import type * as webviewMessages from 'vs/workbench/contrib/notebook/browser/view/renderers/webviewMessages'; // !! IMPORTANT !! everything must be in-line within the webviewPreloads // function. Imports are not allowed. This is stringified and injected into // the webview. declare module globalThis { const acquireVsCodeApi: () => ({ getState(): { [key: string]: unknown; }; setState(data: { [key: string]: unknown; }): void; postMessage: (msg: unknown) => void; }); } declare class ResizeObserver { constructor(onChange: (entries: { target: HTMLElement, contentRect?: ClientRect; }[]) => void); observe(element: Element): void; disconnect(): void; } type Listener<T> = { fn: (evt: T) => void; thisArg: unknown; }; interface EmitterLike<T> { fire(data: T): void; event: Event<T>; } interface PreloadStyles { readonly outputNodePadding: number; readonly outputNodeLeftPadding: number; } export interface PreloadOptions { dragAndDropEnabled: boolean; } declare function __import(path: string): Promise<any>; async function webviewPreloads(style: PreloadStyles, options: PreloadOptions, rendererData: readonly RendererMetadata[]) { let currentOptions = options; const acquireVsCodeApi = globalThis.acquireVsCodeApi; const vscode = acquireVsCodeApi(); delete (globalThis as any).acquireVsCodeApi; const handleInnerClick = (event: MouseEvent) => { if (!event || !event.view || !event.view.document) { return; } for (const node of event.composedPath()) { if (node instanceof HTMLAnchorElement && node.href) { if (node.href.startsWith('blob:')) { handleBlobUrlClick(node.href, node.download); } else if (node.href.startsWith('data:')) { handleDataUrl(node.href, node.download); } event.preventDefault(); return; } } }; const handleDataUrl = async (data: string | ArrayBuffer | null, downloadName: string) => { postNotebookMessage<webviewMessages.IClickedDataUrlMessage>('clicked-data-url', { data, downloadName }); }; const handleBlobUrlClick = async (url: string, downloadName: string) => { try { const response = await fetch(url); const blob = await response.blob(); const reader = new FileReader(); reader.addEventListener('load', () => { handleDataUrl(reader.result, downloadName); }); reader.readAsDataURL(blob); } catch (e) { console.error(e.message); } }; document.body.addEventListener('click', handleInnerClick); const preservedScriptAttributes: (keyof HTMLScriptElement)[] = [ 'type', 'src', 'nonce', 'noModule', 'async', ]; // derived from https://github.com/jquery/jquery/blob/d0ce00cdfa680f1f0c38460bc51ea14079ae8b07/src/core/DOMEval.js const domEval = (container: Element) => { const arr = Array.from(container.getElementsByTagName('script')); for (let n = 0; n < arr.length; n++) { const node = arr[n]; const scriptTag = document.createElement('script'); const trustedScript = ttPolicy?.createScript(node.innerText) ?? node.innerText; scriptTag.text = trustedScript as string; for (const key of preservedScriptAttributes) { const val = node[key] || node.getAttribute && node.getAttribute(key); if (val) { scriptTag.setAttribute(key, val as any); } } // TODO@connor4312: should script with src not be removed? container.appendChild(scriptTag).parentNode!.removeChild(scriptTag); } }; async function loadScriptSource(url: string, originalUri = url): Promise<string> { const res = await fetch(url); const text = await res.text(); if (!res.ok) { throw new Error(`Unexpected ${res.status} requesting ${originalUri}: ${text || res.statusText}`); } return text; } interface RendererContext { getState<T>(): T | undefined; setState<T>(newState: T): void; getRenderer(id: string): Promise<any | undefined>; postMessage?(message: unknown): void; onDidReceiveMessage?: Event<unknown>; } interface ScriptModule { activate(ctx?: RendererContext): Promise<RendererApi | undefined | any> | RendererApi | undefined | any; } const invokeSourceWithGlobals = (functionSrc: string, globals: { [name: string]: unknown }) => { const args = Object.entries(globals); return new Function(...args.map(([k]) => k), functionSrc)(...args.map(([, v]) => v)); }; const runPreload = async (url: string, originalUri: string): Promise<ScriptModule> => { const text = await loadScriptSource(url, originalUri); return { activate: () => { try { return invokeSourceWithGlobals(text, { ...kernelPreloadGlobals, scriptUrl: url }); } catch (e) { console.error(e); throw e; } } }; }; const runRenderScript = async (url: string, rendererId: string): Promise<ScriptModule> => { const text = await loadScriptSource(url); // TODO: Support both the new module based renderers and the old style global renderers const isModule = !text.includes('acquireNotebookRendererApi'); if (isModule) { return __import(url); } else { return createBackCompatModule(rendererId, url, text); } }; const createBackCompatModule = (rendererId: string, scriptUrl: string, scriptText: string): ScriptModule => ({ activate: (): RendererApi => { const onDidCreateOutput = createEmitter<IOutputItem>(); const onWillDestroyOutput = createEmitter<undefined | IDestroyCellInfo>(); const globals = { scriptUrl, acquireNotebookRendererApi: <T>(): GlobalNotebookRendererApi<T> => ({ onDidCreateOutput: onDidCreateOutput.event, onWillDestroyOutput: onWillDestroyOutput.event, setState: newState => vscode.setState({ ...vscode.getState(), [rendererId]: newState }), getState: () => { const state = vscode.getState(); return typeof state === 'object' && state ? state[rendererId] as T : undefined; }, }), }; invokeSourceWithGlobals(scriptText, globals); return { renderOutputItem(outputItem) { onDidCreateOutput.fire({ ...outputItem, outputId: outputItem.id }); }, disposeOutputItem(id) { onWillDestroyOutput.fire(id ? { outputId: id } : undefined); } }; } }); const dimensionUpdater = new class { private readonly pending = new Map<string, webviewMessages.DimensionUpdate>(); update(id: string, height: number, options: { init?: boolean; isOutput?: boolean }) { if (!this.pending.size) { setTimeout(() => { this.updateImmediately(); }, 0); } this.pending.set(id, { id, height, ...options, }); } updateImmediately() { if (!this.pending.size) { return; } postNotebookMessage<webviewMessages.IDimensionMessage>('dimension', { updates: Array.from(this.pending.values()) }); this.pending.clear(); } }; const resizeObserver = new class { private readonly _observer: ResizeObserver; private readonly _observedElements = new WeakMap<Element, { id: string, output: boolean }>(); constructor() { this._observer = new ResizeObserver(entries => { for (const entry of entries) { if (!document.body.contains(entry.target)) { continue; } const observedElementInfo = this._observedElements.get(entry.target); if (!observedElementInfo) { continue; } if (entry.target.id === observedElementInfo.id && entry.contentRect) { if (observedElementInfo.output) { let height = 0; if (entry.contentRect.height !== 0) { entry.target.style.padding = `${style.outputNodePadding}px ${style.outputNodePadding}px ${style.outputNodePadding}px ${style.outputNodeLeftPadding}px`; height = entry.contentRect.height + style.outputNodePadding * 2; } else { entry.target.style.padding = `0px`; } dimensionUpdater.update(observedElementInfo.id, height, { isOutput: true }); } else { dimensionUpdater.update(observedElementInfo.id, entry.target.clientHeight, { isOutput: false }); } } } }); } public observe(container: Element, id: string, output: boolean) { if (this._observedElements.has(container)) { return; } this._observedElements.set(container, { id, output }); this._observer.observe(container); } }; function scrollWillGoToParent(event: WheelEvent) { for (let node = event.target as Node | null; node; node = node.parentNode) { if (!(node instanceof Element) || node.id === 'container' || node.classList.contains('cell_container') || node.classList.contains('output_container')) { return false; } if (event.deltaY < 0 && node.scrollTop > 0) { return true; } if (event.deltaY > 0 && node.scrollTop + node.clientHeight < node.scrollHeight) { return true; } } return false; } const handleWheel = (event: WheelEvent) => { if (event.defaultPrevented || scrollWillGoToParent(event)) { return; } postNotebookMessage<webviewMessages.IWheelMessage>('did-scroll-wheel', { payload: { deltaMode: event.deltaMode, deltaX: event.deltaX, deltaY: event.deltaY, deltaZ: event.deltaZ, detail: event.detail, type: event.type } }); }; function focusFirstFocusableInCell(cellId: string) { const cellOutputContainer = document.getElementById(cellId); if (cellOutputContainer) { const focusableElement = cellOutputContainer.querySelector('[tabindex="0"], [href], button, input, option, select, textarea') as HTMLElement | null; focusableElement?.focus(); } } function createFocusSink(cellId: string, outputId: string, focusNext?: boolean) { const element = document.createElement('div'); element.tabIndex = 0; element.addEventListener('focus', () => { postNotebookMessage<webviewMessages.IBlurOutputMessage>('focus-editor', { id: outputId, focusNext }); }); return element; } function addMouseoverListeners(element: HTMLElement, outputId: string): void { element.addEventListener('mouseenter', () => { postNotebookMessage<webviewMessages.IMouseEnterMessage>('mouseenter', { id: outputId, }); }); element.addEventListener('mouseleave', () => { postNotebookMessage<webviewMessages.IMouseLeaveMessage>('mouseleave', { id: outputId, }); }); } function isAncestor(testChild: Node | null, testAncestor: Node | null): boolean { while (testChild) { if (testChild === testAncestor) { return true; } testChild = testChild.parentNode; } return false; } class FocusTracker { private _outputId: string; private _hasFocus: boolean = false; private _loosingFocus: boolean = false; private _element: HTMLElement | Window; constructor(element: HTMLElement | Window, outputId: string) { this._element = element; this._outputId = outputId; this._hasFocus = isAncestor(document.activeElement, <HTMLElement>element); this._loosingFocus = false; element.addEventListener('focus', this._onFocus.bind(this), true); element.addEventListener('blur', this._onBlur.bind(this), true); } private _onFocus() { this._loosingFocus = false; if (!this._hasFocus) { this._hasFocus = true; postNotebookMessage<webviewMessages.IOutputFocusMessage>('outputFocus', { id: this._outputId, }); } } private _onBlur() { if (this._hasFocus) { this._loosingFocus = true; window.setTimeout(() => { if (this._loosingFocus) { this._loosingFocus = false; this._hasFocus = false; postNotebookMessage<webviewMessages.IOutputBlurMessage>('outputBlur', { id: this._outputId, }); } }, 0); } } dispose() { if (this._element) { this._element.removeEventListener('focus', this._onFocus, true); this._element.removeEventListener('blur', this._onBlur, true); } } } const focusTrackers = new Map<string, FocusTracker>(); function addFocusTracker(element: HTMLElement, outputId: string): void { if (focusTrackers.has(outputId)) { focusTrackers.get(outputId)?.dispose(); } focusTrackers.set(outputId, new FocusTracker(element, outputId)); } function createEmitter<T>(listenerChange: (listeners: Set<Listener<T>>) => void = () => undefined): EmitterLike<T> { const listeners = new Set<Listener<T>>(); return { fire(data) { for (const listener of [...listeners]) { listener.fn.call(listener.thisArg, data); } }, event(fn, thisArg, disposables) { const listenerObj = { fn, thisArg }; const disposable: IDisposable = { dispose: () => { listeners.delete(listenerObj); listenerChange(listeners); }, }; listeners.add(listenerObj); listenerChange(listeners); if (disposables instanceof Array) { disposables.push(disposable); } else if (disposables) { disposables.add(disposable); } return disposable; }, }; } function showPreloadErrors(outputNode: HTMLElement, ...errors: readonly Error[]) { outputNode.innerText = `Error loading preloads:`; const errList = document.createElement('ul'); for (const result of errors) { console.error(result); const item = document.createElement('li'); item.innerText = result.message; errList.appendChild(item); } outputNode.appendChild(errList); } interface IOutputItem { readonly id: string; /** @deprecated */ readonly outputId?: string; /** @deprecated */ readonly element: HTMLElement; readonly mime: string; metadata: unknown; metadata2: unknown; text(): string; json(): any; data(): Uint8Array; blob(): Blob; /** @deprecated */ bytes(): Uint8Array; } interface IDestroyCellInfo { outputId: string; } const onDidReceiveKernelMessage = createEmitter<unknown>(); /** @deprecated */ interface GlobalNotebookRendererApi<T> { setState: (newState: T) => void; getState(): T | undefined; readonly onWillDestroyOutput: Event<undefined | IDestroyCellInfo>; readonly onDidCreateOutput: Event<IOutputItem>; } const kernelPreloadGlobals = { acquireVsCodeApi, onDidReceiveKernelMessage: onDidReceiveKernelMessage.event, postKernelMessage: (data: unknown) => postNotebookMessage('customKernelMessage', { message: data }), }; const ttPolicy = window.trustedTypes?.createPolicy('notebookRenderer', { createHTML: value => value, createScript: value => value, }); window.addEventListener('wheel', handleWheel); window.addEventListener('message', async rawEvent => { const event = rawEvent as ({ data: webviewMessages.ToWebviewMessage; }); switch (event.data.type) { case 'initializeMarkup': { await ensureMarkdownPreviewCells(event.data.cells); dimensionUpdater.updateImmediately(); postNotebookMessage('initializedMarkdownPreview', {}); } break; case 'createMarkupCell': ensureMarkdownPreviewCells([event.data.cell]); break; case 'showMarkupCell': { const data = event.data; const cellContainer = document.getElementById(data.id); if (cellContainer) { cellContainer.style.visibility = 'visible'; cellContainer.style.top = `${data.top}px`; updateMarkdownPreview(cellContainer, data.id, data.content); } } break; case 'hideMarkupCells': { for (const id of event.data.ids) { const cellContainer = document.getElementById(id); if (cellContainer) { cellContainer.style.visibility = 'hidden'; } } } break; case 'unhideMarkupCells': { for (const id of event.data.ids) { const cellContainer = document.getElementById(id); if (cellContainer) { cellContainer.style.visibility = 'visible'; updateMarkdownPreview(cellContainer, id, undefined); } } } break; case 'deleteMarkupCell': { for (const id of event.data.ids) { const cellContainer = document.getElementById(id); cellContainer?.remove(); } } break; case 'updateSelectedMarkupCells': { const selectedCellIds = new Set<string>(event.data.selectedCellIds); for (const oldSelected of document.querySelectorAll('.preview.selected')) { const id = oldSelected.id; if (!selectedCellIds.has(id)) { oldSelected.classList.remove('selected'); } } for (const newSelected of selectedCellIds) { const previewContainer = document.getElementById(newSelected); if (previewContainer) { previewContainer.classList.add('selected'); } } } break; case 'html': { const data = event.data; outputs.enqueue(event.data.outputId, async (state) => { const preloadsAndErrors = await Promise.all<unknown>([ data.rendererId ? renderers.load(data.rendererId) : undefined, ...data.requiredPreloads.map(p => kernelPreloads.waitFor(p.uri)), ].map(p => p?.catch(err => err))); if (state.cancelled) { return; } let cellOutputContainer = document.getElementById(data.cellId); const outputId = data.outputId; if (!cellOutputContainer) { const container = document.getElementById('container')!; const upperWrapperElement = createFocusSink(data.cellId, outputId); container.appendChild(upperWrapperElement); const newElement = document.createElement('div'); newElement.id = data.cellId; newElement.classList.add('cell_container'); container.appendChild(newElement); cellOutputContainer = newElement; const lowerWrapperElement = createFocusSink(data.cellId, outputId, true); container.appendChild(lowerWrapperElement); } cellOutputContainer.style.position = 'absolute'; cellOutputContainer.style.top = data.cellTop + 'px'; const outputContainer = document.createElement('div'); outputContainer.classList.add('output_container'); outputContainer.style.position = 'absolute'; outputContainer.style.overflow = 'hidden'; outputContainer.style.maxHeight = '0px'; outputContainer.style.top = `${data.outputOffset}px`; const outputNode = document.createElement('div'); outputNode.classList.add('output'); outputNode.style.position = 'absolute'; outputNode.style.top = `0px`; outputNode.style.left = data.left + 'px'; // outputNode.style.width = 'calc(100% - ' + data.left + 'px)'; // outputNode.style.minHeight = '32px'; outputNode.style.padding = '0px'; outputNode.id = outputId; addMouseoverListeners(outputNode, outputId); addFocusTracker(outputNode, outputId); const content = data.content; if (content.type === RenderOutputType.Html) { const trustedHtml = ttPolicy?.createHTML(content.htmlContent) ?? content.htmlContent; outputNode.innerHTML = trustedHtml as string; domEval(outputNode); } else if (preloadsAndErrors.some(e => e instanceof Error)) { const errors = preloadsAndErrors.filter((e): e is Error => e instanceof Error); showPreloadErrors(outputNode, ...errors); } else { const rendererApi = preloadsAndErrors[0] as RendererApi; try { rendererApi.renderOutputItem({ id: outputId, element: outputNode, mime: content.mimeType, metadata: content.metadata, metadata2: content.metadata2, data() { return content.valueBytes; }, bytes() { return this.data(); }, text() { return new TextDecoder().decode(content.valueBytes); }, json() { return JSON.parse(this.text()); }, blob() { return new Blob([content.valueBytes], { type: content.mimeType }); } }, outputNode); } catch (e) { showPreloadErrors(outputNode, e); } } cellOutputContainer.appendChild(outputContainer); outputContainer.appendChild(outputNode); resizeObserver.observe(outputNode, outputId, true); if (content.type === RenderOutputType.Html) { domEval(outputNode); } const clientHeight = outputNode.clientHeight; const cps = document.defaultView!.getComputedStyle(outputNode); if (clientHeight !== 0 && cps.padding === '0px') { // we set padding to zero if the output height is zero (then we can have a zero-height output DOM node) // thus we need to ensure the padding is accounted when updating the init height of the output dimensionUpdater.update(outputId, clientHeight + style.outputNodePadding * 2, { isOutput: true, init: true, }); outputNode.style.padding = `${style.outputNodePadding}px ${style.outputNodePadding}px ${style.outputNodePadding}px ${style.outputNodeLeftPadding}px`; } else { dimensionUpdater.update(outputId, outputNode.clientHeight, { isOutput: true, init: true, }); } // don't hide until after this step so that the height is right cellOutputContainer.style.visibility = data.initiallyHidden ? 'hidden' : 'visible'; }); break; } case 'view-scroll': { // const date = new Date(); // console.log('----- will scroll ---- ', date.getMinutes() + ':' + date.getSeconds() + ':' + date.getMilliseconds()); for (const request of event.data.widgets) { const widget = document.getElementById(request.outputId); if (widget) { widget.parentElement!.parentElement!.style.top = `${request.cellTop}px`; widget.parentElement!.style.top = `${request.outputOffset}px`; if (request.forceDisplay) { widget.parentElement!.parentElement!.style.visibility = 'visible'; } } } for (const cell of event.data.markdownPreviews) { const container = document.getElementById(cell.id); if (container) { container.style.top = `${cell.top}px`; } } break; } case 'clear': renderers.clearAll(); document.getElementById('container')!.innerText = ''; focusTrackers.forEach(ft => { ft.dispose(); }); focusTrackers.clear(); break; case 'clearOutput': { const output = document.getElementById(event.data.outputId); const { rendererId, outputId } = event.data; outputs.cancelOutput(outputId); if (output && output.parentNode) { if (rendererId) { renderers.clearOutput(rendererId, outputId); } output.parentNode.removeChild(output); } break; } case 'hideOutput': { const { outputId } = event.data; outputs.enqueue(event.data.outputId, () => { const container = document.getElementById(outputId)?.parentElement?.parentElement; if (container) { container.style.visibility = 'hidden'; } }); break; } case 'showOutput': { const { outputId, cellTop: top } = event.data; outputs.enqueue(event.data.outputId, () => { const output = document.getElementById(outputId); if (output) { output.parentElement!.parentElement!.style.visibility = 'visible'; output.parentElement!.parentElement!.style.top = top + 'px'; dimensionUpdater.update(outputId, output.clientHeight, { isOutput: true, }); } }); break; } case 'ack-dimension': { const { outputId, height } = event.data; const output = document.getElementById(outputId); if (output) { output.parentElement!.style.maxHeight = `${height}px`; output.parentElement!.style.height = `${height}px`; } break; } case 'preload': const resources = event.data.resources; for (const { uri, originalUri } of resources) { kernelPreloads.load(uri, originalUri); } break; case 'focus-output': focusFirstFocusableInCell(event.data.cellId); break; case 'decorations': { const outputContainer = document.getElementById(event.data.cellId); outputContainer?.classList.add(...event.data.addedClassNames); outputContainer?.classList.remove(...event.data.removedClassNames); } break; case 'customKernelMessage': onDidReceiveKernelMessage.fire(event.data.message); break; case 'customRendererMessage': renderers.getRenderer(event.data.rendererId)?.receiveMessage(event.data.message); break; case 'notebookStyles': const documentStyle = document.documentElement.style; for (let i = documentStyle.length - 1; i >= 0; i--) { const property = documentStyle[i]; // Don't remove properties that the webview might have added separately if (property && property.startsWith('--notebook-')) { documentStyle.removeProperty(property); } } // Re-add new properties for (const variable of Object.keys(event.data.styles)) { documentStyle.setProperty(`--${variable}`, event.data.styles[variable]); } break; case 'notebookOptions': currentOptions = event.data.options; // Update markdown previews for (const markdownContainer of document.querySelectorAll('.preview')) { setMarkdownContainerDraggable(markdownContainer, currentOptions.dragAndDropEnabled); } break; } }); interface RendererApi { renderOutputItem: (outputItem: IOutputItem, element: HTMLElement) => void; disposeOutputItem?: (id?: string) => void; } class Renderer { constructor( public readonly data: RendererMetadata, private readonly loadExtension: (id: string) => Promise<void>, ) { } private _onMessageEvent = createEmitter(); private _loadPromise?: Promise<RendererApi | undefined>; private _api: RendererApi | undefined; public get api() { return this._api; } public load(): Promise<RendererApi | undefined> { if (!this._loadPromise) { this._loadPromise = this._load(); } return this._loadPromise; } public receiveMessage(message: unknown) { this._onMessageEvent.fire(message); } private createRendererContext(): RendererContext { const { id, messaging } = this.data; const context: RendererContext = { setState: newState => vscode.setState({ ...vscode.getState(), [id]: newState }), getState: <T>() => { const state = vscode.getState(); return typeof state === 'object' && state ? state[id] as T : undefined; }, // TODO: This is async so that we can return a promise to the API in the future. // Currently the API is always resolved before we call `createRendererContext`. getRenderer: async (id: string) => renderers.getRenderer(id)?.api, }; if (messaging) { context.onDidReceiveMessage = this._onMessageEvent.event; context.postMessage = message => postNotebookMessage('customRendererMessage', { rendererId: id, message }); } return context; } /** Inner function cached in the _loadPromise(). */ private async _load(): Promise<RendererApi | undefined> { const module = await runRenderScript(this.data.entrypoint, this.data.id); if (!module) { return; } const api = await module.activate(this.createRendererContext()); this._api = api; // Squash any errors extends errors. They won't prevent the renderer // itself from working, so just log them. await Promise.all(rendererData .filter(d => d.extends === this.data.id) .map(d => this.loadExtension(d.id).catch(console.error)), ); return api; } } const kernelPreloads = new class { private readonly preloads = new Map<string /* uri */, Promise<unknown>>(); /** * Returns a promise that resolves when the given preload is activated. */ public waitFor(uri: string) { return this.preloads.get(uri) || Promise.resolve(new Error(`Preload not ready: ${uri}`)); } /** * Loads a preload. * @param uri URI to load from * @param originalUri URI to show in an error message if the preload is invalid. */ public load(uri: string, originalUri: string) { const promise = Promise.all([ runPreload(uri, originalUri), this.waitForAllCurrent(), ]).then(([module]) => module.activate()); this.preloads.set(uri, promise); return promise; } /** * Returns a promise that waits for all currently-registered preloads to * activate before resolving. */ private waitForAllCurrent() { return Promise.all([...this.preloads.values()].map(p => p.catch(err => err))); } }; const outputs = new class { private outputs = new Map<string, { cancelled: boolean; queue: Promise<unknown> }>(); /** * Pushes the action onto the list of actions for the given output ID, * ensuring that it's run in-order. */ public enqueue(outputId: string, action: (record: { cancelled: boolean }) => unknown) { const record = this.outputs.get(outputId); if (!record) { this.outputs.set(outputId, { cancelled: false, queue: new Promise(r => r(action({ cancelled: false }))) }); } else { record.queue = record.queue.then(r => !record.cancelled && action(record)); } } /** * Cancels the rendering of all outputs. */ public cancelAll() { for (const record of this.outputs.values()) { record.cancelled = true; } this.outputs.clear(); } /** * Cancels any ongoing rendering out an output. */ public cancelOutput(outputId: string) { const output = this.outputs.get(outputId); if (output) { output.cancelled = true; this.outputs.delete(outputId); } } }; const renderers = new class { private readonly _renderers = new Map</* id */ string, Renderer>(); constructor() { for (const renderer of rendererData) { this._renderers.set(renderer.id, new Renderer(renderer, async (extensionId) => { const ext = this._renderers.get(extensionId); if (!ext) { throw new Error(`Could not find extending renderer: ${extensionId}`); } await ext.load(); })); } } public getRenderer(id: string) { return this._renderers.get(id); } public async load(id: string) { const renderer = this._renderers.get(id); if (!renderer) { throw new Error('Could not find renderer'); } return renderer.load(); } public clearAll() { outputs.cancelAll(); for (const renderer of this._renderers.values()) { renderer.api?.disposeOutputItem?.(); } } public clearOutput(rendererId: string, outputId: string) { outputs.cancelOutput(outputId); this._renderers.get(rendererId)?.api?.disposeOutputItem?.(outputId); } public async render(info: IOutputItem, element: HTMLElement) { const renderers = Array.from(this._renderers.values()) .filter(renderer => renderer.data.mimeTypes.includes(info.mime) && !renderer.data.extends); if (!renderers.length) { throw new Error('Could not find renderer'); } await Promise.all(renderers.map(x => x.load())); renderers[0].api?.renderOutputItem(info, element); } }(); vscode.postMessage({ __vscode_notebook_message: true, type: 'initialized' }); function setMarkdownContainerDraggable(element: Element, isDraggable: boolean) { if (isDraggable) { element.classList.add('draggable'); element.setAttribute('draggable', 'true'); } else { element.classList.remove('draggable'); element.removeAttribute('draggable'); } } async function createMarkdownPreview(cellId: string, content: string, top: number): Promise<HTMLElement> { const container = document.getElementById('container')!; const cellContainer = document.createElement('div'); const existing = document.getElementById(cellId); if (existing) { console.error(`Trying to create markdown preview that already exists: ${cellId}`); return existing; } cellContainer.id = cellId; cellContainer.classList.add('preview'); cellContainer.style.position = 'absolute'; cellContainer.style.top = top + 'px'; container.appendChild(cellContainer); cellContainer.addEventListener('dblclick', () => { postNotebookMessage<webviewMessages.IToggleMarkdownPreviewMessage>('toggleMarkdownPreview', { cellId }); }); cellContainer.addEventListener('click', e => { postNotebookMessage<webviewMessages.IClickMarkdownPreviewMessage>('clickMarkdownPreview', { cellId, altKey: e.altKey, ctrlKey: e.ctrlKey, metaKey: e.metaKey, shiftKey: e.shiftKey, }); }); cellContainer.addEventListener('contextmenu', e => { postNotebookMessage<webviewMessages.IContextMenuMarkdownPreviewMessage>('contextMenuMarkdownPreview', { cellId, clientX: e.clientX, clientY: e.clientY, }); }); cellContainer.addEventListener('mouseenter', () => { postNotebookMessage<webviewMessages.IMouseEnterMarkdownPreviewMessage>('mouseEnterMarkdownPreview', { cellId }); }); cellContainer.addEventListener('mouseleave', () => { postNotebookMessage<webviewMessages.IMouseLeaveMarkdownPreviewMessage>('mouseLeaveMarkdownPreview', { cellId }); }); setMarkdownContainerDraggable(cellContainer, currentOptions.dragAndDropEnabled); cellContainer.addEventListener('dragstart', e => { markdownPreviewDragManager.startDrag(e, cellId); }); cellContainer.addEventListener('drag', e => { markdownPreviewDragManager.updateDrag(e, cellId); }); cellContainer.addEventListener('dragend', e => { markdownPreviewDragManager.endDrag(e, cellId); }); await updateMarkdownPreview(cellContainer, cellId, content); resizeObserver.observe(cellContainer, cellId, false); return cellContainer; } async function ensureMarkdownPreviewCells(update: readonly webviewMessages.IMarkdownCellInitialization[]): Promise<void> { await Promise.all(update.map(async cell => { let container = document.getElementById(cell.cellId); if (container) { await updateMarkdownPreview(container, cell.cellId, cell.content); } else { container = await createMarkdownPreview(cell.cellId, cell.content, cell.offset); } container.style.visibility = cell.visible ? 'visible' : 'hidden'; })); } function postNotebookMessage<T extends webviewMessages.FromWebviewMessage>( type: T['type'], properties: Omit<T, '__vscode_notebook_message' | 'type'> ) { vscode.postMessage({ __vscode_notebook_message: true, type, ...properties }); } let hasPostedRenderedMathTelemetry = false; const unsupportedKatexTermsRegex = /(\\(?:abovewithdelims|array|Arrowvert|arrowvert|atopwithdelims|bbox|bracevert|buildrel|cancelto|cases|class|cssId|ddddot|dddot|DeclareMathOperator|definecolor|displaylines|enclose|eqalign|eqalignno|eqref|hfil|hfill|idotsint|iiiint|label|leftarrowtail|leftroot|leqalignno|lower|mathtip|matrix|mbox|mit|mmlToken|moveleft|moveright|mspace|newenvironment|Newextarrow|notag|oldstyle|overparen|overwithdelims|pmatrix|raise|ref|renewenvironment|require|root|Rule|scr|shoveleft|shoveright|sideset|skew|Space|strut|style|texttip|Tiny|toggle|underparen|unicode|uproot)\b)/gi; async function updateMarkdownPreview(previewContainerNode: HTMLElement, cellId: string, content: string | undefined) { if (typeof content === 'string') { if (content.trim().length === 0) { previewContainerNode.classList.add('emptyMarkdownCell'); previewContainerNode.innerText = ''; } else { previewContainerNode.classList.remove('emptyMarkdownCell'); await renderers.render(createMarkdownOutputItem(cellId, previewContainerNode, content), previewContainerNode); if (!hasPostedRenderedMathTelemetry) { const hasRenderedMath = previewContainerNode.querySelector('.katex'); if (hasRenderedMath) { hasPostedRenderedMathTelemetry = true; postNotebookMessage<webviewMessages.ITelemetryFoundRenderedMarkdownMath>('telemetryFoundRenderedMarkdownMath', {}); } } const matches = previewContainerNode.innerText.match(unsupportedKatexTermsRegex); if (matches) { postNotebookMessage<webviewMessages.ITelemetryFoundUnrenderedMarkdownMath>('telemetryFoundUnrenderedMarkdownMath', { latexDirective: matches[0], }); } } } dimensionUpdater.update(cellId, previewContainerNode.clientHeight, { isOutput: false }); } const markdownPreviewDragManager = new class MarkdownPreviewDragManager { private currentDrag: { cellId: string, clientY: number } | undefined; constructor() { document.addEventListener('dragover', e => { // Allow dropping dragged markdown cells e.preventDefault(); }); document.addEventListener('drop', e => { e.preventDefault(); const drag = this.currentDrag; if (!drag) { return; } this.currentDrag = undefined; postNotebookMessage<webviewMessages.ICellDropMessage>('cell-drop', { cellId: drag.cellId, ctrlKey: e.ctrlKey, altKey: e.altKey, dragOffsetY: e.clientY, }); }); } startDrag(e: DragEvent, cellId: string) { if (!e.dataTransfer) { return; } if (!currentOptions.dragAndDropEnabled) { return; } this.currentDrag = { cellId, clientY: e.clientY }; (e.target as HTMLElement).classList.add('dragging'); postNotebookMessage<webviewMessages.ICellDragStartMessage>('cell-drag-start', { cellId: cellId, dragOffsetY: e.clientY, }); // Continuously send updates while dragging instead of relying on `updateDrag`. // This lets us scroll the list based on drag position. const trySendDragUpdate = () => { if (this.currentDrag?.cellId !== cellId) { return; } postNotebookMessage<webviewMessages.ICellDragMessage>('cell-drag', { cellId: cellId, dragOffsetY: this.currentDrag.clientY, }); requestAnimationFrame(trySendDragUpdate); }; requestAnimationFrame(trySendDragUpdate); } updateDrag(e: DragEvent, cellId: string) { if (cellId !== this.currentDrag?.cellId) { this.currentDrag = undefined; } this.currentDrag = { cellId, clientY: e.clientY }; } endDrag(e: DragEvent, cellId: string) { this.currentDrag = undefined; (e.target as HTMLElement).classList.remove('dragging'); postNotebookMessage<webviewMessages.ICellDragEndMessage>('cell-drag-end', { cellId: cellId }); } }(); function createMarkdownOutputItem(id: string, element: HTMLElement, content: string): IOutputItem { return { id, element, mime: 'text/markdown', metadata: undefined, metadata2: undefined, outputId: undefined, text() { return content; }, json() { return undefined; }, bytes() { return this.data(); }, data() { return new TextEncoder().encode(content); }, blob() { return new Blob([this.data()], { type: this.mime }); }, }; } } export interface RendererMetadata { readonly id: string; readonly entrypoint: string; readonly mimeTypes: readonly string[]; readonly extends: string | undefined; readonly messaging: boolean; } export function preloadsScriptStr(styleValues: PreloadStyles, options: PreloadOptions, renderers: readonly RendererMetadata[]) { // TS will try compiling `import()` in webviePreloads, so use an helper function instead // of using `import(...)` directly return ` const __import = (x) => import(x); (${webviewPreloads})( JSON.parse(decodeURIComponent("${encodeURIComponent(JSON.stringify(styleValues))}")), JSON.parse(decodeURIComponent("${encodeURIComponent(JSON.stringify(options))}")), JSON.parse(decodeURIComponent("${encodeURIComponent(JSON.stringify(renderers))}")) )\n//# sourceURL=notebookWebviewPreloads.js\n`; }
src/vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads.ts
1
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.0005007280269637704, 0.0001759949664119631, 0.00016330780636053532, 0.0001686316099949181, 0.000036595236451830715 ]
{ "id": 2, "code_window": [ "\t\t\t'notebook-run-gutter': `${this.options.runGutter}px`,\n", "\t\t\t'notebook-preivew-node-padding': `${this.options.previewNodePadding}px`,\n", "\t\t\t'notebook-markdown-left-margin': `${this.options.markdownLeftMargin}px`,\n", "\t\t\t'notebook-output-node-left-padding': `${this.options.outputNodeLeftPadding}px`,\n", "\t\t\t'notebook-markdown-min-height': `${this.options.previewNodePadding * 2}px`,\n", "\t\t\t'notebook-cell-output-font-size': `${this.options.fontSize}px`\n", "\t\t};\n", "\t}\n", "\n", "\tprivate generateContent(coreDependencies: string, baseUrl: string) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t'notebook-cell-output-font-size': `${this.options.fontSize}px`,\n", "\t\t\t'notebook-cell-markup-empty-content': nls.localize('notebook.emptyMarkdownPlaceholder', \"Empty markdown cell, double click or press enter to edit.\"),\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView.ts", "type": "replace", "edit_start_line_idx": 166 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'mocha'; import * as assert from 'assert'; import { URI } from 'vscode-uri'; import { resolve } from 'path'; import { TextDocument, DocumentLink } from 'vscode-languageserver-types'; import { WorkspaceFolder } from 'vscode-languageserver-protocol'; import { getCSSLanguageService } from 'vscode-css-languageservice'; import { getDocumentContext } from '../utils/documentContext'; import { getNodeFSRequestService } from '../node/nodeFs'; export interface ItemDescription { offset: number; value: string; target: string; } suite('Links', () => { const cssLanguageService = getCSSLanguageService({ fileSystemProvider: getNodeFSRequestService() }); let assertLink = function (links: DocumentLink[], expected: ItemDescription, document: TextDocument) { let matches = links.filter(link => { return document.offsetAt(link.range.start) === expected.offset; }); assert.strictEqual(matches.length, 1, `${expected.offset} should only existing once: Actual: ${links.map(l => document.offsetAt(l.range.start)).join(', ')}`); let match = matches[0]; assert.strictEqual(document.getText(match.range), expected.value); assert.strictEqual(match.target, expected.target); }; async function assertLinks(value: string, expected: ItemDescription[], testUri: string, workspaceFolders?: WorkspaceFolder[], lang: string = 'css'): Promise<void> { const offset = value.indexOf('|'); value = value.substr(0, offset) + value.substr(offset + 1); const document = TextDocument.create(testUri, lang, 0, value); if (!workspaceFolders) { workspaceFolders = [{ name: 'x', uri: testUri.substr(0, testUri.lastIndexOf('/')) }]; } const context = getDocumentContext(testUri, workspaceFolders); const stylesheet = cssLanguageService.parseStylesheet(document); let links = await cssLanguageService.findDocumentLinks2(document, stylesheet, context)!; assert.strictEqual(links.length, expected.length); for (let item of expected) { assertLink(links, item, document); } } function getTestResource(path: string) { return URI.file(resolve(__dirname, '../../test/linksTestFixtures', path)).toString(); } test('url links', async function () { let testUri = getTestResource('about.css'); let folders = [{ name: 'x', uri: getTestResource('') }]; await assertLinks('html { background-image: url("hello.html|")', [{ offset: 29, value: '"hello.html"', target: getTestResource('hello.html') }], testUri, folders ); }); test('node module resolving', async function () { let testUri = getTestResource('about.css'); let folders = [{ name: 'x', uri: getTestResource('') }]; await assertLinks('html { background-image: url("~foo/hello.html|")', [{ offset: 29, value: '"~foo/hello.html"', target: getTestResource('node_modules/foo/hello.html') }], testUri, folders ); }); test('node module subfolder resolving', async function () { let testUri = getTestResource('subdir/about.css'); let folders = [{ name: 'x', uri: getTestResource('') }]; await assertLinks('html { background-image: url("~foo/hello.html|")', [{ offset: 29, value: '"~foo/hello.html"', target: getTestResource('node_modules/foo/hello.html') }], testUri, folders ); }); });
extensions/css-language-features/server/src/test/links.test.ts
0
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.00017361763457302004, 0.00017116068920586258, 0.00016852913540787995, 0.00017185583419632167, 0.0000018411848259347607 ]
{ "id": 2, "code_window": [ "\t\t\t'notebook-run-gutter': `${this.options.runGutter}px`,\n", "\t\t\t'notebook-preivew-node-padding': `${this.options.previewNodePadding}px`,\n", "\t\t\t'notebook-markdown-left-margin': `${this.options.markdownLeftMargin}px`,\n", "\t\t\t'notebook-output-node-left-padding': `${this.options.outputNodeLeftPadding}px`,\n", "\t\t\t'notebook-markdown-min-height': `${this.options.previewNodePadding * 2}px`,\n", "\t\t\t'notebook-cell-output-font-size': `${this.options.fontSize}px`\n", "\t\t};\n", "\t}\n", "\n", "\tprivate generateContent(coreDependencies: string, baseUrl: string) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t'notebook-cell-output-font-size': `${this.options.fontSize}px`,\n", "\t\t\t'notebook-cell-markup-empty-content': nls.localize('notebook.emptyMarkdownPlaceholder', \"Empty markdown cell, double click or press enter to edit.\"),\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView.ts", "type": "replace", "edit_start_line_idx": 166 }
Monarch definition & snippets: The MIT License (MIT) Copyright (c) 2015 David Owens II Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. TextMate grammar: Copyright (c) 2014 Darin Morrison Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
extensions/swift/LICENSE.md
0
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.00017583223234396428, 0.00017172405205201358, 0.00016462706844322383, 0.00017250674136448652, 0.0000039501192077295855 ]
{ "id": 2, "code_window": [ "\t\t\t'notebook-run-gutter': `${this.options.runGutter}px`,\n", "\t\t\t'notebook-preivew-node-padding': `${this.options.previewNodePadding}px`,\n", "\t\t\t'notebook-markdown-left-margin': `${this.options.markdownLeftMargin}px`,\n", "\t\t\t'notebook-output-node-left-padding': `${this.options.outputNodeLeftPadding}px`,\n", "\t\t\t'notebook-markdown-min-height': `${this.options.previewNodePadding * 2}px`,\n", "\t\t\t'notebook-cell-output-font-size': `${this.options.fontSize}px`\n", "\t\t};\n", "\t}\n", "\n", "\tprivate generateContent(coreDependencies: string, baseUrl: string) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t'notebook-cell-output-font-size': `${this.options.fontSize}px`,\n", "\t\t\t'notebook-cell-markup-empty-content': nls.localize('notebook.emptyMarkdownPlaceholder', \"Empty markdown cell, double click or press enter to edit.\"),\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView.ts", "type": "replace", "edit_start_line_idx": 166 }
{ "comments": { "lineComment": "//", "blockComment": ["/*", "*/"] }, "brackets": [ ["{", "}"], ["[", "]"], ["(", ")"] ], "autoClosingPairs": [ { "open": "[", "close": "]" }, { "open": "{", "close": "}" }, { "open": "(", "close": ")" }, { "open": "'", "close": "'", "notIn": ["string", "comment"] }, { "open": "\"", "close": "\"", "notIn": ["string"] } ], "surroundingPairs": [ ["{", "}"], ["[", "]"], ["(", ")"], ["\"", "\""], ["'", "'"], ["<", ">"] ], "wordPattern": "(-?\\d*\\.\\d\\w*)|([^\\`\\~\\!\\@\\#\\%\\^\\&\\*\\(\\)\\-\\=\\+\\[\\{\\]\\}\\\\\\|\\;\\:\\'\\\"\\,\\.\\<\\>\\/\\?\\s]+)", "folding": { "markers": { "start": "^\\s*#pragma\\s+region\\b", "end": "^\\s*#pragma\\s+endregion\\b" } } }
extensions/cpp/language-configuration.json
0
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.0001710476935841143, 0.00016876254812814295, 0.00016623079136479646, 0.0001688858465058729, 0.0000019351227820152417 ]
{ "id": 3, "code_window": [ "\t\t\t\t\t\t-ms-user-select: none;\n", "\t\t\t\t\t\tcursor: grab;\n", "\t\t\t\t\t}\n", "\n", "\t\t\t\t\t#container > div.preview.emptyMarkdownCell::before {\n", "\t\t\t\t\t\tcontent: \"${nls.localize('notebook.emptyMarkdownPlaceholder', \"Empty markdown cell, double click or press enter to edit.\")}\";\n", "\t\t\t\t\t\tfont-style: italic;\n", "\t\t\t\t\t\topacity: 0.6;\n", "\t\t\t\t\t}\n", "\n", "\t\t\t\t\t#container > div.preview.selected {\n", "\t\t\t\t\t\tbackground: var(--theme-notebook-cell-selected-background);\n", "\t\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView.ts", "type": "replace", "edit_start_line_idx": 220 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IAction } from 'vs/base/common/actions'; import { coalesce } from 'vs/base/common/arrays'; import { VSBuffer } from 'vs/base/common/buffer'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable } from 'vs/base/common/lifecycle'; import { getExtensionForMimeType } from 'vs/base/common/mime'; import { FileAccess, Schemas } from 'vs/base/common/network'; import { isMacintosh, isWeb } from 'vs/base/common/platform'; import { dirname, joinPath } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import * as UUID from 'vs/base/common/uuid'; import * as nls from 'vs/nls'; import { createAndFillInContextMenuActions } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { IMenuService, MenuId } from 'vs/platform/actions/common/actions'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IFileDialogService } from 'vs/platform/dialogs/common/dialogs'; import { IFileService } from 'vs/platform/files/common/files'; import { IOpenerService, matchesScheme } from 'vs/platform/opener/common/opener'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { asWebviewUri } from 'vs/workbench/api/common/shared/webview'; import { CellEditState, ICellOutputViewModel, ICommonCellInfo, ICommonNotebookEditor, IDisplayOutputLayoutUpdateRequest, IDisplayOutputViewModel, IGenericCellViewModel, IInsetRenderOutput, RenderOutputType } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { preloadsScriptStr, RendererMetadata } from 'vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads'; import { transformWebviewThemeVars } from 'vs/workbench/contrib/notebook/browser/view/renderers/webviewThemeMapping'; import { MarkdownCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/markdownCellViewModel'; import { INotebookKernel, INotebookRendererInfo, RendererMessagingSpec } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { IScopedRendererMessaging } from 'vs/workbench/contrib/notebook/common/notebookRendererMessagingService'; import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService'; import { IWebviewService, WebviewContentPurpose, WebviewElement } from 'vs/workbench/contrib/webview/browser/webview'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { ICreationRequestMessage, IMarkdownCellInitialization, FromWebviewMessage, IClickedDataUrlMessage, IContentWidgetTopRequest, IControllerPreload, ToWebviewMessage } from './webviewMessages'; export interface ICachedInset<K extends ICommonCellInfo> { outputId: string; cellInfo: K; renderer?: INotebookRendererInfo; cachedCreation: ICreationRequestMessage; } function html(strings: TemplateStringsArray, ...values: any[]): string { let str = ''; strings.forEach((string, i) => { str += string + (values[i] || ''); }); return str; } export interface INotebookWebviewMessage { message: unknown; } export interface IResolvedBackLayerWebview { webview: WebviewElement; } export class BackLayerWebView<T extends ICommonCellInfo> extends Disposable { element: HTMLElement; webview: WebviewElement | undefined = undefined; insetMapping: Map<IDisplayOutputViewModel, ICachedInset<T>> = new Map(); readonly markdownPreviewMapping = new Map<string, IMarkdownCellInitialization>(); hiddenInsetMapping: Set<IDisplayOutputViewModel> = new Set(); reversedInsetMapping: Map<string, IDisplayOutputViewModel> = new Map(); localResourceRootsCache: URI[] | undefined = undefined; rendererRootsCache: URI[] = []; private readonly _onMessage = this._register(new Emitter<INotebookWebviewMessage>()); private readonly _preloadsCache = new Set<string>(); public readonly onMessage: Event<INotebookWebviewMessage> = this._onMessage.event; private _initalized?: Promise<void>; private _disposed = false; private _currentKernel?: INotebookKernel; constructor( public readonly notebookEditor: ICommonNotebookEditor, public readonly id: string, public readonly documentUri: URI, private options: { outputNodePadding: number, outputNodeLeftPadding: number, previewNodePadding: number, markdownLeftMargin: number, leftMargin: number, rightMargin: number, runGutter: number, dragAndDropEnabled: boolean, fontSize: number }, private readonly rendererMessaging: IScopedRendererMessaging | undefined, @IWebviewService readonly webviewService: IWebviewService, @IOpenerService readonly openerService: IOpenerService, @INotebookService private readonly notebookService: INotebookService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService, @IFileDialogService private readonly fileDialogService: IFileDialogService, @IFileService private readonly fileService: IFileService, @IContextMenuService private readonly contextMenuService: IContextMenuService, @IMenuService private readonly menuService: IMenuService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @ITelemetryService private readonly telemetryService: ITelemetryService, ) { super(); this.element = document.createElement('div'); this.element.style.height = '1400px'; this.element.style.position = 'absolute'; if (rendererMessaging) { this._register(rendererMessaging.onDidReceiveMessage(evt => { this._sendMessageToWebview({ __vscode_notebook_message: true, type: 'customRendererMessage', rendererId: evt.rendererId, message: evt.message }); })); } } updateOptions(options: { outputNodePadding: number, outputNodeLeftPadding: number, previewNodePadding: number, markdownLeftMargin: number, leftMargin: number, rightMargin: number, runGutter: number, dragAndDropEnabled: boolean, fontSize: number }) { this.options = options; this._updateStyles(); this._updateOptions(); } private _updateStyles() { this._sendMessageToWebview({ type: 'notebookStyles', styles: this._generateStyles() }); } private _updateOptions() { this._sendMessageToWebview({ type: 'notebookOptions', options: { dragAndDropEnabled: this.options.dragAndDropEnabled } }); } private _generateStyles() { return { 'notebook-output-left-margin': `${this.options.leftMargin + this.options.runGutter}px`, 'notebook-output-width': `calc(100% - ${this.options.leftMargin + this.options.rightMargin + this.options.runGutter}px)`, 'notebook-output-node-padding': `${this.options.outputNodePadding}px`, 'notebook-run-gutter': `${this.options.runGutter}px`, 'notebook-preivew-node-padding': `${this.options.previewNodePadding}px`, 'notebook-markdown-left-margin': `${this.options.markdownLeftMargin}px`, 'notebook-output-node-left-padding': `${this.options.outputNodeLeftPadding}px`, 'notebook-markdown-min-height': `${this.options.previewNodePadding * 2}px`, 'notebook-cell-output-font-size': `${this.options.fontSize}px` }; } private generateContent(coreDependencies: string, baseUrl: string) { const renderersData = this.getRendererData(); return html` <html lang="en"> <head> <meta charset="UTF-8"> <base href="${baseUrl}/"/> <style> #container .cell_container { width: 100%; } #container .output_container { width: 100%; } #container > div > div > div.output { font-size: var(--notebook-cell-output-font-size); width: var(--notebook-output-width); margin-left: var(--notebook-output-left-margin); padding-top: var(--notebook-output-node-padding); padding-right: var(--notebook-output-node-padding); padding-bottom: var(--notebook-output-node-padding); padding-left: var(--notebook-output-node-left-padding); box-sizing: border-box; background-color: var(--theme-notebook-output-background); } /* markdown */ #container > div.preview { width: 100%; padding-right: var(--notebook-preivew-node-padding); padding-left: var(--notebook-markdown-left-margin); padding-top: var(--notebook-preivew-node-padding); padding-bottom: var(--notebook-preivew-node-padding); box-sizing: border-box; white-space: nowrap; overflow: hidden; white-space: initial; color: var(--theme-ui-foreground); } #container > div.preview.draggable { user-select: none; -webkit-user-select: none; -ms-user-select: none; cursor: grab; } #container > div.preview.emptyMarkdownCell::before { content: "${nls.localize('notebook.emptyMarkdownPlaceholder', "Empty markdown cell, double click or press enter to edit.")}"; font-style: italic; opacity: 0.6; } #container > div.preview.selected { background: var(--theme-notebook-cell-selected-background); } #container > div.preview.dragging { background-color: var(--theme-background); } .monaco-workbench.vs-dark .notebookOverlay .cell.markdown .latex img, .monaco-workbench.vs-dark .notebookOverlay .cell.markdown .latex-block img { filter: brightness(0) invert(1) } #container > div.nb-symbolHighlight { background-color: var(--theme-notebook-symbol-highlight-background); } #container > div.nb-cellDeleted { background-color: var(--theme-notebook-diff-removed-background); } #container > div.nb-cellAdded { background-color: var(--theme-notebook-diff-inserted-background); } #container > div > div:not(.preview) > div { overflow-x: scroll; } body { padding: 0px; height: 100%; width: 100%; } table, thead, tr, th, td, tbody { border: none !important; border-color: transparent; border-spacing: 0; border-collapse: collapse; } table { width: 100%; } table, th, tr { text-align: left !important; } thead { font-weight: bold; background-color: rgba(130, 130, 130, 0.16); } th, td { padding: 4px 8px; } tr:nth-child(even) { background-color: rgba(130, 130, 130, 0.08); } tbody th { font-weight: normal; } </style> </head> <body style="overflow: hidden;"> <script> self.require = {}; </script> ${coreDependencies} <div id='container' class="widgetarea" style="position: absolute;width:100%;top: 0px"></div> <script type="module">${preloadsScriptStr(this.options, { dragAndDropEnabled: this.options.dragAndDropEnabled }, renderersData)}</script> </body> </html>`; } private getRendererData(): RendererMetadata[] { return this.notebookService.getRenderers().map((renderer): RendererMetadata => { const entrypoint = this.asWebviewUri(renderer.entrypoint, renderer.extensionLocation).toString(); return { id: renderer.id, entrypoint, mimeTypes: renderer.mimeTypes, extends: renderer.extends, messaging: renderer.messaging !== RendererMessagingSpec.Never, }; }); } private asWebviewUri(uri: URI, fromExtension: URI | undefined) { return asWebviewUri(uri, fromExtension?.scheme === Schemas.vscodeRemote ? { isRemote: true, authority: fromExtension.authority } : undefined); } postKernelMessage(message: any) { this._sendMessageToWebview({ __vscode_notebook_message: true, type: 'customKernelMessage', message, }); } private resolveOutputId(id: string): { cellInfo: T, output: ICellOutputViewModel } | undefined { const output = this.reversedInsetMapping.get(id); if (!output) { return; } const cellInfo = this.insetMapping.get(output)!.cellInfo; return { cellInfo, output }; } isResolved(): this is IResolvedBackLayerWebview { return !!this.webview; } async createWebview(): Promise<void> { const baseUrl = this.asWebviewUri(dirname(this.documentUri), undefined); // Python hasn't moved to use a preload to load require support yet. // For all other notebooks, we no longer want to include our loader. if (!this.documentUri.path.toLowerCase().endsWith('.ipynb')) { const htmlContent = this.generateContent('', baseUrl.toString()); this._initialize(htmlContent); return; } let coreDependencies = ''; let resolveFunc: () => void; this._initalized = new Promise<void>((resolve, reject) => { resolveFunc = resolve; }); if (!isWeb) { const loaderUri = FileAccess.asFileUri('vs/loader.js', require); const loader = this.asWebviewUri(loaderUri, undefined); coreDependencies = `<script src="${loader}"></script><script> var requirejs = (function() { return require; }()); </script>`; const htmlContent = this.generateContent(coreDependencies, baseUrl.toString()); this._initialize(htmlContent); resolveFunc!(); } else { const loaderUri = FileAccess.asBrowserUri('vs/loader.js', require); fetch(loaderUri.toString(true)).then(async response => { if (response.status !== 200) { throw new Error(response.statusText); } const loaderJs = await response.text(); coreDependencies = ` <script> ${loaderJs} </script> <script> var requirejs = (function() { return require; }()); </script> `; const htmlContent = this.generateContent(coreDependencies, baseUrl.toString()); this._initialize(htmlContent); resolveFunc!(); }, error => { // the fetch request is rejected const htmlContent = this.generateContent(coreDependencies, baseUrl.toString()); this._initialize(htmlContent); resolveFunc!(); }); } await this._initalized; } private _initialize(content: string) { if (!document.body.contains(this.element)) { throw new Error('Element is already detached from the DOM tree'); } this.webview = this._createInset(this.webviewService, content); this.webview.mountTo(this.element); this._register(this.webview); this._register(this.webview.onDidClickLink(link => { if (this._disposed) { return; } if (!link) { return; } if (matchesScheme(link, Schemas.command)) { console.warn('Command links are deprecated and will be removed, use messag passing instead: https://github.com/microsoft/vscode/issues/123601'); } if (matchesScheme(link, Schemas.http) || matchesScheme(link, Schemas.https) || matchesScheme(link, Schemas.mailto) || matchesScheme(link, Schemas.command)) { this.openerService.open(link, { fromUserGesture: true, allowContributedOpeners: true, allowCommands: true }); } })); this._register(this.webview.onMessage((message) => { const data: FromWebviewMessage | { readonly __vscode_notebook_message: undefined } = message.message; if (this._disposed) { return; } if (!data.__vscode_notebook_message) { return; } switch (data.type) { case 'initialized': this.initializeWebViewState(); break; case 'dimension': { for (const update of data.updates) { const height = update.height; if (update.isOutput) { const resolvedResult = this.resolveOutputId(update.id); if (resolvedResult) { const { cellInfo, output } = resolvedResult; this.notebookEditor.updateOutputHeight(cellInfo, output, height, !!update.init, 'webview#dimension'); this.notebookEditor.scheduleOutputHeightAck(cellInfo, update.id, height); } } else { this.notebookEditor.updateMarkdownCellHeight(update.id, height, !!update.init); } } break; } case 'mouseenter': { const resolvedResult = this.resolveOutputId(data.id); if (resolvedResult) { const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo); if (latestCell) { latestCell.outputIsHovered = true; } } break; } case 'mouseleave': { const resolvedResult = this.resolveOutputId(data.id); if (resolvedResult) { const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo); if (latestCell) { latestCell.outputIsHovered = false; } } break; } case 'outputFocus': { const resolvedResult = this.resolveOutputId(data.id); if (resolvedResult) { const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo); if (latestCell) { latestCell.outputIsFocused = true; } } break; } case 'outputBlur': { const resolvedResult = this.resolveOutputId(data.id); if (resolvedResult) { const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo); if (latestCell) { latestCell.outputIsFocused = false; } } break; } case 'scroll-ack': { // const date = new Date(); // const top = data.data.top; // console.log('ack top ', top, ' version: ', data.version, ' - ', date.getMinutes() + ':' + date.getSeconds() + ':' + date.getMilliseconds()); break; } case 'did-scroll-wheel': { this.notebookEditor.triggerScroll({ ...data.payload, preventDefault: () => { }, stopPropagation: () => { } }); break; } case 'focus-editor': { const resolvedResult = this.resolveOutputId(data.id); if (resolvedResult) { const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo); if (!latestCell) { return; } if (data.focusNext) { this.notebookEditor.focusNextNotebookCell(latestCell, 'editor'); } else { this.notebookEditor.focusNotebookCell(latestCell, 'editor'); } } break; } case 'clicked-data-url': { this._onDidClickDataLink(data); break; } case 'customKernelMessage': { this._onMessage.fire({ message: data.message }); break; } case 'customRendererMessage': { this.rendererMessaging?.postMessage(data.rendererId, data.message); break; } case 'clickMarkdownPreview': { const cell = this.notebookEditor.getCellById(data.cellId); if (cell) { if (data.shiftKey || (isMacintosh ? data.metaKey : data.ctrlKey)) { // Modify selection this.notebookEditor.toggleNotebookCellSelection(cell, /* fromPrevious */ data.shiftKey); } else { // Normal click this.notebookEditor.focusNotebookCell(cell, 'container', { skipReveal: true }); } } break; } case 'contextMenuMarkdownPreview': { const cell = this.notebookEditor.getCellById(data.cellId); if (cell) { // Focus the cell first this.notebookEditor.focusNotebookCell(cell, 'container', { skipReveal: true }); // Then show the context menu const webviewRect = this.element.getBoundingClientRect(); this.contextMenuService.showContextMenu({ getActions: () => { const result: IAction[] = []; const menu = this.menuService.createMenu(MenuId.NotebookCellTitle, this.contextKeyService); createAndFillInContextMenuActions(menu, undefined, result); menu.dispose(); return result; }, getAnchor: () => ({ x: webviewRect.x + data.clientX, y: webviewRect.y + data.clientY }) }); } break; } case 'toggleMarkdownPreview': { const cell = this.notebookEditor.getCellById(data.cellId); if (cell) { this.notebookEditor.setMarkdownCellEditState(data.cellId, CellEditState.Editing); this.notebookEditor.focusNotebookCell(cell, 'editor', { skipReveal: true }); } break; } case 'mouseEnterMarkdownPreview': { const cell = this.notebookEditor.getCellById(data.cellId); if (cell instanceof MarkdownCellViewModel) { cell.cellIsHovered = true; } break; } case 'mouseLeaveMarkdownPreview': { const cell = this.notebookEditor.getCellById(data.cellId); if (cell instanceof MarkdownCellViewModel) { cell.cellIsHovered = false; } break; } case 'cell-drag-start': { this.notebookEditor.markdownCellDragStart(data.cellId, data); break; } case 'cell-drag': { this.notebookEditor.markdownCellDrag(data.cellId, data); break; } case 'cell-drop': { this.notebookEditor.markdownCellDrop(data.cellId, { dragOffsetY: data.dragOffsetY, ctrlKey: data.ctrlKey, altKey: data.altKey, }); break; } case 'cell-drag-end': { this.notebookEditor.markdownCellDragEnd(data.cellId); break; } case 'telemetryFoundRenderedMarkdownMath': { this.telemetryService.publicLog2<{}, {}>('notebook/markdown/renderedLatex', {}); break; } case 'telemetryFoundUnrenderedMarkdownMath': { type Classification = { latexDirective: { classification: 'SystemMetaData', purpose: 'FeatureInsight'; }; }; type TelemetryEvent = { latexDirective: string; }; this.telemetryService.publicLog2<TelemetryEvent, Classification>('notebook/markdown/foundUnrenderedLatex', { latexDirective: data.latexDirective }); break; } } })); } private async _onDidClickDataLink(event: IClickedDataUrlMessage): Promise<void> { if (typeof event.data !== 'string') { return; } const [splitStart, splitData] = event.data.split(';base64,'); if (!splitData || !splitStart) { return; } const defaultDir = dirname(this.documentUri); let defaultName: string; if (event.downloadName) { defaultName = event.downloadName; } else { const mimeType = splitStart.replace(/^data:/, ''); const candidateExtension = mimeType && getExtensionForMimeType(mimeType); defaultName = candidateExtension ? `download${candidateExtension}` : 'download'; } const defaultUri = joinPath(defaultDir, defaultName); const newFileUri = await this.fileDialogService.showSaveDialog({ defaultUri }); if (!newFileUri) { return; } const decoded = atob(splitData); const typedArray = new Uint8Array(decoded.length); for (let i = 0; i < decoded.length; i++) { typedArray[i] = decoded.charCodeAt(i); } const buff = VSBuffer.wrap(typedArray); await this.fileService.writeFile(newFileUri, buff); await this.openerService.open(newFileUri); } private _createInset(webviewService: IWebviewService, content: string) { const rootPath = isWeb ? FileAccess.asBrowserUri('', require) : FileAccess.asFileUri('', require); const workspaceFolders = this.contextService.getWorkspace().folders.map(x => x.uri); this.localResourceRootsCache = [ ...this.notebookService.getNotebookProviderResourceRoots(), ...this.notebookService.getRenderers().map(x => dirname(x.entrypoint)), ...workspaceFolders, rootPath, ]; const webview = webviewService.createWebviewElement(this.id, { purpose: WebviewContentPurpose.NotebookRenderer, enableFindWidget: false, transformCssVariables: transformWebviewThemeVars, }, { allowMultipleAPIAcquire: true, allowScripts: true, localResourceRoots: this.localResourceRootsCache, }, undefined); webview.html = content; return webview; } private initializeWebViewState() { const renderers = new Set<INotebookRendererInfo>(); for (const inset of this.insetMapping.values()) { if (inset.renderer) { renderers.add(inset.renderer); } } this._preloadsCache.clear(); if (this._currentKernel) { this._updatePreloadsFromKernel(this._currentKernel); } for (const [output, inset] of this.insetMapping.entries()) { this._sendMessageToWebview({ ...inset.cachedCreation, initiallyHidden: this.hiddenInsetMapping.has(output) }); } const mdCells = [...this.markdownPreviewMapping.values()]; this.markdownPreviewMapping.clear(); this.initializeMarkdown(mdCells); this._updateStyles(); this._updateOptions(); } private shouldUpdateInset(cell: IGenericCellViewModel, output: ICellOutputViewModel, cellTop: number, outputOffset: number): boolean { if (this._disposed) { return false; } if (cell.metadata.outputCollapsed) { return false; } if (this.hiddenInsetMapping.has(output)) { return true; } const outputCache = this.insetMapping.get(output); if (!outputCache) { return false; } if (outputOffset === outputCache.cachedCreation.outputOffset && cellTop === outputCache.cachedCreation.cellTop) { return false; } return true; } ackHeight(cellId: string, id: string, height: number): void { this._sendMessageToWebview({ type: 'ack-dimension', cellId: cellId, outputId: id, height: height }); } updateScrollTops(outputRequests: IDisplayOutputLayoutUpdateRequest[], markdownPreviews: { id: string, top: number }[]) { if (this._disposed) { return; } const widgets = coalesce(outputRequests.map((request): IContentWidgetTopRequest | undefined => { const outputCache = this.insetMapping.get(request.output); if (!outputCache) { return; } if (!request.forceDisplay && !this.shouldUpdateInset(request.cell, request.output, request.cellTop, request.outputOffset)) { return; } const id = outputCache.outputId; outputCache.cachedCreation.cellTop = request.cellTop; outputCache.cachedCreation.outputOffset = request.outputOffset; this.hiddenInsetMapping.delete(request.output); return { outputId: id, cellTop: request.cellTop, outputOffset: request.outputOffset, forceDisplay: request.forceDisplay, }; })); if (!widgets.length && !markdownPreviews.length) { return; } this._sendMessageToWebview({ type: 'view-scroll', widgets: widgets, markdownPreviews, }); } private async createMarkdownPreview(initialization: IMarkdownCellInitialization) { if (this._disposed) { return; } if (this.markdownPreviewMapping.has(initialization.cellId)) { console.error('Trying to create markdown preview that already exists'); return; } this.markdownPreviewMapping.set(initialization.cellId, initialization); this._sendMessageToWebview({ type: 'createMarkupCell', cell: initialization }); } async showMarkdownPreview(initialization: IMarkdownCellInitialization) { if (this._disposed) { return; } const entry = this.markdownPreviewMapping.get(initialization.cellId); if (!entry) { return this.createMarkdownPreview(initialization); } const sameContent = initialization.content === entry.content; if (!sameContent || !entry.visible) { this._sendMessageToWebview({ type: 'showMarkupCell', id: initialization.cellId, handle: initialization.cellHandle, // If the content has not changed, we still want to make sure the // preview is visible but don't need to send anything over content: sameContent ? undefined : initialization.content, top: initialization.offset }); } entry.content = initialization.content; entry.offset = initialization.offset; entry.visible = true; } async hideMarkdownPreviews(cellIds: readonly string[]) { if (this._disposed) { return; } const cellsToHide: string[] = []; for (const cellId of cellIds) { const entry = this.markdownPreviewMapping.get(cellId); if (entry) { if (entry.visible) { cellsToHide.push(cellId); entry.visible = false; } } } if (cellsToHide.length) { this._sendMessageToWebview({ type: 'hideMarkupCells', ids: cellsToHide }); } } async unhideMarkdownPreviews(cellIds: readonly string[]) { if (this._disposed) { return; } const toUnhide: string[] = []; for (const cellId of cellIds) { const entry = this.markdownPreviewMapping.get(cellId); if (entry) { if (!entry.visible) { entry.visible = true; toUnhide.push(cellId); } } else { console.error(`Trying to unhide a preview that does not exist: ${cellId}`); } } this._sendMessageToWebview({ type: 'unhideMarkupCells', ids: toUnhide, }); } async deleteMarkdownPreviews(cellIds: readonly string[]) { if (this._disposed) { return; } for (const id of cellIds) { if (!this.markdownPreviewMapping.has(id)) { console.error(`Trying to delete a preview that does not exist: ${id}`); } this.markdownPreviewMapping.delete(id); } if (cellIds.length) { this._sendMessageToWebview({ type: 'deleteMarkupCell', ids: cellIds }); } } async updateMarkdownPreviewSelections(selectedCellsIds: string[]) { if (this._disposed) { return; } this._sendMessageToWebview({ type: 'updateSelectedMarkupCells', selectedCellIds: selectedCellsIds.filter(id => this.markdownPreviewMapping.has(id)), }); } async initializeMarkdown(cells: ReadonlyArray<IMarkdownCellInitialization>) { if (this._disposed) { return; } // TODO: use proper handler const p = new Promise<void>(resolve => { this.webview?.onMessage(e => { if (e.message.type === 'initializedMarkdownPreview') { resolve(); } }); }); for (const cell of cells) { this.markdownPreviewMapping.set(cell.cellId, { ...cell, visible: false }); } this._sendMessageToWebview({ type: 'initializeMarkup', cells, }); await p; } async createOutput(cellInfo: T, content: IInsetRenderOutput, cellTop: number, offset: number) { if (this._disposed) { return; } if (this.insetMapping.has(content.source)) { const outputCache = this.insetMapping.get(content.source); if (outputCache) { this.hiddenInsetMapping.delete(content.source); this._sendMessageToWebview({ type: 'showOutput', cellId: outputCache.cellInfo.cellId, outputId: outputCache.outputId, cellTop: cellTop, outputOffset: offset }); return; } } const messageBase = { type: 'html', cellId: cellInfo.cellId, cellTop: cellTop, outputOffset: offset, left: 0, requiredPreloads: [], } as const; let message: ICreationRequestMessage; let renderer: INotebookRendererInfo | undefined; if (content.type === RenderOutputType.Extension) { const output = content.source.model; renderer = content.renderer; const outputDto = output.outputs.find(op => op.mime === content.mimeType); // TODO@notebook - the message can contain "bytes" and those are transferable // which improves IPC performance and therefore should be used. However, it does // means that the bytes cannot be used here anymore message = { ...messageBase, outputId: output.outputId, rendererId: content.renderer.id, content: { type: RenderOutputType.Extension, outputId: output.outputId, mimeType: content.mimeType, valueBytes: new Uint8Array(outputDto?.valueBytes ?? []), metadata: output.metadata, metadata2: output.metadata }, }; } else { message = { ...messageBase, outputId: UUID.generateUuid(), content: { type: content.type, htmlContent: content.htmlContent, } }; } this._sendMessageToWebview(message); this.insetMapping.set(content.source, { outputId: message.outputId, cellInfo: cellInfo, renderer, cachedCreation: message }); this.hiddenInsetMapping.delete(content.source); this.reversedInsetMapping.set(message.outputId, content.source); } removeInsets(outputs: readonly ICellOutputViewModel[]) { if (this._disposed) { return; } for (const output of outputs) { const outputCache = this.insetMapping.get(output); if (!outputCache) { continue; } const id = outputCache.outputId; this._sendMessageToWebview({ type: 'clearOutput', rendererId: outputCache.cachedCreation.rendererId, cellUri: outputCache.cellInfo.cellUri.toString(), outputId: id, cellId: outputCache.cellInfo.cellId }); this.insetMapping.delete(output); this.reversedInsetMapping.delete(id); } } hideInset(output: ICellOutputViewModel) { if (this._disposed) { return; } const outputCache = this.insetMapping.get(output); if (!outputCache) { return; } this.hiddenInsetMapping.add(output); this._sendMessageToWebview({ type: 'hideOutput', outputId: outputCache.outputId, cellId: outputCache.cellInfo.cellId, }); } clearInsets() { if (this._disposed) { return; } this._sendMessageToWebview({ type: 'clear' }); this.insetMapping = new Map(); this.reversedInsetMapping = new Map(); } focusWebview() { if (this._disposed) { return; } this.webview?.focus(); } focusOutput(cellId: string) { if (this._disposed) { return; } this.webview?.focus(); setTimeout(() => { // Need this, or focus decoration is not shown. No clue. this._sendMessageToWebview({ type: 'focus-output', cellId, }); }, 50); } deltaCellOutputContainerClassNames(cellId: string, added: string[], removed: string[]) { this._sendMessageToWebview({ type: 'decorations', cellId, addedClassNames: added, removedClassNames: removed }); } async updateKernelPreloads(kernel: INotebookKernel | undefined) { if (this._disposed || kernel === this._currentKernel) { return; } const previousKernel = this._currentKernel; this._currentKernel = kernel; if (previousKernel && previousKernel.preloadUris.length > 0) { this.webview?.reload(); // preloads will be restored after reload } else if (kernel) { this._updatePreloadsFromKernel(kernel); } } private _updatePreloadsFromKernel(kernel: INotebookKernel) { const resources: IControllerPreload[] = []; for (const preload of kernel.preloadUris) { const uri = this.environmentService.isExtensionDevelopment && (preload.scheme === 'http' || preload.scheme === 'https') ? preload : this.asWebviewUri(preload, undefined); if (!this._preloadsCache.has(uri.toString())) { resources.push({ uri: uri.toString(), originalUri: preload.toString() }); this._preloadsCache.add(uri.toString()); } } if (!resources.length) { return; } this._updatePreloads(resources); } private _updatePreloads(resources: IControllerPreload[]) { if (!this.webview) { return; } const mixedResourceRoots = [ ...(this.localResourceRootsCache || []), ...this.rendererRootsCache, ...(this._currentKernel ? [this._currentKernel.localResourceRoot] : []), ]; this.webview.localResourcesRoot = mixedResourceRoots; this._sendMessageToWebview({ type: 'preload', resources: resources, }); } private _sendMessageToWebview(message: ToWebviewMessage) { if (this._disposed) { return; } this.webview?.postMessage(message); } clearPreloadsCache() { this._preloadsCache.clear(); } override dispose() { this._disposed = true; this.webview?.dispose(); super.dispose(); } }
src/vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView.ts
1
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.9984207153320312, 0.008397065103054047, 0.0001635917869862169, 0.0001701243018032983, 0.09000270068645477 ]
{ "id": 3, "code_window": [ "\t\t\t\t\t\t-ms-user-select: none;\n", "\t\t\t\t\t\tcursor: grab;\n", "\t\t\t\t\t}\n", "\n", "\t\t\t\t\t#container > div.preview.emptyMarkdownCell::before {\n", "\t\t\t\t\t\tcontent: \"${nls.localize('notebook.emptyMarkdownPlaceholder', \"Empty markdown cell, double click or press enter to edit.\")}\";\n", "\t\t\t\t\t\tfont-style: italic;\n", "\t\t\t\t\t\topacity: 0.6;\n", "\t\t\t\t\t}\n", "\n", "\t\t\t\t\t#container > div.preview.selected {\n", "\t\t\t\t\t\tbackground: var(--theme-notebook-cell-selected-background);\n", "\t\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView.ts", "type": "replace", "edit_start_line_idx": 220 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { IProductService } from 'vs/platform/product/common/productService'; import { Action } from 'vs/base/common/actions'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { INativeHostService } from 'vs/platform/native/electron-sandbox/native'; import { IDebugService } from 'vs/workbench/contrib/debug/common/debug'; import { IDialogService } from 'vs/platform/dialogs/common/dialogs'; import { randomPort } from 'vs/base/common/ports'; export class DebugExtensionHostAction extends Action { static readonly ID = 'workbench.extensions.action.debugExtensionHost'; static readonly LABEL = nls.localize('debugExtensionHost', "Start Debugging Extension Host"); static readonly CSS_CLASS = 'debug-extension-host'; constructor( @IDebugService private readonly _debugService: IDebugService, @INativeHostService private readonly _nativeHostService: INativeHostService, @IDialogService private readonly _dialogService: IDialogService, @IExtensionService private readonly _extensionService: IExtensionService, @IProductService private readonly productService: IProductService ) { super(DebugExtensionHostAction.ID, DebugExtensionHostAction.LABEL, DebugExtensionHostAction.CSS_CLASS); } override async run(): Promise<any> { const inspectPort = await this._extensionService.getInspectPort(false); if (!inspectPort) { const res = await this._dialogService.confirm({ type: 'info', message: nls.localize('restart1', "Profile Extensions"), detail: nls.localize('restart2', "In order to profile extensions a restart is required. Do you want to restart '{0}' now?", this.productService.nameLong), primaryButton: nls.localize('restart3', "&&Restart"), secondaryButton: nls.localize('cancel', "&&Cancel") }); if (res.confirmed) { await this._nativeHostService.relaunch({ addArgs: [`--inspect-extensions=${randomPort()}`] }); } return; } return this._debugService.startDebugging(undefined, { type: 'node', name: nls.localize('debugExtensionHost.launch.name', "Attach Extension Host"), request: 'attach', port: inspectPort }); } }
src/vs/workbench/contrib/extensions/electron-sandbox/debugExtensionHostAction.ts
0
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.0001745033951010555, 0.00017085258150473237, 0.0001668593322392553, 0.00017113599460572004, 0.0000024662817850185093 ]
{ "id": 3, "code_window": [ "\t\t\t\t\t\t-ms-user-select: none;\n", "\t\t\t\t\t\tcursor: grab;\n", "\t\t\t\t\t}\n", "\n", "\t\t\t\t\t#container > div.preview.emptyMarkdownCell::before {\n", "\t\t\t\t\t\tcontent: \"${nls.localize('notebook.emptyMarkdownPlaceholder', \"Empty markdown cell, double click or press enter to edit.\")}\";\n", "\t\t\t\t\t\tfont-style: italic;\n", "\t\t\t\t\t\topacity: 0.6;\n", "\t\t\t\t\t}\n", "\n", "\t\t\t\t\t#container > div.preview.selected {\n", "\t\t\t\t\t\tbackground: var(--theme-notebook-cell-selected-background);\n", "\t\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView.ts", "type": "replace", "edit_start_line_idx": 220 }
{ "information_for_contributors": [ "This file has been converted from https://github.com/daaain/Handlebars/blob/master/grammars/Handlebars.json", "If you want to provide a fix or improvement, please create a pull request against the original repository.", "Once accepted there, we are happy to receive an update request." ], "version": "https://github.com/daaain/Handlebars/commit/85a153a6f759df4e8da7533e1b3651f007867c51", "name": "Handlebars", "scopeName": "text.html.handlebars", "patterns": [ { "include": "#yfm" }, { "include": "#extends" }, { "include": "#block_comments" }, { "include": "#comments" }, { "include": "#block_helper" }, { "include": "#end_block" }, { "include": "#else_token" }, { "include": "#partial_and_var" }, { "include": "#inline_script" }, { "include": "#html_tags" }, { "include": "text.html.basic" } ], "repository": { "html_tags": { "patterns": [ { "begin": "(<)([a-zA-Z0-9:-]+)(?=[^>]*></\\2>)", "beginCaptures": { "1": { "name": "punctuation.definition.tag.html" }, "2": { "name": "entity.name.tag.html" } }, "end": "(>(<)/)(\\2)(>)", "endCaptures": { "1": { "name": "punctuation.definition.tag.html" }, "2": { "name": "meta.scope.between-tag-pair.html" }, "3": { "name": "entity.name.tag.html" }, "4": { "name": "punctuation.definition.tag.html" } }, "name": "meta.tag.any.html", "patterns": [ { "include": "#tag-stuff" } ] }, { "begin": "(<\\?)(xml)", "captures": { "1": { "name": "punctuation.definition.tag.html" }, "2": { "name": "entity.name.tag.xml.html" } }, "end": "(\\?>)", "name": "meta.tag.preprocessor.xml.html", "patterns": [ { "include": "#tag_generic_attribute" }, { "include": "#string" } ] }, { "begin": "<!--", "captures": { "0": { "name": "punctuation.definition.comment.html" } }, "end": "--\\s*>", "name": "comment.block.html", "patterns": [ { "match": "--", "name": "invalid.illegal.bad-comments-or-CDATA.html" } ] }, { "begin": "<!", "captures": { "0": { "name": "punctuation.definition.tag.html" } }, "end": ">", "name": "meta.tag.sgml.html", "patterns": [ { "begin": "(DOCTYPE|doctype)", "captures": { "1": { "name": "entity.name.tag.doctype.html" } }, "end": "(?=>)", "name": "meta.tag.sgml.doctype.html", "patterns": [ { "match": "\"[^\">]*\"", "name": "string.quoted.double.doctype.identifiers-and-DTDs.html" } ] }, { "begin": "\\[CDATA\\[", "end": "]](?=>)", "name": "constant.other.inline-data.html" }, { "match": "(\\s*)(?!--|>)\\S(\\s*)", "name": "invalid.illegal.bad-comments-or-CDATA.html" } ] }, { "begin": "(?:^\\s+)?(<)((?i:style))\\b(?![^>]*/>)", "captures": { "1": { "name": "punctuation.definition.tag.html" }, "2": { "name": "entity.name.tag.style.html" }, "3": { "name": "punctuation.definition.tag.html" } }, "end": "(</)((?i:style))(>)(?:\\s*\\n)?", "name": "source.css.embedded.html", "patterns": [ { "include": "#tag-stuff" }, { "begin": "(>)", "beginCaptures": { "1": { "name": "punctuation.definition.tag.html" } }, "end": "(?=</(?i:style))", "patterns": [ { "include": "source.css" } ] } ] }, { "begin": "(?:^\\s+)?(<)((?i:script))\\b(?![^>]*/>)", "beginCaptures": { "1": { "name": "punctuation.definition.tag.html" }, "2": { "name": "entity.name.tag.script.html" } }, "end": "(?<=</(script|SCRIPT))(>)(?:\\s*\\n)?", "endCaptures": { "2": { "name": "punctuation.definition.tag.html" } }, "name": "source.js.embedded.html", "patterns": [ { "include": "#tag-stuff" }, { "begin": "(?<!</(?:script|SCRIPT))(>)", "captures": { "1": { "name": "punctuation.definition.tag.html" }, "2": { "name": "entity.name.tag.script.html" } }, "end": "(</)((?i:script))", "patterns": [ { "captures": { "1": { "name": "punctuation.definition.comment.js" } }, "match": "(//).*?((?=</script)|$\\n?)", "name": "comment.line.double-slash.js" }, { "begin": "/\\*", "captures": { "0": { "name": "punctuation.definition.comment.js" } }, "end": "\\*/|(?=</script)", "name": "comment.block.js" }, { "include": "source.js" } ] } ] }, { "begin": "(</?)((?i:body|head|html)\\b)", "captures": { "1": { "name": "punctuation.definition.tag.html" }, "2": { "name": "entity.name.tag.structure.any.html" } }, "end": "(>)", "name": "meta.tag.structure.any.html", "patterns": [ { "include": "#tag-stuff" } ] }, { "begin": "(</?)((?i:address|blockquote|dd|div|header|section|footer|aside|nav|dl|dt|fieldset|form|frame|frameset|h1|h2|h3|h4|h5|h6|iframe|noframes|object|ol|p|ul|applet|center|dir|hr|menu|pre)\\b)", "captures": { "1": { "name": "punctuation.definition.tag.html" }, "2": { "name": "entity.name.tag.block.any.html" } }, "end": "(>)", "name": "meta.tag.block.any.html", "patterns": [ { "include": "#tag-stuff" } ] }, { "begin": "(</?)((?i:a|abbr|acronym|area|b|base|basefont|bdo|big|br|button|caption|cite|code|col|colgroup|del|dfn|em|font|head|html|i|img|input|ins|isindex|kbd|label|legend|li|link|map|meta|noscript|optgroup|option|param|q|s|samp|script|select|small|span|strike|strong|style|sub|sup|table|tbody|td|textarea|tfoot|th|thead|title|tr|tt|u|var)\\b)", "captures": { "1": { "name": "punctuation.definition.tag.html" }, "2": { "name": "entity.name.tag.inline.any.html" } }, "end": "((?: ?/)?>)", "name": "meta.tag.inline.any.html", "patterns": [ { "include": "#tag-stuff" } ] }, { "begin": "(</?)([a-zA-Z0-9:-]+)", "captures": { "1": { "name": "punctuation.definition.tag.html" }, "2": { "name": "entity.name.tag.other.html" } }, "end": "(>)", "name": "meta.tag.other.html", "patterns": [ { "include": "#tag-stuff" } ] }, { "begin": "(</?)([a-zA-Z0-9{}:-]+)", "captures": { "1": { "name": "punctuation.definition.tag.html" }, "2": { "name": "entity.name.tag.tokenised.html" } }, "end": "(>)", "name": "meta.tag.tokenised.html", "patterns": [ { "include": "#tag-stuff" } ] }, { "include": "#entities" }, { "match": "<>", "name": "invalid.illegal.incomplete.html" }, { "match": "<", "name": "invalid.illegal.bad-angle-bracket.html" } ] }, "entities": { "patterns": [ { "captures": { "1": { "name": "punctuation.definition.entity.html" }, "3": { "name": "punctuation.definition.entity.html" } }, "name": "constant.character.entity.html", "match": "(&)([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+)(;)" }, { "name": "invalid.illegal.bad-ampersand.html", "match": "&" } ] }, "end_block": { "begin": "(\\{\\{)(~?/)([a-zA-Z0-9/_\\.-]+)\\s*", "end": "(~?\\}\\})", "name": "meta.function.block.end.handlebars", "endCaptures": { "1": { "name": "support.constant.handlebars" } }, "beginCaptures": { "1": { "name": "support.constant.handlebars" }, "2": { "name": "support.constant.handlebars keyword.control" }, "3": { "name": "support.constant.handlebars keyword.control" } }, "patterns": [] }, "yfm": { "patterns": [ { "patterns": [ { "include": "source.yaml" } ], "begin": "(?<!\\s)---\\n$", "end": "^---\\s", "name": "markup.raw.yaml.front-matter" } ] }, "comments": { "patterns": [ { "patterns": [ { "name": "keyword.annotation.handlebars", "match": "@\\w*" }, { "include": "#comments" } ], "begin": "\\{\\{!", "end": "\\}\\}", "name": "comment.block.handlebars" }, { "captures": { "0": { "name": "punctuation.definition.comment.html" } }, "begin": "<!--", "end": "-{2,3}\\s*>", "name": "comment.block.html", "patterns": [ { "name": "invalid.illegal.bad-comments-or-CDATA.html", "match": "--" } ] } ] }, "block_comments": { "patterns": [ { "patterns": [ { "name": "keyword.annotation.handlebars", "match": "@\\w*" }, { "include": "#comments" } ], "begin": "\\{\\{!--", "end": "--\\}\\}", "name": "comment.block.handlebars" }, { "captures": { "0": { "name": "punctuation.definition.comment.html" } }, "begin": "<!--", "end": "-{2,3}\\s*>", "name": "comment.block.html", "patterns": [ { "name": "invalid.illegal.bad-comments-or-CDATA.html", "match": "--" } ] } ] }, "block_helper": { "begin": "(\\{\\{)(~?\\#)([-a-zA-Z0-9_\\./>]+)\\s?(@?[-a-zA-Z0-9_\\./]+)*\\s?(@?[-a-zA-Z0-9_\\./]+)*\\s?(@?[-a-zA-Z0-9_\\./]+)*", "end": "(~?\\}\\})", "name": "meta.function.block.start.handlebars", "endCaptures": { "1": { "name": "support.constant.handlebars" } }, "beginCaptures": { "1": { "name": "support.constant.handlebars" }, "2": { "name": "support.constant.handlebars keyword.control" }, "3": { "name": "support.constant.handlebars keyword.control" }, "4": { "name": "variable.parameter.handlebars" }, "5": { "name": "support.constant.handlebars" }, "6": { "name": "variable.parameter.handlebars" }, "7": { "name": "support.constant.handlebars" } }, "patterns": [ { "include": "#string" }, { "include": "#handlebars_attribute" } ] }, "string-single-quoted": { "begin": "'", "end": "'", "name": "string.quoted.single.handlebars", "endCaptures": { "0": { "name": "punctuation.definition.string.end.html" } }, "beginCaptures": { "0": { "name": "punctuation.definition.string.begin.html" } }, "patterns": [ { "include": "#escaped-single-quote" }, { "include": "#block_comments" }, { "include": "#comments" }, { "include": "#block_helper" }, { "include": "#else_token" }, { "include": "#end_block" }, { "include": "#partial_and_var" } ] }, "string": { "patterns": [ { "include": "#string-single-quoted" }, { "include": "#string-double-quoted" } ] }, "escaped-single-quote": { "name": "constant.character.escape.js", "match": "\\\\'" }, "escaped-double-quote": { "name": "constant.character.escape.js", "match": "\\\\\"" }, "partial_and_var": { "begin": "(\\{\\{~?\\{*(>|!<)*)\\s*(@?[-a-zA-Z0-9$_\\./]+)*", "end": "(~?\\}\\}\\}*)", "name": "meta.function.inline.other.handlebars", "beginCaptures": { "1": { "name": "support.constant.handlebars" }, "3": { "name": "variable.parameter.handlebars" } }, "endCaptures": { "1": { "name": "support.constant.handlebars" } }, "patterns": [ { "include": "#string" }, { "include": "#handlebars_attribute" } ] }, "handlebars_attribute_name": { "begin": "\\b([-a-zA-Z0-9_\\.]+)\\b=", "captures": { "1": { "name": "variable.parameter.handlebars" } }, "end": "(?='|\"|)", "name": "entity.other.attribute-name.handlebars" }, "handlebars_attribute_value": { "begin": "([-a-zA-Z0-9_\\./]+)\\b", "captures": { "1": { "name": "variable.parameter.handlebars" } }, "end": "('|\"|)", "name": "entity.other.attribute-value.handlebars", "patterns": [ { "include": "#string" } ] }, "handlebars_attribute": { "patterns": [ { "include": "#handlebars_attribute_name" }, { "include": "#handlebars_attribute_value" } ] }, "extends": { "patterns": [ { "end": "(\\}\\})", "begin": "(\\{\\{!<)\\s([-a-zA-Z0-9_\\./]+)", "beginCaptures": { "1": { "name": "support.function.handlebars" }, "2": { "name": "support.class.handlebars" } }, "endCaptures": { "1": { "name": "support.function.handlebars" } }, "name": "meta.preprocessor.handlebars" } ] }, "else_token": { "begin": "(\\{\\{)(~?else)(@?\\s(if)\\s([-a-zA-Z0-9_\\.\\(\\s\\)/]+))?", "end": "(~?\\}\\}\\}*)", "name": "meta.function.inline.else.handlebars", "beginCaptures": { "1": { "name": "support.constant.handlebars" }, "2": { "name": "support.constant.handlebars keyword.control" }, "3": { "name": "support.constant.handlebars" }, "4": { "name": "variable.parameter.handlebars" } }, "endCaptures": { "1": { "name": "support.constant.handlebars" } } }, "string-double-quoted": { "begin": "\"", "end": "\"", "name": "string.quoted.double.handlebars", "beginCaptures": { "0": { "name": "punctuation.definition.string.begin.html" } }, "endCaptures": { "0": { "name": "punctuation.definition.string.end.html" } }, "patterns": [ { "include": "#escaped-double-quote" }, { "include": "#block_comments" }, { "include": "#comments" }, { "include": "#block_helper" }, { "include": "#else_token" }, { "include": "#end_block" }, { "include": "#partial_and_var" } ] }, "inline_script": { "begin": "(?:^\\s+)?(<)((?i:script))\\b(?:.*(type)=([\"'](?:text/x-handlebars-template|text/x-handlebars|text/template|x-tmpl-handlebars)[\"']))(?![^>]*/>)", "beginCaptures": { "1": { "name": "punctuation.definition.tag.html" }, "2": { "name": "entity.name.tag.script.html" }, "3": { "name": "entity.other.attribute-name.html" }, "4": { "name": "string.quoted.double.html" } }, "end": "(?<=</(script|SCRIPT))(>)(?:\\s*\\n)?", "endCaptures": { "2": { "name": "punctuation.definition.tag.html" } }, "name": "source.handlebars.embedded.html", "patterns": [ { "include": "#tag-stuff" }, { "begin": "(?<!</(?:script|SCRIPT))(>)", "captures": { "1": { "name": "punctuation.definition.tag.html" }, "2": { "name": "entity.name.tag.script.html" } }, "end": "(</)((?i:script))", "patterns": [ { "include": "#block_comments" }, { "include": "#comments" }, { "include": "#block_helper" }, { "include": "#end_block" }, { "include": "#else_token" }, { "include": "#partial_and_var" }, { "include": "#html_tags" }, { "include": "text.html.basic" } ] } ] }, "tag_generic_attribute": { "begin": "\\b([a-zA-Z0-9_-]+)\\b\\s*(=)", "captures": { "1": { "name": "entity.other.attribute-name.generic.html" }, "2": { "name": "punctuation.separator.key-value.html" } }, "patterns": [ { "include": "#string" } ], "name": "entity.other.attribute-name.html", "end": "(?<='|\"|)" }, "tag_id_attribute": { "begin": "\\b(id)\\b\\s*(=)", "captures": { "1": { "name": "entity.other.attribute-name.id.html" }, "2": { "name": "punctuation.separator.key-value.html" } }, "end": "(?<='|\"|)", "name": "meta.attribute-with-value.id.html", "patterns": [ { "include": "#string" } ] }, "tag-stuff": { "patterns": [ { "include": "#tag_id_attribute" }, { "include": "#tag_generic_attribute" }, { "include": "#string" }, { "include": "#block_comments" }, { "include": "#comments" }, { "include": "#block_helper" }, { "include": "#end_block" }, { "include": "#else_token" }, { "include": "#partial_and_var" } ] } } }
extensions/handlebars/syntaxes/Handlebars.tmLanguage.json
0
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.00017566230962984264, 0.00017175469838548452, 0.0001681054272921756, 0.00017168332124128938, 0.0000015023430250948877 ]
{ "id": 3, "code_window": [ "\t\t\t\t\t\t-ms-user-select: none;\n", "\t\t\t\t\t\tcursor: grab;\n", "\t\t\t\t\t}\n", "\n", "\t\t\t\t\t#container > div.preview.emptyMarkdownCell::before {\n", "\t\t\t\t\t\tcontent: \"${nls.localize('notebook.emptyMarkdownPlaceholder', \"Empty markdown cell, double click or press enter to edit.\")}\";\n", "\t\t\t\t\t\tfont-style: italic;\n", "\t\t\t\t\t\topacity: 0.6;\n", "\t\t\t\t\t}\n", "\n", "\t\t\t\t\t#container > div.preview.selected {\n", "\t\t\t\t\t\tbackground: var(--theme-notebook-cell-selected-background);\n", "\t\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView.ts", "type": "replace", "edit_start_line_idx": 220 }
[ { "c": "package", "t": "source.go keyword.package.go", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "main", "t": "source.go entity.name.package.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "import", "t": "source.go keyword.import.go", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "(", "t": "source.go punctuation.definition.imports.begin.bracket.round.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "\"", "t": "source.go string.quoted.double.go punctuation.definition.string.begin.go", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "encoding/base64", "t": "source.go string.quoted.double.go entity.name.import.go", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "\"", "t": "source.go string.quoted.double.go punctuation.definition.string.end.go", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "\"", "t": "source.go string.quoted.double.go punctuation.definition.string.begin.go", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "fmt", "t": "source.go string.quoted.double.go entity.name.import.go", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "\"", "t": "source.go string.quoted.double.go punctuation.definition.string.end.go", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": ")", "t": "source.go punctuation.definition.imports.end.bracket.round.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "func", "t": "source.go keyword.function.go", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "main", "t": "source.go entity.name.function.go", "r": { "dark_plus": "entity.name.function: #DCDCAA", "light_plus": "entity.name.function: #795E26", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "entity.name.function: #DCDCAA" } }, { "c": "(", "t": "source.go punctuation.definition.begin.bracket.round.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": ")", "t": "source.go punctuation.definition.end.bracket.round.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "{", "t": "source.go punctuation.definition.begin.bracket.curly.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "dnsName", "t": "source.go variable.other.assignment.go", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": ":=", "t": "source.go keyword.operator.assignment.go", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "\"", "t": "source.go string.quoted.double.go punctuation.definition.string.begin.go", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "test-vm-from-go", "t": "source.go string.quoted.double.go", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "\"", "t": "source.go string.quoted.double.go punctuation.definition.string.end.go", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "storageAccount", "t": "source.go variable.other.assignment.go", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": ":=", "t": "source.go keyword.operator.assignment.go", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "\"", "t": "source.go string.quoted.double.go punctuation.definition.string.begin.go", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "mystorageaccount", "t": "source.go string.quoted.double.go", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "\"", "t": "source.go string.quoted.double.go punctuation.definition.string.end.go", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "c", "t": "source.go variable.other.assignment.go", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": ":=", "t": "source.go keyword.operator.assignment.go", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "make", "t": "source.go support.function.builtin.go", "r": { "dark_plus": "support.function: #DCDCAA", "light_plus": "support.function: #795E26", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.function: #DCDCAA" } }, { "c": "(", "t": "source.go punctuation.definition.begin.bracket.round.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "chan", "t": "source.go keyword.channel.go", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "int", "t": "source.go storage.type.numeric.go", "r": { "dark_plus": "storage.type.numeric.go: #4EC9B0", "light_plus": "storage.type.numeric.go: #267F99", "dark_vs": "storage.type: #569CD6", "light_vs": "storage.type: #0000FF", "hc_black": "storage.type: #569CD6" } }, { "c": ")", "t": "source.go punctuation.definition.end.bracket.round.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "client", "t": "source.go variable.other.assignment.go", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": ",", "t": "source.go punctuation.other.comma.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "err", "t": "source.go variable.other.assignment.go", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": ":=", "t": "source.go keyword.operator.assignment.go", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4" } }, { "c": " management", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": ".", "t": "source.go punctuation.other.period.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "ClientFromPublishSettingsFile", "t": "source.go support.function.go", "r": { "dark_plus": "support.function: #DCDCAA", "light_plus": "support.function: #795E26", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.function: #DCDCAA" } }, { "c": "(", "t": "source.go punctuation.definition.begin.bracket.round.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "\"", "t": "source.go string.quoted.double.go punctuation.definition.string.begin.go", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "path/to/downloaded.publishsettings", "t": "source.go string.quoted.double.go", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "\"", "t": "source.go string.quoted.double.go punctuation.definition.string.end.go", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": ",", "t": "source.go punctuation.other.comma.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "\"", "t": "source.go string.quoted.double.go punctuation.definition.string.begin.go", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "\"", "t": "source.go string.quoted.double.go punctuation.definition.string.end.go", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": ")", "t": "source.go punctuation.definition.end.bracket.round.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "if", "t": "source.go keyword.control.go", "r": { "dark_plus": "keyword.control: #C586C0", "light_plus": "keyword.control: #AF00DB", "dark_vs": "keyword.control: #569CD6", "light_vs": "keyword.control: #0000FF", "hc_black": "keyword.control: #C586C0" } }, { "c": " err ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "!=", "t": "source.go keyword.operator.comparison.go", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "nil", "t": "source.go constant.language.go", "r": { "dark_plus": "constant.language: #569CD6", "light_plus": "constant.language: #0000FF", "dark_vs": "constant.language: #569CD6", "light_vs": "constant.language: #0000FF", "hc_black": "constant.language: #569CD6" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "{", "t": "source.go punctuation.definition.begin.bracket.curly.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "panic", "t": "source.go support.function.builtin.go", "r": { "dark_plus": "support.function: #DCDCAA", "light_plus": "support.function: #795E26", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.function: #DCDCAA" } }, { "c": "(", "t": "source.go punctuation.definition.begin.bracket.round.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "err", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": ")", "t": "source.go punctuation.definition.end.bracket.round.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "}", "t": "source.go punctuation.definition.end.bracket.curly.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "//", "t": "source.go comment.line.double-slash.go punctuation.definition.comment.go", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668" } }, { "c": " create virtual machine", "t": "source.go comment.line.double-slash.go", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "role", "t": "source.go variable.other.assignment.go", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": ":=", "t": "source.go keyword.operator.assignment.go", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4" } }, { "c": " vmutils", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": ".", "t": "source.go punctuation.other.period.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "NewVMConfiguration", "t": "source.go support.function.go", "r": { "dark_plus": "support.function: #DCDCAA", "light_plus": "support.function: #795E26", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.function: #DCDCAA" } }, { "c": "(", "t": "source.go punctuation.definition.begin.bracket.round.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "dnsName", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": ",", "t": "source.go punctuation.other.comma.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": " vmSize", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": ")", "t": "source.go punctuation.definition.end.bracket.round.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": " vmutils", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": ".", "t": "source.go punctuation.other.period.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "ConfigureDeploymentFromPlatformImage", "t": "source.go support.function.go", "r": { "dark_plus": "support.function: #DCDCAA", "light_plus": "support.function: #795E26", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.function: #DCDCAA" } }, { "c": "(", "t": "source.go punctuation.definition.begin.bracket.round.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "&", "t": "source.go keyword.operator.address.go", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4" } }, { "c": "role", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": ",", "t": "source.go punctuation.other.comma.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": " vmImage", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": ",", "t": "source.go punctuation.other.comma.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": " fmt", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": ".", "t": "source.go punctuation.other.period.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "Sprintf", "t": "source.go support.function.go", "r": { "dark_plus": "support.function: #DCDCAA", "light_plus": "support.function: #795E26", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.function: #DCDCAA" } }, { "c": "(", "t": "source.go punctuation.definition.begin.bracket.round.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "\"", "t": "source.go string.quoted.double.go punctuation.definition.string.begin.go", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "http://", "t": "source.go string.quoted.double.go", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "%s", "t": "source.go string.quoted.double.go constant.other.placeholder.go", "r": { "dark_plus": "constant.other.placeholder: #9CDCFE", "light_plus": "constant.other.placeholder: #001080", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": ".blob.core.windows.net/sdktest/", "t": "source.go string.quoted.double.go", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "%s", "t": "source.go string.quoted.double.go constant.other.placeholder.go", "r": { "dark_plus": "constant.other.placeholder: #9CDCFE", "light_plus": "constant.other.placeholder: #001080", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": ".vhd", "t": "source.go string.quoted.double.go", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "\"", "t": "source.go string.quoted.double.go punctuation.definition.string.end.go", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": ",", "t": "source.go punctuation.other.comma.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": " storageAccount", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": ",", "t": "source.go punctuation.other.comma.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": " dnsName", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": ")", "t": "source.go punctuation.definition.end.bracket.round.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": ",", "t": "source.go punctuation.other.comma.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": " ", "t": "source.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "\"", "t": "source.go string.quoted.double.go punctuation.definition.string.begin.go", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "\"", "t": "source.go string.quoted.double.go punctuation.definition.string.end.go", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": ")", "t": "source.go punctuation.definition.end.bracket.round.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "}", "t": "source.go punctuation.definition.end.bracket.curly.go", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } } ]
extensions/vscode-colorize-tests/test/colorize-results/test_go.json
0
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.00017671025125309825, 0.0001737670536385849, 0.00017120693519245833, 0.00017368441331200302, 0.000001202401904265571 ]
{ "id": 4, "code_window": [ "\tlet hasPostedRenderedMathTelemetry = false;\n", "\tconst unsupportedKatexTermsRegex = /(\\\\(?:abovewithdelims|array|Arrowvert|arrowvert|atopwithdelims|bbox|bracevert|buildrel|cancelto|cases|class|cssId|ddddot|dddot|DeclareMathOperator|definecolor|displaylines|enclose|eqalign|eqalignno|eqref|hfil|hfill|idotsint|iiiint|label|leftarrowtail|leftroot|leqalignno|lower|mathtip|matrix|mbox|mit|mmlToken|moveleft|moveright|mspace|newenvironment|Newextarrow|notag|oldstyle|overparen|overwithdelims|pmatrix|raise|ref|renewenvironment|require|root|Rule|scr|shoveleft|shoveright|sideset|skew|Space|strut|style|texttip|Tiny|toggle|underparen|unicode|uproot)\\b)/gi;\n", "\n", "\tasync function updateMarkdownPreview(previewContainerNode: HTMLElement, cellId: string, content: string | undefined) {\n", "\t\tif (typeof content === 'string') {\n", "\t\t\tif (content.trim().length === 0) {\n", "\t\t\t\tpreviewContainerNode.classList.add('emptyMarkdownCell');\n", "\t\t\t\tpreviewContainerNode.innerText = '';\n", "\t\t\t} else {\n", "\t\t\t\tpreviewContainerNode.classList.remove('emptyMarkdownCell');\n", "\t\t\t\tawait renderers.render(createMarkdownOutputItem(cellId, previewContainerNode, content), previewContainerNode);\n", "\n", "\t\t\t\tif (!hasPostedRenderedMathTelemetry) {\n", "\t\t\t\t\tconst hasRenderedMath = previewContainerNode.querySelector('.katex');\n", "\t\t\t\t\tif (hasRenderedMath) {\n", "\t\t\t\t\t\thasPostedRenderedMathTelemetry = true;\n", "\t\t\t\t\t\tpostNotebookMessage<webviewMessages.ITelemetryFoundRenderedMarkdownMath>('telemetryFoundRenderedMarkdownMath', {});\n", "\t\t\t\t\t}\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads.ts", "type": "replace", "edit_start_line_idx": 1000 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IAction } from 'vs/base/common/actions'; import { coalesce } from 'vs/base/common/arrays'; import { VSBuffer } from 'vs/base/common/buffer'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable } from 'vs/base/common/lifecycle'; import { getExtensionForMimeType } from 'vs/base/common/mime'; import { FileAccess, Schemas } from 'vs/base/common/network'; import { isMacintosh, isWeb } from 'vs/base/common/platform'; import { dirname, joinPath } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import * as UUID from 'vs/base/common/uuid'; import * as nls from 'vs/nls'; import { createAndFillInContextMenuActions } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { IMenuService, MenuId } from 'vs/platform/actions/common/actions'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IFileDialogService } from 'vs/platform/dialogs/common/dialogs'; import { IFileService } from 'vs/platform/files/common/files'; import { IOpenerService, matchesScheme } from 'vs/platform/opener/common/opener'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { asWebviewUri } from 'vs/workbench/api/common/shared/webview'; import { CellEditState, ICellOutputViewModel, ICommonCellInfo, ICommonNotebookEditor, IDisplayOutputLayoutUpdateRequest, IDisplayOutputViewModel, IGenericCellViewModel, IInsetRenderOutput, RenderOutputType } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { preloadsScriptStr, RendererMetadata } from 'vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads'; import { transformWebviewThemeVars } from 'vs/workbench/contrib/notebook/browser/view/renderers/webviewThemeMapping'; import { MarkdownCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/markdownCellViewModel'; import { INotebookKernel, INotebookRendererInfo, RendererMessagingSpec } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { IScopedRendererMessaging } from 'vs/workbench/contrib/notebook/common/notebookRendererMessagingService'; import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService'; import { IWebviewService, WebviewContentPurpose, WebviewElement } from 'vs/workbench/contrib/webview/browser/webview'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { ICreationRequestMessage, IMarkdownCellInitialization, FromWebviewMessage, IClickedDataUrlMessage, IContentWidgetTopRequest, IControllerPreload, ToWebviewMessage } from './webviewMessages'; export interface ICachedInset<K extends ICommonCellInfo> { outputId: string; cellInfo: K; renderer?: INotebookRendererInfo; cachedCreation: ICreationRequestMessage; } function html(strings: TemplateStringsArray, ...values: any[]): string { let str = ''; strings.forEach((string, i) => { str += string + (values[i] || ''); }); return str; } export interface INotebookWebviewMessage { message: unknown; } export interface IResolvedBackLayerWebview { webview: WebviewElement; } export class BackLayerWebView<T extends ICommonCellInfo> extends Disposable { element: HTMLElement; webview: WebviewElement | undefined = undefined; insetMapping: Map<IDisplayOutputViewModel, ICachedInset<T>> = new Map(); readonly markdownPreviewMapping = new Map<string, IMarkdownCellInitialization>(); hiddenInsetMapping: Set<IDisplayOutputViewModel> = new Set(); reversedInsetMapping: Map<string, IDisplayOutputViewModel> = new Map(); localResourceRootsCache: URI[] | undefined = undefined; rendererRootsCache: URI[] = []; private readonly _onMessage = this._register(new Emitter<INotebookWebviewMessage>()); private readonly _preloadsCache = new Set<string>(); public readonly onMessage: Event<INotebookWebviewMessage> = this._onMessage.event; private _initalized?: Promise<void>; private _disposed = false; private _currentKernel?: INotebookKernel; constructor( public readonly notebookEditor: ICommonNotebookEditor, public readonly id: string, public readonly documentUri: URI, private options: { outputNodePadding: number, outputNodeLeftPadding: number, previewNodePadding: number, markdownLeftMargin: number, leftMargin: number, rightMargin: number, runGutter: number, dragAndDropEnabled: boolean, fontSize: number }, private readonly rendererMessaging: IScopedRendererMessaging | undefined, @IWebviewService readonly webviewService: IWebviewService, @IOpenerService readonly openerService: IOpenerService, @INotebookService private readonly notebookService: INotebookService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService, @IFileDialogService private readonly fileDialogService: IFileDialogService, @IFileService private readonly fileService: IFileService, @IContextMenuService private readonly contextMenuService: IContextMenuService, @IMenuService private readonly menuService: IMenuService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @ITelemetryService private readonly telemetryService: ITelemetryService, ) { super(); this.element = document.createElement('div'); this.element.style.height = '1400px'; this.element.style.position = 'absolute'; if (rendererMessaging) { this._register(rendererMessaging.onDidReceiveMessage(evt => { this._sendMessageToWebview({ __vscode_notebook_message: true, type: 'customRendererMessage', rendererId: evt.rendererId, message: evt.message }); })); } } updateOptions(options: { outputNodePadding: number, outputNodeLeftPadding: number, previewNodePadding: number, markdownLeftMargin: number, leftMargin: number, rightMargin: number, runGutter: number, dragAndDropEnabled: boolean, fontSize: number }) { this.options = options; this._updateStyles(); this._updateOptions(); } private _updateStyles() { this._sendMessageToWebview({ type: 'notebookStyles', styles: this._generateStyles() }); } private _updateOptions() { this._sendMessageToWebview({ type: 'notebookOptions', options: { dragAndDropEnabled: this.options.dragAndDropEnabled } }); } private _generateStyles() { return { 'notebook-output-left-margin': `${this.options.leftMargin + this.options.runGutter}px`, 'notebook-output-width': `calc(100% - ${this.options.leftMargin + this.options.rightMargin + this.options.runGutter}px)`, 'notebook-output-node-padding': `${this.options.outputNodePadding}px`, 'notebook-run-gutter': `${this.options.runGutter}px`, 'notebook-preivew-node-padding': `${this.options.previewNodePadding}px`, 'notebook-markdown-left-margin': `${this.options.markdownLeftMargin}px`, 'notebook-output-node-left-padding': `${this.options.outputNodeLeftPadding}px`, 'notebook-markdown-min-height': `${this.options.previewNodePadding * 2}px`, 'notebook-cell-output-font-size': `${this.options.fontSize}px` }; } private generateContent(coreDependencies: string, baseUrl: string) { const renderersData = this.getRendererData(); return html` <html lang="en"> <head> <meta charset="UTF-8"> <base href="${baseUrl}/"/> <style> #container .cell_container { width: 100%; } #container .output_container { width: 100%; } #container > div > div > div.output { font-size: var(--notebook-cell-output-font-size); width: var(--notebook-output-width); margin-left: var(--notebook-output-left-margin); padding-top: var(--notebook-output-node-padding); padding-right: var(--notebook-output-node-padding); padding-bottom: var(--notebook-output-node-padding); padding-left: var(--notebook-output-node-left-padding); box-sizing: border-box; background-color: var(--theme-notebook-output-background); } /* markdown */ #container > div.preview { width: 100%; padding-right: var(--notebook-preivew-node-padding); padding-left: var(--notebook-markdown-left-margin); padding-top: var(--notebook-preivew-node-padding); padding-bottom: var(--notebook-preivew-node-padding); box-sizing: border-box; white-space: nowrap; overflow: hidden; white-space: initial; color: var(--theme-ui-foreground); } #container > div.preview.draggable { user-select: none; -webkit-user-select: none; -ms-user-select: none; cursor: grab; } #container > div.preview.emptyMarkdownCell::before { content: "${nls.localize('notebook.emptyMarkdownPlaceholder', "Empty markdown cell, double click or press enter to edit.")}"; font-style: italic; opacity: 0.6; } #container > div.preview.selected { background: var(--theme-notebook-cell-selected-background); } #container > div.preview.dragging { background-color: var(--theme-background); } .monaco-workbench.vs-dark .notebookOverlay .cell.markdown .latex img, .monaco-workbench.vs-dark .notebookOverlay .cell.markdown .latex-block img { filter: brightness(0) invert(1) } #container > div.nb-symbolHighlight { background-color: var(--theme-notebook-symbol-highlight-background); } #container > div.nb-cellDeleted { background-color: var(--theme-notebook-diff-removed-background); } #container > div.nb-cellAdded { background-color: var(--theme-notebook-diff-inserted-background); } #container > div > div:not(.preview) > div { overflow-x: scroll; } body { padding: 0px; height: 100%; width: 100%; } table, thead, tr, th, td, tbody { border: none !important; border-color: transparent; border-spacing: 0; border-collapse: collapse; } table { width: 100%; } table, th, tr { text-align: left !important; } thead { font-weight: bold; background-color: rgba(130, 130, 130, 0.16); } th, td { padding: 4px 8px; } tr:nth-child(even) { background-color: rgba(130, 130, 130, 0.08); } tbody th { font-weight: normal; } </style> </head> <body style="overflow: hidden;"> <script> self.require = {}; </script> ${coreDependencies} <div id='container' class="widgetarea" style="position: absolute;width:100%;top: 0px"></div> <script type="module">${preloadsScriptStr(this.options, { dragAndDropEnabled: this.options.dragAndDropEnabled }, renderersData)}</script> </body> </html>`; } private getRendererData(): RendererMetadata[] { return this.notebookService.getRenderers().map((renderer): RendererMetadata => { const entrypoint = this.asWebviewUri(renderer.entrypoint, renderer.extensionLocation).toString(); return { id: renderer.id, entrypoint, mimeTypes: renderer.mimeTypes, extends: renderer.extends, messaging: renderer.messaging !== RendererMessagingSpec.Never, }; }); } private asWebviewUri(uri: URI, fromExtension: URI | undefined) { return asWebviewUri(uri, fromExtension?.scheme === Schemas.vscodeRemote ? { isRemote: true, authority: fromExtension.authority } : undefined); } postKernelMessage(message: any) { this._sendMessageToWebview({ __vscode_notebook_message: true, type: 'customKernelMessage', message, }); } private resolveOutputId(id: string): { cellInfo: T, output: ICellOutputViewModel } | undefined { const output = this.reversedInsetMapping.get(id); if (!output) { return; } const cellInfo = this.insetMapping.get(output)!.cellInfo; return { cellInfo, output }; } isResolved(): this is IResolvedBackLayerWebview { return !!this.webview; } async createWebview(): Promise<void> { const baseUrl = this.asWebviewUri(dirname(this.documentUri), undefined); // Python hasn't moved to use a preload to load require support yet. // For all other notebooks, we no longer want to include our loader. if (!this.documentUri.path.toLowerCase().endsWith('.ipynb')) { const htmlContent = this.generateContent('', baseUrl.toString()); this._initialize(htmlContent); return; } let coreDependencies = ''; let resolveFunc: () => void; this._initalized = new Promise<void>((resolve, reject) => { resolveFunc = resolve; }); if (!isWeb) { const loaderUri = FileAccess.asFileUri('vs/loader.js', require); const loader = this.asWebviewUri(loaderUri, undefined); coreDependencies = `<script src="${loader}"></script><script> var requirejs = (function() { return require; }()); </script>`; const htmlContent = this.generateContent(coreDependencies, baseUrl.toString()); this._initialize(htmlContent); resolveFunc!(); } else { const loaderUri = FileAccess.asBrowserUri('vs/loader.js', require); fetch(loaderUri.toString(true)).then(async response => { if (response.status !== 200) { throw new Error(response.statusText); } const loaderJs = await response.text(); coreDependencies = ` <script> ${loaderJs} </script> <script> var requirejs = (function() { return require; }()); </script> `; const htmlContent = this.generateContent(coreDependencies, baseUrl.toString()); this._initialize(htmlContent); resolveFunc!(); }, error => { // the fetch request is rejected const htmlContent = this.generateContent(coreDependencies, baseUrl.toString()); this._initialize(htmlContent); resolveFunc!(); }); } await this._initalized; } private _initialize(content: string) { if (!document.body.contains(this.element)) { throw new Error('Element is already detached from the DOM tree'); } this.webview = this._createInset(this.webviewService, content); this.webview.mountTo(this.element); this._register(this.webview); this._register(this.webview.onDidClickLink(link => { if (this._disposed) { return; } if (!link) { return; } if (matchesScheme(link, Schemas.command)) { console.warn('Command links are deprecated and will be removed, use messag passing instead: https://github.com/microsoft/vscode/issues/123601'); } if (matchesScheme(link, Schemas.http) || matchesScheme(link, Schemas.https) || matchesScheme(link, Schemas.mailto) || matchesScheme(link, Schemas.command)) { this.openerService.open(link, { fromUserGesture: true, allowContributedOpeners: true, allowCommands: true }); } })); this._register(this.webview.onMessage((message) => { const data: FromWebviewMessage | { readonly __vscode_notebook_message: undefined } = message.message; if (this._disposed) { return; } if (!data.__vscode_notebook_message) { return; } switch (data.type) { case 'initialized': this.initializeWebViewState(); break; case 'dimension': { for (const update of data.updates) { const height = update.height; if (update.isOutput) { const resolvedResult = this.resolveOutputId(update.id); if (resolvedResult) { const { cellInfo, output } = resolvedResult; this.notebookEditor.updateOutputHeight(cellInfo, output, height, !!update.init, 'webview#dimension'); this.notebookEditor.scheduleOutputHeightAck(cellInfo, update.id, height); } } else { this.notebookEditor.updateMarkdownCellHeight(update.id, height, !!update.init); } } break; } case 'mouseenter': { const resolvedResult = this.resolveOutputId(data.id); if (resolvedResult) { const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo); if (latestCell) { latestCell.outputIsHovered = true; } } break; } case 'mouseleave': { const resolvedResult = this.resolveOutputId(data.id); if (resolvedResult) { const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo); if (latestCell) { latestCell.outputIsHovered = false; } } break; } case 'outputFocus': { const resolvedResult = this.resolveOutputId(data.id); if (resolvedResult) { const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo); if (latestCell) { latestCell.outputIsFocused = true; } } break; } case 'outputBlur': { const resolvedResult = this.resolveOutputId(data.id); if (resolvedResult) { const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo); if (latestCell) { latestCell.outputIsFocused = false; } } break; } case 'scroll-ack': { // const date = new Date(); // const top = data.data.top; // console.log('ack top ', top, ' version: ', data.version, ' - ', date.getMinutes() + ':' + date.getSeconds() + ':' + date.getMilliseconds()); break; } case 'did-scroll-wheel': { this.notebookEditor.triggerScroll({ ...data.payload, preventDefault: () => { }, stopPropagation: () => { } }); break; } case 'focus-editor': { const resolvedResult = this.resolveOutputId(data.id); if (resolvedResult) { const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo); if (!latestCell) { return; } if (data.focusNext) { this.notebookEditor.focusNextNotebookCell(latestCell, 'editor'); } else { this.notebookEditor.focusNotebookCell(latestCell, 'editor'); } } break; } case 'clicked-data-url': { this._onDidClickDataLink(data); break; } case 'customKernelMessage': { this._onMessage.fire({ message: data.message }); break; } case 'customRendererMessage': { this.rendererMessaging?.postMessage(data.rendererId, data.message); break; } case 'clickMarkdownPreview': { const cell = this.notebookEditor.getCellById(data.cellId); if (cell) { if (data.shiftKey || (isMacintosh ? data.metaKey : data.ctrlKey)) { // Modify selection this.notebookEditor.toggleNotebookCellSelection(cell, /* fromPrevious */ data.shiftKey); } else { // Normal click this.notebookEditor.focusNotebookCell(cell, 'container', { skipReveal: true }); } } break; } case 'contextMenuMarkdownPreview': { const cell = this.notebookEditor.getCellById(data.cellId); if (cell) { // Focus the cell first this.notebookEditor.focusNotebookCell(cell, 'container', { skipReveal: true }); // Then show the context menu const webviewRect = this.element.getBoundingClientRect(); this.contextMenuService.showContextMenu({ getActions: () => { const result: IAction[] = []; const menu = this.menuService.createMenu(MenuId.NotebookCellTitle, this.contextKeyService); createAndFillInContextMenuActions(menu, undefined, result); menu.dispose(); return result; }, getAnchor: () => ({ x: webviewRect.x + data.clientX, y: webviewRect.y + data.clientY }) }); } break; } case 'toggleMarkdownPreview': { const cell = this.notebookEditor.getCellById(data.cellId); if (cell) { this.notebookEditor.setMarkdownCellEditState(data.cellId, CellEditState.Editing); this.notebookEditor.focusNotebookCell(cell, 'editor', { skipReveal: true }); } break; } case 'mouseEnterMarkdownPreview': { const cell = this.notebookEditor.getCellById(data.cellId); if (cell instanceof MarkdownCellViewModel) { cell.cellIsHovered = true; } break; } case 'mouseLeaveMarkdownPreview': { const cell = this.notebookEditor.getCellById(data.cellId); if (cell instanceof MarkdownCellViewModel) { cell.cellIsHovered = false; } break; } case 'cell-drag-start': { this.notebookEditor.markdownCellDragStart(data.cellId, data); break; } case 'cell-drag': { this.notebookEditor.markdownCellDrag(data.cellId, data); break; } case 'cell-drop': { this.notebookEditor.markdownCellDrop(data.cellId, { dragOffsetY: data.dragOffsetY, ctrlKey: data.ctrlKey, altKey: data.altKey, }); break; } case 'cell-drag-end': { this.notebookEditor.markdownCellDragEnd(data.cellId); break; } case 'telemetryFoundRenderedMarkdownMath': { this.telemetryService.publicLog2<{}, {}>('notebook/markdown/renderedLatex', {}); break; } case 'telemetryFoundUnrenderedMarkdownMath': { type Classification = { latexDirective: { classification: 'SystemMetaData', purpose: 'FeatureInsight'; }; }; type TelemetryEvent = { latexDirective: string; }; this.telemetryService.publicLog2<TelemetryEvent, Classification>('notebook/markdown/foundUnrenderedLatex', { latexDirective: data.latexDirective }); break; } } })); } private async _onDidClickDataLink(event: IClickedDataUrlMessage): Promise<void> { if (typeof event.data !== 'string') { return; } const [splitStart, splitData] = event.data.split(';base64,'); if (!splitData || !splitStart) { return; } const defaultDir = dirname(this.documentUri); let defaultName: string; if (event.downloadName) { defaultName = event.downloadName; } else { const mimeType = splitStart.replace(/^data:/, ''); const candidateExtension = mimeType && getExtensionForMimeType(mimeType); defaultName = candidateExtension ? `download${candidateExtension}` : 'download'; } const defaultUri = joinPath(defaultDir, defaultName); const newFileUri = await this.fileDialogService.showSaveDialog({ defaultUri }); if (!newFileUri) { return; } const decoded = atob(splitData); const typedArray = new Uint8Array(decoded.length); for (let i = 0; i < decoded.length; i++) { typedArray[i] = decoded.charCodeAt(i); } const buff = VSBuffer.wrap(typedArray); await this.fileService.writeFile(newFileUri, buff); await this.openerService.open(newFileUri); } private _createInset(webviewService: IWebviewService, content: string) { const rootPath = isWeb ? FileAccess.asBrowserUri('', require) : FileAccess.asFileUri('', require); const workspaceFolders = this.contextService.getWorkspace().folders.map(x => x.uri); this.localResourceRootsCache = [ ...this.notebookService.getNotebookProviderResourceRoots(), ...this.notebookService.getRenderers().map(x => dirname(x.entrypoint)), ...workspaceFolders, rootPath, ]; const webview = webviewService.createWebviewElement(this.id, { purpose: WebviewContentPurpose.NotebookRenderer, enableFindWidget: false, transformCssVariables: transformWebviewThemeVars, }, { allowMultipleAPIAcquire: true, allowScripts: true, localResourceRoots: this.localResourceRootsCache, }, undefined); webview.html = content; return webview; } private initializeWebViewState() { const renderers = new Set<INotebookRendererInfo>(); for (const inset of this.insetMapping.values()) { if (inset.renderer) { renderers.add(inset.renderer); } } this._preloadsCache.clear(); if (this._currentKernel) { this._updatePreloadsFromKernel(this._currentKernel); } for (const [output, inset] of this.insetMapping.entries()) { this._sendMessageToWebview({ ...inset.cachedCreation, initiallyHidden: this.hiddenInsetMapping.has(output) }); } const mdCells = [...this.markdownPreviewMapping.values()]; this.markdownPreviewMapping.clear(); this.initializeMarkdown(mdCells); this._updateStyles(); this._updateOptions(); } private shouldUpdateInset(cell: IGenericCellViewModel, output: ICellOutputViewModel, cellTop: number, outputOffset: number): boolean { if (this._disposed) { return false; } if (cell.metadata.outputCollapsed) { return false; } if (this.hiddenInsetMapping.has(output)) { return true; } const outputCache = this.insetMapping.get(output); if (!outputCache) { return false; } if (outputOffset === outputCache.cachedCreation.outputOffset && cellTop === outputCache.cachedCreation.cellTop) { return false; } return true; } ackHeight(cellId: string, id: string, height: number): void { this._sendMessageToWebview({ type: 'ack-dimension', cellId: cellId, outputId: id, height: height }); } updateScrollTops(outputRequests: IDisplayOutputLayoutUpdateRequest[], markdownPreviews: { id: string, top: number }[]) { if (this._disposed) { return; } const widgets = coalesce(outputRequests.map((request): IContentWidgetTopRequest | undefined => { const outputCache = this.insetMapping.get(request.output); if (!outputCache) { return; } if (!request.forceDisplay && !this.shouldUpdateInset(request.cell, request.output, request.cellTop, request.outputOffset)) { return; } const id = outputCache.outputId; outputCache.cachedCreation.cellTop = request.cellTop; outputCache.cachedCreation.outputOffset = request.outputOffset; this.hiddenInsetMapping.delete(request.output); return { outputId: id, cellTop: request.cellTop, outputOffset: request.outputOffset, forceDisplay: request.forceDisplay, }; })); if (!widgets.length && !markdownPreviews.length) { return; } this._sendMessageToWebview({ type: 'view-scroll', widgets: widgets, markdownPreviews, }); } private async createMarkdownPreview(initialization: IMarkdownCellInitialization) { if (this._disposed) { return; } if (this.markdownPreviewMapping.has(initialization.cellId)) { console.error('Trying to create markdown preview that already exists'); return; } this.markdownPreviewMapping.set(initialization.cellId, initialization); this._sendMessageToWebview({ type: 'createMarkupCell', cell: initialization }); } async showMarkdownPreview(initialization: IMarkdownCellInitialization) { if (this._disposed) { return; } const entry = this.markdownPreviewMapping.get(initialization.cellId); if (!entry) { return this.createMarkdownPreview(initialization); } const sameContent = initialization.content === entry.content; if (!sameContent || !entry.visible) { this._sendMessageToWebview({ type: 'showMarkupCell', id: initialization.cellId, handle: initialization.cellHandle, // If the content has not changed, we still want to make sure the // preview is visible but don't need to send anything over content: sameContent ? undefined : initialization.content, top: initialization.offset }); } entry.content = initialization.content; entry.offset = initialization.offset; entry.visible = true; } async hideMarkdownPreviews(cellIds: readonly string[]) { if (this._disposed) { return; } const cellsToHide: string[] = []; for (const cellId of cellIds) { const entry = this.markdownPreviewMapping.get(cellId); if (entry) { if (entry.visible) { cellsToHide.push(cellId); entry.visible = false; } } } if (cellsToHide.length) { this._sendMessageToWebview({ type: 'hideMarkupCells', ids: cellsToHide }); } } async unhideMarkdownPreviews(cellIds: readonly string[]) { if (this._disposed) { return; } const toUnhide: string[] = []; for (const cellId of cellIds) { const entry = this.markdownPreviewMapping.get(cellId); if (entry) { if (!entry.visible) { entry.visible = true; toUnhide.push(cellId); } } else { console.error(`Trying to unhide a preview that does not exist: ${cellId}`); } } this._sendMessageToWebview({ type: 'unhideMarkupCells', ids: toUnhide, }); } async deleteMarkdownPreviews(cellIds: readonly string[]) { if (this._disposed) { return; } for (const id of cellIds) { if (!this.markdownPreviewMapping.has(id)) { console.error(`Trying to delete a preview that does not exist: ${id}`); } this.markdownPreviewMapping.delete(id); } if (cellIds.length) { this._sendMessageToWebview({ type: 'deleteMarkupCell', ids: cellIds }); } } async updateMarkdownPreviewSelections(selectedCellsIds: string[]) { if (this._disposed) { return; } this._sendMessageToWebview({ type: 'updateSelectedMarkupCells', selectedCellIds: selectedCellsIds.filter(id => this.markdownPreviewMapping.has(id)), }); } async initializeMarkdown(cells: ReadonlyArray<IMarkdownCellInitialization>) { if (this._disposed) { return; } // TODO: use proper handler const p = new Promise<void>(resolve => { this.webview?.onMessage(e => { if (e.message.type === 'initializedMarkdownPreview') { resolve(); } }); }); for (const cell of cells) { this.markdownPreviewMapping.set(cell.cellId, { ...cell, visible: false }); } this._sendMessageToWebview({ type: 'initializeMarkup', cells, }); await p; } async createOutput(cellInfo: T, content: IInsetRenderOutput, cellTop: number, offset: number) { if (this._disposed) { return; } if (this.insetMapping.has(content.source)) { const outputCache = this.insetMapping.get(content.source); if (outputCache) { this.hiddenInsetMapping.delete(content.source); this._sendMessageToWebview({ type: 'showOutput', cellId: outputCache.cellInfo.cellId, outputId: outputCache.outputId, cellTop: cellTop, outputOffset: offset }); return; } } const messageBase = { type: 'html', cellId: cellInfo.cellId, cellTop: cellTop, outputOffset: offset, left: 0, requiredPreloads: [], } as const; let message: ICreationRequestMessage; let renderer: INotebookRendererInfo | undefined; if (content.type === RenderOutputType.Extension) { const output = content.source.model; renderer = content.renderer; const outputDto = output.outputs.find(op => op.mime === content.mimeType); // TODO@notebook - the message can contain "bytes" and those are transferable // which improves IPC performance and therefore should be used. However, it does // means that the bytes cannot be used here anymore message = { ...messageBase, outputId: output.outputId, rendererId: content.renderer.id, content: { type: RenderOutputType.Extension, outputId: output.outputId, mimeType: content.mimeType, valueBytes: new Uint8Array(outputDto?.valueBytes ?? []), metadata: output.metadata, metadata2: output.metadata }, }; } else { message = { ...messageBase, outputId: UUID.generateUuid(), content: { type: content.type, htmlContent: content.htmlContent, } }; } this._sendMessageToWebview(message); this.insetMapping.set(content.source, { outputId: message.outputId, cellInfo: cellInfo, renderer, cachedCreation: message }); this.hiddenInsetMapping.delete(content.source); this.reversedInsetMapping.set(message.outputId, content.source); } removeInsets(outputs: readonly ICellOutputViewModel[]) { if (this._disposed) { return; } for (const output of outputs) { const outputCache = this.insetMapping.get(output); if (!outputCache) { continue; } const id = outputCache.outputId; this._sendMessageToWebview({ type: 'clearOutput', rendererId: outputCache.cachedCreation.rendererId, cellUri: outputCache.cellInfo.cellUri.toString(), outputId: id, cellId: outputCache.cellInfo.cellId }); this.insetMapping.delete(output); this.reversedInsetMapping.delete(id); } } hideInset(output: ICellOutputViewModel) { if (this._disposed) { return; } const outputCache = this.insetMapping.get(output); if (!outputCache) { return; } this.hiddenInsetMapping.add(output); this._sendMessageToWebview({ type: 'hideOutput', outputId: outputCache.outputId, cellId: outputCache.cellInfo.cellId, }); } clearInsets() { if (this._disposed) { return; } this._sendMessageToWebview({ type: 'clear' }); this.insetMapping = new Map(); this.reversedInsetMapping = new Map(); } focusWebview() { if (this._disposed) { return; } this.webview?.focus(); } focusOutput(cellId: string) { if (this._disposed) { return; } this.webview?.focus(); setTimeout(() => { // Need this, or focus decoration is not shown. No clue. this._sendMessageToWebview({ type: 'focus-output', cellId, }); }, 50); } deltaCellOutputContainerClassNames(cellId: string, added: string[], removed: string[]) { this._sendMessageToWebview({ type: 'decorations', cellId, addedClassNames: added, removedClassNames: removed }); } async updateKernelPreloads(kernel: INotebookKernel | undefined) { if (this._disposed || kernel === this._currentKernel) { return; } const previousKernel = this._currentKernel; this._currentKernel = kernel; if (previousKernel && previousKernel.preloadUris.length > 0) { this.webview?.reload(); // preloads will be restored after reload } else if (kernel) { this._updatePreloadsFromKernel(kernel); } } private _updatePreloadsFromKernel(kernel: INotebookKernel) { const resources: IControllerPreload[] = []; for (const preload of kernel.preloadUris) { const uri = this.environmentService.isExtensionDevelopment && (preload.scheme === 'http' || preload.scheme === 'https') ? preload : this.asWebviewUri(preload, undefined); if (!this._preloadsCache.has(uri.toString())) { resources.push({ uri: uri.toString(), originalUri: preload.toString() }); this._preloadsCache.add(uri.toString()); } } if (!resources.length) { return; } this._updatePreloads(resources); } private _updatePreloads(resources: IControllerPreload[]) { if (!this.webview) { return; } const mixedResourceRoots = [ ...(this.localResourceRootsCache || []), ...this.rendererRootsCache, ...(this._currentKernel ? [this._currentKernel.localResourceRoot] : []), ]; this.webview.localResourcesRoot = mixedResourceRoots; this._sendMessageToWebview({ type: 'preload', resources: resources, }); } private _sendMessageToWebview(message: ToWebviewMessage) { if (this._disposed) { return; } this.webview?.postMessage(message); } clearPreloadsCache() { this._preloadsCache.clear(); } override dispose() { this._disposed = true; this.webview?.dispose(); super.dispose(); } }
src/vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView.ts
1
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.9157720804214478, 0.9157719612121582, 0.9157719016075134, 0.9157720804214478, 1.0926778060138531e-7 ]
{ "id": 4, "code_window": [ "\tlet hasPostedRenderedMathTelemetry = false;\n", "\tconst unsupportedKatexTermsRegex = /(\\\\(?:abovewithdelims|array|Arrowvert|arrowvert|atopwithdelims|bbox|bracevert|buildrel|cancelto|cases|class|cssId|ddddot|dddot|DeclareMathOperator|definecolor|displaylines|enclose|eqalign|eqalignno|eqref|hfil|hfill|idotsint|iiiint|label|leftarrowtail|leftroot|leqalignno|lower|mathtip|matrix|mbox|mit|mmlToken|moveleft|moveright|mspace|newenvironment|Newextarrow|notag|oldstyle|overparen|overwithdelims|pmatrix|raise|ref|renewenvironment|require|root|Rule|scr|shoveleft|shoveright|sideset|skew|Space|strut|style|texttip|Tiny|toggle|underparen|unicode|uproot)\\b)/gi;\n", "\n", "\tasync function updateMarkdownPreview(previewContainerNode: HTMLElement, cellId: string, content: string | undefined) {\n", "\t\tif (typeof content === 'string') {\n", "\t\t\tif (content.trim().length === 0) {\n", "\t\t\t\tpreviewContainerNode.classList.add('emptyMarkdownCell');\n", "\t\t\t\tpreviewContainerNode.innerText = '';\n", "\t\t\t} else {\n", "\t\t\t\tpreviewContainerNode.classList.remove('emptyMarkdownCell');\n", "\t\t\t\tawait renderers.render(createMarkdownOutputItem(cellId, previewContainerNode, content), previewContainerNode);\n", "\n", "\t\t\t\tif (!hasPostedRenderedMathTelemetry) {\n", "\t\t\t\t\tconst hasRenderedMath = previewContainerNode.querySelector('.katex');\n", "\t\t\t\t\tif (hasRenderedMath) {\n", "\t\t\t\t\t\thasPostedRenderedMathTelemetry = true;\n", "\t\t\t\t\t\tpostNotebookMessage<webviewMessages.ITelemetryFoundRenderedMarkdownMath>('telemetryFoundRenderedMarkdownMath', {});\n", "\t\t\t\t\t}\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads.ts", "type": "replace", "edit_start_line_idx": 1000 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Suite, Context } from 'mocha'; export function describeRepeat(n: number, description: string, callback: (this: Suite) => void): void { for (let i = 0; i < n; i++) { describe(`${description} (iteration ${i})`, callback); } } export function itRepeat(n: number, description: string, callback: (this: Context) => any): void { for (let i = 0; i < n; i++) { it(`${description} (iteration ${i})`, callback); } }
test/smoke/src/utils.ts
0
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.9157726168632507, 0.9157726168632507, 0.9157726168632507, 0.9157726168632507, 0 ]
{ "id": 4, "code_window": [ "\tlet hasPostedRenderedMathTelemetry = false;\n", "\tconst unsupportedKatexTermsRegex = /(\\\\(?:abovewithdelims|array|Arrowvert|arrowvert|atopwithdelims|bbox|bracevert|buildrel|cancelto|cases|class|cssId|ddddot|dddot|DeclareMathOperator|definecolor|displaylines|enclose|eqalign|eqalignno|eqref|hfil|hfill|idotsint|iiiint|label|leftarrowtail|leftroot|leqalignno|lower|mathtip|matrix|mbox|mit|mmlToken|moveleft|moveright|mspace|newenvironment|Newextarrow|notag|oldstyle|overparen|overwithdelims|pmatrix|raise|ref|renewenvironment|require|root|Rule|scr|shoveleft|shoveright|sideset|skew|Space|strut|style|texttip|Tiny|toggle|underparen|unicode|uproot)\\b)/gi;\n", "\n", "\tasync function updateMarkdownPreview(previewContainerNode: HTMLElement, cellId: string, content: string | undefined) {\n", "\t\tif (typeof content === 'string') {\n", "\t\t\tif (content.trim().length === 0) {\n", "\t\t\t\tpreviewContainerNode.classList.add('emptyMarkdownCell');\n", "\t\t\t\tpreviewContainerNode.innerText = '';\n", "\t\t\t} else {\n", "\t\t\t\tpreviewContainerNode.classList.remove('emptyMarkdownCell');\n", "\t\t\t\tawait renderers.render(createMarkdownOutputItem(cellId, previewContainerNode, content), previewContainerNode);\n", "\n", "\t\t\t\tif (!hasPostedRenderedMathTelemetry) {\n", "\t\t\t\t\tconst hasRenderedMath = previewContainerNode.querySelector('.katex');\n", "\t\t\t\t\tif (hasRenderedMath) {\n", "\t\t\t\t\t\thasPostedRenderedMathTelemetry = true;\n", "\t\t\t\t\t\tpostNotebookMessage<webviewMessages.ITelemetryFoundRenderedMarkdownMath>('telemetryFoundRenderedMarkdownMath', {});\n", "\t\t\t\t\t}\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads.ts", "type": "replace", "edit_start_line_idx": 1000 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { Keybinding } from 'vs/base/common/keyCodes'; import { OS } from 'vs/base/common/platform'; import { URI } from 'vs/base/common/uri'; import { IModelService } from 'vs/editor/common/services/modelService'; import { ModelServiceImpl } from 'vs/editor/common/services/modelServiceImpl'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { USLayoutResolvedKeybinding } from 'vs/platform/keybinding/common/usLayoutResolvedKeybinding'; import { IFileMatch } from 'vs/workbench/services/search/common/search'; import { ReplaceAction } from 'vs/workbench/contrib/search/browser/searchActions'; import { FileMatch, FileMatchOrMatch, Match } from 'vs/workbench/contrib/search/common/searchModel'; import { MockObjectTree } from 'vs/workbench/contrib/search/test/browser/mockSearchTree'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { TestThemeService } from 'vs/platform/theme/test/common/testThemeService'; suite('Search Actions', () => { let instantiationService: TestInstantiationService; let counter: number; setup(() => { instantiationService = new TestInstantiationService(); instantiationService.stub(IModelService, stubModelService(instantiationService)); instantiationService.stub(IKeybindingService, {}); instantiationService.stub(IKeybindingService, 'resolveKeybinding', (keybinding: Keybinding) => [new USLayoutResolvedKeybinding(keybinding, OS)]); instantiationService.stub(IKeybindingService, 'lookupKeybinding', (id: string) => null); counter = 0; }); test('get next element to focus after removing a match when it has next sibling file', function () { const fileMatch1 = aFileMatch(); const fileMatch2 = aFileMatch(); const data = [fileMatch1, aMatch(fileMatch1), aMatch(fileMatch1), fileMatch2, aMatch(fileMatch2), aMatch(fileMatch2)]; const tree = aTree(data); const target = data[2]; const testObject: ReplaceAction = instantiationService.createInstance(ReplaceAction, tree, target, null); const actual = testObject.getElementToFocusAfterRemoved(tree, target); assert.strictEqual(data[4], actual); }); test('get next element to focus after removing a match when it does not have next sibling match', function () { const fileMatch1 = aFileMatch(); const fileMatch2 = aFileMatch(); const data = [fileMatch1, aMatch(fileMatch1), aMatch(fileMatch1), fileMatch2, aMatch(fileMatch2), aMatch(fileMatch2)]; const tree = aTree(data); const target = data[5]; const testObject: ReplaceAction = instantiationService.createInstance(ReplaceAction, tree, target, null); const actual = testObject.getElementToFocusAfterRemoved(tree, target); assert.strictEqual(data[4], actual); }); test('get next element to focus after removing a match when it does not have next sibling match and previous match is file match', function () { const fileMatch1 = aFileMatch(); const fileMatch2 = aFileMatch(); const data = [fileMatch1, aMatch(fileMatch1), aMatch(fileMatch1), fileMatch2, aMatch(fileMatch2)]; const tree = aTree(data); const target = data[4]; const testObject: ReplaceAction = instantiationService.createInstance(ReplaceAction, tree, target, null); const actual = testObject.getElementToFocusAfterRemoved(tree, target); assert.strictEqual(data[2], actual); }); test('get next element to focus after removing a match when it is the only match', function () { const fileMatch1 = aFileMatch(); const data = [fileMatch1, aMatch(fileMatch1)]; const tree = aTree(data); const target = data[1]; const testObject: ReplaceAction = instantiationService.createInstance(ReplaceAction, tree, target, null); const actual = testObject.getElementToFocusAfterRemoved(tree, target); assert.strictEqual(undefined, actual); }); test('get next element to focus after removing a file match when it has next sibling', function () { const fileMatch1 = aFileMatch(); const fileMatch2 = aFileMatch(); const fileMatch3 = aFileMatch(); const data = [fileMatch1, aMatch(fileMatch1), fileMatch2, aMatch(fileMatch2), fileMatch3, aMatch(fileMatch3)]; const tree = aTree(data); const target = data[2]; const testObject: ReplaceAction = instantiationService.createInstance(ReplaceAction, tree, target, null); const actual = testObject.getElementToFocusAfterRemoved(tree, target); assert.strictEqual(data[4], actual); }); test('get next element to focus after removing a file match when it has no next sibling', function () { const fileMatch1 = aFileMatch(); const fileMatch2 = aFileMatch(); const fileMatch3 = aFileMatch(); const data = [fileMatch1, aMatch(fileMatch1), fileMatch2, aMatch(fileMatch2), fileMatch3, aMatch(fileMatch3)]; const tree = aTree(data); const target = data[4]; const testObject: ReplaceAction = instantiationService.createInstance(ReplaceAction, tree, target, null); const actual = testObject.getElementToFocusAfterRemoved(tree, target); assert.strictEqual(data[3], actual); }); test('get next element to focus after removing a file match when it is only match', function () { const fileMatch1 = aFileMatch(); const data = [fileMatch1, aMatch(fileMatch1)]; const tree = aTree(data); const target = data[0]; const testObject: ReplaceAction = instantiationService.createInstance(ReplaceAction, tree, target, null); const actual = testObject.getElementToFocusAfterRemoved(tree, target); assert.strictEqual(undefined, actual); }); function aFileMatch(): FileMatch { const rawMatch: IFileMatch = { resource: URI.file('somepath' + ++counter), results: [] }; return instantiationService.createInstance(FileMatch, null, null, null, null, rawMatch); } function aMatch(fileMatch: FileMatch): Match { const line = ++counter; const match = new Match( fileMatch, ['some match'], { startLineNumber: 0, startColumn: 0, endLineNumber: 0, endColumn: 2 }, { startLineNumber: line, startColumn: 0, endLineNumber: line, endColumn: 2 } ); fileMatch.add(match); return match; } function aTree(elements: FileMatchOrMatch[]): any { return new MockObjectTree(elements); } function stubModelService(instantiationService: TestInstantiationService): IModelService { instantiationService.stub(IConfigurationService, new TestConfigurationService()); instantiationService.stub(IThemeService, new TestThemeService()); return instantiationService.createInstance(ModelServiceImpl); } });
src/vs/workbench/contrib/search/test/browser/searchActions.test.ts
0
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.9157720804214478, 0.9157720804214478, 0.9157720804214478, 0.9157720804214478, 0 ]
{ "id": 4, "code_window": [ "\tlet hasPostedRenderedMathTelemetry = false;\n", "\tconst unsupportedKatexTermsRegex = /(\\\\(?:abovewithdelims|array|Arrowvert|arrowvert|atopwithdelims|bbox|bracevert|buildrel|cancelto|cases|class|cssId|ddddot|dddot|DeclareMathOperator|definecolor|displaylines|enclose|eqalign|eqalignno|eqref|hfil|hfill|idotsint|iiiint|label|leftarrowtail|leftroot|leqalignno|lower|mathtip|matrix|mbox|mit|mmlToken|moveleft|moveright|mspace|newenvironment|Newextarrow|notag|oldstyle|overparen|overwithdelims|pmatrix|raise|ref|renewenvironment|require|root|Rule|scr|shoveleft|shoveright|sideset|skew|Space|strut|style|texttip|Tiny|toggle|underparen|unicode|uproot)\\b)/gi;\n", "\n", "\tasync function updateMarkdownPreview(previewContainerNode: HTMLElement, cellId: string, content: string | undefined) {\n", "\t\tif (typeof content === 'string') {\n", "\t\t\tif (content.trim().length === 0) {\n", "\t\t\t\tpreviewContainerNode.classList.add('emptyMarkdownCell');\n", "\t\t\t\tpreviewContainerNode.innerText = '';\n", "\t\t\t} else {\n", "\t\t\t\tpreviewContainerNode.classList.remove('emptyMarkdownCell');\n", "\t\t\t\tawait renderers.render(createMarkdownOutputItem(cellId, previewContainerNode, content), previewContainerNode);\n", "\n", "\t\t\t\tif (!hasPostedRenderedMathTelemetry) {\n", "\t\t\t\t\tconst hasRenderedMath = previewContainerNode.querySelector('.katex');\n", "\t\t\t\t\tif (hasRenderedMath) {\n", "\t\t\t\t\t\thasPostedRenderedMathTelemetry = true;\n", "\t\t\t\t\t\tpostNotebookMessage<webviewMessages.ITelemetryFoundRenderedMarkdownMath>('telemetryFoundRenderedMarkdownMath', {});\n", "\t\t\t\t\t}\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads.ts", "type": "replace", "edit_start_line_idx": 1000 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import * as vscode from 'vscode'; import { posix } from 'path'; import { assertNoRpc } from '../utils'; suite('vscode API - workspace-fs', () => { let root: vscode.Uri; suiteSetup(function () { root = vscode.workspace.workspaceFolders![0]!.uri; }); teardown(assertNoRpc); test('fs.stat', async function () { const stat = await vscode.workspace.fs.stat(root); assert.strictEqual(stat.type, vscode.FileType.Directory); assert.strictEqual(typeof stat.size, 'number'); assert.strictEqual(typeof stat.mtime, 'number'); assert.strictEqual(typeof stat.ctime, 'number'); assert.ok(stat.mtime > 0); assert.ok(stat.ctime > 0); const entries = await vscode.workspace.fs.readDirectory(root); assert.ok(entries.length > 0); // find far.js const tuple = entries.find(tuple => tuple[0] === 'far.js')!; assert.ok(tuple); assert.strictEqual(tuple[0], 'far.js'); assert.strictEqual(tuple[1], vscode.FileType.File); }); test('fs.stat - bad scheme', async function () { try { await vscode.workspace.fs.stat(vscode.Uri.parse('foo:/bar/baz/test.txt')); assert.ok(false); } catch { assert.ok(true); } }); test('fs.stat - missing file', async function () { try { await vscode.workspace.fs.stat(root.with({ path: root.path + '.bad' })); assert.ok(false); } catch (e) { assert.ok(true); } }); test('fs.write/stat/delete', async function () { const uri = root.with({ path: posix.join(root.path, 'new.file') }); await vscode.workspace.fs.writeFile(uri, Buffer.from('HELLO')); const stat = await vscode.workspace.fs.stat(uri); assert.strictEqual(stat.type, vscode.FileType.File); await vscode.workspace.fs.delete(uri); try { await vscode.workspace.fs.stat(uri); assert.ok(false); } catch { assert.ok(true); } }); test('fs.delete folder', async function () { const folder = root.with({ path: posix.join(root.path, 'folder') }); const file = root.with({ path: posix.join(root.path, 'folder/file') }); await vscode.workspace.fs.createDirectory(folder); await vscode.workspace.fs.writeFile(file, Buffer.from('FOO')); await vscode.workspace.fs.stat(folder); await vscode.workspace.fs.stat(file); // ensure non empty folder cannot be deleted try { await vscode.workspace.fs.delete(folder, { recursive: false, useTrash: false }); assert.ok(false); } catch { await vscode.workspace.fs.stat(folder); await vscode.workspace.fs.stat(file); } // ensure non empty folder cannot be deleted is DEFAULT try { await vscode.workspace.fs.delete(folder); // recursive: false as default assert.ok(false); } catch { await vscode.workspace.fs.stat(folder); await vscode.workspace.fs.stat(file); } // delete non empty folder with recursive-flag await vscode.workspace.fs.delete(folder, { recursive: true, useTrash: false }); // esnure folder/file are gone try { await vscode.workspace.fs.stat(folder); assert.ok(false); } catch { assert.ok(true); } try { await vscode.workspace.fs.stat(file); assert.ok(false); } catch { assert.ok(true); } }); test('throws FileSystemError', async function () { try { await vscode.workspace.fs.stat(vscode.Uri.file(`/c468bf16-acfd-4591-825e-2bcebba508a3/71b1f274-91cb-4c19-af00-8495eaab4b73/4b60cb48-a6f2-40ea-9085-0936f4a8f59a.tx6`)); assert.ok(false); } catch (e) { assert.ok(e instanceof vscode.FileSystemError); assert.strictEqual(e.name, vscode.FileSystemError.FileNotFound().name); } }); test('throws FileSystemError', async function () { try { await vscode.workspace.fs.stat(vscode.Uri.parse('foo:/bar')); assert.ok(false); } catch (e) { assert.ok(e instanceof vscode.FileSystemError); assert.strictEqual(e.name, vscode.FileSystemError.Unavailable().name); } }); test('vscode.workspace.fs.remove() (and copy()) succeed unexpectedly. #84177', async function () { const entries = await vscode.workspace.fs.readDirectory(root); assert.ok(entries.length > 0); const someFolder = root.with({ path: posix.join(root.path, '6b1f9d664a92') }); try { await vscode.workspace.fs.delete(someFolder, { recursive: true }); assert.ok(false); } catch (err) { assert.ok(true); } }); test('vscode.workspace.fs.remove() (and copy()) succeed unexpectedly. #84177', async function () { const entries = await vscode.workspace.fs.readDirectory(root); assert.ok(entries.length > 0); const folder = root.with({ path: posix.join(root.path, 'folder') }); const file = root.with({ path: posix.join(root.path, 'folder/file') }); await vscode.workspace.fs.createDirectory(folder); await vscode.workspace.fs.writeFile(file, Buffer.from('FOO')); const someFolder = root.with({ path: posix.join(root.path, '6b1f9d664a92/a564c52da70a') }); try { await vscode.workspace.fs.copy(folder, someFolder, { overwrite: true }); assert.ok(true); } catch (err) { assert.ok(false, err); } finally { await vscode.workspace.fs.delete(folder, { recursive: true, useTrash: false }); await vscode.workspace.fs.delete(someFolder, { recursive: true, useTrash: false }); } }); });
extensions/vscode-api-tests/src/singlefolder-tests/workspace.fs.test.ts
0
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.9157719016075134, 0.9157719016075134, 0.9157719016075134, 0.9157719016075134, 0 ]
{ "id": 5, "code_window": [ "\n", "\t\t\t\tconst matches = previewContainerNode.innerText.match(unsupportedKatexTermsRegex);\n", "\t\t\t\tif (matches) {\n", "\t\t\t\t\tpostNotebookMessage<webviewMessages.ITelemetryFoundUnrenderedMarkdownMath>('telemetryFoundUnrenderedMarkdownMath', {\n", "\t\t\t\t\t\tlatexDirective: matches[0],\n", "\t\t\t\t\t});\n", "\t\t\t\t}\n", "\t\t\t}\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "\t\t\tawait renderers.render(createMarkdownOutputItem(cellId, previewContainerNode, content), previewContainerNode);\n", "\n", "\t\t\tif (!hasPostedRenderedMathTelemetry) {\n", "\t\t\t\tconst hasRenderedMath = previewContainerNode.querySelector('.katex');\n", "\t\t\t\tif (hasRenderedMath) {\n", "\t\t\t\t\thasPostedRenderedMathTelemetry = true;\n", "\t\t\t\t\tpostNotebookMessage<webviewMessages.ITelemetryFoundRenderedMarkdownMath>('telemetryFoundRenderedMarkdownMath', {});\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads.ts", "type": "replace", "edit_start_line_idx": 1015 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import type { Event } from 'vs/base/common/event'; import type { IDisposable } from 'vs/base/common/lifecycle'; import { RenderOutputType } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import type * as webviewMessages from 'vs/workbench/contrib/notebook/browser/view/renderers/webviewMessages'; // !! IMPORTANT !! everything must be in-line within the webviewPreloads // function. Imports are not allowed. This is stringified and injected into // the webview. declare module globalThis { const acquireVsCodeApi: () => ({ getState(): { [key: string]: unknown; }; setState(data: { [key: string]: unknown; }): void; postMessage: (msg: unknown) => void; }); } declare class ResizeObserver { constructor(onChange: (entries: { target: HTMLElement, contentRect?: ClientRect; }[]) => void); observe(element: Element): void; disconnect(): void; } type Listener<T> = { fn: (evt: T) => void; thisArg: unknown; }; interface EmitterLike<T> { fire(data: T): void; event: Event<T>; } interface PreloadStyles { readonly outputNodePadding: number; readonly outputNodeLeftPadding: number; } export interface PreloadOptions { dragAndDropEnabled: boolean; } declare function __import(path: string): Promise<any>; async function webviewPreloads(style: PreloadStyles, options: PreloadOptions, rendererData: readonly RendererMetadata[]) { let currentOptions = options; const acquireVsCodeApi = globalThis.acquireVsCodeApi; const vscode = acquireVsCodeApi(); delete (globalThis as any).acquireVsCodeApi; const handleInnerClick = (event: MouseEvent) => { if (!event || !event.view || !event.view.document) { return; } for (const node of event.composedPath()) { if (node instanceof HTMLAnchorElement && node.href) { if (node.href.startsWith('blob:')) { handleBlobUrlClick(node.href, node.download); } else if (node.href.startsWith('data:')) { handleDataUrl(node.href, node.download); } event.preventDefault(); return; } } }; const handleDataUrl = async (data: string | ArrayBuffer | null, downloadName: string) => { postNotebookMessage<webviewMessages.IClickedDataUrlMessage>('clicked-data-url', { data, downloadName }); }; const handleBlobUrlClick = async (url: string, downloadName: string) => { try { const response = await fetch(url); const blob = await response.blob(); const reader = new FileReader(); reader.addEventListener('load', () => { handleDataUrl(reader.result, downloadName); }); reader.readAsDataURL(blob); } catch (e) { console.error(e.message); } }; document.body.addEventListener('click', handleInnerClick); const preservedScriptAttributes: (keyof HTMLScriptElement)[] = [ 'type', 'src', 'nonce', 'noModule', 'async', ]; // derived from https://github.com/jquery/jquery/blob/d0ce00cdfa680f1f0c38460bc51ea14079ae8b07/src/core/DOMEval.js const domEval = (container: Element) => { const arr = Array.from(container.getElementsByTagName('script')); for (let n = 0; n < arr.length; n++) { const node = arr[n]; const scriptTag = document.createElement('script'); const trustedScript = ttPolicy?.createScript(node.innerText) ?? node.innerText; scriptTag.text = trustedScript as string; for (const key of preservedScriptAttributes) { const val = node[key] || node.getAttribute && node.getAttribute(key); if (val) { scriptTag.setAttribute(key, val as any); } } // TODO@connor4312: should script with src not be removed? container.appendChild(scriptTag).parentNode!.removeChild(scriptTag); } }; async function loadScriptSource(url: string, originalUri = url): Promise<string> { const res = await fetch(url); const text = await res.text(); if (!res.ok) { throw new Error(`Unexpected ${res.status} requesting ${originalUri}: ${text || res.statusText}`); } return text; } interface RendererContext { getState<T>(): T | undefined; setState<T>(newState: T): void; getRenderer(id: string): Promise<any | undefined>; postMessage?(message: unknown): void; onDidReceiveMessage?: Event<unknown>; } interface ScriptModule { activate(ctx?: RendererContext): Promise<RendererApi | undefined | any> | RendererApi | undefined | any; } const invokeSourceWithGlobals = (functionSrc: string, globals: { [name: string]: unknown }) => { const args = Object.entries(globals); return new Function(...args.map(([k]) => k), functionSrc)(...args.map(([, v]) => v)); }; const runPreload = async (url: string, originalUri: string): Promise<ScriptModule> => { const text = await loadScriptSource(url, originalUri); return { activate: () => { try { return invokeSourceWithGlobals(text, { ...kernelPreloadGlobals, scriptUrl: url }); } catch (e) { console.error(e); throw e; } } }; }; const runRenderScript = async (url: string, rendererId: string): Promise<ScriptModule> => { const text = await loadScriptSource(url); // TODO: Support both the new module based renderers and the old style global renderers const isModule = !text.includes('acquireNotebookRendererApi'); if (isModule) { return __import(url); } else { return createBackCompatModule(rendererId, url, text); } }; const createBackCompatModule = (rendererId: string, scriptUrl: string, scriptText: string): ScriptModule => ({ activate: (): RendererApi => { const onDidCreateOutput = createEmitter<IOutputItem>(); const onWillDestroyOutput = createEmitter<undefined | IDestroyCellInfo>(); const globals = { scriptUrl, acquireNotebookRendererApi: <T>(): GlobalNotebookRendererApi<T> => ({ onDidCreateOutput: onDidCreateOutput.event, onWillDestroyOutput: onWillDestroyOutput.event, setState: newState => vscode.setState({ ...vscode.getState(), [rendererId]: newState }), getState: () => { const state = vscode.getState(); return typeof state === 'object' && state ? state[rendererId] as T : undefined; }, }), }; invokeSourceWithGlobals(scriptText, globals); return { renderOutputItem(outputItem) { onDidCreateOutput.fire({ ...outputItem, outputId: outputItem.id }); }, disposeOutputItem(id) { onWillDestroyOutput.fire(id ? { outputId: id } : undefined); } }; } }); const dimensionUpdater = new class { private readonly pending = new Map<string, webviewMessages.DimensionUpdate>(); update(id: string, height: number, options: { init?: boolean; isOutput?: boolean }) { if (!this.pending.size) { setTimeout(() => { this.updateImmediately(); }, 0); } this.pending.set(id, { id, height, ...options, }); } updateImmediately() { if (!this.pending.size) { return; } postNotebookMessage<webviewMessages.IDimensionMessage>('dimension', { updates: Array.from(this.pending.values()) }); this.pending.clear(); } }; const resizeObserver = new class { private readonly _observer: ResizeObserver; private readonly _observedElements = new WeakMap<Element, { id: string, output: boolean }>(); constructor() { this._observer = new ResizeObserver(entries => { for (const entry of entries) { if (!document.body.contains(entry.target)) { continue; } const observedElementInfo = this._observedElements.get(entry.target); if (!observedElementInfo) { continue; } if (entry.target.id === observedElementInfo.id && entry.contentRect) { if (observedElementInfo.output) { let height = 0; if (entry.contentRect.height !== 0) { entry.target.style.padding = `${style.outputNodePadding}px ${style.outputNodePadding}px ${style.outputNodePadding}px ${style.outputNodeLeftPadding}px`; height = entry.contentRect.height + style.outputNodePadding * 2; } else { entry.target.style.padding = `0px`; } dimensionUpdater.update(observedElementInfo.id, height, { isOutput: true }); } else { dimensionUpdater.update(observedElementInfo.id, entry.target.clientHeight, { isOutput: false }); } } } }); } public observe(container: Element, id: string, output: boolean) { if (this._observedElements.has(container)) { return; } this._observedElements.set(container, { id, output }); this._observer.observe(container); } }; function scrollWillGoToParent(event: WheelEvent) { for (let node = event.target as Node | null; node; node = node.parentNode) { if (!(node instanceof Element) || node.id === 'container' || node.classList.contains('cell_container') || node.classList.contains('output_container')) { return false; } if (event.deltaY < 0 && node.scrollTop > 0) { return true; } if (event.deltaY > 0 && node.scrollTop + node.clientHeight < node.scrollHeight) { return true; } } return false; } const handleWheel = (event: WheelEvent) => { if (event.defaultPrevented || scrollWillGoToParent(event)) { return; } postNotebookMessage<webviewMessages.IWheelMessage>('did-scroll-wheel', { payload: { deltaMode: event.deltaMode, deltaX: event.deltaX, deltaY: event.deltaY, deltaZ: event.deltaZ, detail: event.detail, type: event.type } }); }; function focusFirstFocusableInCell(cellId: string) { const cellOutputContainer = document.getElementById(cellId); if (cellOutputContainer) { const focusableElement = cellOutputContainer.querySelector('[tabindex="0"], [href], button, input, option, select, textarea') as HTMLElement | null; focusableElement?.focus(); } } function createFocusSink(cellId: string, outputId: string, focusNext?: boolean) { const element = document.createElement('div'); element.tabIndex = 0; element.addEventListener('focus', () => { postNotebookMessage<webviewMessages.IBlurOutputMessage>('focus-editor', { id: outputId, focusNext }); }); return element; } function addMouseoverListeners(element: HTMLElement, outputId: string): void { element.addEventListener('mouseenter', () => { postNotebookMessage<webviewMessages.IMouseEnterMessage>('mouseenter', { id: outputId, }); }); element.addEventListener('mouseleave', () => { postNotebookMessage<webviewMessages.IMouseLeaveMessage>('mouseleave', { id: outputId, }); }); } function isAncestor(testChild: Node | null, testAncestor: Node | null): boolean { while (testChild) { if (testChild === testAncestor) { return true; } testChild = testChild.parentNode; } return false; } class FocusTracker { private _outputId: string; private _hasFocus: boolean = false; private _loosingFocus: boolean = false; private _element: HTMLElement | Window; constructor(element: HTMLElement | Window, outputId: string) { this._element = element; this._outputId = outputId; this._hasFocus = isAncestor(document.activeElement, <HTMLElement>element); this._loosingFocus = false; element.addEventListener('focus', this._onFocus.bind(this), true); element.addEventListener('blur', this._onBlur.bind(this), true); } private _onFocus() { this._loosingFocus = false; if (!this._hasFocus) { this._hasFocus = true; postNotebookMessage<webviewMessages.IOutputFocusMessage>('outputFocus', { id: this._outputId, }); } } private _onBlur() { if (this._hasFocus) { this._loosingFocus = true; window.setTimeout(() => { if (this._loosingFocus) { this._loosingFocus = false; this._hasFocus = false; postNotebookMessage<webviewMessages.IOutputBlurMessage>('outputBlur', { id: this._outputId, }); } }, 0); } } dispose() { if (this._element) { this._element.removeEventListener('focus', this._onFocus, true); this._element.removeEventListener('blur', this._onBlur, true); } } } const focusTrackers = new Map<string, FocusTracker>(); function addFocusTracker(element: HTMLElement, outputId: string): void { if (focusTrackers.has(outputId)) { focusTrackers.get(outputId)?.dispose(); } focusTrackers.set(outputId, new FocusTracker(element, outputId)); } function createEmitter<T>(listenerChange: (listeners: Set<Listener<T>>) => void = () => undefined): EmitterLike<T> { const listeners = new Set<Listener<T>>(); return { fire(data) { for (const listener of [...listeners]) { listener.fn.call(listener.thisArg, data); } }, event(fn, thisArg, disposables) { const listenerObj = { fn, thisArg }; const disposable: IDisposable = { dispose: () => { listeners.delete(listenerObj); listenerChange(listeners); }, }; listeners.add(listenerObj); listenerChange(listeners); if (disposables instanceof Array) { disposables.push(disposable); } else if (disposables) { disposables.add(disposable); } return disposable; }, }; } function showPreloadErrors(outputNode: HTMLElement, ...errors: readonly Error[]) { outputNode.innerText = `Error loading preloads:`; const errList = document.createElement('ul'); for (const result of errors) { console.error(result); const item = document.createElement('li'); item.innerText = result.message; errList.appendChild(item); } outputNode.appendChild(errList); } interface IOutputItem { readonly id: string; /** @deprecated */ readonly outputId?: string; /** @deprecated */ readonly element: HTMLElement; readonly mime: string; metadata: unknown; metadata2: unknown; text(): string; json(): any; data(): Uint8Array; blob(): Blob; /** @deprecated */ bytes(): Uint8Array; } interface IDestroyCellInfo { outputId: string; } const onDidReceiveKernelMessage = createEmitter<unknown>(); /** @deprecated */ interface GlobalNotebookRendererApi<T> { setState: (newState: T) => void; getState(): T | undefined; readonly onWillDestroyOutput: Event<undefined | IDestroyCellInfo>; readonly onDidCreateOutput: Event<IOutputItem>; } const kernelPreloadGlobals = { acquireVsCodeApi, onDidReceiveKernelMessage: onDidReceiveKernelMessage.event, postKernelMessage: (data: unknown) => postNotebookMessage('customKernelMessage', { message: data }), }; const ttPolicy = window.trustedTypes?.createPolicy('notebookRenderer', { createHTML: value => value, createScript: value => value, }); window.addEventListener('wheel', handleWheel); window.addEventListener('message', async rawEvent => { const event = rawEvent as ({ data: webviewMessages.ToWebviewMessage; }); switch (event.data.type) { case 'initializeMarkup': { await ensureMarkdownPreviewCells(event.data.cells); dimensionUpdater.updateImmediately(); postNotebookMessage('initializedMarkdownPreview', {}); } break; case 'createMarkupCell': ensureMarkdownPreviewCells([event.data.cell]); break; case 'showMarkupCell': { const data = event.data; const cellContainer = document.getElementById(data.id); if (cellContainer) { cellContainer.style.visibility = 'visible'; cellContainer.style.top = `${data.top}px`; updateMarkdownPreview(cellContainer, data.id, data.content); } } break; case 'hideMarkupCells': { for (const id of event.data.ids) { const cellContainer = document.getElementById(id); if (cellContainer) { cellContainer.style.visibility = 'hidden'; } } } break; case 'unhideMarkupCells': { for (const id of event.data.ids) { const cellContainer = document.getElementById(id); if (cellContainer) { cellContainer.style.visibility = 'visible'; updateMarkdownPreview(cellContainer, id, undefined); } } } break; case 'deleteMarkupCell': { for (const id of event.data.ids) { const cellContainer = document.getElementById(id); cellContainer?.remove(); } } break; case 'updateSelectedMarkupCells': { const selectedCellIds = new Set<string>(event.data.selectedCellIds); for (const oldSelected of document.querySelectorAll('.preview.selected')) { const id = oldSelected.id; if (!selectedCellIds.has(id)) { oldSelected.classList.remove('selected'); } } for (const newSelected of selectedCellIds) { const previewContainer = document.getElementById(newSelected); if (previewContainer) { previewContainer.classList.add('selected'); } } } break; case 'html': { const data = event.data; outputs.enqueue(event.data.outputId, async (state) => { const preloadsAndErrors = await Promise.all<unknown>([ data.rendererId ? renderers.load(data.rendererId) : undefined, ...data.requiredPreloads.map(p => kernelPreloads.waitFor(p.uri)), ].map(p => p?.catch(err => err))); if (state.cancelled) { return; } let cellOutputContainer = document.getElementById(data.cellId); const outputId = data.outputId; if (!cellOutputContainer) { const container = document.getElementById('container')!; const upperWrapperElement = createFocusSink(data.cellId, outputId); container.appendChild(upperWrapperElement); const newElement = document.createElement('div'); newElement.id = data.cellId; newElement.classList.add('cell_container'); container.appendChild(newElement); cellOutputContainer = newElement; const lowerWrapperElement = createFocusSink(data.cellId, outputId, true); container.appendChild(lowerWrapperElement); } cellOutputContainer.style.position = 'absolute'; cellOutputContainer.style.top = data.cellTop + 'px'; const outputContainer = document.createElement('div'); outputContainer.classList.add('output_container'); outputContainer.style.position = 'absolute'; outputContainer.style.overflow = 'hidden'; outputContainer.style.maxHeight = '0px'; outputContainer.style.top = `${data.outputOffset}px`; const outputNode = document.createElement('div'); outputNode.classList.add('output'); outputNode.style.position = 'absolute'; outputNode.style.top = `0px`; outputNode.style.left = data.left + 'px'; // outputNode.style.width = 'calc(100% - ' + data.left + 'px)'; // outputNode.style.minHeight = '32px'; outputNode.style.padding = '0px'; outputNode.id = outputId; addMouseoverListeners(outputNode, outputId); addFocusTracker(outputNode, outputId); const content = data.content; if (content.type === RenderOutputType.Html) { const trustedHtml = ttPolicy?.createHTML(content.htmlContent) ?? content.htmlContent; outputNode.innerHTML = trustedHtml as string; domEval(outputNode); } else if (preloadsAndErrors.some(e => e instanceof Error)) { const errors = preloadsAndErrors.filter((e): e is Error => e instanceof Error); showPreloadErrors(outputNode, ...errors); } else { const rendererApi = preloadsAndErrors[0] as RendererApi; try { rendererApi.renderOutputItem({ id: outputId, element: outputNode, mime: content.mimeType, metadata: content.metadata, metadata2: content.metadata2, data() { return content.valueBytes; }, bytes() { return this.data(); }, text() { return new TextDecoder().decode(content.valueBytes); }, json() { return JSON.parse(this.text()); }, blob() { return new Blob([content.valueBytes], { type: content.mimeType }); } }, outputNode); } catch (e) { showPreloadErrors(outputNode, e); } } cellOutputContainer.appendChild(outputContainer); outputContainer.appendChild(outputNode); resizeObserver.observe(outputNode, outputId, true); if (content.type === RenderOutputType.Html) { domEval(outputNode); } const clientHeight = outputNode.clientHeight; const cps = document.defaultView!.getComputedStyle(outputNode); if (clientHeight !== 0 && cps.padding === '0px') { // we set padding to zero if the output height is zero (then we can have a zero-height output DOM node) // thus we need to ensure the padding is accounted when updating the init height of the output dimensionUpdater.update(outputId, clientHeight + style.outputNodePadding * 2, { isOutput: true, init: true, }); outputNode.style.padding = `${style.outputNodePadding}px ${style.outputNodePadding}px ${style.outputNodePadding}px ${style.outputNodeLeftPadding}px`; } else { dimensionUpdater.update(outputId, outputNode.clientHeight, { isOutput: true, init: true, }); } // don't hide until after this step so that the height is right cellOutputContainer.style.visibility = data.initiallyHidden ? 'hidden' : 'visible'; }); break; } case 'view-scroll': { // const date = new Date(); // console.log('----- will scroll ---- ', date.getMinutes() + ':' + date.getSeconds() + ':' + date.getMilliseconds()); for (const request of event.data.widgets) { const widget = document.getElementById(request.outputId); if (widget) { widget.parentElement!.parentElement!.style.top = `${request.cellTop}px`; widget.parentElement!.style.top = `${request.outputOffset}px`; if (request.forceDisplay) { widget.parentElement!.parentElement!.style.visibility = 'visible'; } } } for (const cell of event.data.markdownPreviews) { const container = document.getElementById(cell.id); if (container) { container.style.top = `${cell.top}px`; } } break; } case 'clear': renderers.clearAll(); document.getElementById('container')!.innerText = ''; focusTrackers.forEach(ft => { ft.dispose(); }); focusTrackers.clear(); break; case 'clearOutput': { const output = document.getElementById(event.data.outputId); const { rendererId, outputId } = event.data; outputs.cancelOutput(outputId); if (output && output.parentNode) { if (rendererId) { renderers.clearOutput(rendererId, outputId); } output.parentNode.removeChild(output); } break; } case 'hideOutput': { const { outputId } = event.data; outputs.enqueue(event.data.outputId, () => { const container = document.getElementById(outputId)?.parentElement?.parentElement; if (container) { container.style.visibility = 'hidden'; } }); break; } case 'showOutput': { const { outputId, cellTop: top } = event.data; outputs.enqueue(event.data.outputId, () => { const output = document.getElementById(outputId); if (output) { output.parentElement!.parentElement!.style.visibility = 'visible'; output.parentElement!.parentElement!.style.top = top + 'px'; dimensionUpdater.update(outputId, output.clientHeight, { isOutput: true, }); } }); break; } case 'ack-dimension': { const { outputId, height } = event.data; const output = document.getElementById(outputId); if (output) { output.parentElement!.style.maxHeight = `${height}px`; output.parentElement!.style.height = `${height}px`; } break; } case 'preload': const resources = event.data.resources; for (const { uri, originalUri } of resources) { kernelPreloads.load(uri, originalUri); } break; case 'focus-output': focusFirstFocusableInCell(event.data.cellId); break; case 'decorations': { const outputContainer = document.getElementById(event.data.cellId); outputContainer?.classList.add(...event.data.addedClassNames); outputContainer?.classList.remove(...event.data.removedClassNames); } break; case 'customKernelMessage': onDidReceiveKernelMessage.fire(event.data.message); break; case 'customRendererMessage': renderers.getRenderer(event.data.rendererId)?.receiveMessage(event.data.message); break; case 'notebookStyles': const documentStyle = document.documentElement.style; for (let i = documentStyle.length - 1; i >= 0; i--) { const property = documentStyle[i]; // Don't remove properties that the webview might have added separately if (property && property.startsWith('--notebook-')) { documentStyle.removeProperty(property); } } // Re-add new properties for (const variable of Object.keys(event.data.styles)) { documentStyle.setProperty(`--${variable}`, event.data.styles[variable]); } break; case 'notebookOptions': currentOptions = event.data.options; // Update markdown previews for (const markdownContainer of document.querySelectorAll('.preview')) { setMarkdownContainerDraggable(markdownContainer, currentOptions.dragAndDropEnabled); } break; } }); interface RendererApi { renderOutputItem: (outputItem: IOutputItem, element: HTMLElement) => void; disposeOutputItem?: (id?: string) => void; } class Renderer { constructor( public readonly data: RendererMetadata, private readonly loadExtension: (id: string) => Promise<void>, ) { } private _onMessageEvent = createEmitter(); private _loadPromise?: Promise<RendererApi | undefined>; private _api: RendererApi | undefined; public get api() { return this._api; } public load(): Promise<RendererApi | undefined> { if (!this._loadPromise) { this._loadPromise = this._load(); } return this._loadPromise; } public receiveMessage(message: unknown) { this._onMessageEvent.fire(message); } private createRendererContext(): RendererContext { const { id, messaging } = this.data; const context: RendererContext = { setState: newState => vscode.setState({ ...vscode.getState(), [id]: newState }), getState: <T>() => { const state = vscode.getState(); return typeof state === 'object' && state ? state[id] as T : undefined; }, // TODO: This is async so that we can return a promise to the API in the future. // Currently the API is always resolved before we call `createRendererContext`. getRenderer: async (id: string) => renderers.getRenderer(id)?.api, }; if (messaging) { context.onDidReceiveMessage = this._onMessageEvent.event; context.postMessage = message => postNotebookMessage('customRendererMessage', { rendererId: id, message }); } return context; } /** Inner function cached in the _loadPromise(). */ private async _load(): Promise<RendererApi | undefined> { const module = await runRenderScript(this.data.entrypoint, this.data.id); if (!module) { return; } const api = await module.activate(this.createRendererContext()); this._api = api; // Squash any errors extends errors. They won't prevent the renderer // itself from working, so just log them. await Promise.all(rendererData .filter(d => d.extends === this.data.id) .map(d => this.loadExtension(d.id).catch(console.error)), ); return api; } } const kernelPreloads = new class { private readonly preloads = new Map<string /* uri */, Promise<unknown>>(); /** * Returns a promise that resolves when the given preload is activated. */ public waitFor(uri: string) { return this.preloads.get(uri) || Promise.resolve(new Error(`Preload not ready: ${uri}`)); } /** * Loads a preload. * @param uri URI to load from * @param originalUri URI to show in an error message if the preload is invalid. */ public load(uri: string, originalUri: string) { const promise = Promise.all([ runPreload(uri, originalUri), this.waitForAllCurrent(), ]).then(([module]) => module.activate()); this.preloads.set(uri, promise); return promise; } /** * Returns a promise that waits for all currently-registered preloads to * activate before resolving. */ private waitForAllCurrent() { return Promise.all([...this.preloads.values()].map(p => p.catch(err => err))); } }; const outputs = new class { private outputs = new Map<string, { cancelled: boolean; queue: Promise<unknown> }>(); /** * Pushes the action onto the list of actions for the given output ID, * ensuring that it's run in-order. */ public enqueue(outputId: string, action: (record: { cancelled: boolean }) => unknown) { const record = this.outputs.get(outputId); if (!record) { this.outputs.set(outputId, { cancelled: false, queue: new Promise(r => r(action({ cancelled: false }))) }); } else { record.queue = record.queue.then(r => !record.cancelled && action(record)); } } /** * Cancels the rendering of all outputs. */ public cancelAll() { for (const record of this.outputs.values()) { record.cancelled = true; } this.outputs.clear(); } /** * Cancels any ongoing rendering out an output. */ public cancelOutput(outputId: string) { const output = this.outputs.get(outputId); if (output) { output.cancelled = true; this.outputs.delete(outputId); } } }; const renderers = new class { private readonly _renderers = new Map</* id */ string, Renderer>(); constructor() { for (const renderer of rendererData) { this._renderers.set(renderer.id, new Renderer(renderer, async (extensionId) => { const ext = this._renderers.get(extensionId); if (!ext) { throw new Error(`Could not find extending renderer: ${extensionId}`); } await ext.load(); })); } } public getRenderer(id: string) { return this._renderers.get(id); } public async load(id: string) { const renderer = this._renderers.get(id); if (!renderer) { throw new Error('Could not find renderer'); } return renderer.load(); } public clearAll() { outputs.cancelAll(); for (const renderer of this._renderers.values()) { renderer.api?.disposeOutputItem?.(); } } public clearOutput(rendererId: string, outputId: string) { outputs.cancelOutput(outputId); this._renderers.get(rendererId)?.api?.disposeOutputItem?.(outputId); } public async render(info: IOutputItem, element: HTMLElement) { const renderers = Array.from(this._renderers.values()) .filter(renderer => renderer.data.mimeTypes.includes(info.mime) && !renderer.data.extends); if (!renderers.length) { throw new Error('Could not find renderer'); } await Promise.all(renderers.map(x => x.load())); renderers[0].api?.renderOutputItem(info, element); } }(); vscode.postMessage({ __vscode_notebook_message: true, type: 'initialized' }); function setMarkdownContainerDraggable(element: Element, isDraggable: boolean) { if (isDraggable) { element.classList.add('draggable'); element.setAttribute('draggable', 'true'); } else { element.classList.remove('draggable'); element.removeAttribute('draggable'); } } async function createMarkdownPreview(cellId: string, content: string, top: number): Promise<HTMLElement> { const container = document.getElementById('container')!; const cellContainer = document.createElement('div'); const existing = document.getElementById(cellId); if (existing) { console.error(`Trying to create markdown preview that already exists: ${cellId}`); return existing; } cellContainer.id = cellId; cellContainer.classList.add('preview'); cellContainer.style.position = 'absolute'; cellContainer.style.top = top + 'px'; container.appendChild(cellContainer); cellContainer.addEventListener('dblclick', () => { postNotebookMessage<webviewMessages.IToggleMarkdownPreviewMessage>('toggleMarkdownPreview', { cellId }); }); cellContainer.addEventListener('click', e => { postNotebookMessage<webviewMessages.IClickMarkdownPreviewMessage>('clickMarkdownPreview', { cellId, altKey: e.altKey, ctrlKey: e.ctrlKey, metaKey: e.metaKey, shiftKey: e.shiftKey, }); }); cellContainer.addEventListener('contextmenu', e => { postNotebookMessage<webviewMessages.IContextMenuMarkdownPreviewMessage>('contextMenuMarkdownPreview', { cellId, clientX: e.clientX, clientY: e.clientY, }); }); cellContainer.addEventListener('mouseenter', () => { postNotebookMessage<webviewMessages.IMouseEnterMarkdownPreviewMessage>('mouseEnterMarkdownPreview', { cellId }); }); cellContainer.addEventListener('mouseleave', () => { postNotebookMessage<webviewMessages.IMouseLeaveMarkdownPreviewMessage>('mouseLeaveMarkdownPreview', { cellId }); }); setMarkdownContainerDraggable(cellContainer, currentOptions.dragAndDropEnabled); cellContainer.addEventListener('dragstart', e => { markdownPreviewDragManager.startDrag(e, cellId); }); cellContainer.addEventListener('drag', e => { markdownPreviewDragManager.updateDrag(e, cellId); }); cellContainer.addEventListener('dragend', e => { markdownPreviewDragManager.endDrag(e, cellId); }); await updateMarkdownPreview(cellContainer, cellId, content); resizeObserver.observe(cellContainer, cellId, false); return cellContainer; } async function ensureMarkdownPreviewCells(update: readonly webviewMessages.IMarkdownCellInitialization[]): Promise<void> { await Promise.all(update.map(async cell => { let container = document.getElementById(cell.cellId); if (container) { await updateMarkdownPreview(container, cell.cellId, cell.content); } else { container = await createMarkdownPreview(cell.cellId, cell.content, cell.offset); } container.style.visibility = cell.visible ? 'visible' : 'hidden'; })); } function postNotebookMessage<T extends webviewMessages.FromWebviewMessage>( type: T['type'], properties: Omit<T, '__vscode_notebook_message' | 'type'> ) { vscode.postMessage({ __vscode_notebook_message: true, type, ...properties }); } let hasPostedRenderedMathTelemetry = false; const unsupportedKatexTermsRegex = /(\\(?:abovewithdelims|array|Arrowvert|arrowvert|atopwithdelims|bbox|bracevert|buildrel|cancelto|cases|class|cssId|ddddot|dddot|DeclareMathOperator|definecolor|displaylines|enclose|eqalign|eqalignno|eqref|hfil|hfill|idotsint|iiiint|label|leftarrowtail|leftroot|leqalignno|lower|mathtip|matrix|mbox|mit|mmlToken|moveleft|moveright|mspace|newenvironment|Newextarrow|notag|oldstyle|overparen|overwithdelims|pmatrix|raise|ref|renewenvironment|require|root|Rule|scr|shoveleft|shoveright|sideset|skew|Space|strut|style|texttip|Tiny|toggle|underparen|unicode|uproot)\b)/gi; async function updateMarkdownPreview(previewContainerNode: HTMLElement, cellId: string, content: string | undefined) { if (typeof content === 'string') { if (content.trim().length === 0) { previewContainerNode.classList.add('emptyMarkdownCell'); previewContainerNode.innerText = ''; } else { previewContainerNode.classList.remove('emptyMarkdownCell'); await renderers.render(createMarkdownOutputItem(cellId, previewContainerNode, content), previewContainerNode); if (!hasPostedRenderedMathTelemetry) { const hasRenderedMath = previewContainerNode.querySelector('.katex'); if (hasRenderedMath) { hasPostedRenderedMathTelemetry = true; postNotebookMessage<webviewMessages.ITelemetryFoundRenderedMarkdownMath>('telemetryFoundRenderedMarkdownMath', {}); } } const matches = previewContainerNode.innerText.match(unsupportedKatexTermsRegex); if (matches) { postNotebookMessage<webviewMessages.ITelemetryFoundUnrenderedMarkdownMath>('telemetryFoundUnrenderedMarkdownMath', { latexDirective: matches[0], }); } } } dimensionUpdater.update(cellId, previewContainerNode.clientHeight, { isOutput: false }); } const markdownPreviewDragManager = new class MarkdownPreviewDragManager { private currentDrag: { cellId: string, clientY: number } | undefined; constructor() { document.addEventListener('dragover', e => { // Allow dropping dragged markdown cells e.preventDefault(); }); document.addEventListener('drop', e => { e.preventDefault(); const drag = this.currentDrag; if (!drag) { return; } this.currentDrag = undefined; postNotebookMessage<webviewMessages.ICellDropMessage>('cell-drop', { cellId: drag.cellId, ctrlKey: e.ctrlKey, altKey: e.altKey, dragOffsetY: e.clientY, }); }); } startDrag(e: DragEvent, cellId: string) { if (!e.dataTransfer) { return; } if (!currentOptions.dragAndDropEnabled) { return; } this.currentDrag = { cellId, clientY: e.clientY }; (e.target as HTMLElement).classList.add('dragging'); postNotebookMessage<webviewMessages.ICellDragStartMessage>('cell-drag-start', { cellId: cellId, dragOffsetY: e.clientY, }); // Continuously send updates while dragging instead of relying on `updateDrag`. // This lets us scroll the list based on drag position. const trySendDragUpdate = () => { if (this.currentDrag?.cellId !== cellId) { return; } postNotebookMessage<webviewMessages.ICellDragMessage>('cell-drag', { cellId: cellId, dragOffsetY: this.currentDrag.clientY, }); requestAnimationFrame(trySendDragUpdate); }; requestAnimationFrame(trySendDragUpdate); } updateDrag(e: DragEvent, cellId: string) { if (cellId !== this.currentDrag?.cellId) { this.currentDrag = undefined; } this.currentDrag = { cellId, clientY: e.clientY }; } endDrag(e: DragEvent, cellId: string) { this.currentDrag = undefined; (e.target as HTMLElement).classList.remove('dragging'); postNotebookMessage<webviewMessages.ICellDragEndMessage>('cell-drag-end', { cellId: cellId }); } }(); function createMarkdownOutputItem(id: string, element: HTMLElement, content: string): IOutputItem { return { id, element, mime: 'text/markdown', metadata: undefined, metadata2: undefined, outputId: undefined, text() { return content; }, json() { return undefined; }, bytes() { return this.data(); }, data() { return new TextEncoder().encode(content); }, blob() { return new Blob([this.data()], { type: this.mime }); }, }; } } export interface RendererMetadata { readonly id: string; readonly entrypoint: string; readonly mimeTypes: readonly string[]; readonly extends: string | undefined; readonly messaging: boolean; } export function preloadsScriptStr(styleValues: PreloadStyles, options: PreloadOptions, renderers: readonly RendererMetadata[]) { // TS will try compiling `import()` in webviePreloads, so use an helper function instead // of using `import(...)` directly return ` const __import = (x) => import(x); (${webviewPreloads})( JSON.parse(decodeURIComponent("${encodeURIComponent(JSON.stringify(styleValues))}")), JSON.parse(decodeURIComponent("${encodeURIComponent(JSON.stringify(options))}")), JSON.parse(decodeURIComponent("${encodeURIComponent(JSON.stringify(renderers))}")) )\n//# sourceURL=notebookWebviewPreloads.js\n`; }
src/vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads.ts
1
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.9983940720558167, 0.00796094536781311, 0.00016352051170542836, 0.0001712968514766544, 0.08720455318689346 ]
{ "id": 5, "code_window": [ "\n", "\t\t\t\tconst matches = previewContainerNode.innerText.match(unsupportedKatexTermsRegex);\n", "\t\t\t\tif (matches) {\n", "\t\t\t\t\tpostNotebookMessage<webviewMessages.ITelemetryFoundUnrenderedMarkdownMath>('telemetryFoundUnrenderedMarkdownMath', {\n", "\t\t\t\t\t\tlatexDirective: matches[0],\n", "\t\t\t\t\t});\n", "\t\t\t\t}\n", "\t\t\t}\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "\t\t\tawait renderers.render(createMarkdownOutputItem(cellId, previewContainerNode, content), previewContainerNode);\n", "\n", "\t\t\tif (!hasPostedRenderedMathTelemetry) {\n", "\t\t\t\tconst hasRenderedMath = previewContainerNode.querySelector('.katex');\n", "\t\t\t\tif (hasRenderedMath) {\n", "\t\t\t\t\thasPostedRenderedMathTelemetry = true;\n", "\t\t\t\t\tpostNotebookMessage<webviewMessages.ITelemetryFoundRenderedMarkdownMath>('telemetryFoundRenderedMarkdownMath', {});\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads.ts", "type": "replace", "edit_start_line_idx": 1015 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { dispose, IDisposable, DisposableStore } from 'vs/base/common/lifecycle'; import { Event, Emitter } from 'vs/base/common/event'; import * as objects from 'vs/base/common/objects'; import * as json from 'vs/base/common/json'; import { URI as uri } from 'vs/base/common/uri'; import * as resources from 'vs/base/common/resources'; import { IJSONSchema } from 'vs/base/common/jsonSchema'; import { IEditorPane } from 'vs/workbench/common/editor'; import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration'; import { IFileService } from 'vs/platform/files/common/files'; import { IWorkspaceContextService, IWorkspaceFolder, WorkbenchState, IWorkspaceFoldersChangeEvent } from 'vs/platform/workspace/common/workspace'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IDebugConfigurationProvider, ICompound, IConfig, IGlobalConfig, IConfigurationManager, ILaunch, CONTEXT_DEBUG_CONFIGURATION_TYPE, IConfigPresentation } from 'vs/workbench/contrib/debug/common/debug'; import { IEditorService, ACTIVE_GROUP } from 'vs/workbench/services/editor/common/editorService'; import { launchSchemaId } from 'vs/workbench/services/configuration/common/configuration'; import { IPreferencesService } from 'vs/workbench/services/preferences/common/preferences'; import { Registry } from 'vs/platform/registry/common/platform'; import { IJSONContributionRegistry, Extensions as JSONExtensions } from 'vs/platform/jsonschemas/common/jsonContributionRegistry'; import { launchSchema } from 'vs/workbench/contrib/debug/common/debugSchemas'; import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles'; import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation'; import { withUndefinedAsNull } from 'vs/base/common/types'; import { sequence } from 'vs/base/common/async'; import { IHistoryService } from 'vs/workbench/services/history/common/history'; import { flatten, distinct } from 'vs/base/common/arrays'; import { getVisibleAndSorted } from 'vs/workbench/contrib/debug/common/debugUtils'; import { DebugConfigurationProviderTriggerKind } from 'vs/workbench/api/common/extHostTypes'; import { IUriIdentityService } from 'vs/workbench/services/uriIdentity/common/uriIdentity'; import { AdapterManager } from 'vs/workbench/contrib/debug/browser/debugAdapterManager'; import { debugConfigure } from 'vs/workbench/contrib/debug/browser/debugIcons'; import { ThemeIcon } from 'vs/platform/theme/common/themeService'; const jsonRegistry = Registry.as<IJSONContributionRegistry>(JSONExtensions.JSONContribution); jsonRegistry.registerSchema(launchSchemaId, launchSchema); const DEBUG_SELECTED_CONFIG_NAME_KEY = 'debug.selectedconfigname'; const DEBUG_SELECTED_ROOT = 'debug.selectedroot'; // Debug type is only stored if a dynamic configuration is used for better restore const DEBUG_SELECTED_TYPE = 'debug.selectedtype'; const DEBUG_RECENT_DYNAMIC_CONFIGURATIONS = 'debug.recentdynamicconfigurations'; interface IDynamicPickItem { label: string, launch: ILaunch, config: IConfig } export class ConfigurationManager implements IConfigurationManager { private launches!: ILaunch[]; private selectedName: string | undefined; private selectedLaunch: ILaunch | undefined; private getSelectedConfig: () => Promise<IConfig | undefined> = () => Promise.resolve(undefined); private selectedType: string | undefined; private toDispose: IDisposable[]; private readonly _onDidSelectConfigurationName = new Emitter<void>(); private configProviders: IDebugConfigurationProvider[]; private debugConfigurationTypeContext: IContextKey<string>; constructor( private readonly adapterManager: AdapterManager, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @IConfigurationService private readonly configurationService: IConfigurationService, @IQuickInputService private readonly quickInputService: IQuickInputService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IStorageService private readonly storageService: IStorageService, @IExtensionService private readonly extensionService: IExtensionService, @IHistoryService private readonly historyService: IHistoryService, @IUriIdentityService private readonly uriIdentityService: IUriIdentityService, @IContextKeyService contextKeyService: IContextKeyService ) { this.configProviders = []; this.toDispose = []; this.initLaunches(); this.registerListeners(); const previousSelectedRoot = this.storageService.get(DEBUG_SELECTED_ROOT, StorageScope.WORKSPACE); const previousSelectedType = this.storageService.get(DEBUG_SELECTED_TYPE, StorageScope.WORKSPACE); const previousSelectedLaunch = this.launches.find(l => l.uri.toString() === previousSelectedRoot); const previousSelectedName = this.storageService.get(DEBUG_SELECTED_CONFIG_NAME_KEY, StorageScope.WORKSPACE); this.debugConfigurationTypeContext = CONTEXT_DEBUG_CONFIGURATION_TYPE.bindTo(contextKeyService); const dynamicConfig = previousSelectedType ? { type: previousSelectedType } : undefined; if (previousSelectedLaunch && previousSelectedLaunch.getConfigurationNames().length) { this.selectConfiguration(previousSelectedLaunch, previousSelectedName, undefined, dynamicConfig); } else if (this.launches.length > 0) { this.selectConfiguration(undefined, previousSelectedName, undefined, dynamicConfig); } } registerDebugConfigurationProvider(debugConfigurationProvider: IDebugConfigurationProvider): IDisposable { this.configProviders.push(debugConfigurationProvider); return { dispose: () => { this.unregisterDebugConfigurationProvider(debugConfigurationProvider); } }; } unregisterDebugConfigurationProvider(debugConfigurationProvider: IDebugConfigurationProvider): void { const ix = this.configProviders.indexOf(debugConfigurationProvider); if (ix >= 0) { this.configProviders.splice(ix, 1); } } /** * if scope is not specified,a value of DebugConfigurationProvideTrigger.Initial is assumed. */ hasDebugConfigurationProvider(debugType: string, triggerKind?: DebugConfigurationProviderTriggerKind): boolean { if (triggerKind === undefined) { triggerKind = DebugConfigurationProviderTriggerKind.Initial; } // check if there are providers for the given type that contribute a provideDebugConfigurations method const provider = this.configProviders.find(p => p.provideDebugConfigurations && (p.type === debugType) && (p.triggerKind === triggerKind)); return !!provider; } async resolveConfigurationByProviders(folderUri: uri | undefined, type: string | undefined, config: IConfig, token: CancellationToken): Promise<IConfig | null | undefined> { await this.activateDebuggers('onDebugResolve', type); // pipe the config through the promises sequentially. Append at the end the '*' types const providers = this.configProviders.filter(p => p.type === type && p.resolveDebugConfiguration) .concat(this.configProviders.filter(p => p.type === '*' && p.resolveDebugConfiguration)); let result: IConfig | null | undefined = config; await sequence(providers.map(provider => async () => { // If any provider returned undefined or null make sure to respect that and do not pass the result to more resolver if (result) { result = await provider.resolveDebugConfiguration!(folderUri, result, token); } })); return result; } async resolveDebugConfigurationWithSubstitutedVariables(folderUri: uri | undefined, type: string | undefined, config: IConfig, token: CancellationToken): Promise<IConfig | null | undefined> { // pipe the config through the promises sequentially. Append at the end the '*' types const providers = this.configProviders.filter(p => p.type === type && p.resolveDebugConfigurationWithSubstitutedVariables) .concat(this.configProviders.filter(p => p.type === '*' && p.resolveDebugConfigurationWithSubstitutedVariables)); let result: IConfig | null | undefined = config; await sequence(providers.map(provider => async () => { // If any provider returned undefined or null make sure to respect that and do not pass the result to more resolver if (result) { result = await provider.resolveDebugConfigurationWithSubstitutedVariables!(folderUri, result, token); } })); return result; } async provideDebugConfigurations(folderUri: uri | undefined, type: string, token: CancellationToken): Promise<any[]> { await this.activateDebuggers('onDebugInitialConfigurations'); const results = await Promise.all(this.configProviders.filter(p => p.type === type && p.triggerKind === DebugConfigurationProviderTriggerKind.Initial && p.provideDebugConfigurations).map(p => p.provideDebugConfigurations!(folderUri, token))); return results.reduce((first, second) => first.concat(second), []); } async getDynamicProviders(): Promise<{ label: string, type: string, getProvider: () => Promise<IDebugConfigurationProvider | undefined>, pick: () => Promise<{ launch: ILaunch, config: IConfig } | undefined> }[]> { const extensions = await this.extensionService.getExtensions(); const onDebugDynamicConfigurationsName = 'onDebugDynamicConfigurations'; const debugDynamicExtensionsTypes = extensions.reduce((acc, e) => { if (!e.activationEvents) { return acc; } const explicitTypes: string[] = []; let hasGenericEvent = false; for (const event of e.activationEvents) { if (event === onDebugDynamicConfigurationsName) { hasGenericEvent = true; } else if (event.startsWith(`${onDebugDynamicConfigurationsName}:`)) { explicitTypes.push(event.slice(onDebugDynamicConfigurationsName.length + 1)); } } if (explicitTypes.length) { return acc.concat(explicitTypes); } if (hasGenericEvent) { const debuggerType = e.contributes?.debuggers?.[0].type; return debuggerType ? acc.concat(debuggerType) : acc; } return acc; }, [] as string[]); return debugDynamicExtensionsTypes.map(type => { return { label: this.adapterManager.getDebuggerLabel(type)!, getProvider: async () => { await this.activateDebuggers(onDebugDynamicConfigurationsName, type); return this.configProviders.find(p => p.type === type && p.triggerKind === DebugConfigurationProviderTriggerKind.Dynamic && p.provideDebugConfigurations); }, type, pick: async () => { // Do a late 'onDebugDynamicConfigurationsName' activation so extensions are not activated too early #108578 await this.activateDebuggers(onDebugDynamicConfigurationsName, type); const disposables = new DisposableStore(); const input = disposables.add(this.quickInputService.createQuickPick<IDynamicPickItem>()); input.busy = true; input.placeholder = nls.localize('selectConfiguration', "Select Launch Configuration"); input.show(); const chosenPromise = new Promise<IDynamicPickItem | undefined>(resolve => { disposables.add(input.onDidAccept(() => resolve(input.activeItems[0]))); disposables.add(input.onDidTriggerItemButton(async (context) => { resolve(undefined); const { launch, config } = context.item; await launch.openConfigFile(false, config.type); // Only Launch have a pin trigger button await (launch as Launch).writeConfiguration(config); await this.selectConfiguration(launch, config.name); })); }); const token = new CancellationTokenSource(); const picks: Promise<IDynamicPickItem[]>[] = []; const provider = this.configProviders.find(p => p.type === type && p.triggerKind === DebugConfigurationProviderTriggerKind.Dynamic && p.provideDebugConfigurations); this.getLaunches().forEach(launch => { if (launch.workspace && provider) { picks.push(provider.provideDebugConfigurations!(launch.workspace.uri, token.token).then(configurations => configurations.map(config => ({ label: config.name, description: launch.name, config, buttons: [{ iconClass: ThemeIcon.asClassName(debugConfigure), tooltip: nls.localize('editLaunchConfig', "Edit Debug Configuration in launch.json") }], launch })))); } }); const nestedPicks = await Promise.all(picks); const items = flatten(nestedPicks); input.items = items; input.busy = false; const chosen = await chosenPromise; disposables.dispose(); if (!chosen) { // User canceled quick input we should notify the provider to cancel computing configurations token.cancel(); return; } return chosen; } }; }); } getAllConfigurations(): { launch: ILaunch; name: string; presentation?: IConfigPresentation }[] { const all: { launch: ILaunch, name: string, presentation?: IConfigPresentation }[] = []; for (let l of this.launches) { for (let name of l.getConfigurationNames()) { const config = l.getConfiguration(name) || l.getCompound(name); if (config) { all.push({ launch: l, name, presentation: config.presentation }); } } } return getVisibleAndSorted(all); } getRecentDynamicConfigurations(): { name: string, type: string }[] { return JSON.parse(this.storageService.get(DEBUG_RECENT_DYNAMIC_CONFIGURATIONS, StorageScope.WORKSPACE, '[]')); } private registerListeners(): void { this.toDispose.push(Event.any<IWorkspaceFoldersChangeEvent | WorkbenchState>(this.contextService.onDidChangeWorkspaceFolders, this.contextService.onDidChangeWorkbenchState)(() => { this.initLaunches(); this.selectConfiguration(undefined); this.setCompoundSchemaValues(); })); this.toDispose.push(this.configurationService.onDidChangeConfiguration(async e => { if (e.affectsConfiguration('launch')) { // A change happen in the launch.json. If there is already a launch configuration selected, do not change the selection. await this.selectConfiguration(undefined); this.setCompoundSchemaValues(); } })); this.toDispose.push(this.adapterManager.onDidDebuggersExtPointRead(() => { this.setCompoundSchemaValues(); })); } private initLaunches(): void { this.launches = this.contextService.getWorkspace().folders.map(folder => this.instantiationService.createInstance(Launch, this, this.adapterManager, folder)); if (this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE) { this.launches.push(this.instantiationService.createInstance(WorkspaceLaunch, this, this.adapterManager)); } this.launches.push(this.instantiationService.createInstance(UserLaunch, this, this.adapterManager)); if (this.selectedLaunch && this.launches.indexOf(this.selectedLaunch) === -1) { this.selectConfiguration(undefined); } } private setCompoundSchemaValues(): void { const compoundConfigurationsSchema = (<IJSONSchema>launchSchema.properties!['compounds'].items).properties!['configurations']; const launchNames = this.launches.map(l => l.getConfigurationNames(true)).reduce((first, second) => first.concat(second), []); (<IJSONSchema>compoundConfigurationsSchema.items).oneOf![0].enum = launchNames; (<IJSONSchema>compoundConfigurationsSchema.items).oneOf![1].properties!.name.enum = launchNames; const folderNames = this.contextService.getWorkspace().folders.map(f => f.name); (<IJSONSchema>compoundConfigurationsSchema.items).oneOf![1].properties!.folder.enum = folderNames; jsonRegistry.registerSchema(launchSchemaId, launchSchema); } getLaunches(): ILaunch[] { return this.launches; } getLaunch(workspaceUri: uri | undefined): ILaunch | undefined { if (!uri.isUri(workspaceUri)) { return undefined; } return this.launches.find(l => l.workspace && this.uriIdentityService.extUri.isEqual(l.workspace.uri, workspaceUri)); } get selectedConfiguration(): { launch: ILaunch | undefined, name: string | undefined, getConfig: () => Promise<IConfig | undefined>, type: string | undefined } { return { launch: this.selectedLaunch, name: this.selectedName, getConfig: this.getSelectedConfig, type: this.selectedType }; } get onDidSelectConfiguration(): Event<void> { return this._onDidSelectConfigurationName.event; } getWorkspaceLaunch(): ILaunch | undefined { if (this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE) { return this.launches[this.launches.length - 1]; } return undefined; } async selectConfiguration(launch: ILaunch | undefined, name?: string, config?: IConfig, dynamicConfig?: { type?: string }): Promise<void> { if (typeof launch === 'undefined') { const rootUri = this.historyService.getLastActiveWorkspaceRoot(); launch = this.getLaunch(rootUri); if (!launch || launch.getConfigurationNames().length === 0) { launch = this.launches.find(l => !!(l && l.getConfigurationNames().length)) || launch || this.launches[0]; } } const previousLaunch = this.selectedLaunch; const previousName = this.selectedName; this.selectedLaunch = launch; if (this.selectedLaunch) { this.storageService.store(DEBUG_SELECTED_ROOT, this.selectedLaunch.uri.toString(), StorageScope.WORKSPACE, StorageTarget.MACHINE); } else { this.storageService.remove(DEBUG_SELECTED_ROOT, StorageScope.WORKSPACE); } const names = launch ? launch.getConfigurationNames() : []; this.getSelectedConfig = () => Promise.resolve(config); let type = config?.type; if (name && names.indexOf(name) >= 0) { this.setSelectedLaunchName(name); } else if (dynamicConfig && dynamicConfig.type) { // We could not find the previously used name and config is not passed. We should get all dynamic configurations from providers // And potentially auto select the previously used dynamic configuration #96293 type = dynamicConfig.type; if (!config) { const providers = (await this.getDynamicProviders()).filter(p => p.type === type); this.getSelectedConfig = async () => { const activatedProviders = await Promise.all(providers.map(p => p.getProvider())); const provider = activatedProviders.length > 0 ? activatedProviders[0] : undefined; if (provider && launch && launch.workspace) { const token = new CancellationTokenSource(); const dynamicConfigs = await provider.provideDebugConfigurations!(launch.workspace.uri, token.token); const dynamicConfig = dynamicConfigs.find(c => c.name === name); if (dynamicConfig) { return dynamicConfig; } } return undefined; }; } this.setSelectedLaunchName(name); let recentDynamicProviders = this.getRecentDynamicConfigurations(); if (name && dynamicConfig.type) { // We need to store the recently used dynamic configurations to be able to show them in UI #110009 recentDynamicProviders.unshift({ name, type: dynamicConfig.type }); recentDynamicProviders = distinct(recentDynamicProviders, t => `${t.name} : ${t.type}`); this.storageService.store(DEBUG_RECENT_DYNAMIC_CONFIGURATIONS, JSON.stringify(recentDynamicProviders), StorageScope.WORKSPACE, StorageTarget.USER); } } else if (!this.selectedName || names.indexOf(this.selectedName) === -1) { // We could not find the configuration to select, pick the first one, or reset the selection if there is no launch configuration const nameToSet = names.length ? names[0] : undefined; this.setSelectedLaunchName(nameToSet); } if (!config && launch && this.selectedName) { config = launch.getConfiguration(this.selectedName); type = config?.type; } this.selectedType = dynamicConfig?.type || config?.type; // Only store the selected type if we are having a dynamic configuration. Otherwise restoring this configuration from storage might be misindentified as a dynamic configuration this.storageService.store(DEBUG_SELECTED_TYPE, dynamicConfig ? this.selectedType : undefined, StorageScope.WORKSPACE, StorageTarget.MACHINE); if (type) { this.debugConfigurationTypeContext.set(type); } else { this.debugConfigurationTypeContext.reset(); } if (this.selectedLaunch !== previousLaunch || this.selectedName !== previousName) { this._onDidSelectConfigurationName.fire(); } } async activateDebuggers(activationEvent: string, debugType?: string): Promise<void> { const promises: Promise<any>[] = [ this.extensionService.activateByEvent(activationEvent), this.extensionService.activateByEvent('onDebug') ]; if (debugType) { promises.push(this.extensionService.activateByEvent(`${activationEvent}:${debugType}`)); } await Promise.all(promises); } private setSelectedLaunchName(selectedName: string | undefined): void { this.selectedName = selectedName; if (this.selectedName) { this.storageService.store(DEBUG_SELECTED_CONFIG_NAME_KEY, this.selectedName, StorageScope.WORKSPACE, StorageTarget.MACHINE); } else { this.storageService.remove(DEBUG_SELECTED_CONFIG_NAME_KEY, StorageScope.WORKSPACE); } } dispose(): void { this.toDispose = dispose(this.toDispose); } } abstract class AbstractLaunch { protected abstract getConfig(): IGlobalConfig | undefined; constructor( protected configurationManager: ConfigurationManager, private readonly adapterManager: AdapterManager ) { } getCompound(name: string): ICompound | undefined { const config = this.getConfig(); if (!config || !config.compounds) { return undefined; } return config.compounds.find(compound => compound.name === name); } getConfigurationNames(ignoreCompoundsAndPresentation = false): string[] { const config = this.getConfig(); if (!config || (!Array.isArray(config.configurations) && !Array.isArray(config.compounds))) { return []; } else { const configurations: (IConfig | ICompound)[] = []; if (config.configurations) { configurations.push(...config.configurations.filter(cfg => cfg && typeof cfg.name === 'string')); } if (ignoreCompoundsAndPresentation) { return configurations.map(c => c.name); } if (config.compounds) { configurations.push(...config.compounds.filter(compound => typeof compound.name === 'string' && compound.configurations && compound.configurations.length)); } return getVisibleAndSorted(configurations).map(c => c.name); } } getConfiguration(name: string): IConfig | undefined { // We need to clone the configuration in order to be able to make changes to it #42198 const config = objects.deepClone(this.getConfig()); if (!config || !config.configurations) { return undefined; } const configuration = config.configurations.find(config => config && config.name === name); if (configuration) { if (this instanceof UserLaunch) { configuration.__configurationTarget = ConfigurationTarget.USER; } else if (this instanceof WorkspaceLaunch) { configuration.__configurationTarget = ConfigurationTarget.WORKSPACE; } else { configuration.__configurationTarget = ConfigurationTarget.WORKSPACE_FOLDER; } } return configuration; } async getInitialConfigurationContent(folderUri?: uri, type?: string, token?: CancellationToken): Promise<string> { let content = ''; const adapter = await this.adapterManager.guessDebugger(true, type); if (adapter) { const initialConfigs = await this.configurationManager.provideDebugConfigurations(folderUri, adapter.type, token || CancellationToken.None); content = await adapter.getInitialConfigurationContent(initialConfigs); } return content; } get hidden(): boolean { return false; } } class Launch extends AbstractLaunch implements ILaunch { constructor( configurationManager: ConfigurationManager, adapterManager: AdapterManager, public workspace: IWorkspaceFolder, @IFileService private readonly fileService: IFileService, @ITextFileService private readonly textFileService: ITextFileService, @IEditorService private readonly editorService: IEditorService, @IConfigurationService private readonly configurationService: IConfigurationService ) { super(configurationManager, adapterManager); } get uri(): uri { return resources.joinPath(this.workspace.uri, '/.vscode/launch.json'); } get name(): string { return this.workspace.name; } protected getConfig(): IGlobalConfig | undefined { return this.configurationService.inspect<IGlobalConfig>('launch', { resource: this.workspace.uri }).workspaceFolderValue; } async openConfigFile(preserveFocus: boolean, type?: string, token?: CancellationToken): Promise<{ editor: IEditorPane | null, created: boolean }> { const resource = this.uri; let created = false; let content = ''; try { const fileContent = await this.fileService.readFile(resource); content = fileContent.value.toString(); } catch { // launch.json not found: create one by collecting launch configs from debugConfigProviders content = await this.getInitialConfigurationContent(this.workspace.uri, type, token); if (content) { created = true; // pin only if config file is created #8727 try { await this.textFileService.write(resource, content); } catch (error) { throw new Error(nls.localize('DebugConfig.failed', "Unable to create 'launch.json' file inside the '.vscode' folder ({0}).", error.message)); } } } if (content === '') { return { editor: null, created: false }; } const index = content.indexOf(`"${this.configurationManager.selectedConfiguration.name}"`); let startLineNumber = 1; for (let i = 0; i < index; i++) { if (content.charAt(i) === '\n') { startLineNumber++; } } const selection = startLineNumber > 1 ? { startLineNumber, startColumn: 4 } : undefined; const editor = await this.editorService.openEditor({ resource, options: { selection, preserveFocus, pinned: created, revealIfVisible: true }, }, ACTIVE_GROUP); return ({ editor: withUndefinedAsNull(editor), created }); } async writeConfiguration(configuration: IConfig): Promise<void> { const fullConfig = objects.deepClone(this.getConfig()!); if (!fullConfig.configurations) { fullConfig.configurations = []; } fullConfig.configurations.push(configuration); await this.configurationService.updateValue('launch', fullConfig, { resource: this.workspace.uri }, ConfigurationTarget.WORKSPACE_FOLDER); } } class WorkspaceLaunch extends AbstractLaunch implements ILaunch { constructor( configurationManager: ConfigurationManager, adapterManager: AdapterManager, @IEditorService private readonly editorService: IEditorService, @IConfigurationService private readonly configurationService: IConfigurationService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService ) { super(configurationManager, adapterManager); } get workspace(): undefined { return undefined; } get uri(): uri { return this.contextService.getWorkspace().configuration!; } get name(): string { return nls.localize('workspace', "workspace"); } protected getConfig(): IGlobalConfig | undefined { return this.configurationService.inspect<IGlobalConfig>('launch').workspaceValue; } async openConfigFile(preserveFocus: boolean, type?: string, token?: CancellationToken): Promise<{ editor: IEditorPane | null, created: boolean }> { let launchExistInFile = !!this.getConfig(); if (!launchExistInFile) { // Launch property in workspace config not found: create one by collecting launch configs from debugConfigProviders let content = await this.getInitialConfigurationContent(undefined, type, token); if (content) { await this.configurationService.updateValue('launch', json.parse(content), ConfigurationTarget.WORKSPACE); } else { return { editor: null, created: false }; } } const editor = await this.editorService.openEditor({ resource: this.contextService.getWorkspace().configuration!, options: { preserveFocus } }, ACTIVE_GROUP); return ({ editor: withUndefinedAsNull(editor), created: false }); } } class UserLaunch extends AbstractLaunch implements ILaunch { constructor( configurationManager: ConfigurationManager, adapterManager: AdapterManager, @IConfigurationService private readonly configurationService: IConfigurationService, @IPreferencesService private readonly preferencesService: IPreferencesService ) { super(configurationManager, adapterManager); } get workspace(): undefined { return undefined; } get uri(): uri { return this.preferencesService.userSettingsResource; } get name(): string { return nls.localize('user settings', "user settings"); } override get hidden(): boolean { return true; } protected getConfig(): IGlobalConfig | undefined { return this.configurationService.inspect<IGlobalConfig>('launch').userValue; } async openConfigFile(preserveFocus: boolean): Promise<{ editor: IEditorPane | null, created: boolean }> { const editor = await this.preferencesService.openGlobalSettings(true, { preserveFocus, revealSetting: { key: 'launch' } }); return ({ editor: withUndefinedAsNull(editor), created: false }); } }
src/vs/workbench/contrib/debug/browser/debugConfigurationManager.ts
0
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.0001768948568496853, 0.0001716723490972072, 0.00016133736062329262, 0.00017191984807141125, 0.0000029334046303119976 ]
{ "id": 5, "code_window": [ "\n", "\t\t\t\tconst matches = previewContainerNode.innerText.match(unsupportedKatexTermsRegex);\n", "\t\t\t\tif (matches) {\n", "\t\t\t\t\tpostNotebookMessage<webviewMessages.ITelemetryFoundUnrenderedMarkdownMath>('telemetryFoundUnrenderedMarkdownMath', {\n", "\t\t\t\t\t\tlatexDirective: matches[0],\n", "\t\t\t\t\t});\n", "\t\t\t\t}\n", "\t\t\t}\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "\t\t\tawait renderers.render(createMarkdownOutputItem(cellId, previewContainerNode, content), previewContainerNode);\n", "\n", "\t\t\tif (!hasPostedRenderedMathTelemetry) {\n", "\t\t\t\tconst hasRenderedMath = previewContainerNode.querySelector('.katex');\n", "\t\t\t\tif (hasRenderedMath) {\n", "\t\t\t\t\thasPostedRenderedMathTelemetry = true;\n", "\t\t\t\t\tpostNotebookMessage<webviewMessages.ITelemetryFoundRenderedMarkdownMath>('telemetryFoundRenderedMarkdownMath', {});\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads.ts", "type": "replace", "edit_start_line_idx": 1015 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { StandardTokenType } from 'vs/editor/common/modes'; import * as fs from 'fs'; // import { getPathFromAmdModule } from 'vs/base/test/node/testUtils'; // import { parse } from 'vs/editor/common/modes/tokenization/typescript'; import { toStandardTokenType } from 'vs/editor/common/modes/supports/tokenization'; interface IParseFunc { (text: string): number[]; } interface IAssertion { testLineNumber: number; startOffset: number; length: number; tokenType: StandardTokenType; } interface ITest { content: string; assertions: IAssertion[]; } function parseTest(fileName: string): ITest { interface ILineWithAssertions { line: string; assertions: ILineAssertion[]; } interface ILineAssertion { testLineNumber: number; startOffset: number; length: number; expectedTokenType: StandardTokenType; } const testContents = fs.readFileSync(fileName).toString(); const lines = testContents.split(/\r\n|\n/); const magicToken = lines[0]; let currentElement: ILineWithAssertions = { line: lines[1], assertions: [] }; let parsedTest: ILineWithAssertions[] = []; for (let i = 2; i < lines.length; i++) { let line = lines[i]; if (line.substr(0, magicToken.length) === magicToken) { // this is an assertion line let m1 = line.substr(magicToken.length).match(/^( +)([\^]+) (\w+)\\?$/); if (m1) { currentElement.assertions.push({ testLineNumber: i + 1, startOffset: magicToken.length + m1[1].length, length: m1[2].length, expectedTokenType: toStandardTokenType(m1[3]) }); } else { let m2 = line.substr(magicToken.length).match(/^( +)<(-+) (\w+)\\?$/); if (m2) { currentElement.assertions.push({ testLineNumber: i + 1, startOffset: 0, length: m2[2].length, expectedTokenType: toStandardTokenType(m2[3]) }); } else { throw new Error(`Invalid test line at line number ${i + 1}.`); } } } else { // this is a line to be parsed parsedTest.push(currentElement); currentElement = { line: line, assertions: [] }; } } parsedTest.push(currentElement); let assertions: IAssertion[] = []; let offset = 0; for (let i = 0; i < parsedTest.length; i++) { const parsedTestLine = parsedTest[i]; for (let j = 0; j < parsedTestLine.assertions.length; j++) { const assertion = parsedTestLine.assertions[j]; assertions.push({ testLineNumber: assertion.testLineNumber, startOffset: offset + assertion.startOffset, length: assertion.length, tokenType: assertion.expectedTokenType }); } offset += parsedTestLine.line.length + 1; } let content: string = parsedTest.map(parsedTestLine => parsedTestLine.line).join('\n'); return { content, assertions }; } // @ts-expect-error function executeTest(fileName: string, parseFunc: IParseFunc): void { const { content, assertions } = parseTest(fileName); const actual = parseFunc(content); let actualIndex = 0, actualCount = actual.length / 3; for (let i = 0; i < assertions.length; i++) { const assertion = assertions[i]; while (actualIndex < actualCount && actual[3 * actualIndex] + actual[3 * actualIndex + 1] <= assertion.startOffset) { actualIndex++; } assert.ok( actual[3 * actualIndex] <= assertion.startOffset, `Line ${assertion.testLineNumber} : startOffset : ${actual[3 * actualIndex]} <= ${assertion.startOffset}` ); assert.ok( actual[3 * actualIndex] + actual[3 * actualIndex + 1] >= assertion.startOffset + assertion.length, `Line ${assertion.testLineNumber} : length : ${actual[3 * actualIndex]} + ${actual[3 * actualIndex + 1]} >= ${assertion.startOffset} + ${assertion.length}.` ); assert.strictEqual( actual[3 * actualIndex + 2], assertion.tokenType, `Line ${assertion.testLineNumber} : tokenType`); } } suite('Classification', () => { test('TypeScript', () => { // executeTest(getPathFromAmdModule(require, 'vs/editor/test/node/classification/typescript-test.ts').replace(/\bout\b/, 'src'), parse); }); });
src/vs/editor/test/node/classification/typescript.test.ts
0
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.00017742982890922576, 0.00017232507525477558, 0.00016817486903164536, 0.00017280405154451728, 0.0000026431184778630268 ]
{ "id": 5, "code_window": [ "\n", "\t\t\t\tconst matches = previewContainerNode.innerText.match(unsupportedKatexTermsRegex);\n", "\t\t\t\tif (matches) {\n", "\t\t\t\t\tpostNotebookMessage<webviewMessages.ITelemetryFoundUnrenderedMarkdownMath>('telemetryFoundUnrenderedMarkdownMath', {\n", "\t\t\t\t\t\tlatexDirective: matches[0],\n", "\t\t\t\t\t});\n", "\t\t\t\t}\n", "\t\t\t}\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "\t\t\tawait renderers.render(createMarkdownOutputItem(cellId, previewContainerNode, content), previewContainerNode);\n", "\n", "\t\t\tif (!hasPostedRenderedMathTelemetry) {\n", "\t\t\t\tconst hasRenderedMath = previewContainerNode.querySelector('.katex');\n", "\t\t\t\tif (hasRenderedMath) {\n", "\t\t\t\t\thasPostedRenderedMathTelemetry = true;\n", "\t\t\t\t\tpostNotebookMessage<webviewMessages.ITelemetryFoundRenderedMarkdownMath>('telemetryFoundRenderedMarkdownMath', {});\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads.ts", "type": "replace", "edit_start_line_idx": 1015 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /* Use custom CSS vars to expose padding into parent select for padding calculation */ .monaco-select-box-dropdown-padding { --dropdown-padding-top: 1px; --dropdown-padding-bottom: 1px; } .hc-black .monaco-select-box-dropdown-padding { --dropdown-padding-top: 3px; --dropdown-padding-bottom: 4px; } .monaco-select-box-dropdown-container { display: none; box-sizing: border-box; } .monaco-select-box-dropdown-container > .select-box-details-pane > .select-box-description-markdown * { margin: 0; } .monaco-select-box-dropdown-container > .select-box-details-pane > .select-box-description-markdown a:focus { outline: 1px solid -webkit-focus-ring-color; outline-offset: -1px; } .monaco-select-box-dropdown-container > .select-box-details-pane > .select-box-description-markdown code { line-height: 15px; /** For some reason, this is needed, otherwise <code> will take up 20px height */ font-family: var(--monaco-monospace-font); } .monaco-select-box-dropdown-container.visible { display: flex; flex-direction: column; text-align: left; width: 1px; overflow: hidden; } .monaco-select-box-dropdown-container > .select-box-dropdown-list-container { flex: 0 0 auto; align-self: flex-start; padding-top: var(--dropdown-padding-top); padding-bottom: var(--dropdown-padding-bottom); padding-left: 1px; padding-right: 1px; width: 100%; overflow: hidden; box-sizing: border-box; } .monaco-select-box-dropdown-container > .select-box-details-pane { padding: 5px; } .hc-black .monaco-select-box-dropdown-container > .select-box-dropdown-list-container { padding-top: var(--dropdown-padding-top); padding-bottom: var(--dropdown-padding-bottom); } .monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row { cursor: pointer; } .monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row > .option-text { text-overflow: ellipsis; overflow: hidden; padding-left: 3.5px; white-space: nowrap; float: left; } .monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row > .option-detail { text-overflow: ellipsis; overflow: hidden; padding-left: 3.5px; white-space: nowrap; float: left; opacity: 0.7; } .monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row > .option-decorator-right { text-overflow: ellipsis; overflow: hidden; padding-right: 10px; white-space: nowrap; float: right; } /* Accepted CSS hiding technique for accessibility reader text */ /* https://webaim.org/techniques/css/invisiblecontent/ */ .monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row > .visually-hidden { position: absolute; left: -10000px; top: auto; width: 1px; height: 1px; overflow: hidden; } .monaco-select-box-dropdown-container > .select-box-dropdown-container-width-control { flex: 1 1 auto; align-self: flex-start; opacity: 0; } .monaco-select-box-dropdown-container > .select-box-dropdown-container-width-control > .width-control-div { overflow: hidden; max-height: 0px; } .monaco-select-box-dropdown-container > .select-box-dropdown-container-width-control > .width-control-div > .option-text-width-control { padding-left: 4px; padding-right: 8px; white-space: nowrap; }
src/vs/base/browser/ui/selectBox/selectBoxCustom.css
0
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.0001737163111101836, 0.00016980258806142956, 0.0001643770228838548, 0.00016995631449390203, 0.0000028619922431971645 ]
{ "id": 6, "code_window": [ "\t\t\t\t}\n", "\t\t\t}\n", "\t\t}\n", "\n", "\t\tdimensionUpdater.update(cellId, previewContainerNode.clientHeight, {\n", "\t\t\tisOutput: false\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\t\tconst matches = previewContainerNode.innerText.match(unsupportedKatexTermsRegex);\n", "\t\t\tif (matches) {\n", "\t\t\t\tpostNotebookMessage<webviewMessages.ITelemetryFoundUnrenderedMarkdownMath>('telemetryFoundUnrenderedMarkdownMath', {\n", "\t\t\t\t\tlatexDirective: matches[0],\n", "\t\t\t\t});\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads.ts", "type": "add", "edit_start_line_idx": 1022 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IAction } from 'vs/base/common/actions'; import { coalesce } from 'vs/base/common/arrays'; import { VSBuffer } from 'vs/base/common/buffer'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable } from 'vs/base/common/lifecycle'; import { getExtensionForMimeType } from 'vs/base/common/mime'; import { FileAccess, Schemas } from 'vs/base/common/network'; import { isMacintosh, isWeb } from 'vs/base/common/platform'; import { dirname, joinPath } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import * as UUID from 'vs/base/common/uuid'; import * as nls from 'vs/nls'; import { createAndFillInContextMenuActions } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { IMenuService, MenuId } from 'vs/platform/actions/common/actions'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IFileDialogService } from 'vs/platform/dialogs/common/dialogs'; import { IFileService } from 'vs/platform/files/common/files'; import { IOpenerService, matchesScheme } from 'vs/platform/opener/common/opener'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { asWebviewUri } from 'vs/workbench/api/common/shared/webview'; import { CellEditState, ICellOutputViewModel, ICommonCellInfo, ICommonNotebookEditor, IDisplayOutputLayoutUpdateRequest, IDisplayOutputViewModel, IGenericCellViewModel, IInsetRenderOutput, RenderOutputType } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { preloadsScriptStr, RendererMetadata } from 'vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads'; import { transformWebviewThemeVars } from 'vs/workbench/contrib/notebook/browser/view/renderers/webviewThemeMapping'; import { MarkdownCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/markdownCellViewModel'; import { INotebookKernel, INotebookRendererInfo, RendererMessagingSpec } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { IScopedRendererMessaging } from 'vs/workbench/contrib/notebook/common/notebookRendererMessagingService'; import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService'; import { IWebviewService, WebviewContentPurpose, WebviewElement } from 'vs/workbench/contrib/webview/browser/webview'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { ICreationRequestMessage, IMarkdownCellInitialization, FromWebviewMessage, IClickedDataUrlMessage, IContentWidgetTopRequest, IControllerPreload, ToWebviewMessage } from './webviewMessages'; export interface ICachedInset<K extends ICommonCellInfo> { outputId: string; cellInfo: K; renderer?: INotebookRendererInfo; cachedCreation: ICreationRequestMessage; } function html(strings: TemplateStringsArray, ...values: any[]): string { let str = ''; strings.forEach((string, i) => { str += string + (values[i] || ''); }); return str; } export interface INotebookWebviewMessage { message: unknown; } export interface IResolvedBackLayerWebview { webview: WebviewElement; } export class BackLayerWebView<T extends ICommonCellInfo> extends Disposable { element: HTMLElement; webview: WebviewElement | undefined = undefined; insetMapping: Map<IDisplayOutputViewModel, ICachedInset<T>> = new Map(); readonly markdownPreviewMapping = new Map<string, IMarkdownCellInitialization>(); hiddenInsetMapping: Set<IDisplayOutputViewModel> = new Set(); reversedInsetMapping: Map<string, IDisplayOutputViewModel> = new Map(); localResourceRootsCache: URI[] | undefined = undefined; rendererRootsCache: URI[] = []; private readonly _onMessage = this._register(new Emitter<INotebookWebviewMessage>()); private readonly _preloadsCache = new Set<string>(); public readonly onMessage: Event<INotebookWebviewMessage> = this._onMessage.event; private _initalized?: Promise<void>; private _disposed = false; private _currentKernel?: INotebookKernel; constructor( public readonly notebookEditor: ICommonNotebookEditor, public readonly id: string, public readonly documentUri: URI, private options: { outputNodePadding: number, outputNodeLeftPadding: number, previewNodePadding: number, markdownLeftMargin: number, leftMargin: number, rightMargin: number, runGutter: number, dragAndDropEnabled: boolean, fontSize: number }, private readonly rendererMessaging: IScopedRendererMessaging | undefined, @IWebviewService readonly webviewService: IWebviewService, @IOpenerService readonly openerService: IOpenerService, @INotebookService private readonly notebookService: INotebookService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService, @IFileDialogService private readonly fileDialogService: IFileDialogService, @IFileService private readonly fileService: IFileService, @IContextMenuService private readonly contextMenuService: IContextMenuService, @IMenuService private readonly menuService: IMenuService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @ITelemetryService private readonly telemetryService: ITelemetryService, ) { super(); this.element = document.createElement('div'); this.element.style.height = '1400px'; this.element.style.position = 'absolute'; if (rendererMessaging) { this._register(rendererMessaging.onDidReceiveMessage(evt => { this._sendMessageToWebview({ __vscode_notebook_message: true, type: 'customRendererMessage', rendererId: evt.rendererId, message: evt.message }); })); } } updateOptions(options: { outputNodePadding: number, outputNodeLeftPadding: number, previewNodePadding: number, markdownLeftMargin: number, leftMargin: number, rightMargin: number, runGutter: number, dragAndDropEnabled: boolean, fontSize: number }) { this.options = options; this._updateStyles(); this._updateOptions(); } private _updateStyles() { this._sendMessageToWebview({ type: 'notebookStyles', styles: this._generateStyles() }); } private _updateOptions() { this._sendMessageToWebview({ type: 'notebookOptions', options: { dragAndDropEnabled: this.options.dragAndDropEnabled } }); } private _generateStyles() { return { 'notebook-output-left-margin': `${this.options.leftMargin + this.options.runGutter}px`, 'notebook-output-width': `calc(100% - ${this.options.leftMargin + this.options.rightMargin + this.options.runGutter}px)`, 'notebook-output-node-padding': `${this.options.outputNodePadding}px`, 'notebook-run-gutter': `${this.options.runGutter}px`, 'notebook-preivew-node-padding': `${this.options.previewNodePadding}px`, 'notebook-markdown-left-margin': `${this.options.markdownLeftMargin}px`, 'notebook-output-node-left-padding': `${this.options.outputNodeLeftPadding}px`, 'notebook-markdown-min-height': `${this.options.previewNodePadding * 2}px`, 'notebook-cell-output-font-size': `${this.options.fontSize}px` }; } private generateContent(coreDependencies: string, baseUrl: string) { const renderersData = this.getRendererData(); return html` <html lang="en"> <head> <meta charset="UTF-8"> <base href="${baseUrl}/"/> <style> #container .cell_container { width: 100%; } #container .output_container { width: 100%; } #container > div > div > div.output { font-size: var(--notebook-cell-output-font-size); width: var(--notebook-output-width); margin-left: var(--notebook-output-left-margin); padding-top: var(--notebook-output-node-padding); padding-right: var(--notebook-output-node-padding); padding-bottom: var(--notebook-output-node-padding); padding-left: var(--notebook-output-node-left-padding); box-sizing: border-box; background-color: var(--theme-notebook-output-background); } /* markdown */ #container > div.preview { width: 100%; padding-right: var(--notebook-preivew-node-padding); padding-left: var(--notebook-markdown-left-margin); padding-top: var(--notebook-preivew-node-padding); padding-bottom: var(--notebook-preivew-node-padding); box-sizing: border-box; white-space: nowrap; overflow: hidden; white-space: initial; color: var(--theme-ui-foreground); } #container > div.preview.draggable { user-select: none; -webkit-user-select: none; -ms-user-select: none; cursor: grab; } #container > div.preview.emptyMarkdownCell::before { content: "${nls.localize('notebook.emptyMarkdownPlaceholder', "Empty markdown cell, double click or press enter to edit.")}"; font-style: italic; opacity: 0.6; } #container > div.preview.selected { background: var(--theme-notebook-cell-selected-background); } #container > div.preview.dragging { background-color: var(--theme-background); } .monaco-workbench.vs-dark .notebookOverlay .cell.markdown .latex img, .monaco-workbench.vs-dark .notebookOverlay .cell.markdown .latex-block img { filter: brightness(0) invert(1) } #container > div.nb-symbolHighlight { background-color: var(--theme-notebook-symbol-highlight-background); } #container > div.nb-cellDeleted { background-color: var(--theme-notebook-diff-removed-background); } #container > div.nb-cellAdded { background-color: var(--theme-notebook-diff-inserted-background); } #container > div > div:not(.preview) > div { overflow-x: scroll; } body { padding: 0px; height: 100%; width: 100%; } table, thead, tr, th, td, tbody { border: none !important; border-color: transparent; border-spacing: 0; border-collapse: collapse; } table { width: 100%; } table, th, tr { text-align: left !important; } thead { font-weight: bold; background-color: rgba(130, 130, 130, 0.16); } th, td { padding: 4px 8px; } tr:nth-child(even) { background-color: rgba(130, 130, 130, 0.08); } tbody th { font-weight: normal; } </style> </head> <body style="overflow: hidden;"> <script> self.require = {}; </script> ${coreDependencies} <div id='container' class="widgetarea" style="position: absolute;width:100%;top: 0px"></div> <script type="module">${preloadsScriptStr(this.options, { dragAndDropEnabled: this.options.dragAndDropEnabled }, renderersData)}</script> </body> </html>`; } private getRendererData(): RendererMetadata[] { return this.notebookService.getRenderers().map((renderer): RendererMetadata => { const entrypoint = this.asWebviewUri(renderer.entrypoint, renderer.extensionLocation).toString(); return { id: renderer.id, entrypoint, mimeTypes: renderer.mimeTypes, extends: renderer.extends, messaging: renderer.messaging !== RendererMessagingSpec.Never, }; }); } private asWebviewUri(uri: URI, fromExtension: URI | undefined) { return asWebviewUri(uri, fromExtension?.scheme === Schemas.vscodeRemote ? { isRemote: true, authority: fromExtension.authority } : undefined); } postKernelMessage(message: any) { this._sendMessageToWebview({ __vscode_notebook_message: true, type: 'customKernelMessage', message, }); } private resolveOutputId(id: string): { cellInfo: T, output: ICellOutputViewModel } | undefined { const output = this.reversedInsetMapping.get(id); if (!output) { return; } const cellInfo = this.insetMapping.get(output)!.cellInfo; return { cellInfo, output }; } isResolved(): this is IResolvedBackLayerWebview { return !!this.webview; } async createWebview(): Promise<void> { const baseUrl = this.asWebviewUri(dirname(this.documentUri), undefined); // Python hasn't moved to use a preload to load require support yet. // For all other notebooks, we no longer want to include our loader. if (!this.documentUri.path.toLowerCase().endsWith('.ipynb')) { const htmlContent = this.generateContent('', baseUrl.toString()); this._initialize(htmlContent); return; } let coreDependencies = ''; let resolveFunc: () => void; this._initalized = new Promise<void>((resolve, reject) => { resolveFunc = resolve; }); if (!isWeb) { const loaderUri = FileAccess.asFileUri('vs/loader.js', require); const loader = this.asWebviewUri(loaderUri, undefined); coreDependencies = `<script src="${loader}"></script><script> var requirejs = (function() { return require; }()); </script>`; const htmlContent = this.generateContent(coreDependencies, baseUrl.toString()); this._initialize(htmlContent); resolveFunc!(); } else { const loaderUri = FileAccess.asBrowserUri('vs/loader.js', require); fetch(loaderUri.toString(true)).then(async response => { if (response.status !== 200) { throw new Error(response.statusText); } const loaderJs = await response.text(); coreDependencies = ` <script> ${loaderJs} </script> <script> var requirejs = (function() { return require; }()); </script> `; const htmlContent = this.generateContent(coreDependencies, baseUrl.toString()); this._initialize(htmlContent); resolveFunc!(); }, error => { // the fetch request is rejected const htmlContent = this.generateContent(coreDependencies, baseUrl.toString()); this._initialize(htmlContent); resolveFunc!(); }); } await this._initalized; } private _initialize(content: string) { if (!document.body.contains(this.element)) { throw new Error('Element is already detached from the DOM tree'); } this.webview = this._createInset(this.webviewService, content); this.webview.mountTo(this.element); this._register(this.webview); this._register(this.webview.onDidClickLink(link => { if (this._disposed) { return; } if (!link) { return; } if (matchesScheme(link, Schemas.command)) { console.warn('Command links are deprecated and will be removed, use messag passing instead: https://github.com/microsoft/vscode/issues/123601'); } if (matchesScheme(link, Schemas.http) || matchesScheme(link, Schemas.https) || matchesScheme(link, Schemas.mailto) || matchesScheme(link, Schemas.command)) { this.openerService.open(link, { fromUserGesture: true, allowContributedOpeners: true, allowCommands: true }); } })); this._register(this.webview.onMessage((message) => { const data: FromWebviewMessage | { readonly __vscode_notebook_message: undefined } = message.message; if (this._disposed) { return; } if (!data.__vscode_notebook_message) { return; } switch (data.type) { case 'initialized': this.initializeWebViewState(); break; case 'dimension': { for (const update of data.updates) { const height = update.height; if (update.isOutput) { const resolvedResult = this.resolveOutputId(update.id); if (resolvedResult) { const { cellInfo, output } = resolvedResult; this.notebookEditor.updateOutputHeight(cellInfo, output, height, !!update.init, 'webview#dimension'); this.notebookEditor.scheduleOutputHeightAck(cellInfo, update.id, height); } } else { this.notebookEditor.updateMarkdownCellHeight(update.id, height, !!update.init); } } break; } case 'mouseenter': { const resolvedResult = this.resolveOutputId(data.id); if (resolvedResult) { const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo); if (latestCell) { latestCell.outputIsHovered = true; } } break; } case 'mouseleave': { const resolvedResult = this.resolveOutputId(data.id); if (resolvedResult) { const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo); if (latestCell) { latestCell.outputIsHovered = false; } } break; } case 'outputFocus': { const resolvedResult = this.resolveOutputId(data.id); if (resolvedResult) { const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo); if (latestCell) { latestCell.outputIsFocused = true; } } break; } case 'outputBlur': { const resolvedResult = this.resolveOutputId(data.id); if (resolvedResult) { const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo); if (latestCell) { latestCell.outputIsFocused = false; } } break; } case 'scroll-ack': { // const date = new Date(); // const top = data.data.top; // console.log('ack top ', top, ' version: ', data.version, ' - ', date.getMinutes() + ':' + date.getSeconds() + ':' + date.getMilliseconds()); break; } case 'did-scroll-wheel': { this.notebookEditor.triggerScroll({ ...data.payload, preventDefault: () => { }, stopPropagation: () => { } }); break; } case 'focus-editor': { const resolvedResult = this.resolveOutputId(data.id); if (resolvedResult) { const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo); if (!latestCell) { return; } if (data.focusNext) { this.notebookEditor.focusNextNotebookCell(latestCell, 'editor'); } else { this.notebookEditor.focusNotebookCell(latestCell, 'editor'); } } break; } case 'clicked-data-url': { this._onDidClickDataLink(data); break; } case 'customKernelMessage': { this._onMessage.fire({ message: data.message }); break; } case 'customRendererMessage': { this.rendererMessaging?.postMessage(data.rendererId, data.message); break; } case 'clickMarkdownPreview': { const cell = this.notebookEditor.getCellById(data.cellId); if (cell) { if (data.shiftKey || (isMacintosh ? data.metaKey : data.ctrlKey)) { // Modify selection this.notebookEditor.toggleNotebookCellSelection(cell, /* fromPrevious */ data.shiftKey); } else { // Normal click this.notebookEditor.focusNotebookCell(cell, 'container', { skipReveal: true }); } } break; } case 'contextMenuMarkdownPreview': { const cell = this.notebookEditor.getCellById(data.cellId); if (cell) { // Focus the cell first this.notebookEditor.focusNotebookCell(cell, 'container', { skipReveal: true }); // Then show the context menu const webviewRect = this.element.getBoundingClientRect(); this.contextMenuService.showContextMenu({ getActions: () => { const result: IAction[] = []; const menu = this.menuService.createMenu(MenuId.NotebookCellTitle, this.contextKeyService); createAndFillInContextMenuActions(menu, undefined, result); menu.dispose(); return result; }, getAnchor: () => ({ x: webviewRect.x + data.clientX, y: webviewRect.y + data.clientY }) }); } break; } case 'toggleMarkdownPreview': { const cell = this.notebookEditor.getCellById(data.cellId); if (cell) { this.notebookEditor.setMarkdownCellEditState(data.cellId, CellEditState.Editing); this.notebookEditor.focusNotebookCell(cell, 'editor', { skipReveal: true }); } break; } case 'mouseEnterMarkdownPreview': { const cell = this.notebookEditor.getCellById(data.cellId); if (cell instanceof MarkdownCellViewModel) { cell.cellIsHovered = true; } break; } case 'mouseLeaveMarkdownPreview': { const cell = this.notebookEditor.getCellById(data.cellId); if (cell instanceof MarkdownCellViewModel) { cell.cellIsHovered = false; } break; } case 'cell-drag-start': { this.notebookEditor.markdownCellDragStart(data.cellId, data); break; } case 'cell-drag': { this.notebookEditor.markdownCellDrag(data.cellId, data); break; } case 'cell-drop': { this.notebookEditor.markdownCellDrop(data.cellId, { dragOffsetY: data.dragOffsetY, ctrlKey: data.ctrlKey, altKey: data.altKey, }); break; } case 'cell-drag-end': { this.notebookEditor.markdownCellDragEnd(data.cellId); break; } case 'telemetryFoundRenderedMarkdownMath': { this.telemetryService.publicLog2<{}, {}>('notebook/markdown/renderedLatex', {}); break; } case 'telemetryFoundUnrenderedMarkdownMath': { type Classification = { latexDirective: { classification: 'SystemMetaData', purpose: 'FeatureInsight'; }; }; type TelemetryEvent = { latexDirective: string; }; this.telemetryService.publicLog2<TelemetryEvent, Classification>('notebook/markdown/foundUnrenderedLatex', { latexDirective: data.latexDirective }); break; } } })); } private async _onDidClickDataLink(event: IClickedDataUrlMessage): Promise<void> { if (typeof event.data !== 'string') { return; } const [splitStart, splitData] = event.data.split(';base64,'); if (!splitData || !splitStart) { return; } const defaultDir = dirname(this.documentUri); let defaultName: string; if (event.downloadName) { defaultName = event.downloadName; } else { const mimeType = splitStart.replace(/^data:/, ''); const candidateExtension = mimeType && getExtensionForMimeType(mimeType); defaultName = candidateExtension ? `download${candidateExtension}` : 'download'; } const defaultUri = joinPath(defaultDir, defaultName); const newFileUri = await this.fileDialogService.showSaveDialog({ defaultUri }); if (!newFileUri) { return; } const decoded = atob(splitData); const typedArray = new Uint8Array(decoded.length); for (let i = 0; i < decoded.length; i++) { typedArray[i] = decoded.charCodeAt(i); } const buff = VSBuffer.wrap(typedArray); await this.fileService.writeFile(newFileUri, buff); await this.openerService.open(newFileUri); } private _createInset(webviewService: IWebviewService, content: string) { const rootPath = isWeb ? FileAccess.asBrowserUri('', require) : FileAccess.asFileUri('', require); const workspaceFolders = this.contextService.getWorkspace().folders.map(x => x.uri); this.localResourceRootsCache = [ ...this.notebookService.getNotebookProviderResourceRoots(), ...this.notebookService.getRenderers().map(x => dirname(x.entrypoint)), ...workspaceFolders, rootPath, ]; const webview = webviewService.createWebviewElement(this.id, { purpose: WebviewContentPurpose.NotebookRenderer, enableFindWidget: false, transformCssVariables: transformWebviewThemeVars, }, { allowMultipleAPIAcquire: true, allowScripts: true, localResourceRoots: this.localResourceRootsCache, }, undefined); webview.html = content; return webview; } private initializeWebViewState() { const renderers = new Set<INotebookRendererInfo>(); for (const inset of this.insetMapping.values()) { if (inset.renderer) { renderers.add(inset.renderer); } } this._preloadsCache.clear(); if (this._currentKernel) { this._updatePreloadsFromKernel(this._currentKernel); } for (const [output, inset] of this.insetMapping.entries()) { this._sendMessageToWebview({ ...inset.cachedCreation, initiallyHidden: this.hiddenInsetMapping.has(output) }); } const mdCells = [...this.markdownPreviewMapping.values()]; this.markdownPreviewMapping.clear(); this.initializeMarkdown(mdCells); this._updateStyles(); this._updateOptions(); } private shouldUpdateInset(cell: IGenericCellViewModel, output: ICellOutputViewModel, cellTop: number, outputOffset: number): boolean { if (this._disposed) { return false; } if (cell.metadata.outputCollapsed) { return false; } if (this.hiddenInsetMapping.has(output)) { return true; } const outputCache = this.insetMapping.get(output); if (!outputCache) { return false; } if (outputOffset === outputCache.cachedCreation.outputOffset && cellTop === outputCache.cachedCreation.cellTop) { return false; } return true; } ackHeight(cellId: string, id: string, height: number): void { this._sendMessageToWebview({ type: 'ack-dimension', cellId: cellId, outputId: id, height: height }); } updateScrollTops(outputRequests: IDisplayOutputLayoutUpdateRequest[], markdownPreviews: { id: string, top: number }[]) { if (this._disposed) { return; } const widgets = coalesce(outputRequests.map((request): IContentWidgetTopRequest | undefined => { const outputCache = this.insetMapping.get(request.output); if (!outputCache) { return; } if (!request.forceDisplay && !this.shouldUpdateInset(request.cell, request.output, request.cellTop, request.outputOffset)) { return; } const id = outputCache.outputId; outputCache.cachedCreation.cellTop = request.cellTop; outputCache.cachedCreation.outputOffset = request.outputOffset; this.hiddenInsetMapping.delete(request.output); return { outputId: id, cellTop: request.cellTop, outputOffset: request.outputOffset, forceDisplay: request.forceDisplay, }; })); if (!widgets.length && !markdownPreviews.length) { return; } this._sendMessageToWebview({ type: 'view-scroll', widgets: widgets, markdownPreviews, }); } private async createMarkdownPreview(initialization: IMarkdownCellInitialization) { if (this._disposed) { return; } if (this.markdownPreviewMapping.has(initialization.cellId)) { console.error('Trying to create markdown preview that already exists'); return; } this.markdownPreviewMapping.set(initialization.cellId, initialization); this._sendMessageToWebview({ type: 'createMarkupCell', cell: initialization }); } async showMarkdownPreview(initialization: IMarkdownCellInitialization) { if (this._disposed) { return; } const entry = this.markdownPreviewMapping.get(initialization.cellId); if (!entry) { return this.createMarkdownPreview(initialization); } const sameContent = initialization.content === entry.content; if (!sameContent || !entry.visible) { this._sendMessageToWebview({ type: 'showMarkupCell', id: initialization.cellId, handle: initialization.cellHandle, // If the content has not changed, we still want to make sure the // preview is visible but don't need to send anything over content: sameContent ? undefined : initialization.content, top: initialization.offset }); } entry.content = initialization.content; entry.offset = initialization.offset; entry.visible = true; } async hideMarkdownPreviews(cellIds: readonly string[]) { if (this._disposed) { return; } const cellsToHide: string[] = []; for (const cellId of cellIds) { const entry = this.markdownPreviewMapping.get(cellId); if (entry) { if (entry.visible) { cellsToHide.push(cellId); entry.visible = false; } } } if (cellsToHide.length) { this._sendMessageToWebview({ type: 'hideMarkupCells', ids: cellsToHide }); } } async unhideMarkdownPreviews(cellIds: readonly string[]) { if (this._disposed) { return; } const toUnhide: string[] = []; for (const cellId of cellIds) { const entry = this.markdownPreviewMapping.get(cellId); if (entry) { if (!entry.visible) { entry.visible = true; toUnhide.push(cellId); } } else { console.error(`Trying to unhide a preview that does not exist: ${cellId}`); } } this._sendMessageToWebview({ type: 'unhideMarkupCells', ids: toUnhide, }); } async deleteMarkdownPreviews(cellIds: readonly string[]) { if (this._disposed) { return; } for (const id of cellIds) { if (!this.markdownPreviewMapping.has(id)) { console.error(`Trying to delete a preview that does not exist: ${id}`); } this.markdownPreviewMapping.delete(id); } if (cellIds.length) { this._sendMessageToWebview({ type: 'deleteMarkupCell', ids: cellIds }); } } async updateMarkdownPreviewSelections(selectedCellsIds: string[]) { if (this._disposed) { return; } this._sendMessageToWebview({ type: 'updateSelectedMarkupCells', selectedCellIds: selectedCellsIds.filter(id => this.markdownPreviewMapping.has(id)), }); } async initializeMarkdown(cells: ReadonlyArray<IMarkdownCellInitialization>) { if (this._disposed) { return; } // TODO: use proper handler const p = new Promise<void>(resolve => { this.webview?.onMessage(e => { if (e.message.type === 'initializedMarkdownPreview') { resolve(); } }); }); for (const cell of cells) { this.markdownPreviewMapping.set(cell.cellId, { ...cell, visible: false }); } this._sendMessageToWebview({ type: 'initializeMarkup', cells, }); await p; } async createOutput(cellInfo: T, content: IInsetRenderOutput, cellTop: number, offset: number) { if (this._disposed) { return; } if (this.insetMapping.has(content.source)) { const outputCache = this.insetMapping.get(content.source); if (outputCache) { this.hiddenInsetMapping.delete(content.source); this._sendMessageToWebview({ type: 'showOutput', cellId: outputCache.cellInfo.cellId, outputId: outputCache.outputId, cellTop: cellTop, outputOffset: offset }); return; } } const messageBase = { type: 'html', cellId: cellInfo.cellId, cellTop: cellTop, outputOffset: offset, left: 0, requiredPreloads: [], } as const; let message: ICreationRequestMessage; let renderer: INotebookRendererInfo | undefined; if (content.type === RenderOutputType.Extension) { const output = content.source.model; renderer = content.renderer; const outputDto = output.outputs.find(op => op.mime === content.mimeType); // TODO@notebook - the message can contain "bytes" and those are transferable // which improves IPC performance and therefore should be used. However, it does // means that the bytes cannot be used here anymore message = { ...messageBase, outputId: output.outputId, rendererId: content.renderer.id, content: { type: RenderOutputType.Extension, outputId: output.outputId, mimeType: content.mimeType, valueBytes: new Uint8Array(outputDto?.valueBytes ?? []), metadata: output.metadata, metadata2: output.metadata }, }; } else { message = { ...messageBase, outputId: UUID.generateUuid(), content: { type: content.type, htmlContent: content.htmlContent, } }; } this._sendMessageToWebview(message); this.insetMapping.set(content.source, { outputId: message.outputId, cellInfo: cellInfo, renderer, cachedCreation: message }); this.hiddenInsetMapping.delete(content.source); this.reversedInsetMapping.set(message.outputId, content.source); } removeInsets(outputs: readonly ICellOutputViewModel[]) { if (this._disposed) { return; } for (const output of outputs) { const outputCache = this.insetMapping.get(output); if (!outputCache) { continue; } const id = outputCache.outputId; this._sendMessageToWebview({ type: 'clearOutput', rendererId: outputCache.cachedCreation.rendererId, cellUri: outputCache.cellInfo.cellUri.toString(), outputId: id, cellId: outputCache.cellInfo.cellId }); this.insetMapping.delete(output); this.reversedInsetMapping.delete(id); } } hideInset(output: ICellOutputViewModel) { if (this._disposed) { return; } const outputCache = this.insetMapping.get(output); if (!outputCache) { return; } this.hiddenInsetMapping.add(output); this._sendMessageToWebview({ type: 'hideOutput', outputId: outputCache.outputId, cellId: outputCache.cellInfo.cellId, }); } clearInsets() { if (this._disposed) { return; } this._sendMessageToWebview({ type: 'clear' }); this.insetMapping = new Map(); this.reversedInsetMapping = new Map(); } focusWebview() { if (this._disposed) { return; } this.webview?.focus(); } focusOutput(cellId: string) { if (this._disposed) { return; } this.webview?.focus(); setTimeout(() => { // Need this, or focus decoration is not shown. No clue. this._sendMessageToWebview({ type: 'focus-output', cellId, }); }, 50); } deltaCellOutputContainerClassNames(cellId: string, added: string[], removed: string[]) { this._sendMessageToWebview({ type: 'decorations', cellId, addedClassNames: added, removedClassNames: removed }); } async updateKernelPreloads(kernel: INotebookKernel | undefined) { if (this._disposed || kernel === this._currentKernel) { return; } const previousKernel = this._currentKernel; this._currentKernel = kernel; if (previousKernel && previousKernel.preloadUris.length > 0) { this.webview?.reload(); // preloads will be restored after reload } else if (kernel) { this._updatePreloadsFromKernel(kernel); } } private _updatePreloadsFromKernel(kernel: INotebookKernel) { const resources: IControllerPreload[] = []; for (const preload of kernel.preloadUris) { const uri = this.environmentService.isExtensionDevelopment && (preload.scheme === 'http' || preload.scheme === 'https') ? preload : this.asWebviewUri(preload, undefined); if (!this._preloadsCache.has(uri.toString())) { resources.push({ uri: uri.toString(), originalUri: preload.toString() }); this._preloadsCache.add(uri.toString()); } } if (!resources.length) { return; } this._updatePreloads(resources); } private _updatePreloads(resources: IControllerPreload[]) { if (!this.webview) { return; } const mixedResourceRoots = [ ...(this.localResourceRootsCache || []), ...this.rendererRootsCache, ...(this._currentKernel ? [this._currentKernel.localResourceRoot] : []), ]; this.webview.localResourcesRoot = mixedResourceRoots; this._sendMessageToWebview({ type: 'preload', resources: resources, }); } private _sendMessageToWebview(message: ToWebviewMessage) { if (this._disposed) { return; } this.webview?.postMessage(message); } clearPreloadsCache() { this._preloadsCache.clear(); } override dispose() { this._disposed = true; this.webview?.dispose(); super.dispose(); } }
src/vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView.ts
1
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.0026668605860322714, 0.00020706024952232838, 0.00016318906273227185, 0.00016883073840290308, 0.0002454578352626413 ]
{ "id": 6, "code_window": [ "\t\t\t\t}\n", "\t\t\t}\n", "\t\t}\n", "\n", "\t\tdimensionUpdater.update(cellId, previewContainerNode.clientHeight, {\n", "\t\t\tisOutput: false\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\t\tconst matches = previewContainerNode.innerText.match(unsupportedKatexTermsRegex);\n", "\t\t\tif (matches) {\n", "\t\t\t\tpostNotebookMessage<webviewMessages.ITelemetryFoundUnrenderedMarkdownMath>('telemetryFoundUnrenderedMarkdownMath', {\n", "\t\t\t\t\tlatexDirective: matches[0],\n", "\t\t\t\t});\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads.ts", "type": "add", "edit_start_line_idx": 1022 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import 'mocha'; import * as vscode from 'vscode'; import LinkProvider from '../features/documentLinkProvider'; import { InMemoryDocument } from './inMemoryDocument'; const testFile = vscode.Uri.joinPath(vscode.workspace.workspaceFolders![0].uri, 'x.md'); const noopToken = new class implements vscode.CancellationToken { private _onCancellationRequestedEmitter = new vscode.EventEmitter<void>(); public onCancellationRequested = this._onCancellationRequestedEmitter.event; get isCancellationRequested() { return false; } }; function getLinksForFile(fileContents: string) { const doc = new InMemoryDocument(testFile, fileContents); const provider = new LinkProvider(); return provider.provideDocumentLinks(doc, noopToken); } function assertRangeEqual(expected: vscode.Range, actual: vscode.Range) { assert.strictEqual(expected.start.line, actual.start.line); assert.strictEqual(expected.start.character, actual.start.character); assert.strictEqual(expected.end.line, actual.end.line); assert.strictEqual(expected.end.character, actual.end.character); } suite('markdown.DocumentLinkProvider', () => { test('Should not return anything for empty document', () => { const links = getLinksForFile(''); assert.strictEqual(links.length, 0); }); test('Should not return anything for simple document without links', () => { const links = getLinksForFile('# a\nfdasfdfsafsa'); assert.strictEqual(links.length, 0); }); test('Should detect basic http links', () => { const links = getLinksForFile('a [b](https://example.com) c'); assert.strictEqual(links.length, 1); const [link] = links; assertRangeEqual(link.range, new vscode.Range(0, 6, 0, 25)); }); test('Should detect basic workspace links', () => { { const links = getLinksForFile('a [b](./file) c'); assert.strictEqual(links.length, 1); const [link] = links; assertRangeEqual(link.range, new vscode.Range(0, 6, 0, 12)); } { const links = getLinksForFile('a [b](file.png) c'); assert.strictEqual(links.length, 1); const [link] = links; assertRangeEqual(link.range, new vscode.Range(0, 6, 0, 14)); } }); test('Should detect links with title', () => { const links = getLinksForFile('a [b](https://example.com "abc") c'); assert.strictEqual(links.length, 1); const [link] = links; assertRangeEqual(link.range, new vscode.Range(0, 6, 0, 25)); }); // #35245 test('Should handle links with escaped characters in name', () => { const links = getLinksForFile('a [b\\]](./file)'); assert.strictEqual(links.length, 1); const [link] = links; assertRangeEqual(link.range, new vscode.Range(0, 8, 0, 14)); }); test('Should handle links with balanced parens', () => { { const links = getLinksForFile('a [b](https://example.com/a()c) c'); assert.strictEqual(links.length, 1); const [link] = links; assertRangeEqual(link.range, new vscode.Range(0, 6, 0, 30)); } { const links = getLinksForFile('a [b](https://example.com/a(b)c) c'); assert.strictEqual(links.length, 1); const [link] = links; assertRangeEqual(link.range, new vscode.Range(0, 6, 0, 31)); } { // #49011 const links = getLinksForFile('[A link](http://ThisUrlhasParens/A_link(in_parens))'); assert.strictEqual(links.length, 1); const [link] = links; assertRangeEqual(link.range, new vscode.Range(0, 9, 0, 50)); } }); test('Should handle two links without space', () => { const links = getLinksForFile('a ([test](test)[test2](test2)) c'); assert.strictEqual(links.length, 2); const [link1, link2] = links; assertRangeEqual(link1.range, new vscode.Range(0, 10, 0, 14)); assertRangeEqual(link2.range, new vscode.Range(0, 23, 0, 28)); }); // #49238 test('should handle hyperlinked images', () => { { const links = getLinksForFile('[![alt text](image.jpg)](https://example.com)'); assert.strictEqual(links.length, 2); const [link1, link2] = links; assertRangeEqual(link1.range, new vscode.Range(0, 13, 0, 22)); assertRangeEqual(link2.range, new vscode.Range(0, 25, 0, 44)); } { const links = getLinksForFile('[![a]( whitespace.jpg )]( https://whitespace.com )'); assert.strictEqual(links.length, 2); const [link1, link2] = links; assertRangeEqual(link1.range, new vscode.Range(0, 7, 0, 21)); assertRangeEqual(link2.range, new vscode.Range(0, 26, 0, 48)); } { const links = getLinksForFile('[![a](img1.jpg)](file1.txt) text [![a](img2.jpg)](file2.txt)'); assert.strictEqual(links.length, 4); const [link1, link2, link3, link4] = links; assertRangeEqual(link1.range, new vscode.Range(0, 6, 0, 14)); assertRangeEqual(link2.range, new vscode.Range(0, 17, 0, 26)); assertRangeEqual(link3.range, new vscode.Range(0, 39, 0, 47)); assertRangeEqual(link4.range, new vscode.Range(0, 50, 0, 59)); } }); // #107471 test('Should not consider link references starting with ^ character valid', () => { const links = getLinksForFile('[^reference]: https://example.com'); assert.strictEqual(links.length, 0); }); });
extensions/markdown-language-features/src/test/documentLinkProvider.test.ts
0
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.0001749360526446253, 0.00017065348220057786, 0.00016685885202605277, 0.00017104849393945187, 0.0000021060393464722438 ]
{ "id": 6, "code_window": [ "\t\t\t\t}\n", "\t\t\t}\n", "\t\t}\n", "\n", "\t\tdimensionUpdater.update(cellId, previewContainerNode.clientHeight, {\n", "\t\t\tisOutput: false\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\t\tconst matches = previewContainerNode.innerText.match(unsupportedKatexTermsRegex);\n", "\t\t\tif (matches) {\n", "\t\t\t\tpostNotebookMessage<webviewMessages.ITelemetryFoundUnrenderedMarkdownMath>('telemetryFoundUnrenderedMarkdownMath', {\n", "\t\t\t\t\tlatexDirective: matches[0],\n", "\t\t\t\t});\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads.ts", "type": "add", "edit_start_line_idx": 1022 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from 'vs/nls'; import { CancellationToken } from 'vs/base/common/cancellation'; import { getLocation, parse } from 'vs/base/common/json'; import { Disposable } from 'vs/base/common/lifecycle'; import { Position } from 'vs/editor/common/core/position'; import { ITextModel } from 'vs/editor/common/model'; import { CompletionContext, CompletionList, CompletionProviderRegistry, CompletionItemKind, CompletionItem } from 'vs/editor/common/modes'; import { IExtensionManagementService } from 'vs/platform/extensionManagement/common/extensionManagement'; import { IWorkbenchContribution } from 'vs/workbench/common/contributions'; import { Range } from 'vs/editor/common/core/range'; export class ExtensionsCompletionItemsProvider extends Disposable implements IWorkbenchContribution { constructor( @IExtensionManagementService private readonly extensionManagementService: IExtensionManagementService, ) { super(); this._register(CompletionProviderRegistry.register({ language: 'jsonc', pattern: '**/settings.json' }, { provideCompletionItems: async (model: ITextModel, position: Position, _context: CompletionContext, token: CancellationToken): Promise<CompletionList> => { const getWordRangeAtPosition = (model: ITextModel, position: Position): Range | null => { const wordAtPosition = model.getWordAtPosition(position); return wordAtPosition ? new Range(position.lineNumber, wordAtPosition.startColumn, position.lineNumber, wordAtPosition.endColumn) : null; }; const location = getLocation(model.getValue(), model.getOffsetAt(position)); const range = getWordRangeAtPosition(model, position) ?? Range.fromPositions(position, position); // extensions.supportUntrustedWorkspaces if (location.path[0] === 'extensions.supportUntrustedWorkspaces' && location.path.length === 2 && location.isAtPropertyKey) { let alreadyConfigured: string[] = []; try { alreadyConfigured = Object.keys(parse(model.getValue())['extensions.supportUntrustedWorkspaces']); } catch (e) {/* ignore error */ } return { suggestions: await this.provideSupportUntrustedWorkspacesExtensionProposals(alreadyConfigured, range) }; } return { suggestions: [] }; } })); } private async provideSupportUntrustedWorkspacesExtensionProposals(alreadyConfigured: string[], range: Range): Promise<CompletionItem[]> { const suggestions: CompletionItem[] = []; const installedExtensions = (await this.extensionManagementService.getInstalled()).filter(e => e.manifest.main); const proposedExtensions = installedExtensions.filter(e => alreadyConfigured.indexOf(e.identifier.id) === -1); if (proposedExtensions.length) { suggestions.push(...proposedExtensions.map(e => { const text = `"${e.identifier.id}": {\n\t"supported": true,\n\t"version": "${e.manifest.version}"\n},`; return { label: e.identifier.id, kind: CompletionItemKind.Value, insertText: text, filterText: text, range }; })); } else { const text = '"vscode.csharp": {\n\t"supported": true,\n\t"version": "0.0.0"\n},'; suggestions.push({ label: localize('exampleExtension', "Example"), kind: CompletionItemKind.Value, insertText: text, filterText: text, range }); } return suggestions; } }
src/vs/workbench/contrib/extensions/browser/extensionsCompletionItemsProvider.ts
0
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.00017554762598592788, 0.00017188613128382713, 0.00016819039592519403, 0.0001720016880426556, 0.0000024629573545098538 ]
{ "id": 6, "code_window": [ "\t\t\t\t}\n", "\t\t\t}\n", "\t\t}\n", "\n", "\t\tdimensionUpdater.update(cellId, previewContainerNode.clientHeight, {\n", "\t\t\tisOutput: false\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\t\tconst matches = previewContainerNode.innerText.match(unsupportedKatexTermsRegex);\n", "\t\t\tif (matches) {\n", "\t\t\t\tpostNotebookMessage<webviewMessages.ITelemetryFoundUnrenderedMarkdownMath>('telemetryFoundUnrenderedMarkdownMath', {\n", "\t\t\t\t\tlatexDirective: matches[0],\n", "\t\t\t\t});\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads.ts", "type": "add", "edit_start_line_idx": 1022 }
{ "version": "2.0.0", "command": "npm", "type": "shell", "presentation": { "reveal": "silent", }, "args": ["run", "compile"], "isBackground": true, "problemMatcher": "$tsc-watch" }
extensions/npm/.vscode/tasks.json
0
https://github.com/microsoft/vscode/commit/39dc60dec680e7ab996ea18f7e9f95cbd0c92a26
[ 0.0001768975635059178, 0.00017316691810265183, 0.00016943627269938588, 0.00017316691810265183, 0.000003730645403265953 ]
{ "id": 0, "code_window": [ " }\n", "\n", " function findBaseOfDeclaration<T>(checker: TypeChecker, declaration: Declaration, cb: (symbol: Symbol) => T[] | undefined): T[] | undefined {\n", " const classOrInterfaceDeclaration = declaration.parent?.kind === SyntaxKind.Constructor ? declaration.parent.parent : declaration.parent;\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ " if (hasStaticModifier(declaration)) return;\n", "\n" ], "file_path": "src/services/services.ts", "type": "add", "edit_start_line_idx": 601 }
///<reference path="fourslash.ts" /> // @Filename: inheritDoc.ts ////class Foo { //// /** //// * Foo constructor documentation //// */ //// constructor(value: number) {} //// /** //// * Foo#method1 documentation //// */ //// static method1() {} //// /** //// * Foo#method2 documentation //// */ //// method2() {} //// /** //// * Foo#property1 documentation //// */ //// property1: string; ////} ////interface Baz { //// /** Baz#property1 documentation */ //// property1: string; //// /** //// * Baz#property2 documentation //// */ //// property2: object; ////} ////class Bar extends Foo implements Baz { //// ctorValue: number; //// /** @inheritDoc */ //// constructor(value: number) { //// super(value); //// this.ctorValue = value; //// } //// /** @inheritDoc */ //// static method1() {} //// method2() {} //// /** @inheritDoc */ //// property1: string; //// /** //// * Bar#property2 //// * @inheritDoc //// */ //// property2: object; ////} ////const b = new Bar/*1*/(5); ////b.method2/*2*/(); ////Bar.method1/*3*/(); ////const p1 = b.property1/*4*/; ////const p2 = b.property2/*5*/; verify.quickInfoAt("1", "constructor Bar(value: number): Bar", undefined); // constructors aren't actually inherited verify.quickInfoAt("2", "(method) Bar.method2(): void", "Foo#method2 documentation"); // use inherited docs only verify.quickInfoAt("3", "(method) Bar.method1(): void", undefined); // statics aren't actually inherited verify.quickInfoAt("4", "(property) Bar.property1: string", "Foo#property1 documentation"); // use inherited docs only verify.quickInfoAt("5", "(property) Bar.property2: object", "Baz#property2 documentation\nBar#property2"); // include local and inherited docs
tests/cases/fourslash/jsDocInheritDoc.ts
1
https://github.com/microsoft/TypeScript/commit/a05d851dc35ff0c9de40bd9b7a4cebac7b7e0158
[ 0.0001737998245516792, 0.0001709893113002181, 0.0001654420339036733, 0.00017185276374220848, 0.000002919170356108225 ]
{ "id": 0, "code_window": [ " }\n", "\n", " function findBaseOfDeclaration<T>(checker: TypeChecker, declaration: Declaration, cb: (symbol: Symbol) => T[] | undefined): T[] | undefined {\n", " const classOrInterfaceDeclaration = declaration.parent?.kind === SyntaxKind.Constructor ? declaration.parent.parent : declaration.parent;\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ " if (hasStaticModifier(declaration)) return;\n", "\n" ], "file_path": "src/services/services.ts", "type": "add", "edit_start_line_idx": 601 }
=== tests/cases/compiler/a.js === function F(): number { } >F : Symbol(F, Decl(a.js, 0, 0))
tests/baselines/reference/jsFileCompilationReturnTypeSyntaxOfFunction.symbols
0
https://github.com/microsoft/TypeScript/commit/a05d851dc35ff0c9de40bd9b7a4cebac7b7e0158
[ 0.0003026379272341728, 0.0003026379272341728, 0.0003026379272341728, 0.0003026379272341728, 0 ]
{ "id": 0, "code_window": [ " }\n", "\n", " function findBaseOfDeclaration<T>(checker: TypeChecker, declaration: Declaration, cb: (symbol: Symbol) => T[] | undefined): T[] | undefined {\n", " const classOrInterfaceDeclaration = declaration.parent?.kind === SyntaxKind.Constructor ? declaration.parent.parent : declaration.parent;\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ " if (hasStaticModifier(declaration)) return;\n", "\n" ], "file_path": "src/services/services.ts", "type": "add", "edit_start_line_idx": 601 }
class X<T> { f(t: T) { return { a: t }; } } var x: X<number>; var t1 = x.f(5); t1.a = 5; // Should not error: t1 should have type {a: number}, instead has type {a: T}
tests/cases/compiler/genericObjectLitReturnType.ts
0
https://github.com/microsoft/TypeScript/commit/a05d851dc35ff0c9de40bd9b7a4cebac7b7e0158
[ 0.000665130908600986, 0.0004171342879999429, 0.00016913765284698457, 0.0004171342879999429, 0.00024799664970487356 ]
{ "id": 0, "code_window": [ " }\n", "\n", " function findBaseOfDeclaration<T>(checker: TypeChecker, declaration: Declaration, cb: (symbol: Symbol) => T[] | undefined): T[] | undefined {\n", " const classOrInterfaceDeclaration = declaration.parent?.kind === SyntaxKind.Constructor ? declaration.parent.parent : declaration.parent;\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ " if (hasStaticModifier(declaration)) return;\n", "\n" ], "file_path": "src/services/services.ts", "type": "add", "edit_start_line_idx": 601 }
{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m2.ts"],"names":[],"mappings":";;;AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC,SAAgB,KAAK;IACjB,OAAO,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"}
tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderNoOutdir/node/ref/m2.js.map
0
https://github.com/microsoft/TypeScript/commit/a05d851dc35ff0c9de40bd9b7a4cebac7b7e0158
[ 0.00016599318769294769, 0.00016599318769294769, 0.00016599318769294769, 0.00016599318769294769, 0 ]
{ "id": 1, "code_window": [ " const classOrInterfaceDeclaration = declaration.parent?.kind === SyntaxKind.Constructor ? declaration.parent.parent : declaration.parent;\n", " if (!classOrInterfaceDeclaration) {\n", " return;\n", " }\n", " return firstDefined(getAllSuperTypeNodes(classOrInterfaceDeclaration), superTypeNode => {\n", " const symbol = checker.getPropertyOfType(checker.getTypeAtLocation(superTypeNode), declaration.symbol.name);\n", " return symbol ? cb(symbol) : undefined;\n", " });\n", " }\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (!classOrInterfaceDeclaration) return;\n", "\n" ], "file_path": "src/services/services.ts", "type": "replace", "edit_start_line_idx": 602 }
///<reference path="fourslash.ts" /> // @Filename: inheritDoc.ts ////class Foo { //// /** //// * Foo constructor documentation //// */ //// constructor(value: number) {} //// /** //// * Foo#method1 documentation //// */ //// static method1() {} //// /** //// * Foo#method2 documentation //// */ //// method2() {} //// /** //// * Foo#property1 documentation //// */ //// property1: string; ////} ////interface Baz { //// /** Baz#property1 documentation */ //// property1: string; //// /** //// * Baz#property2 documentation //// */ //// property2: object; ////} ////class Bar extends Foo implements Baz { //// ctorValue: number; //// /** @inheritDoc */ //// constructor(value: number) { //// super(value); //// this.ctorValue = value; //// } //// /** @inheritDoc */ //// static method1() {} //// method2() {} //// /** @inheritDoc */ //// property1: string; //// /** //// * Bar#property2 //// * @inheritDoc //// */ //// property2: object; ////} ////const b = new Bar/*1*/(5); ////b.method2/*2*/(); ////Bar.method1/*3*/(); ////const p1 = b.property1/*4*/; ////const p2 = b.property2/*5*/; verify.quickInfoAt("1", "constructor Bar(value: number): Bar", undefined); // constructors aren't actually inherited verify.quickInfoAt("2", "(method) Bar.method2(): void", "Foo#method2 documentation"); // use inherited docs only verify.quickInfoAt("3", "(method) Bar.method1(): void", undefined); // statics aren't actually inherited verify.quickInfoAt("4", "(property) Bar.property1: string", "Foo#property1 documentation"); // use inherited docs only verify.quickInfoAt("5", "(property) Bar.property2: object", "Baz#property2 documentation\nBar#property2"); // include local and inherited docs
tests/cases/fourslash/jsDocInheritDoc.ts
1
https://github.com/microsoft/TypeScript/commit/a05d851dc35ff0c9de40bd9b7a4cebac7b7e0158
[ 0.00017424550605937839, 0.00017068414308596402, 0.00016445337678305805, 0.00017180180293507874, 0.000003562416850400041 ]
{ "id": 1, "code_window": [ " const classOrInterfaceDeclaration = declaration.parent?.kind === SyntaxKind.Constructor ? declaration.parent.parent : declaration.parent;\n", " if (!classOrInterfaceDeclaration) {\n", " return;\n", " }\n", " return firstDefined(getAllSuperTypeNodes(classOrInterfaceDeclaration), superTypeNode => {\n", " const symbol = checker.getPropertyOfType(checker.getTypeAtLocation(superTypeNode), declaration.symbol.name);\n", " return symbol ? cb(symbol) : undefined;\n", " });\n", " }\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (!classOrInterfaceDeclaration) return;\n", "\n" ], "file_path": "src/services/services.ts", "type": "replace", "edit_start_line_idx": 602 }
=== tests/cases/conformance/es6/unicodeExtendedEscapes/unicodeExtendedEscapesInStrings04_ES6.ts === var x = "\u{00000000}"; >x : Symbol(x, Decl(unicodeExtendedEscapesInStrings04_ES6.ts, 0, 3))
tests/baselines/reference/unicodeExtendedEscapesInStrings04_ES6.symbols
0
https://github.com/microsoft/TypeScript/commit/a05d851dc35ff0c9de40bd9b7a4cebac7b7e0158
[ 0.00017068779561668634, 0.00017068779561668634, 0.00017068779561668634, 0.00017068779561668634, 0 ]
{ "id": 1, "code_window": [ " const classOrInterfaceDeclaration = declaration.parent?.kind === SyntaxKind.Constructor ? declaration.parent.parent : declaration.parent;\n", " if (!classOrInterfaceDeclaration) {\n", " return;\n", " }\n", " return firstDefined(getAllSuperTypeNodes(classOrInterfaceDeclaration), superTypeNode => {\n", " const symbol = checker.getPropertyOfType(checker.getTypeAtLocation(superTypeNode), declaration.symbol.name);\n", " return symbol ? cb(symbol) : undefined;\n", " });\n", " }\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (!classOrInterfaceDeclaration) return;\n", "\n" ], "file_path": "src/services/services.ts", "type": "replace", "edit_start_line_idx": 602 }
// @allowJs: true // @noEmit: true // @experimentalDecorators: true // @filename: a.js @internal class C { }
tests/cases/compiler/jsFileCompilationDecoratorSyntax.ts
0
https://github.com/microsoft/TypeScript/commit/a05d851dc35ff0c9de40bd9b7a4cebac7b7e0158
[ 0.00016969414718914777, 0.00016969414718914777, 0.00016969414718914777, 0.00016969414718914777, 0 ]
{ "id": 1, "code_window": [ " const classOrInterfaceDeclaration = declaration.parent?.kind === SyntaxKind.Constructor ? declaration.parent.parent : declaration.parent;\n", " if (!classOrInterfaceDeclaration) {\n", " return;\n", " }\n", " return firstDefined(getAllSuperTypeNodes(classOrInterfaceDeclaration), superTypeNode => {\n", " const symbol = checker.getPropertyOfType(checker.getTypeAtLocation(superTypeNode), declaration.symbol.name);\n", " return symbol ? cb(symbol) : undefined;\n", " });\n", " }\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (!classOrInterfaceDeclaration) return;\n", "\n" ], "file_path": "src/services/services.ts", "type": "replace", "edit_start_line_idx": 602 }
//// [parserEnumDeclaration4.ts] enum void { } //// [parserEnumDeclaration4.js] var ; (function () { })( || ( = {})); void {};
tests/baselines/reference/parserEnumDeclaration4.js
0
https://github.com/microsoft/TypeScript/commit/a05d851dc35ff0c9de40bd9b7a4cebac7b7e0158
[ 0.00016294431407004595, 0.00016294431407004595, 0.00016294431407004595, 0.00016294431407004595, 0 ]
{ "id": 3, "code_window": [ "//// * Bar#property2\n", "//// * @inheritDoc\n", "//// */\n", "//// property2: object;\n", "////}\n", "////const b = new Bar/*1*/(5);\n", "////b.method2/*2*/();\n", "////Bar.method1/*3*/();\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "////\n", "//// static /*6*/property3 = \"class prop\";\n" ], "file_path": "tests/cases/fourslash/jsDocInheritDoc.ts", "type": "add", "edit_start_line_idx": 45 }
///<reference path="fourslash.ts" /> // @Filename: inheritDoc.ts ////class Foo { //// /** //// * Foo constructor documentation //// */ //// constructor(value: number) {} //// /** //// * Foo#method1 documentation //// */ //// static method1() {} //// /** //// * Foo#method2 documentation //// */ //// method2() {} //// /** //// * Foo#property1 documentation //// */ //// property1: string; ////} ////interface Baz { //// /** Baz#property1 documentation */ //// property1: string; //// /** //// * Baz#property2 documentation //// */ //// property2: object; ////} ////class Bar extends Foo implements Baz { //// ctorValue: number; //// /** @inheritDoc */ //// constructor(value: number) { //// super(value); //// this.ctorValue = value; //// } //// /** @inheritDoc */ //// static method1() {} //// method2() {} //// /** @inheritDoc */ //// property1: string; //// /** //// * Bar#property2 //// * @inheritDoc //// */ //// property2: object; ////} ////const b = new Bar/*1*/(5); ////b.method2/*2*/(); ////Bar.method1/*3*/(); ////const p1 = b.property1/*4*/; ////const p2 = b.property2/*5*/; verify.quickInfoAt("1", "constructor Bar(value: number): Bar", undefined); // constructors aren't actually inherited verify.quickInfoAt("2", "(method) Bar.method2(): void", "Foo#method2 documentation"); // use inherited docs only verify.quickInfoAt("3", "(method) Bar.method1(): void", undefined); // statics aren't actually inherited verify.quickInfoAt("4", "(property) Bar.property1: string", "Foo#property1 documentation"); // use inherited docs only verify.quickInfoAt("5", "(property) Bar.property2: object", "Baz#property2 documentation\nBar#property2"); // include local and inherited docs
tests/cases/fourslash/jsDocInheritDoc.ts
1
https://github.com/microsoft/TypeScript/commit/a05d851dc35ff0c9de40bd9b7a4cebac7b7e0158
[ 0.9980331063270569, 0.33407995104789734, 0.0003182288201060146, 0.003361594397574663, 0.46913036704063416 ]
{ "id": 3, "code_window": [ "//// * Bar#property2\n", "//// * @inheritDoc\n", "//// */\n", "//// property2: object;\n", "////}\n", "////const b = new Bar/*1*/(5);\n", "////b.method2/*2*/();\n", "////Bar.method1/*3*/();\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "////\n", "//// static /*6*/property3 = \"class prop\";\n" ], "file_path": "tests/cases/fourslash/jsDocInheritDoc.ts", "type": "add", "edit_start_line_idx": 45 }
tests/cases/compiler/errorLocationForInterfaceExtension.ts(3,21): error TS2693: 'string' only refers to a type, but is being used as a value here. ==== tests/cases/compiler/errorLocationForInterfaceExtension.ts (1 errors) ==== var n = ''; interface x extends string { } ~~~~~~ !!! error TS2693: 'string' only refers to a type, but is being used as a value here.
tests/baselines/reference/errorLocationForInterfaceExtension.errors.txt
0
https://github.com/microsoft/TypeScript/commit/a05d851dc35ff0c9de40bd9b7a4cebac7b7e0158
[ 0.0001756544370437041, 0.00017137144459411502, 0.00016708843759261072, 0.00017137144459411502, 0.000004282999725546688 ]
{ "id": 3, "code_window": [ "//// * Bar#property2\n", "//// * @inheritDoc\n", "//// */\n", "//// property2: object;\n", "////}\n", "////const b = new Bar/*1*/(5);\n", "////b.method2/*2*/();\n", "////Bar.method1/*3*/();\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "////\n", "//// static /*6*/property3 = \"class prop\";\n" ], "file_path": "tests/cases/fourslash/jsDocInheritDoc.ts", "type": "add", "edit_start_line_idx": 45 }
tests/cases/compiler/unusedMultipleParameters2InFunctionDeclaration.ts(1,18): error TS6133: 'person' is declared but its value is never read. tests/cases/compiler/unusedMultipleParameters2InFunctionDeclaration.ts(1,34): error TS6133: 'person2' is declared but its value is never read. tests/cases/compiler/unusedMultipleParameters2InFunctionDeclaration.ts(1,51): error TS6133: 'person3' is declared but its value is never read. tests/cases/compiler/unusedMultipleParameters2InFunctionDeclaration.ts(2,9): error TS6133: 'unused' is declared but its value is never read. ==== tests/cases/compiler/unusedMultipleParameters2InFunctionDeclaration.ts (4 errors) ==== function greeter(person: string, person2: string, person3: string) { ~~~~~~ !!! error TS6133: 'person' is declared but its value is never read. ~~~~~~~ !!! error TS6133: 'person2' is declared but its value is never read. ~~~~~~~ !!! error TS6133: 'person3' is declared but its value is never read. var unused = 20; ~~~~~~ !!! error TS6133: 'unused' is declared but its value is never read. person2 = "dummy value"; }
tests/baselines/reference/unusedMultipleParameters2InFunctionDeclaration.errors.txt
0
https://github.com/microsoft/TypeScript/commit/a05d851dc35ff0c9de40bd9b7a4cebac7b7e0158
[ 0.0001750660449033603, 0.000174207758391276, 0.00017334948643110693, 0.000174207758391276, 8.582792361266911e-7 ]
{ "id": 3, "code_window": [ "//// * Bar#property2\n", "//// * @inheritDoc\n", "//// */\n", "//// property2: object;\n", "////}\n", "////const b = new Bar/*1*/(5);\n", "////b.method2/*2*/();\n", "////Bar.method1/*3*/();\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "////\n", "//// static /*6*/property3 = \"class prop\";\n" ], "file_path": "tests/cases/fourslash/jsDocInheritDoc.ts", "type": "add", "edit_start_line_idx": 45 }
// @target: ES6 // @noEmitHelpers: true async function foo(): Promise<void> { }
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration1_es6.ts
0
https://github.com/microsoft/TypeScript/commit/a05d851dc35ff0c9de40bd9b7a4cebac7b7e0158
[ 0.00017374033632222563, 0.00017374033632222563, 0.00017374033632222563, 0.00017374033632222563, 0 ]
{ "id": 4, "code_window": [ "verify.quickInfoAt(\"1\", \"constructor Bar(value: number): Bar\", undefined); // constructors aren't actually inherited\n", "verify.quickInfoAt(\"2\", \"(method) Bar.method2(): void\", \"Foo#method2 documentation\"); // use inherited docs only\n", "verify.quickInfoAt(\"3\", \"(method) Bar.method1(): void\", undefined); // statics aren't actually inherited\n", "verify.quickInfoAt(\"4\", \"(property) Bar.property1: string\", \"Foo#property1 documentation\"); // use inherited docs only\n", "verify.quickInfoAt(\"5\", \"(property) Bar.property2: object\", \"Baz#property2 documentation\\nBar#property2\"); // include local and inherited docs\n" ], "labels": [ "keep", "keep", "keep", "keep", "add" ], "after_edit": [ "verify.quickInfoAt(\"6\", \"(property) Bar.property3: string\", undefined);" ], "file_path": "tests/cases/fourslash/jsDocInheritDoc.ts", "type": "add", "edit_start_line_idx": 57 }
///<reference path="fourslash.ts" /> // @Filename: inheritDoc.ts ////class Foo { //// /** //// * Foo constructor documentation //// */ //// constructor(value: number) {} //// /** //// * Foo#method1 documentation //// */ //// static method1() {} //// /** //// * Foo#method2 documentation //// */ //// method2() {} //// /** //// * Foo#property1 documentation //// */ //// property1: string; ////} ////interface Baz { //// /** Baz#property1 documentation */ //// property1: string; //// /** //// * Baz#property2 documentation //// */ //// property2: object; ////} ////class Bar extends Foo implements Baz { //// ctorValue: number; //// /** @inheritDoc */ //// constructor(value: number) { //// super(value); //// this.ctorValue = value; //// } //// /** @inheritDoc */ //// static method1() {} //// method2() {} //// /** @inheritDoc */ //// property1: string; //// /** //// * Bar#property2 //// * @inheritDoc //// */ //// property2: object; ////} ////const b = new Bar/*1*/(5); ////b.method2/*2*/(); ////Bar.method1/*3*/(); ////const p1 = b.property1/*4*/; ////const p2 = b.property2/*5*/; verify.quickInfoAt("1", "constructor Bar(value: number): Bar", undefined); // constructors aren't actually inherited verify.quickInfoAt("2", "(method) Bar.method2(): void", "Foo#method2 documentation"); // use inherited docs only verify.quickInfoAt("3", "(method) Bar.method1(): void", undefined); // statics aren't actually inherited verify.quickInfoAt("4", "(property) Bar.property1: string", "Foo#property1 documentation"); // use inherited docs only verify.quickInfoAt("5", "(property) Bar.property2: object", "Baz#property2 documentation\nBar#property2"); // include local and inherited docs
tests/cases/fourslash/jsDocInheritDoc.ts
1
https://github.com/microsoft/TypeScript/commit/a05d851dc35ff0c9de40bd9b7a4cebac7b7e0158
[ 0.996276319026947, 0.16728739440441132, 0.0004856476152781397, 0.0018170449184253812, 0.3707357347011566 ]
{ "id": 4, "code_window": [ "verify.quickInfoAt(\"1\", \"constructor Bar(value: number): Bar\", undefined); // constructors aren't actually inherited\n", "verify.quickInfoAt(\"2\", \"(method) Bar.method2(): void\", \"Foo#method2 documentation\"); // use inherited docs only\n", "verify.quickInfoAt(\"3\", \"(method) Bar.method1(): void\", undefined); // statics aren't actually inherited\n", "verify.quickInfoAt(\"4\", \"(property) Bar.property1: string\", \"Foo#property1 documentation\"); // use inherited docs only\n", "verify.quickInfoAt(\"5\", \"(property) Bar.property2: object\", \"Baz#property2 documentation\\nBar#property2\"); // include local and inherited docs\n" ], "labels": [ "keep", "keep", "keep", "keep", "add" ], "after_edit": [ "verify.quickInfoAt(\"6\", \"(property) Bar.property3: string\", undefined);" ], "file_path": "tests/cases/fourslash/jsDocInheritDoc.ts", "type": "add", "edit_start_line_idx": 57 }
export enum SignatureFlags { None = 0, IsIndexer = 1, IsStringIndexer = 1 << 1, IsNumberIndexer = 1 << 2 }
tests/cases/conformance/parser/ecmascript5/EnumDeclarations/parserEnum2.ts
0
https://github.com/microsoft/TypeScript/commit/a05d851dc35ff0c9de40bd9b7a4cebac7b7e0158
[ 0.00017048348672688007, 0.00017048348672688007, 0.00017048348672688007, 0.00017048348672688007, 0 ]
{ "id": 4, "code_window": [ "verify.quickInfoAt(\"1\", \"constructor Bar(value: number): Bar\", undefined); // constructors aren't actually inherited\n", "verify.quickInfoAt(\"2\", \"(method) Bar.method2(): void\", \"Foo#method2 documentation\"); // use inherited docs only\n", "verify.quickInfoAt(\"3\", \"(method) Bar.method1(): void\", undefined); // statics aren't actually inherited\n", "verify.quickInfoAt(\"4\", \"(property) Bar.property1: string\", \"Foo#property1 documentation\"); // use inherited docs only\n", "verify.quickInfoAt(\"5\", \"(property) Bar.property2: object\", \"Baz#property2 documentation\\nBar#property2\"); // include local and inherited docs\n" ], "labels": [ "keep", "keep", "keep", "keep", "add" ], "after_edit": [ "verify.quickInfoAt(\"6\", \"(property) Bar.property3: string\", undefined);" ], "file_path": "tests/cases/fourslash/jsDocInheritDoc.ts", "type": "add", "edit_start_line_idx": 57 }
=== tests/cases/conformance/statements/forStatements/forStatements.ts === interface I { id: number; >id : number } class C implements I { >C : C id: number; >id : number } class D<T>{ >D : D<T> source: T; >source : T recurse: D<T>; >recurse : D<T> wrapped: D<D<T>> >wrapped : D<D<T>> } function F(x: string): number { return 42; } >F : (x: string) => number >x : string >42 : 42 module M { >M : typeof M export class A { >A : A name: string; >name : string } export function F2(x: number): string { return x.toString(); } >F2 : (x: number) => string >x : number >x.toString() : string >x.toString : (radix?: number) => string >x : number >toString : (radix?: number) => string } for(var aNumber: number = 9.9;;){} >aNumber : number >9.9 : 9.9 for(var aString: string = 'this is a string';;){} >aString : string >'this is a string' : "this is a string" for(var aDate: Date = new Date(12);;){} >aDate : Date >new Date(12) : Date >Date : DateConstructor >12 : 12 for(var anObject: Object = new Object();;){} >anObject : Object >new Object() : Object >Object : ObjectConstructor for(var anAny: any = null;;){} >anAny : any >null : null for(var aSecondAny: any = undefined;;){} >aSecondAny : any >undefined : undefined for(var aVoid: void = undefined;;){} >aVoid : void >undefined : undefined for(var anInterface: I = new C();;){} >anInterface : I >new C() : C >C : typeof C for(var aClass: C = new C();;){} >aClass : C >new C() : C >C : typeof C for(var aGenericClass: D<string> = new D<string>();;){} >aGenericClass : D<string> >new D<string>() : D<string> >D : typeof D for(var anObjectLiteral: I = { id: 12 };;){} >anObjectLiteral : I >{ id: 12 } : { id: number; } >id : number >12 : 12 for(var anOtherObjectLiteral: { id: number } = new C();;){} >anOtherObjectLiteral : { id: number; } >id : number >new C() : C >C : typeof C for(var aFunction: typeof F = F;;){} >aFunction : (x: string) => number >F : (x: string) => number >F : (x: string) => number for(var anOtherFunction: (x: string) => number = F;;){} >anOtherFunction : (x: string) => number >x : string >F : (x: string) => number for(var aLambda: typeof F = (x) => 2;;){} >aLambda : (x: string) => number >F : (x: string) => number >(x) => 2 : (x: string) => number >x : string >2 : 2 for(var aModule: typeof M = M;;){} >aModule : typeof M >M : typeof M >M : typeof M for(var aClassInModule: M.A = new M.A();;){} >aClassInModule : M.A >M : any >new M.A() : M.A >M.A : typeof M.A >M : typeof M >A : typeof M.A for(var aFunctionInModule: typeof M.F2 = (x) => 'this is a string';;){} >aFunctionInModule : (x: number) => string >M.F2 : (x: number) => string >M : typeof M >F2 : (x: number) => string >(x) => 'this is a string' : (x: number) => string >x : number >'this is a string' : "this is a string"
tests/baselines/reference/forStatements.types
0
https://github.com/microsoft/TypeScript/commit/a05d851dc35ff0c9de40bd9b7a4cebac7b7e0158
[ 0.0007247362518683076, 0.0002252735139336437, 0.00016369225340895355, 0.0001711365912342444, 0.00014994431694503874 ]
{ "id": 4, "code_window": [ "verify.quickInfoAt(\"1\", \"constructor Bar(value: number): Bar\", undefined); // constructors aren't actually inherited\n", "verify.quickInfoAt(\"2\", \"(method) Bar.method2(): void\", \"Foo#method2 documentation\"); // use inherited docs only\n", "verify.quickInfoAt(\"3\", \"(method) Bar.method1(): void\", undefined); // statics aren't actually inherited\n", "verify.quickInfoAt(\"4\", \"(property) Bar.property1: string\", \"Foo#property1 documentation\"); // use inherited docs only\n", "verify.quickInfoAt(\"5\", \"(property) Bar.property2: object\", \"Baz#property2 documentation\\nBar#property2\"); // include local and inherited docs\n" ], "labels": [ "keep", "keep", "keep", "keep", "add" ], "after_edit": [ "verify.quickInfoAt(\"6\", \"(property) Bar.property3: string\", undefined);" ], "file_path": "tests/cases/fourslash/jsDocInheritDoc.ts", "type": "add", "edit_start_line_idx": 57 }
/// <reference path='fourslash.ts' /> //@Filename: file.tsx // @jsx: preserve // @noLib: true //// declare function ComponentSpecific<U>(l: {prop: U}): JSX.Element; //// declare function ComponentSpecific1<U>(l: {prop: U, "ignore-prop": number}): JSX.Element; //// function Bar<T extends {prop: number}>(arg: T) { //// let a1 = <Compone/*1*/ntSpecific {...arg} ignore-prop="hi" />; // U is number //// let a2 = <ComponentSpecific1 {...arg} ignore-prop={10} />; // U is number //// let a3 = <Component/*2*/Specific {...arg} prop="hello" />; // U is "hello" //// } verify.quickInfos({ 1: "function ComponentSpecific<number>(l: {\n prop: number;\n}): JSX.Element", 2: "function ComponentSpecific<never>(l: {\n prop: never;\n}): JSX.Element" });
tests/cases/fourslash/tsxQuickInfo6.ts
0
https://github.com/microsoft/TypeScript/commit/a05d851dc35ff0c9de40bd9b7a4cebac7b7e0158
[ 0.0009803384309634566, 0.0005750763230025768, 0.0001698142586974427, 0.0005750763230025768, 0.00040526207885704935 ]
{ "id": 3, "code_window": [ "tests/cases/conformance/jsdoc/0.js(61,19): error TS2339: Property 'a' does not exist on type 'String'.\n", "tests/cases/conformance/jsdoc/0.js(61,22): error TS2339: Property 'b' does not exist on type 'String'.\n", "tests/cases/conformance/jsdoc/0.js(63,20): error TS8024: JSDoc '@param' tag has name 'y', but there is no parameter with that name.\n", "\n", "\n", "==== tests/cases/conformance/jsdoc/0.js (4 errors) ====\n", " // Object literal syntax\n", " /**\n", " * @param {{a: string, b: string}} obj\n", " * @param {string} x\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "==== tests/cases/conformance/jsdoc/0.js (3 errors) ====\n" ], "file_path": "tests/baselines/reference/jsdocParamTag2.errors.txt", "type": "replace", "edit_start_line_idx": 6 }
tests/cases/conformance/jsdoc/bad.js(2,11): error TS1003: Identifier expected. tests/cases/conformance/jsdoc/bad.js(2,11): error TS8024: JSDoc '@param' tag has name '', but there is no parameter with that name. tests/cases/conformance/jsdoc/bad.js(5,4): error TS1003: Identifier expected. tests/cases/conformance/jsdoc/bad.js(5,4): error TS8024: JSDoc '@param' tag has name '', but there is no parameter with that name. tests/cases/conformance/jsdoc/bad.js(6,20): error TS1003: Identifier expected. tests/cases/conformance/jsdoc/bad.js(6,20): error TS8024: JSDoc '@param' tag has name '', but there is no parameter with that name. tests/cases/conformance/jsdoc/bad.js(9,14): error TS7006: Parameter 'x' implicitly has an 'any' type. tests/cases/conformance/jsdoc/bad.js(9,17): error TS7006: Parameter 'y' implicitly has an 'any' type. tests/cases/conformance/jsdoc/bad.js(9,20): error TS7006: Parameter 'z' implicitly has an 'any' type. ==== tests/cases/conformance/jsdoc/good.js (0 errors) ==== /** * @param * {number} x Arg x. * @param {number} * y Arg y. * @param {number} z * Arg z. */ function good(x, y, z) { } good(1, 2, 3) ==== tests/cases/conformance/jsdoc/bad.js (9 errors) ==== /** * @param * !!! error TS1003: Identifier expected. !!! error TS8024: JSDoc '@param' tag has name '', but there is no parameter with that name. * {number} x Arg x. * @param {number} * * y Arg y. !!! error TS1003: Identifier expected. !!! error TS8024: JSDoc '@param' tag has name '', but there is no parameter with that name. * @param {number} * z !!! error TS1003: Identifier expected. !!! error TS8024: JSDoc '@param' tag has name '', but there is no parameter with that name. * Arg z. */ function bad(x, y, z) { ~ !!! error TS7006: Parameter 'x' implicitly has an 'any' type. ~ !!! error TS7006: Parameter 'y' implicitly has an 'any' type. ~ !!! error TS7006: Parameter 'z' implicitly has an 'any' type. } bad(1, 2, 3)
tests/baselines/reference/paramTagWrapping.errors.txt
1
https://github.com/microsoft/TypeScript/commit/2da62a784bbba237b8239e84c8629cfafb0f595e
[ 0.003331052605062723, 0.0007667655008845031, 0.00016890444385353476, 0.00020672380924224854, 0.0011530795600265265 ]
{ "id": 3, "code_window": [ "tests/cases/conformance/jsdoc/0.js(61,19): error TS2339: Property 'a' does not exist on type 'String'.\n", "tests/cases/conformance/jsdoc/0.js(61,22): error TS2339: Property 'b' does not exist on type 'String'.\n", "tests/cases/conformance/jsdoc/0.js(63,20): error TS8024: JSDoc '@param' tag has name 'y', but there is no parameter with that name.\n", "\n", "\n", "==== tests/cases/conformance/jsdoc/0.js (4 errors) ====\n", " // Object literal syntax\n", " /**\n", " * @param {{a: string, b: string}} obj\n", " * @param {string} x\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "==== tests/cases/conformance/jsdoc/0.js (3 errors) ====\n" ], "file_path": "tests/baselines/reference/jsdocParamTag2.errors.txt", "type": "replace", "edit_start_line_idx": 6 }
Exit Code: 2 Standard output: node_modules/@types/connect/index.d.ts(20,42): error TS2689: Cannot extend an interface 'http.IncomingMessage'. Did you mean 'implements'? Standard error:
tests/baselines/reference/user/TypeScript-WeChat-Starter.log
0
https://github.com/microsoft/TypeScript/commit/2da62a784bbba237b8239e84c8629cfafb0f595e
[ 0.0001620804105186835, 0.0001620804105186835, 0.0001620804105186835, 0.0001620804105186835, 0 ]
{ "id": 3, "code_window": [ "tests/cases/conformance/jsdoc/0.js(61,19): error TS2339: Property 'a' does not exist on type 'String'.\n", "tests/cases/conformance/jsdoc/0.js(61,22): error TS2339: Property 'b' does not exist on type 'String'.\n", "tests/cases/conformance/jsdoc/0.js(63,20): error TS8024: JSDoc '@param' tag has name 'y', but there is no parameter with that name.\n", "\n", "\n", "==== tests/cases/conformance/jsdoc/0.js (4 errors) ====\n", " // Object literal syntax\n", " /**\n", " * @param {{a: string, b: string}} obj\n", " * @param {string} x\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "==== tests/cases/conformance/jsdoc/0.js (3 errors) ====\n" ], "file_path": "tests/baselines/reference/jsdocParamTag2.errors.txt", "type": "replace", "edit_start_line_idx": 6 }
EmitSkipped: false FileName : /tests/cases/fourslash/shims/inputFile1.js var x = 5; var Bar = /** @class */ (function () { function Bar() { } return Bar; }()); FileName : /tests/cases/fourslash/shims/inputFile1.d.ts declare var x: number; declare class Bar { x: string; y: number; } EmitSkipped: false FileName : /tests/cases/fourslash/shims/inputFile2.js var x1 = "hello world"; var Foo = /** @class */ (function () { function Foo() { } return Foo; }()); FileName : /tests/cases/fourslash/shims/inputFile2.d.ts declare var x1: string; declare class Foo { x: string; y: number; }
tests/baselines/reference/getEmitOutput.baseline
0
https://github.com/microsoft/TypeScript/commit/2da62a784bbba237b8239e84c8629cfafb0f595e
[ 0.0001694277161732316, 0.00016686049639247358, 0.00016426124784629792, 0.00016687647439539433, 0.000002344421773159411 ]
{ "id": 3, "code_window": [ "tests/cases/conformance/jsdoc/0.js(61,19): error TS2339: Property 'a' does not exist on type 'String'.\n", "tests/cases/conformance/jsdoc/0.js(61,22): error TS2339: Property 'b' does not exist on type 'String'.\n", "tests/cases/conformance/jsdoc/0.js(63,20): error TS8024: JSDoc '@param' tag has name 'y', but there is no parameter with that name.\n", "\n", "\n", "==== tests/cases/conformance/jsdoc/0.js (4 errors) ====\n", " // Object literal syntax\n", " /**\n", " * @param {{a: string, b: string}} obj\n", " * @param {string} x\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "==== tests/cases/conformance/jsdoc/0.js (3 errors) ====\n" ], "file_path": "tests/baselines/reference/jsdocParamTag2.errors.txt", "type": "replace", "edit_start_line_idx": 6 }
tests/cases/compiler/destructuredLateBoundNameHasCorrectTypes.ts(11,21): error TS2525: Initializer provides no value for this binding element and the binding element has no default value. tests/cases/compiler/destructuredLateBoundNameHasCorrectTypes.ts(11,37): error TS2353: Object literal may only specify known properties, and 'prop' does not exist in type '{ prop2: any; }'. ==== tests/cases/compiler/destructuredLateBoundNameHasCorrectTypes.ts (2 errors) ==== let { [Symbol.iterator]: destructured } = []; void destructured; const named = "prop"; let { [named]: computed } = { prop: "b" }; void computed; const notPresent = "prop2"; let { [notPresent]: computed2 } = { prop: "b" }; ~~~~~~~~~ !!! error TS2525: Initializer provides no value for this binding element and the binding element has no default value. ~~~~ !!! error TS2353: Object literal may only specify known properties, and 'prop' does not exist in type '{ prop2: any; }'.
tests/baselines/reference/destructuredLateBoundNameHasCorrectTypes.errors.txt
0
https://github.com/microsoft/TypeScript/commit/2da62a784bbba237b8239e84c8629cfafb0f595e
[ 0.00019708088075276464, 0.0001807030785130337, 0.0001669694611337036, 0.00017805895186029375, 0.000012434308700903784 ]
{ "id": 4, "code_window": [ " \n", " /**\n", " * @param {object} obj - this type gets ignored\n", " ~~~\n", "!!! error TS8024: JSDoc '@param' tag has name 'obj', but there is no parameter with that name.\n", " * @param {string} obj.a\n", " * @param {string} obj.b - and x's type gets used for both parameters\n", " * @param {string} x\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "tests/baselines/reference/jsdocParamTag2.errors.txt", "type": "replace", "edit_start_line_idx": 63 }
tests/cases/conformance/jsdoc/bad.js(2,11): error TS1003: Identifier expected. tests/cases/conformance/jsdoc/bad.js(2,11): error TS8024: JSDoc '@param' tag has name '', but there is no parameter with that name. tests/cases/conformance/jsdoc/bad.js(5,4): error TS1003: Identifier expected. tests/cases/conformance/jsdoc/bad.js(5,4): error TS8024: JSDoc '@param' tag has name '', but there is no parameter with that name. tests/cases/conformance/jsdoc/bad.js(6,20): error TS1003: Identifier expected. tests/cases/conformance/jsdoc/bad.js(6,20): error TS8024: JSDoc '@param' tag has name '', but there is no parameter with that name. tests/cases/conformance/jsdoc/bad.js(9,14): error TS7006: Parameter 'x' implicitly has an 'any' type. tests/cases/conformance/jsdoc/bad.js(9,17): error TS7006: Parameter 'y' implicitly has an 'any' type. tests/cases/conformance/jsdoc/bad.js(9,20): error TS7006: Parameter 'z' implicitly has an 'any' type. ==== tests/cases/conformance/jsdoc/good.js (0 errors) ==== /** * @param * {number} x Arg x. * @param {number} * y Arg y. * @param {number} z * Arg z. */ function good(x, y, z) { } good(1, 2, 3) ==== tests/cases/conformance/jsdoc/bad.js (9 errors) ==== /** * @param * !!! error TS1003: Identifier expected. !!! error TS8024: JSDoc '@param' tag has name '', but there is no parameter with that name. * {number} x Arg x. * @param {number} * * y Arg y. !!! error TS1003: Identifier expected. !!! error TS8024: JSDoc '@param' tag has name '', but there is no parameter with that name. * @param {number} * z !!! error TS1003: Identifier expected. !!! error TS8024: JSDoc '@param' tag has name '', but there is no parameter with that name. * Arg z. */ function bad(x, y, z) { ~ !!! error TS7006: Parameter 'x' implicitly has an 'any' type. ~ !!! error TS7006: Parameter 'y' implicitly has an 'any' type. ~ !!! error TS7006: Parameter 'z' implicitly has an 'any' type. } bad(1, 2, 3)
tests/baselines/reference/paramTagWrapping.errors.txt
1
https://github.com/microsoft/TypeScript/commit/2da62a784bbba237b8239e84c8629cfafb0f595e
[ 0.0006647018599323928, 0.00034158318885602057, 0.00016510463319718838, 0.0002194600092479959, 0.00021034019300714135 ]
{ "id": 4, "code_window": [ " \n", " /**\n", " * @param {object} obj - this type gets ignored\n", " ~~~\n", "!!! error TS8024: JSDoc '@param' tag has name 'obj', but there is no parameter with that name.\n", " * @param {string} obj.a\n", " * @param {string} obj.b - and x's type gets used for both parameters\n", " * @param {string} x\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "tests/baselines/reference/jsdocParamTag2.errors.txt", "type": "replace", "edit_start_line_idx": 63 }
//// [parservoidInQualifiedName0.ts] var v : void; //// [parservoidInQualifiedName0.js] var v;
tests/baselines/reference/parservoidInQualifiedName0.js
0
https://github.com/microsoft/TypeScript/commit/2da62a784bbba237b8239e84c8629cfafb0f595e
[ 0.00017472583567723632, 0.00017472583567723632, 0.00017472583567723632, 0.00017472583567723632, 0 ]
{ "id": 4, "code_window": [ " \n", " /**\n", " * @param {object} obj - this type gets ignored\n", " ~~~\n", "!!! error TS8024: JSDoc '@param' tag has name 'obj', but there is no parameter with that name.\n", " * @param {string} obj.a\n", " * @param {string} obj.b - and x's type gets used for both parameters\n", " * @param {string} x\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "tests/baselines/reference/jsdocParamTag2.errors.txt", "type": "replace", "edit_start_line_idx": 63 }
//// [asyncArrowFunction8_es6.ts] var foo = async (): Promise<void> => { var v = { [await]: foo } } //// [asyncArrowFunction8_es6.js] var foo = () => __awaiter(this, void 0, void 0, function* () { var v = { [yield ]: foo }; });
tests/baselines/reference/asyncArrowFunction8_es6.js
0
https://github.com/microsoft/TypeScript/commit/2da62a784bbba237b8239e84c8629cfafb0f595e
[ 0.00017301311891060323, 0.00017301311891060323, 0.00017301311891060323, 0.00017301311891060323, 0 ]
{ "id": 4, "code_window": [ " \n", " /**\n", " * @param {object} obj - this type gets ignored\n", " ~~~\n", "!!! error TS8024: JSDoc '@param' tag has name 'obj', but there is no parameter with that name.\n", " * @param {string} obj.a\n", " * @param {string} obj.b - and x's type gets used for both parameters\n", " * @param {string} x\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "tests/baselines/reference/jsdocParamTag2.errors.txt", "type": "replace", "edit_start_line_idx": 63 }
const fn = <T>(): (() => T) => null as any;
tests/cases/compiler/parseArrowFunctionWithFunctionReturnType.ts
0
https://github.com/microsoft/TypeScript/commit/2da62a784bbba237b8239e84c8629cfafb0f595e
[ 0.00016685121227055788, 0.00016685121227055788, 0.00016685121227055788, 0.00016685121227055788, 0 ]
{ "id": 0, "code_window": [ " active: boolean;\n", "}\n", "\n", "export const Panel = ({ active }: Props) => {\n", " const { 0: results, 1: setState } = useAddonState<Results>(ADDON_ID, []);\n", " const emit = useChannel({\n", " [EVENTS.RESULT]: newResults => setState(newResults),\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const [results, setState] = useAddonState<Results>(ADDON_ID, []);\n" ], "file_path": "dev-kits/addon-roundtrip/src/panel.tsx", "type": "replace", "edit_start_line_idx": 11 }
/* eslint-disable react/no-multi-comp */ import React, { ReactElement, Component, useContext, useEffect } from 'react'; import memoize from 'memoizerific'; // @ts-ignore shallow-equal is not in DefinitelyTyped import shallowEqualObjects from 'shallow-equal/objects'; import Events from '@storybook/core-events'; import { RenderData as RouterData } from '@storybook/router'; import { Listener } from '@storybook/channels'; import initProviderApi, { SubAPI as ProviderAPI, Provider } from './init-provider-api'; import { createContext } from './context'; import Store, { Options } from './store'; import getInitialState from './initial-state'; import initAddons, { SubAPI as AddonsAPI } from './modules/addons'; import initChannel, { SubAPI as ChannelAPI } from './modules/channel'; import initNotifications, { SubState as NotificationState, SubAPI as NotificationAPI, } from './modules/notifications'; import initStories, { SubState as StoriesSubState, SubAPI as StoriesAPI, StoriesRaw, } from './modules/stories'; import initLayout, { SubState as LayoutSubState, SubAPI as LayoutAPI } from './modules/layout'; import initShortcuts, { SubState as ShortcutsSubState, SubAPI as ShortcutsAPI, } from './modules/shortcuts'; import initURL, { QueryParams, SubAPI as UrlAPI } from './modules/url'; import initVersions, { SubState as VersionsSubState, SubAPI as VersionsAPI, } from './modules/versions'; export { Options as StoreOptions, Listener as ChannelListener }; const ManagerContext = createContext({ api: undefined, state: getInitialState({}) }); const { STORY_CHANGED, SET_STORIES, SELECT_STORY } = Events; export type Module = StoreData & RouterData & ProviderData & { mode?: 'production' | 'development' }; export type State = Other & LayoutSubState & StoriesSubState & NotificationState & VersionsSubState & RouterData & ShortcutsSubState; export type API = AddonsAPI & ChannelAPI & ProviderAPI & StoriesAPI & LayoutAPI & NotificationAPI & ShortcutsAPI & VersionsAPI & UrlAPI & OtherAPI; interface OtherAPI { [key: string]: any; } interface Other { customQueryParams: QueryParams; [key: string]: any; } export interface Combo { api: API; state: State; } interface ProviderData { provider: Provider; } interface StoreData { store: Store; } interface Children { children: Component | ((props: Combo) => Component); } type StatePartial = Partial<State>; export type Props = Children & RouterData & ProviderData; class ManagerProvider extends Component<Props, State> { static displayName = 'Manager'; api: API; modules: any[]; constructor(props: Props) { super(props); const { provider, location, path, viewMode, storyId, navigate } = props; const store = new Store({ getState: () => this.state, setState: (stateChange: StatePartial, callback) => this.setState(stateChange, callback), }); // Initialize the state to be the initial (persisted) state of the store. // This gives the modules the chance to read the persisted state, apply their defaults // and override if necessary this.state = store.getInitialState(getInitialState({})); const apiData = { navigate, store, provider, location, path, viewMode, storyId, }; this.modules = [ initChannel, initAddons, initLayout, initNotifications, initShortcuts, initStories, initURL, initVersions, ].map(initModule => initModule(apiData)); // Create our initial state by combining the initial state of all modules, then overlaying any saved state const state = getInitialState(...this.modules.map(m => m.state)); // Get our API by combining the APIs exported by each module const combo = Object.assign({ navigate }, ...this.modules.map(m => m.api)); const api = initProviderApi({ provider, store, api: combo }); api.on(STORY_CHANGED, (id: string) => { const options = api.getParameters(id, 'options'); if (options) { api.setOptions(options); } }); api.on(SET_STORIES, (data: { stories: StoriesRaw }) => { api.setStories(data.stories); const options = storyId ? api.getParameters(storyId, 'options') : api.getParameters(Object.keys(data.stories)[0], 'options'); api.setOptions(options); }); api.on( SELECT_STORY, ({ kind, story, ...rest }: { kind: string; story: string; [k: string]: any }) => { api.selectStory(kind, story, rest); } ); this.state = state; this.api = api; } static getDerivedStateFromProps = (props: Props, state: State) => { if (state.path !== props.path) { return { ...state, location: props.location, path: props.path, viewMode: props.viewMode, storyId: props.storyId, }; } return null; }; componentDidMount() { // Now every module has had a chance to set its API, call init on each module which gives it // a chance to do things that call other modules' APIs. this.modules.forEach(({ init }) => { if (init) { init({ api: this.api }); } }); } shouldComponentUpdate(nextProps: Props, nextState: State) { const prevState = this.state; const prevProps = this.props; if (prevState !== nextState) { return true; } if (prevProps.path !== nextProps.path) { return true; } return false; } render() { const { children } = this.props; const value = { state: this.state, api: this.api, }; return ( <ManagerContext.Provider value={value}> {typeof children === 'function' ? children(value) : children} </ManagerContext.Provider> ); } } interface ConsumerProps<S, C> { filter?: (combo: C) => S; pure?: boolean; children: (d: S | C) => ReactElement<any> | null; } interface SubState { [key: string]: any; } class ManagerConsumer extends Component<ConsumerProps<SubState, Combo>> { dataMemory?: (combo: Combo) => SubState; prevChildren?: ReactElement<any> | null; prevData?: SubState; constructor(props: ConsumerProps<SubState, Combo>) { super(props); this.dataMemory = props.filter ? memoize(10)(props.filter) : null; } render() { const { children, pure } = this.props; return ( <ManagerContext.Consumer> {d => { const data = this.dataMemory ? this.dataMemory(d) : d; if ( pure && this.prevChildren && this.prevData && shallowEqualObjects(data, this.prevData) ) { return this.prevChildren; } this.prevChildren = children(data); this.prevData = data; return this.prevChildren; }} </ManagerContext.Consumer> ); } } export function useStorybookState(): State { const { state } = useContext(ManagerContext); return state; } export function useStorybookApi(): API { const { api } = useContext(ManagerContext); return api; } export { ManagerConsumer as Consumer, ManagerProvider as Provider }; export interface EventMap { [eventId: string]: Listener; } function getAddonStateOrDefault<S>(api: API, addonId: string, defaultState: S): S { const fromStore = api.getAddonState(addonId); if (typeof fromStore === 'undefined') { api.setAddonState<S>(addonId, defaultState); return defaultState; } return fromStore as S; } type StateMerger<S> = (input: S) => S; export function useAddonState<S>(addonId: string, defaultState?: S) { const api = useStorybookApi(); const setState = (newStateOrMerger: S | StateMerger<S>, options?: Options) => api.setAddonState<S>(addonId, newStateOrMerger, options); const state = getAddonStateOrDefault<S>(api, addonId, defaultState); return { 0: state, 1: setState }; } export const useChannel = (eventMap: EventMap) => { const api = useStorybookApi(); useEffect(() => { Object.entries(eventMap).forEach(([type, listener]) => api.on(type, listener)); return () => { Object.entries(eventMap).forEach(([type, listener]) => api.off(type, listener)); }; }); return api.emit; };
lib/api/src/index.tsx
1
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.0023601411376148462, 0.0004765824996866286, 0.00016564186080358922, 0.00017477769870311022, 0.0006690995069220662 ]
{ "id": 0, "code_window": [ " active: boolean;\n", "}\n", "\n", "export const Panel = ({ active }: Props) => {\n", " const { 0: results, 1: setState } = useAddonState<Results>(ADDON_ID, []);\n", " const emit = useChannel({\n", " [EVENTS.RESULT]: newResults => setState(newResults),\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const [results, setState] = useAddonState<Results>(ADDON_ID, []);\n" ], "file_path": "dev-kits/addon-roundtrip/src/panel.tsx", "type": "replace", "edit_start_line_idx": 11 }
local
lib/cli/test/fixtures/meteor/.meteor/.gitignore
0
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.00017826755356509238, 0.00017826755356509238, 0.00017826755356509238, 0.00017826755356509238, 0 ]
{ "id": 0, "code_window": [ " active: boolean;\n", "}\n", "\n", "export const Panel = ({ active }: Props) => {\n", " const { 0: results, 1: setState } = useAddonState<Results>(ADDON_ID, []);\n", " const emit = useChannel({\n", " [EVENTS.RESULT]: newResults => setState(newResults),\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const [results, setState] = useAddonState<Results>(ADDON_ID, []);\n" ], "file_path": "dev-kits/addon-roundtrip/src/panel.tsx", "type": "replace", "edit_start_line_idx": 11 }
/* You can add global styles to this file, and also import other style files */
lib/cli/test/fixtures/angular-cli-v6/src/styles.css
0
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.00017661626043263823, 0.00017661626043263823, 0.00017661626043263823, 0.00017661626043263823, 0 ]
{ "id": 0, "code_window": [ " active: boolean;\n", "}\n", "\n", "export const Panel = ({ active }: Props) => {\n", " const { 0: results, 1: setState } = useAddonState<Results>(ADDON_ID, []);\n", " const emit = useChannel({\n", " [EVENTS.RESULT]: newResults => setState(newResults),\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const [results, setState] = useAddonState<Results>(ADDON_ID, []);\n" ], "file_path": "dev-kits/addon-roundtrip/src/panel.tsx", "type": "replace", "edit_start_line_idx": 11 }
export function babelDefault(config) { return { ...config, plugins: [ ...config.plugins, [require.resolve('@babel/plugin-transform-react-jsx'), { pragma: 'h' }], ], }; }
app/preact/src/server/framework-preset-preact.js
0
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.00017517490778118372, 0.00017517490778118372, 0.00017517490778118372, 0.00017517490778118372, 0 ]
{ "id": 1, "code_window": [ " [eventId: string]: Listener;\n", "}\n", "\n", "function getAddonStateOrDefault<S>(api: API, addonId: string, defaultState: S): S {\n", " const fromStore = api.getAddonState(addonId);\n", " if (typeof fromStore === 'undefined') {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "function stateOrDefault<S>(fromStore: S, defaultState: S): S {\n" ], "file_path": "lib/api/src/index.tsx", "type": "replace", "edit_start_line_idx": 284 }
/* eslint-disable react/no-multi-comp */ import React, { ReactElement, Component, useContext, useEffect } from 'react'; import memoize from 'memoizerific'; // @ts-ignore shallow-equal is not in DefinitelyTyped import shallowEqualObjects from 'shallow-equal/objects'; import Events from '@storybook/core-events'; import { RenderData as RouterData } from '@storybook/router'; import { Listener } from '@storybook/channels'; import initProviderApi, { SubAPI as ProviderAPI, Provider } from './init-provider-api'; import { createContext } from './context'; import Store, { Options } from './store'; import getInitialState from './initial-state'; import initAddons, { SubAPI as AddonsAPI } from './modules/addons'; import initChannel, { SubAPI as ChannelAPI } from './modules/channel'; import initNotifications, { SubState as NotificationState, SubAPI as NotificationAPI, } from './modules/notifications'; import initStories, { SubState as StoriesSubState, SubAPI as StoriesAPI, StoriesRaw, } from './modules/stories'; import initLayout, { SubState as LayoutSubState, SubAPI as LayoutAPI } from './modules/layout'; import initShortcuts, { SubState as ShortcutsSubState, SubAPI as ShortcutsAPI, } from './modules/shortcuts'; import initURL, { QueryParams, SubAPI as UrlAPI } from './modules/url'; import initVersions, { SubState as VersionsSubState, SubAPI as VersionsAPI, } from './modules/versions'; export { Options as StoreOptions, Listener as ChannelListener }; const ManagerContext = createContext({ api: undefined, state: getInitialState({}) }); const { STORY_CHANGED, SET_STORIES, SELECT_STORY } = Events; export type Module = StoreData & RouterData & ProviderData & { mode?: 'production' | 'development' }; export type State = Other & LayoutSubState & StoriesSubState & NotificationState & VersionsSubState & RouterData & ShortcutsSubState; export type API = AddonsAPI & ChannelAPI & ProviderAPI & StoriesAPI & LayoutAPI & NotificationAPI & ShortcutsAPI & VersionsAPI & UrlAPI & OtherAPI; interface OtherAPI { [key: string]: any; } interface Other { customQueryParams: QueryParams; [key: string]: any; } export interface Combo { api: API; state: State; } interface ProviderData { provider: Provider; } interface StoreData { store: Store; } interface Children { children: Component | ((props: Combo) => Component); } type StatePartial = Partial<State>; export type Props = Children & RouterData & ProviderData; class ManagerProvider extends Component<Props, State> { static displayName = 'Manager'; api: API; modules: any[]; constructor(props: Props) { super(props); const { provider, location, path, viewMode, storyId, navigate } = props; const store = new Store({ getState: () => this.state, setState: (stateChange: StatePartial, callback) => this.setState(stateChange, callback), }); // Initialize the state to be the initial (persisted) state of the store. // This gives the modules the chance to read the persisted state, apply their defaults // and override if necessary this.state = store.getInitialState(getInitialState({})); const apiData = { navigate, store, provider, location, path, viewMode, storyId, }; this.modules = [ initChannel, initAddons, initLayout, initNotifications, initShortcuts, initStories, initURL, initVersions, ].map(initModule => initModule(apiData)); // Create our initial state by combining the initial state of all modules, then overlaying any saved state const state = getInitialState(...this.modules.map(m => m.state)); // Get our API by combining the APIs exported by each module const combo = Object.assign({ navigate }, ...this.modules.map(m => m.api)); const api = initProviderApi({ provider, store, api: combo }); api.on(STORY_CHANGED, (id: string) => { const options = api.getParameters(id, 'options'); if (options) { api.setOptions(options); } }); api.on(SET_STORIES, (data: { stories: StoriesRaw }) => { api.setStories(data.stories); const options = storyId ? api.getParameters(storyId, 'options') : api.getParameters(Object.keys(data.stories)[0], 'options'); api.setOptions(options); }); api.on( SELECT_STORY, ({ kind, story, ...rest }: { kind: string; story: string; [k: string]: any }) => { api.selectStory(kind, story, rest); } ); this.state = state; this.api = api; } static getDerivedStateFromProps = (props: Props, state: State) => { if (state.path !== props.path) { return { ...state, location: props.location, path: props.path, viewMode: props.viewMode, storyId: props.storyId, }; } return null; }; componentDidMount() { // Now every module has had a chance to set its API, call init on each module which gives it // a chance to do things that call other modules' APIs. this.modules.forEach(({ init }) => { if (init) { init({ api: this.api }); } }); } shouldComponentUpdate(nextProps: Props, nextState: State) { const prevState = this.state; const prevProps = this.props; if (prevState !== nextState) { return true; } if (prevProps.path !== nextProps.path) { return true; } return false; } render() { const { children } = this.props; const value = { state: this.state, api: this.api, }; return ( <ManagerContext.Provider value={value}> {typeof children === 'function' ? children(value) : children} </ManagerContext.Provider> ); } } interface ConsumerProps<S, C> { filter?: (combo: C) => S; pure?: boolean; children: (d: S | C) => ReactElement<any> | null; } interface SubState { [key: string]: any; } class ManagerConsumer extends Component<ConsumerProps<SubState, Combo>> { dataMemory?: (combo: Combo) => SubState; prevChildren?: ReactElement<any> | null; prevData?: SubState; constructor(props: ConsumerProps<SubState, Combo>) { super(props); this.dataMemory = props.filter ? memoize(10)(props.filter) : null; } render() { const { children, pure } = this.props; return ( <ManagerContext.Consumer> {d => { const data = this.dataMemory ? this.dataMemory(d) : d; if ( pure && this.prevChildren && this.prevData && shallowEqualObjects(data, this.prevData) ) { return this.prevChildren; } this.prevChildren = children(data); this.prevData = data; return this.prevChildren; }} </ManagerContext.Consumer> ); } } export function useStorybookState(): State { const { state } = useContext(ManagerContext); return state; } export function useStorybookApi(): API { const { api } = useContext(ManagerContext); return api; } export { ManagerConsumer as Consumer, ManagerProvider as Provider }; export interface EventMap { [eventId: string]: Listener; } function getAddonStateOrDefault<S>(api: API, addonId: string, defaultState: S): S { const fromStore = api.getAddonState(addonId); if (typeof fromStore === 'undefined') { api.setAddonState<S>(addonId, defaultState); return defaultState; } return fromStore as S; } type StateMerger<S> = (input: S) => S; export function useAddonState<S>(addonId: string, defaultState?: S) { const api = useStorybookApi(); const setState = (newStateOrMerger: S | StateMerger<S>, options?: Options) => api.setAddonState<S>(addonId, newStateOrMerger, options); const state = getAddonStateOrDefault<S>(api, addonId, defaultState); return { 0: state, 1: setState }; } export const useChannel = (eventMap: EventMap) => { const api = useStorybookApi(); useEffect(() => { Object.entries(eventMap).forEach(([type, listener]) => api.on(type, listener)); return () => { Object.entries(eventMap).forEach(([type, listener]) => api.off(type, listener)); }; }); return api.emit; };
lib/api/src/index.tsx
1
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.999214768409729, 0.09390705823898315, 0.0001665798481553793, 0.00017355613817926496, 0.290926069021225 ]
{ "id": 1, "code_window": [ " [eventId: string]: Listener;\n", "}\n", "\n", "function getAddonStateOrDefault<S>(api: API, addonId: string, defaultState: S): S {\n", " const fromStore = api.getAddonState(addonId);\n", " if (typeof fromStore === 'undefined') {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "function stateOrDefault<S>(fromStore: S, defaultState: S): S {\n" ], "file_path": "lib/api/src/index.tsx", "type": "replace", "edit_start_line_idx": 284 }
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], imports: [BrowserModule], providers: [], bootstrap: [AppComponent], }) export class AppModule {}
examples/angular-cli/src/app/app.module.ts
0
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.00017591977666597813, 0.00017434675828553736, 0.0001727737399050966, 0.00017434675828553736, 0.0000015730183804407716 ]
{ "id": 1, "code_window": [ " [eventId: string]: Listener;\n", "}\n", "\n", "function getAddonStateOrDefault<S>(api: API, addonId: string, defaultState: S): S {\n", " const fromStore = api.getAddonState(addonId);\n", " if (typeof fromStore === 'undefined') {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "function stateOrDefault<S>(fromStore: S, defaultState: S): S {\n" ], "file_path": "lib/api/src/index.tsx", "type": "replace", "edit_start_line_idx": 284 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Storyshots Addon|Knobs Simple 1`] = ` <section class="storybook-snapshot-container" > <div style="width: 200px; height: 200px; background-color: green;" > <p> I am interactive </p> </div> </section> `;
examples/svelte-kitchen-sink/src/stories/__snapshots__/addon-knobs.stories.storyshot
0
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.0001743266184348613, 0.00017331729759462178, 0.00017230799130629748, 0.00017331729759462178, 0.0000010093135642819107 ]
{ "id": 1, "code_window": [ " [eventId: string]: Listener;\n", "}\n", "\n", "function getAddonStateOrDefault<S>(api: API, addonId: string, defaultState: S): S {\n", " const fromStore = api.getAddonState(addonId);\n", " if (typeof fromStore === 'undefined') {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "function stateOrDefault<S>(fromStore: S, defaultState: S): S {\n" ], "file_path": "lib/api/src/index.tsx", "type": "replace", "edit_start_line_idx": 284 }
// Based on http://backbonejs.org/docs/backbone.html#section-164 import { document, Element } from 'global'; import { isEqual } from 'lodash'; import { addons } from '@storybook/addons'; import Events from '@storybook/core-events'; import { actions } from './actions'; let lastSubscription: () => () => void; let lastArgs: any[]; const delegateEventSplitter = /^(\S+)\s*(.*)$/; const isIE = Element != null && !Element.prototype.matches; const matchesMethod = isIE ? 'msMatchesSelector' : 'matches'; const root = document && document.getElementById('root'); const hasMatchInAncestry = (element: any, selector: any): boolean => { if (element[matchesMethod](selector)) { return true; } const parent = element.parentElement; if (!parent) { return false; } return hasMatchInAncestry(parent, selector); }; const createHandlers = (actionsFn: (...arg: any[]) => object, ...args: any[]) => { const actionsObject = actionsFn(...args); return Object.entries(actionsObject).map(([key, action]) => { const [_, eventName, selector] = key.match(delegateEventSplitter); return { eventName, handler: (e: { target: any }) => { if (!selector || hasMatchInAncestry(e.target, selector)) { action(e); } }, }; }); }; const actionsSubscription = (...args: any[]) => { if (!isEqual(args, lastArgs)) { lastArgs = args; // @ts-ignore const handlers = createHandlers(...args); lastSubscription = () => { handlers.forEach(({ eventName, handler }) => root.addEventListener(eventName, handler)); return () => handlers.forEach(({ eventName, handler }) => root.removeEventListener(eventName, handler)); }; } return lastSubscription; }; export const createDecorator = (actionsFn: any) => (...args: any[]) => (storyFn: () => any) => { if (root != null) { addons.getChannel().emit(Events.REGISTER_SUBSCRIPTION, actionsSubscription(actionsFn, ...args)); } return storyFn(); }; export const withActions = createDecorator(actions);
addons/actions/src/preview/withActions.ts
0
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.0001721984299365431, 0.00017001850937958807, 0.000168284255778417, 0.0001696744147920981, 0.0000015034107718747691 ]
{ "id": 2, "code_window": [ " if (typeof fromStore === 'undefined') {\n", " api.setAddonState<S>(addonId, defaultState);\n", "\n", " return defaultState;\n", " }\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "lib/api/src/index.tsx", "type": "replace", "edit_start_line_idx": 287 }
import React, { Fragment, useMemo } from 'react'; import { useAddonState, useChannel } from '@storybook/api'; import { ADDON_ID, EVENTS } from './constants'; type Results = string[]; interface Props { active: boolean; } export const Panel = ({ active }: Props) => { const { 0: results, 1: setState } = useAddonState<Results>(ADDON_ID, []); const emit = useChannel({ [EVENTS.RESULT]: newResults => setState(newResults), }); const output = useMemo( () => ( <div hidden={!active}> {results.length ? ( <ol> {results.map((i: string) => ( <li key={i.toString()}>{i}</li> ))} </ol> ) : null} <button type="button" onClick={() => emit(EVENTS.REQUEST)}> emit </button> <button type="button" onClick={() => setState([])}> setState </button> <button type="button" onClick={() => setState([], { persistence: 'session' })}> setState with options </button> <button type="button" onClick={() => setState(s => [...s, 'foo'])}> setState with function </button> </div> ), [active, results] ); return <Fragment>{output}</Fragment>; };
dev-kits/addon-roundtrip/src/panel.tsx
1
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.0009771785698831081, 0.0003983044589404017, 0.0001655004161875695, 0.0001748975191731006, 0.0003169388510286808 ]
{ "id": 2, "code_window": [ " if (typeof fromStore === 'undefined') {\n", " api.setAddonState<S>(addonId, defaultState);\n", "\n", " return defaultState;\n", " }\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "lib/api/src/index.tsx", "type": "replace", "edit_start_line_idx": 287 }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Hello world</title> </head> <body> <div id="root"></div> <script src="dist/bundle.js"></script> </body> </html>
lib/cli/test/fixtures/webpack_react_frozen_lock/index.html
0
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.0001772587129380554, 0.00017488296725787222, 0.00017250723612960428, 0.00017488296725787222, 0.000002375738404225558 ]
{ "id": 2, "code_window": [ " if (typeof fromStore === 'undefined') {\n", " api.setAddonState<S>(addonId, defaultState);\n", "\n", " return defaultState;\n", " }\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "lib/api/src/index.tsx", "type": "replace", "edit_start_line_idx": 287 }
#!/usr/bin/env node process.env.NODE_ENV = process.env.NODE_ENV || 'production'; require('../dist/server/build');
app/angular/bin/build.js
0
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.00016888593381736428, 0.00016888593381736428, 0.00016888593381736428, 0.00016888593381736428, 0 ]
{ "id": 2, "code_window": [ " if (typeof fromStore === 'undefined') {\n", " api.setAddonState<S>(addonId, defaultState);\n", "\n", " return defaultState;\n", " }\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "lib/api/src/index.tsx", "type": "replace", "edit_start_line_idx": 287 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Storyshots Core|Parameters passed to story 1`] = ` <div data-is="parameters" id="root" > <div> Parameters are {"options":{"hierarchyRootSeparator":{},"hierarchySeparator":{}},"globalParameter":"globalParameter","chapterParameter":"chapterParameter","storyParameter":"storyParameter","id":"root","dataIs":"parameters"} </div> </div> `;
examples/riot-kitchen-sink/src/stories/__snapshots__/core.stories.storyshot
0
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.00017710414249449968, 0.00017546274466440082, 0.00017382136138621718, 0.00017546274466440082, 0.0000016413905541412532 ]
{ "id": 3, "code_window": [ " return defaultState;\n", " }\n", " return fromStore as S;\n", "}\n", "\n", "type StateMerger<S> = (input: S) => S;\n", "\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return fromStore;\n" ], "file_path": "lib/api/src/index.tsx", "type": "replace", "edit_start_line_idx": 291 }
/* eslint-disable react/no-multi-comp */ import React, { ReactElement, Component, useContext, useEffect } from 'react'; import memoize from 'memoizerific'; // @ts-ignore shallow-equal is not in DefinitelyTyped import shallowEqualObjects from 'shallow-equal/objects'; import Events from '@storybook/core-events'; import { RenderData as RouterData } from '@storybook/router'; import { Listener } from '@storybook/channels'; import initProviderApi, { SubAPI as ProviderAPI, Provider } from './init-provider-api'; import { createContext } from './context'; import Store, { Options } from './store'; import getInitialState from './initial-state'; import initAddons, { SubAPI as AddonsAPI } from './modules/addons'; import initChannel, { SubAPI as ChannelAPI } from './modules/channel'; import initNotifications, { SubState as NotificationState, SubAPI as NotificationAPI, } from './modules/notifications'; import initStories, { SubState as StoriesSubState, SubAPI as StoriesAPI, StoriesRaw, } from './modules/stories'; import initLayout, { SubState as LayoutSubState, SubAPI as LayoutAPI } from './modules/layout'; import initShortcuts, { SubState as ShortcutsSubState, SubAPI as ShortcutsAPI, } from './modules/shortcuts'; import initURL, { QueryParams, SubAPI as UrlAPI } from './modules/url'; import initVersions, { SubState as VersionsSubState, SubAPI as VersionsAPI, } from './modules/versions'; export { Options as StoreOptions, Listener as ChannelListener }; const ManagerContext = createContext({ api: undefined, state: getInitialState({}) }); const { STORY_CHANGED, SET_STORIES, SELECT_STORY } = Events; export type Module = StoreData & RouterData & ProviderData & { mode?: 'production' | 'development' }; export type State = Other & LayoutSubState & StoriesSubState & NotificationState & VersionsSubState & RouterData & ShortcutsSubState; export type API = AddonsAPI & ChannelAPI & ProviderAPI & StoriesAPI & LayoutAPI & NotificationAPI & ShortcutsAPI & VersionsAPI & UrlAPI & OtherAPI; interface OtherAPI { [key: string]: any; } interface Other { customQueryParams: QueryParams; [key: string]: any; } export interface Combo { api: API; state: State; } interface ProviderData { provider: Provider; } interface StoreData { store: Store; } interface Children { children: Component | ((props: Combo) => Component); } type StatePartial = Partial<State>; export type Props = Children & RouterData & ProviderData; class ManagerProvider extends Component<Props, State> { static displayName = 'Manager'; api: API; modules: any[]; constructor(props: Props) { super(props); const { provider, location, path, viewMode, storyId, navigate } = props; const store = new Store({ getState: () => this.state, setState: (stateChange: StatePartial, callback) => this.setState(stateChange, callback), }); // Initialize the state to be the initial (persisted) state of the store. // This gives the modules the chance to read the persisted state, apply their defaults // and override if necessary this.state = store.getInitialState(getInitialState({})); const apiData = { navigate, store, provider, location, path, viewMode, storyId, }; this.modules = [ initChannel, initAddons, initLayout, initNotifications, initShortcuts, initStories, initURL, initVersions, ].map(initModule => initModule(apiData)); // Create our initial state by combining the initial state of all modules, then overlaying any saved state const state = getInitialState(...this.modules.map(m => m.state)); // Get our API by combining the APIs exported by each module const combo = Object.assign({ navigate }, ...this.modules.map(m => m.api)); const api = initProviderApi({ provider, store, api: combo }); api.on(STORY_CHANGED, (id: string) => { const options = api.getParameters(id, 'options'); if (options) { api.setOptions(options); } }); api.on(SET_STORIES, (data: { stories: StoriesRaw }) => { api.setStories(data.stories); const options = storyId ? api.getParameters(storyId, 'options') : api.getParameters(Object.keys(data.stories)[0], 'options'); api.setOptions(options); }); api.on( SELECT_STORY, ({ kind, story, ...rest }: { kind: string; story: string; [k: string]: any }) => { api.selectStory(kind, story, rest); } ); this.state = state; this.api = api; } static getDerivedStateFromProps = (props: Props, state: State) => { if (state.path !== props.path) { return { ...state, location: props.location, path: props.path, viewMode: props.viewMode, storyId: props.storyId, }; } return null; }; componentDidMount() { // Now every module has had a chance to set its API, call init on each module which gives it // a chance to do things that call other modules' APIs. this.modules.forEach(({ init }) => { if (init) { init({ api: this.api }); } }); } shouldComponentUpdate(nextProps: Props, nextState: State) { const prevState = this.state; const prevProps = this.props; if (prevState !== nextState) { return true; } if (prevProps.path !== nextProps.path) { return true; } return false; } render() { const { children } = this.props; const value = { state: this.state, api: this.api, }; return ( <ManagerContext.Provider value={value}> {typeof children === 'function' ? children(value) : children} </ManagerContext.Provider> ); } } interface ConsumerProps<S, C> { filter?: (combo: C) => S; pure?: boolean; children: (d: S | C) => ReactElement<any> | null; } interface SubState { [key: string]: any; } class ManagerConsumer extends Component<ConsumerProps<SubState, Combo>> { dataMemory?: (combo: Combo) => SubState; prevChildren?: ReactElement<any> | null; prevData?: SubState; constructor(props: ConsumerProps<SubState, Combo>) { super(props); this.dataMemory = props.filter ? memoize(10)(props.filter) : null; } render() { const { children, pure } = this.props; return ( <ManagerContext.Consumer> {d => { const data = this.dataMemory ? this.dataMemory(d) : d; if ( pure && this.prevChildren && this.prevData && shallowEqualObjects(data, this.prevData) ) { return this.prevChildren; } this.prevChildren = children(data); this.prevData = data; return this.prevChildren; }} </ManagerContext.Consumer> ); } } export function useStorybookState(): State { const { state } = useContext(ManagerContext); return state; } export function useStorybookApi(): API { const { api } = useContext(ManagerContext); return api; } export { ManagerConsumer as Consumer, ManagerProvider as Provider }; export interface EventMap { [eventId: string]: Listener; } function getAddonStateOrDefault<S>(api: API, addonId: string, defaultState: S): S { const fromStore = api.getAddonState(addonId); if (typeof fromStore === 'undefined') { api.setAddonState<S>(addonId, defaultState); return defaultState; } return fromStore as S; } type StateMerger<S> = (input: S) => S; export function useAddonState<S>(addonId: string, defaultState?: S) { const api = useStorybookApi(); const setState = (newStateOrMerger: S | StateMerger<S>, options?: Options) => api.setAddonState<S>(addonId, newStateOrMerger, options); const state = getAddonStateOrDefault<S>(api, addonId, defaultState); return { 0: state, 1: setState }; } export const useChannel = (eventMap: EventMap) => { const api = useStorybookApi(); useEffect(() => { Object.entries(eventMap).forEach(([type, listener]) => api.on(type, listener)); return () => { Object.entries(eventMap).forEach(([type, listener]) => api.off(type, listener)); }; }); return api.emit; };
lib/api/src/index.tsx
1
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.9978377223014832, 0.0879347026348114, 0.0001672896178206429, 0.00017825938994064927, 0.2710801959037781 ]
{ "id": 3, "code_window": [ " return defaultState;\n", " }\n", " return fromStore as S;\n", "}\n", "\n", "type StateMerger<S> = (input: S) => S;\n", "\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return fromStore;\n" ], "file_path": "lib/api/src/index.tsx", "type": "replace", "edit_start_line_idx": 291 }
import { start } from '@storybook/core/client'; import './globals'; import render from './render'; const { clientApi, configApi, forceReRender } = start(render); export const { storiesOf, setAddon, addDecorator, addParameters, clearDecorators, getStorybook, raw, } = clientApi; export const { configure } = configApi; export { forceReRender };
app/react/src/client/preview/index.js
0
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.0001719826686894521, 0.00017059920355677605, 0.00016921572387218475, 0.00017059920355677605, 0.0000013834724086336792 ]
{ "id": 3, "code_window": [ " return defaultState;\n", " }\n", " return fromStore as S;\n", "}\n", "\n", "type StateMerger<S> = (input: S) => S;\n", "\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return fromStore;\n" ], "file_path": "lib/api/src/index.tsx", "type": "replace", "edit_start_line_idx": 291 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`PropTable/Thead renders a thead html node with children 1`] = ` <thead> <div> foo bar </div> </thead> `; exports[`PropTable/Thead renders a thead html node with multiple children elements 1`] = ` <thead> <div> foo bar </div> <div> baz </div> </thead> `;
addons/info/src/components/PropTable/components/__snapshots__/Thead.test.js.snap
0
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.00018009787891060114, 0.0001764348562574014, 0.00017220368317794055, 0.00017700300668366253, 0.0000032477353215654148 ]
{ "id": 3, "code_window": [ " return defaultState;\n", " }\n", " return fromStore as S;\n", "}\n", "\n", "type StateMerger<S> = (input: S) => S;\n", "\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return fromStore;\n" ], "file_path": "lib/api/src/index.tsx", "type": "replace", "edit_start_line_idx": 291 }
// Storybook's implementation of SimpleBar https://github.com/Grsmto/simplebar // Note: "SimpleBar can't be used on the <body>, <textarea> or <iframe> elements." import React, { Fragment, FunctionComponent } from 'react'; import { styled, Global } from '@storybook/theming'; import SimpleBar from 'simplebar-react'; import { getScrollAreaStyles } from './ScrollAreaStyles'; export interface ScrollProps { horizontal?: boolean; vertical?: boolean; [key: string]: any; } const Scroll = styled(({ vertical, horizontal, ...rest }: ScrollProps) => <SimpleBar {...rest} />)( ({ vertical }) => !vertical ? { overflowY: 'hidden', } : { overflowY: 'auto', }, ({ horizontal }) => !horizontal ? { overflowX: 'hidden', } : { overflowX: 'auto', } ); export interface ScrollAreaProps { horizontal?: boolean; vertical?: boolean; className?: string; } export const ScrollArea: FunctionComponent<ScrollAreaProps> = ({ children, vertical, horizontal, ...props }) => ( <Fragment> <Global styles={getScrollAreaStyles} /> <Scroll vertical={vertical} horizontal={horizontal} {...props}> {children} </Scroll> </Fragment> ); ScrollArea.defaultProps = { horizontal: false, vertical: false, };
lib/components/src/ScrollArea/ScrollArea.tsx
0
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.00018090747471433133, 0.00017408409621566534, 0.00016787876666057855, 0.00017325827502645552, 0.000003896313501172699 ]
{ "id": 4, "code_window": [ "export function useAddonState<S>(addonId: string, defaultState?: S) {\n", " const api = useStorybookApi();\n", "\n", " const setState = (newStateOrMerger: S | StateMerger<S>, options?: Options) =>\n", " api.setAddonState<S>(addonId, newStateOrMerger, options);\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ " const existingState = api.getAddonState<S>(addonId);\n", " const state = stateOrDefault<S>(existingState, defaultState);\n", "\n", " const setState = (newStateOrMerger: S | StateMerger<S>, options?: Options) => {\n", " return api.setAddonState<S>(addonId, newStateOrMerger, options);\n", " };\n" ], "file_path": "lib/api/src/index.tsx", "type": "replace", "edit_start_line_idx": 299 }
/* eslint-disable react/no-multi-comp */ import React, { ReactElement, Component, useContext, useEffect } from 'react'; import memoize from 'memoizerific'; // @ts-ignore shallow-equal is not in DefinitelyTyped import shallowEqualObjects from 'shallow-equal/objects'; import Events from '@storybook/core-events'; import { RenderData as RouterData } from '@storybook/router'; import { Listener } from '@storybook/channels'; import initProviderApi, { SubAPI as ProviderAPI, Provider } from './init-provider-api'; import { createContext } from './context'; import Store, { Options } from './store'; import getInitialState from './initial-state'; import initAddons, { SubAPI as AddonsAPI } from './modules/addons'; import initChannel, { SubAPI as ChannelAPI } from './modules/channel'; import initNotifications, { SubState as NotificationState, SubAPI as NotificationAPI, } from './modules/notifications'; import initStories, { SubState as StoriesSubState, SubAPI as StoriesAPI, StoriesRaw, } from './modules/stories'; import initLayout, { SubState as LayoutSubState, SubAPI as LayoutAPI } from './modules/layout'; import initShortcuts, { SubState as ShortcutsSubState, SubAPI as ShortcutsAPI, } from './modules/shortcuts'; import initURL, { QueryParams, SubAPI as UrlAPI } from './modules/url'; import initVersions, { SubState as VersionsSubState, SubAPI as VersionsAPI, } from './modules/versions'; export { Options as StoreOptions, Listener as ChannelListener }; const ManagerContext = createContext({ api: undefined, state: getInitialState({}) }); const { STORY_CHANGED, SET_STORIES, SELECT_STORY } = Events; export type Module = StoreData & RouterData & ProviderData & { mode?: 'production' | 'development' }; export type State = Other & LayoutSubState & StoriesSubState & NotificationState & VersionsSubState & RouterData & ShortcutsSubState; export type API = AddonsAPI & ChannelAPI & ProviderAPI & StoriesAPI & LayoutAPI & NotificationAPI & ShortcutsAPI & VersionsAPI & UrlAPI & OtherAPI; interface OtherAPI { [key: string]: any; } interface Other { customQueryParams: QueryParams; [key: string]: any; } export interface Combo { api: API; state: State; } interface ProviderData { provider: Provider; } interface StoreData { store: Store; } interface Children { children: Component | ((props: Combo) => Component); } type StatePartial = Partial<State>; export type Props = Children & RouterData & ProviderData; class ManagerProvider extends Component<Props, State> { static displayName = 'Manager'; api: API; modules: any[]; constructor(props: Props) { super(props); const { provider, location, path, viewMode, storyId, navigate } = props; const store = new Store({ getState: () => this.state, setState: (stateChange: StatePartial, callback) => this.setState(stateChange, callback), }); // Initialize the state to be the initial (persisted) state of the store. // This gives the modules the chance to read the persisted state, apply their defaults // and override if necessary this.state = store.getInitialState(getInitialState({})); const apiData = { navigate, store, provider, location, path, viewMode, storyId, }; this.modules = [ initChannel, initAddons, initLayout, initNotifications, initShortcuts, initStories, initURL, initVersions, ].map(initModule => initModule(apiData)); // Create our initial state by combining the initial state of all modules, then overlaying any saved state const state = getInitialState(...this.modules.map(m => m.state)); // Get our API by combining the APIs exported by each module const combo = Object.assign({ navigate }, ...this.modules.map(m => m.api)); const api = initProviderApi({ provider, store, api: combo }); api.on(STORY_CHANGED, (id: string) => { const options = api.getParameters(id, 'options'); if (options) { api.setOptions(options); } }); api.on(SET_STORIES, (data: { stories: StoriesRaw }) => { api.setStories(data.stories); const options = storyId ? api.getParameters(storyId, 'options') : api.getParameters(Object.keys(data.stories)[0], 'options'); api.setOptions(options); }); api.on( SELECT_STORY, ({ kind, story, ...rest }: { kind: string; story: string; [k: string]: any }) => { api.selectStory(kind, story, rest); } ); this.state = state; this.api = api; } static getDerivedStateFromProps = (props: Props, state: State) => { if (state.path !== props.path) { return { ...state, location: props.location, path: props.path, viewMode: props.viewMode, storyId: props.storyId, }; } return null; }; componentDidMount() { // Now every module has had a chance to set its API, call init on each module which gives it // a chance to do things that call other modules' APIs. this.modules.forEach(({ init }) => { if (init) { init({ api: this.api }); } }); } shouldComponentUpdate(nextProps: Props, nextState: State) { const prevState = this.state; const prevProps = this.props; if (prevState !== nextState) { return true; } if (prevProps.path !== nextProps.path) { return true; } return false; } render() { const { children } = this.props; const value = { state: this.state, api: this.api, }; return ( <ManagerContext.Provider value={value}> {typeof children === 'function' ? children(value) : children} </ManagerContext.Provider> ); } } interface ConsumerProps<S, C> { filter?: (combo: C) => S; pure?: boolean; children: (d: S | C) => ReactElement<any> | null; } interface SubState { [key: string]: any; } class ManagerConsumer extends Component<ConsumerProps<SubState, Combo>> { dataMemory?: (combo: Combo) => SubState; prevChildren?: ReactElement<any> | null; prevData?: SubState; constructor(props: ConsumerProps<SubState, Combo>) { super(props); this.dataMemory = props.filter ? memoize(10)(props.filter) : null; } render() { const { children, pure } = this.props; return ( <ManagerContext.Consumer> {d => { const data = this.dataMemory ? this.dataMemory(d) : d; if ( pure && this.prevChildren && this.prevData && shallowEqualObjects(data, this.prevData) ) { return this.prevChildren; } this.prevChildren = children(data); this.prevData = data; return this.prevChildren; }} </ManagerContext.Consumer> ); } } export function useStorybookState(): State { const { state } = useContext(ManagerContext); return state; } export function useStorybookApi(): API { const { api } = useContext(ManagerContext); return api; } export { ManagerConsumer as Consumer, ManagerProvider as Provider }; export interface EventMap { [eventId: string]: Listener; } function getAddonStateOrDefault<S>(api: API, addonId: string, defaultState: S): S { const fromStore = api.getAddonState(addonId); if (typeof fromStore === 'undefined') { api.setAddonState<S>(addonId, defaultState); return defaultState; } return fromStore as S; } type StateMerger<S> = (input: S) => S; export function useAddonState<S>(addonId: string, defaultState?: S) { const api = useStorybookApi(); const setState = (newStateOrMerger: S | StateMerger<S>, options?: Options) => api.setAddonState<S>(addonId, newStateOrMerger, options); const state = getAddonStateOrDefault<S>(api, addonId, defaultState); return { 0: state, 1: setState }; } export const useChannel = (eventMap: EventMap) => { const api = useStorybookApi(); useEffect(() => { Object.entries(eventMap).forEach(([type, listener]) => api.on(type, listener)); return () => { Object.entries(eventMap).forEach(([type, listener]) => api.off(type, listener)); }; }); return api.emit; };
lib/api/src/index.tsx
1
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.9989284873008728, 0.21204721927642822, 0.0001647275494178757, 0.00018511919188313186, 0.3995496928691864 ]
{ "id": 4, "code_window": [ "export function useAddonState<S>(addonId: string, defaultState?: S) {\n", " const api = useStorybookApi();\n", "\n", " const setState = (newStateOrMerger: S | StateMerger<S>, options?: Options) =>\n", " api.setAddonState<S>(addonId, newStateOrMerger, options);\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ " const existingState = api.getAddonState<S>(addonId);\n", " const state = stateOrDefault<S>(existingState, defaultState);\n", "\n", " const setState = (newStateOrMerger: S | StateMerger<S>, options?: Options) => {\n", " return api.setAddonState<S>(addonId, newStateOrMerger, options);\n", " };\n" ], "file_path": "lib/api/src/index.tsx", "type": "replace", "edit_start_line_idx": 299 }
class BaseTestPlugin1 {} class BaseTestPlugin2 {} export default { devtool: 'cheap-eval-source-map', resolve: { extensions: ['.js', '.jsx'], alias: { baseAlias: 'base-alias', }, modules: [], }, module: { noParse: /jquery/, rules: [ { test: /\.js$/, include: 'app/baseSrc', loader: 'babel-loader', options: {}, }, ], }, plugins: [new BaseTestPlugin1(), new BaseTestPlugin2()], };
app/react/src/server/__mocks__/mockConfig.js
0
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.0001768796646501869, 0.00017414195463061333, 0.00016936827159952372, 0.0001761779421940446, 0.000003387641754670767 ]
{ "id": 4, "code_window": [ "export function useAddonState<S>(addonId: string, defaultState?: S) {\n", " const api = useStorybookApi();\n", "\n", " const setState = (newStateOrMerger: S | StateMerger<S>, options?: Options) =>\n", " api.setAddonState<S>(addonId, newStateOrMerger, options);\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ " const existingState = api.getAddonState<S>(addonId);\n", " const state = stateOrDefault<S>(existingState, defaultState);\n", "\n", " const setState = (newStateOrMerger: S | StateMerger<S>, options?: Options) => {\n", " return api.setAddonState<S>(addonId, newStateOrMerger, options);\n", " };\n" ], "file_path": "lib/api/src/index.tsx", "type": "replace", "edit_start_line_idx": 299 }
<svg width="256" height="178" viewBox="0 0 256 178" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid"><g fill="none"><path d="M153.6 177.98L51.194.605H102.4L204.807 177.98H153.6z" fill="#FF4081"/><path d="M153.6 177.98l25.6-44.344 25.607 44.344H153.6z" fill-opacity=".2" fill="#FFF"/><path d="M128 133.636l25.6 44.344 25.6-44.344H128z" fill-opacity=".1" fill="#FFF"/><path d="M102.4 89.292l25.6 44.344 25.6-44.344h-51.2z" fill-opacity=".1" fill="#000"/><path d="M102.4 89.292L128 44.948l25.6 44.344h-51.2z" fill-opacity=".2" fill="#000"/><path d="M76.8 44.948l25.6 44.344 25.601-44.344h-51.2z" fill-opacity=".3" fill="#000"/><path d="M76.8 44.948L102.4.605l25.601 44.343h-51.2z" fill-opacity=".4" fill="#000"/><path d="M51.194.605L76.8 44.948 102.4.605H51.195z" fill-opacity=".5" fill="#000"/><path d="M51.194 177.98L-.013 89.292l25.606-44.344L102.4 177.98H51.193z" fill="#536DFE"/><path d="M51.194 177.98L76.8 133.636l25.6 44.344H51.195z" fill-opacity=".2" fill="#FFF"/><path d="M25.593 133.636l25.6 44.344L76.8 133.636H25.593z" fill-opacity=".1" fill="#FFF"/><path d="M25.593 133.636l25.6-44.344L76.8 133.636H25.593z"/><path d="M-.013 89.292l25.606 44.344 25.6-44.344H-.012z" fill-opacity=".1" fill="#000"/><path d="M-.013 89.292l25.606-44.344 25.6 44.344H-.012z" fill-opacity=".2" fill="#000"/><path d="M51.194 89.292l-25.6-44.344L51.193.605 76.8 44.948 51.194 89.292z" fill="#303F9F"/><path d="M76.8 44.948L51.194.605l-25.6 44.343H76.8z" fill-opacity=".2" fill="#000"/><path d="M204.806 177.98L179.2 133.636l25.606-44.344 25.6 44.344-25.6 44.344z" fill="#3F51B5"/><path d="M230.407 133.636l-25.6 44.344-25.607-44.344h51.207z" fill-opacity=".2" fill="#000"/><path d="M230.407 133.636L153.6.605h51.207l51.207 88.687-25.606 44.344h-.001z" fill="#7986CB"/><path d="M204.806 89.292l25.6 44.344 25.607-44.344h-51.207z" fill-opacity=".2" fill="#FFF"/><path d="M204.806 89.292l25.6-44.344 25.607 44.344h-51.207z" fill-opacity=".1" fill="#FFF"/><path d="M179.2 44.948L204.806.605l25.6 44.343H179.2z" fill-opacity=".1" fill="#000"/><path d="M153.6.605l25.6 44.343L204.808.605H153.6z" fill-opacity=".2" fill="#000"/></g></svg>
examples/polymer-cli/src/logo.svg
0
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.00021037495753262192, 0.00021037495753262192, 0.00021037495753262192, 0.00021037495753262192, 0 ]
{ "id": 4, "code_window": [ "export function useAddonState<S>(addonId: string, defaultState?: S) {\n", " const api = useStorybookApi();\n", "\n", " const setState = (newStateOrMerger: S | StateMerger<S>, options?: Options) =>\n", " api.setAddonState<S>(addonId, newStateOrMerger, options);\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ " const existingState = api.getAddonState<S>(addonId);\n", " const state = stateOrDefault<S>(existingState, defaultState);\n", "\n", " const setState = (newStateOrMerger: S | StateMerger<S>, options?: Options) => {\n", " return api.setAddonState<S>(addonId, newStateOrMerger, options);\n", " };\n" ], "file_path": "lib/api/src/index.tsx", "type": "replace", "edit_start_line_idx": 299 }
import PropTypes from 'prop-types'; import React from 'react'; import { TextInput } from 'react-native'; function formatArray(value, separator) { if (value === '') { return []; } return value.split(separator); } const ArrayType = ({ knob, onChange }) => ( <TextInput id={knob.name} underlineColorAndroid="transparent" style={{ borderWidth: 1, borderColor: '#f7f4f4', borderRadius: 2, fontSize: 13, padding: 5, margin: 10, color: '#555', }} value={knob.value.join(knob.separator)} onChangeText={e => onChange(formatArray(e, knob.separator))} /> ); ArrayType.defaultProps = { knob: {}, onChange: value => value, }; ArrayType.propTypes = { knob: PropTypes.shape({ name: PropTypes.string, value: PropTypes.array, }), onChange: PropTypes.func, }; ArrayType.serialize = value => value; ArrayType.deserialize = value => { if (Array.isArray(value)) return value; return Object.keys(value) .sort() .reduce((array, key) => [...array, value[key]], []); }; export default ArrayType;
addons/ondevice-knobs/src/types/Array.js
0
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.00018019012350123376, 0.00017561831919010729, 0.0001715242542559281, 0.00017627424676902592, 0.0000028255544748390093 ]
{ "id": 5, "code_window": [ "\n", " const state = getAddonStateOrDefault<S>(api, addonId, defaultState);\n", "\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " if (typeof existingState === 'undefined') {\n", " api.setAddonState<S>(addonId, state);\n", " }\n" ], "file_path": "lib/api/src/index.tsx", "type": "replace", "edit_start_line_idx": 302 }
import React, { Fragment, useMemo } from 'react'; import { useAddonState, useChannel } from '@storybook/api'; import { ADDON_ID, EVENTS } from './constants'; type Results = string[]; interface Props { active: boolean; } export const Panel = ({ active }: Props) => { const { 0: results, 1: setState } = useAddonState<Results>(ADDON_ID, []); const emit = useChannel({ [EVENTS.RESULT]: newResults => setState(newResults), }); const output = useMemo( () => ( <div hidden={!active}> {results.length ? ( <ol> {results.map((i: string) => ( <li key={i.toString()}>{i}</li> ))} </ol> ) : null} <button type="button" onClick={() => emit(EVENTS.REQUEST)}> emit </button> <button type="button" onClick={() => setState([])}> setState </button> <button type="button" onClick={() => setState([], { persistence: 'session' })}> setState with options </button> <button type="button" onClick={() => setState(s => [...s, 'foo'])}> setState with function </button> </div> ), [active, results] ); return <Fragment>{output}</Fragment>; };
dev-kits/addon-roundtrip/src/panel.tsx
1
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.5212708711624146, 0.10440210998058319, 0.00016811922250781208, 0.0001766583591233939, 0.20843437314033508 ]
{ "id": 5, "code_window": [ "\n", " const state = getAddonStateOrDefault<S>(api, addonId, defaultState);\n", "\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " if (typeof existingState === 'undefined') {\n", " api.setAddonState<S>(addonId, state);\n", " }\n" ], "file_path": "lib/api/src/index.tsx", "type": "replace", "edit_start_line_idx": 302 }
import '@storybook/addon-actions/register'; import '@storybook/addon-links/register';
lib/cli/generators/REACT_NATIVE/template/storybook/addons.js
0
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.00017645077605266124, 0.00017645077605266124, 0.00017645077605266124, 0.00017645077605266124, 0 ]
{ "id": 5, "code_window": [ "\n", " const state = getAddonStateOrDefault<S>(api, addonId, defaultState);\n", "\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " if (typeof existingState === 'undefined') {\n", " api.setAddonState<S>(addonId, state);\n", " }\n" ], "file_path": "lib/api/src/index.tsx", "type": "replace", "edit_start_line_idx": 302 }
# http://www.robotstxt.org User-agent: * Disallow:
lib/cli/test/fixtures/ember-cli/public/robots.txt
0
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.00017321581253781915, 0.00017321581253781915, 0.00017321581253781915, 0.00017321581253781915, 0 ]
{ "id": 5, "code_window": [ "\n", " const state = getAddonStateOrDefault<S>(api, addonId, defaultState);\n", "\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " if (typeof existingState === 'undefined') {\n", " api.setAddonState<S>(addonId, state);\n", " }\n" ], "file_path": "lib/api/src/index.tsx", "type": "replace", "edit_start_line_idx": 302 }
import React from 'react'; import memoize from 'memoizerific'; import { Consumer } from '@storybook/api'; import AddonPanel from '../components/panel/panel'; const createPanelActions = memoize(1)(api => ({ onSelect: panel => api.setSelectedPanel(panel), toggleVisibility: () => api.togglePanel(), togglePosition: () => api.togglePanelPosition(), })); const mapper = ({ state, api }) => ({ panels: api.getPanels(), selectedPanel: api.getSelectedPanel(), panelPosition: state.layout.panelPosition, actions: createPanelActions(api), }); export default props => ( <Consumer filter={mapper}>{customProps => <AddonPanel {...props} {...customProps} />}</Consumer> );
lib/ui/src/containers/panel.js
0
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.9896425604820251, 0.32999226450920105, 0.000166775964316912, 0.00016748129564803094, 0.46644318103790283 ]
{ "id": 6, "code_window": [ "\n", " return { 0: state, 1: setState };\n", "}\n", "\n", "export const useChannel = (eventMap: EventMap) => {\n", " const api = useStorybookApi();\n", " useEffect(() => {\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return [state, setState] as [\n", " S,\n", " (newStateOrMerger: S | StateMerger<S>, options?: Options) => Promise<S>\n", " ];\n" ], "file_path": "lib/api/src/index.tsx", "type": "replace", "edit_start_line_idx": 304 }
/* eslint-disable react/no-multi-comp */ import React, { ReactElement, Component, useContext, useEffect } from 'react'; import memoize from 'memoizerific'; // @ts-ignore shallow-equal is not in DefinitelyTyped import shallowEqualObjects from 'shallow-equal/objects'; import Events from '@storybook/core-events'; import { RenderData as RouterData } from '@storybook/router'; import { Listener } from '@storybook/channels'; import initProviderApi, { SubAPI as ProviderAPI, Provider } from './init-provider-api'; import { createContext } from './context'; import Store, { Options } from './store'; import getInitialState from './initial-state'; import initAddons, { SubAPI as AddonsAPI } from './modules/addons'; import initChannel, { SubAPI as ChannelAPI } from './modules/channel'; import initNotifications, { SubState as NotificationState, SubAPI as NotificationAPI, } from './modules/notifications'; import initStories, { SubState as StoriesSubState, SubAPI as StoriesAPI, StoriesRaw, } from './modules/stories'; import initLayout, { SubState as LayoutSubState, SubAPI as LayoutAPI } from './modules/layout'; import initShortcuts, { SubState as ShortcutsSubState, SubAPI as ShortcutsAPI, } from './modules/shortcuts'; import initURL, { QueryParams, SubAPI as UrlAPI } from './modules/url'; import initVersions, { SubState as VersionsSubState, SubAPI as VersionsAPI, } from './modules/versions'; export { Options as StoreOptions, Listener as ChannelListener }; const ManagerContext = createContext({ api: undefined, state: getInitialState({}) }); const { STORY_CHANGED, SET_STORIES, SELECT_STORY } = Events; export type Module = StoreData & RouterData & ProviderData & { mode?: 'production' | 'development' }; export type State = Other & LayoutSubState & StoriesSubState & NotificationState & VersionsSubState & RouterData & ShortcutsSubState; export type API = AddonsAPI & ChannelAPI & ProviderAPI & StoriesAPI & LayoutAPI & NotificationAPI & ShortcutsAPI & VersionsAPI & UrlAPI & OtherAPI; interface OtherAPI { [key: string]: any; } interface Other { customQueryParams: QueryParams; [key: string]: any; } export interface Combo { api: API; state: State; } interface ProviderData { provider: Provider; } interface StoreData { store: Store; } interface Children { children: Component | ((props: Combo) => Component); } type StatePartial = Partial<State>; export type Props = Children & RouterData & ProviderData; class ManagerProvider extends Component<Props, State> { static displayName = 'Manager'; api: API; modules: any[]; constructor(props: Props) { super(props); const { provider, location, path, viewMode, storyId, navigate } = props; const store = new Store({ getState: () => this.state, setState: (stateChange: StatePartial, callback) => this.setState(stateChange, callback), }); // Initialize the state to be the initial (persisted) state of the store. // This gives the modules the chance to read the persisted state, apply their defaults // and override if necessary this.state = store.getInitialState(getInitialState({})); const apiData = { navigate, store, provider, location, path, viewMode, storyId, }; this.modules = [ initChannel, initAddons, initLayout, initNotifications, initShortcuts, initStories, initURL, initVersions, ].map(initModule => initModule(apiData)); // Create our initial state by combining the initial state of all modules, then overlaying any saved state const state = getInitialState(...this.modules.map(m => m.state)); // Get our API by combining the APIs exported by each module const combo = Object.assign({ navigate }, ...this.modules.map(m => m.api)); const api = initProviderApi({ provider, store, api: combo }); api.on(STORY_CHANGED, (id: string) => { const options = api.getParameters(id, 'options'); if (options) { api.setOptions(options); } }); api.on(SET_STORIES, (data: { stories: StoriesRaw }) => { api.setStories(data.stories); const options = storyId ? api.getParameters(storyId, 'options') : api.getParameters(Object.keys(data.stories)[0], 'options'); api.setOptions(options); }); api.on( SELECT_STORY, ({ kind, story, ...rest }: { kind: string; story: string; [k: string]: any }) => { api.selectStory(kind, story, rest); } ); this.state = state; this.api = api; } static getDerivedStateFromProps = (props: Props, state: State) => { if (state.path !== props.path) { return { ...state, location: props.location, path: props.path, viewMode: props.viewMode, storyId: props.storyId, }; } return null; }; componentDidMount() { // Now every module has had a chance to set its API, call init on each module which gives it // a chance to do things that call other modules' APIs. this.modules.forEach(({ init }) => { if (init) { init({ api: this.api }); } }); } shouldComponentUpdate(nextProps: Props, nextState: State) { const prevState = this.state; const prevProps = this.props; if (prevState !== nextState) { return true; } if (prevProps.path !== nextProps.path) { return true; } return false; } render() { const { children } = this.props; const value = { state: this.state, api: this.api, }; return ( <ManagerContext.Provider value={value}> {typeof children === 'function' ? children(value) : children} </ManagerContext.Provider> ); } } interface ConsumerProps<S, C> { filter?: (combo: C) => S; pure?: boolean; children: (d: S | C) => ReactElement<any> | null; } interface SubState { [key: string]: any; } class ManagerConsumer extends Component<ConsumerProps<SubState, Combo>> { dataMemory?: (combo: Combo) => SubState; prevChildren?: ReactElement<any> | null; prevData?: SubState; constructor(props: ConsumerProps<SubState, Combo>) { super(props); this.dataMemory = props.filter ? memoize(10)(props.filter) : null; } render() { const { children, pure } = this.props; return ( <ManagerContext.Consumer> {d => { const data = this.dataMemory ? this.dataMemory(d) : d; if ( pure && this.prevChildren && this.prevData && shallowEqualObjects(data, this.prevData) ) { return this.prevChildren; } this.prevChildren = children(data); this.prevData = data; return this.prevChildren; }} </ManagerContext.Consumer> ); } } export function useStorybookState(): State { const { state } = useContext(ManagerContext); return state; } export function useStorybookApi(): API { const { api } = useContext(ManagerContext); return api; } export { ManagerConsumer as Consumer, ManagerProvider as Provider }; export interface EventMap { [eventId: string]: Listener; } function getAddonStateOrDefault<S>(api: API, addonId: string, defaultState: S): S { const fromStore = api.getAddonState(addonId); if (typeof fromStore === 'undefined') { api.setAddonState<S>(addonId, defaultState); return defaultState; } return fromStore as S; } type StateMerger<S> = (input: S) => S; export function useAddonState<S>(addonId: string, defaultState?: S) { const api = useStorybookApi(); const setState = (newStateOrMerger: S | StateMerger<S>, options?: Options) => api.setAddonState<S>(addonId, newStateOrMerger, options); const state = getAddonStateOrDefault<S>(api, addonId, defaultState); return { 0: state, 1: setState }; } export const useChannel = (eventMap: EventMap) => { const api = useStorybookApi(); useEffect(() => { Object.entries(eventMap).forEach(([type, listener]) => api.on(type, listener)); return () => { Object.entries(eventMap).forEach(([type, listener]) => api.off(type, listener)); }; }); return api.emit; };
lib/api/src/index.tsx
1
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.9980151653289795, 0.12276005744934082, 0.00016554980538785458, 0.0004410685505717993, 0.32202082872390747 ]
{ "id": 6, "code_window": [ "\n", " return { 0: state, 1: setState };\n", "}\n", "\n", "export const useChannel = (eventMap: EventMap) => {\n", " const api = useStorybookApi();\n", " useEffect(() => {\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return [state, setState] as [\n", " S,\n", " (newStateOrMerger: S | StateMerger<S>, options?: Options) => Promise<S>\n", " ];\n" ], "file_path": "lib/api/src/index.tsx", "type": "replace", "edit_start_line_idx": 304 }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>EmberFixture Tests</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> {{content-for "head"}} {{content-for "test-head"}} <link rel="stylesheet" href="{{rootURL}}assets/vendor.css"> <link rel="stylesheet" href="{{rootURL}}assets/ember-fixture.css"> <link rel="stylesheet" href="{{rootURL}}assets/test-support.css"> {{content-for "head-footer"}} {{content-for "test-head-footer"}} </head> <body> {{content-for "body"}} {{content-for "test-body"}} <script src="/testem.js" integrity=""></script> <script src="{{rootURL}}assets/vendor.js"></script> <script src="{{rootURL}}assets/test-support.js"></script> <script src="{{rootURL}}assets/ember-fixture.js"></script> <script src="{{rootURL}}assets/tests.js"></script> {{content-for "body-footer"}} {{content-for "test-body-footer"}} </body> </html>
lib/cli/test/fixtures/ember-cli/tests/index.html
0
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.00017515804211143404, 0.00017212146485690027, 0.0001689117052592337, 0.00017220806330442429, 0.0000022103895389591344 ]
{ "id": 6, "code_window": [ "\n", " return { 0: state, 1: setState };\n", "}\n", "\n", "export const useChannel = (eventMap: EventMap) => {\n", " const api = useStorybookApi();\n", " useEffect(() => {\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return [state, setState] as [\n", " S,\n", " (newStateOrMerger: S | StateMerger<S>, options?: Options) => Promise<S>\n", " ];\n" ], "file_path": "lib/api/src/index.tsx", "type": "replace", "edit_start_line_idx": 304 }
import React from 'react'; import { storiesOf } from '@storybook/react'; const data = { user: { name: 'Joe', }, }; storiesOf('My Component', module) .add('state', () => <span>Hello {data.user?.name}</span>)
lib/cli/test/fixtures/react_babel_config_js/stories/index.stories.js
0
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.000176705201738514, 0.00017195864347741008, 0.00016721209976822138, 0.00017195864347741008, 0.000004746550985146314 ]
{ "id": 6, "code_window": [ "\n", " return { 0: state, 1: setState };\n", "}\n", "\n", "export const useChannel = (eventMap: EventMap) => {\n", " const api = useStorybookApi();\n", " useEffect(() => {\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return [state, setState] as [\n", " S,\n", " (newStateOrMerger: S | StateMerger<S>, options?: Options) => Promise<S>\n", " ];\n" ], "file_path": "lib/api/src/index.tsx", "type": "replace", "edit_start_line_idx": 304 }
import '@storybook/addon-actions/register'; import '@storybook/addon-links/register';
lib/cli/generators/SVELTE/template/.storybook/addons.js
0
https://github.com/storybookjs/storybook/commit/89273a8e1e840d8a0da88a975750eca7c6e8b831
[ 0.00017409339488949627, 0.00017409339488949627, 0.00017409339488949627, 0.00017409339488949627, 0 ]
{ "id": 0, "code_window": [ "\n", "export class MarkdownString implements IMarkdownString {\n", "\n", "\tstatic isEmpty(oneOrMany: IMarkdownString | IMarkdownString[]): boolean {\n", "\t\tif (MarkdownString.isMarkdownString(oneOrMany)) {\n", "\t\t\treturn Boolean(oneOrMany.value);\n", "\t\t} else if (Array.isArray(oneOrMany)) {\n", "\t\t\treturn oneOrMany.every(MarkdownString.isEmpty);\n", "\t\t} else {\n", "\t\t\treturn false;\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\treturn !oneOrMany.value;\n" ], "file_path": "src/vs/base/common/htmlContent.ts", "type": "replace", "edit_start_line_idx": 19 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { equals } from 'vs/base/common/arrays'; import { marked } from 'vs/base/common/marked/marked'; export interface IMarkdownString { value: string; trusted?: true; } export class MarkdownString implements IMarkdownString { static isEmpty(oneOrMany: IMarkdownString | IMarkdownString[]): boolean { if (MarkdownString.isMarkdownString(oneOrMany)) { return Boolean(oneOrMany.value); } else if (Array.isArray(oneOrMany)) { return oneOrMany.every(MarkdownString.isEmpty); } else { return false; } } static isMarkdownString(thing: any): thing is IMarkdownString { if (thing instanceof MarkdownString) { return true; } else if (typeof thing === 'object') { return typeof (<IMarkdownString>thing).value === 'string' && (typeof (<IMarkdownString>thing).trusted === 'boolean' || (<IMarkdownString>thing).trusted === void 0); } return false; } value: string; trusted?: true; constructor(value: string = '') { this.value = value; } appendText(value: string): this { // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash this.value += value.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); return this; } appendCodeblock(langId: string, code: string): this { this.value += '```'; this.value += langId; this.value += '\n'; this.value += code; this.value += '```\n'; return this; } } export function markedStringsEquals(a: IMarkdownString | IMarkdownString[], b: IMarkdownString | IMarkdownString[]): boolean { if (!a && !b) { return true; } else if (!a || !b) { return false; } else if (Array.isArray(a) && Array.isArray(b)) { return equals(a, b, markdownStringEqual); } else if (MarkdownString.isMarkdownString(a) && MarkdownString.isMarkdownString(b)) { return markdownStringEqual(a, b); } else { return false; } } function markdownStringEqual(a: IMarkdownString, b: IMarkdownString): boolean { if (a === b) { return true; } else if (!a || !b) { return false; } else { return a.value === b.value && a.trusted === b.trusted; } } export function removeMarkdownEscapes(text: string): string { if (!text) { return text; } return text.replace(/\\([\\`*_{}[\]()#+\-.!])/g, '$1'); } export function containsCommandLink(value: string): boolean { let uses = false; const renderer = new marked.Renderer(); renderer.link = (href, title, text): string => { if (href.match(/^command:/i)) { uses = true; } return 'link'; }; marked(value, { renderer }); return uses; }
src/vs/base/common/htmlContent.ts
1
https://github.com/microsoft/vscode/commit/57da808a984cfc91174aab7bb07389c78fa4998e
[ 0.998289167881012, 0.36770927906036377, 0.0001674734812695533, 0.0006243590032681823, 0.4729113280773163 ]
{ "id": 0, "code_window": [ "\n", "export class MarkdownString implements IMarkdownString {\n", "\n", "\tstatic isEmpty(oneOrMany: IMarkdownString | IMarkdownString[]): boolean {\n", "\t\tif (MarkdownString.isMarkdownString(oneOrMany)) {\n", "\t\t\treturn Boolean(oneOrMany.value);\n", "\t\t} else if (Array.isArray(oneOrMany)) {\n", "\t\t\treturn oneOrMany.every(MarkdownString.isEmpty);\n", "\t\t} else {\n", "\t\t\treturn false;\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\treturn !oneOrMany.value;\n" ], "file_path": "src/vs/base/common/htmlContent.ts", "type": "replace", "edit_start_line_idx": 19 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import URI from 'vs/base/common/uri'; import { TPromise } from 'vs/base/common/winjs.base'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import * as paths from 'vs/base/common/paths'; import { TrieMap } from 'vs/base/common/map'; import Event from 'vs/base/common/event'; export const IWorkspaceContextService = createDecorator<IWorkspaceContextService>('contextService'); export interface IWorkspaceContextService { _serviceBrand: any; /** * Returns if the application was opened with a workspace or not. */ hasWorkspace(): boolean; /** * Returns if the application was opened with a folder. */ hasFolderWorkspace(): boolean; /** * Returns if the application was opened with a workspace that can have one or more folders. */ hasMultiFolderWorkspace(): boolean; /** * Provides access to the workspace object the platform is running with. This may be null if the workbench was opened * without workspace (empty); */ getLegacyWorkspace(): ILegacyWorkspace; /** * Provides access to the workspace object the platform is running with. This may be null if the workbench was opened * without workspace (empty); */ getWorkspace(): IWorkspace; /** * Save the existing workspace in the given location */ saveWorkspace(location: URI): TPromise<void>; /** * An event which fires on workspace name changes. */ onDidChangeWorkspaceName: Event<void>; /** * An event which fires on workspace roots change. */ onDidChangeWorkspaceRoots: Event<void>; /** * Returns the root for the given resource from the workspace. * Can be null if there is no workspace or the resource is not inside the workspace. */ getRoot(resource: URI): URI; /** * Returns if the provided resource is inside the workspace or not. */ isInsideWorkspace(resource: URI): boolean; /** * Given a workspace relative path, returns the resource with the absolute path. */ toResource: (workspaceRelativePath: string) => URI; } export interface ILegacyWorkspace { /** * the full uri of the workspace. this is a file:// URL to the location * of the workspace on disk. */ resource: URI; /** * creation time of the workspace folder if known */ ctime?: number; } export interface IWorkspace { /** * the unique identifier of the workspace. */ readonly id: string; /** * the name of the workspace. */ readonly name: string; /** * Roots in the workspace. */ readonly roots: URI[]; /** * the location of the workspace configuration */ readonly configuration?: URI; } export class LegacyWorkspace implements ILegacyWorkspace { private _name: string; constructor(private _resource: URI, private _ctime?: number) { this._name = paths.basename(this._resource.fsPath) || this._resource.fsPath; } public get resource(): URI { return this._resource; } public get name(): string { return this._name; } public get ctime(): number { return this._ctime; } public toResource(workspaceRelativePath: string, root?: URI): URI { if (typeof workspaceRelativePath === 'string') { return URI.file(paths.join(root ? root.fsPath : this._resource.fsPath, workspaceRelativePath)); } return null; } } export class Workspace implements IWorkspace { private _rootsMap: TrieMap<URI> = new TrieMap<URI>(); constructor( public readonly id: string, private _name: string, private _roots: URI[], private _configuration: URI = null ) { this.updateRootsMap(); } public get roots(): URI[] { return this._roots; } public set roots(roots: URI[]) { this._roots = roots; this.updateRootsMap(); } public get name(): string { return this._name; } public set name(name: string) { this._name = name; } public get configuration(): URI { return this._configuration; } public set configuration(configuration: URI) { this._configuration = configuration; } public getRoot(resource: URI): URI { if (!resource) { return null; } return this._rootsMap.findSubstr(resource.fsPath); } private updateRootsMap(): void { this._rootsMap = new TrieMap<URI>(); for (const root of this.roots) { this._rootsMap.insert(root.fsPath, root); } } public toJSON(): IWorkspace { return { id: this.id, roots: this.roots, name: this.name }; } }
src/vs/platform/workspace/common/workspace.ts
0
https://github.com/microsoft/vscode/commit/57da808a984cfc91174aab7bb07389c78fa4998e
[ 0.00021018287225160748, 0.00017289802781306207, 0.0001656306703807786, 0.000171233230503276, 0.000008992208677227609 ]