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": 2,
"code_window": [
" tab: '',\n",
" runAsync: false,\n",
" ctas: false,\n",
" };\n",
" // Merge table to tables in state\n",
" table = Object.assign({}, table, data, {\n",
" expanded: true,\n",
" isMetadataLoading: false,\n",
" });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const newTable = Object.assign({}, table, data, {\n"
],
"file_path": "superset/assets/javascripts/SqlLab/actions.js",
"type": "replace",
"edit_start_line_idx": 275
} | /* global notify */
import React from 'react';
import PropTypes from 'prop-types';
import { FormControl, FormGroup, Overlay, Popover, Row, Col } from 'react-bootstrap';
import Button from '../../components/Button';
const propTypes = {
defaultLabel: PropTypes.string,
sql: PropTypes.string,
schema: PropTypes.string,
dbId: PropTypes.number,
animation: PropTypes.bool,
onSave: PropTypes.func,
};
const defaultProps = {
defaultLabel: 'Undefined',
animation: true,
onSave: () => {},
};
class SaveQuery extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
description: '',
label: props.defaultLabel,
showSave: false,
};
this.toggleSave = this.toggleSave.bind(this);
this.onSave = this.onSave.bind(this);
this.onCancel = this.onCancel.bind(this);
this.onLabelChange = this.onLabelChange.bind(this);
this.onDescriptionChange = this.onDescriptionChange.bind(this);
}
onSave() {
const query = {
label: this.state.label,
description: this.state.description,
db_id: this.props.dbId,
schema: this.props.schema,
sql: this.props.sql,
};
this.props.onSave(query);
this.setState({ showSave: false });
}
onCancel() {
this.setState({ showSave: false });
}
onLabelChange(e) {
this.setState({ label: e.target.value });
}
onDescriptionChange(e) {
this.setState({ description: e.target.value });
}
toggleSave(e) {
this.setState({ target: e.target, showSave: !this.state.showSave });
}
renderPopover() {
return (
<Popover id="embed-code-popover">
<FormGroup bsSize="small" style={{ width: '350px' }}>
<Row>
<Col md={12}>
<small>
<label className="control-label" htmlFor="embed-height">
Label
</label>
</small>
<FormControl
type="text"
placeholder="Label for your query"
value={this.state.label}
onChange={this.onLabelChange}
/>
</Col>
</Row>
<br />
<Row>
<Col md={12}>
<small>
<label className="control-label" htmlFor="embed-height">Description</label>
</small>
<FormControl
componentClass="textarea"
placeholder="Write a description for your query"
value={this.state.description}
onChange={this.onDescriptionChange}
/>
</Col>
</Row>
<br />
<Row>
<Col md={12}>
<Button
bsStyle="primary"
onClick={this.onSave}
className="m-r-3"
>
Save
</Button>
<Button onClick={this.onCancel} className="cancelQuery">
Cancel
</Button>
</Col>
</Row>
</FormGroup>
</Popover>
);
}
render() {
return (
<span className="SaveQuery">
<Overlay
trigger="click"
target={this.state.target}
show={this.state.showSave}
placement="bottom"
animation={this.props.animation}
>
{this.renderPopover()}
</Overlay>
<Button bsSize="small" className="toggleSave" onClick={this.toggleSave}>
<i className="fa fa-save" /> Save Query
</Button>
</span>
);
}
}
SaveQuery.propTypes = propTypes;
SaveQuery.defaultProps = defaultProps;
export default SaveQuery;
| superset/assets/javascripts/SqlLab/components/SaveQuery.jsx | 0 | https://github.com/apache/superset/commit/5dbfdefae82674d71ab1f1464622d199a6f72f30 | [
0.00018878017726819962,
0.00017244303307961673,
0.0001653783256188035,
0.00017332989955320954,
0.000005884628535568481
] |
{
"id": 2,
"code_window": [
" tab: '',\n",
" runAsync: false,\n",
" ctas: false,\n",
" };\n",
" // Merge table to tables in state\n",
" table = Object.assign({}, table, data, {\n",
" expanded: true,\n",
" isMetadataLoading: false,\n",
" });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const newTable = Object.assign({}, table, data, {\n"
],
"file_path": "superset/assets/javascripts/SqlLab/actions.js",
"type": "replace",
"edit_start_line_idx": 275
} | /* eslint-disable global-require */
const vizMap = {
area: require('./nvd3_vis.js'),
bar: require('./nvd3_vis.js'),
big_number: require('./big_number.js'),
big_number_total: require('./big_number.js'),
box_plot: require('./nvd3_vis.js'),
bubble: require('./nvd3_vis.js'),
bullet: require('./nvd3_vis.js'),
cal_heatmap: require('./cal_heatmap.js'),
compare: require('./nvd3_vis.js'),
directed_force: require('./directed_force.js'),
dist_bar: require('./nvd3_vis.js'),
filter_box: require('./filter_box.jsx'),
heatmap: require('./heatmap.js'),
histogram: require('./histogram.js'),
horizon: require('./horizon.js'),
iframe: require('./iframe.js'),
line: require('./nvd3_vis.js'),
mapbox: require('./mapbox.jsx'),
markup: require('./markup.js'),
para: require('./parallel_coordinates.js'),
pie: require('./nvd3_vis.js'),
pivot_table: require('./pivot_table.js'),
sankey: require('./sankey.js'),
separator: require('./markup.js'),
sunburst: require('./sunburst.js'),
table: require('./table.js'),
treemap: require('./treemap.js'),
word_cloud: require('./word_cloud.js'),
world_map: require('./world_map.js'),
dual_line: require('./nvd3_vis.js'),
};
export default vizMap;
| superset/assets/visualizations/main.js | 0 | https://github.com/apache/superset/commit/5dbfdefae82674d71ab1f1464622d199a6f72f30 | [
0.00017688507796265185,
0.00017431433661840856,
0.00016927317483350635,
0.00017554954683873802,
0.000002961537802548264
] |
{
"id": 3,
"code_window": [
" expanded: true,\n",
" isMetadataLoading: false,\n",
" });\n",
" dispatch(mergeTable(table, dataPreviewQuery));\n",
" // Run query to get preview data for table\n",
" dispatch(runQuery(dataPreviewQuery));\n",
" })\n",
" .fail(() => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" dispatch(mergeTable(newTable, dataPreviewQuery));\n"
],
"file_path": "superset/assets/javascripts/SqlLab/actions.js",
"type": "replace",
"edit_start_line_idx": 279
} | """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
import inspect
import logging
import re
import textwrap
import time
import sqlparse
from sqlalchemy import select
from sqlalchemy.sql import text
from flask_babel import lazy_gettext as _
from superset.utils import SupersetTemplateException
from superset.utils import QueryStatus
from superset import utils
from superset import cache_util
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):
"""Abstract class for database engine specific configurations"""
engine = 'base' # str as defined in sqlalchemy.engine.engine
cursor_execute_kwargs = {}
time_grains = tuple()
time_groupby_inline = False
limit_method = LimitMethod.FETCH_MANY
time_secondary_columns = False
@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 adjust_database_uri(cls, uri, selected_schema):
"""Based on a URI and selected schema, return a new URI
The URI here represents the URI as entered when saving the database,
``selected_schema`` is the schema currently active presumably in
the SQL Lab dropdown. Based on that, for some database engine,
we can return a new altered URI that connects straight to the
active schema, meaning the users won't have to prefix the object
names by the schema name.
Some databases engines have 2 level of namespacing: database and
schema (postgres, oracle, mssql, ...)
For those it's probably better to not alter the database
component of the URI with the schema name, it won't work.
Some database drivers like presto accept "{catalog}/{schema}" in
the database component of the URL, that can be handled here.
"""
return uri
@classmethod
def sql_preprocessor(cls, sql):
"""If the SQL needs to be altered prior to running it
For example Presto needs to double `%` characters
"""
return sql
@classmethod
def patch(cls):
pass
@classmethod
def get_table_names(cls, schema, inspector):
return sorted(inspector.get_table_names(schema))
@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, latest_partition=True):
fields = '*'
cols = []
if show_cols or latest_partition:
cols = my_db.get_table(table_name, schema=schema).columns
if show_cols:
fields = [my_db.get_quoter()(c.name) for c in cols]
full_table_name = table_name
if schema:
full_table_name = schema + '.' + table_name
qry = select(fields).select_from(text(full_table_name))
if limit:
qry = qry.limit(limit)
if latest_partition:
partition_query = cls.where_latest_partition(
table_name, schema, my_db, qry, columns=cols)
if partition_query != False: # noqa
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 Db2EngineSpec(BaseEngineSpec):
engine = 'ibm_db_sa'
time_grains = (
Grain('Time Column', _('Time Column'), '{col}'),
Grain('second', _('second'),
'CAST({col} as TIMESTAMP)'
' - MICROSECOND({col}) MICROSECONDS'),
Grain('minute', _('minute'),
'CAST({col} as TIMESTAMP)'
' - SECOND({col}) SECONDS'
' - MICROSECOND({col}) MICROSECONDS'),
Grain('hour', _('hour'),
'CAST({col} as TIMESTAMP)'
' - MINUTE({col}) MINUTES'
' - SECOND({col}) SECONDS'
' - MICROSECOND({col}) MICROSECONDS '),
Grain('day', _('day'),
'CAST({col} as TIMESTAMP)'
' - HOUR({col}) HOURS'
' - MINUTE({col}) MINUTES'
' - SECOND({col}) SECONDS'
' - MICROSECOND({col}) MICROSECONDS '),
Grain('week', _('week'),
'{col} - (DAYOFWEEK({col})) DAYS'),
Grain('month', _('month'),
'{col} - (DAY({col})-1) DAYS'),
Grain('quarter', _('quarter'),
'{col} - (DAY({col})-1) DAYS'
' - (MONTH({col})-1) MONTHS'
' + ((QUARTER({col})-1) * 3) MONTHS'),
Grain('year', _('year'),
'{col} - (DAY({col})-1) DAYS'
' - (MONTH({col})-1) MONTHS'),
)
@classmethod
def epoch_to_dttm(cls):
return "(TIMESTAMP('1970-01-01', '00:00:00') + {col} SECONDS)"
@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
@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):
schemas = db.inspector.get_schema_names()
result_sets = {}
all_result_sets = []
schema = schemas[0]
if datasource_type == 'table':
result_sets[schema] = sorted(db.inspector.get_table_names())
elif datasource_type == 'view':
result_sets[schema] = sorted(db.inspector.get_view_names())
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 convert_dttm(cls, target_type, dttm):
iso = dttm.isoformat().replace('T', ' ')
if '.' not in iso:
iso += '.000000'
return "'{}'".format(iso)
@classmethod
def get_table_names(cls, schema, inspector):
"""Need to disregard the schema for Sqlite"""
return sorted(inspector.get_table_names())
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 adjust_database_uri(cls, uri, selected_schema=None):
if selected_schema:
uri.database = selected_schema
return uri
@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 adjust_database_uri(cls, uri, selected_schema=None):
database = uri.database
if selected_schema:
if '/' in database:
database = database.split('/')[0] + '/' + selected_schema
else:
database += '/' + selected_schema
uri.database = database
return uri
@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, show_first=True)
return {
'partitions': {
'cols': cols,
'latest': {col_name: latest_part},
'partitionQuery': pql,
}
}
@classmethod
def handle_cursor(cls, cursor, query, session):
"""Updates progress information"""
logging.info('Polling the cursor for progress')
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)
logging.info(
'Query progress: {} / {} '
'splits'.format(completed_splits, total_splits))
if progress > query.progress:
query.progress = progress
session.commit()
time.sleep(1)
logging.info('Polling the cursor for progress')
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]
return '{} 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, show_first=False):
"""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
:param show_first: displays the value for the first partitioning key
if there are many partitioning keys
:type show_first: bool
>>> 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 not show_first and 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 adjust_database_uri(cls, uri, selected_schema=None):
if selected_schema:
uri.database = selected_schema
return uri
@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).one()
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, schema, database, **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'
class AthenaEngineSpec(BaseEngineSpec):
engine = 'awsathena'
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 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 ("CAST ('{}' AS TIMESTAMP)"
.format(dttm.strftime('%Y-%m-%d %H:%M:%S')))
@classmethod
def epoch_to_dttm(cls):
return "from_unixtime({col})"
class ClickHouseEngineSpec(BaseEngineSpec):
"""Dialect for ClickHouse analytical DB."""
engine = 'clickhouse'
time_secondary_columns = True
time_groupby_inline = True
time_grains = (
Grain('Time Column', _('Time Column'), '{col}'),
Grain('minute', _('minute'),
"toStartOfMinute(toDateTime({col}))"),
Grain('5 minute', _('5 minute'),
"toDateTime(intDiv(toUInt32(toDateTime({col})), 300)*300)"),
Grain('10 minute', _('10 minute'),
"toDateTime(intDiv(toUInt32(toDateTime({col})), 600)*600)"),
Grain('hour', _('hour'),
"toStartOfHour(toDateTime({col}))"),
Grain('day', _('day'),
"toStartOfDay(toDateTime({col}))"),
Grain('month', _('month'),
"toStartOfMonth(toDateTime({col}))"),
Grain('quarter', _('quarter'),
"toStartOfQuarter(toDateTime({col}))"),
Grain('year', _('year'),
"toStartOfYear(toDateTime({col}))"),
)
@classmethod
def convert_dttm(cls, target_type, dttm):
tt = target_type.upper()
if tt == 'DATE':
return "toDate('{}')".format(dttm.strftime('%Y-%m-%d'))
if tt == 'DATETIME':
return "toDateTime('{}')".format(
dttm.strftime('%Y-%m-%d %H:%M:%S'))
return "'{}'".format(dttm.strftime('%Y-%m-%d %H:%M:%S'))
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/5dbfdefae82674d71ab1f1464622d199a6f72f30 | [
0.001653678365983069,
0.00022434986021835357,
0.00016094693273771554,
0.0001729921204969287,
0.00021511828526854515
] |
{
"id": 3,
"code_window": [
" expanded: true,\n",
" isMetadataLoading: false,\n",
" });\n",
" dispatch(mergeTable(table, dataPreviewQuery));\n",
" // Run query to get preview data for table\n",
" dispatch(runQuery(dataPreviewQuery));\n",
" })\n",
" .fail(() => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" dispatch(mergeTable(newTable, dataPreviewQuery));\n"
],
"file_path": "superset/assets/javascripts/SqlLab/actions.js",
"type": "replace",
"edit_start_line_idx": 279
} | """making audit nullable
Revision ID: 18e88e1cc004
Revises: 430039611635
Create Date: 2016-03-13 21:30:24.833107
"""
# revision identifiers, used by Alembic.
revision = '18e88e1cc004'
down_revision = '430039611635'
from alembic import op
import sqlalchemy as sa
def upgrade():
try:
op.alter_column(
'clusters', 'changed_on',
existing_type=sa.DATETIME(),
nullable=True)
op.alter_column(
'clusters', 'created_on',
existing_type=sa.DATETIME(), nullable=True)
op.drop_constraint(None, 'columns', type_='foreignkey')
op.drop_constraint(None, 'columns', type_='foreignkey')
op.drop_column('columns', 'created_on')
op.drop_column('columns', 'created_by_fk')
op.drop_column('columns', 'changed_on')
op.drop_column('columns', 'changed_by_fk')
op.alter_column('css_templates', 'changed_on',
existing_type=sa.DATETIME(),
nullable=True)
op.alter_column('css_templates', 'created_on',
existing_type=sa.DATETIME(),
nullable=True)
op.alter_column('dashboards', 'changed_on',
existing_type=sa.DATETIME(),
nullable=True)
op.alter_column('dashboards', 'created_on',
existing_type=sa.DATETIME(),
nullable=True)
op.create_unique_constraint(None, 'dashboards', ['slug'])
op.alter_column('datasources', 'changed_by_fk',
existing_type=sa.INTEGER(),
nullable=True)
op.alter_column('datasources', 'changed_on',
existing_type=sa.DATETIME(),
nullable=True)
op.alter_column('datasources', 'created_by_fk',
existing_type=sa.INTEGER(),
nullable=True)
op.alter_column('datasources', 'created_on',
existing_type=sa.DATETIME(),
nullable=True)
op.alter_column('dbs', 'changed_on',
existing_type=sa.DATETIME(),
nullable=True)
op.alter_column('dbs', 'created_on',
existing_type=sa.DATETIME(),
nullable=True)
op.alter_column('slices', 'changed_on',
existing_type=sa.DATETIME(),
nullable=True)
op.alter_column('slices', 'created_on',
existing_type=sa.DATETIME(),
nullable=True)
op.alter_column('sql_metrics', 'changed_on',
existing_type=sa.DATETIME(),
nullable=True)
op.alter_column('sql_metrics', 'created_on',
existing_type=sa.DATETIME(),
nullable=True)
op.alter_column('table_columns', 'changed_on',
existing_type=sa.DATETIME(),
nullable=True)
op.alter_column('table_columns', 'created_on',
existing_type=sa.DATETIME(),
nullable=True)
op.alter_column('tables', 'changed_on',
existing_type=sa.DATETIME(),
nullable=True)
op.alter_column('tables', 'created_on',
existing_type=sa.DATETIME(),
nullable=True)
op.alter_column('url', 'changed_on',
existing_type=sa.DATETIME(),
nullable=True)
op.alter_column('url', 'created_on',
existing_type=sa.DATETIME(),
nullable=True)
### end Alembic commands ###
except:
pass
def downgrade():
pass
| superset/migrations/versions/18e88e1cc004_making_audit_nullable.py | 0 | https://github.com/apache/superset/commit/5dbfdefae82674d71ab1f1464622d199a6f72f30 | [
0.00017738569295033813,
0.00017476876382716,
0.00016954228340182453,
0.00017541095439810306,
0.0000022789893137087347
] |
{
"id": 3,
"code_window": [
" expanded: true,\n",
" isMetadataLoading: false,\n",
" });\n",
" dispatch(mergeTable(table, dataPreviewQuery));\n",
" // Run query to get preview data for table\n",
" dispatch(runQuery(dataPreviewQuery));\n",
" })\n",
" .fail(() => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" dispatch(mergeTable(newTable, dataPreviewQuery));\n"
],
"file_path": "superset/assets/javascripts/SqlLab/actions.js",
"type": "replace",
"edit_start_line_idx": 279
} | verbose: true
instrumentation:
root: './javascripts'
extensions: ['.js', '.jsx']
excludes: [
'dist/**'
]
embed-source: false
variable: __coverage__
compact: true
preserve-comments: false
complete-copy: false
save-baseline: true
baseline-file: ./coverage/coverage-baseline.json
include-all-sources: true
include-pid: false
es-modules: true
reporting:
print: summary
reports:
- lcov
dir: ./coverage
watermarks:
statements: [50, 80]
lines: [50, 80]
functions: [50, 80]
branches: [50, 80]
report-config:
clover: {file: clover.xml}
cobertura: {file: cobertura-coverage.xml}
json: {file: coverage-final.json}
json-summary: {file: coverage-summary.json}
lcovonly: {file: lcov.info}
teamcity: {file: null, blockName: Code Coverage Summary}
text: {file: null, maxCols: 0}
text-lcov: {file: lcov.info}
text-summary: {file: null}
hooks:
hook-run-in-context: false
post-require-hook: null
handle-sigint: false
check:
global:
statements: 0
lines: 0
branches: 0
functions: 0
excludes: []
each:
statements: 0
lines: 0
branches: 0
functions: 0
excludes: []
| superset/assets/.istanbul.yml | 0 | https://github.com/apache/superset/commit/5dbfdefae82674d71ab1f1464622d199a6f72f30 | [
0.00018226352403871715,
0.00017822188965510577,
0.00017509525059722364,
0.00017821570509113371,
0.000002245345967821777
] |
{
"id": 3,
"code_window": [
" expanded: true,\n",
" isMetadataLoading: false,\n",
" });\n",
" dispatch(mergeTable(table, dataPreviewQuery));\n",
" // Run query to get preview data for table\n",
" dispatch(runQuery(dataPreviewQuery));\n",
" })\n",
" .fail(() => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" dispatch(mergeTable(newTable, dataPreviewQuery));\n"
],
"file_path": "superset/assets/javascripts/SqlLab/actions.js",
"type": "replace",
"edit_start_line_idx": 279
} | import React from 'react';
import PropTypes from 'prop-types';
import { Button as BootstrapButton, Tooltip, OverlayTrigger } from 'react-bootstrap';
import { slugify } from '../modules/utils';
const propTypes = {
tooltip: PropTypes.node,
placement: PropTypes.string,
};
const defaultProps = {
bsSize: 'sm',
placement: 'top',
};
export default function Button(props) {
const buttonProps = Object.assign({}, props);
const tooltip = props.tooltip;
const placement = props.placement;
delete buttonProps.tooltip;
delete buttonProps.placement;
let button = (
<BootstrapButton {...buttonProps} >
{props.children}
</BootstrapButton>
);
if (props.tooltip) {
button = (
<OverlayTrigger
placement={placement}
overlay={<Tooltip id={`${slugify(tooltip)}-tooltip`}>{tooltip}</Tooltip>}
>
{button}
</OverlayTrigger>
);
}
return button;
}
Button.propTypes = propTypes;
Button.defaultProps = defaultProps;
| superset/assets/javascripts/components/Button.jsx | 0 | https://github.com/apache/superset/commit/5dbfdefae82674d71ab1f1464622d199a6f72f30 | [
0.0001761633320711553,
0.00017396846669726074,
0.00017163748270832002,
0.00017426778504159302,
0.000001930563030327903
] |
{
"id": 4,
"code_window": [
" // Run query to get preview data for table\n",
" dispatch(runQuery(dataPreviewQuery));\n",
" })\n",
" .fail(() => {\n",
" notify.error('Error occurred while fetching table metadata');\n",
" });\n",
"\n",
" url = `/superset/extra_table_metadata/${query.dbId}/${tableName}/${schemaName}/`;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const newTable = Object.assign({}, table, {\n",
" isMetadataLoading: false,\n",
" });\n",
" dispatch(mergeTable(newTable));\n"
],
"file_path": "superset/assets/javascripts/SqlLab/actions.js",
"type": "add",
"edit_start_line_idx": 284
} | /* global notify */
import shortid from 'shortid';
import { now } from '../modules/dates';
const $ = require('jquery');
export const RESET_STATE = 'RESET_STATE';
export const ADD_QUERY_EDITOR = 'ADD_QUERY_EDITOR';
export const CLONE_QUERY_TO_NEW_TAB = 'CLONE_QUERY_TO_NEW_TAB';
export const REMOVE_QUERY_EDITOR = 'REMOVE_QUERY_EDITOR';
export const MERGE_TABLE = 'MERGE_TABLE';
export const REMOVE_TABLE = 'REMOVE_TABLE';
export const END_QUERY = 'END_QUERY';
export const REMOVE_QUERY = 'REMOVE_QUERY';
export const EXPAND_TABLE = 'EXPAND_TABLE';
export const COLLAPSE_TABLE = 'COLLAPSE_TABLE';
export const QUERY_EDITOR_SETDB = 'QUERY_EDITOR_SETDB';
export const QUERY_EDITOR_SET_SCHEMA = 'QUERY_EDITOR_SET_SCHEMA';
export const QUERY_EDITOR_SET_TITLE = 'QUERY_EDITOR_SET_TITLE';
export const QUERY_EDITOR_SET_AUTORUN = 'QUERY_EDITOR_SET_AUTORUN';
export const QUERY_EDITOR_SET_SQL = 'QUERY_EDITOR_SET_SQL';
export const QUERY_EDITOR_SET_SELECTED_TEXT = 'QUERY_EDITOR_SET_SELECTED_TEXT';
export const SET_DATABASES = 'SET_DATABASES';
export const SET_ACTIVE_QUERY_EDITOR = 'SET_ACTIVE_QUERY_EDITOR';
export const SET_ACTIVE_SOUTHPANE_TAB = 'SET_ACTIVE_SOUTHPANE_TAB';
export const ADD_ALERT = 'ADD_ALERT';
export const REMOVE_ALERT = 'REMOVE_ALERT';
export const REFRESH_QUERIES = 'REFRESH_QUERIES';
export const RUN_QUERY = 'RUN_QUERY';
export const START_QUERY = 'START_QUERY';
export const STOP_QUERY = 'STOP_QUERY';
export const REQUEST_QUERY_RESULTS = 'REQUEST_QUERY_RESULTS';
export const QUERY_SUCCESS = 'QUERY_SUCCESS';
export const QUERY_FAILED = 'QUERY_FAILED';
export const CLEAR_QUERY_RESULTS = 'CLEAR_QUERY_RESULTS';
export const REMOVE_DATA_PREVIEW = 'REMOVE_DATA_PREVIEW';
export const CHANGE_DATA_PREVIEW_ID = 'CHANGE_DATA_PREVIEW_ID';
export const SAVE_QUERY = 'SAVE_QUERY';
export function resetState() {
return { type: RESET_STATE };
}
export function saveQuery(query) {
const url = '/savedqueryviewapi/api/create';
$.ajax({
type: 'POST',
url,
data: query,
success: () => notify.success('Your query was saved'),
error: () => notify.error('Your query could not be saved'),
dataType: 'json',
});
return { type: SAVE_QUERY };
}
export function startQuery(query) {
Object.assign(query, {
id: query.id ? query.id : shortid.generate(),
progress: 0,
startDttm: now(),
state: (query.runAsync) ? 'pending' : 'running',
cached: false,
});
return { type: START_QUERY, query };
}
export function querySuccess(query, results) {
return { type: QUERY_SUCCESS, query, results };
}
export function queryFailed(query, msg) {
return { type: QUERY_FAILED, query, msg };
}
export function stopQuery(query) {
return { type: STOP_QUERY, query };
}
export function clearQueryResults(query) {
return { type: CLEAR_QUERY_RESULTS, query };
}
export function removeDataPreview(table) {
return { type: REMOVE_DATA_PREVIEW, table };
}
export function requestQueryResults(query) {
return { type: REQUEST_QUERY_RESULTS, query };
}
export function fetchQueryResults(query) {
return function (dispatch) {
dispatch(requestQueryResults(query));
const sqlJsonUrl = `/superset/results/${query.resultsKey}/`;
$.ajax({
type: 'GET',
dataType: 'json',
url: sqlJsonUrl,
success(results) {
dispatch(querySuccess(query, results));
},
error(err) {
let msg = 'Failed at retrieving results from the results backend';
if (err.responseJSON && err.responseJSON.error) {
msg = err.responseJSON.error;
}
dispatch(queryFailed(query, msg));
},
});
};
}
export function runQuery(query) {
return function (dispatch) {
dispatch(startQuery(query));
const sqlJsonRequest = {
client_id: query.id,
database_id: query.dbId,
json: true,
runAsync: query.runAsync,
schema: query.schema,
sql: query.sql,
sql_editor_id: query.sqlEditorId,
tab: query.tab,
tmp_table_name: query.tempTableName,
select_as_cta: query.ctas,
};
const sqlJsonUrl = '/superset/sql_json/' + location.search;
$.ajax({
type: 'POST',
dataType: 'json',
url: sqlJsonUrl,
data: sqlJsonRequest,
success(results) {
if (!query.runAsync) {
dispatch(querySuccess(query, results));
}
},
error(err, textStatus, errorThrown) {
let msg;
try {
msg = err.responseJSON.error;
} catch (e) {
if (err.responseText !== undefined) {
msg = err.responseText;
}
}
if (textStatus === 'error' && errorThrown === '') {
msg = 'Could not connect to server';
} else if (msg === null) {
msg = `[${textStatus}] ${errorThrown}`;
}
if (msg.indexOf('The CSRF token is missing') > 0) {
msg = 'Your session timed out, please refresh your page and try again.';
}
dispatch(queryFailed(query, msg));
},
});
};
}
export function postStopQuery(query) {
return function (dispatch) {
const stopQueryUrl = '/superset/stop_query/';
const stopQueryRequestData = { client_id: query.id };
dispatch(stopQuery(query));
$.ajax({
type: 'POST',
dataType: 'json',
url: stopQueryUrl,
data: stopQueryRequestData,
success() {
notify.success('Query was stopped.');
},
error() {
notify.error('Failed at stopping query.');
},
});
};
}
export function setDatabases(databases) {
return { type: SET_DATABASES, databases };
}
export function addQueryEditor(queryEditor) {
const newQe = Object.assign({}, queryEditor, { id: shortid.generate() });
return { type: ADD_QUERY_EDITOR, queryEditor: newQe };
}
export function cloneQueryToNewTab(query) {
return { type: CLONE_QUERY_TO_NEW_TAB, query };
}
export function addAlert(alert) {
const o = Object.assign({}, alert);
o.id = shortid.generate();
return { type: ADD_ALERT, alert: o };
}
export function removeAlert(alert) {
return { type: REMOVE_ALERT, alert };
}
export function setActiveQueryEditor(queryEditor) {
return { type: SET_ACTIVE_QUERY_EDITOR, queryEditor };
}
export function setActiveSouthPaneTab(tabId) {
return { type: SET_ACTIVE_SOUTHPANE_TAB, tabId };
}
export function removeQueryEditor(queryEditor) {
return { type: REMOVE_QUERY_EDITOR, queryEditor };
}
export function removeQuery(query) {
return { type: REMOVE_QUERY, query };
}
export function queryEditorSetDb(queryEditor, dbId) {
return { type: QUERY_EDITOR_SETDB, queryEditor, dbId };
}
export function queryEditorSetSchema(queryEditor, schema) {
return { type: QUERY_EDITOR_SET_SCHEMA, queryEditor, schema };
}
export function queryEditorSetAutorun(queryEditor, autorun) {
return { type: QUERY_EDITOR_SET_AUTORUN, queryEditor, autorun };
}
export function queryEditorSetTitle(queryEditor, title) {
return { type: QUERY_EDITOR_SET_TITLE, queryEditor, title };
}
export function queryEditorSetSql(queryEditor, sql) {
return { type: QUERY_EDITOR_SET_SQL, queryEditor, sql };
}
export function queryEditorSetSelectedText(queryEditor, sql) {
return { type: QUERY_EDITOR_SET_SELECTED_TEXT, queryEditor, sql };
}
export function mergeTable(table, query) {
return { type: MERGE_TABLE, table, query };
}
export function addTable(query, tableName, schemaName) {
return function (dispatch) {
let table = {
dbId: query.dbId,
queryEditorId: query.id,
schema: schemaName,
name: tableName,
isMetadataLoading: true,
isExtraMetadataLoading: true,
expanded: false,
};
dispatch(mergeTable(table));
let url = `/superset/table/${query.dbId}/${tableName}/${schemaName}/`;
$.get(url, (data) => {
const dataPreviewQuery = {
id: shortid.generate(),
dbId: query.dbId,
sql: data.selectStar,
tableName,
sqlEditorId: null,
tab: '',
runAsync: false,
ctas: false,
};
// Merge table to tables in state
table = Object.assign({}, table, data, {
expanded: true,
isMetadataLoading: false,
});
dispatch(mergeTable(table, dataPreviewQuery));
// Run query to get preview data for table
dispatch(runQuery(dataPreviewQuery));
})
.fail(() => {
notify.error('Error occurred while fetching table metadata');
});
url = `/superset/extra_table_metadata/${query.dbId}/${tableName}/${schemaName}/`;
$.get(url, (data) => {
table = Object.assign({}, table, data, { isExtraMetadataLoading: false });
dispatch(mergeTable(table));
});
};
}
export function changeDataPreviewId(oldQueryId, newQuery) {
return { type: CHANGE_DATA_PREVIEW_ID, oldQueryId, newQuery };
}
export function reFetchQueryResults(query) {
return function (dispatch) {
const newQuery = {
id: shortid.generate(),
dbId: query.dbId,
sql: query.sql,
tableName: query.tableName,
sqlEditorId: null,
tab: '',
runAsync: false,
ctas: false,
};
dispatch(runQuery(newQuery));
dispatch(changeDataPreviewId(query.id, newQuery));
};
}
export function expandTable(table) {
return { type: EXPAND_TABLE, table };
}
export function collapseTable(table) {
return { type: COLLAPSE_TABLE, table };
}
export function removeTable(table) {
return { type: REMOVE_TABLE, table };
}
export function refreshQueries(alteredQueries) {
return { type: REFRESH_QUERIES, alteredQueries };
}
export function popStoredQuery(urlId) {
return function (dispatch) {
$.ajax({
type: 'GET',
url: `/kv/${urlId}`,
success: (data) => {
const newQuery = JSON.parse(data);
const queryEditorProps = {
title: newQuery.title ? newQuery.title : 'shared query',
dbId: newQuery.dbId ? parseInt(newQuery.dbId, 10) : null,
schema: newQuery.schema ? newQuery.schema : null,
autorun: newQuery.autorun ? newQuery.autorun : false,
sql: newQuery.sql ? newQuery.sql : 'SELECT ...',
};
dispatch(addQueryEditor(queryEditorProps));
},
error: () => notify.error("The query couldn't be loaded"),
});
};
}
export function popSavedQuery(saveQueryId) {
return function (dispatch) {
$.ajax({
type: 'GET',
url: `/savedqueryviewapi/api/get/${saveQueryId}`,
success: (data) => {
const sq = data.result;
const queryEditorProps = {
title: sq.label,
dbId: sq.db_id ? parseInt(sq.db_id, 10) : null,
schema: sq.schema,
autorun: false,
sql: sq.sql,
};
dispatch(addQueryEditor(queryEditorProps));
},
error: () => notify.error("The query couldn't be loaded"),
});
};
}
| superset/assets/javascripts/SqlLab/actions.js | 1 | https://github.com/apache/superset/commit/5dbfdefae82674d71ab1f1464622d199a6f72f30 | [
0.9979846477508545,
0.02820231392979622,
0.00016657922242302448,
0.0003999221371486783,
0.15945978462696075
] |
{
"id": 4,
"code_window": [
" // Run query to get preview data for table\n",
" dispatch(runQuery(dataPreviewQuery));\n",
" })\n",
" .fail(() => {\n",
" notify.error('Error occurred while fetching table metadata');\n",
" });\n",
"\n",
" url = `/superset/extra_table_metadata/${query.dbId}/${tableName}/${schemaName}/`;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const newTable = Object.assign({}, table, {\n",
" isMetadataLoading: false,\n",
" });\n",
" dispatch(mergeTable(newTable));\n"
],
"file_path": "superset/assets/javascripts/SqlLab/actions.js",
"type": "add",
"edit_start_line_idx": 284
} | import React from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as Actions from '../actions';
const $ = require('jquery');
const QUERY_UPDATE_FREQ = 2000;
const QUERY_UPDATE_BUFFER_MS = 5000;
class QueryAutoRefresh extends React.PureComponent {
componentWillMount() {
this.startTimer();
}
componentWillUnmount() {
this.stopTimer();
}
shouldCheckForQueries() {
// if there are started or running queries, this method should return true
const { queries } = this.props;
const queryKeys = Object.keys(queries);
const queriesAsArray = queryKeys.map(key => queries[key]);
return queriesAsArray.some(q =>
['running', 'started', 'pending', 'fetching'].indexOf(q.state) >= 0);
}
startTimer() {
if (!(this.timer)) {
this.timer = setInterval(this.stopwatch.bind(this), QUERY_UPDATE_FREQ);
}
}
stopTimer() {
clearInterval(this.timer);
this.timer = null;
}
stopwatch() {
// only poll /superset/queries/ if there are started or running queries
if (this.shouldCheckForQueries()) {
const url = '/superset/queries/' + (this.props.queriesLastUpdate - QUERY_UPDATE_BUFFER_MS);
$.getJSON(url, (data) => {
if (Object.keys(data).length > 0) {
this.props.actions.refreshQueries(data);
}
});
}
}
render() {
return null;
}
}
QueryAutoRefresh.propTypes = {
queries: PropTypes.object.isRequired,
actions: PropTypes.object.isRequired,
queriesLastUpdate: PropTypes.number.isRequired,
};
function mapStateToProps(state) {
return {
queries: state.queries,
queriesLastUpdate: state.queriesLastUpdate,
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(Actions, dispatch),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(QueryAutoRefresh);
| superset/assets/javascripts/SqlLab/components/QueryAutoRefresh.jsx | 0 | https://github.com/apache/superset/commit/5dbfdefae82674d71ab1f1464622d199a6f72f30 | [
0.0042105927132070065,
0.0006878154817968607,
0.00016751133080106229,
0.00017188118363264948,
0.0013318820856511593
] |
{
"id": 4,
"code_window": [
" // Run query to get preview data for table\n",
" dispatch(runQuery(dataPreviewQuery));\n",
" })\n",
" .fail(() => {\n",
" notify.error('Error occurred while fetching table metadata');\n",
" });\n",
"\n",
" url = `/superset/extra_table_metadata/${query.dbId}/${tableName}/${schemaName}/`;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const newTable = Object.assign({}, table, {\n",
" isMetadataLoading: false,\n",
" });\n",
" dispatch(mergeTable(newTable));\n"
],
"file_path": "superset/assets/javascripts/SqlLab/actions.js",
"type": "add",
"edit_start_line_idx": 284
} | """add_cache_timeout_to_druid_cluster
Revision ID: ab3d66c4246e
Revises: eca4694defa7
Create Date: 2016-09-30 18:01:30.579760
"""
# revision identifiers, used by Alembic.
revision = 'ab3d66c4246e'
down_revision = 'eca4694defa7'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column(
'clusters', sa.Column('cache_timeout', sa.Integer(), nullable=True))
def downgrade():
op.drop_column('clusters', 'cache_timeout')
| superset/migrations/versions/ab3d66c4246e_add_cache_timeout_to_druid_cluster.py | 0 | https://github.com/apache/superset/commit/5dbfdefae82674d71ab1f1464622d199a6f72f30 | [
0.00017246957577299327,
0.00017060832760762423,
0.00016869120008777827,
0.00017066419241018593,
0.0000015430211988132214
] |
{
"id": 4,
"code_window": [
" // Run query to get preview data for table\n",
" dispatch(runQuery(dataPreviewQuery));\n",
" })\n",
" .fail(() => {\n",
" notify.error('Error occurred while fetching table metadata');\n",
" });\n",
"\n",
" url = `/superset/extra_table_metadata/${query.dbId}/${tableName}/${schemaName}/`;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const newTable = Object.assign({}, table, {\n",
" isMetadataLoading: false,\n",
" });\n",
" dispatch(mergeTable(newTable));\n"
],
"file_path": "superset/assets/javascripts/SqlLab/actions.js",
"type": "add",
"edit_start_line_idx": 284
} | import React from 'react';
import PropTypes from 'prop-types';
import { Tooltip, OverlayTrigger } from 'react-bootstrap';
import { slugify } from '../modules/utils';
const propTypes = {
label: PropTypes.string.isRequired,
tooltip: PropTypes.string.isRequired,
};
export default function InfoTooltipWithTrigger({ label, tooltip }) {
return (
<OverlayTrigger
placement="right"
overlay={<Tooltip id={`${slugify(label)}-tooltip`}>{tooltip}</Tooltip>}
>
<i className="fa fa-question-circle-o" />
</OverlayTrigger>
);
}
InfoTooltipWithTrigger.propTypes = propTypes;
| superset/assets/javascripts/components/InfoTooltipWithTrigger.jsx | 0 | https://github.com/apache/superset/commit/5dbfdefae82674d71ab1f1464622d199a6f72f30 | [
0.00017608742928132415,
0.00017366581596434116,
0.00017170459614135325,
0.00017320540791843086,
0.0000018186597117164638
] |
{
"id": 5,
"code_window": [
" url = `/superset/extra_table_metadata/${query.dbId}/${tableName}/${schemaName}/`;\n",
" $.get(url, (data) => {\n",
" table = Object.assign({}, table, data, { isExtraMetadataLoading: false });\n",
" dispatch(mergeTable(table));\n",
" });\n",
" };\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" })\n",
" .fail(() => {\n",
" const newTable = Object.assign({}, table, {\n",
" isExtraMetadataLoading: false,\n",
" });\n",
" dispatch(mergeTable(newTable));\n",
" notify.error('Error occurred while fetching table metadata');\n"
],
"file_path": "superset/assets/javascripts/SqlLab/actions.js",
"type": "add",
"edit_start_line_idx": 291
} | /* global notify */
import shortid from 'shortid';
import { now } from '../modules/dates';
const $ = require('jquery');
export const RESET_STATE = 'RESET_STATE';
export const ADD_QUERY_EDITOR = 'ADD_QUERY_EDITOR';
export const CLONE_QUERY_TO_NEW_TAB = 'CLONE_QUERY_TO_NEW_TAB';
export const REMOVE_QUERY_EDITOR = 'REMOVE_QUERY_EDITOR';
export const MERGE_TABLE = 'MERGE_TABLE';
export const REMOVE_TABLE = 'REMOVE_TABLE';
export const END_QUERY = 'END_QUERY';
export const REMOVE_QUERY = 'REMOVE_QUERY';
export const EXPAND_TABLE = 'EXPAND_TABLE';
export const COLLAPSE_TABLE = 'COLLAPSE_TABLE';
export const QUERY_EDITOR_SETDB = 'QUERY_EDITOR_SETDB';
export const QUERY_EDITOR_SET_SCHEMA = 'QUERY_EDITOR_SET_SCHEMA';
export const QUERY_EDITOR_SET_TITLE = 'QUERY_EDITOR_SET_TITLE';
export const QUERY_EDITOR_SET_AUTORUN = 'QUERY_EDITOR_SET_AUTORUN';
export const QUERY_EDITOR_SET_SQL = 'QUERY_EDITOR_SET_SQL';
export const QUERY_EDITOR_SET_SELECTED_TEXT = 'QUERY_EDITOR_SET_SELECTED_TEXT';
export const SET_DATABASES = 'SET_DATABASES';
export const SET_ACTIVE_QUERY_EDITOR = 'SET_ACTIVE_QUERY_EDITOR';
export const SET_ACTIVE_SOUTHPANE_TAB = 'SET_ACTIVE_SOUTHPANE_TAB';
export const ADD_ALERT = 'ADD_ALERT';
export const REMOVE_ALERT = 'REMOVE_ALERT';
export const REFRESH_QUERIES = 'REFRESH_QUERIES';
export const RUN_QUERY = 'RUN_QUERY';
export const START_QUERY = 'START_QUERY';
export const STOP_QUERY = 'STOP_QUERY';
export const REQUEST_QUERY_RESULTS = 'REQUEST_QUERY_RESULTS';
export const QUERY_SUCCESS = 'QUERY_SUCCESS';
export const QUERY_FAILED = 'QUERY_FAILED';
export const CLEAR_QUERY_RESULTS = 'CLEAR_QUERY_RESULTS';
export const REMOVE_DATA_PREVIEW = 'REMOVE_DATA_PREVIEW';
export const CHANGE_DATA_PREVIEW_ID = 'CHANGE_DATA_PREVIEW_ID';
export const SAVE_QUERY = 'SAVE_QUERY';
export function resetState() {
return { type: RESET_STATE };
}
export function saveQuery(query) {
const url = '/savedqueryviewapi/api/create';
$.ajax({
type: 'POST',
url,
data: query,
success: () => notify.success('Your query was saved'),
error: () => notify.error('Your query could not be saved'),
dataType: 'json',
});
return { type: SAVE_QUERY };
}
export function startQuery(query) {
Object.assign(query, {
id: query.id ? query.id : shortid.generate(),
progress: 0,
startDttm: now(),
state: (query.runAsync) ? 'pending' : 'running',
cached: false,
});
return { type: START_QUERY, query };
}
export function querySuccess(query, results) {
return { type: QUERY_SUCCESS, query, results };
}
export function queryFailed(query, msg) {
return { type: QUERY_FAILED, query, msg };
}
export function stopQuery(query) {
return { type: STOP_QUERY, query };
}
export function clearQueryResults(query) {
return { type: CLEAR_QUERY_RESULTS, query };
}
export function removeDataPreview(table) {
return { type: REMOVE_DATA_PREVIEW, table };
}
export function requestQueryResults(query) {
return { type: REQUEST_QUERY_RESULTS, query };
}
export function fetchQueryResults(query) {
return function (dispatch) {
dispatch(requestQueryResults(query));
const sqlJsonUrl = `/superset/results/${query.resultsKey}/`;
$.ajax({
type: 'GET',
dataType: 'json',
url: sqlJsonUrl,
success(results) {
dispatch(querySuccess(query, results));
},
error(err) {
let msg = 'Failed at retrieving results from the results backend';
if (err.responseJSON && err.responseJSON.error) {
msg = err.responseJSON.error;
}
dispatch(queryFailed(query, msg));
},
});
};
}
export function runQuery(query) {
return function (dispatch) {
dispatch(startQuery(query));
const sqlJsonRequest = {
client_id: query.id,
database_id: query.dbId,
json: true,
runAsync: query.runAsync,
schema: query.schema,
sql: query.sql,
sql_editor_id: query.sqlEditorId,
tab: query.tab,
tmp_table_name: query.tempTableName,
select_as_cta: query.ctas,
};
const sqlJsonUrl = '/superset/sql_json/' + location.search;
$.ajax({
type: 'POST',
dataType: 'json',
url: sqlJsonUrl,
data: sqlJsonRequest,
success(results) {
if (!query.runAsync) {
dispatch(querySuccess(query, results));
}
},
error(err, textStatus, errorThrown) {
let msg;
try {
msg = err.responseJSON.error;
} catch (e) {
if (err.responseText !== undefined) {
msg = err.responseText;
}
}
if (textStatus === 'error' && errorThrown === '') {
msg = 'Could not connect to server';
} else if (msg === null) {
msg = `[${textStatus}] ${errorThrown}`;
}
if (msg.indexOf('The CSRF token is missing') > 0) {
msg = 'Your session timed out, please refresh your page and try again.';
}
dispatch(queryFailed(query, msg));
},
});
};
}
export function postStopQuery(query) {
return function (dispatch) {
const stopQueryUrl = '/superset/stop_query/';
const stopQueryRequestData = { client_id: query.id };
dispatch(stopQuery(query));
$.ajax({
type: 'POST',
dataType: 'json',
url: stopQueryUrl,
data: stopQueryRequestData,
success() {
notify.success('Query was stopped.');
},
error() {
notify.error('Failed at stopping query.');
},
});
};
}
export function setDatabases(databases) {
return { type: SET_DATABASES, databases };
}
export function addQueryEditor(queryEditor) {
const newQe = Object.assign({}, queryEditor, { id: shortid.generate() });
return { type: ADD_QUERY_EDITOR, queryEditor: newQe };
}
export function cloneQueryToNewTab(query) {
return { type: CLONE_QUERY_TO_NEW_TAB, query };
}
export function addAlert(alert) {
const o = Object.assign({}, alert);
o.id = shortid.generate();
return { type: ADD_ALERT, alert: o };
}
export function removeAlert(alert) {
return { type: REMOVE_ALERT, alert };
}
export function setActiveQueryEditor(queryEditor) {
return { type: SET_ACTIVE_QUERY_EDITOR, queryEditor };
}
export function setActiveSouthPaneTab(tabId) {
return { type: SET_ACTIVE_SOUTHPANE_TAB, tabId };
}
export function removeQueryEditor(queryEditor) {
return { type: REMOVE_QUERY_EDITOR, queryEditor };
}
export function removeQuery(query) {
return { type: REMOVE_QUERY, query };
}
export function queryEditorSetDb(queryEditor, dbId) {
return { type: QUERY_EDITOR_SETDB, queryEditor, dbId };
}
export function queryEditorSetSchema(queryEditor, schema) {
return { type: QUERY_EDITOR_SET_SCHEMA, queryEditor, schema };
}
export function queryEditorSetAutorun(queryEditor, autorun) {
return { type: QUERY_EDITOR_SET_AUTORUN, queryEditor, autorun };
}
export function queryEditorSetTitle(queryEditor, title) {
return { type: QUERY_EDITOR_SET_TITLE, queryEditor, title };
}
export function queryEditorSetSql(queryEditor, sql) {
return { type: QUERY_EDITOR_SET_SQL, queryEditor, sql };
}
export function queryEditorSetSelectedText(queryEditor, sql) {
return { type: QUERY_EDITOR_SET_SELECTED_TEXT, queryEditor, sql };
}
export function mergeTable(table, query) {
return { type: MERGE_TABLE, table, query };
}
export function addTable(query, tableName, schemaName) {
return function (dispatch) {
let table = {
dbId: query.dbId,
queryEditorId: query.id,
schema: schemaName,
name: tableName,
isMetadataLoading: true,
isExtraMetadataLoading: true,
expanded: false,
};
dispatch(mergeTable(table));
let url = `/superset/table/${query.dbId}/${tableName}/${schemaName}/`;
$.get(url, (data) => {
const dataPreviewQuery = {
id: shortid.generate(),
dbId: query.dbId,
sql: data.selectStar,
tableName,
sqlEditorId: null,
tab: '',
runAsync: false,
ctas: false,
};
// Merge table to tables in state
table = Object.assign({}, table, data, {
expanded: true,
isMetadataLoading: false,
});
dispatch(mergeTable(table, dataPreviewQuery));
// Run query to get preview data for table
dispatch(runQuery(dataPreviewQuery));
})
.fail(() => {
notify.error('Error occurred while fetching table metadata');
});
url = `/superset/extra_table_metadata/${query.dbId}/${tableName}/${schemaName}/`;
$.get(url, (data) => {
table = Object.assign({}, table, data, { isExtraMetadataLoading: false });
dispatch(mergeTable(table));
});
};
}
export function changeDataPreviewId(oldQueryId, newQuery) {
return { type: CHANGE_DATA_PREVIEW_ID, oldQueryId, newQuery };
}
export function reFetchQueryResults(query) {
return function (dispatch) {
const newQuery = {
id: shortid.generate(),
dbId: query.dbId,
sql: query.sql,
tableName: query.tableName,
sqlEditorId: null,
tab: '',
runAsync: false,
ctas: false,
};
dispatch(runQuery(newQuery));
dispatch(changeDataPreviewId(query.id, newQuery));
};
}
export function expandTable(table) {
return { type: EXPAND_TABLE, table };
}
export function collapseTable(table) {
return { type: COLLAPSE_TABLE, table };
}
export function removeTable(table) {
return { type: REMOVE_TABLE, table };
}
export function refreshQueries(alteredQueries) {
return { type: REFRESH_QUERIES, alteredQueries };
}
export function popStoredQuery(urlId) {
return function (dispatch) {
$.ajax({
type: 'GET',
url: `/kv/${urlId}`,
success: (data) => {
const newQuery = JSON.parse(data);
const queryEditorProps = {
title: newQuery.title ? newQuery.title : 'shared query',
dbId: newQuery.dbId ? parseInt(newQuery.dbId, 10) : null,
schema: newQuery.schema ? newQuery.schema : null,
autorun: newQuery.autorun ? newQuery.autorun : false,
sql: newQuery.sql ? newQuery.sql : 'SELECT ...',
};
dispatch(addQueryEditor(queryEditorProps));
},
error: () => notify.error("The query couldn't be loaded"),
});
};
}
export function popSavedQuery(saveQueryId) {
return function (dispatch) {
$.ajax({
type: 'GET',
url: `/savedqueryviewapi/api/get/${saveQueryId}`,
success: (data) => {
const sq = data.result;
const queryEditorProps = {
title: sq.label,
dbId: sq.db_id ? parseInt(sq.db_id, 10) : null,
schema: sq.schema,
autorun: false,
sql: sq.sql,
};
dispatch(addQueryEditor(queryEditorProps));
},
error: () => notify.error("The query couldn't be loaded"),
});
};
}
| superset/assets/javascripts/SqlLab/actions.js | 1 | https://github.com/apache/superset/commit/5dbfdefae82674d71ab1f1464622d199a6f72f30 | [
0.9978095889091492,
0.0825202688574791,
0.00016532375593669713,
0.00043073156848549843,
0.26658129692077637
] |
{
"id": 5,
"code_window": [
" url = `/superset/extra_table_metadata/${query.dbId}/${tableName}/${schemaName}/`;\n",
" $.get(url, (data) => {\n",
" table = Object.assign({}, table, data, { isExtraMetadataLoading: false });\n",
" dispatch(mergeTable(table));\n",
" });\n",
" };\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" })\n",
" .fail(() => {\n",
" const newTable = Object.assign({}, table, {\n",
" isExtraMetadataLoading: false,\n",
" });\n",
" dispatch(mergeTable(newTable));\n",
" notify.error('Error occurred while fetching table metadata');\n"
],
"file_path": "superset/assets/javascripts/SqlLab/actions.js",
"type": "add",
"edit_start_line_idx": 291
} | import sinon from 'sinon';
import * as actions from '../../../javascripts/SqlLab/actions';
export const mockedActions = sinon.stub(Object.assign({}, actions));
export const alert = { bsStyle: 'danger', msg: 'Ooops', id: 'lksvmcx32' };
export const table = {
dbId: 1,
selectStar: 'SELECT * FROM ab_user',
queryEditorId: 'rJ-KP47a',
schema: 'superset',
name: 'ab_user',
id: 'r11Vgt60',
dataPreviewQueryId: null,
partitions: {
cols: ['username'],
latest: 'bob',
partitionQuery: 'SHOW PARTITIONS FROM ab_user',
},
indexes: [
{
unique: true,
column_names: [
'username',
],
type: 'UNIQUE',
name: 'username',
},
{
unique: true,
column_names: [
'email',
],
type: 'UNIQUE',
name: 'email',
},
{
unique: false,
column_names: [
'created_by_fk',
],
name: 'created_by_fk',
},
{
unique: false,
column_names: [
'changed_by_fk',
],
name: 'changed_by_fk',
},
],
columns: [
{
indexed: false,
longType: 'INTEGER(11)',
type: 'INTEGER',
name: 'id',
keys: [
{
column_names: ['id'],
type: 'pk',
name: null,
},
],
},
{
indexed: false,
longType: 'VARCHAR(64)',
type: 'VARCHAR',
name: 'first_name',
keys: [
{
column_names: [
'first_name',
],
name: 'slices_ibfk_1',
referred_columns: [
'id',
],
referred_table: 'datasources',
type: 'fk',
referred_schema: 'carapal',
options: {},
},
{
unique: false,
column_names: [
'druid_datasource_id',
],
type: 'index',
name: 'druid_datasource_id',
},
],
},
{
indexed: false,
longType: 'VARCHAR(64)',
type: 'VARCHAR',
name: 'last_name',
},
{
indexed: true,
longType: 'VARCHAR(64)',
type: 'VARCHAR',
name: 'username',
},
{
indexed: false,
longType: 'VARCHAR(256)',
type: 'VARCHAR',
name: 'password',
},
{
indexed: false,
longType: 'TINYINT(1)',
type: 'TINYINT',
name: 'active',
},
{
indexed: true,
longType: 'VARCHAR(64)',
type: 'VARCHAR',
name: 'email',
},
{
indexed: false,
longType: 'DATETIME',
type: 'DATETIME',
name: 'last_login',
},
{
indexed: false,
longType: 'INTEGER(11)',
type: 'INTEGER',
name: 'login_count',
},
{
indexed: false,
longType: 'INTEGER(11)',
type: 'INTEGER',
name: 'fail_login_count',
},
{
indexed: false,
longType: 'DATETIME',
type: 'DATETIME',
name: 'created_on',
},
{
indexed: false,
longType: 'DATETIME',
type: 'DATETIME',
name: 'changed_on',
},
{
indexed: true,
longType: 'INTEGER(11)',
type: 'INTEGER',
name: 'created_by_fk',
},
{
indexed: true,
longType: 'INTEGER(11)',
type: 'INTEGER',
name: 'changed_by_fk',
},
],
expanded: true,
};
export const defaultQueryEditor = {
id: 'dfsadfs',
autorun: false,
dbId: null,
latestQueryId: null,
selectedText: null,
sql: 'SELECT *\nFROM\nWHERE',
title: 'Untitled Query',
};
export const queries = [
{
dbId: 1,
sql: 'SELECT *FROM superset.slices',
sqlEditorId: 'SJ8YO72R',
tab: 'Demo',
runAsync: false,
ctas: false,
cached: false,
id: 'BkA1CLrJg',
progress: 100,
startDttm: 1476910566092.96,
state: 'success',
changedOn: 1476910566000,
tempTable: null,
userId: 1,
executedSql: null,
changed_on: '2016-10-19T20:56:06',
rows: 42,
endDttm: 1476910566798,
limit_reached: false,
schema: null,
errorMessage: null,
db: 'main',
user: 'admin',
limit: 1000,
serverId: 141,
resultsKey: null,
results: {
columns: ['col1', 'col2'],
data: [
{ col1: 0, col2: 1 },
{ col1: 2, col2: 3 },
],
},
},
{
dbId: 1,
sql: 'SELECT *FROM superset.slices',
sqlEditorId: 'SJ8YO72R',
tab: 'Demo',
runAsync: true,
ctas: false,
cached: false,
id: 'S1zeAISkx',
progress: 100,
startDttm: 1476910570802.2,
state: 'success',
changedOn: 1476910572000,
tempTable: null,
userId: 1,
executedSql: (
'SELECT * \nFROM (SELECT created_on, changed_on, id, slice_name, ' +
'druid_datasource_id, table_id, datasource_type, datasource_name, ' +
'viz_type, params, created_by_fk, changed_by_fk, description, ' +
'cache_timeout, perm\nFROM superset.slices) AS inner_qry \n LIMIT 1000'
),
changed_on: '2016-10-19T20:56:12',
rows: 42,
endDttm: 1476910579693,
limit_reached: false,
schema: null,
errorMessage: null,
db: 'main',
user: 'admin',
limit: 1000,
serverId: 142,
resultsKey: '417149f4-cd27-4f80-91f3-c45c871003f7',
results: null,
},
];
export const initialState = {
alerts: [],
queries: {},
databases: {},
queryEditors: [defaultQueryEditor],
tabHistory: [defaultQueryEditor.id],
tables: [],
workspaceQueries: [],
queriesLastUpdate: 0,
activeSouthPaneTab: 'Results',
};
export const query = {
dbId: 1,
sql: 'SELECT * FROM something',
sqlEditorId: defaultQueryEditor.id,
tab: 'unimportant',
tempTableName: null,
runAsync: false,
ctas: false,
cached: false,
};
| superset/assets/spec/javascripts/sqllab/fixtures.js | 0 | https://github.com/apache/superset/commit/5dbfdefae82674d71ab1f1464622d199a6f72f30 | [
0.001641048351302743,
0.0002499441325198859,
0.00016683863941580057,
0.00017655262490734458,
0.0002847542054951191
] |
{
"id": 5,
"code_window": [
" url = `/superset/extra_table_metadata/${query.dbId}/${tableName}/${schemaName}/`;\n",
" $.get(url, (data) => {\n",
" table = Object.assign({}, table, data, { isExtraMetadataLoading: false });\n",
" dispatch(mergeTable(table));\n",
" });\n",
" };\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" })\n",
" .fail(() => {\n",
" const newTable = Object.assign({}, table, {\n",
" isExtraMetadataLoading: false,\n",
" });\n",
" dispatch(mergeTable(newTable));\n",
" notify.error('Error occurred while fetching table metadata');\n"
],
"file_path": "superset/assets/javascripts/SqlLab/actions.js",
"type": "add",
"edit_start_line_idx": 291
} | .tab-pane {
min-height: 400px;
background: white;
border: 1px solid #bbb;
border-top: 0px;
}
.label {
display: inline-block;
margin-right: 5px;
margin-bottom: 5px;
}
| superset/assets/javascripts/profile/main.css | 0 | https://github.com/apache/superset/commit/5dbfdefae82674d71ab1f1464622d199a6f72f30 | [
0.00017459744412917644,
0.00017240751185454428,
0.00017021759413182735,
0.00017240751185454428,
0.0000021899249986745417
] |
{
"id": 5,
"code_window": [
" url = `/superset/extra_table_metadata/${query.dbId}/${tableName}/${schemaName}/`;\n",
" $.get(url, (data) => {\n",
" table = Object.assign({}, table, data, { isExtraMetadataLoading: false });\n",
" dispatch(mergeTable(table));\n",
" });\n",
" };\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" })\n",
" .fail(() => {\n",
" const newTable = Object.assign({}, table, {\n",
" isExtraMetadataLoading: false,\n",
" });\n",
" dispatch(mergeTable(newTable));\n",
" notify.error('Error occurred while fetching table metadata');\n"
],
"file_path": "superset/assets/javascripts/SqlLab/actions.js",
"type": "add",
"edit_start_line_idx": 291
} | """Unit tests for Superset"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from datetime import datetime
import json
import unittest
from mock import Mock, patch
from superset import db, sm, security
from superset.connectors.druid.models import DruidCluster, DruidDatasource
from superset.connectors.druid.models import PyDruid
from .base_tests import SupersetTestCase
SEGMENT_METADATA = [{
"id": "some_id",
"intervals": ["2013-05-13T00:00:00.000Z/2013-05-14T00:00:00.000Z"],
"columns": {
"__time": {
"type": "LONG", "hasMultipleValues": False,
"size": 407240380, "cardinality": None, "errorMessage": None},
"dim1": {
"type": "STRING", "hasMultipleValues": False,
"size": 100000, "cardinality": 1944, "errorMessage": None},
"dim2": {
"type": "STRING", "hasMultipleValues": True,
"size": 100000, "cardinality": 1504, "errorMessage": None},
"metric1": {
"type": "FLOAT", "hasMultipleValues": False,
"size": 100000, "cardinality": None, "errorMessage": None}
},
"aggregators": {
"metric1": {
"type": "longSum",
"name": "metric1",
"fieldName": "metric1"}
},
"size": 300000,
"numRows": 5000000
}]
GB_RESULT_SET = [
{
"version": "v1",
"timestamp": "2012-01-01T00:00:00.000Z",
"event": {
"dim1": 'Canada',
"metric1": 12345678,
}
},
{
"version": "v1",
"timestamp": "2012-01-01T00:00:00.000Z",
"event": {
"dim1": 'USA',
"metric1": 12345678 / 2,
}
},
]
class DruidTests(SupersetTestCase):
"""Testing interactions with Druid"""
def __init__(self, *args, **kwargs):
super(DruidTests, self).__init__(*args, **kwargs)
@patch('superset.connectors.druid.models.PyDruid')
def test_client(self, PyDruid):
self.login(username='admin')
instance = PyDruid.return_value
instance.time_boundary.return_value = [
{'result': {'maxTime': '2016-01-01'}}]
instance.segment_metadata.return_value = SEGMENT_METADATA
cluster = (
db.session
.query(DruidCluster)
.filter_by(cluster_name='test_cluster')
.first()
)
if cluster:
db.session.delete(cluster)
db.session.commit()
cluster = DruidCluster(
cluster_name='test_cluster',
coordinator_host='localhost',
coordinator_port=7979,
broker_host='localhost',
broker_port=7980,
metadata_last_refreshed=datetime.now())
db.session.add(cluster)
cluster.get_datasources = Mock(return_value=['test_datasource'])
cluster.get_druid_version = Mock(return_value='0.9.1')
cluster.refresh_datasources()
cluster.refresh_datasources(merge_flag=True)
datasource_id = cluster.datasources[0].id
db.session.commit()
nres = [
list(v['event'].items()) + [('timestamp', v['timestamp'])]
for v in GB_RESULT_SET]
nres = [dict(v) for v in nres]
import pandas as pd
df = pd.DataFrame(nres)
instance.export_pandas.return_value = df
instance.query_dict = {}
instance.query_builder.last_query.query_dict = {}
resp = self.get_resp('/superset/explore/druid/{}/'.format(
datasource_id))
self.assertIn("test_datasource", resp)
form_data = {
'viz_type': 'table',
'granularity': 'one+day',
'druid_time_origin': '',
'since': '7+days+ago',
'until': 'now',
'row_limit': 5000,
'include_search': 'false',
'metrics': ['count'],
'groupby': ['dim1'],
'force': 'true',
}
# One groupby
url = (
'/superset/explore_json/druid/{}/?form_data={}'.format(
datasource_id, json.dumps(form_data))
)
resp = self.get_json_resp(url)
self.assertEqual("Canada", resp['data']['records'][0]['dim1'])
form_data = {
'viz_type': 'table',
'granularity': 'one+day',
'druid_time_origin': '',
'since': '7+days+ago',
'until': 'now',
'row_limit': 5000,
'include_search': 'false',
'metrics': ['count'],
'groupby': ['dim1', 'dim2d'],
'force': 'true',
}
# two groupby
url = (
'/superset/explore_json/druid/{}/?form_data={}'.format(
datasource_id, json.dumps(form_data))
)
resp = self.get_json_resp(url)
self.assertEqual("Canada", resp['data']['records'][0]['dim1'])
def test_druid_sync_from_config(self):
CLUSTER_NAME = 'new_druid'
self.login()
cluster = self.get_or_create(
DruidCluster,
{'cluster_name': CLUSTER_NAME},
db.session)
db.session.merge(cluster)
db.session.commit()
ds = (
db.session.query(DruidDatasource)
.filter_by(datasource_name='test_click')
.first()
)
if ds:
db.session.delete(ds)
db.session.commit()
cfg = {
"user": "admin",
"cluster": CLUSTER_NAME,
"config": {
"name": "test_click",
"dimensions": ["affiliate_id", "campaign", "first_seen"],
"metrics_spec": [{"type": "count", "name": "count"},
{"type": "sum", "name": "sum"}],
"batch_ingestion": {
"sql": "SELECT * FROM clicks WHERE d='{{ ds }}'",
"ts_column": "d",
"sources": [{
"table": "clicks",
"partition": "d='{{ ds }}'"
}]
}
}
}
def check():
resp = self.client.post('/superset/sync_druid/', data=json.dumps(cfg))
druid_ds = (
db.session
.query(DruidDatasource)
.filter_by(datasource_name="test_click")
.one()
)
col_names = set([c.column_name for c in druid_ds.columns])
assert {"affiliate_id", "campaign", "first_seen"} == col_names
metric_names = {m.metric_name for m in druid_ds.metrics}
assert {"count", "sum"} == metric_names
assert resp.status_code == 201
check()
# checking twice to make sure a second sync yields the same results
check()
# datasource exists, add new metrics and dimensions
cfg = {
"user": "admin",
"cluster": CLUSTER_NAME,
"config": {
"name": "test_click",
"dimensions": ["affiliate_id", "second_seen"],
"metrics_spec": [
{"type": "bla", "name": "sum"},
{"type": "unique", "name": "unique"}
],
}
}
resp = self.client.post('/superset/sync_druid/', data=json.dumps(cfg))
druid_ds = db.session.query(DruidDatasource).filter_by(
datasource_name="test_click").one()
# columns and metrics are not deleted if config is changed as
# user could define his own dimensions / metrics and want to keep them
assert set([c.column_name for c in druid_ds.columns]) == set(
["affiliate_id", "campaign", "first_seen", "second_seen"])
assert set([m.metric_name for m in druid_ds.metrics]) == set(
["count", "sum", "unique"])
# metric type will not be overridden, sum stays instead of bla
assert set([m.metric_type for m in druid_ds.metrics]) == set(
["longSum", "sum", "unique"])
assert resp.status_code == 201
def test_filter_druid_datasource(self):
CLUSTER_NAME = 'new_druid'
cluster = self.get_or_create(
DruidCluster,
{'cluster_name': CLUSTER_NAME},
db.session)
db.session.merge(cluster)
gamma_ds = self.get_or_create(
DruidDatasource, {'datasource_name': 'datasource_for_gamma'},
db.session)
gamma_ds.cluster = cluster
db.session.merge(gamma_ds)
no_gamma_ds = self.get_or_create(
DruidDatasource, {'datasource_name': 'datasource_not_for_gamma'},
db.session)
no_gamma_ds.cluster = cluster
db.session.merge(no_gamma_ds)
db.session.commit()
security.merge_perm(sm, 'datasource_access', gamma_ds.perm)
security.merge_perm(sm, 'datasource_access', no_gamma_ds.perm)
perm = sm.find_permission_view_menu(
'datasource_access', gamma_ds.get_perm())
sm.add_permission_role(sm.find_role('Gamma'), perm)
sm.get_session.commit()
self.login(username='gamma')
url = '/druiddatasourcemodelview/list/'
resp = self.get_resp(url)
self.assertIn('datasource_for_gamma', resp)
self.assertNotIn('datasource_not_for_gamma', resp)
if __name__ == '__main__':
unittest.main()
| tests/druid_tests.py | 0 | https://github.com/apache/superset/commit/5dbfdefae82674d71ab1f1464622d199a6f72f30 | [
0.002526105847209692,
0.00042032013880088925,
0.0001680720888543874,
0.00017450423911213875,
0.0006448629428632557
] |
{
"id": 6,
"code_window": [
" \"\"\").format(**locals())\n",
" return sql\n",
"\n",
" @classmethod\n",
" def _latest_partition_from_df(cls, df):\n",
" return df.to_records(index=False)[0][0]\n",
"\n",
" @classmethod\n",
" def latest_partition(cls, table_name, schema, database, show_first=False):\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" recs = df.to_records(index=False)\n",
" if recs:\n",
" return recs[0][0]\n"
],
"file_path": "superset/db_engine_specs.py",
"type": "replace",
"edit_start_line_idx": 542
} | """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
import inspect
import logging
import re
import textwrap
import time
import sqlparse
from sqlalchemy import select
from sqlalchemy.sql import text
from flask_babel import lazy_gettext as _
from superset.utils import SupersetTemplateException
from superset.utils import QueryStatus
from superset import utils
from superset import cache_util
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):
"""Abstract class for database engine specific configurations"""
engine = 'base' # str as defined in sqlalchemy.engine.engine
cursor_execute_kwargs = {}
time_grains = tuple()
time_groupby_inline = False
limit_method = LimitMethod.FETCH_MANY
time_secondary_columns = False
@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 adjust_database_uri(cls, uri, selected_schema):
"""Based on a URI and selected schema, return a new URI
The URI here represents the URI as entered when saving the database,
``selected_schema`` is the schema currently active presumably in
the SQL Lab dropdown. Based on that, for some database engine,
we can return a new altered URI that connects straight to the
active schema, meaning the users won't have to prefix the object
names by the schema name.
Some databases engines have 2 level of namespacing: database and
schema (postgres, oracle, mssql, ...)
For those it's probably better to not alter the database
component of the URI with the schema name, it won't work.
Some database drivers like presto accept "{catalog}/{schema}" in
the database component of the URL, that can be handled here.
"""
return uri
@classmethod
def sql_preprocessor(cls, sql):
"""If the SQL needs to be altered prior to running it
For example Presto needs to double `%` characters
"""
return sql
@classmethod
def patch(cls):
pass
@classmethod
def get_table_names(cls, schema, inspector):
return sorted(inspector.get_table_names(schema))
@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, latest_partition=True):
fields = '*'
cols = []
if show_cols or latest_partition:
cols = my_db.get_table(table_name, schema=schema).columns
if show_cols:
fields = [my_db.get_quoter()(c.name) for c in cols]
full_table_name = table_name
if schema:
full_table_name = schema + '.' + table_name
qry = select(fields).select_from(text(full_table_name))
if limit:
qry = qry.limit(limit)
if latest_partition:
partition_query = cls.where_latest_partition(
table_name, schema, my_db, qry, columns=cols)
if partition_query != False: # noqa
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 Db2EngineSpec(BaseEngineSpec):
engine = 'ibm_db_sa'
time_grains = (
Grain('Time Column', _('Time Column'), '{col}'),
Grain('second', _('second'),
'CAST({col} as TIMESTAMP)'
' - MICROSECOND({col}) MICROSECONDS'),
Grain('minute', _('minute'),
'CAST({col} as TIMESTAMP)'
' - SECOND({col}) SECONDS'
' - MICROSECOND({col}) MICROSECONDS'),
Grain('hour', _('hour'),
'CAST({col} as TIMESTAMP)'
' - MINUTE({col}) MINUTES'
' - SECOND({col}) SECONDS'
' - MICROSECOND({col}) MICROSECONDS '),
Grain('day', _('day'),
'CAST({col} as TIMESTAMP)'
' - HOUR({col}) HOURS'
' - MINUTE({col}) MINUTES'
' - SECOND({col}) SECONDS'
' - MICROSECOND({col}) MICROSECONDS '),
Grain('week', _('week'),
'{col} - (DAYOFWEEK({col})) DAYS'),
Grain('month', _('month'),
'{col} - (DAY({col})-1) DAYS'),
Grain('quarter', _('quarter'),
'{col} - (DAY({col})-1) DAYS'
' - (MONTH({col})-1) MONTHS'
' + ((QUARTER({col})-1) * 3) MONTHS'),
Grain('year', _('year'),
'{col} - (DAY({col})-1) DAYS'
' - (MONTH({col})-1) MONTHS'),
)
@classmethod
def epoch_to_dttm(cls):
return "(TIMESTAMP('1970-01-01', '00:00:00') + {col} SECONDS)"
@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
@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):
schemas = db.inspector.get_schema_names()
result_sets = {}
all_result_sets = []
schema = schemas[0]
if datasource_type == 'table':
result_sets[schema] = sorted(db.inspector.get_table_names())
elif datasource_type == 'view':
result_sets[schema] = sorted(db.inspector.get_view_names())
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 convert_dttm(cls, target_type, dttm):
iso = dttm.isoformat().replace('T', ' ')
if '.' not in iso:
iso += '.000000'
return "'{}'".format(iso)
@classmethod
def get_table_names(cls, schema, inspector):
"""Need to disregard the schema for Sqlite"""
return sorted(inspector.get_table_names())
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 adjust_database_uri(cls, uri, selected_schema=None):
if selected_schema:
uri.database = selected_schema
return uri
@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 adjust_database_uri(cls, uri, selected_schema=None):
database = uri.database
if selected_schema:
if '/' in database:
database = database.split('/')[0] + '/' + selected_schema
else:
database += '/' + selected_schema
uri.database = database
return uri
@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, show_first=True)
return {
'partitions': {
'cols': cols,
'latest': {col_name: latest_part},
'partitionQuery': pql,
}
}
@classmethod
def handle_cursor(cls, cursor, query, session):
"""Updates progress information"""
logging.info('Polling the cursor for progress')
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)
logging.info(
'Query progress: {} / {} '
'splits'.format(completed_splits, total_splits))
if progress > query.progress:
query.progress = progress
session.commit()
time.sleep(1)
logging.info('Polling the cursor for progress')
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]
return '{} 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, show_first=False):
"""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
:param show_first: displays the value for the first partitioning key
if there are many partitioning keys
:type show_first: bool
>>> 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 not show_first and 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 adjust_database_uri(cls, uri, selected_schema=None):
if selected_schema:
uri.database = selected_schema
return uri
@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).one()
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, schema, database, **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'
class AthenaEngineSpec(BaseEngineSpec):
engine = 'awsathena'
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 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 ("CAST ('{}' AS TIMESTAMP)"
.format(dttm.strftime('%Y-%m-%d %H:%M:%S')))
@classmethod
def epoch_to_dttm(cls):
return "from_unixtime({col})"
class ClickHouseEngineSpec(BaseEngineSpec):
"""Dialect for ClickHouse analytical DB."""
engine = 'clickhouse'
time_secondary_columns = True
time_groupby_inline = True
time_grains = (
Grain('Time Column', _('Time Column'), '{col}'),
Grain('minute', _('minute'),
"toStartOfMinute(toDateTime({col}))"),
Grain('5 minute', _('5 minute'),
"toDateTime(intDiv(toUInt32(toDateTime({col})), 300)*300)"),
Grain('10 minute', _('10 minute'),
"toDateTime(intDiv(toUInt32(toDateTime({col})), 600)*600)"),
Grain('hour', _('hour'),
"toStartOfHour(toDateTime({col}))"),
Grain('day', _('day'),
"toStartOfDay(toDateTime({col}))"),
Grain('month', _('month'),
"toStartOfMonth(toDateTime({col}))"),
Grain('quarter', _('quarter'),
"toStartOfQuarter(toDateTime({col}))"),
Grain('year', _('year'),
"toStartOfYear(toDateTime({col}))"),
)
@classmethod
def convert_dttm(cls, target_type, dttm):
tt = target_type.upper()
if tt == 'DATE':
return "toDate('{}')".format(dttm.strftime('%Y-%m-%d'))
if tt == 'DATETIME':
return "toDateTime('{}')".format(
dttm.strftime('%Y-%m-%d %H:%M:%S'))
return "'{}'".format(dttm.strftime('%Y-%m-%d %H:%M:%S'))
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/5dbfdefae82674d71ab1f1464622d199a6f72f30 | [
0.9233776330947876,
0.025747131556272507,
0.0001615374640095979,
0.00017469553858973086,
0.1264733076095581
] |
{
"id": 6,
"code_window": [
" \"\"\").format(**locals())\n",
" return sql\n",
"\n",
" @classmethod\n",
" def _latest_partition_from_df(cls, df):\n",
" return df.to_records(index=False)[0][0]\n",
"\n",
" @classmethod\n",
" def latest_partition(cls, table_name, schema, database, show_first=False):\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" recs = df.to_records(index=False)\n",
" if recs:\n",
" return recs[0][0]\n"
],
"file_path": "superset/db_engine_specs.py",
"type": "replace",
"edit_start_line_idx": 542
} | Tutorial for Superset Administrators
====================================
This tutorial targets a Superset administrator: someone configuring Superset
for an organization on behalf of users. We'll show you how to connect Superset
to a new database and configure a table in that database for analysis. You'll
also explore the data you've exposed and add a visualization to a dashboard
so that you get a feel for the end-to-end user experience.
Connecting to a new database
----------------------------
We assume you already have a database configured and can connect to it from the
instance on which you’re running Superset. If you’re just testing Superset and
want to explore sample data, you can load some
`sample PostgreSQL datasets <https://wiki.postgresql.org/wiki/Sample_Databases>`_
into a fresh DB, or configure the
`example weather data <https://github.com/dylburger/noaa-ghcn-weather-data>`_
we use here.
Under the **Sources** menu, select the *Databases* option:
.. image:: _static/img/tutorial/tutorial_01_sources_database.png
:scale: 70%
On the resulting page, click on the green plus sign, near the top left:
.. image:: _static/img/tutorial/tutorial_02_add_database.png
:scale: 70%
You can configure a number of advanced options on this page, but for
this walkthrough, you’ll only need to do **two things**:
1. Name your database connection:
.. image:: _static/img/tutorial/tutorial_03_database_name.png
:scale: 70%
2. Provide the SQLAlchemy Connection URI and test the connection:
.. image:: _static/img/tutorial/tutorial_04_sqlalchemy_connection_string.png
:scale: 70%
This example shows the connection string for our test weather database.
As noted in the text below the URI, you should refer to the SQLAlchemy
documentation on
`creating new connection URIs <http://docs.sqlalchemy.org/en/rel_1_0/core/engines.html#database-urls>`_
for your target database.
Click the **Test Connection** button to confirm things work end to end.
Once Superset can successfully connect and authenticate, you should see
a popup like this:
.. image:: _static/img/tutorial/tutorial_05_connection_popup.png
:scale: 50%
Moreover, you should also see the list of tables Superset can read from
the schema you’re connected to, at the bottom of the page:
.. image:: _static/img/tutorial/tutorial_06_list_of_tables.png
:scale: 70%
If the connection looks good, save the configuration by clicking the **Save**
button at the bottom of the page:
.. image:: _static/img/tutorial/tutorial_07_save_button.png
:scale: 70%
Adding a new table
------------------
Now that you’ve configured a database, you’ll need to add specific tables
to Superset that you’d like to query.
Under the **Sources** menu, select the *Tables* option:
.. image:: _static/img/tutorial/tutorial_08_sources_tables.png
:scale: 70%
On the resulting page, click on the green plus sign, near the top left:
.. image:: _static/img/tutorial/tutorial_09_add_new_table.png
:scale: 70%
You only need a few pieces of information to add a new table to Superset:
* The name of the table
.. image:: _static/img/tutorial/tutorial_10_table_name.png
:scale: 70%
* The target database from the **Database** drop-down menu (i.e. the one
you just added above)
.. image:: _static/img/tutorial/tutorial_11_choose_db.png
:scale: 70%
* Optionally, the database schema. If the table exists in the “default” schema
(e.g. the *public* schema in PostgreSQL or Redshift), you can leave the schema
field blank.
Click on the **Save** button to save the configuration:
.. image:: _static/img/tutorial/tutorial_07_save_button.png
:scale: 70%
When redirected back to the list of tables, you should see a message indicating
that your table was created:
.. image:: _static/img/tutorial/tutorial_12_table_creation_success_msg.png
:scale: 70%
This message also directs you to edit the table configuration. We’ll edit a limited
portion of the configuration now - just to get you started - and leave the rest for
a more advanced tutorial.
Click on the edit button next to the table you’ve created:
.. image:: _static/img/tutorial/tutorial_13_edit_table_config.png
:scale: 70%
On the resulting page, click on the **List Table Column** tab. Here, you’ll define the
way you can use specific columns of your table when exploring your data. We’ll run
through these options to describe their purpose:
* If you want users to group metrics by a specific field, mark it as **Groupable**.
* If you need to filter on a specific field, mark it as **Filterable**.
* Is this field something you’d like to get the distinct count of? Check the **Count
Distinct** box.
* Is this a metric you want to sum, or get basic summary statistics for? The **Sum**,
**Min**, and **Max** columns will help.
* The **is temporal** field should be checked for any date or time fields. We’ll cover
how this manifests itself in analyses in a moment.
Here’s how we’ve configured fields for the weather data. Even for measures like the
weather measurements (precipitation, snowfall, etc.), it’s ideal to group and filter
by these values:
.. image:: _static/img/tutorial/tutorial_14_field_config.png
As with the configurations above, click the **Save** button to save these settings.
Exploring your data
-------------------
To start exploring your data, simply click on the table name you just created in
the list of available tables:
.. image:: _static/img/tutorial/tutorial_15_click_table_name.png
By default, you’ll be presented with a Table View:
.. image:: _static/img/tutorial/tutorial_16_datasource_chart_type.png
Let’s walk through a basic query to get the count of all records in our table.
First, we’ll need to change the **Since** filter to capture the range of our data.
You can use simple phrases to apply these filters, like "3 years ago":
.. image:: _static/img/tutorial/tutorial_17_choose_time_range.png
The upper limit for time, the **Until** filter, defaults to "now", which may or may
not be what you want.
Look for the Metrics section under the **GROUP BY** header, and start typing "Count"
- you’ll see a list of metrics matching what you type:
.. image:: _static/img/tutorial/tutorial_18_choose_metric.png
Select the *COUNT(\*)* metric, then click the green **Query** button near the top
of the explore:
.. image:: _static/img/tutorial/tutorial_19_click_query.png
You’ll see your results in the table:
.. image:: _static/img/tutorial/tutorial_20_count_star_result.png
Let’s group this by the *weather_description* field to get the count of records by
the type of weather recorded by adding it to the *Group by* section:
.. image:: _static/img/tutorial/tutorial_21_group_by.png
and run the query:
.. image:: _static/img/tutorial/tutorial_22_group_by_result.png
Let’s find a more useful data point: the top 10 times and places that recorded the
highest temperature in 2015.
We replace *weather_description* with *latitude*, *longitude* and *measurement_date* in the
*Group by* section:
.. image:: _static/img/tutorial/tutorial_23_group_by_more_dimensions.png
And replace *COUNT(\*)* with *max__measurement_flag*:
.. image:: _static/img/tutorial/tutorial_24_max_metric.png
The *max__measurement_flag* metric was created when we checked the box under **Max** and
next to the *measurement_flag* field, indicating that this field was numeric and that
we wanted to find its maximum value when grouped by specific fields.
In our case, *measurement_flag* is the value of the measurement taken, which clearly
depends on the type of measurement (the researchers recorded different values for
precipitation and temperature). Therefore, we must filter our query only on records
where the *weather_description* is equal to "Maximum temperature", which we do in
the **Filters** section at the bottom of the explore:
.. image:: _static/img/tutorial/tutorial_25_max_temp_filter.png
Finally, since we only care about the top 10 measurements, we limit our results to
10 records using the *Row limit* option under the **Options** header:
.. image:: _static/img/tutorial/tutorial_26_row_limit.png
We click **Query** and get the following results:
.. image:: _static/img/tutorial/tutorial_27_top_10_max_temps.png
In this dataset, the maximum temperature is recorded in tenths of a degree Celsius.
The top value of 1370, measured in the middle of Nevada, is equal to 137 C, or roughly
278 degrees F. It’s unlikely this value was correctly recorded. We’ve already been able
to investigate some outliers with Superset, but this just scratches the surface of what
we can do.
You may want to do a couple more things with this measure:
* The default formatting shows values like 1.37k, which may be difficult for some
users to read. It’s likely you may want to see the full, comma-separated value.
You can change the formatting of any measure by editing its config (*Edit Table
Config > List Sql Metric > Edit Metric > D3Format*)
* Moreover, you may want to see the temperature measurements in plain degrees C,
not tenths of a degree. Or you may want to convert the temperature to degrees
Fahrenheit. You can change the SQL that gets executed agains the database, baking
the logic into the measure itself (*Edit Table Config > List Sql Metric > Edit
Metric > SQL Expression*)
For now, though, let’s create a better visualization of these data and add it to
a dashboard.
We change the Chart Type to "Distribution - Bar Chart":
.. image:: _static/img/tutorial/tutorial_28_bar_chart.png
Our filter on Maximum temperature measurements was retained, but the query and
formatting options are dependent on the chart type, so you’ll have to set the
values again:
.. image:: _static/img/tutorial/tutorial_29_bar_chart_series_metrics.png
You should note the extensive formatting options for this chart: the ability to
set axis labels, margins, ticks, etc. To make the data presentable to a broad
audience, you’ll want to apply many of these to slices that end up in dashboards.
For now, though, we run our query and get the following chart:
.. image:: _static/img/tutorial/tutorial_30_bar_chart_results.png
:scale: 70%
Creating a slice and dashboard
------------------------------
This view might be interesting to researchers, so let’s save it. In Superset,
a saved query is called a **Slice**.
To create a slice, click the **Save as** button near the top-left of the
explore:
.. image:: _static/img/tutorial/tutorial_19_click_query.png
A popup should appear, asking you to name the slice, and optionally add it to a
dashboard. Since we haven’t yet created any dashboards, we can create one and
immediately add our slice to it. Let’s do it:
.. image:: _static/img/tutorial/tutorial_31_save_slice_to_dashboard.png
:scale: 70%
Click Save, which will direct you back to your original query. We see that
our slice and dashboard were successfully created:
.. image:: _static/img/tutorial/tutorial_32_save_slice_confirmation.png
:scale: 70%
Let’s check out our new dashboard. We click on the **Dashboards** menu:
.. image:: _static/img/tutorial/tutorial_33_dashboard.png
and find the dashboard we just created:
.. image:: _static/img/tutorial/tutorial_34_weather_dashboard.png
Things seemed to have worked - our slice is here!
.. image:: _static/img/tutorial/tutorial_35_slice_on_dashboard.png
:scale: 70%
But it’s a bit smaller than we might like. Luckily, you can adjust the size
of slices in a dashboard by clicking, holding and dragging the bottom-right
corner to your desired dimensions:
.. image:: _static/img/tutorial/tutorial_36_adjust_dimensions.gif
:scale: 120%
After adjusting the size, you’ll be asked to click on the icon near the
top-right of the dashboard to save the new configuration.
Congrats! You’ve successfully linked, analyzed, and visualized data in Superset.
There are a wealth of other table configuration and visualization options, so
please start exploring and creating slices and dashboards of your own.
| docs/tutorial.rst | 0 | https://github.com/apache/superset/commit/5dbfdefae82674d71ab1f1464622d199a6f72f30 | [
0.00017581699648872018,
0.00017052533803507686,
0.0001620006951270625,
0.00017186299373861402,
0.00000396974337490974
] |
{
"id": 6,
"code_window": [
" \"\"\").format(**locals())\n",
" return sql\n",
"\n",
" @classmethod\n",
" def _latest_partition_from_df(cls, df):\n",
" return df.to_records(index=False)[0][0]\n",
"\n",
" @classmethod\n",
" def latest_partition(cls, table_name, schema, database, show_first=False):\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" recs = df.to_records(index=False)\n",
" if recs:\n",
" return recs[0][0]\n"
],
"file_path": "superset/db_engine_specs.py",
"type": "replace",
"edit_start_line_idx": 542
} | [ignore: superset/assets/node_modules/**]
[python: superset/**.py]
[jinja2: superset/**/templates/**.html]
encoding = utf-8
| babel/babel.cfg | 0 | https://github.com/apache/superset/commit/5dbfdefae82674d71ab1f1464622d199a6f72f30 | [
0.0001774514967110008,
0.0001774514967110008,
0.0001774514967110008,
0.0001774514967110008,
0
] |
{
"id": 6,
"code_window": [
" \"\"\").format(**locals())\n",
" return sql\n",
"\n",
" @classmethod\n",
" def _latest_partition_from_df(cls, df):\n",
" return df.to_records(index=False)[0][0]\n",
"\n",
" @classmethod\n",
" def latest_partition(cls, table_name, schema, database, show_first=False):\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" recs = df.to_records(index=False)\n",
" if recs:\n",
" return recs[0][0]\n"
],
"file_path": "superset/db_engine_specs.py",
"type": "replace",
"edit_start_line_idx": 542
} | import { List } from 'immutable';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import {
Column,
Table,
SortDirection,
SortIndicator,
} from 'react-virtualized';
import { getTextWidth } from '../../modules/visUtils';
const propTypes = {
orderedColumnKeys: PropTypes.array.isRequired,
data: PropTypes.array.isRequired,
height: PropTypes.number.isRequired,
filterText: PropTypes.string,
headerHeight: PropTypes.number,
overscanRowCount: PropTypes.number,
rowHeight: PropTypes.number,
striped: PropTypes.bool,
};
const defaultProps = {
filterText: '',
headerHeight: 32,
overscanRowCount: 10,
rowHeight: 32,
striped: true,
};
export default class FilterableTable extends PureComponent {
constructor(props) {
super(props);
this.list = List(this.formatTableData(props.data));
this.headerRenderer = this.headerRenderer.bind(this);
this.rowClassName = this.rowClassName.bind(this);
this.sort = this.sort.bind(this);
this.widthsForColumnsByKey = this.getWidthsForColumns();
this.totalTableWidth = props.orderedColumnKeys
.map(key => this.widthsForColumnsByKey[key])
.reduce((curr, next) => curr + next);
this.state = {
sortBy: null,
sortDirection: SortDirection.ASC,
fitted: false,
};
}
componentDidMount() {
this.fitTableToWidthIfNeeded();
}
getDatum(list, index) {
return list.get(index % list.size);
}
getWidthsForColumns() {
const PADDING = 40; // accounts for cell padding and width of sorting icon
const widthsByColumnKey = {};
this.props.orderedColumnKeys.forEach((key) => {
const colWidths = this.list
.map(d => getTextWidth(d[key]) + PADDING) // get width for each value for a key
.push(getTextWidth(key) + PADDING); // add width of column key to end of list
// set max width as value for key
widthsByColumnKey[key] = Math.max(...colWidths);
});
return widthsByColumnKey;
}
fitTableToWidthIfNeeded() {
const containerWidth = this.container.getBoundingClientRect().width;
if (containerWidth > this.totalTableWidth) {
this.totalTableWidth = containerWidth - 2; // accomodates 1px border on container
}
this.setState({ fitted: true });
}
formatTableData(data) {
const formattedData = data.map((row) => {
const newRow = {};
for (const k in row) {
const val = row[k];
if (typeof (val) === 'string') {
newRow[k] = val;
} else {
newRow[k] = JSON.stringify(val);
}
}
return newRow;
});
return formattedData;
}
hasMatch(text, row) {
const values = [];
for (const key in row) {
if (row.hasOwnProperty(key)) {
values.push(row[key].toLowerCase());
}
}
return values.some(v => v.includes(text.toLowerCase()));
}
headerRenderer({ dataKey, label, sortBy, sortDirection }) {
return (
<div>
{label}
{sortBy === dataKey &&
<SortIndicator sortDirection={sortDirection} />
}
</div>
);
}
rowClassName({ index }) {
let className = '';
if (this.props.striped) {
className = index % 2 === 0 ? 'even-row' : 'odd-row';
}
return className;
}
sort({ sortBy, sortDirection }) {
this.setState({ sortBy, sortDirection });
}
render() {
const { sortBy, sortDirection } = this.state;
const {
filterText,
headerHeight,
height,
orderedColumnKeys,
overscanRowCount,
rowHeight,
} = this.props;
let sortedAndFilteredList = this.list;
// filter list
if (filterText) {
sortedAndFilteredList = this.list.filter(row => this.hasMatch(filterText, row));
}
// sort list
if (sortBy) {
sortedAndFilteredList = sortedAndFilteredList
.sortBy(item => item[sortBy])
.update(list => sortDirection === SortDirection.DESC ? list.reverse() : list);
}
const rowGetter = ({ index }) => this.getDatum(sortedAndFilteredList, index);
return (
<div
style={{ height }}
className="filterable-table-container"
ref={(ref) => { this.container = ref; }}
>
{this.state.fitted &&
<Table
ref="Table"
headerHeight={headerHeight}
height={height - 2}
overscanRowCount={overscanRowCount}
rowClassName={this.rowClassName}
rowHeight={rowHeight}
rowGetter={rowGetter}
rowCount={sortedAndFilteredList.size}
sort={this.sort}
sortBy={sortBy}
sortDirection={sortDirection}
width={this.totalTableWidth}
>
{orderedColumnKeys.map(columnKey => (
<Column
dataKey={columnKey}
disableSort={false}
headerRenderer={this.headerRenderer}
width={this.widthsForColumnsByKey[columnKey]}
label={columnKey}
key={columnKey}
/>
))}
</Table>
}
</div>
);
}
}
FilterableTable.propTypes = propTypes;
FilterableTable.defaultProps = defaultProps;
| superset/assets/javascripts/components/FilterableTable/FilterableTable.jsx | 0 | https://github.com/apache/superset/commit/5dbfdefae82674d71ab1f1464622d199a6f72f30 | [
0.0001754162658471614,
0.0001701286091702059,
0.0001634079817449674,
0.00016888600657694042,
0.000003860329798044404
] |
{
"id": 0,
"code_window": [
" '@material-ui/utils': resolveAliasPath('./packages/material-ui-utils/src'),\n",
"};\n",
"\n",
"const productionPlugins = [\n",
" '@babel/plugin-transform-react-constant-elements',\n",
" ['babel-plugin-react-remove-properties', { properties: ['data-mui-test'] }],\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [],
"file_path": "babel.config.js",
"type": "replace",
"edit_start_line_idx": 25
} | const path = require('path');
const React = require('react');
const errorCodesPath = path.resolve(__dirname, './docs/public/static/error-codes.json');
const missingError = process.env.MUI_EXTRACT_ERROR_CODES === 'true' ? 'write' : 'annotate';
function resolveAliasPath(relativeToBabelConf) {
const resolvedPath = path.relative(process.cwd(), path.resolve(__dirname, relativeToBabelConf));
return `./${resolvedPath.replace('\\', '/')}`;
}
const defaultAlias = {
'@material-ui/core': resolveAliasPath('./packages/material-ui/src'),
'@material-ui/docs': resolveAliasPath('./packages/material-ui-docs/src'),
'@material-ui/icons': resolveAliasPath('./packages/material-ui-icons/src'),
'@material-ui/lab': resolveAliasPath('./packages/material-ui-lab/src'),
'@material-ui/styled-engine': resolveAliasPath('./packages/material-ui-styled-engine/src'),
'@material-ui/styled-engine-sc': resolveAliasPath('./packages/material-ui-styled-engine-sc/src'),
'@material-ui/styles': resolveAliasPath('./packages/material-ui-styles/src'),
'@material-ui/system': resolveAliasPath('./packages/material-ui-system/src'),
'@material-ui/unstyled': resolveAliasPath('./packages/material-ui-unstyled/src'),
'@material-ui/utils': resolveAliasPath('./packages/material-ui-utils/src'),
};
const productionPlugins = [
'@babel/plugin-transform-react-constant-elements',
['babel-plugin-react-remove-properties', { properties: ['data-mui-test'] }],
[
'babel-plugin-transform-react-remove-prop-types',
{
mode: 'unsafe-wrap',
},
],
];
module.exports = function getBabelConfig(api) {
const useESModules = api.env(['legacy', 'modern', 'stable', 'rollup']);
const presets = [
[
'@babel/preset-env',
{
bugfixes: true,
browserslistEnv: process.env.BABEL_ENV || process.env.NODE_ENV,
debug: process.env.MUI_BUILD_VERBOSE === 'true',
modules: useESModules ? false : 'commonjs',
shippedProposals: api.env('modern'),
},
],
[
'@babel/preset-react',
{
runtime: React.version.startsWith('16')
? 'classic'
: // default in Babel 8
'automatic',
},
],
'@babel/preset-typescript',
];
const plugins = [
[
'babel-plugin-macros',
{
muiError: {
errorCodesPath,
missingError,
},
},
],
'babel-plugin-optimize-clsx',
// Need the following 3 proposals for all targets in .browserslistrc.
// With our usage the transpiled loose mode is equivalent to spec mode.
['@babel/plugin-proposal-class-properties', { loose: true }],
['@babel/plugin-proposal-private-methods', { loose: true }],
['@babel/plugin-proposal-object-rest-spread', { loose: true }],
[
'@babel/plugin-transform-runtime',
{
useESModules,
// any package needs to declare 7.4.4 as a runtime dependency. default is ^7.0.0
version: '^7.4.4',
},
],
];
if (process.env.NODE_ENV === 'production') {
plugins.push(...productionPlugins);
}
if (process.env.NODE_ENV === 'test') {
plugins.push([
'babel-plugin-module-resolver',
{
alias: defaultAlias,
root: ['./'],
},
]);
}
return {
presets,
plugins,
ignore: [/@babel[\\|/]runtime/], // Fix a Windows issue.
env: {
coverage: {
plugins: [
'babel-plugin-istanbul',
[
'babel-plugin-module-resolver',
{
root: ['./'],
alias: defaultAlias,
},
],
],
},
development: {
plugins: [
[
'babel-plugin-module-resolver',
{
alias: {
...defaultAlias,
modules: './modules',
'typescript-to-proptypes': './packages/typescript-to-proptypes/src',
},
root: ['./'],
},
],
],
},
legacy: {
plugins: [
// IE11 support
'@babel/plugin-transform-object-assign',
],
},
test: {
sourceMaps: 'both',
plugins: [
[
'babel-plugin-module-resolver',
{
root: ['./'],
alias: defaultAlias,
},
],
],
},
benchmark: {
plugins: [
...productionPlugins,
[
'babel-plugin-module-resolver',
{
alias: defaultAlias,
},
],
],
},
},
};
};
| babel.config.js | 1 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.9991374015808105,
0.2161967009305954,
0.00017252466932404786,
0.02177146077156067,
0.3704439699649811
] |
{
"id": 0,
"code_window": [
" '@material-ui/utils': resolveAliasPath('./packages/material-ui-utils/src'),\n",
"};\n",
"\n",
"const productionPlugins = [\n",
" '@babel/plugin-transform-react-constant-elements',\n",
" ['babel-plugin-react-remove-properties', { properties: ['data-mui-test'] }],\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [],
"file_path": "babel.config.js",
"type": "replace",
"edit_start_line_idx": 25
} | /* tslint:disable max-line-length */
/**
*              
*/
declare const cyan: {
/**
* Preview: 
*/
50: '#e0f7fa';
/**
* Preview: 
*/
100: '#b2ebf2';
/**
* Preview: 
*/
200: '#80deea';
/**
* Preview: 
*/
300: '#4dd0e1';
/**
* Preview: 
*/
400: '#26c6da';
/**
* Preview: 
*/
500: '#00bcd4';
/**
* Preview: 
*/
600: '#00acc1';
/**
* Preview: 
*/
700: '#0097a7';
/**
* Preview: 
*/
800: '#00838f';
/**
* Preview: 
*/
900: '#006064';
/**
* Preview: 
*/
A100: '#84ffff';
/**
* Preview: 
*/
A200: '#18ffff';
/**
* Preview: 
*/
A400: '#00e5ff';
/**
* Preview: 
*/
A700: '#00b8d4';
};
export default cyan;
| packages/material-ui/src/colors/cyan.d.ts | 0 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.0009501862223260105,
0.00044811383122578263,
0.00017396063776686788,
0.00038922482053749263,
0.00022990009165368974
] |
{
"id": 0,
"code_window": [
" '@material-ui/utils': resolveAliasPath('./packages/material-ui-utils/src'),\n",
"};\n",
"\n",
"const productionPlugins = [\n",
" '@babel/plugin-transform-react-constant-elements',\n",
" ['babel-plugin-react-remove-properties', { properties: ['data-mui-test'] }],\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [],
"file_path": "babel.config.js",
"type": "replace",
"edit_start_line_idx": 25
} | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M19 10.41V15h2V7h-8v2h4.59L12 14.59 4.41 7 3 8.41l9 9z" />
, 'CallMissedOutgoingTwoTone');
| packages/material-ui-icons/src/CallMissedOutgoingTwoTone.js | 0 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.0002589537180028856,
0.0002589537180028856,
0.0002589537180028856,
0.0002589537180028856,
0
] |
{
"id": 0,
"code_window": [
" '@material-ui/utils': resolveAliasPath('./packages/material-ui-utils/src'),\n",
"};\n",
"\n",
"const productionPlugins = [\n",
" '@babel/plugin-transform-react-constant-elements',\n",
" ['babel-plugin-react-remove-properties', { properties: ['data-mui-test'] }],\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [],
"file_path": "babel.config.js",
"type": "replace",
"edit_start_line_idx": 25
} | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M7 17h14V3H7v14zm5-12h4v10h-2V7h-2V5z" opacity=".3" /><path d="M14 15h2V5h-4v2h2zm7-14H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14zM1 5v16c0 1.1.9 2 2 2h16v-2H3V5H1z" /></React.Fragment>
, 'Filter1TwoTone');
| packages/material-ui-icons/src/Filter1TwoTone.js | 0 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.00022598789655603468,
0.00022598789655603468,
0.00022598789655603468,
0.00022598789655603468,
0
] |
{
"id": 1,
"code_window": [
" ['babel-plugin-react-remove-properties', { properties: ['data-mui-test'] }],\n",
" [\n",
" 'babel-plugin-transform-react-remove-prop-types',\n",
" {\n",
" mode: 'unsafe-wrap',\n",
" },\n",
" ],\n",
"];\n",
"\n",
"module.exports = function getBabelConfig(api) {\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "babel.config.js",
"type": "replace",
"edit_start_line_idx": 27
} | const path = require('path');
const React = require('react');
const errorCodesPath = path.resolve(__dirname, './docs/public/static/error-codes.json');
const missingError = process.env.MUI_EXTRACT_ERROR_CODES === 'true' ? 'write' : 'annotate';
function resolveAliasPath(relativeToBabelConf) {
const resolvedPath = path.relative(process.cwd(), path.resolve(__dirname, relativeToBabelConf));
return `./${resolvedPath.replace('\\', '/')}`;
}
const defaultAlias = {
'@material-ui/core': resolveAliasPath('./packages/material-ui/src'),
'@material-ui/docs': resolveAliasPath('./packages/material-ui-docs/src'),
'@material-ui/icons': resolveAliasPath('./packages/material-ui-icons/src'),
'@material-ui/lab': resolveAliasPath('./packages/material-ui-lab/src'),
'@material-ui/styled-engine': resolveAliasPath('./packages/material-ui-styled-engine/src'),
'@material-ui/styled-engine-sc': resolveAliasPath('./packages/material-ui-styled-engine-sc/src'),
'@material-ui/styles': resolveAliasPath('./packages/material-ui-styles/src'),
'@material-ui/system': resolveAliasPath('./packages/material-ui-system/src'),
'@material-ui/unstyled': resolveAliasPath('./packages/material-ui-unstyled/src'),
'@material-ui/utils': resolveAliasPath('./packages/material-ui-utils/src'),
};
const productionPlugins = [
'@babel/plugin-transform-react-constant-elements',
['babel-plugin-react-remove-properties', { properties: ['data-mui-test'] }],
[
'babel-plugin-transform-react-remove-prop-types',
{
mode: 'unsafe-wrap',
},
],
];
module.exports = function getBabelConfig(api) {
const useESModules = api.env(['legacy', 'modern', 'stable', 'rollup']);
const presets = [
[
'@babel/preset-env',
{
bugfixes: true,
browserslistEnv: process.env.BABEL_ENV || process.env.NODE_ENV,
debug: process.env.MUI_BUILD_VERBOSE === 'true',
modules: useESModules ? false : 'commonjs',
shippedProposals: api.env('modern'),
},
],
[
'@babel/preset-react',
{
runtime: React.version.startsWith('16')
? 'classic'
: // default in Babel 8
'automatic',
},
],
'@babel/preset-typescript',
];
const plugins = [
[
'babel-plugin-macros',
{
muiError: {
errorCodesPath,
missingError,
},
},
],
'babel-plugin-optimize-clsx',
// Need the following 3 proposals for all targets in .browserslistrc.
// With our usage the transpiled loose mode is equivalent to spec mode.
['@babel/plugin-proposal-class-properties', { loose: true }],
['@babel/plugin-proposal-private-methods', { loose: true }],
['@babel/plugin-proposal-object-rest-spread', { loose: true }],
[
'@babel/plugin-transform-runtime',
{
useESModules,
// any package needs to declare 7.4.4 as a runtime dependency. default is ^7.0.0
version: '^7.4.4',
},
],
];
if (process.env.NODE_ENV === 'production') {
plugins.push(...productionPlugins);
}
if (process.env.NODE_ENV === 'test') {
plugins.push([
'babel-plugin-module-resolver',
{
alias: defaultAlias,
root: ['./'],
},
]);
}
return {
presets,
plugins,
ignore: [/@babel[\\|/]runtime/], // Fix a Windows issue.
env: {
coverage: {
plugins: [
'babel-plugin-istanbul',
[
'babel-plugin-module-resolver',
{
root: ['./'],
alias: defaultAlias,
},
],
],
},
development: {
plugins: [
[
'babel-plugin-module-resolver',
{
alias: {
...defaultAlias,
modules: './modules',
'typescript-to-proptypes': './packages/typescript-to-proptypes/src',
},
root: ['./'],
},
],
],
},
legacy: {
plugins: [
// IE11 support
'@babel/plugin-transform-object-assign',
],
},
test: {
sourceMaps: 'both',
plugins: [
[
'babel-plugin-module-resolver',
{
root: ['./'],
alias: defaultAlias,
},
],
],
},
benchmark: {
plugins: [
...productionPlugins,
[
'babel-plugin-module-resolver',
{
alias: defaultAlias,
},
],
],
},
},
};
};
| babel.config.js | 1 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.9958784580230713,
0.06584230065345764,
0.0001660229463595897,
0.0003028977371286601,
0.23414573073387146
] |
{
"id": 1,
"code_window": [
" ['babel-plugin-react-remove-properties', { properties: ['data-mui-test'] }],\n",
" [\n",
" 'babel-plugin-transform-react-remove-prop-types',\n",
" {\n",
" mode: 'unsafe-wrap',\n",
" },\n",
" ],\n",
"];\n",
"\n",
"module.exports = function getBabelConfig(api) {\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "babel.config.js",
"type": "replace",
"edit_start_line_idx": 27
} | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M22 11V3h-7v3H9V3H2v8h7V8h2v10h4v3h7v-8h-7v3h-2V8h2v3h7zM7 9H4V5h3v4zm10 6h3v4h-3v-4zm0-10h3v4h-3V5z" /><path d="M7 5v4H4V5h3m13 0v4h-3V5h3m0 10v4h-3v-4h3" opacity=".3" /></React.Fragment>
, 'AccountTreeTwoTone');
| packages/material-ui-icons/src/AccountTreeTwoTone.js | 0 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.00017302020569331944,
0.00017302020569331944,
0.00017302020569331944,
0.00017302020569331944,
0
] |
{
"id": 1,
"code_window": [
" ['babel-plugin-react-remove-properties', { properties: ['data-mui-test'] }],\n",
" [\n",
" 'babel-plugin-transform-react-remove-prop-types',\n",
" {\n",
" mode: 'unsafe-wrap',\n",
" },\n",
" ],\n",
"];\n",
"\n",
"module.exports = function getBabelConfig(api) {\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "babel.config.js",
"type": "replace",
"edit_start_line_idx": 27
} | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M10 19h4v-3h-4v3zM5 4v3h5v3h4V7h5V4H5zM3 14h18v-2H3v2z" />
, 'FormatStrikethroughOutlined');
| packages/material-ui-icons/src/FormatStrikethroughOutlined.js | 0 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.00017256777209695429,
0.00017256777209695429,
0.00017256777209695429,
0.00017256777209695429,
0
] |
{
"id": 1,
"code_window": [
" ['babel-plugin-react-remove-properties', { properties: ['data-mui-test'] }],\n",
" [\n",
" 'babel-plugin-transform-react-remove-prop-types',\n",
" {\n",
" mode: 'unsafe-wrap',\n",
" },\n",
" ],\n",
"];\n",
"\n",
"module.exports = function getBabelConfig(api) {\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "babel.config.js",
"type": "replace",
"edit_start_line_idx": 27
} | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M21.6 18.2L13 11.75v-.91c1.65-.49 2.8-2.17 2.43-4.05-.26-1.31-1.3-2.4-2.61-2.7C10.54 3.57 8.5 5.3 8.5 7.5h2c0-.83.67-1.5 1.5-1.5s1.5.67 1.5 1.5c0 .84-.69 1.52-1.53 1.5H11v2.75L2.4 18.2c-.77.58-.36 1.8.6 1.8h18c.96 0 1.37-1.22.6-1.8zM6 18l6-4.5 6 4.5H6z" />
, 'CheckroomSharp');
| packages/material-ui-icons/src/CheckroomSharp.js | 0 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.00017326322267763317,
0.00017326322267763317,
0.00017326322267763317,
0.00017326322267763317,
0
] |
{
"id": 2,
"code_window": [
" version: '^7.4.4',\n",
" },\n",
" ],\n",
" ];\n",
"\n",
" if (process.env.NODE_ENV === 'production') {\n",
" plugins.push(...productionPlugins);\n",
" }\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" '@babel/plugin-transform-react-constant-elements',\n",
" [\n",
" 'babel-plugin-transform-react-remove-prop-types',\n",
" {\n",
" mode: 'unsafe-wrap',\n",
" },\n",
" ],\n"
],
"file_path": "babel.config.js",
"type": "add",
"edit_start_line_idx": 85
} | import * as Mocha from 'mocha';
import { expect } from 'chai';
import * as React from 'react';
import { stub } from 'sinon';
import { createMochaHooks } from './mochaHooks';
import { createClientRender } from './createClientRender';
describe('mochaHooks', () => {
// one block per hook.
describe('afterEach', () => {
describe('throws on unexpected console.(warn|error) in afterEach', function suite() {
const mochaHooks = createMochaHooks(Mocha);
beforeEach(function beforeEachHook() {
mochaHooks.beforeAll.forEach((beforeAllMochaHook) => {
beforeAllMochaHook.call(this);
});
mochaHooks.beforeEach.forEach((beforeEachMochaHook) => {
beforeEachMochaHook.call(this);
});
});
it('', () => {
console.warn('unexpected warning');
console.error('unexpected error');
});
afterEach(function afterEachHook() {
const errorStub = stub(this.test, 'error');
mochaHooks.afterEach.forEach((afterEachMochaHook) => {
afterEachMochaHook.call(this);
});
mochaHooks.afterAll.forEach((afterAllMochaHook) => {
afterAllMochaHook.call(this);
});
expect(errorStub.callCount).to.equal(2);
expect(String(errorStub.firstCall.args[0])).to.include(
'console.warn message #1:\n unexpected warning\n\nStack:',
);
expect(String(errorStub.secondCall.args[0])).to.include(
'console.error message #1:\n unexpected error\n\nStack:',
);
});
});
describe('dedupes missing act() warnings by component', () => {
const mochaHooks = createMochaHooks(Mocha);
const render = createClientRender();
beforeEach(function beforeEachHook() {
mochaHooks.beforeAll.forEach((beforeAllMochaHook) => {
beforeAllMochaHook.call(this);
});
mochaHooks.beforeEach.forEach((beforeEachMochaHook) => {
beforeEachMochaHook.call(this);
});
});
it('', () => {
const Child = React.forwardRef(function Child() {
React.useEffect(() => {});
React.useEffect(() => {});
return null;
});
let setState;
function Parent() {
setState = React.useState(0)[1];
React.useEffect(() => {});
React.useEffect(() => {});
return <Child />;
}
render(<Parent />);
// not wrapped in act()
setState(1);
});
afterEach(function afterEachHook() {
const errorStub = stub(this.test, 'error');
mochaHooks.afterEach.forEach((afterEachMochaHook) => {
afterEachMochaHook.call(this);
});
mochaHooks.afterAll.forEach((afterAllMochaHook) => {
afterAllMochaHook.call(this);
});
expect(errorStub.callCount).to.equal(1);
const error = String(errorStub.firstCall.args[0]);
expect(
error.match(/An update to Parent inside a test was not wrapped in act/g),
).to.have.lengthOf(1);
expect(
error.match(/An update to Parent ran an effect, but was not wrapped in act/g),
).to.have.lengthOf(1);
expect(
error.match(
/An update to ForwardRef\(Child\) ran an effect, but was not wrapped in act/g,
),
).to.have.lengthOf(1);
});
});
});
});
| test/utils/mochaHooks.test.js | 1 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.00017494973144493997,
0.0001718709390843287,
0.00016880333714652807,
0.00017165254394058138,
0.0000017433117136533838
] |
{
"id": 2,
"code_window": [
" version: '^7.4.4',\n",
" },\n",
" ],\n",
" ];\n",
"\n",
" if (process.env.NODE_ENV === 'production') {\n",
" plugins.push(...productionPlugins);\n",
" }\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" '@babel/plugin-transform-react-constant-elements',\n",
" [\n",
" 'babel-plugin-transform-react-remove-prop-types',\n",
" {\n",
" mode: 'unsafe-wrap',\n",
" },\n",
" ],\n"
],
"file_path": "babel.config.js",
"type": "add",
"edit_start_line_idx": 85
} | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-9 9.5H8v1h3V15H6.5v-2.5c0-.55.45-1 1-1h2v-1h-3V9H10c.55 0 1 .45 1 1v1.5c0 .55-.45 1-1 1zm8 2.5h-1.75l-1.75-2.25V15H13V9h1.5v2.25L16.25 9H18l-2.25 3L18 15z" />
, 'TwoK');
| packages/material-ui-icons/src/TwoK.js | 0 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.00017224949260707945,
0.00017224949260707945,
0.00017224949260707945,
0.00017224949260707945,
0
] |
{
"id": 2,
"code_window": [
" version: '^7.4.4',\n",
" },\n",
" ],\n",
" ];\n",
"\n",
" if (process.env.NODE_ENV === 'production') {\n",
" plugins.push(...productionPlugins);\n",
" }\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" '@babel/plugin-transform-react-constant-elements',\n",
" [\n",
" 'babel-plugin-transform-react-remove-prop-types',\n",
" {\n",
" mode: 'unsafe-wrap',\n",
" },\n",
" ],\n"
],
"file_path": "babel.config.js",
"type": "add",
"edit_start_line_idx": 85
} | import { ListItemIconClassKey } from './ListItemIcon';
export type ListItemIconClasses = Record<ListItemIconClassKey, string>;
declare const listItemIconClasses: ListItemIconClasses;
export function getListItemIconUtilityClass(slot: string): string;
export default listItemIconClasses;
| packages/material-ui/src/ListItemIcon/listItemIconClasses.d.ts | 0 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.00017091464542318135,
0.00017091464542318135,
0.00017091464542318135,
0.00017091464542318135,
0
] |
{
"id": 2,
"code_window": [
" version: '^7.4.4',\n",
" },\n",
" ],\n",
" ];\n",
"\n",
" if (process.env.NODE_ENV === 'production') {\n",
" plugins.push(...productionPlugins);\n",
" }\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" '@babel/plugin-transform-react-constant-elements',\n",
" [\n",
" 'babel-plugin-transform-react-remove-prop-types',\n",
" {\n",
" mode: 'unsafe-wrap',\n",
" },\n",
" ],\n"
],
"file_path": "babel.config.js",
"type": "add",
"edit_start_line_idx": 85
} | import * as React from 'react';
import { experimentalStyled as styled } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import Box from '@material-ui/core/Box';
import Grid from '@material-ui/core/Grid';
const Item = styled(Paper)(({ theme }) => ({
padding: theme.spacing(2),
textAlign: 'center',
color: theme.palette.text.secondary,
}));
export default function CenteredGrid() {
return (
<Box sx={{ flexGrow: 1 }}>
<Grid container spacing={3}>
<Grid item xs={12}>
<Item>xs=12</Item>
</Grid>
<Grid item xs={6}>
<Item>xs=6</Item>
</Grid>
<Grid item xs={6}>
<Item>xs=6</Item>
</Grid>
<Grid item xs={3}>
<Item>xs=3</Item>
</Grid>
<Grid item xs={3}>
<Item>xs=3</Item>
</Grid>
<Grid item xs={3}>
<Item>xs=3</Item>
</Grid>
<Grid item xs={3}>
<Item>xs=3</Item>
</Grid>
</Grid>
</Box>
);
}
| docs/src/pages/components/grid/CenteredGrid.js | 0 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.0001746583729982376,
0.00017325946828350425,
0.00017041165847331285,
0.00017355622549075633,
0.0000014986709402364795
] |
{
"id": 3,
"code_window": [
" return null;\n",
" });\n",
"\n",
" let setState;\n",
" function Parent() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" let unsafeSetState;\n"
],
"file_path": "test/utils/mochaHooks.test.js",
"type": "replace",
"edit_start_line_idx": 66
} | const path = require('path');
const React = require('react');
const errorCodesPath = path.resolve(__dirname, './docs/public/static/error-codes.json');
const missingError = process.env.MUI_EXTRACT_ERROR_CODES === 'true' ? 'write' : 'annotate';
function resolveAliasPath(relativeToBabelConf) {
const resolvedPath = path.relative(process.cwd(), path.resolve(__dirname, relativeToBabelConf));
return `./${resolvedPath.replace('\\', '/')}`;
}
const defaultAlias = {
'@material-ui/core': resolveAliasPath('./packages/material-ui/src'),
'@material-ui/docs': resolveAliasPath('./packages/material-ui-docs/src'),
'@material-ui/icons': resolveAliasPath('./packages/material-ui-icons/src'),
'@material-ui/lab': resolveAliasPath('./packages/material-ui-lab/src'),
'@material-ui/styled-engine': resolveAliasPath('./packages/material-ui-styled-engine/src'),
'@material-ui/styled-engine-sc': resolveAliasPath('./packages/material-ui-styled-engine-sc/src'),
'@material-ui/styles': resolveAliasPath('./packages/material-ui-styles/src'),
'@material-ui/system': resolveAliasPath('./packages/material-ui-system/src'),
'@material-ui/unstyled': resolveAliasPath('./packages/material-ui-unstyled/src'),
'@material-ui/utils': resolveAliasPath('./packages/material-ui-utils/src'),
};
const productionPlugins = [
'@babel/plugin-transform-react-constant-elements',
['babel-plugin-react-remove-properties', { properties: ['data-mui-test'] }],
[
'babel-plugin-transform-react-remove-prop-types',
{
mode: 'unsafe-wrap',
},
],
];
module.exports = function getBabelConfig(api) {
const useESModules = api.env(['legacy', 'modern', 'stable', 'rollup']);
const presets = [
[
'@babel/preset-env',
{
bugfixes: true,
browserslistEnv: process.env.BABEL_ENV || process.env.NODE_ENV,
debug: process.env.MUI_BUILD_VERBOSE === 'true',
modules: useESModules ? false : 'commonjs',
shippedProposals: api.env('modern'),
},
],
[
'@babel/preset-react',
{
runtime: React.version.startsWith('16')
? 'classic'
: // default in Babel 8
'automatic',
},
],
'@babel/preset-typescript',
];
const plugins = [
[
'babel-plugin-macros',
{
muiError: {
errorCodesPath,
missingError,
},
},
],
'babel-plugin-optimize-clsx',
// Need the following 3 proposals for all targets in .browserslistrc.
// With our usage the transpiled loose mode is equivalent to spec mode.
['@babel/plugin-proposal-class-properties', { loose: true }],
['@babel/plugin-proposal-private-methods', { loose: true }],
['@babel/plugin-proposal-object-rest-spread', { loose: true }],
[
'@babel/plugin-transform-runtime',
{
useESModules,
// any package needs to declare 7.4.4 as a runtime dependency. default is ^7.0.0
version: '^7.4.4',
},
],
];
if (process.env.NODE_ENV === 'production') {
plugins.push(...productionPlugins);
}
if (process.env.NODE_ENV === 'test') {
plugins.push([
'babel-plugin-module-resolver',
{
alias: defaultAlias,
root: ['./'],
},
]);
}
return {
presets,
plugins,
ignore: [/@babel[\\|/]runtime/], // Fix a Windows issue.
env: {
coverage: {
plugins: [
'babel-plugin-istanbul',
[
'babel-plugin-module-resolver',
{
root: ['./'],
alias: defaultAlias,
},
],
],
},
development: {
plugins: [
[
'babel-plugin-module-resolver',
{
alias: {
...defaultAlias,
modules: './modules',
'typescript-to-proptypes': './packages/typescript-to-proptypes/src',
},
root: ['./'],
},
],
],
},
legacy: {
plugins: [
// IE11 support
'@babel/plugin-transform-object-assign',
],
},
test: {
sourceMaps: 'both',
plugins: [
[
'babel-plugin-module-resolver',
{
root: ['./'],
alias: defaultAlias,
},
],
],
},
benchmark: {
plugins: [
...productionPlugins,
[
'babel-plugin-module-resolver',
{
alias: defaultAlias,
},
],
],
},
},
};
};
| babel.config.js | 1 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.0001710051146801561,
0.00016762687300797552,
0.00016472613788209856,
0.0001676222018431872,
0.0000016968709815046168
] |
{
"id": 3,
"code_window": [
" return null;\n",
" });\n",
"\n",
" let setState;\n",
" function Parent() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" let unsafeSetState;\n"
],
"file_path": "test/utils/mochaHooks.test.js",
"type": "replace",
"edit_start_line_idx": 66
} | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M15 16h4v2h-4zm0-8h7v2h-7zm0 4h6v2h-6zM3 18c0 1.1.9 2 2 2h6c1.1 0 2-.9 2-2V8H3v10zm2-8h6v8H5v-8zm5-6H6L5 5H2v2h12V5h-3z" />
, 'DeleteSweepOutlined');
| packages/material-ui-icons/src/DeleteSweepOutlined.js | 0 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.00017082260455936193,
0.00017082260455936193,
0.00017082260455936193,
0.00017082260455936193,
0
] |
{
"id": 3,
"code_window": [
" return null;\n",
" });\n",
"\n",
" let setState;\n",
" function Parent() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" let unsafeSetState;\n"
],
"file_path": "test/utils/mochaHooks.test.js",
"type": "replace",
"edit_start_line_idx": 66
} | import './utils/init';
import './utils/setupKarma';
const integrationContext = require.context(
'../packages/material-ui/test/integration',
true,
/\.test\.(js|ts|tsx)$/,
);
integrationContext.keys().forEach(integrationContext);
const coreUnitContext = require.context(
'../packages/material-ui/src/',
true,
/\.test\.(js|ts|tsx)$/,
);
coreUnitContext.keys().forEach(coreUnitContext);
const labUnitContext = require.context(
'../packages/material-ui-lab/src/',
true,
/\.test\.(js|ts|tsx)$/,
);
labUnitContext.keys().forEach(labUnitContext);
const styledEngineContext = require.context(
'../packages/material-ui-styled-engine/src/',
true,
/\.test\.(js|ts|tsx)$/,
);
styledEngineContext.keys().forEach(styledEngineContext);
const styledEngineSCContext = require.context(
'../packages/material-ui-styled-engine-sc/src/',
true,
/\.test\.(js|ts|tsx)$/,
);
styledEngineSCContext.keys().forEach(styledEngineSCContext);
const systemContext = require.context(
'../packages/material-ui-system/src/',
true,
/\.test\.(js|ts|tsx)$/,
);
systemContext.keys().forEach(systemContext);
const unstyledContext = require.context(
'../packages/material-ui-unstyled/src/',
true,
/\.test\.(js|ts|tsx)$/,
);
unstyledContext.keys().forEach(unstyledContext);
| test/karma.tests.js | 0 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.00017355853924527764,
0.0001699268614174798,
0.00016690515622030944,
0.0001697793632047251,
0.00000194321182789281
] |
{
"id": 3,
"code_window": [
" return null;\n",
" });\n",
"\n",
" let setState;\n",
" function Parent() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" let unsafeSetState;\n"
],
"file_path": "test/utils/mochaHooks.test.js",
"type": "replace",
"edit_start_line_idx": 66
} | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M14 12l-2 2-2-2 2-2 2 2zm-2-6l2.12 2.12 2.5-2.5L12 1 7.38 5.62l2.5 2.5L12 6zm-6 6l2.12-2.12-2.5-2.5L1 12l4.62 4.62 2.5-2.5L6 12zm12 0l-2.12 2.12 2.5 2.5L23 12l-4.62-4.62-2.5 2.5L18 12zm-6 6l-2.12-2.12-2.5 2.5L12 23l4.62-4.62-2.5-2.5L12 18z" />
, 'ApiSharp');
| packages/material-ui-icons/src/ApiSharp.js | 0 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.00017064304847735912,
0.00017064304847735912,
0.00017064304847735912,
0.00017064304847735912,
0
] |
{
"id": 4,
"code_window": [
" function Parent() {\n",
" setState = React.useState(0)[1];\n",
" React.useEffect(() => {});\n",
" React.useEffect(() => {});\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const [state, setState] = React.useState(0);\n",
" unsafeSetState = setState;\n",
"\n"
],
"file_path": "test/utils/mochaHooks.test.js",
"type": "replace",
"edit_start_line_idx": 68
} | import * as Mocha from 'mocha';
import { expect } from 'chai';
import * as React from 'react';
import { stub } from 'sinon';
import { createMochaHooks } from './mochaHooks';
import { createClientRender } from './createClientRender';
describe('mochaHooks', () => {
// one block per hook.
describe('afterEach', () => {
describe('throws on unexpected console.(warn|error) in afterEach', function suite() {
const mochaHooks = createMochaHooks(Mocha);
beforeEach(function beforeEachHook() {
mochaHooks.beforeAll.forEach((beforeAllMochaHook) => {
beforeAllMochaHook.call(this);
});
mochaHooks.beforeEach.forEach((beforeEachMochaHook) => {
beforeEachMochaHook.call(this);
});
});
it('', () => {
console.warn('unexpected warning');
console.error('unexpected error');
});
afterEach(function afterEachHook() {
const errorStub = stub(this.test, 'error');
mochaHooks.afterEach.forEach((afterEachMochaHook) => {
afterEachMochaHook.call(this);
});
mochaHooks.afterAll.forEach((afterAllMochaHook) => {
afterAllMochaHook.call(this);
});
expect(errorStub.callCount).to.equal(2);
expect(String(errorStub.firstCall.args[0])).to.include(
'console.warn message #1:\n unexpected warning\n\nStack:',
);
expect(String(errorStub.secondCall.args[0])).to.include(
'console.error message #1:\n unexpected error\n\nStack:',
);
});
});
describe('dedupes missing act() warnings by component', () => {
const mochaHooks = createMochaHooks(Mocha);
const render = createClientRender();
beforeEach(function beforeEachHook() {
mochaHooks.beforeAll.forEach((beforeAllMochaHook) => {
beforeAllMochaHook.call(this);
});
mochaHooks.beforeEach.forEach((beforeEachMochaHook) => {
beforeEachMochaHook.call(this);
});
});
it('', () => {
const Child = React.forwardRef(function Child() {
React.useEffect(() => {});
React.useEffect(() => {});
return null;
});
let setState;
function Parent() {
setState = React.useState(0)[1];
React.useEffect(() => {});
React.useEffect(() => {});
return <Child />;
}
render(<Parent />);
// not wrapped in act()
setState(1);
});
afterEach(function afterEachHook() {
const errorStub = stub(this.test, 'error');
mochaHooks.afterEach.forEach((afterEachMochaHook) => {
afterEachMochaHook.call(this);
});
mochaHooks.afterAll.forEach((afterAllMochaHook) => {
afterAllMochaHook.call(this);
});
expect(errorStub.callCount).to.equal(1);
const error = String(errorStub.firstCall.args[0]);
expect(
error.match(/An update to Parent inside a test was not wrapped in act/g),
).to.have.lengthOf(1);
expect(
error.match(/An update to Parent ran an effect, but was not wrapped in act/g),
).to.have.lengthOf(1);
expect(
error.match(
/An update to ForwardRef\(Child\) ran an effect, but was not wrapped in act/g,
),
).to.have.lengthOf(1);
});
});
});
});
| test/utils/mochaHooks.test.js | 1 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.9980689883232117,
0.26867663860321045,
0.00016793159011285752,
0.000173350956174545,
0.4385248124599457
] |
{
"id": 4,
"code_window": [
" function Parent() {\n",
" setState = React.useState(0)[1];\n",
" React.useEffect(() => {});\n",
" React.useEffect(() => {});\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const [state, setState] = React.useState(0);\n",
" unsafeSetState = setState;\n",
"\n"
],
"file_path": "test/utils/mochaHooks.test.js",
"type": "replace",
"edit_start_line_idx": 68
} | import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { usePreviousProps, deepmerge } from '@material-ui/utils';
import { generateUtilityClasses, isHostComponent } from '@material-ui/unstyled';
import BadgeUnstyled, {
badgeUnstyledClasses,
getBadgeUtilityClass,
} from '@material-ui/unstyled/BadgeUnstyled';
import styled from '../styles/experimentalStyled';
import useThemeProps from '../styles/useThemeProps';
import capitalize from '../utils/capitalize';
export const badgeClasses = {
...badgeUnstyledClasses,
...generateUtilityClasses('MuiBadge', ['colorError', 'colorPrimary', 'colorSecondary']),
};
const RADIUS_STANDARD = 10;
const RADIUS_DOT = 4;
const overridesResolver = (props, styles) => {
const { styleProps } = props;
return deepmerge(
{
[`& .${badgeClasses.badge}`]: {
...styles.badge,
...styles[styleProps.variant],
...styles[
`anchorOrigin${capitalize(styleProps.anchorOrigin.vertical)}${capitalize(
styleProps.anchorOrigin.horizontal,
)}${capitalize(styleProps.overlap)}`
],
...(styleProps.color !== 'default' && styles[`color${capitalize(styleProps.color)}`]),
...(styleProps.invisible && styles.invisible),
},
},
styles.root || {},
);
};
const extendUtilityClasses = (styleProps) => {
const { color, classes = {} } = styleProps;
return {
...classes,
badge: clsx(classes.badge, {
[getBadgeUtilityClass(`color${capitalize(color)}`)]: color !== 'default',
[classes[`color${capitalize(color)}`]]: color !== 'default',
}),
};
};
const BadgeRoot = styled(
'span',
{},
{ name: 'MuiBadge', slot: 'Root', overridesResolver },
)({
position: 'relative',
display: 'inline-flex',
// For correct alignment with the text.
verticalAlign: 'middle',
flexShrink: 0,
});
const BadgeBadge = styled(
'span',
{},
{ name: 'MuiBadge', slot: 'Badge', overridesResolver },
)(({ theme, styleProps }) => ({
display: 'flex',
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'center',
alignContent: 'center',
alignItems: 'center',
position: 'absolute',
boxSizing: 'border-box',
fontFamily: theme.typography.fontFamily,
fontWeight: theme.typography.fontWeightMedium,
fontSize: theme.typography.pxToRem(12),
minWidth: RADIUS_STANDARD * 2,
lineHeight: 1,
padding: '0 6px',
height: RADIUS_STANDARD * 2,
borderRadius: RADIUS_STANDARD,
zIndex: 1, // Render the badge on top of potential ripples.
transition: theme.transitions.create('transform', {
easing: theme.transitions.easing.easeInOut,
duration: theme.transitions.duration.enteringScreen,
}),
...(styleProps.color !== 'default' && {
backgroundColor: theme.palette[styleProps.color].main,
color: theme.palette[styleProps.color].contrastText,
}),
...(styleProps.variant === 'dot' && {
borderRadius: RADIUS_DOT,
height: RADIUS_DOT * 2,
minWidth: RADIUS_DOT * 2,
padding: 0,
}),
...(styleProps.anchorOrigin.vertical === 'top' &&
styleProps.anchorOrigin.horizontal === 'right' &&
styleProps.overlap === 'rectangular' && {
top: 0,
right: 0,
transform: 'scale(1) translate(50%, -50%)',
transformOrigin: '100% 0%',
[`&.${badgeClasses.invisible}`]: {
transform: 'scale(0) translate(50%, -50%)',
},
}),
...(styleProps.anchorOrigin.vertical === 'bottom' &&
styleProps.anchorOrigin.horizontal === 'right' &&
styleProps.overlap === 'rectangular' && {
bottom: 0,
right: 0,
transform: 'scale(1) translate(50%, 50%)',
transformOrigin: '100% 100%',
[`&.${badgeClasses.invisible}`]: {
transform: 'scale(0) translate(50%, 50%)',
},
}),
...(styleProps.anchorOrigin.vertical === 'top' &&
styleProps.anchorOrigin.horizontal === 'left' &&
styleProps.overlap === 'rectangular' && {
top: 0,
left: 0,
transform: 'scale(1) translate(-50%, -50%)',
transformOrigin: '0% 0%',
[`&.${badgeClasses.invisible}`]: {
transform: 'scale(0) translate(-50%, -50%)',
},
}),
...(styleProps.anchorOrigin.vertical === 'bottom' &&
styleProps.anchorOrigin.horizontal === 'left' &&
styleProps.overlap === 'rectangular' && {
bottom: 0,
left: 0,
transform: 'scale(1) translate(-50%, 50%)',
transformOrigin: '0% 100%',
[`&.${badgeClasses.invisible}`]: {
transform: 'scale(0) translate(-50%, 50%)',
},
}),
...(styleProps.anchorOrigin.vertical === 'top' &&
styleProps.anchorOrigin.horizontal === 'right' &&
styleProps.overlap === 'circular' && {
top: '14%',
right: '14%',
transform: 'scale(1) translate(50%, -50%)',
transformOrigin: '100% 0%',
[`&.${badgeClasses.invisible}`]: {
transform: 'scale(0) translate(50%, -50%)',
},
}),
...(styleProps.anchorOrigin.vertical === 'bottom' &&
styleProps.anchorOrigin.horizontal === 'right' &&
styleProps.overlap === 'circular' && {
bottom: '14%',
right: '14%',
transform: 'scale(1) translate(50%, 50%)',
transformOrigin: '100% 100%',
[`&.${badgeClasses.invisible}`]: {
transform: 'scale(0) translate(50%, 50%)',
},
}),
...(styleProps.anchorOrigin.vertical === 'top' &&
styleProps.anchorOrigin.horizontal === 'left' &&
styleProps.overlap === 'circular' && {
top: '14%',
left: '14%',
transform: 'scale(1) translate(-50%, -50%)',
transformOrigin: '0% 0%',
[`&.${badgeClasses.invisible}`]: {
transform: 'scale(0) translate(-50%, -50%)',
},
}),
...(styleProps.anchorOrigin.vertical === 'bottom' &&
styleProps.anchorOrigin.horizontal === 'left' &&
styleProps.overlap === 'circular' && {
bottom: '14%',
left: '14%',
transform: 'scale(1) translate(-50%, 50%)',
transformOrigin: '0% 100%',
[`&.${badgeClasses.invisible}`]: {
transform: 'scale(0) translate(-50%, 50%)',
},
}),
...(styleProps.invisible && {
transition: theme.transitions.create('transform', {
easing: theme.transitions.easing.easeInOut,
duration: theme.transitions.duration.leavingScreen,
}),
}),
}));
const Badge = React.forwardRef(function Badge(inProps, ref) {
const { isRtl, ...props } = useThemeProps({ props: inProps, name: 'MuiBadge' });
const {
components = {},
componentsProps = {},
color: colorProp = 'default',
invisible: invisibleProp,
badgeContent: badgeContentProp,
showZero = false,
variant: variantProp = 'standard',
...other
} = props;
const prevProps = usePreviousProps({
color: colorProp,
});
let invisible = invisibleProp;
if (
invisibleProp == null &&
((badgeContentProp === 0 && !showZero) || (badgeContentProp == null && variantProp !== 'dot'))
) {
invisible = true;
}
const { color = colorProp } = invisible ? prevProps : props;
const styleProps = { ...props, invisible, color };
const classes = extendUtilityClasses(styleProps);
return (
<BadgeUnstyled
invisible={invisibleProp}
badgeContent={badgeContentProp}
showZero={showZero}
variant={variantProp}
{...other}
components={{
Root: BadgeRoot,
Badge: BadgeBadge,
...components,
}}
componentsProps={{
root: {
...componentsProps.root,
...((!components.Root || !isHostComponent(components.Root)) && {
styleProps: { ...componentsProps.root?.styleProps, color },
}),
},
badge: {
...componentsProps.badge,
...((!components.Thumb || !isHostComponent(components.Thumb)) && {
styleProps: { ...componentsProps.badge?.styleProps, color },
}),
},
}}
classes={classes}
ref={ref}
/>
);
});
Badge.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The anchor of the badge.
* @default {
* vertical: 'top',
* horizontal: 'right',
* }
*/
anchorOrigin: PropTypes.shape({
horizontal: PropTypes.oneOf(['left', 'right']).isRequired,
vertical: PropTypes.oneOf(['bottom', 'top']).isRequired,
}),
/**
* The content rendered within the badge.
*/
badgeContent: PropTypes.node,
/**
* The badge will be added relative to this node.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* The color of the component. It supports those theme colors that make sense for this component.
* @default 'default'
*/
color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([
PropTypes.oneOf(['default', 'error', 'primary', 'secondary']),
PropTypes.string,
]),
/**
* The components used for each slot inside the Badge.
* Either a string to use a HTML element or a component.
* @default {}
*/
components: PropTypes.shape({
Badge: PropTypes.elementType,
Root: PropTypes.elementType,
}),
/**
* The props used for each slot inside the Badge.
* @default {}
*/
componentsProps: PropTypes.object,
/**
* If `true`, the badge is invisible.
*/
invisible: PropTypes.bool,
/**
* Max count to show.
* @default 99
*/
max: PropTypes.number,
/**
* Wrapped shape the badge should overlap.
* @default 'rectangular'
*/
overlap: PropTypes.oneOf(['circular', 'rectangular']),
/**
* Controls whether the badge is hidden when `badgeContent` is zero.
* @default false
*/
showZero: PropTypes.bool,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.object,
/**
* The variant to use.
* @default 'standard'
*/
variant: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([
PropTypes.oneOf(['dot', 'standard']),
PropTypes.string,
]),
};
export default Badge;
| packages/material-ui/src/Badge/Badge.js | 0 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.0001776290882844478,
0.0001730923686409369,
0.0001618609530851245,
0.00017473316984251142,
0.0000034195672924397513
] |
{
"id": 4,
"code_window": [
" function Parent() {\n",
" setState = React.useState(0)[1];\n",
" React.useEffect(() => {});\n",
" React.useEffect(() => {});\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const [state, setState] = React.useState(0);\n",
" unsafeSetState = setState;\n",
"\n"
],
"file_path": "test/utils/mochaHooks.test.js",
"type": "replace",
"edit_start_line_idx": 68
} | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M9 12c0 1.66 1.34 3 3 3s3-1.34 3-3-1.34-3-3-3-3 1.34-3 3z" /><path d="M8 10V8H5.09C6.47 5.61 9.05 4 12 4c3.72 0 6.85 2.56 7.74 6h2.06c-.93-4.56-4.96-8-9.8-8-3.27 0-6.18 1.58-8 4.01V4H2v6h6zm8 4v2h2.91c-1.38 2.39-3.96 4-6.91 4-3.72 0-6.85-2.56-7.74-6H2.2c.93 4.56 4.96 8 9.8 8 3.27 0 6.18-1.58 8-4.01V20h2v-6h-6z" /></React.Fragment>
, 'FlipCameraAndroidSharp');
| packages/material-ui-icons/src/FlipCameraAndroidSharp.js | 0 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.00016763659368734807,
0.00016763659368734807,
0.00016763659368734807,
0.00016763659368734807,
0
] |
{
"id": 4,
"code_window": [
" function Parent() {\n",
" setState = React.useState(0)[1];\n",
" React.useEffect(() => {});\n",
" React.useEffect(() => {});\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const [state, setState] = React.useState(0);\n",
" unsafeSetState = setState;\n",
"\n"
],
"file_path": "test/utils/mochaHooks.test.js",
"type": "replace",
"edit_start_line_idx": 68
} | # Über das Labor
<p class="description">Dieses Paket enthält die Inkubator-Komponenten, die noch nicht bereit sind, in den Kern aufgenommen zu werden.</p>
Der Hauptunterschied zwischen dem Labor und dem Kern besteht darin, wie die Komponenten versioniert werden. Ein separates Labor-Paket erlaubt es uns, wenn es notwendig ist, nicht rückwärtskompatible Änderungen zu veröffentlichen, ohne die [langsamere Veröffentlichungsfrequenz](https://material-ui.com/versions/#release-frequency) des Kernpakets einzuschränken.
As developers use and test the components and report issues, the maintainers learn more about shortcomings of the components: missing features, accessibility issues, bugs, API design, etc. The older and more used a component is, the less likely it is that new issues will be found and subsequently need to introduce breaking changes.
For a component to be ready to move to the core, the following criteria are considered:
- Folgendes sollte **verwendet werden**. Das Material-UI-Team verwendet neben anderen Metriken Google Analytics Statistiken, um die Nutzung der einzelnen Komponenten zu bewerten. Eine Laborkomponente mit geringem Verbrauch bedeutet entweder, dass sie noch nicht vollständig funktioniert oder dass eine geringe Nachfrage besteht.
- Sie muss der **Codequalität** der Kernkomponenten entsprechen. It doesn't have to be perfect to be a part of the core, but the component should be reliable enough that developers can depend on it.
- Jede Komponente benötigt **Typdefinitionen**. It is not currently required that a lab component is typed, but it would need to be typed to move to the core.
- Erfordert eine gute **Testabdeckung**. Some of the lab components don't currently have comprehensive tests.
- Kann es ein **ausschlaggebender Punkt** sein, um Benutzer zu einem Upgrade auf die neueste Hauptversion zu bewegen? The less fragmented the community is, the better.
- Es muss eine geringe Wahrscheinlichkeit für eine **einschneidende Änderung** in der kurzen/mittleren Zukunft bestehen. For instance, if it needs a new feature that will likely require a breaking change, it may be preferable to delay its promotion to the core.
## Installation
Installieren Sie das Paket innerhalb des Projektordners mit:
```sh
// mit npm
npm install @material-ui/lab
// mit yarn
yarn add @material-ui/lab
```
Das Labor hat eine Peer-Abhängigkeit von den Kernkomponenten. Wenn Sie in Ihrem Projekt noch keine Material-UI verwenden, können Sie es mit folgendem installieren:
```sh
// mit npm
npm install @material-ui/core
// mit yarn
yarn add @material-ui/core
```
## TypeScript
In order to benefit from the [CSS overrides](/customization/theme-components/#global-style-overrides) and [default prop customization](/customization/theme-components/#default-props) with the theme, TypeScript users need to import the following types. Internally, it uses [module augmentation](/guides/typescript/#customization-of-theme) to extend the default theme structure with the extension components available in the lab.
```tsx
import '@material-ui/lab/themeAugmentation';
const theme = createMuiTheme({
components: {
MuiTimeline: {
styleOverrides: {
root: {
backgroundColor: 'red',
},
},
},
},
});
```
| docs/src/pages/components/about-the-lab/about-the-lab-de.md | 0 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.0001743515458656475,
0.00017038738587871194,
0.00016593826876487583,
0.0001708580821286887,
0.0000029086968424962834
] |
{
"id": 5,
"code_window": [
" React.useEffect(() => {});\n",
" React.useEffect(() => {});\n",
"\n",
" return <Child />;\n",
" }\n",
"\n",
" render(<Parent />);\n",
"\n",
" // not wrapped in act()\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return <Child rerender={state} />;\n"
],
"file_path": "test/utils/mochaHooks.test.js",
"type": "replace",
"edit_start_line_idx": 72
} | import * as Mocha from 'mocha';
import { expect } from 'chai';
import * as React from 'react';
import { stub } from 'sinon';
import { createMochaHooks } from './mochaHooks';
import { createClientRender } from './createClientRender';
describe('mochaHooks', () => {
// one block per hook.
describe('afterEach', () => {
describe('throws on unexpected console.(warn|error) in afterEach', function suite() {
const mochaHooks = createMochaHooks(Mocha);
beforeEach(function beforeEachHook() {
mochaHooks.beforeAll.forEach((beforeAllMochaHook) => {
beforeAllMochaHook.call(this);
});
mochaHooks.beforeEach.forEach((beforeEachMochaHook) => {
beforeEachMochaHook.call(this);
});
});
it('', () => {
console.warn('unexpected warning');
console.error('unexpected error');
});
afterEach(function afterEachHook() {
const errorStub = stub(this.test, 'error');
mochaHooks.afterEach.forEach((afterEachMochaHook) => {
afterEachMochaHook.call(this);
});
mochaHooks.afterAll.forEach((afterAllMochaHook) => {
afterAllMochaHook.call(this);
});
expect(errorStub.callCount).to.equal(2);
expect(String(errorStub.firstCall.args[0])).to.include(
'console.warn message #1:\n unexpected warning\n\nStack:',
);
expect(String(errorStub.secondCall.args[0])).to.include(
'console.error message #1:\n unexpected error\n\nStack:',
);
});
});
describe('dedupes missing act() warnings by component', () => {
const mochaHooks = createMochaHooks(Mocha);
const render = createClientRender();
beforeEach(function beforeEachHook() {
mochaHooks.beforeAll.forEach((beforeAllMochaHook) => {
beforeAllMochaHook.call(this);
});
mochaHooks.beforeEach.forEach((beforeEachMochaHook) => {
beforeEachMochaHook.call(this);
});
});
it('', () => {
const Child = React.forwardRef(function Child() {
React.useEffect(() => {});
React.useEffect(() => {});
return null;
});
let setState;
function Parent() {
setState = React.useState(0)[1];
React.useEffect(() => {});
React.useEffect(() => {});
return <Child />;
}
render(<Parent />);
// not wrapped in act()
setState(1);
});
afterEach(function afterEachHook() {
const errorStub = stub(this.test, 'error');
mochaHooks.afterEach.forEach((afterEachMochaHook) => {
afterEachMochaHook.call(this);
});
mochaHooks.afterAll.forEach((afterAllMochaHook) => {
afterAllMochaHook.call(this);
});
expect(errorStub.callCount).to.equal(1);
const error = String(errorStub.firstCall.args[0]);
expect(
error.match(/An update to Parent inside a test was not wrapped in act/g),
).to.have.lengthOf(1);
expect(
error.match(/An update to Parent ran an effect, but was not wrapped in act/g),
).to.have.lengthOf(1);
expect(
error.match(
/An update to ForwardRef\(Child\) ran an effect, but was not wrapped in act/g,
),
).to.have.lengthOf(1);
});
});
});
});
| test/utils/mochaHooks.test.js | 1 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.9977574944496155,
0.09275853633880615,
0.00016601882816758007,
0.00017416875925846398,
0.28620341420173645
] |
{
"id": 5,
"code_window": [
" React.useEffect(() => {});\n",
" React.useEffect(() => {});\n",
"\n",
" return <Child />;\n",
" }\n",
"\n",
" render(<Parent />);\n",
"\n",
" // not wrapped in act()\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return <Child rerender={state} />;\n"
],
"file_path": "test/utils/mochaHooks.test.js",
"type": "replace",
"edit_start_line_idx": 72
} | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M9.5 6.5v3h-3v-3h3M11 5H5v6h6V5zm-1.5 9.5v3h-3v-3h3M11 13H5v6h6v-6zm6.5-6.5v3h-3v-3h3M19 5h-6v6h6V5zm-6 8h1.5v1.5H13V13zm1.5 1.5H16V16h-1.5v-1.5zM16 13h1.5v1.5H16V13zm-3 3h1.5v1.5H13V16zm1.5 1.5H16V19h-1.5v-1.5zM16 16h1.5v1.5H16V16zm1.5-1.5H19V16h-1.5v-1.5zm0 3H19V19h-1.5v-1.5zM22 7h-2V4h-3V2h5v5zm0 15v-5h-2v3h-3v2h5zM2 22h5v-2H4v-3H2v5zM2 2v5h2V4h3V2H2z" />
, 'QrCodeScannerSharp');
| packages/material-ui-icons/src/QrCodeScannerSharp.js | 0 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.00016582771786488593,
0.00016582771786488593,
0.00016582771786488593,
0.00016582771786488593,
0
] |
{
"id": 5,
"code_window": [
" React.useEffect(() => {});\n",
" React.useEffect(() => {});\n",
"\n",
" return <Child />;\n",
" }\n",
"\n",
" render(<Parent />);\n",
"\n",
" // not wrapped in act()\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return <Child rerender={state} />;\n"
],
"file_path": "test/utils/mochaHooks.test.js",
"type": "replace",
"edit_start_line_idx": 72
} | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M6 11H2c-.55 0-1 .45-1 1s.45 1 1 1h4c.55 0 1-.45 1-1s-.45-1-1-1zm2.47-3.94l-.72-.72a.9959.9959 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41l.71.71c.39.39 1.02.39 1.41 0 .39-.38.39-1.02.01-1.4zM12 1c-.56 0-1 .45-1 1v4c0 .55.45 1 1 1s1-.45 1-1V2c0-.55-.45-1-1-1zm5.66 5.35a.9959.9959 0 0 0-1.41 0l-.71.71c-.39.39-.39 1.02 0 1.41.39.39 1.02.39 1.41 0l.71-.71c.38-.39.38-1.03 0-1.41zM17 12c0 .56.45 1 1 1h4c.55 0 1-.45 1-1s-.45-1-1-1h-4c-.55 0-1 .45-1 1zm-5-3c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3zm3.53 7.94l.71.71c.39.39 1.02.39 1.41 0 .39-.39.39-1.02 0-1.41l-.71-.71a.9959.9959 0 0 0-1.41 0c-.38.39-.38 1.03 0 1.41zm-9.19.71c.39.39 1.02.39 1.41 0l.71-.71c.39-.39.39-1.02 0-1.41a.9959.9959 0 0 0-1.41 0l-.71.71c-.38.39-.38 1.03 0 1.41zM12 23c.56 0 1-.45 1-1v-4c0-.55-.45-1-1-1s-1 .45-1 1v4c0 .55.45 1 1 1z" />
, 'FlareRounded');
| packages/material-ui-icons/src/FlareRounded.js | 0 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.0008685705251991749,
0.0008685705251991749,
0.0008685705251991749,
0.0008685705251991749,
0
] |
{
"id": 5,
"code_window": [
" React.useEffect(() => {});\n",
" React.useEffect(() => {});\n",
"\n",
" return <Child />;\n",
" }\n",
"\n",
" render(<Parent />);\n",
"\n",
" // not wrapped in act()\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return <Child rerender={state} />;\n"
],
"file_path": "test/utils/mochaHooks.test.js",
"type": "replace",
"edit_start_line_idx": 72
} | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M12 7.77L18.39 18H5.61L12 7.77M12 4L2 20h20L12 4z" />
, 'ChangeHistorySharp');
| packages/material-ui-icons/src/ChangeHistorySharp.js | 0 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.00016532125300727785,
0.00016532125300727785,
0.00016532125300727785,
0.00016532125300727785,
0
] |
{
"id": 6,
"code_window": [
"\n",
" render(<Parent />);\n",
"\n",
" // not wrapped in act()\n",
" setState(1);\n",
" });\n",
"\n",
" afterEach(function afterEachHook() {\n",
" const errorStub = stub(this.test, 'error');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" unsafeSetState(1);\n"
],
"file_path": "test/utils/mochaHooks.test.js",
"type": "replace",
"edit_start_line_idx": 78
} | import * as Mocha from 'mocha';
import { expect } from 'chai';
import * as React from 'react';
import { stub } from 'sinon';
import { createMochaHooks } from './mochaHooks';
import { createClientRender } from './createClientRender';
describe('mochaHooks', () => {
// one block per hook.
describe('afterEach', () => {
describe('throws on unexpected console.(warn|error) in afterEach', function suite() {
const mochaHooks = createMochaHooks(Mocha);
beforeEach(function beforeEachHook() {
mochaHooks.beforeAll.forEach((beforeAllMochaHook) => {
beforeAllMochaHook.call(this);
});
mochaHooks.beforeEach.forEach((beforeEachMochaHook) => {
beforeEachMochaHook.call(this);
});
});
it('', () => {
console.warn('unexpected warning');
console.error('unexpected error');
});
afterEach(function afterEachHook() {
const errorStub = stub(this.test, 'error');
mochaHooks.afterEach.forEach((afterEachMochaHook) => {
afterEachMochaHook.call(this);
});
mochaHooks.afterAll.forEach((afterAllMochaHook) => {
afterAllMochaHook.call(this);
});
expect(errorStub.callCount).to.equal(2);
expect(String(errorStub.firstCall.args[0])).to.include(
'console.warn message #1:\n unexpected warning\n\nStack:',
);
expect(String(errorStub.secondCall.args[0])).to.include(
'console.error message #1:\n unexpected error\n\nStack:',
);
});
});
describe('dedupes missing act() warnings by component', () => {
const mochaHooks = createMochaHooks(Mocha);
const render = createClientRender();
beforeEach(function beforeEachHook() {
mochaHooks.beforeAll.forEach((beforeAllMochaHook) => {
beforeAllMochaHook.call(this);
});
mochaHooks.beforeEach.forEach((beforeEachMochaHook) => {
beforeEachMochaHook.call(this);
});
});
it('', () => {
const Child = React.forwardRef(function Child() {
React.useEffect(() => {});
React.useEffect(() => {});
return null;
});
let setState;
function Parent() {
setState = React.useState(0)[1];
React.useEffect(() => {});
React.useEffect(() => {});
return <Child />;
}
render(<Parent />);
// not wrapped in act()
setState(1);
});
afterEach(function afterEachHook() {
const errorStub = stub(this.test, 'error');
mochaHooks.afterEach.forEach((afterEachMochaHook) => {
afterEachMochaHook.call(this);
});
mochaHooks.afterAll.forEach((afterAllMochaHook) => {
afterAllMochaHook.call(this);
});
expect(errorStub.callCount).to.equal(1);
const error = String(errorStub.firstCall.args[0]);
expect(
error.match(/An update to Parent inside a test was not wrapped in act/g),
).to.have.lengthOf(1);
expect(
error.match(/An update to Parent ran an effect, but was not wrapped in act/g),
).to.have.lengthOf(1);
expect(
error.match(
/An update to ForwardRef\(Child\) ran an effect, but was not wrapped in act/g,
),
).to.have.lengthOf(1);
});
});
});
});
| test/utils/mochaHooks.test.js | 1 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.9989967942237854,
0.4775646924972534,
0.00025612922036089003,
0.23692825436592102,
0.4781932830810547
] |
{
"id": 6,
"code_window": [
"\n",
" render(<Parent />);\n",
"\n",
" // not wrapped in act()\n",
" setState(1);\n",
" });\n",
"\n",
" afterEach(function afterEachHook() {\n",
" const errorStub = stub(this.test, 'error');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" unsafeSetState(1);\n"
],
"file_path": "test/utils/mochaHooks.test.js",
"type": "replace",
"edit_start_line_idx": 78
} | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M5 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm12-2c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm0 10c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4z" />
, 'HdrWeak');
| packages/material-ui-icons/src/HdrWeak.js | 0 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.0001747568167047575,
0.0001747568167047575,
0.0001747568167047575,
0.0001747568167047575,
0
] |
{
"id": 6,
"code_window": [
"\n",
" render(<Parent />);\n",
"\n",
" // not wrapped in act()\n",
" setState(1);\n",
" });\n",
"\n",
" afterEach(function afterEachHook() {\n",
" const errorStub = stub(this.test, 'error');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" unsafeSetState(1);\n"
],
"file_path": "test/utils/mochaHooks.test.js",
"type": "replace",
"edit_start_line_idx": 78
} | import { generateUtilityClass, generateUtilityClasses } from '@material-ui/unstyled';
export function getAvatarGroupUtilityClass(slot) {
return generateUtilityClass('MuiAvatarGroup', slot);
}
const avatarGroupClasses = generateUtilityClasses('MuiAvatarGroup', ['root', 'avatar']);
export default avatarGroupClasses;
| packages/material-ui/src/AvatarGroup/avatarGroupClasses.js | 0 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.00017467584984842688,
0.00017467584984842688,
0.00017467584984842688,
0.00017467584984842688,
0
] |
{
"id": 6,
"code_window": [
"\n",
" render(<Parent />);\n",
"\n",
" // not wrapped in act()\n",
" setState(1);\n",
" });\n",
"\n",
" afterEach(function afterEachHook() {\n",
" const errorStub = stub(this.test, 'error');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" unsafeSetState(1);\n"
],
"file_path": "test/utils/mochaHooks.test.js",
"type": "replace",
"edit_start_line_idx": 78
} | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M3 10h11v2H3zm0-4h11v2H3zm0 8h7v2H3zm13-1v8l6-4z" />
, 'PlaylistPlay');
| packages/material-ui-icons/src/PlaylistPlay.js | 0 | https://github.com/mui/material-ui/commit/1f510d4581b854eba6a3cd7f7011d64e838202f2 | [
0.00017646914056967944,
0.00017646914056967944,
0.00017646914056967944,
0.00017646914056967944,
0
] |
{
"id": 0,
"code_window": [
"import { getCurrentInstance, hasInjectionContext, inject, onUnmounted } from 'vue'\n",
"import type { Ref } from 'vue'\n",
"import type { NavigationFailure, NavigationGuard, RouteLocationNormalized, RouteLocationPathRaw, RouteLocationRaw, Router, useRoute as _useRoute, useRouter as _useRouter } from '#vue-router'\n",
"import { sanitizeStatusCode } from 'h3'\n",
"import { hasProtocol, joinURL, parseURL } from 'ufo'\n",
"\n",
"import { useNuxtApp, useRuntimeConfig } from '../nuxt'\n",
"import type { NuxtError } from './error'\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { hasProtocol, joinURL, parseURL, withQuery } from 'ufo'\n"
],
"file_path": "packages/nuxt/src/app/composables/router.ts",
"type": "replace",
"edit_start_line_idx": 4
} | import { getCurrentInstance, hasInjectionContext, inject, onUnmounted } from 'vue'
import type { Ref } from 'vue'
import type { NavigationFailure, NavigationGuard, RouteLocationNormalized, RouteLocationPathRaw, RouteLocationRaw, Router, useRoute as _useRoute, useRouter as _useRouter } from '#vue-router'
import { sanitizeStatusCode } from 'h3'
import { hasProtocol, joinURL, parseURL } from 'ufo'
import { useNuxtApp, useRuntimeConfig } from '../nuxt'
import type { NuxtError } from './error'
import { createError, showError } from './error'
import { useState } from './state'
import type { PageMeta } from '#app'
export const useRouter: typeof _useRouter = () => {
return useNuxtApp()?.$router as Router
}
export const useRoute: typeof _useRoute = () => {
if (process.dev && isProcessingMiddleware()) {
console.warn('[nuxt] Calling `useRoute` within middleware may lead to misleading results. Instead, use the (to, from) arguments passed to the middleware to access the new and old routes.')
}
if (hasInjectionContext()) {
return inject('_route', useNuxtApp()._route)
}
return useNuxtApp()._route
}
export const onBeforeRouteLeave = (guard: NavigationGuard) => {
const unsubscribe = useRouter().beforeEach((to, from, next) => {
if (to === from) { return }
return guard(to, from, next)
})
onUnmounted(unsubscribe)
}
export const onBeforeRouteUpdate = (guard: NavigationGuard) => {
const unsubscribe = useRouter().beforeEach(guard)
onUnmounted(unsubscribe)
}
export interface RouteMiddleware {
(to: RouteLocationNormalized, from: RouteLocationNormalized): ReturnType<NavigationGuard>
}
/*! @__NO_SIDE_EFFECTS__ */
export function defineNuxtRouteMiddleware (middleware: RouteMiddleware) {
return middleware
}
export interface AddRouteMiddlewareOptions {
global?: boolean
}
interface AddRouteMiddleware {
(name: string, middleware: RouteMiddleware, options?: AddRouteMiddlewareOptions): void
(middleware: RouteMiddleware): void
}
export const addRouteMiddleware: AddRouteMiddleware = (name: string | RouteMiddleware, middleware?: RouteMiddleware, options: AddRouteMiddlewareOptions = {}) => {
const nuxtApp = useNuxtApp()
const global = options.global || typeof name !== 'string'
const mw = typeof name !== 'string' ? name : middleware
if (!mw) {
console.warn('[nuxt] No route middleware passed to `addRouteMiddleware`.', name)
return
}
if (global) {
nuxtApp._middleware.global.push(mw)
} else {
nuxtApp._middleware.named[name] = mw
}
}
const isProcessingMiddleware = () => {
try {
if (useNuxtApp()._processingMiddleware) {
return true
}
} catch {
// Within an async middleware
return true
}
return false
}
// Conditional types, either one or other
type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never }
type XOR<T, U> = (T | U) extends Object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U
export type OpenWindowFeatures = {
popup?: boolean
noopener?: boolean
noreferrer?: boolean
} & XOR<{width?: number}, {innerWidth?: number}>
& XOR<{height?: number}, {innerHeight?: number}>
& XOR<{left?: number}, {screenX?: number}>
& XOR<{top?: number}, {screenY?: number}>
export type OpenOptions = {
target: '_blank' | '_parent' | '_self' | '_top' | (string & {})
windowFeatures?: OpenWindowFeatures
}
export interface NavigateToOptions {
replace?: boolean
redirectCode?: number
external?: boolean
open?: OpenOptions
}
export const navigateTo = (to: RouteLocationRaw | undefined | null, options?: NavigateToOptions): Promise<void | NavigationFailure | false> | false | void | RouteLocationRaw => {
if (!to) {
to = '/'
}
const toPath = typeof to === 'string' ? to : ((to as RouteLocationPathRaw).path || '/')
// Early open handler
if (options?.open) {
if (process.client) {
const { target = '_blank', windowFeatures = {} } = options.open
const features = Object.entries(windowFeatures)
.filter(([_, value]) => value !== undefined)
.map(([feature, value]) => `${feature.toLowerCase()}=${value}`)
.join(', ')
open(toPath, target, features)
}
return Promise.resolve()
}
const isExternal = options?.external || hasProtocol(toPath, { acceptRelative: true })
if (isExternal && !options?.external) {
throw new Error('Navigating to external URL is not allowed by default. Use `navigateTo (url, { external: true })`.')
}
if (isExternal && parseURL(toPath).protocol === 'script:') {
throw new Error('Cannot navigate to an URL with script protocol.')
}
const inMiddleware = isProcessingMiddleware()
// Early redirect on client-side
if (process.client && !isExternal && inMiddleware) {
return to
}
const router = useRouter()
if (process.server) {
const nuxtApp = useNuxtApp()
if (nuxtApp.ssrContext) {
const fullPath = typeof to === 'string' || isExternal ? toPath : router.resolve(to).fullPath || '/'
const location = isExternal ? toPath : joinURL(useRuntimeConfig().app.baseURL, fullPath)
async function redirect (response: any) {
// TODO: consider deprecating in favour of `app:rendered` and removing
await nuxtApp.callHook('app:redirected')
const encodedLoc = location.replace(/"/g, '%22')
nuxtApp.ssrContext!._renderResponse = {
statusCode: sanitizeStatusCode(options?.redirectCode || 302, 302),
body: `<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=${encodedLoc}"></head></html>`,
headers: { location }
}
return response
}
// We wait to perform the redirect last in case any other middleware will intercept the redirect
// and redirect somewhere else instead.
if (!isExternal && inMiddleware) {
router.afterEach(final => final.fullPath === fullPath ? redirect(false) : undefined)
return to
}
return redirect(!inMiddleware ? undefined : /* abort route navigation */ false)
}
}
// Client-side redirection using vue-router
if (isExternal) {
if (options?.replace) {
location.replace(toPath)
} else {
location.href = toPath
}
return Promise.resolve()
}
return options?.replace ? router.replace(to) : router.push(to)
}
/** This will abort navigation within a Nuxt route middleware handler. */
export const abortNavigation = (err?: string | Partial<NuxtError>) => {
if (process.dev && !isProcessingMiddleware()) {
throw new Error('abortNavigation() is only usable inside a route middleware handler.')
}
if (!err) { return false }
err = createError(err)
if (err.fatal) {
useNuxtApp().runWithContext(() => showError(err as NuxtError))
}
throw err
}
export const setPageLayout = (layout: string) => {
if (process.server) {
if (process.dev && getCurrentInstance() && useState('_layout').value !== layout) {
console.warn('[warn] [nuxt] `setPageLayout` should not be called to change the layout on the server within a component as this will cause hydration errors.')
}
useState('_layout').value = layout
}
const nuxtApp = useNuxtApp()
if (process.dev && nuxtApp.isHydrating && nuxtApp.payload.serverRendered && useState('_layout').value !== layout) {
console.warn('[warn] [nuxt] `setPageLayout` should not be called to change the layout during hydration as this will cause hydration errors.')
}
const inMiddleware = isProcessingMiddleware()
if (inMiddleware || process.server || nuxtApp.isHydrating) {
const unsubscribe = useRouter().beforeResolve((to) => {
to.meta.layout = layout as Exclude<PageMeta['layout'], Ref | false>
unsubscribe()
})
}
if (!inMiddleware) {
useRoute().meta.layout = layout as Exclude<PageMeta['layout'], Ref | false>
}
}
| packages/nuxt/src/app/composables/router.ts | 1 | https://github.com/nuxt/nuxt/commit/05a8c2d955b9dc7f13e0bc6ad6e347f2a9d40f23 | [
0.9965245127677917,
0.043816447257995605,
0.00016766873886808753,
0.000871384865604341,
0.1986895650625229
] |
{
"id": 0,
"code_window": [
"import { getCurrentInstance, hasInjectionContext, inject, onUnmounted } from 'vue'\n",
"import type { Ref } from 'vue'\n",
"import type { NavigationFailure, NavigationGuard, RouteLocationNormalized, RouteLocationPathRaw, RouteLocationRaw, Router, useRoute as _useRoute, useRouter as _useRouter } from '#vue-router'\n",
"import { sanitizeStatusCode } from 'h3'\n",
"import { hasProtocol, joinURL, parseURL } from 'ufo'\n",
"\n",
"import { useNuxtApp, useRuntimeConfig } from '../nuxt'\n",
"import type { NuxtError } from './error'\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { hasProtocol, joinURL, parseURL, withQuery } from 'ufo'\n"
],
"file_path": "packages/nuxt/src/app/composables/router.ts",
"type": "replace",
"edit_start_line_idx": 4
} | export default defineNuxtRouteMiddleware((to) => {
to.meta.foo = 'Injected by extended middleware from foo'
})
| test/fixtures/basic-types/extends/node_modules/foo/middleware/foo.ts | 0 | https://github.com/nuxt/nuxt/commit/05a8c2d955b9dc7f13e0bc6ad6e347f2a9d40f23 | [
0.0037379441782832146,
0.0037379441782832146,
0.0037379441782832146,
0.0037379441782832146,
0
] |
{
"id": 0,
"code_window": [
"import { getCurrentInstance, hasInjectionContext, inject, onUnmounted } from 'vue'\n",
"import type { Ref } from 'vue'\n",
"import type { NavigationFailure, NavigationGuard, RouteLocationNormalized, RouteLocationPathRaw, RouteLocationRaw, Router, useRoute as _useRoute, useRouter as _useRouter } from '#vue-router'\n",
"import { sanitizeStatusCode } from 'h3'\n",
"import { hasProtocol, joinURL, parseURL } from 'ufo'\n",
"\n",
"import { useNuxtApp, useRuntimeConfig } from '../nuxt'\n",
"import type { NuxtError } from './error'\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { hasProtocol, joinURL, parseURL, withQuery } from 'ufo'\n"
],
"file_path": "packages/nuxt/src/app/composables/router.ts",
"type": "replace",
"edit_start_line_idx": 4
} | <template>
<div>
Home
</div>
</template>
| examples/routing/middleware/pages/index.vue | 0 | https://github.com/nuxt/nuxt/commit/05a8c2d955b9dc7f13e0bc6ad6e347f2a9d40f23 | [
0.00017296049918513745,
0.00017296049918513745,
0.00017296049918513745,
0.00017296049918513745,
0
] |
{
"id": 0,
"code_window": [
"import { getCurrentInstance, hasInjectionContext, inject, onUnmounted } from 'vue'\n",
"import type { Ref } from 'vue'\n",
"import type { NavigationFailure, NavigationGuard, RouteLocationNormalized, RouteLocationPathRaw, RouteLocationRaw, Router, useRoute as _useRoute, useRouter as _useRouter } from '#vue-router'\n",
"import { sanitizeStatusCode } from 'h3'\n",
"import { hasProtocol, joinURL, parseURL } from 'ufo'\n",
"\n",
"import { useNuxtApp, useRuntimeConfig } from '../nuxt'\n",
"import type { NuxtError } from './error'\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { hasProtocol, joinURL, parseURL, withQuery } from 'ufo'\n"
],
"file_path": "packages/nuxt/src/app/composables/router.ts",
"type": "replace",
"edit_start_line_idx": 4
} | ---
title: "onBeforeRouteLeave"
description: The onBeforeRouteLeave composable allows registering a route guard within a component.
---
# `onBeforeRouteLeave`
The `onBeforeRouteLeave` composable adds a navigation guard that triggers whenever the component for the current location is about to be left.
::ReadMore{link="https://router.vuejs.org/api/#Functions-onBeforeRouteLeave"}
::
| docs/3.api/3.utils/on-before-route-leave.md | 0 | https://github.com/nuxt/nuxt/commit/05a8c2d955b9dc7f13e0bc6ad6e347f2a9d40f23 | [
0.00043947366066277027,
0.00030559347942471504,
0.00017171326908282936,
0.00030559347942471504,
0.00013388019578997046
] |
{
"id": 1,
"code_window": [
" if (!to) {\n",
" to = '/'\n",
" }\n",
"\n",
" const toPath = typeof to === 'string' ? to : ((to as RouteLocationPathRaw).path || '/')\n",
"\n",
" // Early open handler\n",
" if (options?.open) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const toPath = typeof to === 'string' ? to : (withQuery((to as RouteLocationPathRaw).path || '/', to.query || {}) + (to.hash || ''))\n"
],
"file_path": "packages/nuxt/src/app/composables/router.ts",
"type": "replace",
"edit_start_line_idx": 115
} | import { fileURLToPath } from 'node:url'
import fsp from 'node:fs/promises'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { execaCommand } from 'execa'
import { globby } from 'globby'
import { join } from 'pathe'
describe.skipIf(process.env.SKIP_BUNDLE_SIZE === 'true' || process.env.ECOSYSTEM_CI)('minimal nuxt application', () => {
const rootDir = fileURLToPath(new URL('./fixtures/minimal', import.meta.url))
const publicDir = join(rootDir, '.output/public')
const serverDir = join(rootDir, '.output/server')
const stats = {
client: { totalBytes: 0, files: [] as string[] },
server: { totalBytes: 0, files: [] as string[] }
}
beforeAll(async () => {
await execaCommand(`pnpm nuxi build ${rootDir}`)
}, 120 * 1000)
afterAll(async () => {
await fsp.writeFile(join(rootDir, '.output/test-stats.json'), JSON.stringify(stats, null, 2))
})
it('default client bundle size', async () => {
stats.client = await analyzeSizes('**/*.js', publicDir)
expect(roundToKilobytes(stats.client.totalBytes)).toMatchInlineSnapshot('"97.1k"')
expect(stats.client.files.map(f => f.replace(/\..*\.js/, '.js'))).toMatchInlineSnapshot(`
[
"_nuxt/entry.js",
]
`)
})
it('default server bundle size', async () => {
stats.server = await analyzeSizes(['**/*.mjs', '!node_modules'], serverDir)
expect(roundToKilobytes(stats.server.totalBytes)).toMatchInlineSnapshot('"61.9k"')
const modules = await analyzeSizes('node_modules/**/*', serverDir)
expect(roundToKilobytes(modules.totalBytes)).toMatchInlineSnapshot('"2286k"')
const packages = modules.files
.filter(m => m.endsWith('package.json'))
.map(m => m.replace('/package.json', '').replace('node_modules/', ''))
.sort()
expect(packages).toMatchInlineSnapshot(`
[
"@babel/parser",
"@unhead/dom",
"@unhead/shared",
"@unhead/ssr",
"@vue/compiler-core",
"@vue/compiler-dom",
"@vue/compiler-ssr",
"@vue/reactivity",
"@vue/runtime-core",
"@vue/runtime-dom",
"@vue/server-renderer",
"@vue/shared",
"cookie-es",
"defu",
"destr",
"devalue",
"estree-walker",
"h3",
"hookable",
"iron-webcrypto",
"klona",
"node-fetch-native",
"ofetch",
"ohash",
"pathe",
"radix3",
"scule",
"source-map-js",
"ufo",
"uncrypto",
"unctx",
"unenv",
"unhead",
"unstorage",
"vue",
"vue-bundle-renderer",
]
`)
})
})
async function analyzeSizes (pattern: string | string[], rootDir: string) {
const files: string[] = await globby(pattern, { cwd: rootDir })
let totalBytes = 0
for (const file of files) {
const path = join(rootDir, file)
const isSymlink = (await fsp.lstat(path).catch(() => null))?.isSymbolicLink()
if (!isSymlink) {
const bytes = Buffer.byteLength(await fsp.readFile(path))
totalBytes += bytes
}
}
return { files, totalBytes }
}
function roundToKilobytes (bytes: number) {
return (bytes / 1024).toFixed(bytes > (100 * 1024) ? 0 : 1) + 'k'
}
| test/bundle.test.ts | 1 | https://github.com/nuxt/nuxt/commit/05a8c2d955b9dc7f13e0bc6ad6e347f2a9d40f23 | [
0.00017577306425664574,
0.0001717626437311992,
0.0001674479281064123,
0.00017250081873498857,
0.000002302595703440602
] |
{
"id": 1,
"code_window": [
" if (!to) {\n",
" to = '/'\n",
" }\n",
"\n",
" const toPath = typeof to === 'string' ? to : ((to as RouteLocationPathRaw).path || '/')\n",
"\n",
" // Early open handler\n",
" if (options?.open) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const toPath = typeof to === 'string' ? to : (withQuery((to as RouteLocationPathRaw).path || '/', to.query || {}) + (to.hash || ''))\n"
],
"file_path": "packages/nuxt/src/app/composables/router.ts",
"type": "replace",
"edit_start_line_idx": 115
} | ---
description: "Nuxt 3 (and Bridge) uses Native ES Modules."
---
# ES Modules
This guide helps explain what ES Modules are and how to make a Nuxt app (or upstream library) compatible with ESM.
## Background
### CommonJS Modules
CommonJS (CJS) is a format introduced by Node.js that allows sharing functionality between isolated JavaScript modules ([read more](https://nodejs.org/api/modules.html)).
You might be already familiar with this syntax:
```js
const a = require('./a')
module.exports.a = a
```
Bundlers like webpack and Rollup support this syntax and allow you to use modules written in CommonJS in the browser.
### ESM Syntax
Most of the time, when people talk about ESM vs CJS, they are talking about a different syntax for writing [modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules).
```js
import a from './a'
export { a }
```
Before ECMAScript Modules (ESM) became a standard (it took more than 10 years!), tooling like
[webpack](https://webpack.js.org/guides/ecma-script-modules/) and even languages like TypeScript started supporting so-called **ESM syntax**.
However, there are some key differences with actual spec; here's [a helpful explainer](https://hacks.mozilla.org/2018/03/es-modules-a-cartoon-deep-dive/).
### What is 'Native' ESM?
You may have been writing your app using ESM syntax for a long time. After all, it's natively supported by the browser, and in Nuxt 2 we compiled all the code you wrote to the appropriate format (CJS for server, ESM for browser).
When using modules you'd install into your package, things were a little different. A sample library might expose both CJS and ESM versions, and let us pick which one we wanted:
```json
{
"name": "sample-library",
"main": "dist/sample-library.cjs.js",
"module": "dist/sample-library.esm.js"
}
```
So in Nuxt 2, the bundler (webpack) would pull in the CJS file ('main') for the server build and use the ESM file ('module') for the client build.
However, in recent Node.js LTS releases, it is now possible to [use native ESM module](https://nodejs.org/api/esm.html) within Node.js. That means that Node.js itself can process JavaScript using ESM syntax, although it doesn't do it by default. The two most common ways to enable ESM syntax are:
- set `type: 'module'` within your `package.json` and keep using `.js` extension
- use the `.mjs` file extensions (recommended)
This is what we do for Nuxt Nitro; we output a `.output/server/index.mjs` file. That tells Node.js to treat this file as a native ES module.
### What Are Valid Imports in a Node.js Context?
When you `import` a module rather than `require` it, Node.js resolves it differently. For example, when you import `sample-library`, Node.js will look not for the `main` but for the `exports` or `module` entry in that library's `package.json`.
This is also true of dynamic imports, like `const b = await import('sample-library')`.
Node supports the following kinds of imports (see [docs](https://nodejs.org/api/packages.html#determining-module-system)):
1. files ending in `.mjs` - these are expected to use ESM syntax
1. files ending in `.cjs` - these are expected to use CJS syntax
1. files ending in `.js` - these are expected to use CJS syntax unless their `package.json` has `type: 'module'`
### What Kinds of Problems Can There Be?
For a long time module authors have been producing ESM-syntax builds but using conventions like `.esm.js` or `.es.js`, which they have added to the `module` field in their `package.json`. This hasn't been a problem until now because they have only been used by bundlers like webpack, which don't especially care about the file extension.
However, if you try to import a package with an `.esm.js` file in a Node.js ESM context, it won't work, and you'll get an error like:
```bash
(node:22145) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
/path/to/index.js:1
export default {}
^^^^^^
SyntaxError: Unexpected token 'export'
at wrapSafe (internal/modules/cjs/loader.js:1001:16)
at Module._compile (internal/modules/cjs/loader.js:1049:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
....
at async Object.loadESM (internal/process/esm_loader.js:68:5)
```
You might also get this error if you have a named import from an ESM-syntax build that Node.js thinks is CJS:
```bash
file:///path/to/index.mjs:5
import { named } from 'sample-library'
^^^^^
SyntaxError: Named export 'named' not found. The requested module 'sample-library' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:
import pkg from 'sample-library';
const { named } = pkg;
at ModuleJob._instantiate (internal/modules/esm/module_job.js:120:21)
at async ModuleJob.run (internal/modules/esm/module_job.js:165:5)
at async Loader.import (internal/modules/esm/loader.js:177:24)
at async Object.loadESM (internal/process/esm_loader.js:68:5)
```
## Troubleshooting ESM Issues
If you encounter these errors, the issue is almost certainly with the upstream library. They need to [fix their library](#library-author-guide) to support being imported by Node.
### Transpiling Libraries
In the meantime, you can tell Nuxt not to try to import these libraries by adding them to `build.transpile`:
```js
export default defineNuxtConfig({
build: {
transpile: ['sample-library']
}
})
```
You may find that you _also_ need to add other packages that are being imported by these libraries.
### Aliasing Libraries
In some cases, you may also need to manually alias the library to the CJS version, for example:
```js
export default defineNuxtConfig({
alias: {
'sample-library': 'sample-library/dist/sample-library.cjs.js'
}
})
```
### Default Exports
A dependency with CommonJS format, can use `module.exports` or `exports` to provide a default export:
```js [node_modules/cjs-pkg/index.js]
module.exports = { test: 123 }
// or
exports.test = 123
```
This normally works well if we `require` such dependency:
```js [test.cjs]
const pkg = require('cjs-pkg')
console.log(pkg) // { test: 123 }
```
[Node.js in native ESM mode](https://nodejs.org/api/esm.html#interoperability-with-commonjs), [typescript with `esModuleInterop` enabled](https://www.typescriptlang.org/tsconfig#esModuleInterop) and bundlers such as webpack, provide a compatibility mechanism so that we can default import such library.
This mechanism is often referred to as "interop require default":
```js
import pkg from 'cjs-pkg'
console.log(pkg) // { test: 123 }
```
However, because of the complexities of syntax detection and different bundle formats, there is always a chance that the interop default fails and we end up with something like this:
```js
import pkg from 'cjs-pkg'
console.log(pkg) // { default: { test: 123 } }
```
Also when using dynamic import syntax (in both CJS and ESM files), we always have this situation:
```js
import('cjs-pkg').then(console.log) // [Module: null prototype] { default: { test: '123' } }
```
In this case, we need to manually interop the default export:
```js
// Static import
import { default as pkg } from 'cjs-pkg'
// Dynamic import
import('cjs-pkg').then(m => m.default || m).then(console.log)
```
For handling more complex situations and more safety, we recommend and internally use [mlly](https://github.com/unjs/mlly) in Nuxt 3 that can preserve named exports.
```js
import { interopDefault } from 'mlly'
// Assuming the shape is { default: { foo: 'bar' }, baz: 'qux' }
import myModule from 'my-module'
console.log(interopDefault(myModule)) // { foo: 'bar', baz: 'qux' }
```
## Library Author Guide
The good news is that it's relatively simple to fix issues of ESM compatibility. There are two main options:
1. **You can rename your ESM files to end with `.mjs`.**
_This is the recommended and simplest approach._ You may have to sort out issues with your library's dependencies and possibly with your build system, but in most cases, this should fix the problem for you. It's also recommended to rename your CJS files to end with `.cjs`, for the greatest explicitness.
1. **You can opt to make your entire library ESM-only**.
This would mean setting `type: 'module'` in your `package.json` and ensuring that your built library uses ESM syntax. However, you may face issues with your dependencies - and this approach means your library can _only_ be consumed in an ESM context.
### Migration
The initial step from CJS to ESM is updating any usage of `require` to use `import` instead:
::code-group
```js [Before]
module.exports = ...
exports.hello = ...
```
```js [After]
export default ...
export const hello = ...
```
::
::code-group
```js [Before]
const myLib = require('my-lib')
```
```js [After]
import myLib from 'my-lib'
// or
const myLib = await import('my-lib').then(lib => lib.default || lib)
```
::
In ESM Modules, unlike CJS, `require`, `require.resolve`, `__filename` and `__dirname` globals are not available
and should be replaced with `import()` and `import.meta.filename`.
::code-group
```js [Before]
import { join } from 'path'
const newDir = join(__dirname, 'new-dir')
```
```js [After]
import { fileURLToPath } from 'node:url'
const newDir = fileURLToPath(new URL('./new-dir', import.meta.url))
```
::
::code-group
```js [Before]
const someFile = require.resolve('./lib/foo.js')
```
```js [After]
import { resolvePath } from 'mlly'
const someFile = await resolvePath('my-lib', { url: import.meta.url })
```
::
### Best Practices
- Prefer named exports rather than default export. This helps reduce CJS conflicts. (see [Default exports](#default-exports) section)
- Avoid depending on Node.js built-ins and CommonJS or Node.js-only dependencies as much as possible to make your library usable in Browsers and Edge Workers without needing Nitro polyfills.
- Use new `exports` field with conditional exports. ([read more](https://nodejs.org/api/packages.html#conditional-exports)).
```json
{
"exports": {
".": {
"import": "./dist/mymodule.mjs"
}
}
}
```
| docs/2.guide/1.concepts/7.esm.md | 0 | https://github.com/nuxt/nuxt/commit/05a8c2d955b9dc7f13e0bc6ad6e347f2a9d40f23 | [
0.00017693736299406737,
0.0001691448997007683,
0.00016206945292651653,
0.0001694819948170334,
0.00000339392477144429
] |
{
"id": 1,
"code_window": [
" if (!to) {\n",
" to = '/'\n",
" }\n",
"\n",
" const toPath = typeof to === 'string' ? to : ((to as RouteLocationPathRaw).path || '/')\n",
"\n",
" // Early open handler\n",
" if (options?.open) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const toPath = typeof to === 'string' ? to : (withQuery((to as RouteLocationPathRaw).path || '/', to.query || {}) + (to.hash || ''))\n"
],
"file_path": "packages/nuxt/src/app/composables/router.ts",
"type": "replace",
"edit_start_line_idx": 115
} | # Pages and Layouts
## `app.vue`
Nuxt 3 provides a central entry point to your app via `~/app.vue`. If you don't have an `app.vue` file in your source directory, Nuxt will use its own default version.
This file is a great place to put any custom code that needs to be run once when your app starts up, as well as any components that are present on every page of your app. For example, if you only have one layout, you can move this to `app.vue` instead.
[Read more about `app.vue`](/docs/guide/directory-structure/app).
### Migration
1. Consider creating an `app.vue` file and including any logic that needs to run once at the top-level of your app. You can check out [an example here](/docs/guide/directory-structure/app).
## Layouts
If you are using layouts in your app for multiple pages, there is only a slight change required.
In Nuxt 2, the `<Nuxt>` component is used within a layout to render the current page. In Nuxt 3, layouts use slots instead, so you will have to replace that component with a `<slot />`. This also allows advanced use cases with named and scoped slots. [Read more about layouts](/docs/guide/directory-structure/layouts).
You will also need to change how you define the layout used by a page using the `definePageMeta` compiler macro. Layouts will be kebab-cased. So `layouts/customLayout.vue` becomes `custom-layout` when referenced in your page.
### Migration
1. Replace `<Nuxt />` with `<slot />`
1. Use `definePageMeta` to select the layout used by your page.
1. Move `~/layouts/_error.vue` to `~/error.vue`. See [the error handling docs](/docs/getting-started/error-handling). If you want to ensure that this page uses a layout, you can use [the `<NuxtLayout>` component](/docs/guide/directory-structure/layouts) directly within `error.vue`:
```vue
<template>
<div>
<NuxtLayout name="default">
<!-- -->
</NuxtLayout>
</div>
</template>
```
### Example: `~/layouts/custom.vue`
::code-group
```diff [layouts/custom.vue]
<template>
<div id="app-layout">
<main>
- <Nuxt />
+ <slot />
</main>
</div>
</template>
```
```diff [pages/index.vue]
<script>
+ definePageMeta({ layout: 'custom' })
export default {
- layout: 'custom'
}
</script>
```
::
## Pages
Nuxt 3 ships with an optional `vue-router` integration triggered by the existence of a `pages/` directory in your source directory. If you only have a single page, you may consider instead moving it to `app.vue` for a lighter build.
### Dynamic Routes
The format for defining dynamic routes in Nuxt 3 is slightly different from Nuxt 2, so you may need to rename some of the files within `pages/`.
1. Where you previously used `_id` to define a dynamic route parameter you now use `[id]`.
1. Where you previously used `_.vue` to define a catch-all route, you now use `[...slug].vue`.
### Nested Routes
In Nuxt 2, you will have defined any nested routes (with parent and child components) using `<Nuxt>` and `<NuxtChild>`. In Nuxt 3, these have been replaced with a single `<NuxtPage>` component.
### Page Keys and Keep-alive Props
If you were passing a custom page key or keep-alive props to `<Nuxt>`, you will now use `definePageMeta` to set these options.
See [more about migrating Nuxt component hooks](/docs/migration/component-options).
### Page and Layout Transitions
If you have been defining transitions for your page or layout directly in your component options, you will now need to use `definePageMeta` to set the transition. Since Vue 3, [-enter and -leave CSS classes have been renamed](https://v3-migration.vuejs.org/breaking-changes/transition.html). The `style` prop from `<Nuxt>` no longer applies to transition when used on `<slot>`, so move the styles to your `-active` class.
[Read more about `pages/`](/docs/guide/directory-structure/pages).
### Migration
1. Rename any pages with dynamic parameters to match the new format.
1. Update `<Nuxt>` and `<NuxtChild>` to be `<NuxtPage>`.
1. If you're using the Composition API, you can also migrate `this.$route` and `this.$router` to use `useRoute` and `useRouter` composables.
#### Example: Dynamic Routes
::code-group
``` [Nuxt 2]
- URL: /users
- Page: /pages/users/index.vue
- URL: /users/some-user-name
- Page: /pages/users/_user.vue
- Usage: params.user
- URL: /users/some-user-name/edit
- Page: /pages/users/_user/edit.vue
- Usage: params.user
- URL: /users/anything-else
- Page: /pages/users/_.vue
- Usage: params.pathMatch
```
``` [Nuxt 3]
- URL: /users
- Page: /pages/users/index.vue
- URL: /users/some-user-name
- Page: /pages/users/[user].vue
- Usage: params.user
- URL: /users/some-user-name/edit
- Page: /pages/users/[user]/edit.vue
- Usage: params.user
- URL: /users/anything-else
- Page: /pages/users/[...slug].vue
- Usage: params.slug
```
::
#### Example: Nested Routes and `definePageMeta`
::code-group
```vue [Nuxt 2]
<template>
<div>
<NuxtChild keep-alive :keep-alive-props="{ exclude: ['modal'] }" :nuxt-child-key="$route.slug" />
</div>
</template>
<script>
export default {
transition: 'page' // or { name: 'page' }
}
</script>
```
```vue [Nuxt 3]
<template>
<div>
<NuxtPage />
</div>
</template>
<script setup>
// This compiler macro works in both <script> and <script setup>
definePageMeta({
// you can also pass a string or a computed property
key: route => route.slug,
transition: {
name: 'page',
},
keepalive: {
exclude: ['modal']
},
})
</script>
```
::
## `<NuxtLink>` Component
Most of the syntax and functionality are the same for the global [NuxtLink](/docs/api/components/nuxt-link) component. If you have been using the shortcut `<NLink>` format, you should update this to use `<NuxtLink>`.
`<NuxtLink>` is now a drop-in replacement for _all_ links, even external ones. You can read more about it, and how to extend it to provide your own link component, [in the docs](/docs/api/components/nuxt-link).
## Programmatic Navigation
When migrating from Nuxt 2 to Nuxt 3, you will have to update how you programmatically navigate your users. In Nuxt 2, you had access to the underlying Vue Router with `this.$router`. In Nuxt 3, you can use the `navigateTo()` utility method which allows you to pass a route and parameters to Vue Router.
**Note:** Ensure to always `await` on `navigateTo` or chain it's result by returning from functions.
::code-group
```vue [Nuxt 2]
<script>
export default {
methods: {
navigate(){
this.$router.push({
path: '/search',
query: {
name: 'first name',
type: '1'
}
})
}
}
}
</script>
```
```vue [Nuxt 3]
<script setup>
const router = useRouter();
function navigate(){
return navigateTo({
path: '/search',
query: {
name: 'first name',
type: '1'
}
})
}
</script>
```
::
| docs/7.migration/6.pages-and-layouts.md | 0 | https://github.com/nuxt/nuxt/commit/05a8c2d955b9dc7f13e0bc6ad6e347f2a9d40f23 | [
0.00017358419427182525,
0.00016867415979504585,
0.00016499808407388628,
0.00016804164624772966,
0.0000025481854208919685
] |
{
"id": 1,
"code_window": [
" if (!to) {\n",
" to = '/'\n",
" }\n",
"\n",
" const toPath = typeof to === 'string' ? to : ((to as RouteLocationPathRaw).path || '/')\n",
"\n",
" // Early open handler\n",
" if (options?.open) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const toPath = typeof to === 'string' ? to : (withQuery((to as RouteLocationPathRaw).path || '/', to.query || {}) + (to.hash || ''))\n"
],
"file_path": "packages/nuxt/src/app/composables/router.ts",
"type": "replace",
"edit_start_line_idx": 115
} | telemetry.enabled=false
| .nuxtrc | 0 | https://github.com/nuxt/nuxt/commit/05a8c2d955b9dc7f13e0bc6ad6e347f2a9d40f23 | [
0.00016748736379668117,
0.00016748736379668117,
0.00016748736379668117,
0.00016748736379668117,
0
] |
{
"id": 2,
"code_window": [
"describe('navigate external', () => {\n",
" it('should redirect to example.com', async () => {\n",
" const { headers } = await fetch('/navigate-to-external/', { redirect: 'manual' })\n",
"\n",
" expect(headers.get('location')).toEqual('https://example.com/')\n",
" })\n",
"\n",
" it('should redirect to api endpoint', async () => {\n",
" const { headers } = await fetch('/navigate-to-api', { redirect: 'manual' })\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(headers.get('location')).toEqual('https://example.com/?redirect=false#test')\n"
],
"file_path": "test/basic.test.ts",
"type": "replace",
"edit_start_line_idx": 790
} | import { getCurrentInstance, hasInjectionContext, inject, onUnmounted } from 'vue'
import type { Ref } from 'vue'
import type { NavigationFailure, NavigationGuard, RouteLocationNormalized, RouteLocationPathRaw, RouteLocationRaw, Router, useRoute as _useRoute, useRouter as _useRouter } from '#vue-router'
import { sanitizeStatusCode } from 'h3'
import { hasProtocol, joinURL, parseURL } from 'ufo'
import { useNuxtApp, useRuntimeConfig } from '../nuxt'
import type { NuxtError } from './error'
import { createError, showError } from './error'
import { useState } from './state'
import type { PageMeta } from '#app'
export const useRouter: typeof _useRouter = () => {
return useNuxtApp()?.$router as Router
}
export const useRoute: typeof _useRoute = () => {
if (process.dev && isProcessingMiddleware()) {
console.warn('[nuxt] Calling `useRoute` within middleware may lead to misleading results. Instead, use the (to, from) arguments passed to the middleware to access the new and old routes.')
}
if (hasInjectionContext()) {
return inject('_route', useNuxtApp()._route)
}
return useNuxtApp()._route
}
export const onBeforeRouteLeave = (guard: NavigationGuard) => {
const unsubscribe = useRouter().beforeEach((to, from, next) => {
if (to === from) { return }
return guard(to, from, next)
})
onUnmounted(unsubscribe)
}
export const onBeforeRouteUpdate = (guard: NavigationGuard) => {
const unsubscribe = useRouter().beforeEach(guard)
onUnmounted(unsubscribe)
}
export interface RouteMiddleware {
(to: RouteLocationNormalized, from: RouteLocationNormalized): ReturnType<NavigationGuard>
}
/*! @__NO_SIDE_EFFECTS__ */
export function defineNuxtRouteMiddleware (middleware: RouteMiddleware) {
return middleware
}
export interface AddRouteMiddlewareOptions {
global?: boolean
}
interface AddRouteMiddleware {
(name: string, middleware: RouteMiddleware, options?: AddRouteMiddlewareOptions): void
(middleware: RouteMiddleware): void
}
export const addRouteMiddleware: AddRouteMiddleware = (name: string | RouteMiddleware, middleware?: RouteMiddleware, options: AddRouteMiddlewareOptions = {}) => {
const nuxtApp = useNuxtApp()
const global = options.global || typeof name !== 'string'
const mw = typeof name !== 'string' ? name : middleware
if (!mw) {
console.warn('[nuxt] No route middleware passed to `addRouteMiddleware`.', name)
return
}
if (global) {
nuxtApp._middleware.global.push(mw)
} else {
nuxtApp._middleware.named[name] = mw
}
}
const isProcessingMiddleware = () => {
try {
if (useNuxtApp()._processingMiddleware) {
return true
}
} catch {
// Within an async middleware
return true
}
return false
}
// Conditional types, either one or other
type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never }
type XOR<T, U> = (T | U) extends Object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U
export type OpenWindowFeatures = {
popup?: boolean
noopener?: boolean
noreferrer?: boolean
} & XOR<{width?: number}, {innerWidth?: number}>
& XOR<{height?: number}, {innerHeight?: number}>
& XOR<{left?: number}, {screenX?: number}>
& XOR<{top?: number}, {screenY?: number}>
export type OpenOptions = {
target: '_blank' | '_parent' | '_self' | '_top' | (string & {})
windowFeatures?: OpenWindowFeatures
}
export interface NavigateToOptions {
replace?: boolean
redirectCode?: number
external?: boolean
open?: OpenOptions
}
export const navigateTo = (to: RouteLocationRaw | undefined | null, options?: NavigateToOptions): Promise<void | NavigationFailure | false> | false | void | RouteLocationRaw => {
if (!to) {
to = '/'
}
const toPath = typeof to === 'string' ? to : ((to as RouteLocationPathRaw).path || '/')
// Early open handler
if (options?.open) {
if (process.client) {
const { target = '_blank', windowFeatures = {} } = options.open
const features = Object.entries(windowFeatures)
.filter(([_, value]) => value !== undefined)
.map(([feature, value]) => `${feature.toLowerCase()}=${value}`)
.join(', ')
open(toPath, target, features)
}
return Promise.resolve()
}
const isExternal = options?.external || hasProtocol(toPath, { acceptRelative: true })
if (isExternal && !options?.external) {
throw new Error('Navigating to external URL is not allowed by default. Use `navigateTo (url, { external: true })`.')
}
if (isExternal && parseURL(toPath).protocol === 'script:') {
throw new Error('Cannot navigate to an URL with script protocol.')
}
const inMiddleware = isProcessingMiddleware()
// Early redirect on client-side
if (process.client && !isExternal && inMiddleware) {
return to
}
const router = useRouter()
if (process.server) {
const nuxtApp = useNuxtApp()
if (nuxtApp.ssrContext) {
const fullPath = typeof to === 'string' || isExternal ? toPath : router.resolve(to).fullPath || '/'
const location = isExternal ? toPath : joinURL(useRuntimeConfig().app.baseURL, fullPath)
async function redirect (response: any) {
// TODO: consider deprecating in favour of `app:rendered` and removing
await nuxtApp.callHook('app:redirected')
const encodedLoc = location.replace(/"/g, '%22')
nuxtApp.ssrContext!._renderResponse = {
statusCode: sanitizeStatusCode(options?.redirectCode || 302, 302),
body: `<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=${encodedLoc}"></head></html>`,
headers: { location }
}
return response
}
// We wait to perform the redirect last in case any other middleware will intercept the redirect
// and redirect somewhere else instead.
if (!isExternal && inMiddleware) {
router.afterEach(final => final.fullPath === fullPath ? redirect(false) : undefined)
return to
}
return redirect(!inMiddleware ? undefined : /* abort route navigation */ false)
}
}
// Client-side redirection using vue-router
if (isExternal) {
if (options?.replace) {
location.replace(toPath)
} else {
location.href = toPath
}
return Promise.resolve()
}
return options?.replace ? router.replace(to) : router.push(to)
}
/** This will abort navigation within a Nuxt route middleware handler. */
export const abortNavigation = (err?: string | Partial<NuxtError>) => {
if (process.dev && !isProcessingMiddleware()) {
throw new Error('abortNavigation() is only usable inside a route middleware handler.')
}
if (!err) { return false }
err = createError(err)
if (err.fatal) {
useNuxtApp().runWithContext(() => showError(err as NuxtError))
}
throw err
}
export const setPageLayout = (layout: string) => {
if (process.server) {
if (process.dev && getCurrentInstance() && useState('_layout').value !== layout) {
console.warn('[warn] [nuxt] `setPageLayout` should not be called to change the layout on the server within a component as this will cause hydration errors.')
}
useState('_layout').value = layout
}
const nuxtApp = useNuxtApp()
if (process.dev && nuxtApp.isHydrating && nuxtApp.payload.serverRendered && useState('_layout').value !== layout) {
console.warn('[warn] [nuxt] `setPageLayout` should not be called to change the layout during hydration as this will cause hydration errors.')
}
const inMiddleware = isProcessingMiddleware()
if (inMiddleware || process.server || nuxtApp.isHydrating) {
const unsubscribe = useRouter().beforeResolve((to) => {
to.meta.layout = layout as Exclude<PageMeta['layout'], Ref | false>
unsubscribe()
})
}
if (!inMiddleware) {
useRoute().meta.layout = layout as Exclude<PageMeta['layout'], Ref | false>
}
}
| packages/nuxt/src/app/composables/router.ts | 1 | https://github.com/nuxt/nuxt/commit/05a8c2d955b9dc7f13e0bc6ad6e347f2a9d40f23 | [
0.018565403297543526,
0.001454911194741726,
0.00016643315029796213,
0.00019096056348644197,
0.003715046914294362
] |
{
"id": 2,
"code_window": [
"describe('navigate external', () => {\n",
" it('should redirect to example.com', async () => {\n",
" const { headers } = await fetch('/navigate-to-external/', { redirect: 'manual' })\n",
"\n",
" expect(headers.get('location')).toEqual('https://example.com/')\n",
" })\n",
"\n",
" it('should redirect to api endpoint', async () => {\n",
" const { headers } = await fetch('/navigate-to-api', { redirect: 'manual' })\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(headers.get('location')).toEqual('https://example.com/?redirect=false#test')\n"
],
"file_path": "test/basic.test.ts",
"type": "replace",
"edit_start_line_idx": 790
} | import { useNuxtApp } from '../nuxt'
import { requestIdleCallback } from '../compat/idle-callback'
export const onNuxtReady = (callback: () => any) => {
if (process.server) { return }
const nuxtApp = useNuxtApp()
if (nuxtApp.isHydrating) {
nuxtApp.hooks.hookOnce('app:suspense:resolve', () => { requestIdleCallback(callback) })
} else {
requestIdleCallback(callback)
}
}
| packages/nuxt/src/app/composables/ready.ts | 0 | https://github.com/nuxt/nuxt/commit/05a8c2d955b9dc7f13e0bc6ad6e347f2a9d40f23 | [
0.00017543451394885778,
0.00017238646978512406,
0.00016933841106947511,
0.00017238646978512406,
0.000003048051439691335
] |
{
"id": 2,
"code_window": [
"describe('navigate external', () => {\n",
" it('should redirect to example.com', async () => {\n",
" const { headers } = await fetch('/navigate-to-external/', { redirect: 'manual' })\n",
"\n",
" expect(headers.get('location')).toEqual('https://example.com/')\n",
" })\n",
"\n",
" it('should redirect to api endpoint', async () => {\n",
" const { headers } = await fetch('/navigate-to-api', { redirect: 'manual' })\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(headers.get('location')).toEqual('https://example.com/?redirect=false#test')\n"
],
"file_path": "test/basic.test.ts",
"type": "replace",
"edit_start_line_idx": 790
} | <template>
<div>
don't look at this
</div>
</template>
<script lang="ts">
export default defineNuxtComponent({
asyncData () {
throw new Error('OH NNNNNNOOOOOOOOOOO')
}
})
</script>
| test/fixtures/basic/pages/legacy-async-data-fail.vue | 0 | https://github.com/nuxt/nuxt/commit/05a8c2d955b9dc7f13e0bc6ad6e347f2a9d40f23 | [
0.00017270768876187503,
0.00017175675020553172,
0.00017080582620110363,
0.00017175675020553172,
9.509312803857028e-7
] |
{
"id": 2,
"code_window": [
"describe('navigate external', () => {\n",
" it('should redirect to example.com', async () => {\n",
" const { headers } = await fetch('/navigate-to-external/', { redirect: 'manual' })\n",
"\n",
" expect(headers.get('location')).toEqual('https://example.com/')\n",
" })\n",
"\n",
" it('should redirect to api endpoint', async () => {\n",
" const { headers } = await fetch('/navigate-to-api', { redirect: 'manual' })\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(headers.get('location')).toEqual('https://example.com/?redirect=false#test')\n"
],
"file_path": "test/basic.test.ts",
"type": "replace",
"edit_start_line_idx": 790
} | {
"name": "@nuxt/webpack-builder",
"version": "3.5.3",
"repository": "nuxt/nuxt",
"license": "MIT",
"type": "module",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs"
},
"./dist/*": "./dist/*"
},
"files": [
"dist"
],
"scripts": {
"prepack": "unbuild"
},
"dependencies": {
"@nuxt/friendly-errors-webpack-plugin": "^2.5.2",
"@nuxt/kit": "workspace:../kit",
"autoprefixer": "^10.4.14",
"css-loader": "^6.8.1",
"css-minimizer-webpack-plugin": "^5.0.0",
"cssnano": "^6.0.1",
"esbuild-loader": "^3.0.1",
"escape-string-regexp": "^5.0.0",
"estree-walker": "^3.0.3",
"file-loader": "^6.2.0",
"fork-ts-checker-webpack-plugin": "^8.0.0",
"fs-extra": "^11.1.1",
"h3": "^1.6.6",
"hash-sum": "^2.0.0",
"lodash-es": "^4.17.21",
"magic-string": "^0.30.0",
"memfs": "^3.5.3",
"mini-css-extract-plugin": "^2.7.6",
"mlly": "^1.3.0",
"ohash": "^1.1.2",
"pathe": "^1.1.1",
"pify": "^6.1.0",
"postcss": "^8.4.24",
"postcss-import": "^15.1.0",
"postcss-loader": "^7.3.3",
"postcss-url": "^10.1.3",
"pug-plain-loader": "^1.1.0",
"std-env": "^3.3.3",
"time-fix-plugin": "^2.0.7",
"ufo": "^1.1.2",
"unplugin": "^1.3.1",
"url-loader": "^4.1.1",
"vue-bundle-renderer": "^1.0.3",
"vue-loader": "^17.2.2",
"webpack": "^5.86.0",
"webpack-bundle-analyzer": "^4.9.0",
"webpack-dev-middleware": "^6.1.1",
"webpack-hot-middleware": "^2.25.3",
"webpack-virtual-modules": "^0.5.0",
"webpackbar": "^5.0.2"
},
"devDependencies": {
"@nuxt/schema": "workspace:../schema",
"@types/fs-extra": "11.0.1",
"@types/lodash-es": "4.17.7",
"@types/pify": "5.0.1",
"@types/webpack-bundle-analyzer": "4.6.0",
"@types/webpack-hot-middleware": "2.25.6",
"@types/webpack-virtual-modules": "0.1.1",
"unbuild": "latest",
"vue": "3.3.4"
},
"peerDependencies": {
"vue": "^3.3.4"
},
"engines": {
"node": "^14.18.0 || >=16.10.0"
}
}
| packages/webpack/package.json | 0 | https://github.com/nuxt/nuxt/commit/05a8c2d955b9dc7f13e0bc6ad6e347f2a9d40f23 | [
0.0002486832672730088,
0.0001808131200959906,
0.00017079475219361484,
0.0001721112639643252,
0.00002405546183581464
] |
{
"id": 3,
"code_window": [
" await fsp.writeFile(join(rootDir, '.output/test-stats.json'), JSON.stringify(stats, null, 2))\n",
" })\n",
"\n",
" it('default client bundle size', async () => {\n",
" stats.client = await analyzeSizes('**/*.js', publicDir)\n",
" expect(roundToKilobytes(stats.client.totalBytes)).toMatchInlineSnapshot('\"97.1k\"')\n",
" expect(stats.client.files.map(f => f.replace(/\\..*\\.js/, '.js'))).toMatchInlineSnapshot(`\n",
" [\n",
" \"_nuxt/entry.js\",\n",
" ]\n",
" `)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(roundToKilobytes(stats.client.totalBytes)).toMatchInlineSnapshot('\"97.2k\"')\n"
],
"file_path": "test/bundle.test.ts",
"type": "replace",
"edit_start_line_idx": 27
} | import { fileURLToPath } from 'node:url'
import fsp from 'node:fs/promises'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { execaCommand } from 'execa'
import { globby } from 'globby'
import { join } from 'pathe'
describe.skipIf(process.env.SKIP_BUNDLE_SIZE === 'true' || process.env.ECOSYSTEM_CI)('minimal nuxt application', () => {
const rootDir = fileURLToPath(new URL('./fixtures/minimal', import.meta.url))
const publicDir = join(rootDir, '.output/public')
const serverDir = join(rootDir, '.output/server')
const stats = {
client: { totalBytes: 0, files: [] as string[] },
server: { totalBytes: 0, files: [] as string[] }
}
beforeAll(async () => {
await execaCommand(`pnpm nuxi build ${rootDir}`)
}, 120 * 1000)
afterAll(async () => {
await fsp.writeFile(join(rootDir, '.output/test-stats.json'), JSON.stringify(stats, null, 2))
})
it('default client bundle size', async () => {
stats.client = await analyzeSizes('**/*.js', publicDir)
expect(roundToKilobytes(stats.client.totalBytes)).toMatchInlineSnapshot('"97.1k"')
expect(stats.client.files.map(f => f.replace(/\..*\.js/, '.js'))).toMatchInlineSnapshot(`
[
"_nuxt/entry.js",
]
`)
})
it('default server bundle size', async () => {
stats.server = await analyzeSizes(['**/*.mjs', '!node_modules'], serverDir)
expect(roundToKilobytes(stats.server.totalBytes)).toMatchInlineSnapshot('"61.9k"')
const modules = await analyzeSizes('node_modules/**/*', serverDir)
expect(roundToKilobytes(modules.totalBytes)).toMatchInlineSnapshot('"2286k"')
const packages = modules.files
.filter(m => m.endsWith('package.json'))
.map(m => m.replace('/package.json', '').replace('node_modules/', ''))
.sort()
expect(packages).toMatchInlineSnapshot(`
[
"@babel/parser",
"@unhead/dom",
"@unhead/shared",
"@unhead/ssr",
"@vue/compiler-core",
"@vue/compiler-dom",
"@vue/compiler-ssr",
"@vue/reactivity",
"@vue/runtime-core",
"@vue/runtime-dom",
"@vue/server-renderer",
"@vue/shared",
"cookie-es",
"defu",
"destr",
"devalue",
"estree-walker",
"h3",
"hookable",
"iron-webcrypto",
"klona",
"node-fetch-native",
"ofetch",
"ohash",
"pathe",
"radix3",
"scule",
"source-map-js",
"ufo",
"uncrypto",
"unctx",
"unenv",
"unhead",
"unstorage",
"vue",
"vue-bundle-renderer",
]
`)
})
})
async function analyzeSizes (pattern: string | string[], rootDir: string) {
const files: string[] = await globby(pattern, { cwd: rootDir })
let totalBytes = 0
for (const file of files) {
const path = join(rootDir, file)
const isSymlink = (await fsp.lstat(path).catch(() => null))?.isSymbolicLink()
if (!isSymlink) {
const bytes = Buffer.byteLength(await fsp.readFile(path))
totalBytes += bytes
}
}
return { files, totalBytes }
}
function roundToKilobytes (bytes: number) {
return (bytes / 1024).toFixed(bytes > (100 * 1024) ? 0 : 1) + 'k'
}
| test/bundle.test.ts | 1 | https://github.com/nuxt/nuxt/commit/05a8c2d955b9dc7f13e0bc6ad6e347f2a9d40f23 | [
0.9978716373443604,
0.09203989803791046,
0.00017298638704232872,
0.001395445317029953,
0.2864527702331543
] |
{
"id": 3,
"code_window": [
" await fsp.writeFile(join(rootDir, '.output/test-stats.json'), JSON.stringify(stats, null, 2))\n",
" })\n",
"\n",
" it('default client bundle size', async () => {\n",
" stats.client = await analyzeSizes('**/*.js', publicDir)\n",
" expect(roundToKilobytes(stats.client.totalBytes)).toMatchInlineSnapshot('\"97.1k\"')\n",
" expect(stats.client.files.map(f => f.replace(/\\..*\\.js/, '.js'))).toMatchInlineSnapshot(`\n",
" [\n",
" \"_nuxt/entry.js\",\n",
" ]\n",
" `)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(roundToKilobytes(stats.client.totalBytes)).toMatchInlineSnapshot('\"97.2k\"')\n"
],
"file_path": "test/bundle.test.ts",
"type": "replace",
"edit_start_line_idx": 27
} | # `useFetch`
This composable provides a convenient wrapper around [`useAsyncData`](/docs/api/composables/use-async-data) and [`$fetch`](/docs/api/utils/dollarfetch).
It automatically generates a key based on URL and fetch options, provides type hints for request url based on server routes, and infers API response type.
::alert{type=warning}
`useFetch` is a composable meant to be called directly in a setup function, plugin, or route middleware. It returns reactive composables and handles adding responses to the Nuxt payload so they can be passed from server to client without re-fetching the data on client side when the page hydrates.
::
## Type
```ts [Signature]
function useFetch(
url: string | Request | Ref<string | Request> | () => string | Request,
options?: UseFetchOptions<DataT>
): Promise<AsyncData<DataT>>
type UseFetchOptions = {
key?: string
method?: string
query?: SearchParams
params?: SearchParams
body?: RequestInit['body'] | Record<string, any>
headers?: Record<string, string> | [key: string, value: string][] | Headers
baseURL?: string
server?: boolean
lazy?: boolean
immediate?: boolean
default?: () => DataT
transform?: (input: DataT) => DataT
pick?: string[]
watch?: WatchSource[]
}
type AsyncData<DataT, ErrorT> = {
data: Ref<DataT | null>
pending: Ref<boolean>
refresh: (opts?: AsyncDataExecuteOptions) => Promise<void>
execute: (opts?: AsyncDataExecuteOptions) => Promise<void>
error: Ref<ErrorT | null>
}
interface AsyncDataExecuteOptions {
dedupe?: boolean
}
```
## Params
* **URL**: The URL to fetch.
* **Options (extends [unjs/ofetch](https://github.com/unjs/ofetch) options & [AsyncDataOptions](/docs/api/composables/use-async-data#params))**:
* `method`: Request method.
* `query`: Adds query search params to URL using [ufo](https://github.com/unjs/ufo)
* `params`: Alias for `query`
* `body`: Request body - automatically stringified (if an object is passed).
* `headers`: Request headers.
* `baseURL`: Base URL for the request.
::alert{type=info}
All fetch options can be given a `computed` or `ref` value. These will be watched and new requests made automatically with any new values if they are updated.
::
* **Options (from `useAsyncData`)**:
* `key`: a unique key to ensure that data fetching can be properly de-duplicated across requests, if not provided, it will be generated based on the static code location where `useAsyncData` is used.
* `server`: Whether to fetch the data on the server (defaults to `true`).
* `default`: A factory function to set the default value of the data, before the async function resolves - particularly useful with the `lazy: true` option.
* `pick`: Only pick specified keys in this array from the `handler` function result.
* `watch`: Watch an array of reactive sources and auto-refresh the fetch result when they change. Fetch options and URL are watched by default. You can completely ignore reactive sources by using `watch: false`. Together with `immediate: false`, this allows for a fully-manual `useFetch`.
* `transform`: A function that can be used to alter `handler` function result after resolving.
* `immediate`: When set to `false`, will prevent the request from firing immediately. (defaults to `true`)
::alert{type=warning}
If you provide a function or ref as the `url` parameter, or if you provide functions as arguments to the `options` parameter, then the `useFetch` call will not match other `useFetch` calls elsewhere in your codebase, even if the options seem to be identical. If you wish to force a match, you may provide your own key in `options`.
::
## Return Values
* **data**: the result of the asynchronous function that is passed in.
* **pending**: a boolean indicating whether the data is still being fetched.
* **refresh**/**execute** : a function that can be used to refresh the data returned by the `handler` function.
* **error**: an error object if the data fetching failed.
By default, Nuxt waits until a `refresh` is finished before it can be executed again.
::alert{type=warning}
If you have not fetched data on the server (for example, with `server: false`), then the data _will not_ be fetched until hydration completes. This means even if you await `useFetch` on client-side, `data` will remain null within `<script setup>`.
::
## Example
```ts
const { data, pending, error, refresh } = await useFetch('https://api.nuxtjs.dev/mountains',{
pick: ['title']
})
```
Adding Query Search Params:
Using the `query` option, you can add search parameters to your query. This option is extended from [unjs/ofetch](https://github.com/unjs/ofetch) and is using [unjs/ufo](https://github.com/unjs/ufo) to create the URL. Objects are automatically stringified.
```ts
const param1 = ref('value1')
const { data, pending, error, refresh } = await useFetch('https://api.nuxtjs.dev/mountains',{
query: { param1, param2: 'value2' }
})
```
Results in `https://api.nuxtjs.dev/mountains?param1=value1¶m2=value2`
Using [interceptors](https://github.com/unjs/ofetch#%EF%B8%8F-interceptors):
```ts
const { data, pending, error, refresh } = await useFetch('/api/auth/login', {
onRequest({ request, options }) {
// Set the request headers
options.headers = options.headers || {}
options.headers.authorization = '...'
},
onRequestError({ request, options, error }) {
// Handle the request errors
},
onResponse({ request, response, options }) {
// Process the response data
localStorage.setItem('token', response._data.token)
},
onResponseError({ request, response, options }) {
// Handle the response errors
}
})
```
::alert{type=warning}
`useFetch` is a reserved function name transformed by the compiler, so you should not name your own function `useFetch`.
::
::LinkExample{link="/docs/examples/other/use-custom-fetch-composable"}
::
:ReadMore{link="/docs/getting-started/data-fetching"}
::LinkExample{link="/docs/examples/composables/use-fetch"}
::
| docs/3.api/1.composables/use-fetch.md | 0 | https://github.com/nuxt/nuxt/commit/05a8c2d955b9dc7f13e0bc6ad6e347f2a9d40f23 | [
0.00019735901150852442,
0.00017079035751521587,
0.00016025140939746052,
0.00017083415878005326,
0.000009262491403205786
] |
{
"id": 3,
"code_window": [
" await fsp.writeFile(join(rootDir, '.output/test-stats.json'), JSON.stringify(stats, null, 2))\n",
" })\n",
"\n",
" it('default client bundle size', async () => {\n",
" stats.client = await analyzeSizes('**/*.js', publicDir)\n",
" expect(roundToKilobytes(stats.client.totalBytes)).toMatchInlineSnapshot('\"97.1k\"')\n",
" expect(stats.client.files.map(f => f.replace(/\\..*\\.js/, '.js'))).toMatchInlineSnapshot(`\n",
" [\n",
" \"_nuxt/entry.js\",\n",
" ]\n",
" `)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(roundToKilobytes(stats.client.totalBytes)).toMatchInlineSnapshot('\"97.2k\"')\n"
],
"file_path": "test/bundle.test.ts",
"type": "replace",
"edit_start_line_idx": 27
} | name: "\U0001F41E Bug report (Nuxt 2)"
description: Create a report to help us improve Nuxt
labels: ["pending triage", "2.x"]
body:
- type: markdown
attributes:
value: |
Please carefully read the contribution docs before creating a bug report
👉 https://nuxt.com/docs/community/reporting-bugs
Please use a template below to create a minimal reproduction
👉 https://stackblitz.com/github/nuxt/starter/tree/v2
👉 https://codesandbox.io/p/github/nuxt/starter/v2
- type: textarea
id: bug-env
attributes:
label: Environment
description: You can use `npx envinfo --system --npmPackages '{nuxt,@nuxt/*}' --binaries --browsers` to fill this section
placeholder: Environment
validations:
required: true
- type: textarea
id: reproduction
attributes:
label: Reproduction
description: Please provide a link to a repo that can reproduce the problem you ran into. A [**minimal reproduction**](https://nuxt.com/docs/community/reporting-bugs#create-a-minimal-reproduction) is required unless you are absolutely sure that the issue is obvious and the provided information is enough to understand the problem. If a report is vague (e.g. just a generic error message) and has no reproduction, it will receive a "need reproduction" label. If no reproduction is provided we might close it.
placeholder: Reproduction
validations:
required: true
- type: textarea
id: bug-description
attributes:
label: Describe the bug
description: A clear and concise description of what the bug is. If you intend to submit a PR for this issue, tell us in the description. Thanks!
placeholder: Bug description
validations:
required: true
- type: textarea
id: additonal
attributes:
label: Additional context
description: If applicable, add any other context about the problem here
- type: textarea
id: logs
attributes:
label: Logs
description: |
Optional if provided reproduction. Please try not to insert an image but copy paste the log text.
render: shell-script
| .github/ISSUE_TEMPLATE/z-bug-report-2.yml | 0 | https://github.com/nuxt/nuxt/commit/05a8c2d955b9dc7f13e0bc6ad6e347f2a9d40f23 | [
0.0001790837850421667,
0.00017400147044099867,
0.00016664132999721915,
0.00017597715486772358,
0.0000046380405365198385
] |
{
"id": 3,
"code_window": [
" await fsp.writeFile(join(rootDir, '.output/test-stats.json'), JSON.stringify(stats, null, 2))\n",
" })\n",
"\n",
" it('default client bundle size', async () => {\n",
" stats.client = await analyzeSizes('**/*.js', publicDir)\n",
" expect(roundToKilobytes(stats.client.totalBytes)).toMatchInlineSnapshot('\"97.1k\"')\n",
" expect(stats.client.files.map(f => f.replace(/\\..*\\.js/, '.js'))).toMatchInlineSnapshot(`\n",
" [\n",
" \"_nuxt/entry.js\",\n",
" ]\n",
" `)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(roundToKilobytes(stats.client.totalBytes)).toMatchInlineSnapshot('\"97.2k\"')\n"
],
"file_path": "test/bundle.test.ts",
"type": "replace",
"edit_start_line_idx": 27
} | export const namedExport = defineComponent({
setup: () => () => h('div', 'This is a custom component with a named export.')
})
| test/fixtures/basic/other-components-folder/named-export.ts | 0 | https://github.com/nuxt/nuxt/commit/05a8c2d955b9dc7f13e0bc6ad6e347f2a9d40f23 | [
0.00017151396605186164,
0.00017151396605186164,
0.00017151396605186164,
0.00017151396605186164,
0
] |
{
"id": 4,
"code_window": [
" throw new Error('this should not run')\n",
" })\n",
"}\n",
"await navigateTo('https://example.com/', { external: true, replace: true })\n",
"</script>"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"await navigateTo({ path: 'https://example.com/', query: { redirect: false }, hash: '#test' }, { external: true, replace: true })\n"
],
"file_path": "test/fixtures/basic/pages/navigate-to-external.vue",
"type": "replace",
"edit_start_line_idx": 10
} | import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
import { joinURL, withQuery } from 'ufo'
import { isCI, isWindows } from 'std-env'
import { normalize } from 'pathe'
import { $fetch, createPage, fetch, isDev, setup, startServer, url } from '@nuxt/test-utils'
import { $fetchComponent } from '@nuxt/test-utils/experimental'
import type { NuxtIslandResponse } from '../packages/nuxt/src/core/runtime/nitro/renderer'
import { expectNoClientErrors, expectWithPolling, isRenderingJson, parseData, parsePayload, renderPage, withLogs } from './utils'
const isWebpack = process.env.TEST_BUILDER === 'webpack'
await setup({
rootDir: fileURLToPath(new URL('./fixtures/basic', import.meta.url)),
dev: process.env.TEST_ENV === 'dev',
server: true,
browser: true,
setupTimeout: (isWindows ? 240 : 120) * 1000,
nuxtConfig: {
builder: isWebpack ? 'webpack' : 'vite',
buildDir: process.env.NITRO_BUILD_DIR,
nitro: { output: { dir: process.env.NITRO_OUTPUT_DIR } }
}
})
describe('server api', () => {
it('should serialize', async () => {
expect(await $fetch('/api/hello')).toBe('Hello API')
expect(await $fetch('/api/hey')).toEqual({
foo: 'bar',
baz: 'qux'
})
})
it('should preserve states', async () => {
expect(await $fetch('/api/counter')).toEqual({ count: 0 })
expect(await $fetch('/api/counter')).toEqual({ count: 1 })
expect(await $fetch('/api/counter')).toEqual({ count: 2 })
expect(await $fetch('/api/counter')).toEqual({ count: 3 })
})
})
describe('route rules', () => {
it('should enable spa mode', async () => {
const { script, attrs } = parseData(await $fetch('/route-rules/spa'))
expect(script.serverRendered).toEqual(false)
if (isRenderingJson) {
expect(attrs['data-ssr']).toEqual('false')
}
await expectNoClientErrors('/route-rules/spa')
})
it('test noScript routeRules', async () => {
const page = await createPage('/no-scripts')
expect(await page.locator('script').all()).toHaveLength(0)
await page.close()
})
})
describe('modules', () => {
it('should auto-register modules in ~/modules', async () => {
const result = await $fetch('/auto-registered-module')
expect(result).toEqual('handler added by auto-registered module')
})
})
describe('pages', () => {
it('render index', async () => {
const html = await $fetch('/')
// Snapshot
// expect(html).toMatchInlineSnapshot()
// should render text
expect(html).toContain('Hello Nuxt 3!')
// should inject runtime config
expect(html).toContain('RuntimeConfig | testConfig: 123')
expect(html).toContain('needsFallback:')
// composables auto import
expect(html).toContain('Composable | foo: auto imported from ~/composables/foo.ts')
expect(html).toContain('Composable | bar: auto imported from ~/utils/useBar.ts')
expect(html).toContain('Composable | template: auto imported from ~/composables/template.ts')
expect(html).toContain('Composable | star: auto imported from ~/composables/nested/bar.ts via star export')
// should import components
expect(html).toContain('This is a custom component with a named export.')
// should remove dev-only and replace with any fallback content
expect(html).toContain(isDev() ? 'Some dev-only info' : 'Some prod-only info')
// should apply attributes to client-only components
expect(html).toContain('<div style="color:red;" class="client-only"></div>')
// should render server-only components
expect(html.replace(/ nuxt-ssr-component-uid="[^"]*"/, '')).toContain('<div class="server-only" style="background-color:gray;"> server-only component </div>')
// should register global components automatically
expect(html).toContain('global component registered automatically')
expect(html).toContain('global component via suffix')
await expectNoClientErrors('/')
})
// TODO: support jsx with webpack
it.runIf(!isWebpack)('supports jsx', async () => {
const html = await $fetch('/jsx')
// should import JSX/TSX components with custom elements
expect(html).toContain('TSX component')
expect(html).toContain('<custom-component>custom</custom-component>')
})
it('respects aliases in page metadata', async () => {
const html = await $fetch('/some-alias')
expect(html).toContain('Hello Nuxt 3!')
})
it('respects redirects in page metadata', async () => {
const { headers } = await fetch('/redirect', { redirect: 'manual' })
expect(headers.get('location')).toEqual('/')
})
it('includes page metadata from pages added in pages:extend hook', async () => {
const res = await fetch('/page-extend')
expect(res.headers.get('x-extend')).toEqual('added in pages:extend')
})
it('validates routes', async () => {
const { status, headers } = await fetch('/forbidden')
expect(status).toEqual(404)
expect(headers.get('Set-Cookie')).toBe('set-in-plugin=true; Path=/')
const page = await createPage('/navigate-to-forbidden')
await page.waitForLoadState('networkidle')
await page.getByText('should throw a 404 error').click()
expect(await page.getByRole('heading').textContent()).toMatchInlineSnapshot('"Page Not Found: /forbidden"')
await page.goto(url('/navigate-to-forbidden'))
await page.waitForLoadState('networkidle')
await page.getByText('should be caught by catchall').click()
expect(await page.getByRole('heading').textContent()).toMatchInlineSnapshot('"[...slug].vue"')
await page.close()
})
it('returns 500 when there is an infinite redirect', async () => {
const { status } = await fetch('/redirect-infinite', { redirect: 'manual' })
expect(status).toEqual(500)
})
it('render catchall page', async () => {
const res = await fetch('/not-found')
expect(res.status).toEqual(200)
const html = await res.text()
// Snapshot
// expect(html).toMatchInlineSnapshot()
expect(html).toContain('[...slug].vue')
expect(html).toContain('catchall at not-found')
// Middleware still runs after validation: https://github.com/nuxt/nuxt/issues/15650
expect(html).toContain('Middleware ran: true')
await expectNoClientErrors('/not-found')
})
it('should render correctly when loaded on a different path', async () => {
const page = await createPage('/proxy')
await page.waitForLoadState('networkidle')
expect(await page.innerText('body')).toContain('Composable | foo: auto imported from ~/composables/foo.ts')
await expectNoClientErrors('/proxy')
})
it('preserves query', async () => {
const html = await $fetch('/?test=true')
// Snapshot
// expect(html).toMatchInlineSnapshot()
// should render text
expect(html).toContain('Path: /?test=true')
await expectNoClientErrors('/?test=true')
})
it('/nested/[foo]/[bar].vue', async () => {
const html = await $fetch('/nested/one/two')
// Snapshot
// expect(html).toMatchInlineSnapshot()
expect(html).toContain('nested/[foo]/[bar].vue')
expect(html).toContain('foo: one')
expect(html).toContain('bar: two')
})
it('/nested/[foo]/index.vue', async () => {
const html = await $fetch('/nested/foobar')
// TODO: should resolved to same entry
// const html2 = await $fetch('/nested/foobar/index')
// expect(html).toEqual(html2)
// Snapshot
// expect(html).toMatchInlineSnapshot()
expect(html).toContain('nested/[foo]/index.vue')
expect(html).toContain('foo: foobar')
await expectNoClientErrors('/nested/foobar')
})
it('/nested/[foo]/user-[group].vue', async () => {
const html = await $fetch('/nested/foobar/user-admin')
// Snapshot
// expect(html).toMatchInlineSnapshot()
expect(html).toContain('nested/[foo]/user-[group].vue')
expect(html).toContain('foo: foobar')
expect(html).toContain('group: admin')
await expectNoClientErrors('/nested/foobar/user-admin')
})
it('/parent', async () => {
const html = await $fetch('/parent')
expect(html).toContain('parent/index')
await expectNoClientErrors('/parent')
})
it('/another-parent', async () => {
const html = await $fetch('/another-parent')
expect(html).toContain('another-parent/index')
await expectNoClientErrors('/another-parent')
})
it('/client-only-components', async () => {
const html = await $fetch('/client-only-components')
// ensure fallbacks with classes and arbitrary attributes are rendered
expect(html).toContain('<div class="client-only-script" foo="bar">')
expect(html).toContain('<div class="client-only-script-setup" foo="hello">')
expect(html).toContain('<div>Fallback</div>')
// ensure components are not rendered server-side
expect(html).not.toContain('Should not be server rendered')
await expectNoClientErrors('/client-only-components')
const page = await createPage('/client-only-components')
await page.waitForLoadState('networkidle')
const hiddenSelectors = [
'.string-stateful-should-be-hidden',
'.client-script-should-be-hidden',
'.string-stateful-script-should-be-hidden',
'.no-state-hidden'
]
const visibleSelectors = [
'.string-stateful',
'.string-stateful-script',
'.client-only-script',
'.client-only-script-setup',
'.no-state'
]
// ensure directives are correctly applied
await Promise.all(hiddenSelectors.map(selector => page.locator(selector).isHidden()))
.then(results => results.forEach(isHidden => expect(isHidden).toBeTruthy()))
// ensure hidden components are still rendered
await Promise.all(hiddenSelectors.map(selector => page.locator(selector).innerHTML()))
.then(results => results.forEach(innerHTML => expect(innerHTML).not.toBe('')))
// ensure single root node components are rendered once on client (should not be empty)
await Promise.all(visibleSelectors.map(selector => page.locator(selector).innerHTML()))
.then(results => results.forEach(innerHTML => expect(innerHTML).not.toBe('')))
// issue #20061
expect(await page.$eval('.client-only-script-setup', e => getComputedStyle(e).backgroundColor)).toBe('rgb(255, 0, 0)')
// ensure multi-root-node is correctly rendered
expect(await page.locator('.multi-root-node-count').innerHTML()).toContain('0')
expect(await page.locator('.multi-root-node-button').innerHTML()).toContain('add 1 to count')
expect(await page.locator('.multi-root-node-script-count').innerHTML()).toContain('0')
expect(await page.locator('.multi-root-node-script-button').innerHTML()).toContain('add 1 to count')
// ensure components reactivity
await page.locator('.multi-root-node-button').click()
await page.locator('.multi-root-node-script-button').click()
await page.locator('.client-only-script button').click()
await page.locator('.client-only-script-setup button').click()
expect(await page.locator('.multi-root-node-count').innerHTML()).toContain('1')
expect(await page.locator('.multi-root-node-script-count').innerHTML()).toContain('1')
expect(await page.locator('.client-only-script-setup button').innerHTML()).toContain('1')
expect(await page.locator('.client-only-script button').innerHTML()).toContain('1')
// ensure components ref is working and reactive
await page.locator('button.test-ref-1').click()
await page.locator('button.test-ref-2').click()
await page.locator('button.test-ref-3').click()
await page.locator('button.test-ref-4').click()
expect(await page.locator('.client-only-script-setup button').innerHTML()).toContain('2')
expect(await page.locator('.client-only-script button').innerHTML()).toContain('2')
expect(await page.locator('.string-stateful-script').innerHTML()).toContain('1')
expect(await page.locator('.string-stateful').innerHTML()).toContain('1')
// ensure directives are reactive
await page.locator('button#show-all').click()
await Promise.all(hiddenSelectors.map(selector => page.locator(selector).isVisible()))
.then(results => results.forEach(isVisible => expect(isVisible).toBeTruthy()))
await page.close()
})
it('/wrapper-expose/layout', async () => {
await expectNoClientErrors('/wrapper-expose/layout')
let lastLog: string|undefined
const page = await createPage('/wrapper-expose/layout')
page.on('console', (log) => {
lastLog = log.text()
})
page.on('pageerror', (log) => {
lastLog = log.message
})
await page.waitForLoadState('networkidle')
await page.locator('.log-foo').first().click()
expect(lastLog).toContain('.logFoo is not a function')
await page.locator('.log-hello').first().click()
expect(lastLog).toContain('world')
await page.locator('.add-count').first().click()
expect(await page.locator('.count').first().innerText()).toContain('1')
// change layout
await page.locator('.swap-layout').click()
await page.waitForTimeout(25)
expect(await page.locator('.count').first().innerText()).toContain('0')
await page.locator('.log-foo').first().click()
expect(lastLog).toContain('bar')
await page.locator('.log-hello').first().click()
expect(lastLog).toContain('.logHello is not a function')
await page.locator('.add-count').first().click()
expect(await page.locator('.count').first().innerText()).toContain('1')
// change layout
await page.locator('.swap-layout').click()
await page.waitForTimeout(25)
expect(await page.locator('.count').first().innerText()).toContain('0')
})
it('/client-only-explicit-import', async () => {
const html = await $fetch('/client-only-explicit-import')
// ensure fallbacks with classes and arbitrary attributes are rendered
expect(html).toContain('<div class="client-only-script" foo="bar">')
expect(html).toContain('<div class="lazy-client-only-script-setup" foo="hello">')
// ensure components are not rendered server-side
expect(html).not.toContain('client only script')
await expectNoClientErrors('/client-only-explicit-import')
})
it('/wrapper-expose/page', async () => {
await expectNoClientErrors('/wrapper-expose/page')
let lastLog: string|undefined
const page = await createPage('/wrapper-expose/page')
page.on('console', (log) => {
lastLog = log.text()
})
page.on('pageerror', (log) => {
lastLog = log.message
})
await page.waitForLoadState('networkidle')
await page.locator('#log-foo').click()
expect(lastLog === 'bar').toBeTruthy()
// change page
await page.locator('#to-hello').click()
await page.locator('#log-foo').click()
expect(lastLog?.includes('.foo is not a function')).toBeTruthy()
await page.locator('#log-hello').click()
expect(lastLog === 'world').toBeTruthy()
})
it('client-fallback', async () => {
const classes = [
'clientfallback-non-stateful-setup',
'clientfallback-non-stateful',
'clientfallback-stateful-setup',
'clientfallback-stateful'
]
const html = await $fetch('/client-fallback')
// ensure failed components are not rendered server-side
expect(html).not.toContain('This breaks in server-side setup.')
classes.forEach(c => expect(html).not.toContain(c))
// ensure not failed component not be rendered
expect(html).not.toContain('Sugar Counter 12 x 0 = 0')
// ensure NuxtClientFallback is being rendered with its fallback tag and attributes
expect(html).toContain('<span class="break-in-ssr">this failed to render</span>')
// ensure Fallback slot is being rendered server side
expect(html).toContain('Hello world !')
// ensure not failed component are correctly rendered
expect(html).not.toContain('<p></p>')
expect(html).toContain('hi')
await expectNoClientErrors('/client-fallback')
const page = await createPage('/client-fallback')
await page.waitForLoadState('networkidle')
// ensure components reactivity once mounted
await page.locator('#increment-count').click()
expect(await page.locator('#sugar-counter').innerHTML()).toContain('Sugar Counter 12 x 1 = 12')
// keep-fallback strategy
expect(await page.locator('#keep-fallback').all()).toHaveLength(1)
// #20833
expect(await page.locator('body').innerHTML()).not.toContain('Hello world !')
await page.close()
})
it('/islands', async () => {
const page = await createPage('/islands')
await page.waitForLoadState('networkidle')
await page.locator('#increase-pure-component').click()
await page.waitForResponse(response => response.url().includes('/__nuxt_island/') && response.status() === 200)
await page.waitForLoadState('networkidle')
expect(await page.locator('#slot-in-server').first().innerHTML()).toContain('Slot with in .server component')
expect(await page.locator('#test-slot').first().innerHTML()).toContain('Slot with name test')
// test fallback slot with v-for
expect(await page.locator('.fallback-slot-content').all()).toHaveLength(2)
// test islands update
expect(await page.locator('.box').innerHTML()).toContain('"number": 101,')
await page.locator('#update-server-components').click()
await Promise.all([
page.waitForResponse(response => response.url().includes('/__nuxt_island/LongAsyncComponent') && response.status() === 200),
page.waitForResponse(response => response.url().includes('/__nuxt_island/AsyncServerComponent') && response.status() === 200)
])
await page.waitForLoadState('networkidle')
expect(await page.locator('#async-server-component-count').innerHTML()).toContain(('1'))
expect(await page.locator('#long-async-component-count').innerHTML()).toContain('1')
// test islands slots interactivity
await page.locator('#first-sugar-counter button').click()
expect(await page.locator('#first-sugar-counter').innerHTML()).toContain('Sugar Counter 13')
// test islands mounted client side with slot
await page.locator('#show-island').click()
await page.waitForResponse(response => response.url().includes('/__nuxt_island/') && response.status() === 200)
await page.waitForLoadState('networkidle')
expect(await page.locator('#island-mounted-client-side').innerHTML()).toContain('Interactive testing slot post SSR')
await page.close()
})
it('/legacy-async-data-fail', async () => {
const response = await fetch('/legacy-async-data-fail').then(r => r.text())
expect(response).not.toContain('don\'t look at this')
expect(response).toContain('OH NNNNNNOOOOOOOOOOO')
})
})
describe('nuxt composables', () => {
it('has useRequestURL()', async () => {
const html = await $fetch('/url')
expect(html).toContain('path: /url')
})
it('sets cookies correctly', async () => {
const res = await fetch('/cookies', {
headers: {
cookie: Object.entries({
'browser-accessed-but-not-used': 'provided-by-browser',
'browser-accessed-with-default-value': 'provided-by-browser',
'browser-set': 'provided-by-browser',
'browser-set-to-null': 'provided-by-browser',
'browser-set-to-null-with-default': 'provided-by-browser'
}).map(([key, value]) => `${key}=${value}`).join('; ')
}
})
const cookies = res.headers.get('set-cookie')
expect(cookies).toMatchInlineSnapshot('"set-in-plugin=true; Path=/, set=set; Path=/, browser-set=set; Path=/, browser-set-to-null=; Max-Age=0; Path=/, browser-set-to-null-with-default=; Max-Age=0; Path=/"')
})
})
describe('rich payloads', () => {
it('correctly serializes and revivifies complex types', async () => {
const html = await $fetch('/json-payload')
for (const test of [
'Date: true',
'Recursive objects: true',
'Shallow reactive: true',
'Shallow ref: true',
'Undefined ref: true',
'Reactive: true',
'Ref: true',
'Error: true'
]) {
expect(html).toContain(test)
}
})
})
describe('nuxt links', () => {
it('handles trailing slashes', async () => {
const html = await $fetch('/nuxt-link/trailing-slash')
const data: Record<string, string[]> = {}
for (const selector of ['nuxt-link', 'router-link', 'link-with-trailing-slash', 'link-without-trailing-slash']) {
data[selector] = []
for (const match of html.matchAll(new RegExp(`href="([^"]*)"[^>]*class="[^"]*\\b${selector}\\b`, 'g'))) {
data[selector].push(match[1])
}
}
expect(data).toMatchInlineSnapshot(`
{
"link-with-trailing-slash": [
"/",
"/nuxt-link/trailing-slash/",
"/nuxt-link/trailing-slash/",
"/nuxt-link/trailing-slash/?test=true&thing=other/thing#thing-other",
"/nuxt-link/trailing-slash/?test=true&thing=other/thing#thing-other",
"/nuxt-link/trailing-slash/",
"/nuxt-link/trailing-slash/?with-state=true",
"/nuxt-link/trailing-slash/?without-state=true",
],
"link-without-trailing-slash": [
"/",
"/nuxt-link/trailing-slash",
"/nuxt-link/trailing-slash",
"/nuxt-link/trailing-slash?test=true&thing=other/thing#thing-other",
"/nuxt-link/trailing-slash?test=true&thing=other/thing#thing-other",
"/nuxt-link/trailing-slash",
"/nuxt-link/trailing-slash?with-state=true",
"/nuxt-link/trailing-slash?without-state=true",
],
"nuxt-link": [
"/",
"/nuxt-link/trailing-slash",
"/nuxt-link/trailing-slash/",
"/nuxt-link/trailing-slash?test=true&thing=other/thing#thing-other",
"/nuxt-link/trailing-slash/?test=true&thing=other/thing#thing-other",
"/nuxt-link/trailing-slash",
"/nuxt-link/trailing-slash?with-state=true",
"/nuxt-link/trailing-slash?without-state=true",
],
"router-link": [
"/",
"/nuxt-link/trailing-slash",
"/nuxt-link/trailing-slash/",
"/nuxt-link/trailing-slash?test=true&thing=other/thing#thing-other",
"/nuxt-link/trailing-slash/?test=true&thing=other/thing#thing-other",
"/nuxt-link/trailing-slash",
"/nuxt-link/trailing-slash?with-state=true",
"/nuxt-link/trailing-slash?without-state=true",
],
}
`)
})
it('preserves route state', async () => {
const page = await createPage('/nuxt-link/trailing-slash')
await page.waitForLoadState('networkidle')
for (const selector of ['nuxt-link', 'router-link', 'link-with-trailing-slash', 'link-without-trailing-slash']) {
await page.locator(`.${selector}[href*=with-state]`).click()
await page.waitForLoadState('networkidle')
expect(await page.getByTestId('window-state').innerText()).toContain('bar')
await page.locator(`.${selector}[href*=without-state]`).click()
await page.waitForLoadState('networkidle')
expect(await page.getByTestId('window-state').innerText()).not.toContain('bar')
}
await page.close()
})
})
describe('head tags', () => {
it('SSR should render tags', async () => {
const headHtml = await $fetch('/head')
expect(headHtml).toContain('<title>Using a dynamic component - Title Template Fn Change</title>')
expect(headHtml).not.toContain('<meta name="description" content="first">')
expect(headHtml).toContain('<meta charset="utf-16">')
expect(headHtml.match('meta charset').length).toEqual(1)
expect(headHtml).toContain('<meta name="viewport" content="width=1024, initial-scale=1">')
expect(headHtml.match('meta name="viewport"').length).toEqual(1)
expect(headHtml).not.toContain('<meta charset="utf-8">')
expect(headHtml).toContain('<meta name="description" content="overriding with an inline useHead call">')
expect(headHtml).toMatch(/<html[^>]*class="html-attrs-test"/)
expect(headHtml).toMatch(/<body[^>]*class="body-attrs-test"/)
expect(headHtml).toContain('<script src="https://a-body-appended-script.com"></script></body>')
const indexHtml = await $fetch('/')
// should render charset by default
expect(indexHtml).toContain('<meta charset="utf-8">')
// should render <Head> components
expect(indexHtml).toContain('<title>Basic fixture</title>')
})
it('SSR script setup should render tags', async () => {
const headHtml = await $fetch('/head-script-setup')
// useHead - title & titleTemplate are working
expect(headHtml).toContain('<title>head script setup - Nuxt Playground</title>')
// useSeoMeta - template params
expect(headHtml).toContain('<meta property="og:title" content="head script setup - Nuxt Playground">')
// useSeoMeta - refs
expect(headHtml).toContain('<meta name="description" content="head script setup description for Nuxt Playground">')
// useServerHead - shorthands
expect(headHtml).toContain('>/* Custom styles */</style>')
// useHeadSafe - removes dangerous content
expect(headHtml).toContain('<script id="xss-script"></script>')
expect(headHtml).toContain('<meta content="0;javascript:alert(1)">')
})
it('SPA should render appHead tags', async () => {
const headHtml = await $fetch('/head', { headers: { 'x-nuxt-no-ssr': '1' } })
expect(headHtml).toContain('<meta name="description" content="Nuxt Fixture">')
expect(headHtml).toContain('<meta charset="utf-8">')
expect(headHtml).toContain('<meta name="viewport" content="width=1024, initial-scale=1">')
})
it('legacy vueuse/head works', async () => {
const headHtml = await $fetch('/vueuse-head')
expect(headHtml).toContain('<title>using provides usehead and updateDOM - VueUse head polyfill test</title>')
})
it('should render http-equiv correctly', async () => {
const html = await $fetch('/head')
// http-equiv should be rendered kebab case
expect(html).toContain('<meta content="default-src https" http-equiv="content-security-policy">')
})
// TODO: Doesn't adds header in test environment
// it.todo('should render stylesheet link tag (SPA mode)', async () => {
// const html = await $fetch('/head', { headers: { 'x-nuxt-no-ssr': '1' } })
// expect(html).toMatch(/<link rel="stylesheet" href="\/_nuxt\/[^>]*.css"/)
// })
})
describe('legacy async data', () => {
it('should work with defineNuxtComponent', async () => {
const html = await $fetch('/legacy/async-data')
expect(html).toContain('<div>Hello API</div>')
expect(html).toContain('<div>fooChild</div>')
expect(html).toContain('<div>fooParent</div>')
const { script } = parseData(html)
expect(script.data['options:asyncdata:hello'].hello).toBe('Hello API')
expect(Object.values(script.data)).toMatchInlineSnapshot(`
[
{
"baz": "qux",
"foo": "bar",
},
{
"hello": "Hello API",
},
{
"fooParent": "fooParent",
},
{
"fooChild": "fooChild",
},
]
`)
})
})
describe('navigate', () => {
it('should redirect to index with navigateTo', async () => {
const { headers, status } = await fetch('/navigate-to/', { redirect: 'manual' })
expect(headers.get('location')).toEqual('/')
expect(status).toEqual(301)
})
it('respects redirects + headers in middleware', async () => {
const res = await fetch('/navigate-some-path/', { redirect: 'manual', headers: { 'trailing-slash': 'true' } })
expect(res.headers.get('location')).toEqual('/navigate-some-path')
expect(res.status).toEqual(307)
expect(await res.text()).toMatchInlineSnapshot('"<!DOCTYPE html><html><head><meta http-equiv=\\"refresh\\" content=\\"0; url=/navigate-some-path\\"></head></html>"')
})
it('should not overwrite headers', async () => {
const { headers, status } = await fetch('/navigate-to-external', { redirect: 'manual' })
expect(headers.get('location')).toEqual('/')
expect(status).toEqual(302)
})
it('should not run setup function in path redirected to', async () => {
const { headers, status } = await fetch('/navigate-to-error', { redirect: 'manual' })
expect(headers.get('location')).toEqual('/setup-should-not-run')
expect(status).toEqual(302)
})
it('supports directly aborting navigation on SSR', async () => {
const { status } = await fetch('/navigate-to-false', { redirect: 'manual' })
expect(status).toEqual(404)
})
})
describe('preserves current instance', () => {
it('should not return getCurrentInstance when there\'s an error in data', async () => {
await fetch('/instance/error')
const html = await $fetch('/instance/next-request')
expect(html).toContain('This should be false: false')
})
// TODO: re-enable when https://github.com/nuxt/nuxt/issues/15164 is resolved
it.skipIf(isWindows)('should not lose current nuxt app after await in vue component', async () => {
const requests = await Promise.all(Array.from({ length: 100 }).map(() => $fetch('/instance/next-request')))
for (const html of requests) {
expect(html).toContain('This should be true: true')
}
})
})
describe('errors', () => {
it('should render a JSON error page', async () => {
const res = await fetch('/error', {
headers: {
accept: 'application/json'
}
})
expect(res.status).toBe(422)
expect(res.statusText).toBe('This is a custom error')
const error = await res.json()
delete error.stack
expect(error).toMatchObject({
message: 'This is a custom error',
statusCode: 422,
statusMessage: 'This is a custom error',
url: '/error'
})
})
it('should render a HTML error page', async () => {
const res = await fetch('/error')
// TODO: remove when we update CI to node v18
if (process.version.startsWith('v16')) {
expect(res.headers.get('Set-Cookie')).toBe('set-in-plugin=true; Path=/')
} else {
expect(res.headers.get('Set-Cookie')).toBe('set-in-plugin=true; Path=/, some-error=was%20set; Path=/')
}
expect(await res.text()).toContain('This is a custom error')
})
it('should not allow accessing error route directly', async () => {
const res = await fetch('/__nuxt_error', {
headers: {
accept: 'application/json'
}
})
expect(res.status).toBe(404)
const error = await res.json()
delete error.stack
expect(error).toMatchInlineSnapshot(`
{
"message": "Page Not Found: /__nuxt_error",
"statusCode": 404,
"statusMessage": "Page Not Found: /__nuxt_error",
"url": "/__nuxt_error",
}
`)
})
// TODO: need to create test for webpack
it.runIf(!isDev() && !isWebpack)('should handle chunk loading errors', async () => {
const { page, consoleLogs } = await renderPage('/')
await page.getByText('Increment state').click()
await page.getByText('Increment state').click()
expect(await page.innerText('div')).toContain('Some value: 3')
await page.getByText('Chunk error').click()
await page.waitForURL(url('/chunk-error'))
expect(consoleLogs.map(c => c.text).join('')).toContain('caught chunk load error')
expect(await page.innerText('div')).toContain('Chunk error page')
await page.waitForLoadState('networkidle')
expect(await page.innerText('div')).toContain('State: 3')
await page.close()
})
})
describe('navigate external', () => {
it('should redirect to example.com', async () => {
const { headers } = await fetch('/navigate-to-external/', { redirect: 'manual' })
expect(headers.get('location')).toEqual('https://example.com/')
})
it('should redirect to api endpoint', async () => {
const { headers } = await fetch('/navigate-to-api', { redirect: 'manual' })
expect(headers.get('location')).toEqual('/api/test')
})
})
describe('middlewares', () => {
it('should redirect to index with global middleware', async () => {
const html = await $fetch('/redirect/')
// Snapshot
// expect(html).toMatchInlineSnapshot()
expect(html).toContain('Hello Nuxt 3!')
})
it('should allow aborting navigation on server-side', async () => {
const res = await fetch('/?abort', {
headers: {
accept: 'application/json'
}
})
expect(res.status).toEqual(401)
})
it('should allow aborting navigation fatally on client-side', async () => {
const html = await $fetch('/middleware-abort')
expect(html).not.toContain('This is the error page')
const page = await createPage('/middleware-abort')
await page.waitForLoadState('networkidle')
expect(await page.innerHTML('body')).toContain('This is the error page')
await page.close()
})
it('should inject auth', async () => {
const html = await $fetch('/auth')
// Snapshot
// expect(html).toMatchInlineSnapshot()
expect(html).toContain('auth.vue')
expect(html).toContain('auth: Injected by injectAuth middleware')
})
it('should not inject auth', async () => {
const html = await $fetch('/no-auth')
// Snapshot
// expect(html).toMatchInlineSnapshot()
expect(html).toContain('no-auth.vue')
expect(html).toContain('auth: ')
expect(html).not.toContain('Injected by injectAuth middleware')
})
it('should redirect to index with http 307 with navigateTo on server side', async () => {
const html = await fetch('/navigate-to-redirect', { redirect: 'manual' })
expect(html.headers.get('location')).toEqual('/')
expect(html.status).toEqual(307)
})
})
describe('plugins', () => {
it('basic plugin', async () => {
const html = await $fetch('/plugins')
expect(html).toContain('myPlugin: Injected by my-plugin')
})
it('async plugin', async () => {
const html = await $fetch('/plugins')
expect(html).toContain('asyncPlugin: Async plugin works! 123')
expect(html).toContain('useFetch works!')
})
})
describe('layouts', () => {
it('should apply custom layout', async () => {
const html = await $fetch('/with-layout')
// Snapshot
// expect(html).toMatchInlineSnapshot()
expect(html).toContain('with-layout.vue')
expect(html).toContain('Custom Layout:')
})
it('should work with a dynamically set layout', async () => {
const html = await $fetch('/with-dynamic-layout')
// Snapshot
// expect(html).toMatchInlineSnapshot()
expect(html).toContain('with-dynamic-layout')
expect(html).toContain('Custom Layout:')
await expectNoClientErrors('/with-dynamic-layout')
})
it('should work with a computed layout', async () => {
const html = await $fetch('/with-computed-layout')
// Snapshot
// expect(html).toMatchInlineSnapshot()
expect(html).toContain('with-computed-layout')
expect(html).toContain('Custom Layout')
await expectNoClientErrors('/with-computed-layout')
})
it('should allow passing custom props to a layout', async () => {
const html = await $fetch('/layouts/with-props')
expect(html).toContain('some prop was passed')
await expectNoClientErrors('/layouts/with-props')
})
})
describe('reactivity transform', () => {
it('should works', async () => {
const html = await $fetch('/')
expect(html).toContain('Sugar Counter 12 x 2 = 24')
})
})
describe('composable tree shaking', () => {
it('should work', async () => {
const html = await $fetch('/tree-shake')
expect(html).toContain('Tree Shake Example')
const page = await createPage('/tree-shake')
// check page doesn't have any errors or warnings in the console
await page.waitForLoadState('networkidle')
// ensure scoped classes are correctly assigned between client and server
expect(await page.$eval('h1', e => getComputedStyle(e).color)).toBe('rgb(255, 192, 203)')
await expectNoClientErrors('/tree-shake')
await page.close()
})
})
describe('server tree shaking', () => {
it('should work', async () => {
const html = await $fetch('/client')
expect(html).toContain('This page should not crash when rendered')
expect(html).toContain('fallback for ClientOnly')
expect(html).not.toContain('rendered client-side')
expect(html).not.toContain('id="client-side"')
const page = await createPage('/client')
await page.waitForLoadState('networkidle')
// ensure scoped classes are correctly assigned between client and server
expect(await page.$eval('.red', e => getComputedStyle(e).color)).toBe('rgb(255, 0, 0)')
expect(await page.$eval('.blue', e => getComputedStyle(e).color)).toBe('rgb(0, 0, 255)')
expect(await page.locator('#client-side').textContent()).toContain('This should be rendered client-side')
await page.close()
})
})
describe('extends support', () => {
describe('layouts & pages', () => {
it('extends foo/layouts/default & foo/pages/index', async () => {
const html = await $fetch('/foo')
expect(html).toContain('Extended layout from foo')
expect(html).toContain('Extended page from foo')
})
it('extends [bar/layouts/override & bar/pages/override] over [foo/layouts/override & foo/pages/override]', async () => {
const html = await $fetch('/override')
expect(html).toContain('Extended layout from bar')
expect(html).toContain('Extended page from bar')
})
})
describe('components', () => {
it('extends foo/components/ExtendsFoo', async () => {
const html = await $fetch('/foo')
expect(html).toContain('Extended component from foo')
})
it('extends bar/components/ExtendsOverride over foo/components/ExtendsOverride', async () => {
const html = await $fetch('/override')
expect(html).toContain('Extended component from bar')
})
})
describe('middlewares', () => {
it('works with layer aliases', async () => {
const html = await $fetch('/foo')
expect(html).toContain('from layer alias')
})
it('extends foo/middleware/foo', async () => {
const html = await $fetch('/foo')
expect(html).toContain('Middleware | foo: Injected by extended middleware from foo')
})
it('extends bar/middleware/override over foo/middleware/override', async () => {
const html = await $fetch('/override')
expect(html).toContain('Middleware | override: Injected by extended middleware from bar')
})
})
describe('composables', () => {
it('extends foo/composables/foo', async () => {
const html = await $fetch('/foo')
expect(html).toContain('Composable | useExtendsFoo: foo')
})
it('allows overriding composables', async () => {
const html = await $fetch('/extends')
expect(html).toContain('test from project')
})
})
describe('plugins', () => {
it('extends foo/plugins/foo', async () => {
const html = await $fetch('/foo')
expect(html).toContain('Plugin | foo: String generated from foo plugin!')
})
})
describe('server', () => {
it('extends foo/server/api/foo', async () => {
expect(await $fetch('/api/foo')).toBe('foo')
})
it('extends foo/server/middleware/foo', async () => {
const { headers } = await fetch('/')
expect(headers.get('injected-header')).toEqual('foo')
})
})
describe('app', () => {
it('extends foo/app/router.options & bar/app/router.options', async () => {
const html: string = await $fetch('/')
const routerLinkClasses = html.match(/href="\/" class="([^"]*)"/)?.[1].split(' ')
expect(routerLinkClasses).toContain('foo-active-class')
expect(routerLinkClasses).toContain('bar-exact-active-class')
})
})
})
// Bug #7337
describe('deferred app suspense resolve', () => {
async function behaviour (path: string) {
await withLogs(async (page, logs) => {
await page.goto(url(path))
await page.waitForLoadState('networkidle')
// Wait for all pending micro ticks to be cleared in case hydration haven't finished yet.
await page.evaluate(() => new Promise(resolve => setTimeout(resolve, 10)))
const hydrationLogs = logs.filter(log => log.includes('isHydrating'))
expect(hydrationLogs.length).toBe(3)
expect(hydrationLogs.every(log => log === 'isHydrating: true'))
})
}
it('should wait for all suspense instance on initial hydration', async () => {
await behaviour('/async-parent/child')
})
it('should wait for all suspense instance on initial hydration', async () => {
await behaviour('/internal-layout/async-parent/child')
})
})
describe('nested suspense', () => {
const navigations = [
['/suspense/sync-1/async-1/', '/suspense/sync-2/async-1/'],
['/suspense/sync-1/sync-1/', '/suspense/sync-2/async-1/'],
['/suspense/async-1/async-1/', '/suspense/async-2/async-1/'],
['/suspense/async-1/sync-1/', '/suspense/async-2/async-1/']
]
it.each(navigations)('should navigate from %s to %s with no white flash', async (start, nav) => {
const page = await createPage(start, {})
await page.waitForLoadState('networkidle')
const slug = nav.replace(/[/-]+/g, '-')
await page.click(`[href^="${nav}"]`)
const text = await page.waitForFunction(slug => document.querySelector(`#${slug}`)?.innerHTML, slug)
// @ts-expect-error TODO: fix upstream in playwright - types for evaluate are broken
.then(r => r.evaluate(r => r))
// expect(text).toMatchInlineSnapshot()
// const parent = await page.waitForSelector(`#${slug}`, { state: 'attached' })
// const text = await parent.innerText()
expect(text).toContain('Async child: 2 - 1')
await page.close()
})
})
// Bug #6592
describe('page key', () => {
it('should not cause run of setup if navigation not change page key and layout', async () => {
async function behaviour (path: string) {
await withLogs(async (page, logs) => {
await page.goto(url(`${path}/0`))
await page.waitForLoadState('networkidle')
await page.click(`[href="${path}/1"]`)
await page.waitForSelector('#page-1')
// Wait for all pending micro ticks to be cleared,
// so we are not resolved too early when there are repeated page loading
await page.evaluate(() => new Promise(resolve => setTimeout(resolve, 10)))
expect(logs.filter(l => l.includes('Child Setup')).length).toBe(1)
})
}
await behaviour('/fixed-keyed-child-parent')
await behaviour('/internal-layout/fixed-keyed-child-parent')
})
it('will cause run of setup if navigation changed page key', async () => {
async function behaviour (path: string) {
await withLogs(async (page, logs) => {
await page.goto(url(`${path}/0`))
await page.waitForLoadState('networkidle')
await page.click(`[href="${path}/1"]`)
await page.waitForSelector('#page-1')
// Wait for all pending micro ticks to be cleared,
// so we are not resolved too early when there are repeated page loading
await page.evaluate(() => new Promise(resolve => setTimeout(resolve, 10)))
expect(logs.filter(l => l.includes('Child Setup')).length).toBe(2)
})
}
await behaviour('/keyed-child-parent')
await behaviour('/internal-layout/keyed-child-parent')
})
})
// Bug #6592
describe('layout change not load page twice', () => {
async function behaviour (path1: string, path2: string) {
await withLogs(async (page, logs) => {
await page.goto(url(path1))
await page.waitForLoadState('networkidle')
await page.click(`[href="${path2}"]`)
await page.waitForSelector('#with-layout2')
// Wait for all pending micro ticks to be cleared,
// so we are not resolved too early when there are repeated page loading
await page.evaluate(() => new Promise(resolve => setTimeout(resolve, 10)))
expect(logs.filter(l => l.includes('Layout2 Page Setup')).length).toBe(1)
})
}
it('should not cause run of page setup to repeat if layout changed', async () => {
await behaviour('/with-layout', '/with-layout2')
await behaviour('/internal-layout/with-layout', '/internal-layout/with-layout2')
})
})
describe('automatically keyed composables', () => {
it('should automatically generate keys', async () => {
const html = await $fetch('/keyed-composables')
expect(html).toContain('true')
expect(html).not.toContain('false')
})
it('should match server-generated keys', async () => {
await expectNoClientErrors('/keyed-composables')
})
it('should not automatically generate keys', async () => {
await expectNoClientErrors('/keyed-composables/local')
const html = await $fetch('/keyed-composables/local')
expect(html).toContain('true')
expect(html).not.toContain('false')
})
})
describe.skipIf(isDev() || isWebpack)('inlining component styles', () => {
it('should inline styles', async () => {
const html = await $fetch('/styles')
for (const style of [
'{--assets:"assets"}', // <script>
'{--scoped:"scoped"}', // <style lang=css>
'{--postcss:"postcss"}' // <style lang=postcss>
]) {
expect(html).toContain(style)
}
})
it('does not load stylesheet for page styles', async () => {
const html: string = await $fetch('/styles')
expect(html.match(/<link [^>]*href="[^"]*\.css">/g)?.filter(m => m.includes('entry'))?.map(m => m.replace(/\.[^.]*\.css/, '.css'))).toMatchInlineSnapshot(`
[
"<link rel=\\"preload\\" as=\\"style\\" href=\\"/_nuxt/entry.css\\">",
"<link rel=\\"stylesheet\\" href=\\"/_nuxt/entry.css\\">",
]
`)
})
it('still downloads client-only styles', async () => {
const page = await createPage('/styles')
await page.waitForLoadState('networkidle')
expect(await page.$eval('.client-only-css', e => getComputedStyle(e).color)).toBe('rgb(50, 50, 50)')
await page.close()
})
it.todo('renders client-only styles only', async () => {
const html = await $fetch('/styles')
expect(html).toContain('{--client-only:"client-only"}')
})
})
describe('prefetching', () => {
it('should prefetch components', async () => {
await expectNoClientErrors('/prefetch/components')
})
it('should not prefetch certain dynamic imports by default', async () => {
const html = await $fetch('/auth')
// should not prefetch global components
expect(html).not.toMatch(/<link [^>]*\/_nuxt\/TestGlobal[^>]*\.js"/)
// should not prefetch all other pages
expect(html).not.toMatch(/<link [^>]*\/_nuxt\/navigate-to[^>]*\.js"/)
})
})
// TODO: make test less flakey on Windows
describe.runIf(isDev() && (!isWindows || !isCI))('detecting invalid root nodes', () => {
it.each(['1', '2', '3', '4'])('should detect invalid root nodes in pages (\'/invalid-root/%s\')', async (path) => {
const { consoleLogs, page } = await renderPage(joinURL('/invalid-root', path))
await page.evaluate(() => new Promise(resolve => setTimeout(resolve, 10)))
await expectWithPolling(
() => consoleLogs
.map(w => w.text).join('\n')
.includes('does not have a single root node and will cause errors when navigating between routes'),
true
)
await page.close()
})
it.each(['fine'])('should not complain if there is no transition (%s)', async (path) => {
const { consoleLogs, page } = await renderPage(joinURL('/invalid-root', path))
await page.evaluate(() => new Promise(resolve => setTimeout(resolve, 10)))
const consoleLogsWarns = consoleLogs.filter(i => i.type === 'warning')
expect(consoleLogsWarns.length).toEqual(0)
await page.close()
})
})
// TODO: dynamic paths in dev
describe.skipIf(isDev())('dynamic paths', () => {
it('should work with no overrides', async () => {
const html: string = await $fetch('/assets')
for (const match of html.matchAll(/(href|src)="(.*?)"|url\(([^)]*?)\)/g)) {
const url = match[2] || match[3]
expect(url.startsWith('/_nuxt/') || url === '/public.svg').toBeTruthy()
}
})
// webpack injects CSS differently
it.skipIf(isWebpack)('adds relative paths to CSS', async () => {
const html: string = await $fetch('/assets')
const urls = Array.from(html.matchAll(/(href|src)="(.*?)"|url\(([^)]*?)\)/g)).map(m => m[2] || m[3])
const cssURL = urls.find(u => /_nuxt\/assets.*\.css$/.test(u))
expect(cssURL).toBeDefined()
const css: string = await $fetch(cssURL!)
const imageUrls = Array.from(css.matchAll(/url\(([^)]*)\)/g)).map(m => m[1].replace(/[-.][\w]{8}\./g, '.'))
expect(imageUrls).toMatchInlineSnapshot(`
[
"./logo.svg",
"../public.svg",
"../public.svg",
"../public.svg",
]
`)
})
it('should allow setting base URL and build assets directory', async () => {
process.env.NUXT_APP_BUILD_ASSETS_DIR = '/_other/'
process.env.NUXT_APP_BASE_URL = '/foo/'
await startServer()
const html = await $fetch('/foo/assets')
for (const match of html.matchAll(/(href|src)="(.*?)"|url\(([^)]*?)\)/g)) {
const url = match[2] || match[3]
expect(
url.startsWith('/foo/_other/') ||
url === '/foo/public.svg' ||
// TODO: webpack does not yet support dynamic static paths
(isWebpack && url === '/public.svg')
).toBeTruthy()
}
})
it('should allow setting relative baseURL', async () => {
delete process.env.NUXT_APP_BUILD_ASSETS_DIR
process.env.NUXT_APP_BASE_URL = './'
await startServer()
const html = await $fetch('/assets')
for (const match of html.matchAll(/(href|src)="(.*?)"|url\(([^)]*?)\)/g)) {
const url = match[2] || match[3]
expect(
url.startsWith('./_nuxt/') ||
url === './public.svg' ||
// TODO: webpack does not yet support dynamic static paths
(isWebpack && url === '/public.svg')
).toBeTruthy()
expect(url.startsWith('./_nuxt/_nuxt')).toBeFalsy()
}
})
it('should use baseURL when redirecting', async () => {
process.env.NUXT_APP_BUILD_ASSETS_DIR = '/_other/'
process.env.NUXT_APP_BASE_URL = '/foo/'
await startServer()
const { headers } = await fetch('/foo/navigate-to/', { redirect: 'manual' })
expect(headers.get('location')).toEqual('/foo/')
})
it('should allow setting CDN URL', async () => {
process.env.NUXT_APP_BASE_URL = '/foo/'
process.env.NUXT_APP_CDN_URL = 'https://example.com/'
process.env.NUXT_APP_BUILD_ASSETS_DIR = '/_cdn/'
await startServer()
const html = await $fetch('/foo/assets')
for (const match of html.matchAll(/(href|src)="(.*?)"|url\(([^)]*?)\)/g)) {
const url = match[2] || match[3]
expect(
url.startsWith('https://example.com/_cdn/') ||
url === 'https://example.com/public.svg' ||
// TODO: webpack does not yet support dynamic static paths
(isWebpack && url === '/public.svg')
).toBeTruthy()
}
})
it('restore server', async () => {
process.env.NUXT_APP_BASE_URL = undefined
process.env.NUXT_APP_CDN_URL = undefined
process.env.NUXT_APP_BUILD_ASSETS_DIR = undefined
await startServer()
})
})
describe('app config', () => {
it('should work', async () => {
const html = await $fetch('/app-config')
const expectedAppConfig = {
fromNuxtConfig: true,
nested: {
val: 2
},
fromLayer: true,
userConfig: 123
}
expect(html).toContain(JSON.stringify(expectedAppConfig))
const serverAppConfig = await $fetch('/api/app-config')
expect(serverAppConfig).toMatchObject({ appConfig: expectedAppConfig })
})
})
describe('component islands', () => {
it('renders components with route', async () => {
const result: NuxtIslandResponse = await $fetch('/__nuxt_island/RouteComponent?url=/foo')
if (isDev()) {
result.head.link = result.head.link.filter(l => !l.href.includes('@nuxt+ui-templates') && (l.href.startsWith('_nuxt/components/islands/') && l.href.includes('_nuxt/components/islands/RouteComponent')))
}
expect(result).toMatchInlineSnapshot(`
{
"head": {
"link": [],
"style": [],
},
"html": "<pre nuxt-ssr-component-uid> Route: /foo
</pre>",
"state": {},
}
`)
})
it('render async component', async () => {
const result: NuxtIslandResponse = await $fetch(withQuery('/__nuxt_island/LongAsyncComponent', {
props: JSON.stringify({
count: 3
})
}))
if (isDev()) {
result.head.link = result.head.link.filter(l => !l.href.includes('@nuxt+ui-templates') && (l.href.startsWith('_nuxt/components/islands/') && l.href.includes('_nuxt/components/islands/LongAsyncComponent')))
}
expect(result).toMatchInlineSnapshot(`
{
"head": {
"link": [],
"style": [],
},
"html": "<div nuxt-ssr-component-uid><div> count is above 2 </div><div style=\\"display:contents;\\" nuxt-ssr-slot-name=\\"default\\"></div> that was very long ... <div id=\\"long-async-component-count\\">3</div><div style=\\"display:contents;\\" nuxt-ssr-slot-name=\\"test\\" nuxt-ssr-slot-data=\\"[{"count":3}]\\"></div><p>hello world !!!</p><div style=\\"display:contents;\\" nuxt-ssr-slot-name=\\"hello\\" nuxt-ssr-slot-data=\\"[{"t":0},{"t":1},{"t":2}]\\"><div nuxt-slot-fallback-start=\\"hello\\"></div><!--[--><div style=\\"display:contents;\\"><div> fallback slot -- index: 0</div></div><div style=\\"display:contents;\\"><div> fallback slot -- index: 1</div></div><div style=\\"display:contents;\\"><div> fallback slot -- index: 2</div></div><!--]--><div nuxt-slot-fallback-end></div></div><div style=\\"display:contents;\\" nuxt-ssr-slot-name=\\"fallback\\" nuxt-ssr-slot-data=\\"[{"t":"fall"},{"t":"back"}]\\"><div nuxt-slot-fallback-start=\\"fallback\\"></div><!--[--><div style=\\"display:contents;\\"><div>fall slot -- index: 0</div><div class=\\"fallback-slot-content\\"> wonderful fallback </div></div><div style=\\"display:contents;\\"><div>back slot -- index: 1</div><div class=\\"fallback-slot-content\\"> wonderful fallback </div></div><!--]--><div nuxt-slot-fallback-end></div></div></div>",
"state": {},
}
`)
})
it('render .server async component', async () => {
const result: NuxtIslandResponse = await $fetch(withQuery('/__nuxt_island/AsyncServerComponent', {
props: JSON.stringify({
count: 2
})
}))
if (isDev()) {
result.head.link = result.head.link.filter(l => !l.href.includes('@nuxt+ui-templates') && (l.href.startsWith('_nuxt/components/islands/') && l.href.includes('_nuxt/components/islands/AsyncServerComponent')))
}
expect(result).toMatchInlineSnapshot(`
{
"head": {
"link": [],
"style": [],
},
"html": "<div nuxt-ssr-component-uid> This is a .server (20ms) async component that was very long ... <div id=\\"async-server-component-count\\">2</div><div style=\\"display:contents;\\" nuxt-ssr-slot-name=\\"default\\"></div></div>",
"state": {},
}
`)
})
it('renders pure components', async () => {
const result: NuxtIslandResponse = await $fetch(withQuery('/__nuxt_island/PureComponent', {
props: JSON.stringify({
bool: false,
number: 3487,
str: 'something',
obj: { foo: 42, bar: false, me: 'hi' }
})
}))
result.html = result.html.replace(/ nuxt-ssr-component-uid="([^"]*)"/g, '')
if (isDev()) {
result.head.link = result.head.link.filter(l => !l.href.includes('@nuxt+ui-templates'))
const fixtureDir = normalize(fileURLToPath(new URL('./fixtures/basic', import.meta.url)))
for (const link of result.head.link) {
link.href = link.href.replace(fixtureDir, '/<rootDir>').replaceAll('//', '/')
link.key = link.key.replace(/-[a-zA-Z0-9]+$/, '')
}
}
result.head.style = result.head.style.map(s => ({
...s,
innerHTML: (s.innerHTML || '').replace(/data-v-[a-z0-9]+/, 'data-v-xxxxx'),
key: s.key.replace(/-[a-zA-Z0-9]+$/, '')
}))
// TODO: fix rendering of styles in webpack
if (!isDev() && !isWebpack) {
expect(result.head).toMatchInlineSnapshot(`
{
"link": [],
"style": [
{
"innerHTML": "pre[data-v-xxxxx]{color:blue}",
"key": "island-style",
},
],
}
`)
} else if (isDev() && !isWebpack) {
expect(result.head).toMatchInlineSnapshot(`
{
"link": [
{
"href": "/_nuxt/components/islands/PureComponent.vue?vue&type=style&index=0&scoped=c0c0cf89&lang.css",
"key": "island-link",
"rel": "stylesheet",
},
],
"style": [],
}
`)
}
expect(result.html.replace(/data-v-\w+|"|<!--.*-->/g, '')).toMatchInlineSnapshot(`
"<div nuxt-ssr-component-uid > Was router enabled: true <br > Props: <pre >{
number: 3487,
str: something,
obj: {
foo: 42,
bar: false,
me: hi
},
bool: false
}</pre></div>"
`)
expect(result.state).toMatchInlineSnapshot(`
{
"$shasRouter": true,
}
`)
})
it('test client-side navigation', async () => {
const page = await createPage('/')
await page.waitForLoadState('networkidle')
await page.click('#islands')
await page.waitForLoadState('networkidle')
await page.locator('#increase-pure-component').click()
await page.waitForResponse(response => response.url().includes('/__nuxt_island/') && response.status() === 200)
await page.waitForLoadState('networkidle')
expect(await page.locator('#slot-in-server').first().innerHTML()).toContain('Slot with in .server component')
expect(await page.locator('#test-slot').first().innerHTML()).toContain('Slot with name test')
// test islands update
expect(await page.locator('.box').innerHTML()).toContain('"number": 101,')
await page.locator('#update-server-components').click()
await Promise.all([
page.waitForResponse(response => response.url().includes('/__nuxt_island/LongAsyncComponent') && response.status() === 200),
page.waitForResponse(response => response.url().includes('/__nuxt_island/AsyncServerComponent') && response.status() === 200)
])
await page.waitForLoadState('networkidle')
expect(await page.locator('#async-server-component-count').innerHTML()).toContain(('1'))
expect(await page.locator('#long-async-component-count').innerHTML()).toContain('1')
// test islands slots interactivity
await page.locator('#first-sugar-counter button').click()
expect(await page.locator('#first-sugar-counter').innerHTML()).toContain('Sugar Counter 13')
await page.close()
})
})
describe.runIf(isDev() && !isWebpack)('vite plugins', () => {
it('does not override vite plugins', async () => {
expect(await $fetch('/vite-plugin-without-path')).toBe('vite-plugin without path')
expect(await $fetch('/__nuxt-test')).toBe('vite-plugin with __nuxt prefix')
})
it('does not allow direct access to nuxt source folder', async () => {
expect(await $fetch('/app.config')).toContain('catchall at')
})
})
describe.skipIf(isDev() || isWindows || !isRenderingJson)('payload rendering', () => {
it('renders a payload', async () => {
const payload = await $fetch('/random/a/_payload.json', { responseType: 'text' })
const data = parsePayload(payload)
expect(typeof data.prerenderedAt).toEqual('number')
expect(data.data).toMatchObject({
hey: {
baz: 'qux',
foo: 'bar'
},
rand_a: expect.arrayContaining([expect.anything()])
})
})
it('does not fetch a prefetched payload', async () => {
const page = await createPage()
const requests = [] as string[]
page.on('request', (req) => {
requests.push(req.url().replace(url('/'), '/'))
})
await page.goto(url('/random/a'))
await page.waitForLoadState('networkidle')
// We are manually prefetching other payloads
expect(requests).toContain('/random/c/_payload.json')
// We are not triggering API requests in the payload
expect(requests).not.toContain(expect.stringContaining('/api/random'))
expect(requests).not.toContain(expect.stringContaining('/__nuxt_island'))
// requests.length = 0
await page.click('[href="/random/b"]')
await page.waitForLoadState('networkidle')
// We are not triggering API requests in the payload in client-side nav
expect(requests).not.toContain('/api/random')
expect(requests).not.toContain(expect.stringContaining('/__nuxt_island'))
// We are fetching a payload we did not prefetch
expect(requests).toContain('/random/b/_payload.json')
// We are not refetching payloads we've already prefetched
// expect(requests.filter(p => p.includes('_payload')).length).toBe(1)
// requests.length = 0
await page.click('[href="/random/c"]')
await page.waitForLoadState('networkidle')
// We are not triggering API requests in the payload in client-side nav
expect(requests).not.toContain('/api/random')
expect(requests).not.toContain(expect.stringContaining('/__nuxt_island'))
// We are not refetching payloads we've already prefetched
// Note: we refetch on dev as urls differ between '' and '?import'
// expect(requests.filter(p => p.includes('_payload')).length).toBe(isDev() ? 1 : 0)
await page.close()
})
})
describe.skipIf(isWindows)('useAsyncData', () => {
it('single request resolves', async () => {
await expectNoClientErrors('/useAsyncData/single')
})
it('two requests resolve', async () => {
await expectNoClientErrors('/useAsyncData/double')
})
it('two requests resolve and sync', async () => {
await $fetch('/useAsyncData/refresh')
})
it('requests can be cancelled/overridden', async () => {
await expectNoClientErrors('/useAsyncData/override')
})
it('two requests made at once resolve and sync', async () => {
await expectNoClientErrors('/useAsyncData/promise-all')
})
it('requests status can be used', async () => {
const html = await $fetch('/useAsyncData/status')
expect(html).toContain('true')
expect(html).not.toContain('false')
const page = await createPage('/useAsyncData/status')
await page.waitForLoadState('networkidle')
expect(await page.locator('#status5-values').textContent()).toContain('idle,pending,success')
await page.close()
})
})
describe.runIf(isDev())('component testing', () => {
it('should work', async () => {
const comp1 = await $fetchComponent('components/SugarCounter.vue', { multiplier: 2 })
expect(comp1).toContain('12 x 2 = 24')
const comp2 = await $fetchComponent('components/SugarCounter.vue', { multiplier: 4 })
expect(comp2).toContain('12 x 4 = 48')
})
})
| test/basic.test.ts | 1 | https://github.com/nuxt/nuxt/commit/05a8c2d955b9dc7f13e0bc6ad6e347f2a9d40f23 | [
0.01338894385844469,
0.0003788016038015485,
0.00016360597510356456,
0.00016737480473238975,
0.0011581979924812913
] |
{
"id": 4,
"code_window": [
" throw new Error('this should not run')\n",
" })\n",
"}\n",
"await navigateTo('https://example.com/', { external: true, replace: true })\n",
"</script>"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"await navigateTo({ path: 'https://example.com/', query: { redirect: false }, hash: '#test' }, { external: true, replace: true })\n"
],
"file_path": "test/fixtures/basic/pages/navigate-to-external.vue",
"type": "replace",
"edit_start_line_idx": 10
} | <script setup lang="ts">
const props = defineProps<{ foo: string }>()
</script>
<template>
<div>
<div>client only script setup component {{ props.foo }}</div>
<slot name="test" />
</div>
</template>
| test/fixtures/basic/components/ClientOnlySetupScript.client.vue | 0 | https://github.com/nuxt/nuxt/commit/05a8c2d955b9dc7f13e0bc6ad6e347f2a9d40f23 | [
0.00031716146622784436,
0.00024477974511682987,
0.00017239805310964584,
0.00024477974511682987,
0.00007238170655909926
] |
{
"id": 4,
"code_window": [
" throw new Error('this should not run')\n",
" })\n",
"}\n",
"await navigateTo('https://example.com/', { external: true, replace: true })\n",
"</script>"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"await navigateTo({ path: 'https://example.com/', query: { redirect: false }, hash: '#test' }, { external: true, replace: true })\n"
],
"file_path": "test/fixtures/basic/pages/navigate-to-external.vue",
"type": "replace",
"edit_start_line_idx": 10
} | import { useNuxt } from '@nuxt/kit'
import escapeRegExp from 'escape-string-regexp'
import { normalize } from 'pathe'
interface Envs {
isDev: boolean
isClient?: boolean
isServer?: boolean
}
export function transpile (envs: Envs): Array<string | RegExp> {
const nuxt = useNuxt()
const transpile = []
for (let pattern of nuxt.options.build.transpile) {
if (typeof pattern === 'function') {
const result = pattern(envs)
if (result) { pattern = result }
}
if (typeof pattern === 'string') {
transpile.push(new RegExp(escapeRegExp(normalize(pattern))))
} else if (pattern instanceof RegExp) {
transpile.push(pattern)
}
}
return transpile
}
| packages/vite/src/utils/transpile.ts | 0 | https://github.com/nuxt/nuxt/commit/05a8c2d955b9dc7f13e0bc6ad6e347f2a9d40f23 | [
0.00016997155034914613,
0.00016887574747670442,
0.0001675649982644245,
0.00016909072292037308,
9.941599046214833e-7
] |
{
"id": 4,
"code_window": [
" throw new Error('this should not run')\n",
" })\n",
"}\n",
"await navigateTo('https://example.com/', { external: true, replace: true })\n",
"</script>"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"await navigateTo({ path: 'https://example.com/', query: { redirect: false }, hash: '#test' }, { external: true, replace: true })\n"
],
"file_path": "test/fixtures/basic/pages/navigate-to-external.vue",
"type": "replace",
"edit_start_line_idx": 10
} | <template>
<NuxtExampleLayout example="app/teleport">
<div>
<!-- SSR Teleport -->
<Teleport to="body">
SSR Teleport
</Teleport>
<!-- Client Teleport -->
<ClientOnly>
<Teleport to="body">
<div>
Hello from a client-side teleport!
</div>
</Teleport>
</ClientOnly>
<!-- Modal Example -->
<MyModal />
</div>
</NuxtExampleLayout>
</template>
| examples/app/teleport/app.vue | 0 | https://github.com/nuxt/nuxt/commit/05a8c2d955b9dc7f13e0bc6ad6e347f2a9d40f23 | [
0.00016802594473119825,
0.00016689550830051303,
0.00016569271974731237,
0.0001669678749749437,
9.539083976051188e-7
] |
{
"id": 0,
"code_window": [
"\t\treturn element.getId();\n",
"\t}\n",
"\n",
"\tpublic hasChildren(tree: tree.ITree, element: any): boolean {\n",
"\t\treturn element instanceof model.Model || (element instanceof model.Thread && (<model.Thread>element).stopped);\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t// TODO@isidor also has children if it is a session\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugViewer.ts",
"type": "add",
"edit_start_line_idx": 356
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import nls = require('vs/nls');
import { TPromise } from 'vs/base/common/winjs.base';
import lifecycle = require('vs/base/common/lifecycle');
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import paths = require('vs/base/common/paths');
import async = require('vs/base/common/async');
import errors = require('vs/base/common/errors');
import strings = require('vs/base/common/strings');
import { isMacintosh } from 'vs/base/common/platform';
import dom = require('vs/base/browser/dom');
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import labels = require('vs/base/common/labels');
import actions = require('vs/base/common/actions');
import actionbar = require('vs/base/browser/ui/actionbar/actionbar');
import tree = require('vs/base/parts/tree/browser/tree');
import { InputBox, IInputValidationOptions } from 'vs/base/browser/ui/inputbox/inputBox';
import treedefaults = require('vs/base/parts/tree/browser/treeDefaults');
import renderer = require('vs/base/parts/tree/browser/actionsRenderer');
import debug = require('vs/workbench/parts/debug/common/debug');
import model = require('vs/workbench/parts/debug/common/debugModel');
import viewmodel = require('vs/workbench/parts/debug/common/debugViewModel');
import debugactions = require('vs/workbench/parts/debug/browser/debugActions');
import { CopyValueAction } from 'vs/workbench/parts/debug/electron-browser/electronDebugActions';
import { IContextViewService, IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
const $ = dom.$;
const booleanRegex = /^true|false$/i;
const stringRegex = /^(['"]).*\1$/;
const MAX_VALUE_RENDER_LENGTH_IN_VIEWLET = 1024;
export function renderExpressionValue(expressionOrValue: debug.IExpression | string, container: HTMLElement, showChanged: boolean, maxValueRenderLength?: number): void {
let value = typeof expressionOrValue === 'string' ? expressionOrValue : expressionOrValue.value;
// remove stale classes
container.className = 'value';
// when resolving expressions we represent errors from the server as a variable with name === null.
if (value === null || ((expressionOrValue instanceof model.Expression || expressionOrValue instanceof model.Variable) && !expressionOrValue.available)) {
dom.addClass(container, 'unavailable');
if (value !== model.Expression.DEFAULT_VALUE) {
dom.addClass(container, 'error');
}
} else if (!isNaN(+value)) {
dom.addClass(container, 'number');
} else if (booleanRegex.test(value)) {
dom.addClass(container, 'boolean');
} else if (stringRegex.test(value)) {
dom.addClass(container, 'string');
}
if (showChanged && (<any>expressionOrValue).valueChanged) {
// value changed color has priority over other colors.
container.className = 'value changed';
}
if (maxValueRenderLength && value.length > maxValueRenderLength) {
value = value.substr(0, maxValueRenderLength) + '...';
}
container.textContent = value;
container.title = value;
}
export function renderVariable(tree: tree.ITree, variable: model.Variable, data: IVariableTemplateData, showChanged: boolean): void {
if (variable.available) {
data.name.textContent = variable.name;
data.name.title = variable.type ? variable.type : '';
}
if (variable.value) {
data.name.textContent += ':';
renderExpressionValue(variable, data.value, showChanged, MAX_VALUE_RENDER_LENGTH_IN_VIEWLET);
data.value.title = variable.value;
} else {
data.value.textContent = '';
data.value.title = '';
}
}
interface IRenameBoxOptions {
initialValue: string;
ariaLabel: string;
placeholder?: string;
validationOptions?: IInputValidationOptions;
}
function renderRenameBox(debugService: debug.IDebugService, contextViewService: IContextViewService, tree: tree.ITree, element: any, container: HTMLElement, options: IRenameBoxOptions): void {
let inputBoxContainer = dom.append(container, $('.inputBoxContainer'));
let inputBox = new InputBox(inputBoxContainer, contextViewService, {
validationOptions: options.validationOptions,
placeholder: options.placeholder,
ariaLabel: options.ariaLabel
});
inputBox.value = options.initialValue ? options.initialValue : '';
inputBox.focus();
inputBox.select();
let disposed = false;
const toDispose: [lifecycle.IDisposable] = [inputBox];
const wrapUp = async.once((renamed: boolean) => {
if (!disposed) {
disposed = true;
if (element instanceof model.Expression && renamed && inputBox.value) {
debugService.renameWatchExpression(element.getId(), inputBox.value).done(null, errors.onUnexpectedError);
} else if (element instanceof model.Expression && !element.name) {
debugService.removeWatchExpressions(element.getId());
} else if (element instanceof model.FunctionBreakpoint && renamed && inputBox.value) {
debugService.renameFunctionBreakpoint(element.getId(), inputBox.value).done(null, errors.onUnexpectedError);
} else if (element instanceof model.FunctionBreakpoint && !element.name) {
debugService.removeFunctionBreakpoints(element.getId()).done(null, errors.onUnexpectedError);
} else if (element instanceof model.Variable) {
(<model.Variable>element).errorMessage = null;
if (renamed && element.value !== inputBox.value) {
debugService.setVariable(element, inputBox.value)
// if everything went fine we need to refresh that tree element since his value updated
.done(() => tree.refresh(element, false), errors.onUnexpectedError);
}
}
tree.clearHighlight();
tree.DOMFocus();
tree.setFocus(element);
// need to remove the input box since this template will be reused.
container.removeChild(inputBoxContainer);
lifecycle.dispose(toDispose);
}
});
toDispose.push(dom.addStandardDisposableListener(inputBox.inputElement, 'keydown', (e: IKeyboardEvent) => {
const isEscape = e.equals(KeyCode.Escape);
const isEnter = e.equals(KeyCode.Enter);
if (isEscape || isEnter) {
wrapUp(isEnter);
}
}));
toDispose.push(dom.addDisposableListener(inputBox.inputElement, 'blur', () => {
wrapUp(true);
}));
}
function getSourceName(source: Source, contextService: IWorkspaceContextService): string {
if (source.inMemory) {
return source.name;
}
return labels.getPathLabel(paths.basename(source.uri.fsPath), contextService);
}
export class BaseDebugController extends treedefaults.DefaultController {
constructor(
protected debugService: debug.IDebugService,
private contextMenuService: IContextMenuService,
private actionProvider: renderer.IActionProvider,
private focusOnContextMenu = true
) {
super();
if (isMacintosh) {
this.downKeyBindingDispatcher.set(KeyMod.CtrlCmd | KeyCode.Backspace, this.onDelete.bind(this));
} else {
this.downKeyBindingDispatcher.set(KeyCode.Delete, this.onDelete.bind(this));
this.downKeyBindingDispatcher.set(KeyMod.Shift | KeyCode.Delete, this.onDelete.bind(this));
}
}
public onContextMenu(tree: tree.ITree, element: debug.IEnablement, event: tree.ContextMenuEvent): boolean {
if (event.target && event.target.tagName && event.target.tagName.toLowerCase() === 'input') {
return false;
}
event.preventDefault();
event.stopPropagation();
if (this.focusOnContextMenu) {
tree.setFocus(element);
}
if (this.actionProvider.hasSecondaryActions(tree, element)) {
const anchor = { x: event.posx + 1, y: event.posy };
this.contextMenuService.showContextMenu({
getAnchor: () => anchor,
getActions: () => this.actionProvider.getSecondaryActions(tree, element),
onHide: (wasCancelled?: boolean) => {
if (wasCancelled) {
tree.DOMFocus();
}
},
getActionsContext: () => element
});
return true;
}
return false;
}
protected onDelete(tree: tree.ITree, event: IKeyboardEvent): boolean {
return false;
}
}
// call stack
class ThreadAndSessionId {
constructor(public sessionId: string, public threadId: number) { }
}
export class CallStackController extends BaseDebugController {
protected onLeftClick(tree: tree.ITree, element: any, event: IMouseEvent): boolean {
if (element instanceof ThreadAndSessionId) {
return this.showMoreStackFrames(tree, element);
}
if (element instanceof model.StackFrame) {
this.focusStackFrame(element, event, true);
}
return super.onLeftClick(tree, element, event);
}
protected onEnter(tree: tree.ITree, event: IKeyboardEvent): boolean {
const element = tree.getFocus();
if (element instanceof ThreadAndSessionId) {
return this.showMoreStackFrames(tree, element);
}
if (element instanceof model.StackFrame) {
this.focusStackFrame(element, event, false);
}
return super.onEnter(tree, event);
}
protected onUp(tree: tree.ITree, event: IKeyboardEvent): boolean {
super.onUp(tree, event);
this.focusStackFrame(tree.getFocus(), event, true);
return true;
}
protected onPageUp(tree: tree.ITree, event: IKeyboardEvent): boolean {
super.onPageUp(tree, event);
this.focusStackFrame(tree.getFocus(), event, true);
return true;
}
protected onDown(tree: tree.ITree, event: IKeyboardEvent): boolean {
super.onDown(tree, event);
this.focusStackFrame(tree.getFocus(), event, true);
return true;
}
protected onPageDown(tree: tree.ITree, event: IKeyboardEvent): boolean {
super.onPageDown(tree, event);
this.focusStackFrame(tree.getFocus(), event, true);
return true;
}
// user clicked / pressed on 'Load More Stack Frames', get those stack frames and refresh the tree.
private showMoreStackFrames(tree: tree.ITree, threadAndSessionId: ThreadAndSessionId): boolean {
const thread = this.debugService.getModel().getThreads(threadAndSessionId.sessionId)[threadAndSessionId.threadId];
if (thread) {
thread.getCallStack(true)
.done(() => tree.refresh(), errors.onUnexpectedError);
}
return true;
}
private focusStackFrame(stackFrame: debug.IStackFrame, event: IKeyboardEvent | IMouseEvent, preserveFocus: boolean): void {
this.debugService.setFocusedStackFrameAndEvaluate(stackFrame).done(null, errors.onUnexpectedError);
if (stackFrame) {
const sideBySide = (event && (event.ctrlKey || event.metaKey));
this.debugService.openOrRevealSource(stackFrame.source, stackFrame.lineNumber, preserveFocus, sideBySide).done(null, errors.onUnexpectedError);
}
}
}
export class CallStackActionProvider implements renderer.IActionProvider {
constructor( @IInstantiationService private instantiationService: IInstantiationService, @debug.IDebugService private debugService: debug.IDebugService) {
// noop
}
public hasActions(tree: tree.ITree, element: any): boolean {
return false;
}
public getActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
return TPromise.as([]);
}
public hasSecondaryActions(tree: tree.ITree, element: any): boolean {
return element instanceof model.Thread || element instanceof model.StackFrame;
}
public getSecondaryActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
const actions: actions.Action[] = [];
if (element instanceof model.Thread) {
const thread = <model.Thread>element;
if (thread.stopped) {
actions.push(this.instantiationService.createInstance(debugactions.ContinueAction, debugactions.ContinueAction.ID, debugactions.ContinueAction.LABEL));
actions.push(this.instantiationService.createInstance(debugactions.StepOverAction, debugactions.StepOverAction.ID, debugactions.StepOverAction.LABEL));
actions.push(this.instantiationService.createInstance(debugactions.StepIntoAction, debugactions.StepIntoAction.ID, debugactions.StepIntoAction.LABEL));
actions.push(this.instantiationService.createInstance(debugactions.StepOutAction, debugactions.StepOutAction.ID, debugactions.StepOutAction.LABEL));
} else {
actions.push(this.instantiationService.createInstance(debugactions.PauseAction, debugactions.PauseAction.ID, debugactions.PauseAction.LABEL));
}
} else if (element instanceof model.StackFrame) {
const capabilities = this.debugService.getViewModel().activeSession.configuration.capabilities;
if (typeof capabilities.supportsRestartFrame === 'boolean' && capabilities.supportsRestartFrame) {
actions.push(this.instantiationService.createInstance(debugactions.RestartFrameAction, debugactions.RestartFrameAction.ID, debugactions.RestartFrameAction.LABEL));
}
}
return TPromise.as(actions);
}
public getActionItem(tree: tree.ITree, element: any, action: actions.IAction): actionbar.IActionItem {
return null;
}
}
export class CallStackDataSource implements tree.IDataSource {
constructor( @debug.IDebugService private debugService: debug.IDebugService) {
// noop
}
public getId(tree: tree.ITree, element: any): string {
if (typeof element === 'number') {
return element.toString();
}
if (typeof element === 'string') {
return element;
}
return element.getId();
}
public hasChildren(tree: tree.ITree, element: any): boolean {
return element instanceof model.Model || (element instanceof model.Thread && (<model.Thread>element).stopped);
}
public getChildren(tree: tree.ITree, element: any): TPromise<any> {
if (element instanceof model.Thread) {
return this.getThreadChildren(element);
}
// TODO@Isidor FIX THIS
const session = this.debugService.getViewModel().activeSession;
if (!session) {
return TPromise.as([]);
}
const threads = (<model.Model>element).getThreads(session.getId());
return TPromise.as(Object.keys(threads).map(ref => threads[ref]));
}
private getThreadChildren(thread: debug.IThread): TPromise<any> {
return thread.getCallStack().then((callStack: any[]) => {
if (thread.stoppedDetails && thread.stoppedDetails.framesErrorMessage) {
return callStack.concat([thread.stoppedDetails.framesErrorMessage]);
}
if (thread.stoppedDetails && thread.stoppedDetails.totalFrames > callStack.length) {
return callStack.concat([new ThreadAndSessionId(thread.sessionId, thread.threadId)]);
}
return callStack;
});
}
public getParent(tree: tree.ITree, element: any): TPromise<any> {
return TPromise.as(null);
}
}
interface IThreadTemplateData {
thread: HTMLElement;
name: HTMLElement;
state: HTMLElement;
stateLabel: HTMLSpanElement;
}
interface IErrorTemplateData {
label: HTMLElement;
}
interface ILoadMoreTemplateData {
label: HTMLElement;
}
interface IStackFrameTemplateData {
stackFrame: HTMLElement;
label: HTMLElement;
file: HTMLElement;
fileName: HTMLElement;
lineNumber: HTMLElement;
}
export class CallStackRenderer implements tree.IRenderer {
private static THREAD_TEMPLATE_ID = 'thread';
private static STACK_FRAME_TEMPLATE_ID = 'stackFrame';
private static ERROR_TEMPLATE_ID = 'error';
private static LOAD_MORE_TEMPLATE_ID = 'loadMore';
constructor( @IWorkspaceContextService private contextService: IWorkspaceContextService) {
// noop
}
public getHeight(tree: tree.ITree, element: any): number {
return 22;
}
public getTemplateId(tree: tree.ITree, element: any): string {
if (element instanceof model.Thread) {
return CallStackRenderer.THREAD_TEMPLATE_ID;
}
if (element instanceof model.StackFrame) {
return CallStackRenderer.STACK_FRAME_TEMPLATE_ID;
}
if (typeof element === 'string') {
return CallStackRenderer.ERROR_TEMPLATE_ID;
}
return CallStackRenderer.LOAD_MORE_TEMPLATE_ID;
}
public renderTemplate(tree: tree.ITree, templateId: string, container: HTMLElement): any {
if (templateId === CallStackRenderer.LOAD_MORE_TEMPLATE_ID) {
let data: ILoadMoreTemplateData = Object.create(null);
data.label = dom.append(container, $('.load-more'));
return data;
}
if (templateId === CallStackRenderer.ERROR_TEMPLATE_ID) {
let data: ILoadMoreTemplateData = Object.create(null);
data.label = dom.append(container, $('.error'));
return data;
}
if (templateId === CallStackRenderer.THREAD_TEMPLATE_ID) {
let data: IThreadTemplateData = Object.create(null);
data.thread = dom.append(container, $('.thread'));
data.name = dom.append(data.thread, $('.name'));
data.state = dom.append(data.thread, $('.state'));
data.stateLabel = dom.append(data.state, $('span.label'));
return data;
}
let data: IStackFrameTemplateData = Object.create(null);
data.stackFrame = dom.append(container, $('.stack-frame'));
data.label = dom.append(data.stackFrame, $('span.label'));
data.file = dom.append(data.stackFrame, $('.file'));
data.fileName = dom.append(data.file, $('span.file-name'));
data.lineNumber = dom.append(data.file, $('span.line-number'));
return data;
}
public renderElement(tree: tree.ITree, element: any, templateId: string, templateData: any): void {
if (templateId === CallStackRenderer.THREAD_TEMPLATE_ID) {
this.renderThread(element, templateData);
} else if (templateId === CallStackRenderer.STACK_FRAME_TEMPLATE_ID) {
this.renderStackFrame(element, templateData);
} else if (templateId === CallStackRenderer.ERROR_TEMPLATE_ID) {
this.renderError(element, templateData);
} else {
this.renderLoadMore(element, templateData);
}
}
private renderThread(thread: debug.IThread, data: IThreadTemplateData): void {
data.thread.title = nls.localize('thread', "Thread");
data.name.textContent = thread.name;
data.stateLabel.textContent = thread.stopped ? nls.localize('paused', "paused")
: nls.localize({ key: 'running', comment: ['indicates state'] }, "running");
}
private renderError(element: string, data: IErrorTemplateData) {
data.label.textContent = element;
data.label.title = element;
}
private renderLoadMore(element: any, data: ILoadMoreTemplateData): void {
data.label.textContent = nls.localize('loadMoreStackFrames', "Load More Stack Frames");
}
private renderStackFrame(stackFrame: debug.IStackFrame, data: IStackFrameTemplateData): void {
stackFrame.source.available ? dom.removeClass(data.stackFrame, 'disabled') : dom.addClass(data.stackFrame, 'disabled');
data.file.title = stackFrame.source.uri.fsPath;
data.label.textContent = stackFrame.name;
data.label.title = stackFrame.name;
data.fileName.textContent = getSourceName(stackFrame.source, this.contextService);
if (stackFrame.lineNumber !== undefined) {
data.lineNumber.textContent = `${stackFrame.lineNumber}`;
dom.removeClass(data.lineNumber, 'unavailable');
} else {
dom.addClass(data.lineNumber, 'unavailable');
}
}
public disposeTemplate(tree: tree.ITree, templateId: string, templateData: any): void {
// noop
}
}
export class CallstackAccessibilityProvider implements tree.IAccessibilityProvider {
constructor( @IWorkspaceContextService private contextService: IWorkspaceContextService) {
// noop
}
public getAriaLabel(tree: tree.ITree, element: any): string {
if (element instanceof model.Thread) {
return nls.localize('threadAriaLabel', "Thread {0}, callstack, debug", (<model.Thread>element).name);
}
if (element instanceof model.StackFrame) {
return nls.localize('stackFrameAriaLabel', "Stack Frame {0} line {1} {2}, callstack, debug", (<model.StackFrame>element).name, (<model.StackFrame>element).lineNumber, getSourceName((<model.StackFrame>element).source, this.contextService));
}
return null;
}
}
// variables
export class VariablesActionProvider implements renderer.IActionProvider {
constructor(private instantiationService: IInstantiationService) {
// noop
}
public hasActions(tree: tree.ITree, element: any): boolean {
return false;
}
public getActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
return TPromise.as([]);
}
public hasSecondaryActions(tree: tree.ITree, element: any): boolean {
return element instanceof model.Variable;
}
public getSecondaryActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
let actions: actions.Action[] = [];
const variable = <model.Variable>element;
if (variable.reference === 0) {
actions.push(this.instantiationService.createInstance(debugactions.SetValueAction, debugactions.SetValueAction.ID, debugactions.SetValueAction.LABEL, variable));
actions.push(this.instantiationService.createInstance(CopyValueAction, CopyValueAction.ID, CopyValueAction.LABEL, variable));
actions.push(new actionbar.Separator());
}
actions.push(this.instantiationService.createInstance(debugactions.AddToWatchExpressionsAction, debugactions.AddToWatchExpressionsAction.ID, debugactions.AddToWatchExpressionsAction.LABEL, variable));
return TPromise.as(actions);
}
public getActionItem(tree: tree.ITree, element: any, action: actions.IAction): actionbar.IActionItem {
return null;
}
}
export class VariablesDataSource implements tree.IDataSource {
public getId(tree: tree.ITree, element: any): string {
return element.getId();
}
public hasChildren(tree: tree.ITree, element: any): boolean {
if (element instanceof viewmodel.ViewModel || element instanceof model.Scope) {
return true;
}
let variable = <model.Variable>element;
return variable.reference !== 0 && !strings.equalsIgnoreCase(variable.value, 'null');
}
public getChildren(tree: tree.ITree, element: any): TPromise<any> {
if (element instanceof viewmodel.ViewModel) {
let focusedStackFrame = (<viewmodel.ViewModel>element).getFocusedStackFrame();
return focusedStackFrame ? focusedStackFrame.getScopes() : TPromise.as([]);
}
let scope = <model.Scope>element;
return scope.getChildren();
}
public getParent(tree: tree.ITree, element: any): TPromise<any> {
return TPromise.as(null);
}
}
interface IScopeTemplateData {
name: HTMLElement;
}
export interface IVariableTemplateData {
expression: HTMLElement;
name: HTMLElement;
value: HTMLElement;
}
export class VariablesRenderer implements tree.IRenderer {
private static SCOPE_TEMPLATE_ID = 'scope';
private static VARIABLE_TEMPLATE_ID = 'variable';
constructor(
@debug.IDebugService private debugService: debug.IDebugService,
@IContextViewService private contextViewService: IContextViewService
) {
// noop
}
public getHeight(tree: tree.ITree, element: any): number {
return 22;
}
public getTemplateId(tree: tree.ITree, element: any): string {
if (element instanceof model.Scope) {
return VariablesRenderer.SCOPE_TEMPLATE_ID;
}
if (element instanceof model.Variable) {
return VariablesRenderer.VARIABLE_TEMPLATE_ID;
}
return null;
}
public renderTemplate(tree: tree.ITree, templateId: string, container: HTMLElement): any {
if (templateId === VariablesRenderer.SCOPE_TEMPLATE_ID) {
let data: IScopeTemplateData = Object.create(null);
data.name = dom.append(container, $('.scope'));
return data;
}
let data: IVariableTemplateData = Object.create(null);
data.expression = dom.append(container, $('.expression'));
data.name = dom.append(data.expression, $('span.name'));
data.value = dom.append(data.expression, $('span.value'));
return data;
}
public renderElement(tree: tree.ITree, element: any, templateId: string, templateData: any): void {
if (templateId === VariablesRenderer.SCOPE_TEMPLATE_ID) {
this.renderScope(element, templateData);
} else {
const variable = <model.Variable>element;
if (variable === this.debugService.getViewModel().getSelectedExpression() || variable.errorMessage) {
renderRenameBox(this.debugService, this.contextViewService, tree, variable, (<IVariableTemplateData>templateData).expression, {
initialValue: variable.value,
ariaLabel: nls.localize('variableValueAriaLabel', "Type new variable value"),
validationOptions: {
validation: (value: string) => variable.errorMessage ? ({ content: variable.errorMessage }) : null
}
});
} else {
renderVariable(tree, variable, templateData, true);
}
}
}
private renderScope(scope: model.Scope, data: IScopeTemplateData): void {
data.name.textContent = scope.name;
}
public disposeTemplate(tree: tree.ITree, templateId: string, templateData: any): void {
// noop
}
}
export class VariablesAccessibilityProvider implements tree.IAccessibilityProvider {
public getAriaLabel(tree: tree.ITree, element: any): string {
if (element instanceof model.Scope) {
return nls.localize('variableScopeAriaLabel', "Scope {0}, variables, debug", (<model.Scope>element).name);
}
if (element instanceof model.Variable) {
return nls.localize('variableAriaLabel', "{0} value {1}, variables, debug", (<model.Variable>element).name, (<model.Variable>element).value);
}
return null;
}
}
export class VariablesController extends BaseDebugController {
constructor(debugService: debug.IDebugService, contextMenuService: IContextMenuService, actionProvider: renderer.IActionProvider) {
super(debugService, contextMenuService, actionProvider);
this.downKeyBindingDispatcher.set(KeyCode.Enter, this.setSelectedExpression.bind(this));
}
protected onLeftClick(tree: tree.ITree, element: any, event: IMouseEvent): boolean {
// double click on primitive value: open input box to be able to set the value
if (element instanceof model.Variable && event.detail === 2) {
const expression = <debug.IExpression>element;
if (expression.reference === 0) {
this.debugService.getViewModel().setSelectedExpression(expression);
}
return true;
}
return super.onLeftClick(tree, element, event);
}
protected setSelectedExpression(tree: tree.ITree, event: KeyboardEvent): boolean {
const element = tree.getFocus();
if (element instanceof model.Variable && element.reference === 0) {
this.debugService.getViewModel().setSelectedExpression(element);
return true;
}
return false;
}
}
// watch expressions
export class WatchExpressionsActionProvider implements renderer.IActionProvider {
private instantiationService: IInstantiationService;
constructor(instantiationService: IInstantiationService) {
this.instantiationService = instantiationService;
}
public hasActions(tree: tree.ITree, element: any): boolean {
return element instanceof model.Expression && !!element.name;
}
public hasSecondaryActions(tree: tree.ITree, element: any): boolean {
return true;
}
public getActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
return TPromise.as(this.getExpressionActions());
}
public getExpressionActions(): actions.IAction[] {
return [this.instantiationService.createInstance(debugactions.RemoveWatchExpressionAction, debugactions.RemoveWatchExpressionAction.ID, debugactions.RemoveWatchExpressionAction.LABEL)];
}
public getSecondaryActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
const actions: actions.Action[] = [];
if (element instanceof model.Expression) {
const expression = <model.Expression>element;
actions.push(this.instantiationService.createInstance(debugactions.AddWatchExpressionAction, debugactions.AddWatchExpressionAction.ID, debugactions.AddWatchExpressionAction.LABEL));
actions.push(this.instantiationService.createInstance(debugactions.RenameWatchExpressionAction, debugactions.RenameWatchExpressionAction.ID, debugactions.RenameWatchExpressionAction.LABEL, expression));
if (expression.reference === 0) {
actions.push(this.instantiationService.createInstance(CopyValueAction, CopyValueAction.ID, CopyValueAction.LABEL, expression.value));
}
actions.push(new actionbar.Separator());
actions.push(this.instantiationService.createInstance(debugactions.RemoveWatchExpressionAction, debugactions.RemoveWatchExpressionAction.ID, debugactions.RemoveWatchExpressionAction.LABEL));
actions.push(this.instantiationService.createInstance(debugactions.RemoveAllWatchExpressionsAction, debugactions.RemoveAllWatchExpressionsAction.ID, debugactions.RemoveAllWatchExpressionsAction.LABEL));
} else {
actions.push(this.instantiationService.createInstance(debugactions.AddWatchExpressionAction, debugactions.AddWatchExpressionAction.ID, debugactions.AddWatchExpressionAction.LABEL));
if (element instanceof model.Variable) {
const variable = <model.Variable>element;
if (variable.reference === 0) {
actions.push(this.instantiationService.createInstance(CopyValueAction, CopyValueAction.ID, CopyValueAction.LABEL, variable.value));
}
actions.push(new actionbar.Separator());
}
actions.push(this.instantiationService.createInstance(debugactions.RemoveAllWatchExpressionsAction, debugactions.RemoveAllWatchExpressionsAction.ID, debugactions.RemoveAllWatchExpressionsAction.LABEL));
}
return TPromise.as(actions);
}
public getActionItem(tree: tree.ITree, element: any, action: actions.IAction): actionbar.IActionItem {
return null;
}
}
export class WatchExpressionsDataSource implements tree.IDataSource {
public getId(tree: tree.ITree, element: any): string {
return element.getId();
}
public hasChildren(tree: tree.ITree, element: any): boolean {
if (element instanceof model.Model) {
return true;
}
const watchExpression = <model.Expression>element;
return watchExpression.reference !== 0 && !strings.equalsIgnoreCase(watchExpression.value, 'null');
}
public getChildren(tree: tree.ITree, element: any): TPromise<any> {
if (element instanceof model.Model) {
return TPromise.as((<model.Model>element).getWatchExpressions());
}
let expression = <model.Expression>element;
return expression.getChildren();
}
public getParent(tree: tree.ITree, element: any): TPromise<any> {
return TPromise.as(null);
}
}
interface IWatchExpressionTemplateData extends IVariableTemplateData {
actionBar: actionbar.ActionBar;
}
export class WatchExpressionsRenderer implements tree.IRenderer {
private static WATCH_EXPRESSION_TEMPLATE_ID = 'watchExpression';
private static VARIABLE_TEMPLATE_ID = 'variables';
private toDispose: lifecycle.IDisposable[];
private actionProvider: WatchExpressionsActionProvider;
constructor(
actionProvider: renderer.IActionProvider,
private actionRunner: actions.IActionRunner,
@debug.IDebugService private debugService: debug.IDebugService,
@IContextViewService private contextViewService: IContextViewService
) {
this.toDispose = [];
this.actionProvider = <WatchExpressionsActionProvider>actionProvider;
}
public getHeight(tree: tree.ITree, element: any): number {
return 22;
}
public getTemplateId(tree: tree.ITree, element: any): string {
if (element instanceof model.Expression) {
return WatchExpressionsRenderer.WATCH_EXPRESSION_TEMPLATE_ID;
}
return WatchExpressionsRenderer.VARIABLE_TEMPLATE_ID;
}
public renderTemplate(tree: tree.ITree, templateId: string, container: HTMLElement): any {
let data: IWatchExpressionTemplateData = Object.create(null);
if (templateId === WatchExpressionsRenderer.WATCH_EXPRESSION_TEMPLATE_ID) {
data.actionBar = new actionbar.ActionBar(container, { actionRunner: this.actionRunner });
data.actionBar.push(this.actionProvider.getExpressionActions(), { icon: true, label: false });
}
data.expression = dom.append(container, $('.expression'));
data.name = dom.append(data.expression, $('span.name'));
data.value = dom.append(data.expression, $('span.value'));
return data;
}
public renderElement(tree: tree.ITree, element: any, templateId: string, templateData: any): void {
if (templateId === WatchExpressionsRenderer.WATCH_EXPRESSION_TEMPLATE_ID) {
this.renderWatchExpression(tree, element, templateData);
} else {
renderVariable(tree, element, templateData, true);
}
}
private renderWatchExpression(tree: tree.ITree, watchExpression: debug.IExpression, data: IWatchExpressionTemplateData): void {
let selectedExpression = this.debugService.getViewModel().getSelectedExpression();
if ((selectedExpression instanceof model.Expression && selectedExpression.getId() === watchExpression.getId()) || (watchExpression instanceof model.Expression && !watchExpression.name)) {
renderRenameBox(this.debugService, this.contextViewService, tree, watchExpression, data.expression, {
initialValue: watchExpression.name,
placeholder: nls.localize('watchExpressionPlaceholder', "Expression to watch"),
ariaLabel: nls.localize('watchExpressionInputAriaLabel', "Type watch expression")
});
}
data.actionBar.context = watchExpression;
data.name.textContent = watchExpression.name;
if (watchExpression.value) {
data.name.textContent += ':';
renderExpressionValue(watchExpression, data.value, true, MAX_VALUE_RENDER_LENGTH_IN_VIEWLET);
data.name.title = watchExpression.type ? watchExpression.type : watchExpression.value;
}
}
public disposeTemplate(tree: tree.ITree, templateId: string, templateData: any): void {
if (templateId === WatchExpressionsRenderer.WATCH_EXPRESSION_TEMPLATE_ID) {
(<IWatchExpressionTemplateData>templateData).actionBar.dispose();
}
}
public dispose(): void {
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
export class WatchExpressionsAccessibilityProvider implements tree.IAccessibilityProvider {
public getAriaLabel(tree: tree.ITree, element: any): string {
if (element instanceof model.Expression) {
return nls.localize('watchExpressionAriaLabel', "{0} value {1}, watch, debug", (<model.Expression>element).name, (<model.Expression>element).value);
}
if (element instanceof model.Variable) {
return nls.localize('watchVariableAriaLabel', "{0} value {1}, watch, debug", (<model.Variable>element).name, (<model.Variable>element).value);
}
return null;
}
}
export class WatchExpressionsController extends BaseDebugController {
constructor(debugService: debug.IDebugService, contextMenuService: IContextMenuService, actionProvider: renderer.IActionProvider) {
super(debugService, contextMenuService, actionProvider);
if (isMacintosh) {
this.downKeyBindingDispatcher.set(KeyCode.Enter, this.onRename.bind(this));
} else {
this.downKeyBindingDispatcher.set(KeyCode.F2, this.onRename.bind(this));
}
}
protected onLeftClick(tree: tree.ITree, element: any, event: IMouseEvent): boolean {
// double click on primitive value: open input box to be able to select and copy value.
if (element instanceof model.Expression && event.detail === 2) {
const expression = <debug.IExpression>element;
if (expression.reference === 0) {
this.debugService.getViewModel().setSelectedExpression(expression);
}
return true;
}
return super.onLeftClick(tree, element, event);
}
protected onRename(tree: tree.ITree, event: KeyboardEvent): boolean {
const element = tree.getFocus();
if (element instanceof model.Expression) {
const watchExpression = <model.Expression>element;
if (watchExpression.reference === 0) {
this.debugService.getViewModel().setSelectedExpression(watchExpression);
}
return true;
}
return false;
}
protected onDelete(tree: tree.ITree, event: IKeyboardEvent): boolean {
const element = tree.getFocus();
if (element instanceof model.Expression) {
const we = <model.Expression>element;
this.debugService.removeWatchExpressions(we.getId());
return true;
}
return false;
}
}
// breakpoints
export class BreakpointsActionProvider implements renderer.IActionProvider {
constructor(private instantiationService: IInstantiationService) {
// noop
}
public hasActions(tree: tree.ITree, element: any): boolean {
return element instanceof model.Breakpoint;
}
public hasSecondaryActions(tree: tree.ITree, element: any): boolean {
return element instanceof model.Breakpoint || element instanceof model.ExceptionBreakpoint || element instanceof model.FunctionBreakpoint;
}
public getActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
if (element instanceof model.Breakpoint) {
return TPromise.as(this.getBreakpointActions());
}
return TPromise.as([]);
}
public getBreakpointActions(): actions.IAction[] {
return [this.instantiationService.createInstance(debugactions.RemoveBreakpointAction, debugactions.RemoveBreakpointAction.ID, debugactions.RemoveBreakpointAction.LABEL)];
}
public getSecondaryActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
const actions: actions.Action[] = [this.instantiationService.createInstance(debugactions.ToggleEnablementAction, debugactions.ToggleEnablementAction.ID, debugactions.ToggleEnablementAction.LABEL)];
actions.push(new actionbar.Separator());
if (element instanceof model.Breakpoint || element instanceof model.FunctionBreakpoint) {
actions.push(this.instantiationService.createInstance(debugactions.RemoveBreakpointAction, debugactions.RemoveBreakpointAction.ID, debugactions.RemoveBreakpointAction.LABEL));
}
actions.push(this.instantiationService.createInstance(debugactions.RemoveAllBreakpointsAction, debugactions.RemoveAllBreakpointsAction.ID, debugactions.RemoveAllBreakpointsAction.LABEL));
actions.push(new actionbar.Separator());
actions.push(this.instantiationService.createInstance(debugactions.ToggleBreakpointsActivatedAction, debugactions.ToggleBreakpointsActivatedAction.ID, debugactions.ToggleBreakpointsActivatedAction.ACTIVATE_LABEL));
actions.push(new actionbar.Separator());
actions.push(this.instantiationService.createInstance(debugactions.EnableAllBreakpointsAction, debugactions.EnableAllBreakpointsAction.ID, debugactions.EnableAllBreakpointsAction.LABEL));
actions.push(this.instantiationService.createInstance(debugactions.DisableAllBreakpointsAction, debugactions.DisableAllBreakpointsAction.ID, debugactions.DisableAllBreakpointsAction.LABEL));
actions.push(new actionbar.Separator());
actions.push(this.instantiationService.createInstance(debugactions.AddFunctionBreakpointAction, debugactions.AddFunctionBreakpointAction.ID, debugactions.AddFunctionBreakpointAction.LABEL));
if (element instanceof model.FunctionBreakpoint) {
actions.push(this.instantiationService.createInstance(debugactions.RenameFunctionBreakpointAction, debugactions.RenameFunctionBreakpointAction.ID, debugactions.RenameFunctionBreakpointAction.LABEL));
}
actions.push(new actionbar.Separator());
actions.push(this.instantiationService.createInstance(debugactions.ReapplyBreakpointsAction, debugactions.ReapplyBreakpointsAction.ID, debugactions.ReapplyBreakpointsAction.LABEL));
return TPromise.as(actions);
}
public getActionItem(tree: tree.ITree, element: any, action: actions.IAction): actionbar.IActionItem {
return null;
}
}
export class BreakpointsDataSource implements tree.IDataSource {
public getId(tree: tree.ITree, element: any): string {
return element.getId();
}
public hasChildren(tree: tree.ITree, element: any): boolean {
return element instanceof model.Model;
}
public getChildren(tree: tree.ITree, element: any): TPromise<any> {
const model = <model.Model>element;
const exBreakpoints = <debug.IEnablement[]>model.getExceptionBreakpoints();
return TPromise.as(exBreakpoints.concat(model.getFunctionBreakpoints()).concat(model.getBreakpoints()));
}
public getParent(tree: tree.ITree, element: any): TPromise<any> {
return TPromise.as(null);
}
}
interface IExceptionBreakpointTemplateData {
breakpoint: HTMLElement;
name: HTMLElement;
checkbox: HTMLInputElement;
toDisposeBeforeRender: lifecycle.IDisposable[];
}
interface IBreakpointTemplateData extends IExceptionBreakpointTemplateData {
actionBar: actionbar.ActionBar;
lineNumber: HTMLElement;
filePath: HTMLElement;
}
interface IFunctionBreakpointTemplateData extends IExceptionBreakpointTemplateData {
actionBar: actionbar.ActionBar;
}
export class BreakpointsRenderer implements tree.IRenderer {
private static EXCEPTION_BREAKPOINT_TEMPLATE_ID = 'exceptionBreakpoint';
private static FUNCTION_BREAKPOINT_TEMPLATE_ID = 'functionBreakpoint';
private static BREAKPOINT_TEMPLATE_ID = 'breakpoint';
constructor(
private actionProvider: BreakpointsActionProvider,
private actionRunner: actions.IActionRunner,
@IWorkspaceContextService private contextService: IWorkspaceContextService,
@debug.IDebugService private debugService: debug.IDebugService,
@IContextViewService private contextViewService: IContextViewService
) {
// noop
}
public getHeight(tree: tree.ITree, element: any): number {
return 22;
}
public getTemplateId(tree: tree.ITree, element: any): string {
if (element instanceof model.Breakpoint) {
return BreakpointsRenderer.BREAKPOINT_TEMPLATE_ID;
}
if (element instanceof model.FunctionBreakpoint) {
return BreakpointsRenderer.FUNCTION_BREAKPOINT_TEMPLATE_ID;
}
if (element instanceof model.ExceptionBreakpoint) {
return BreakpointsRenderer.EXCEPTION_BREAKPOINT_TEMPLATE_ID;
}
return null;
}
public renderTemplate(tree: tree.ITree, templateId: string, container: HTMLElement): any {
const data: IBreakpointTemplateData = Object.create(null);
if (templateId === BreakpointsRenderer.BREAKPOINT_TEMPLATE_ID || templateId === BreakpointsRenderer.FUNCTION_BREAKPOINT_TEMPLATE_ID) {
data.actionBar = new actionbar.ActionBar(container, { actionRunner: this.actionRunner });
data.actionBar.push(this.actionProvider.getBreakpointActions(), { icon: true, label: false });
}
data.breakpoint = dom.append(container, $('.breakpoint'));
data.toDisposeBeforeRender = [];
data.checkbox = <HTMLInputElement>$('input');
data.checkbox.type = 'checkbox';
dom.append(data.breakpoint, data.checkbox);
data.name = dom.append(data.breakpoint, $('span.name'));
if (templateId === BreakpointsRenderer.BREAKPOINT_TEMPLATE_ID) {
data.lineNumber = dom.append(data.breakpoint, $('span.line-number'));
data.filePath = dom.append(data.breakpoint, $('span.file-path'));
}
return data;
}
public renderElement(tree: tree.ITree, element: any, templateId: string, templateData: any): void {
templateData.toDisposeBeforeRender = lifecycle.dispose(templateData.toDisposeBeforeRender);
templateData.toDisposeBeforeRender.push(dom.addStandardDisposableListener(templateData.checkbox, 'change', (e) => {
this.debugService.enableOrDisableBreakpoints(!element.enabled, element);
}));
if (templateId === BreakpointsRenderer.EXCEPTION_BREAKPOINT_TEMPLATE_ID) {
this.renderExceptionBreakpoint(element, templateData);
} else if (templateId === BreakpointsRenderer.FUNCTION_BREAKPOINT_TEMPLATE_ID) {
this.renderFunctionBreakpoint(tree, element, templateData);
} else {
this.renderBreakpoint(tree, element, templateData);
}
}
private renderExceptionBreakpoint(exceptionBreakpoint: debug.IExceptionBreakpoint, data: IExceptionBreakpointTemplateData): void {
data.name.textContent = exceptionBreakpoint.label || `${exceptionBreakpoint.filter} exceptions`;;
data.breakpoint.title = data.name.textContent;
data.checkbox.checked = exceptionBreakpoint.enabled;
}
private renderFunctionBreakpoint(tree: tree.ITree, functionBreakpoint: debug.IFunctionBreakpoint, data: IFunctionBreakpointTemplateData): void {
const selected = this.debugService.getViewModel().getSelectedFunctionBreakpoint();
if (!functionBreakpoint.name || (selected && selected.getId() === functionBreakpoint.getId())) {
renderRenameBox(this.debugService, this.contextViewService, tree, functionBreakpoint, data.breakpoint, {
initialValue: functionBreakpoint.name,
placeholder: nls.localize('functionBreakpointPlaceholder', "Function to break on"),
ariaLabel: nls.localize('functionBreakPointInputAriaLabel', "Type function breakpoint")
});
} else {
data.name.textContent = functionBreakpoint.name;
data.checkbox.checked = functionBreakpoint.enabled;
data.breakpoint.title = functionBreakpoint.name;
// Mark function breakpoints as disabled if deactivated or if debug type does not support them #9099
const session = this.debugService.getViewModel().activeSession;
if ((session && !session.configuration.capabilities.supportsFunctionBreakpoints) || !this.debugService.getModel().areBreakpointsActivated()) {
tree.addTraits('disabled', [functionBreakpoint]);
if (session && !session.configuration.capabilities.supportsFunctionBreakpoints) {
data.breakpoint.title = nls.localize('functionBreakpointsNotSupported', "Function breakpoints are not supported by this debug type");
}
} else {
tree.removeTraits('disabled', [functionBreakpoint]);
}
}
data.actionBar.context = functionBreakpoint;
}
private renderBreakpoint(tree: tree.ITree, breakpoint: debug.IBreakpoint, data: IBreakpointTemplateData): void {
this.debugService.getModel().areBreakpointsActivated() ? tree.removeTraits('disabled', [breakpoint]) : tree.addTraits('disabled', [breakpoint]);
data.name.textContent = labels.getPathLabel(paths.basename(breakpoint.source.uri.fsPath), this.contextService);
data.lineNumber.textContent = breakpoint.desiredLineNumber !== breakpoint.lineNumber ? breakpoint.desiredLineNumber + ' \u2192 ' + breakpoint.lineNumber : '' + breakpoint.lineNumber;
data.filePath.textContent = labels.getPathLabel(paths.dirname(breakpoint.source.uri.fsPath), this.contextService);
data.checkbox.checked = breakpoint.enabled;
data.actionBar.context = breakpoint;
const debugActive = this.debugService.state === debug.State.Running || this.debugService.state === debug.State.Stopped || this.debugService.state === debug.State.Initializing;
if (debugActive && !breakpoint.verified) {
tree.addTraits('disabled', [breakpoint]);
if (breakpoint.message) {
data.breakpoint.title = breakpoint.message;
}
} else if (breakpoint.condition || breakpoint.hitCondition) {
data.breakpoint.title = breakpoint.condition ? breakpoint.condition : breakpoint.hitCondition;
}
}
public disposeTemplate(tree: tree.ITree, templateId: string, templateData: any): void {
if (templateId === BreakpointsRenderer.BREAKPOINT_TEMPLATE_ID || templateId === BreakpointsRenderer.FUNCTION_BREAKPOINT_TEMPLATE_ID) {
templateData.actionBar.dispose();
}
}
}
export class BreakpointsAccessibilityProvider implements tree.IAccessibilityProvider {
constructor( @IWorkspaceContextService private contextService: IWorkspaceContextService) {
// noop
}
public getAriaLabel(tree: tree.ITree, element: any): string {
if (element instanceof model.Breakpoint) {
return nls.localize('breakpointAriaLabel', "Breakpoint line {0} {1}, breakpoints, debug", (<model.Breakpoint>element).lineNumber, getSourceName((<model.Breakpoint>element).source, this.contextService));
}
if (element instanceof model.FunctionBreakpoint) {
return nls.localize('functionBreakpointAriaLabel', "Function breakpoint {0}, breakpoints, debug", (<model.FunctionBreakpoint>element).name);
}
if (element instanceof model.ExceptionBreakpoint) {
return nls.localize('exceptionBreakpointAriaLabel', "Exception breakpoint {0}, breakpoints, debug", (<model.ExceptionBreakpoint>element).filter);
}
return null;
}
}
export class BreakpointsController extends BaseDebugController {
constructor(debugService: debug.IDebugService, contextMenuService: IContextMenuService, actionProvider: renderer.IActionProvider) {
super(debugService, contextMenuService, actionProvider);
if (isMacintosh) {
this.downKeyBindingDispatcher.set(KeyCode.Enter, this.onRename.bind(this));
} else {
this.downKeyBindingDispatcher.set(KeyCode.F2, this.onRename.bind(this));
}
}
protected onLeftClick(tree: tree.ITree, element: any, event: IMouseEvent): boolean {
if (element instanceof model.FunctionBreakpoint && event.detail === 2) {
this.debugService.getViewModel().setSelectedFunctionBreakpoint(element);
return true;
}
if (element instanceof model.Breakpoint) {
this.openBreakpointSource(element, event, true);
}
return super.onLeftClick(tree, element, event);
}
protected onRename(tree: tree.ITree, event: IKeyboardEvent): boolean {
const element = tree.getFocus();
if (element instanceof model.FunctionBreakpoint && element.name) {
this.debugService.getViewModel().setSelectedFunctionBreakpoint(element);
return true;
}
if (element instanceof model.Breakpoint) {
this.openBreakpointSource(element, event, false);
}
return super.onEnter(tree, event);
}
protected onSpace(tree: tree.ITree, event: IKeyboardEvent): boolean {
super.onSpace(tree, event);
const element = <debug.IEnablement>tree.getFocus();
this.debugService.enableOrDisableBreakpoints(!element.enabled, element).done(null, errors.onUnexpectedError);
return true;
}
protected onDelete(tree: tree.ITree, event: IKeyboardEvent): boolean {
const element = tree.getFocus();
if (element instanceof model.Breakpoint) {
this.debugService.removeBreakpoints((<model.Breakpoint>element).getId()).done(null, errors.onUnexpectedError);
return true;
} else if (element instanceof model.FunctionBreakpoint) {
const fbp = <model.FunctionBreakpoint>element;
this.debugService.removeFunctionBreakpoints(fbp.getId()).done(null, errors.onUnexpectedError);
return true;
}
return false;
}
private openBreakpointSource(breakpoint: debug.IBreakpoint, event: IKeyboardEvent | IMouseEvent, preserveFocus: boolean): void {
if (!breakpoint.source.inMemory) {
const sideBySide = (event && (event.ctrlKey || event.metaKey));
this.debugService.openOrRevealSource(breakpoint.source, breakpoint.lineNumber, preserveFocus, sideBySide).done(null, errors.onUnexpectedError);
}
}
}
| src/vs/workbench/parts/debug/electron-browser/debugViewer.ts | 1 | https://github.com/microsoft/vscode/commit/bb194502143f100abe468b1328a54e33c62fd514 | [
0.9899165034294128,
0.05699574574828148,
0.00016469880938529968,
0.0006338523235172033,
0.20411552488803864
] |
{
"id": 0,
"code_window": [
"\t\treturn element.getId();\n",
"\t}\n",
"\n",
"\tpublic hasChildren(tree: tree.ITree, element: any): boolean {\n",
"\t\treturn element instanceof model.Model || (element instanceof model.Thread && (<model.Thread>element).stopped);\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t// TODO@isidor also has children if it is a session\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugViewer.ts",
"type": "add",
"edit_start_line_idx": 356
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// NOTE: THIS FILE WILL BE OVERWRITTEN DURING BUILD TIME, DO NOT EDIT
define([], {}); | src/vs/workbench/workbench.main.nls.js | 0 | https://github.com/microsoft/vscode/commit/bb194502143f100abe468b1328a54e33c62fd514 | [
0.00017753272550180554,
0.00017753272550180554,
0.00017753272550180554,
0.00017753272550180554,
0
] |
{
"id": 0,
"code_window": [
"\t\treturn element.getId();\n",
"\t}\n",
"\n",
"\tpublic hasChildren(tree: tree.ITree, element: any): boolean {\n",
"\t\treturn element instanceof model.Model || (element instanceof model.Thread && (<model.Thread>element).stopped);\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t// TODO@isidor also has children if it is a session\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugViewer.ts",
"type": "add",
"edit_start_line_idx": 356
} | /*---------------------------------------------------------------------------------------------
* 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 Event, { Emitter } from 'vs/base/common/event';
import { TPromise } from 'vs/base/common/winjs.base';
import URI from 'vs/base/common/uri';
import { TextFileEditorModel } from 'vs/workbench/services/textfile/common/textFileEditorModel';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService';
import { ModelState, ITextFileEditorModel, LocalFileChangeEvent, ITextFileEditorModelManager, TextFileModelChangeEvent, StateChange } from 'vs/workbench/services/textfile/common/textfiles';
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
import { IEventService } from 'vs/platform/event/common/event';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { FileChangesEvent, EventType as CommonFileEventType } from 'vs/platform/files/common/files';
export class TextFileEditorModelManager implements ITextFileEditorModelManager {
// Delay in ms that we wait at minimum before we update a model from a file change event.
// This reduces the chance that a save from the client triggers an update of the editor.
private static FILE_CHANGE_UPDATE_DELAY = 2000;
private toUnbind: IDisposable[];
private _onModelDirty: Emitter<TextFileModelChangeEvent>;
private _onModelSaveError: Emitter<TextFileModelChangeEvent>;
private _onModelSaved: Emitter<TextFileModelChangeEvent>;
private _onModelReverted: Emitter<TextFileModelChangeEvent>;
private _onModelEncodingChanged: Emitter<TextFileModelChangeEvent>;
private mapResourceToDisposeListener: { [resource: string]: IDisposable; };
private mapResourceToStateChangeListener: { [resource: string]: IDisposable; };
private mapResourceToModel: { [resource: string]: ITextFileEditorModel; };
private mapResourceToPendingModelLoaders: { [resource: string]: TPromise<ITextFileEditorModel> };
constructor(
@ILifecycleService private lifecycleService: ILifecycleService,
@IEventService private eventService: IEventService,
@IInstantiationService private instantiationService: IInstantiationService,
@IEditorGroupService private editorGroupService: IEditorGroupService
) {
this.toUnbind = [];
this._onModelDirty = new Emitter<TextFileModelChangeEvent>();
this._onModelSaveError = new Emitter<TextFileModelChangeEvent>();
this._onModelSaved = new Emitter<TextFileModelChangeEvent>();
this._onModelReverted = new Emitter<TextFileModelChangeEvent>();
this._onModelEncodingChanged = new Emitter<TextFileModelChangeEvent>();
this.toUnbind.push(this._onModelDirty);
this.toUnbind.push(this._onModelSaveError);
this.toUnbind.push(this._onModelSaved);
this.toUnbind.push(this._onModelReverted);
this.toUnbind.push(this._onModelEncodingChanged);
this.mapResourceToModel = Object.create(null);
this.mapResourceToDisposeListener = Object.create(null);
this.mapResourceToStateChangeListener = Object.create(null);
this.mapResourceToPendingModelLoaders = Object.create(null);
this.registerListeners();
}
private registerListeners(): void {
// Editors changing/closing
this.toUnbind.push(this.editorGroupService.onEditorsChanged(() => this.onEditorsChanged()));
this.toUnbind.push(this.editorGroupService.getStacksModel().onEditorClosed(() => this.onEditorClosed()));
// File changes
this.toUnbind.push(this.eventService.addListener2('files.internal:fileChanged', (e: LocalFileChangeEvent) => this.onLocalFileChange(e)));
this.toUnbind.push(this.eventService.addListener2(CommonFileEventType.FILE_CHANGES, (e: FileChangesEvent) => this.onFileChanges(e)));
// Lifecycle
this.lifecycleService.onShutdown(this.dispose, this);
}
private onEditorsChanged(): void {
this.disposeUnusedModels();
}
private onEditorClosed(): void {
this.disposeUnusedModels();
}
private disposeModelIfPossible(resource: URI): void {
const model = this.get(resource);
if (this.canDispose(model)) {
model.dispose();
}
}
private onLocalFileChange(e: LocalFileChangeEvent): void {
if (e.gotMoved() || e.gotDeleted()) {
this.disposeModelIfPossible(e.getBefore().resource); // dispose models of moved or deleted files
}
}
private onFileChanges(e: FileChangesEvent): void {
// Dispose inputs that got deleted
e.getDeleted().forEach(deleted => {
this.disposeModelIfPossible(deleted.resource);
});
// Dispose models that got changed and are not visible. We do this because otherwise
// cached file models will be stale from the contents on disk.
e.getUpdated()
.map(u => this.get(u.resource))
.filter(model => {
if (!model) {
return false;
}
if (Date.now() - model.getLastSaveAttemptTime() < TextFileEditorModelManager.FILE_CHANGE_UPDATE_DELAY) {
return false; // this is a weak check to see if the change came from outside the editor or not
}
return true; // ok boss
})
.forEach(model => this.disposeModelIfPossible(model.getResource()));
}
private canDispose(textModel: ITextFileEditorModel): boolean {
if (!textModel) {
return false; // we need data!
}
if (textModel.isDisposed()) {
return false; // already disposed
}
if (textModel.textEditorModel && textModel.textEditorModel.isAttachedToEditor()) {
return false; // never dispose when attached to editor
}
if (textModel.getState() !== ModelState.SAVED) {
return false; // never dispose unsaved models
}
if (this.mapResourceToPendingModelLoaders[textModel.getResource().toString()]) {
return false; // never dispose models that we are about to load at the same time
}
return true;
}
public get onModelDirty(): Event<TextFileModelChangeEvent> {
return this._onModelDirty.event;
}
public get onModelSaveError(): Event<TextFileModelChangeEvent> {
return this._onModelSaveError.event;
}
public get onModelSaved(): Event<TextFileModelChangeEvent> {
return this._onModelSaved.event;
}
public get onModelReverted(): Event<TextFileModelChangeEvent> {
return this._onModelReverted.event;
}
public get onModelEncodingChanged(): Event<TextFileModelChangeEvent> {
return this._onModelEncodingChanged.event;
}
public get(resource: URI): ITextFileEditorModel {
return this.mapResourceToModel[resource.toString()];
}
public loadOrCreate(resource: URI, encoding: string, refresh?: boolean): TPromise<ITextFileEditorModel> {
// Return early if model is currently being loaded
const pendingLoad = this.mapResourceToPendingModelLoaders[resource.toString()];
if (pendingLoad) {
return pendingLoad;
}
let modelPromise: TPromise<ITextFileEditorModel>;
// Model exists
let model = this.get(resource);
if (model) {
if (!refresh) {
modelPromise = TPromise.as(model);
} else {
modelPromise = model.load();
}
}
// Model does not exist
else {
model = this.instantiationService.createInstance(TextFileEditorModel, resource, encoding);
modelPromise = model.load();
// Install state change listener
this.mapResourceToStateChangeListener[resource.toString()] = model.onDidStateChange(state => {
const event = new TextFileModelChangeEvent(model, state);
switch (state) {
case StateChange.DIRTY:
this._onModelDirty.fire(event);
break;
case StateChange.SAVE_ERROR:
this._onModelSaveError.fire(event);
break;
case StateChange.SAVED:
this._onModelSaved.fire(event);
break;
case StateChange.REVERTED:
this._onModelReverted.fire(event);
break;
case StateChange.ENCODING:
this._onModelEncodingChanged.fire(event);
break;
}
});
}
// Store pending loads to avoid race conditions
this.mapResourceToPendingModelLoaders[resource.toString()] = modelPromise;
return modelPromise.then(model => {
// Make known to manager (if not already known)
this.add(resource, model);
// Remove from pending loads
this.mapResourceToPendingModelLoaders[resource.toString()] = null;
return model;
}, error => {
// Free resources of this invalid model
model.dispose();
// Remove from pending loads
this.mapResourceToPendingModelLoaders[resource.toString()] = null;
return TPromise.wrapError(error);
});
}
public getAll(resource?: URI): ITextFileEditorModel[] {
return Object.keys(this.mapResourceToModel)
.filter(r => !resource || resource.toString() === r)
.map(r => this.mapResourceToModel[r]);
}
public add(resource: URI, model: ITextFileEditorModel): void {
const knownModel = this.mapResourceToModel[resource.toString()];
if (knownModel === model) {
return; // already cached
}
// dispose any previously stored dispose listener for this resource
const disposeListener = this.mapResourceToDisposeListener[resource.toString()];
if (disposeListener) {
disposeListener.dispose();
}
// store in cache but remove when model gets disposed
this.mapResourceToModel[resource.toString()] = model;
this.mapResourceToDisposeListener[resource.toString()] = model.onDispose(() => this.remove(resource));
}
public remove(resource: URI): void {
delete this.mapResourceToModel[resource.toString()];
const disposeListener = this.mapResourceToDisposeListener[resource.toString()];
if (disposeListener) {
dispose(disposeListener);
delete this.mapResourceToDisposeListener[resource.toString()];
}
const stateChangeListener = this.mapResourceToStateChangeListener[resource.toString()];
if (stateChangeListener) {
dispose(stateChangeListener);
delete this.mapResourceToStateChangeListener[resource.toString()];
}
}
public clear(): void {
// model cache
this.mapResourceToModel = Object.create(null);
// dispose dispose listeners
let keys = Object.keys(this.mapResourceToDisposeListener);
dispose(keys.map(k => this.mapResourceToDisposeListener[k]));
this.mapResourceToDisposeListener = Object.create(null);
// dispose state change listeners
keys = Object.keys(this.mapResourceToStateChangeListener);
dispose(keys.map(k => this.mapResourceToStateChangeListener[k]));
this.mapResourceToStateChangeListener = Object.create(null);
}
private disposeUnusedModels(): void {
// To not grow our text file model cache infinitly, we dispose models that
// are not showing up in any opened editor.
// Get all cached file models
this.getAll()
// Only models that are not open inside the editor area
.filter(model => !this.editorGroupService.getStacksModel().isOpen(model.getResource()))
// Dispose
.forEach(model => this.disposeModelIfPossible(model.getResource()));
}
public dispose(): void {
this.toUnbind = dispose(this.toUnbind);
}
} | src/vs/workbench/services/textfile/common/textFileEditorModelManager.ts | 0 | https://github.com/microsoft/vscode/commit/bb194502143f100abe468b1328a54e33c62fd514 | [
0.0015872130170464516,
0.0002695356379263103,
0.00016542722005397081,
0.0001743062457535416,
0.0002940964186564088
] |
{
"id": 0,
"code_window": [
"\t\treturn element.getId();\n",
"\t}\n",
"\n",
"\tpublic hasChildren(tree: tree.ITree, element: any): boolean {\n",
"\t\treturn element instanceof model.Model || (element instanceof model.Thread && (<model.Thread>element).stopped);\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t// TODO@isidor also has children if it is a session\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugViewer.ts",
"type": "add",
"edit_start_line_idx": 356
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
body {
font-family: "Segoe WPC", "Segoe UI", "SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback";
font-size: 14px;
padding-left: 12px;
line-height: 22px;
}
img {
max-width: 100%;
max-height: 100%;
}
a {
color: #4080D0;
text-decoration: none;
}
a:focus,
input:focus,
select:focus,
textarea:focus {
outline: 1px solid -webkit-focus-ring-color;
outline-offset: -1px;
}
hr {
border: 0;
height: 2px;
border-bottom: 2px solid;
}
h1 {
padding-bottom: 0.3em;
line-height: 1.2;
border-bottom-width: 1px;
border-bottom-style: solid;
}
h1, h2, h3 {
font-weight: normal;
}
h1 code,
h2 code,
h3 code,
h4 code,
h5 code,
h6 code {
font-size: inherit;
line-height: auto;
}
a:hover {
color: #4080D0;
text-decoration: underline;
}
table {
border-collapse: collapse;
}
table > thead > tr > th {
text-align: left;
border-bottom: 1px solid;
}
table > thead > tr > th,
table > thead > tr > td,
table > tbody > tr > th,
table > tbody > tr > td {
padding: 5px 10px;
}
table > tbody > tr + tr > td {
border-top: 1px solid;
}
blockquote {
margin: 0 7px 0 5px;
padding: 0 16px 0 10px;
border-left: 5px solid;
}
code {
font-family: Menlo, Monaco, Consolas, "Droid Sans Mono", "Courier New", monospace, "Droid Sans Fallback";
font-size: 14px;
line-height: 19px;
}
.mac code {
font-size: 12px;
line-height: 18px;
}
code > div {
padding: 16px;
border-radius: 3px;
overflow: auto;
}
/** Theming */
.vscode-light {
color: rgb(30, 30, 30);
}
.vscode-dark {
color: #DDD;
}
.vscode-high-contrast {
color: white;
}
.vscode-light code {
color: #A31515;
}
.vscode-dark code {
color: #D7BA7D;
}
.vscode-light code > div {
background-color: rgba(220, 220, 220, 0.4);
}
.vscode-dark code > div {
background-color: rgba(10, 10, 10, 0.4);
}
.vscode-high-contrast code > div {
background-color: rgb(0, 0, 0);
}
.vscode-high-contrast h1 {
border-color: rgb(0, 0, 0);
}
.vscode-light table > thead > tr > th {
border-color: rgba(0, 0, 0, 0.69);
}
.vscode-dark table > thead > tr > th {
border-color: rgba(255, 255, 255, 0.69);
}
.vscode-light h1,
.vscode-light hr,
.vscode-light table > tbody > tr + tr > td {
border-color: rgba(0, 0, 0, 0.18);
}
.vscode-dark h1,
.vscode-dark hr,
.vscode-dark table > tbody > tr + tr > td {
border-color: rgba(255, 255, 255, 0.18);
}
.vscode-light blockquote,
.vscode-dark blockquote {
background: rgba(127, 127, 127, 0.1);
border-color: rgba(0, 122, 204, 0.5);
}
.vscode-high-contrast blockquote {
background: transparent;
border-color: #fff;
} | extensions/markdown/media/markdown.css | 0 | https://github.com/microsoft/vscode/commit/bb194502143f100abe468b1328a54e33c62fd514 | [
0.00017722068878356367,
0.0001743423636071384,
0.00017194838437717408,
0.00017407471023034304,
0.0000016095649471026263
] |
{
"id": 1,
"code_window": [
"\tpublic getChildren(tree: tree.ITree, element: any): TPromise<any> {\n",
"\t\tif (element instanceof model.Thread) {\n",
"\t\t\treturn this.getThreadChildren(element);\n",
"\t\t}\n",
"\n",
"\t\t// TODO@Isidor FIX THIS\n",
"\t\tconst session = this.debugService.getViewModel().activeSession;\n",
"\t\tif (!session) {\n",
"\t\t\treturn TPromise.as([]);\n",
"\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tif (element instanceof model.Model) {\n",
"\t\t\treturn TPromise.as(element.getSessions());\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugViewer.ts",
"type": "replace",
"edit_start_line_idx": 363
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import nls = require('vs/nls');
import { TPromise } from 'vs/base/common/winjs.base';
import lifecycle = require('vs/base/common/lifecycle');
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import paths = require('vs/base/common/paths');
import async = require('vs/base/common/async');
import errors = require('vs/base/common/errors');
import strings = require('vs/base/common/strings');
import { isMacintosh } from 'vs/base/common/platform';
import dom = require('vs/base/browser/dom');
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import labels = require('vs/base/common/labels');
import actions = require('vs/base/common/actions');
import actionbar = require('vs/base/browser/ui/actionbar/actionbar');
import tree = require('vs/base/parts/tree/browser/tree');
import { InputBox, IInputValidationOptions } from 'vs/base/browser/ui/inputbox/inputBox';
import treedefaults = require('vs/base/parts/tree/browser/treeDefaults');
import renderer = require('vs/base/parts/tree/browser/actionsRenderer');
import debug = require('vs/workbench/parts/debug/common/debug');
import model = require('vs/workbench/parts/debug/common/debugModel');
import viewmodel = require('vs/workbench/parts/debug/common/debugViewModel');
import debugactions = require('vs/workbench/parts/debug/browser/debugActions');
import { CopyValueAction } from 'vs/workbench/parts/debug/electron-browser/electronDebugActions';
import { IContextViewService, IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
const $ = dom.$;
const booleanRegex = /^true|false$/i;
const stringRegex = /^(['"]).*\1$/;
const MAX_VALUE_RENDER_LENGTH_IN_VIEWLET = 1024;
export function renderExpressionValue(expressionOrValue: debug.IExpression | string, container: HTMLElement, showChanged: boolean, maxValueRenderLength?: number): void {
let value = typeof expressionOrValue === 'string' ? expressionOrValue : expressionOrValue.value;
// remove stale classes
container.className = 'value';
// when resolving expressions we represent errors from the server as a variable with name === null.
if (value === null || ((expressionOrValue instanceof model.Expression || expressionOrValue instanceof model.Variable) && !expressionOrValue.available)) {
dom.addClass(container, 'unavailable');
if (value !== model.Expression.DEFAULT_VALUE) {
dom.addClass(container, 'error');
}
} else if (!isNaN(+value)) {
dom.addClass(container, 'number');
} else if (booleanRegex.test(value)) {
dom.addClass(container, 'boolean');
} else if (stringRegex.test(value)) {
dom.addClass(container, 'string');
}
if (showChanged && (<any>expressionOrValue).valueChanged) {
// value changed color has priority over other colors.
container.className = 'value changed';
}
if (maxValueRenderLength && value.length > maxValueRenderLength) {
value = value.substr(0, maxValueRenderLength) + '...';
}
container.textContent = value;
container.title = value;
}
export function renderVariable(tree: tree.ITree, variable: model.Variable, data: IVariableTemplateData, showChanged: boolean): void {
if (variable.available) {
data.name.textContent = variable.name;
data.name.title = variable.type ? variable.type : '';
}
if (variable.value) {
data.name.textContent += ':';
renderExpressionValue(variable, data.value, showChanged, MAX_VALUE_RENDER_LENGTH_IN_VIEWLET);
data.value.title = variable.value;
} else {
data.value.textContent = '';
data.value.title = '';
}
}
interface IRenameBoxOptions {
initialValue: string;
ariaLabel: string;
placeholder?: string;
validationOptions?: IInputValidationOptions;
}
function renderRenameBox(debugService: debug.IDebugService, contextViewService: IContextViewService, tree: tree.ITree, element: any, container: HTMLElement, options: IRenameBoxOptions): void {
let inputBoxContainer = dom.append(container, $('.inputBoxContainer'));
let inputBox = new InputBox(inputBoxContainer, contextViewService, {
validationOptions: options.validationOptions,
placeholder: options.placeholder,
ariaLabel: options.ariaLabel
});
inputBox.value = options.initialValue ? options.initialValue : '';
inputBox.focus();
inputBox.select();
let disposed = false;
const toDispose: [lifecycle.IDisposable] = [inputBox];
const wrapUp = async.once((renamed: boolean) => {
if (!disposed) {
disposed = true;
if (element instanceof model.Expression && renamed && inputBox.value) {
debugService.renameWatchExpression(element.getId(), inputBox.value).done(null, errors.onUnexpectedError);
} else if (element instanceof model.Expression && !element.name) {
debugService.removeWatchExpressions(element.getId());
} else if (element instanceof model.FunctionBreakpoint && renamed && inputBox.value) {
debugService.renameFunctionBreakpoint(element.getId(), inputBox.value).done(null, errors.onUnexpectedError);
} else if (element instanceof model.FunctionBreakpoint && !element.name) {
debugService.removeFunctionBreakpoints(element.getId()).done(null, errors.onUnexpectedError);
} else if (element instanceof model.Variable) {
(<model.Variable>element).errorMessage = null;
if (renamed && element.value !== inputBox.value) {
debugService.setVariable(element, inputBox.value)
// if everything went fine we need to refresh that tree element since his value updated
.done(() => tree.refresh(element, false), errors.onUnexpectedError);
}
}
tree.clearHighlight();
tree.DOMFocus();
tree.setFocus(element);
// need to remove the input box since this template will be reused.
container.removeChild(inputBoxContainer);
lifecycle.dispose(toDispose);
}
});
toDispose.push(dom.addStandardDisposableListener(inputBox.inputElement, 'keydown', (e: IKeyboardEvent) => {
const isEscape = e.equals(KeyCode.Escape);
const isEnter = e.equals(KeyCode.Enter);
if (isEscape || isEnter) {
wrapUp(isEnter);
}
}));
toDispose.push(dom.addDisposableListener(inputBox.inputElement, 'blur', () => {
wrapUp(true);
}));
}
function getSourceName(source: Source, contextService: IWorkspaceContextService): string {
if (source.inMemory) {
return source.name;
}
return labels.getPathLabel(paths.basename(source.uri.fsPath), contextService);
}
export class BaseDebugController extends treedefaults.DefaultController {
constructor(
protected debugService: debug.IDebugService,
private contextMenuService: IContextMenuService,
private actionProvider: renderer.IActionProvider,
private focusOnContextMenu = true
) {
super();
if (isMacintosh) {
this.downKeyBindingDispatcher.set(KeyMod.CtrlCmd | KeyCode.Backspace, this.onDelete.bind(this));
} else {
this.downKeyBindingDispatcher.set(KeyCode.Delete, this.onDelete.bind(this));
this.downKeyBindingDispatcher.set(KeyMod.Shift | KeyCode.Delete, this.onDelete.bind(this));
}
}
public onContextMenu(tree: tree.ITree, element: debug.IEnablement, event: tree.ContextMenuEvent): boolean {
if (event.target && event.target.tagName && event.target.tagName.toLowerCase() === 'input') {
return false;
}
event.preventDefault();
event.stopPropagation();
if (this.focusOnContextMenu) {
tree.setFocus(element);
}
if (this.actionProvider.hasSecondaryActions(tree, element)) {
const anchor = { x: event.posx + 1, y: event.posy };
this.contextMenuService.showContextMenu({
getAnchor: () => anchor,
getActions: () => this.actionProvider.getSecondaryActions(tree, element),
onHide: (wasCancelled?: boolean) => {
if (wasCancelled) {
tree.DOMFocus();
}
},
getActionsContext: () => element
});
return true;
}
return false;
}
protected onDelete(tree: tree.ITree, event: IKeyboardEvent): boolean {
return false;
}
}
// call stack
class ThreadAndSessionId {
constructor(public sessionId: string, public threadId: number) { }
}
export class CallStackController extends BaseDebugController {
protected onLeftClick(tree: tree.ITree, element: any, event: IMouseEvent): boolean {
if (element instanceof ThreadAndSessionId) {
return this.showMoreStackFrames(tree, element);
}
if (element instanceof model.StackFrame) {
this.focusStackFrame(element, event, true);
}
return super.onLeftClick(tree, element, event);
}
protected onEnter(tree: tree.ITree, event: IKeyboardEvent): boolean {
const element = tree.getFocus();
if (element instanceof ThreadAndSessionId) {
return this.showMoreStackFrames(tree, element);
}
if (element instanceof model.StackFrame) {
this.focusStackFrame(element, event, false);
}
return super.onEnter(tree, event);
}
protected onUp(tree: tree.ITree, event: IKeyboardEvent): boolean {
super.onUp(tree, event);
this.focusStackFrame(tree.getFocus(), event, true);
return true;
}
protected onPageUp(tree: tree.ITree, event: IKeyboardEvent): boolean {
super.onPageUp(tree, event);
this.focusStackFrame(tree.getFocus(), event, true);
return true;
}
protected onDown(tree: tree.ITree, event: IKeyboardEvent): boolean {
super.onDown(tree, event);
this.focusStackFrame(tree.getFocus(), event, true);
return true;
}
protected onPageDown(tree: tree.ITree, event: IKeyboardEvent): boolean {
super.onPageDown(tree, event);
this.focusStackFrame(tree.getFocus(), event, true);
return true;
}
// user clicked / pressed on 'Load More Stack Frames', get those stack frames and refresh the tree.
private showMoreStackFrames(tree: tree.ITree, threadAndSessionId: ThreadAndSessionId): boolean {
const thread = this.debugService.getModel().getThreads(threadAndSessionId.sessionId)[threadAndSessionId.threadId];
if (thread) {
thread.getCallStack(true)
.done(() => tree.refresh(), errors.onUnexpectedError);
}
return true;
}
private focusStackFrame(stackFrame: debug.IStackFrame, event: IKeyboardEvent | IMouseEvent, preserveFocus: boolean): void {
this.debugService.setFocusedStackFrameAndEvaluate(stackFrame).done(null, errors.onUnexpectedError);
if (stackFrame) {
const sideBySide = (event && (event.ctrlKey || event.metaKey));
this.debugService.openOrRevealSource(stackFrame.source, stackFrame.lineNumber, preserveFocus, sideBySide).done(null, errors.onUnexpectedError);
}
}
}
export class CallStackActionProvider implements renderer.IActionProvider {
constructor( @IInstantiationService private instantiationService: IInstantiationService, @debug.IDebugService private debugService: debug.IDebugService) {
// noop
}
public hasActions(tree: tree.ITree, element: any): boolean {
return false;
}
public getActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
return TPromise.as([]);
}
public hasSecondaryActions(tree: tree.ITree, element: any): boolean {
return element instanceof model.Thread || element instanceof model.StackFrame;
}
public getSecondaryActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
const actions: actions.Action[] = [];
if (element instanceof model.Thread) {
const thread = <model.Thread>element;
if (thread.stopped) {
actions.push(this.instantiationService.createInstance(debugactions.ContinueAction, debugactions.ContinueAction.ID, debugactions.ContinueAction.LABEL));
actions.push(this.instantiationService.createInstance(debugactions.StepOverAction, debugactions.StepOverAction.ID, debugactions.StepOverAction.LABEL));
actions.push(this.instantiationService.createInstance(debugactions.StepIntoAction, debugactions.StepIntoAction.ID, debugactions.StepIntoAction.LABEL));
actions.push(this.instantiationService.createInstance(debugactions.StepOutAction, debugactions.StepOutAction.ID, debugactions.StepOutAction.LABEL));
} else {
actions.push(this.instantiationService.createInstance(debugactions.PauseAction, debugactions.PauseAction.ID, debugactions.PauseAction.LABEL));
}
} else if (element instanceof model.StackFrame) {
const capabilities = this.debugService.getViewModel().activeSession.configuration.capabilities;
if (typeof capabilities.supportsRestartFrame === 'boolean' && capabilities.supportsRestartFrame) {
actions.push(this.instantiationService.createInstance(debugactions.RestartFrameAction, debugactions.RestartFrameAction.ID, debugactions.RestartFrameAction.LABEL));
}
}
return TPromise.as(actions);
}
public getActionItem(tree: tree.ITree, element: any, action: actions.IAction): actionbar.IActionItem {
return null;
}
}
export class CallStackDataSource implements tree.IDataSource {
constructor( @debug.IDebugService private debugService: debug.IDebugService) {
// noop
}
public getId(tree: tree.ITree, element: any): string {
if (typeof element === 'number') {
return element.toString();
}
if (typeof element === 'string') {
return element;
}
return element.getId();
}
public hasChildren(tree: tree.ITree, element: any): boolean {
return element instanceof model.Model || (element instanceof model.Thread && (<model.Thread>element).stopped);
}
public getChildren(tree: tree.ITree, element: any): TPromise<any> {
if (element instanceof model.Thread) {
return this.getThreadChildren(element);
}
// TODO@Isidor FIX THIS
const session = this.debugService.getViewModel().activeSession;
if (!session) {
return TPromise.as([]);
}
const threads = (<model.Model>element).getThreads(session.getId());
return TPromise.as(Object.keys(threads).map(ref => threads[ref]));
}
private getThreadChildren(thread: debug.IThread): TPromise<any> {
return thread.getCallStack().then((callStack: any[]) => {
if (thread.stoppedDetails && thread.stoppedDetails.framesErrorMessage) {
return callStack.concat([thread.stoppedDetails.framesErrorMessage]);
}
if (thread.stoppedDetails && thread.stoppedDetails.totalFrames > callStack.length) {
return callStack.concat([new ThreadAndSessionId(thread.sessionId, thread.threadId)]);
}
return callStack;
});
}
public getParent(tree: tree.ITree, element: any): TPromise<any> {
return TPromise.as(null);
}
}
interface IThreadTemplateData {
thread: HTMLElement;
name: HTMLElement;
state: HTMLElement;
stateLabel: HTMLSpanElement;
}
interface IErrorTemplateData {
label: HTMLElement;
}
interface ILoadMoreTemplateData {
label: HTMLElement;
}
interface IStackFrameTemplateData {
stackFrame: HTMLElement;
label: HTMLElement;
file: HTMLElement;
fileName: HTMLElement;
lineNumber: HTMLElement;
}
export class CallStackRenderer implements tree.IRenderer {
private static THREAD_TEMPLATE_ID = 'thread';
private static STACK_FRAME_TEMPLATE_ID = 'stackFrame';
private static ERROR_TEMPLATE_ID = 'error';
private static LOAD_MORE_TEMPLATE_ID = 'loadMore';
constructor( @IWorkspaceContextService private contextService: IWorkspaceContextService) {
// noop
}
public getHeight(tree: tree.ITree, element: any): number {
return 22;
}
public getTemplateId(tree: tree.ITree, element: any): string {
if (element instanceof model.Thread) {
return CallStackRenderer.THREAD_TEMPLATE_ID;
}
if (element instanceof model.StackFrame) {
return CallStackRenderer.STACK_FRAME_TEMPLATE_ID;
}
if (typeof element === 'string') {
return CallStackRenderer.ERROR_TEMPLATE_ID;
}
return CallStackRenderer.LOAD_MORE_TEMPLATE_ID;
}
public renderTemplate(tree: tree.ITree, templateId: string, container: HTMLElement): any {
if (templateId === CallStackRenderer.LOAD_MORE_TEMPLATE_ID) {
let data: ILoadMoreTemplateData = Object.create(null);
data.label = dom.append(container, $('.load-more'));
return data;
}
if (templateId === CallStackRenderer.ERROR_TEMPLATE_ID) {
let data: ILoadMoreTemplateData = Object.create(null);
data.label = dom.append(container, $('.error'));
return data;
}
if (templateId === CallStackRenderer.THREAD_TEMPLATE_ID) {
let data: IThreadTemplateData = Object.create(null);
data.thread = dom.append(container, $('.thread'));
data.name = dom.append(data.thread, $('.name'));
data.state = dom.append(data.thread, $('.state'));
data.stateLabel = dom.append(data.state, $('span.label'));
return data;
}
let data: IStackFrameTemplateData = Object.create(null);
data.stackFrame = dom.append(container, $('.stack-frame'));
data.label = dom.append(data.stackFrame, $('span.label'));
data.file = dom.append(data.stackFrame, $('.file'));
data.fileName = dom.append(data.file, $('span.file-name'));
data.lineNumber = dom.append(data.file, $('span.line-number'));
return data;
}
public renderElement(tree: tree.ITree, element: any, templateId: string, templateData: any): void {
if (templateId === CallStackRenderer.THREAD_TEMPLATE_ID) {
this.renderThread(element, templateData);
} else if (templateId === CallStackRenderer.STACK_FRAME_TEMPLATE_ID) {
this.renderStackFrame(element, templateData);
} else if (templateId === CallStackRenderer.ERROR_TEMPLATE_ID) {
this.renderError(element, templateData);
} else {
this.renderLoadMore(element, templateData);
}
}
private renderThread(thread: debug.IThread, data: IThreadTemplateData): void {
data.thread.title = nls.localize('thread', "Thread");
data.name.textContent = thread.name;
data.stateLabel.textContent = thread.stopped ? nls.localize('paused', "paused")
: nls.localize({ key: 'running', comment: ['indicates state'] }, "running");
}
private renderError(element: string, data: IErrorTemplateData) {
data.label.textContent = element;
data.label.title = element;
}
private renderLoadMore(element: any, data: ILoadMoreTemplateData): void {
data.label.textContent = nls.localize('loadMoreStackFrames', "Load More Stack Frames");
}
private renderStackFrame(stackFrame: debug.IStackFrame, data: IStackFrameTemplateData): void {
stackFrame.source.available ? dom.removeClass(data.stackFrame, 'disabled') : dom.addClass(data.stackFrame, 'disabled');
data.file.title = stackFrame.source.uri.fsPath;
data.label.textContent = stackFrame.name;
data.label.title = stackFrame.name;
data.fileName.textContent = getSourceName(stackFrame.source, this.contextService);
if (stackFrame.lineNumber !== undefined) {
data.lineNumber.textContent = `${stackFrame.lineNumber}`;
dom.removeClass(data.lineNumber, 'unavailable');
} else {
dom.addClass(data.lineNumber, 'unavailable');
}
}
public disposeTemplate(tree: tree.ITree, templateId: string, templateData: any): void {
// noop
}
}
export class CallstackAccessibilityProvider implements tree.IAccessibilityProvider {
constructor( @IWorkspaceContextService private contextService: IWorkspaceContextService) {
// noop
}
public getAriaLabel(tree: tree.ITree, element: any): string {
if (element instanceof model.Thread) {
return nls.localize('threadAriaLabel', "Thread {0}, callstack, debug", (<model.Thread>element).name);
}
if (element instanceof model.StackFrame) {
return nls.localize('stackFrameAriaLabel', "Stack Frame {0} line {1} {2}, callstack, debug", (<model.StackFrame>element).name, (<model.StackFrame>element).lineNumber, getSourceName((<model.StackFrame>element).source, this.contextService));
}
return null;
}
}
// variables
export class VariablesActionProvider implements renderer.IActionProvider {
constructor(private instantiationService: IInstantiationService) {
// noop
}
public hasActions(tree: tree.ITree, element: any): boolean {
return false;
}
public getActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
return TPromise.as([]);
}
public hasSecondaryActions(tree: tree.ITree, element: any): boolean {
return element instanceof model.Variable;
}
public getSecondaryActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
let actions: actions.Action[] = [];
const variable = <model.Variable>element;
if (variable.reference === 0) {
actions.push(this.instantiationService.createInstance(debugactions.SetValueAction, debugactions.SetValueAction.ID, debugactions.SetValueAction.LABEL, variable));
actions.push(this.instantiationService.createInstance(CopyValueAction, CopyValueAction.ID, CopyValueAction.LABEL, variable));
actions.push(new actionbar.Separator());
}
actions.push(this.instantiationService.createInstance(debugactions.AddToWatchExpressionsAction, debugactions.AddToWatchExpressionsAction.ID, debugactions.AddToWatchExpressionsAction.LABEL, variable));
return TPromise.as(actions);
}
public getActionItem(tree: tree.ITree, element: any, action: actions.IAction): actionbar.IActionItem {
return null;
}
}
export class VariablesDataSource implements tree.IDataSource {
public getId(tree: tree.ITree, element: any): string {
return element.getId();
}
public hasChildren(tree: tree.ITree, element: any): boolean {
if (element instanceof viewmodel.ViewModel || element instanceof model.Scope) {
return true;
}
let variable = <model.Variable>element;
return variable.reference !== 0 && !strings.equalsIgnoreCase(variable.value, 'null');
}
public getChildren(tree: tree.ITree, element: any): TPromise<any> {
if (element instanceof viewmodel.ViewModel) {
let focusedStackFrame = (<viewmodel.ViewModel>element).getFocusedStackFrame();
return focusedStackFrame ? focusedStackFrame.getScopes() : TPromise.as([]);
}
let scope = <model.Scope>element;
return scope.getChildren();
}
public getParent(tree: tree.ITree, element: any): TPromise<any> {
return TPromise.as(null);
}
}
interface IScopeTemplateData {
name: HTMLElement;
}
export interface IVariableTemplateData {
expression: HTMLElement;
name: HTMLElement;
value: HTMLElement;
}
export class VariablesRenderer implements tree.IRenderer {
private static SCOPE_TEMPLATE_ID = 'scope';
private static VARIABLE_TEMPLATE_ID = 'variable';
constructor(
@debug.IDebugService private debugService: debug.IDebugService,
@IContextViewService private contextViewService: IContextViewService
) {
// noop
}
public getHeight(tree: tree.ITree, element: any): number {
return 22;
}
public getTemplateId(tree: tree.ITree, element: any): string {
if (element instanceof model.Scope) {
return VariablesRenderer.SCOPE_TEMPLATE_ID;
}
if (element instanceof model.Variable) {
return VariablesRenderer.VARIABLE_TEMPLATE_ID;
}
return null;
}
public renderTemplate(tree: tree.ITree, templateId: string, container: HTMLElement): any {
if (templateId === VariablesRenderer.SCOPE_TEMPLATE_ID) {
let data: IScopeTemplateData = Object.create(null);
data.name = dom.append(container, $('.scope'));
return data;
}
let data: IVariableTemplateData = Object.create(null);
data.expression = dom.append(container, $('.expression'));
data.name = dom.append(data.expression, $('span.name'));
data.value = dom.append(data.expression, $('span.value'));
return data;
}
public renderElement(tree: tree.ITree, element: any, templateId: string, templateData: any): void {
if (templateId === VariablesRenderer.SCOPE_TEMPLATE_ID) {
this.renderScope(element, templateData);
} else {
const variable = <model.Variable>element;
if (variable === this.debugService.getViewModel().getSelectedExpression() || variable.errorMessage) {
renderRenameBox(this.debugService, this.contextViewService, tree, variable, (<IVariableTemplateData>templateData).expression, {
initialValue: variable.value,
ariaLabel: nls.localize('variableValueAriaLabel', "Type new variable value"),
validationOptions: {
validation: (value: string) => variable.errorMessage ? ({ content: variable.errorMessage }) : null
}
});
} else {
renderVariable(tree, variable, templateData, true);
}
}
}
private renderScope(scope: model.Scope, data: IScopeTemplateData): void {
data.name.textContent = scope.name;
}
public disposeTemplate(tree: tree.ITree, templateId: string, templateData: any): void {
// noop
}
}
export class VariablesAccessibilityProvider implements tree.IAccessibilityProvider {
public getAriaLabel(tree: tree.ITree, element: any): string {
if (element instanceof model.Scope) {
return nls.localize('variableScopeAriaLabel', "Scope {0}, variables, debug", (<model.Scope>element).name);
}
if (element instanceof model.Variable) {
return nls.localize('variableAriaLabel', "{0} value {1}, variables, debug", (<model.Variable>element).name, (<model.Variable>element).value);
}
return null;
}
}
export class VariablesController extends BaseDebugController {
constructor(debugService: debug.IDebugService, contextMenuService: IContextMenuService, actionProvider: renderer.IActionProvider) {
super(debugService, contextMenuService, actionProvider);
this.downKeyBindingDispatcher.set(KeyCode.Enter, this.setSelectedExpression.bind(this));
}
protected onLeftClick(tree: tree.ITree, element: any, event: IMouseEvent): boolean {
// double click on primitive value: open input box to be able to set the value
if (element instanceof model.Variable && event.detail === 2) {
const expression = <debug.IExpression>element;
if (expression.reference === 0) {
this.debugService.getViewModel().setSelectedExpression(expression);
}
return true;
}
return super.onLeftClick(tree, element, event);
}
protected setSelectedExpression(tree: tree.ITree, event: KeyboardEvent): boolean {
const element = tree.getFocus();
if (element instanceof model.Variable && element.reference === 0) {
this.debugService.getViewModel().setSelectedExpression(element);
return true;
}
return false;
}
}
// watch expressions
export class WatchExpressionsActionProvider implements renderer.IActionProvider {
private instantiationService: IInstantiationService;
constructor(instantiationService: IInstantiationService) {
this.instantiationService = instantiationService;
}
public hasActions(tree: tree.ITree, element: any): boolean {
return element instanceof model.Expression && !!element.name;
}
public hasSecondaryActions(tree: tree.ITree, element: any): boolean {
return true;
}
public getActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
return TPromise.as(this.getExpressionActions());
}
public getExpressionActions(): actions.IAction[] {
return [this.instantiationService.createInstance(debugactions.RemoveWatchExpressionAction, debugactions.RemoveWatchExpressionAction.ID, debugactions.RemoveWatchExpressionAction.LABEL)];
}
public getSecondaryActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
const actions: actions.Action[] = [];
if (element instanceof model.Expression) {
const expression = <model.Expression>element;
actions.push(this.instantiationService.createInstance(debugactions.AddWatchExpressionAction, debugactions.AddWatchExpressionAction.ID, debugactions.AddWatchExpressionAction.LABEL));
actions.push(this.instantiationService.createInstance(debugactions.RenameWatchExpressionAction, debugactions.RenameWatchExpressionAction.ID, debugactions.RenameWatchExpressionAction.LABEL, expression));
if (expression.reference === 0) {
actions.push(this.instantiationService.createInstance(CopyValueAction, CopyValueAction.ID, CopyValueAction.LABEL, expression.value));
}
actions.push(new actionbar.Separator());
actions.push(this.instantiationService.createInstance(debugactions.RemoveWatchExpressionAction, debugactions.RemoveWatchExpressionAction.ID, debugactions.RemoveWatchExpressionAction.LABEL));
actions.push(this.instantiationService.createInstance(debugactions.RemoveAllWatchExpressionsAction, debugactions.RemoveAllWatchExpressionsAction.ID, debugactions.RemoveAllWatchExpressionsAction.LABEL));
} else {
actions.push(this.instantiationService.createInstance(debugactions.AddWatchExpressionAction, debugactions.AddWatchExpressionAction.ID, debugactions.AddWatchExpressionAction.LABEL));
if (element instanceof model.Variable) {
const variable = <model.Variable>element;
if (variable.reference === 0) {
actions.push(this.instantiationService.createInstance(CopyValueAction, CopyValueAction.ID, CopyValueAction.LABEL, variable.value));
}
actions.push(new actionbar.Separator());
}
actions.push(this.instantiationService.createInstance(debugactions.RemoveAllWatchExpressionsAction, debugactions.RemoveAllWatchExpressionsAction.ID, debugactions.RemoveAllWatchExpressionsAction.LABEL));
}
return TPromise.as(actions);
}
public getActionItem(tree: tree.ITree, element: any, action: actions.IAction): actionbar.IActionItem {
return null;
}
}
export class WatchExpressionsDataSource implements tree.IDataSource {
public getId(tree: tree.ITree, element: any): string {
return element.getId();
}
public hasChildren(tree: tree.ITree, element: any): boolean {
if (element instanceof model.Model) {
return true;
}
const watchExpression = <model.Expression>element;
return watchExpression.reference !== 0 && !strings.equalsIgnoreCase(watchExpression.value, 'null');
}
public getChildren(tree: tree.ITree, element: any): TPromise<any> {
if (element instanceof model.Model) {
return TPromise.as((<model.Model>element).getWatchExpressions());
}
let expression = <model.Expression>element;
return expression.getChildren();
}
public getParent(tree: tree.ITree, element: any): TPromise<any> {
return TPromise.as(null);
}
}
interface IWatchExpressionTemplateData extends IVariableTemplateData {
actionBar: actionbar.ActionBar;
}
export class WatchExpressionsRenderer implements tree.IRenderer {
private static WATCH_EXPRESSION_TEMPLATE_ID = 'watchExpression';
private static VARIABLE_TEMPLATE_ID = 'variables';
private toDispose: lifecycle.IDisposable[];
private actionProvider: WatchExpressionsActionProvider;
constructor(
actionProvider: renderer.IActionProvider,
private actionRunner: actions.IActionRunner,
@debug.IDebugService private debugService: debug.IDebugService,
@IContextViewService private contextViewService: IContextViewService
) {
this.toDispose = [];
this.actionProvider = <WatchExpressionsActionProvider>actionProvider;
}
public getHeight(tree: tree.ITree, element: any): number {
return 22;
}
public getTemplateId(tree: tree.ITree, element: any): string {
if (element instanceof model.Expression) {
return WatchExpressionsRenderer.WATCH_EXPRESSION_TEMPLATE_ID;
}
return WatchExpressionsRenderer.VARIABLE_TEMPLATE_ID;
}
public renderTemplate(tree: tree.ITree, templateId: string, container: HTMLElement): any {
let data: IWatchExpressionTemplateData = Object.create(null);
if (templateId === WatchExpressionsRenderer.WATCH_EXPRESSION_TEMPLATE_ID) {
data.actionBar = new actionbar.ActionBar(container, { actionRunner: this.actionRunner });
data.actionBar.push(this.actionProvider.getExpressionActions(), { icon: true, label: false });
}
data.expression = dom.append(container, $('.expression'));
data.name = dom.append(data.expression, $('span.name'));
data.value = dom.append(data.expression, $('span.value'));
return data;
}
public renderElement(tree: tree.ITree, element: any, templateId: string, templateData: any): void {
if (templateId === WatchExpressionsRenderer.WATCH_EXPRESSION_TEMPLATE_ID) {
this.renderWatchExpression(tree, element, templateData);
} else {
renderVariable(tree, element, templateData, true);
}
}
private renderWatchExpression(tree: tree.ITree, watchExpression: debug.IExpression, data: IWatchExpressionTemplateData): void {
let selectedExpression = this.debugService.getViewModel().getSelectedExpression();
if ((selectedExpression instanceof model.Expression && selectedExpression.getId() === watchExpression.getId()) || (watchExpression instanceof model.Expression && !watchExpression.name)) {
renderRenameBox(this.debugService, this.contextViewService, tree, watchExpression, data.expression, {
initialValue: watchExpression.name,
placeholder: nls.localize('watchExpressionPlaceholder', "Expression to watch"),
ariaLabel: nls.localize('watchExpressionInputAriaLabel', "Type watch expression")
});
}
data.actionBar.context = watchExpression;
data.name.textContent = watchExpression.name;
if (watchExpression.value) {
data.name.textContent += ':';
renderExpressionValue(watchExpression, data.value, true, MAX_VALUE_RENDER_LENGTH_IN_VIEWLET);
data.name.title = watchExpression.type ? watchExpression.type : watchExpression.value;
}
}
public disposeTemplate(tree: tree.ITree, templateId: string, templateData: any): void {
if (templateId === WatchExpressionsRenderer.WATCH_EXPRESSION_TEMPLATE_ID) {
(<IWatchExpressionTemplateData>templateData).actionBar.dispose();
}
}
public dispose(): void {
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
export class WatchExpressionsAccessibilityProvider implements tree.IAccessibilityProvider {
public getAriaLabel(tree: tree.ITree, element: any): string {
if (element instanceof model.Expression) {
return nls.localize('watchExpressionAriaLabel', "{0} value {1}, watch, debug", (<model.Expression>element).name, (<model.Expression>element).value);
}
if (element instanceof model.Variable) {
return nls.localize('watchVariableAriaLabel', "{0} value {1}, watch, debug", (<model.Variable>element).name, (<model.Variable>element).value);
}
return null;
}
}
export class WatchExpressionsController extends BaseDebugController {
constructor(debugService: debug.IDebugService, contextMenuService: IContextMenuService, actionProvider: renderer.IActionProvider) {
super(debugService, contextMenuService, actionProvider);
if (isMacintosh) {
this.downKeyBindingDispatcher.set(KeyCode.Enter, this.onRename.bind(this));
} else {
this.downKeyBindingDispatcher.set(KeyCode.F2, this.onRename.bind(this));
}
}
protected onLeftClick(tree: tree.ITree, element: any, event: IMouseEvent): boolean {
// double click on primitive value: open input box to be able to select and copy value.
if (element instanceof model.Expression && event.detail === 2) {
const expression = <debug.IExpression>element;
if (expression.reference === 0) {
this.debugService.getViewModel().setSelectedExpression(expression);
}
return true;
}
return super.onLeftClick(tree, element, event);
}
protected onRename(tree: tree.ITree, event: KeyboardEvent): boolean {
const element = tree.getFocus();
if (element instanceof model.Expression) {
const watchExpression = <model.Expression>element;
if (watchExpression.reference === 0) {
this.debugService.getViewModel().setSelectedExpression(watchExpression);
}
return true;
}
return false;
}
protected onDelete(tree: tree.ITree, event: IKeyboardEvent): boolean {
const element = tree.getFocus();
if (element instanceof model.Expression) {
const we = <model.Expression>element;
this.debugService.removeWatchExpressions(we.getId());
return true;
}
return false;
}
}
// breakpoints
export class BreakpointsActionProvider implements renderer.IActionProvider {
constructor(private instantiationService: IInstantiationService) {
// noop
}
public hasActions(tree: tree.ITree, element: any): boolean {
return element instanceof model.Breakpoint;
}
public hasSecondaryActions(tree: tree.ITree, element: any): boolean {
return element instanceof model.Breakpoint || element instanceof model.ExceptionBreakpoint || element instanceof model.FunctionBreakpoint;
}
public getActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
if (element instanceof model.Breakpoint) {
return TPromise.as(this.getBreakpointActions());
}
return TPromise.as([]);
}
public getBreakpointActions(): actions.IAction[] {
return [this.instantiationService.createInstance(debugactions.RemoveBreakpointAction, debugactions.RemoveBreakpointAction.ID, debugactions.RemoveBreakpointAction.LABEL)];
}
public getSecondaryActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
const actions: actions.Action[] = [this.instantiationService.createInstance(debugactions.ToggleEnablementAction, debugactions.ToggleEnablementAction.ID, debugactions.ToggleEnablementAction.LABEL)];
actions.push(new actionbar.Separator());
if (element instanceof model.Breakpoint || element instanceof model.FunctionBreakpoint) {
actions.push(this.instantiationService.createInstance(debugactions.RemoveBreakpointAction, debugactions.RemoveBreakpointAction.ID, debugactions.RemoveBreakpointAction.LABEL));
}
actions.push(this.instantiationService.createInstance(debugactions.RemoveAllBreakpointsAction, debugactions.RemoveAllBreakpointsAction.ID, debugactions.RemoveAllBreakpointsAction.LABEL));
actions.push(new actionbar.Separator());
actions.push(this.instantiationService.createInstance(debugactions.ToggleBreakpointsActivatedAction, debugactions.ToggleBreakpointsActivatedAction.ID, debugactions.ToggleBreakpointsActivatedAction.ACTIVATE_LABEL));
actions.push(new actionbar.Separator());
actions.push(this.instantiationService.createInstance(debugactions.EnableAllBreakpointsAction, debugactions.EnableAllBreakpointsAction.ID, debugactions.EnableAllBreakpointsAction.LABEL));
actions.push(this.instantiationService.createInstance(debugactions.DisableAllBreakpointsAction, debugactions.DisableAllBreakpointsAction.ID, debugactions.DisableAllBreakpointsAction.LABEL));
actions.push(new actionbar.Separator());
actions.push(this.instantiationService.createInstance(debugactions.AddFunctionBreakpointAction, debugactions.AddFunctionBreakpointAction.ID, debugactions.AddFunctionBreakpointAction.LABEL));
if (element instanceof model.FunctionBreakpoint) {
actions.push(this.instantiationService.createInstance(debugactions.RenameFunctionBreakpointAction, debugactions.RenameFunctionBreakpointAction.ID, debugactions.RenameFunctionBreakpointAction.LABEL));
}
actions.push(new actionbar.Separator());
actions.push(this.instantiationService.createInstance(debugactions.ReapplyBreakpointsAction, debugactions.ReapplyBreakpointsAction.ID, debugactions.ReapplyBreakpointsAction.LABEL));
return TPromise.as(actions);
}
public getActionItem(tree: tree.ITree, element: any, action: actions.IAction): actionbar.IActionItem {
return null;
}
}
export class BreakpointsDataSource implements tree.IDataSource {
public getId(tree: tree.ITree, element: any): string {
return element.getId();
}
public hasChildren(tree: tree.ITree, element: any): boolean {
return element instanceof model.Model;
}
public getChildren(tree: tree.ITree, element: any): TPromise<any> {
const model = <model.Model>element;
const exBreakpoints = <debug.IEnablement[]>model.getExceptionBreakpoints();
return TPromise.as(exBreakpoints.concat(model.getFunctionBreakpoints()).concat(model.getBreakpoints()));
}
public getParent(tree: tree.ITree, element: any): TPromise<any> {
return TPromise.as(null);
}
}
interface IExceptionBreakpointTemplateData {
breakpoint: HTMLElement;
name: HTMLElement;
checkbox: HTMLInputElement;
toDisposeBeforeRender: lifecycle.IDisposable[];
}
interface IBreakpointTemplateData extends IExceptionBreakpointTemplateData {
actionBar: actionbar.ActionBar;
lineNumber: HTMLElement;
filePath: HTMLElement;
}
interface IFunctionBreakpointTemplateData extends IExceptionBreakpointTemplateData {
actionBar: actionbar.ActionBar;
}
export class BreakpointsRenderer implements tree.IRenderer {
private static EXCEPTION_BREAKPOINT_TEMPLATE_ID = 'exceptionBreakpoint';
private static FUNCTION_BREAKPOINT_TEMPLATE_ID = 'functionBreakpoint';
private static BREAKPOINT_TEMPLATE_ID = 'breakpoint';
constructor(
private actionProvider: BreakpointsActionProvider,
private actionRunner: actions.IActionRunner,
@IWorkspaceContextService private contextService: IWorkspaceContextService,
@debug.IDebugService private debugService: debug.IDebugService,
@IContextViewService private contextViewService: IContextViewService
) {
// noop
}
public getHeight(tree: tree.ITree, element: any): number {
return 22;
}
public getTemplateId(tree: tree.ITree, element: any): string {
if (element instanceof model.Breakpoint) {
return BreakpointsRenderer.BREAKPOINT_TEMPLATE_ID;
}
if (element instanceof model.FunctionBreakpoint) {
return BreakpointsRenderer.FUNCTION_BREAKPOINT_TEMPLATE_ID;
}
if (element instanceof model.ExceptionBreakpoint) {
return BreakpointsRenderer.EXCEPTION_BREAKPOINT_TEMPLATE_ID;
}
return null;
}
public renderTemplate(tree: tree.ITree, templateId: string, container: HTMLElement): any {
const data: IBreakpointTemplateData = Object.create(null);
if (templateId === BreakpointsRenderer.BREAKPOINT_TEMPLATE_ID || templateId === BreakpointsRenderer.FUNCTION_BREAKPOINT_TEMPLATE_ID) {
data.actionBar = new actionbar.ActionBar(container, { actionRunner: this.actionRunner });
data.actionBar.push(this.actionProvider.getBreakpointActions(), { icon: true, label: false });
}
data.breakpoint = dom.append(container, $('.breakpoint'));
data.toDisposeBeforeRender = [];
data.checkbox = <HTMLInputElement>$('input');
data.checkbox.type = 'checkbox';
dom.append(data.breakpoint, data.checkbox);
data.name = dom.append(data.breakpoint, $('span.name'));
if (templateId === BreakpointsRenderer.BREAKPOINT_TEMPLATE_ID) {
data.lineNumber = dom.append(data.breakpoint, $('span.line-number'));
data.filePath = dom.append(data.breakpoint, $('span.file-path'));
}
return data;
}
public renderElement(tree: tree.ITree, element: any, templateId: string, templateData: any): void {
templateData.toDisposeBeforeRender = lifecycle.dispose(templateData.toDisposeBeforeRender);
templateData.toDisposeBeforeRender.push(dom.addStandardDisposableListener(templateData.checkbox, 'change', (e) => {
this.debugService.enableOrDisableBreakpoints(!element.enabled, element);
}));
if (templateId === BreakpointsRenderer.EXCEPTION_BREAKPOINT_TEMPLATE_ID) {
this.renderExceptionBreakpoint(element, templateData);
} else if (templateId === BreakpointsRenderer.FUNCTION_BREAKPOINT_TEMPLATE_ID) {
this.renderFunctionBreakpoint(tree, element, templateData);
} else {
this.renderBreakpoint(tree, element, templateData);
}
}
private renderExceptionBreakpoint(exceptionBreakpoint: debug.IExceptionBreakpoint, data: IExceptionBreakpointTemplateData): void {
data.name.textContent = exceptionBreakpoint.label || `${exceptionBreakpoint.filter} exceptions`;;
data.breakpoint.title = data.name.textContent;
data.checkbox.checked = exceptionBreakpoint.enabled;
}
private renderFunctionBreakpoint(tree: tree.ITree, functionBreakpoint: debug.IFunctionBreakpoint, data: IFunctionBreakpointTemplateData): void {
const selected = this.debugService.getViewModel().getSelectedFunctionBreakpoint();
if (!functionBreakpoint.name || (selected && selected.getId() === functionBreakpoint.getId())) {
renderRenameBox(this.debugService, this.contextViewService, tree, functionBreakpoint, data.breakpoint, {
initialValue: functionBreakpoint.name,
placeholder: nls.localize('functionBreakpointPlaceholder', "Function to break on"),
ariaLabel: nls.localize('functionBreakPointInputAriaLabel', "Type function breakpoint")
});
} else {
data.name.textContent = functionBreakpoint.name;
data.checkbox.checked = functionBreakpoint.enabled;
data.breakpoint.title = functionBreakpoint.name;
// Mark function breakpoints as disabled if deactivated or if debug type does not support them #9099
const session = this.debugService.getViewModel().activeSession;
if ((session && !session.configuration.capabilities.supportsFunctionBreakpoints) || !this.debugService.getModel().areBreakpointsActivated()) {
tree.addTraits('disabled', [functionBreakpoint]);
if (session && !session.configuration.capabilities.supportsFunctionBreakpoints) {
data.breakpoint.title = nls.localize('functionBreakpointsNotSupported', "Function breakpoints are not supported by this debug type");
}
} else {
tree.removeTraits('disabled', [functionBreakpoint]);
}
}
data.actionBar.context = functionBreakpoint;
}
private renderBreakpoint(tree: tree.ITree, breakpoint: debug.IBreakpoint, data: IBreakpointTemplateData): void {
this.debugService.getModel().areBreakpointsActivated() ? tree.removeTraits('disabled', [breakpoint]) : tree.addTraits('disabled', [breakpoint]);
data.name.textContent = labels.getPathLabel(paths.basename(breakpoint.source.uri.fsPath), this.contextService);
data.lineNumber.textContent = breakpoint.desiredLineNumber !== breakpoint.lineNumber ? breakpoint.desiredLineNumber + ' \u2192 ' + breakpoint.lineNumber : '' + breakpoint.lineNumber;
data.filePath.textContent = labels.getPathLabel(paths.dirname(breakpoint.source.uri.fsPath), this.contextService);
data.checkbox.checked = breakpoint.enabled;
data.actionBar.context = breakpoint;
const debugActive = this.debugService.state === debug.State.Running || this.debugService.state === debug.State.Stopped || this.debugService.state === debug.State.Initializing;
if (debugActive && !breakpoint.verified) {
tree.addTraits('disabled', [breakpoint]);
if (breakpoint.message) {
data.breakpoint.title = breakpoint.message;
}
} else if (breakpoint.condition || breakpoint.hitCondition) {
data.breakpoint.title = breakpoint.condition ? breakpoint.condition : breakpoint.hitCondition;
}
}
public disposeTemplate(tree: tree.ITree, templateId: string, templateData: any): void {
if (templateId === BreakpointsRenderer.BREAKPOINT_TEMPLATE_ID || templateId === BreakpointsRenderer.FUNCTION_BREAKPOINT_TEMPLATE_ID) {
templateData.actionBar.dispose();
}
}
}
export class BreakpointsAccessibilityProvider implements tree.IAccessibilityProvider {
constructor( @IWorkspaceContextService private contextService: IWorkspaceContextService) {
// noop
}
public getAriaLabel(tree: tree.ITree, element: any): string {
if (element instanceof model.Breakpoint) {
return nls.localize('breakpointAriaLabel', "Breakpoint line {0} {1}, breakpoints, debug", (<model.Breakpoint>element).lineNumber, getSourceName((<model.Breakpoint>element).source, this.contextService));
}
if (element instanceof model.FunctionBreakpoint) {
return nls.localize('functionBreakpointAriaLabel', "Function breakpoint {0}, breakpoints, debug", (<model.FunctionBreakpoint>element).name);
}
if (element instanceof model.ExceptionBreakpoint) {
return nls.localize('exceptionBreakpointAriaLabel', "Exception breakpoint {0}, breakpoints, debug", (<model.ExceptionBreakpoint>element).filter);
}
return null;
}
}
export class BreakpointsController extends BaseDebugController {
constructor(debugService: debug.IDebugService, contextMenuService: IContextMenuService, actionProvider: renderer.IActionProvider) {
super(debugService, contextMenuService, actionProvider);
if (isMacintosh) {
this.downKeyBindingDispatcher.set(KeyCode.Enter, this.onRename.bind(this));
} else {
this.downKeyBindingDispatcher.set(KeyCode.F2, this.onRename.bind(this));
}
}
protected onLeftClick(tree: tree.ITree, element: any, event: IMouseEvent): boolean {
if (element instanceof model.FunctionBreakpoint && event.detail === 2) {
this.debugService.getViewModel().setSelectedFunctionBreakpoint(element);
return true;
}
if (element instanceof model.Breakpoint) {
this.openBreakpointSource(element, event, true);
}
return super.onLeftClick(tree, element, event);
}
protected onRename(tree: tree.ITree, event: IKeyboardEvent): boolean {
const element = tree.getFocus();
if (element instanceof model.FunctionBreakpoint && element.name) {
this.debugService.getViewModel().setSelectedFunctionBreakpoint(element);
return true;
}
if (element instanceof model.Breakpoint) {
this.openBreakpointSource(element, event, false);
}
return super.onEnter(tree, event);
}
protected onSpace(tree: tree.ITree, event: IKeyboardEvent): boolean {
super.onSpace(tree, event);
const element = <debug.IEnablement>tree.getFocus();
this.debugService.enableOrDisableBreakpoints(!element.enabled, element).done(null, errors.onUnexpectedError);
return true;
}
protected onDelete(tree: tree.ITree, event: IKeyboardEvent): boolean {
const element = tree.getFocus();
if (element instanceof model.Breakpoint) {
this.debugService.removeBreakpoints((<model.Breakpoint>element).getId()).done(null, errors.onUnexpectedError);
return true;
} else if (element instanceof model.FunctionBreakpoint) {
const fbp = <model.FunctionBreakpoint>element;
this.debugService.removeFunctionBreakpoints(fbp.getId()).done(null, errors.onUnexpectedError);
return true;
}
return false;
}
private openBreakpointSource(breakpoint: debug.IBreakpoint, event: IKeyboardEvent | IMouseEvent, preserveFocus: boolean): void {
if (!breakpoint.source.inMemory) {
const sideBySide = (event && (event.ctrlKey || event.metaKey));
this.debugService.openOrRevealSource(breakpoint.source, breakpoint.lineNumber, preserveFocus, sideBySide).done(null, errors.onUnexpectedError);
}
}
}
| src/vs/workbench/parts/debug/electron-browser/debugViewer.ts | 1 | https://github.com/microsoft/vscode/commit/bb194502143f100abe468b1328a54e33c62fd514 | [
0.9992049336433411,
0.033126574009656906,
0.00016177409270312637,
0.00021344036213122308,
0.1703736037015915
] |
{
"id": 1,
"code_window": [
"\tpublic getChildren(tree: tree.ITree, element: any): TPromise<any> {\n",
"\t\tif (element instanceof model.Thread) {\n",
"\t\t\treturn this.getThreadChildren(element);\n",
"\t\t}\n",
"\n",
"\t\t// TODO@Isidor FIX THIS\n",
"\t\tconst session = this.debugService.getViewModel().activeSession;\n",
"\t\tif (!session) {\n",
"\t\t\treturn TPromise.as([]);\n",
"\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tif (element instanceof model.Model) {\n",
"\t\t\treturn TPromise.as(element.getSessions());\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugViewer.ts",
"type": "replace",
"edit_start_line_idx": 363
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"formatAction.label": "Code formatieren"
} | i18n/deu/src/vs/editor/contrib/format/common/formatActions.i18n.json | 0 | https://github.com/microsoft/vscode/commit/bb194502143f100abe468b1328a54e33c62fd514 | [
0.0001791780669009313,
0.0001791780669009313,
0.0001791780669009313,
0.0001791780669009313,
0
] |
{
"id": 1,
"code_window": [
"\tpublic getChildren(tree: tree.ITree, element: any): TPromise<any> {\n",
"\t\tif (element instanceof model.Thread) {\n",
"\t\t\treturn this.getThreadChildren(element);\n",
"\t\t}\n",
"\n",
"\t\t// TODO@Isidor FIX THIS\n",
"\t\tconst session = this.debugService.getViewModel().activeSession;\n",
"\t\tif (!session) {\n",
"\t\t\treturn TPromise.as([]);\n",
"\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tif (element instanceof model.Model) {\n",
"\t\t\treturn TPromise.as(element.getSessions());\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugViewer.ts",
"type": "replace",
"edit_start_line_idx": 363
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"notFound": "在 Zip 中找不到 {0}。"
} | i18n/chs/src/vs/base/node/zip.i18n.json | 0 | https://github.com/microsoft/vscode/commit/bb194502143f100abe468b1328a54e33c62fd514 | [
0.0001784224878065288,
0.0001784224878065288,
0.0001784224878065288,
0.0001784224878065288,
0
] |
{
"id": 1,
"code_window": [
"\tpublic getChildren(tree: tree.ITree, element: any): TPromise<any> {\n",
"\t\tif (element instanceof model.Thread) {\n",
"\t\t\treturn this.getThreadChildren(element);\n",
"\t\t}\n",
"\n",
"\t\t// TODO@Isidor FIX THIS\n",
"\t\tconst session = this.debugService.getViewModel().activeSession;\n",
"\t\tif (!session) {\n",
"\t\t\treturn TPromise.as([]);\n",
"\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tif (element instanceof model.Model) {\n",
"\t\t\treturn TPromise.as(element.getSessions());\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugViewer.ts",
"type": "replace",
"edit_start_line_idx": 363
} | /*---------------------------------------------------------------------------------------------
* 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 { Socket, Server as NetServer, createConnection, createServer } from 'net';
import { TPromise } from 'vs/base/common/winjs.base';
import { IDisposable } from 'vs/base/common/lifecycle';
import Event, { Emitter, once } from 'vs/base/common/event';
import { fromEventEmitter } from 'vs/base/node/event';
import { ChannelServer, ChannelClient, IMessagePassingProtocol, IChannelServer, IChannelClient, IRoutingChannelClient, IClientRouter, IChannel } from 'vs/base/parts/ipc/common/ipc';
function bufferIndexOf(buffer: Buffer, value: number, start = 0) {
while (start < buffer.length && buffer[start] !== value) {
start++;
}
return start;
}
class Protocol implements IMessagePassingProtocol {
private static Boundary = new Buffer([0]);
private _onMessage: Event<any>;
get onMessage(): Event<any> { return this._onMessage; }
constructor(private socket: Socket) {
let buffer = null;
const emitter = new Emitter<any>();
const onRawData = fromEventEmitter(socket, 'data', data => data);
onRawData((data: Buffer) => {
let lastIndex = 0;
let index = 0;
while ((index = bufferIndexOf(data, 0, lastIndex)) < data.length) {
const dataToParse = data.slice(lastIndex, index);
if (buffer) {
emitter.fire(JSON.parse(Buffer.concat([buffer, dataToParse]).toString('utf8')));
buffer = null;
} else {
emitter.fire(JSON.parse(dataToParse.toString('utf8')));
}
lastIndex = index + 1;
}
if (index - lastIndex > 0) {
const dataToBuffer = data.slice(lastIndex, index);
if (buffer) {
buffer = Buffer.concat([buffer, dataToBuffer]);
} else {
buffer = dataToBuffer;
}
}
});
this._onMessage = emitter.event;
}
public send(message: any): void {
try {
this.socket.write(JSON.stringify(message));
this.socket.write(Protocol.Boundary);
} catch (e) {
// noop
}
}
}
class RoutingChannelClient implements IRoutingChannelClient, IDisposable {
private ipcClients: { [id: string]: ChannelClient; };
private onClientAdded = new Emitter();
constructor() {
this.ipcClients = Object.create(null);
}
add(id: string, client: ChannelClient): void {
this.ipcClients[id] = client;
this.onClientAdded.fire();
}
remove(id: string): void {
delete this.ipcClients[id];
}
private getClient(clientId: string): TPromise<IChannelClient> {
const getClientFn = (clientId: string, c: (client: IChannelClient) => void): boolean => {
let client = this.ipcClients[clientId];
if (client) {
c(client);
return true;
}
return false;
};
return new TPromise<IChannelClient>((c, e) => {
if (!getClientFn(clientId, c)) {
let disposable = this.onClientAdded.event(() => {
if (getClientFn(clientId, c)) {
disposable.dispose();
}
});
}
});
}
getChannel<T extends IChannel>(channelName: string, router: IClientRouter): T {
const call = (command: string, arg: any) => {
const id = router.routeCall(command, arg);
if (!id) {
return TPromise.wrapError('Client id should be provided');
}
return this.getClient(id).then(client => client.getChannel(channelName).call(command, arg));
};
return { call } as T;
}
dispose() {
this.ipcClients = null;
this.onClientAdded.dispose();
}
}
// TODO@joao: move multi channel implementation down to ipc
export class Server implements IChannelServer, IRoutingChannelClient, IDisposable {
private channels: { [name: string]: IChannel };
private router: RoutingChannelClient;
constructor(private server: NetServer) {
this.channels = Object.create(null);
this.router = new RoutingChannelClient();
this.server.on('connection', (socket: Socket) => {
const protocol = new Protocol(socket);
const onFirstMessage = once(protocol.onMessage);
onFirstMessage(id => {
const channelServer = new ChannelServer(protocol);
Object.keys(this.channels)
.forEach(name => channelServer.registerChannel(name, this.channels[name]));
const channelClient = new ChannelClient(protocol);
this.router.add(id, channelClient);
socket.once('close', () => {
channelClient.dispose();
this.router.remove(id);
channelServer.dispose();
});
});
});
}
getChannel<T extends IChannel>(channelName: string, router: IClientRouter): T {
return this.router.getChannel<T>(channelName, router);
}
registerChannel(channelName: string, channel: IChannel): void {
this.channels[channelName] = channel;
}
dispose(): void {
this.router.dispose();
this.router = null;
this.channels = null;
this.server.close();
this.server = null;
}
}
export class Client implements IChannelClient, IChannelServer, IDisposable {
private channelClient: ChannelClient;
private channelServer: ChannelServer;
private _onClose = new Emitter<void>();
get onClose(): Event<void> { return this._onClose.event; }
constructor(private socket: Socket, id: string) {
const protocol = new Protocol(socket);
protocol.send(id);
this.channelClient = new ChannelClient(protocol);
this.channelServer = new ChannelServer(protocol);
socket.once('close', () => this._onClose.fire());
}
getChannel<T extends IChannel>(channelName: string): T {
return this.channelClient.getChannel(channelName) as T;
}
registerChannel(channelName: string, channel: IChannel): void {
this.channelServer.registerChannel(channelName, channel);
}
dispose(): void {
this.socket.end();
this.socket = null;
this.channelClient = null;
this.channelServer.dispose();
this.channelServer = null;
}
}
export function serve(port: number): TPromise<Server>;
export function serve(namedPipe: string): TPromise<Server>;
export function serve(hook: any): TPromise<Server> {
return new TPromise<Server>((c, e) => {
const server = createServer();
server.on('error', e);
server.listen(hook, () => {
server.removeListener('error', e);
c(new Server(server));
});
});
}
export function connect(port: number, clientId: string): TPromise<Client>;
export function connect(namedPipe: string, clientId: string): TPromise<Client>;
export function connect(hook: any, clientId: string): TPromise<Client> {
return new TPromise<Client>((c, e) => {
const socket = createConnection(hook, () => {
socket.removeListener('error', e);
c(new Client(socket, clientId));
});
socket.once('error', e);
});
} | src/vs/base/parts/ipc/node/ipc.net.ts | 0 | https://github.com/microsoft/vscode/commit/bb194502143f100abe468b1328a54e33c62fd514 | [
0.00017764770018402487,
0.00017215900879818946,
0.0001654336811043322,
0.00017166766338050365,
0.000003474447339613107
] |
{
"id": 2,
"code_window": [
"\t\t}\n",
"\n",
"\t\tconst threads = (<model.Model>element).getThreads(session.getId());\n",
"\t\treturn TPromise.as(Object.keys(threads).map(ref => threads[ref]));\n",
"\t}\n",
"\n",
"\tprivate getThreadChildren(thread: debug.IThread): TPromise<any> {\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst session = <debug.IRawDebugSession>element;\n",
"\t\tconst threads = this.debugService.getModel().getThreads(session.getId());\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugViewer.ts",
"type": "replace",
"edit_start_line_idx": 370
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import nls = require('vs/nls');
import { TPromise } from 'vs/base/common/winjs.base';
import lifecycle = require('vs/base/common/lifecycle');
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import paths = require('vs/base/common/paths');
import async = require('vs/base/common/async');
import errors = require('vs/base/common/errors');
import strings = require('vs/base/common/strings');
import { isMacintosh } from 'vs/base/common/platform';
import dom = require('vs/base/browser/dom');
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import labels = require('vs/base/common/labels');
import actions = require('vs/base/common/actions');
import actionbar = require('vs/base/browser/ui/actionbar/actionbar');
import tree = require('vs/base/parts/tree/browser/tree');
import { InputBox, IInputValidationOptions } from 'vs/base/browser/ui/inputbox/inputBox';
import treedefaults = require('vs/base/parts/tree/browser/treeDefaults');
import renderer = require('vs/base/parts/tree/browser/actionsRenderer');
import debug = require('vs/workbench/parts/debug/common/debug');
import model = require('vs/workbench/parts/debug/common/debugModel');
import viewmodel = require('vs/workbench/parts/debug/common/debugViewModel');
import debugactions = require('vs/workbench/parts/debug/browser/debugActions');
import { CopyValueAction } from 'vs/workbench/parts/debug/electron-browser/electronDebugActions';
import { IContextViewService, IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
const $ = dom.$;
const booleanRegex = /^true|false$/i;
const stringRegex = /^(['"]).*\1$/;
const MAX_VALUE_RENDER_LENGTH_IN_VIEWLET = 1024;
export function renderExpressionValue(expressionOrValue: debug.IExpression | string, container: HTMLElement, showChanged: boolean, maxValueRenderLength?: number): void {
let value = typeof expressionOrValue === 'string' ? expressionOrValue : expressionOrValue.value;
// remove stale classes
container.className = 'value';
// when resolving expressions we represent errors from the server as a variable with name === null.
if (value === null || ((expressionOrValue instanceof model.Expression || expressionOrValue instanceof model.Variable) && !expressionOrValue.available)) {
dom.addClass(container, 'unavailable');
if (value !== model.Expression.DEFAULT_VALUE) {
dom.addClass(container, 'error');
}
} else if (!isNaN(+value)) {
dom.addClass(container, 'number');
} else if (booleanRegex.test(value)) {
dom.addClass(container, 'boolean');
} else if (stringRegex.test(value)) {
dom.addClass(container, 'string');
}
if (showChanged && (<any>expressionOrValue).valueChanged) {
// value changed color has priority over other colors.
container.className = 'value changed';
}
if (maxValueRenderLength && value.length > maxValueRenderLength) {
value = value.substr(0, maxValueRenderLength) + '...';
}
container.textContent = value;
container.title = value;
}
export function renderVariable(tree: tree.ITree, variable: model.Variable, data: IVariableTemplateData, showChanged: boolean): void {
if (variable.available) {
data.name.textContent = variable.name;
data.name.title = variable.type ? variable.type : '';
}
if (variable.value) {
data.name.textContent += ':';
renderExpressionValue(variable, data.value, showChanged, MAX_VALUE_RENDER_LENGTH_IN_VIEWLET);
data.value.title = variable.value;
} else {
data.value.textContent = '';
data.value.title = '';
}
}
interface IRenameBoxOptions {
initialValue: string;
ariaLabel: string;
placeholder?: string;
validationOptions?: IInputValidationOptions;
}
function renderRenameBox(debugService: debug.IDebugService, contextViewService: IContextViewService, tree: tree.ITree, element: any, container: HTMLElement, options: IRenameBoxOptions): void {
let inputBoxContainer = dom.append(container, $('.inputBoxContainer'));
let inputBox = new InputBox(inputBoxContainer, contextViewService, {
validationOptions: options.validationOptions,
placeholder: options.placeholder,
ariaLabel: options.ariaLabel
});
inputBox.value = options.initialValue ? options.initialValue : '';
inputBox.focus();
inputBox.select();
let disposed = false;
const toDispose: [lifecycle.IDisposable] = [inputBox];
const wrapUp = async.once((renamed: boolean) => {
if (!disposed) {
disposed = true;
if (element instanceof model.Expression && renamed && inputBox.value) {
debugService.renameWatchExpression(element.getId(), inputBox.value).done(null, errors.onUnexpectedError);
} else if (element instanceof model.Expression && !element.name) {
debugService.removeWatchExpressions(element.getId());
} else if (element instanceof model.FunctionBreakpoint && renamed && inputBox.value) {
debugService.renameFunctionBreakpoint(element.getId(), inputBox.value).done(null, errors.onUnexpectedError);
} else if (element instanceof model.FunctionBreakpoint && !element.name) {
debugService.removeFunctionBreakpoints(element.getId()).done(null, errors.onUnexpectedError);
} else if (element instanceof model.Variable) {
(<model.Variable>element).errorMessage = null;
if (renamed && element.value !== inputBox.value) {
debugService.setVariable(element, inputBox.value)
// if everything went fine we need to refresh that tree element since his value updated
.done(() => tree.refresh(element, false), errors.onUnexpectedError);
}
}
tree.clearHighlight();
tree.DOMFocus();
tree.setFocus(element);
// need to remove the input box since this template will be reused.
container.removeChild(inputBoxContainer);
lifecycle.dispose(toDispose);
}
});
toDispose.push(dom.addStandardDisposableListener(inputBox.inputElement, 'keydown', (e: IKeyboardEvent) => {
const isEscape = e.equals(KeyCode.Escape);
const isEnter = e.equals(KeyCode.Enter);
if (isEscape || isEnter) {
wrapUp(isEnter);
}
}));
toDispose.push(dom.addDisposableListener(inputBox.inputElement, 'blur', () => {
wrapUp(true);
}));
}
function getSourceName(source: Source, contextService: IWorkspaceContextService): string {
if (source.inMemory) {
return source.name;
}
return labels.getPathLabel(paths.basename(source.uri.fsPath), contextService);
}
export class BaseDebugController extends treedefaults.DefaultController {
constructor(
protected debugService: debug.IDebugService,
private contextMenuService: IContextMenuService,
private actionProvider: renderer.IActionProvider,
private focusOnContextMenu = true
) {
super();
if (isMacintosh) {
this.downKeyBindingDispatcher.set(KeyMod.CtrlCmd | KeyCode.Backspace, this.onDelete.bind(this));
} else {
this.downKeyBindingDispatcher.set(KeyCode.Delete, this.onDelete.bind(this));
this.downKeyBindingDispatcher.set(KeyMod.Shift | KeyCode.Delete, this.onDelete.bind(this));
}
}
public onContextMenu(tree: tree.ITree, element: debug.IEnablement, event: tree.ContextMenuEvent): boolean {
if (event.target && event.target.tagName && event.target.tagName.toLowerCase() === 'input') {
return false;
}
event.preventDefault();
event.stopPropagation();
if (this.focusOnContextMenu) {
tree.setFocus(element);
}
if (this.actionProvider.hasSecondaryActions(tree, element)) {
const anchor = { x: event.posx + 1, y: event.posy };
this.contextMenuService.showContextMenu({
getAnchor: () => anchor,
getActions: () => this.actionProvider.getSecondaryActions(tree, element),
onHide: (wasCancelled?: boolean) => {
if (wasCancelled) {
tree.DOMFocus();
}
},
getActionsContext: () => element
});
return true;
}
return false;
}
protected onDelete(tree: tree.ITree, event: IKeyboardEvent): boolean {
return false;
}
}
// call stack
class ThreadAndSessionId {
constructor(public sessionId: string, public threadId: number) { }
}
export class CallStackController extends BaseDebugController {
protected onLeftClick(tree: tree.ITree, element: any, event: IMouseEvent): boolean {
if (element instanceof ThreadAndSessionId) {
return this.showMoreStackFrames(tree, element);
}
if (element instanceof model.StackFrame) {
this.focusStackFrame(element, event, true);
}
return super.onLeftClick(tree, element, event);
}
protected onEnter(tree: tree.ITree, event: IKeyboardEvent): boolean {
const element = tree.getFocus();
if (element instanceof ThreadAndSessionId) {
return this.showMoreStackFrames(tree, element);
}
if (element instanceof model.StackFrame) {
this.focusStackFrame(element, event, false);
}
return super.onEnter(tree, event);
}
protected onUp(tree: tree.ITree, event: IKeyboardEvent): boolean {
super.onUp(tree, event);
this.focusStackFrame(tree.getFocus(), event, true);
return true;
}
protected onPageUp(tree: tree.ITree, event: IKeyboardEvent): boolean {
super.onPageUp(tree, event);
this.focusStackFrame(tree.getFocus(), event, true);
return true;
}
protected onDown(tree: tree.ITree, event: IKeyboardEvent): boolean {
super.onDown(tree, event);
this.focusStackFrame(tree.getFocus(), event, true);
return true;
}
protected onPageDown(tree: tree.ITree, event: IKeyboardEvent): boolean {
super.onPageDown(tree, event);
this.focusStackFrame(tree.getFocus(), event, true);
return true;
}
// user clicked / pressed on 'Load More Stack Frames', get those stack frames and refresh the tree.
private showMoreStackFrames(tree: tree.ITree, threadAndSessionId: ThreadAndSessionId): boolean {
const thread = this.debugService.getModel().getThreads(threadAndSessionId.sessionId)[threadAndSessionId.threadId];
if (thread) {
thread.getCallStack(true)
.done(() => tree.refresh(), errors.onUnexpectedError);
}
return true;
}
private focusStackFrame(stackFrame: debug.IStackFrame, event: IKeyboardEvent | IMouseEvent, preserveFocus: boolean): void {
this.debugService.setFocusedStackFrameAndEvaluate(stackFrame).done(null, errors.onUnexpectedError);
if (stackFrame) {
const sideBySide = (event && (event.ctrlKey || event.metaKey));
this.debugService.openOrRevealSource(stackFrame.source, stackFrame.lineNumber, preserveFocus, sideBySide).done(null, errors.onUnexpectedError);
}
}
}
export class CallStackActionProvider implements renderer.IActionProvider {
constructor( @IInstantiationService private instantiationService: IInstantiationService, @debug.IDebugService private debugService: debug.IDebugService) {
// noop
}
public hasActions(tree: tree.ITree, element: any): boolean {
return false;
}
public getActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
return TPromise.as([]);
}
public hasSecondaryActions(tree: tree.ITree, element: any): boolean {
return element instanceof model.Thread || element instanceof model.StackFrame;
}
public getSecondaryActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
const actions: actions.Action[] = [];
if (element instanceof model.Thread) {
const thread = <model.Thread>element;
if (thread.stopped) {
actions.push(this.instantiationService.createInstance(debugactions.ContinueAction, debugactions.ContinueAction.ID, debugactions.ContinueAction.LABEL));
actions.push(this.instantiationService.createInstance(debugactions.StepOverAction, debugactions.StepOverAction.ID, debugactions.StepOverAction.LABEL));
actions.push(this.instantiationService.createInstance(debugactions.StepIntoAction, debugactions.StepIntoAction.ID, debugactions.StepIntoAction.LABEL));
actions.push(this.instantiationService.createInstance(debugactions.StepOutAction, debugactions.StepOutAction.ID, debugactions.StepOutAction.LABEL));
} else {
actions.push(this.instantiationService.createInstance(debugactions.PauseAction, debugactions.PauseAction.ID, debugactions.PauseAction.LABEL));
}
} else if (element instanceof model.StackFrame) {
const capabilities = this.debugService.getViewModel().activeSession.configuration.capabilities;
if (typeof capabilities.supportsRestartFrame === 'boolean' && capabilities.supportsRestartFrame) {
actions.push(this.instantiationService.createInstance(debugactions.RestartFrameAction, debugactions.RestartFrameAction.ID, debugactions.RestartFrameAction.LABEL));
}
}
return TPromise.as(actions);
}
public getActionItem(tree: tree.ITree, element: any, action: actions.IAction): actionbar.IActionItem {
return null;
}
}
export class CallStackDataSource implements tree.IDataSource {
constructor( @debug.IDebugService private debugService: debug.IDebugService) {
// noop
}
public getId(tree: tree.ITree, element: any): string {
if (typeof element === 'number') {
return element.toString();
}
if (typeof element === 'string') {
return element;
}
return element.getId();
}
public hasChildren(tree: tree.ITree, element: any): boolean {
return element instanceof model.Model || (element instanceof model.Thread && (<model.Thread>element).stopped);
}
public getChildren(tree: tree.ITree, element: any): TPromise<any> {
if (element instanceof model.Thread) {
return this.getThreadChildren(element);
}
// TODO@Isidor FIX THIS
const session = this.debugService.getViewModel().activeSession;
if (!session) {
return TPromise.as([]);
}
const threads = (<model.Model>element).getThreads(session.getId());
return TPromise.as(Object.keys(threads).map(ref => threads[ref]));
}
private getThreadChildren(thread: debug.IThread): TPromise<any> {
return thread.getCallStack().then((callStack: any[]) => {
if (thread.stoppedDetails && thread.stoppedDetails.framesErrorMessage) {
return callStack.concat([thread.stoppedDetails.framesErrorMessage]);
}
if (thread.stoppedDetails && thread.stoppedDetails.totalFrames > callStack.length) {
return callStack.concat([new ThreadAndSessionId(thread.sessionId, thread.threadId)]);
}
return callStack;
});
}
public getParent(tree: tree.ITree, element: any): TPromise<any> {
return TPromise.as(null);
}
}
interface IThreadTemplateData {
thread: HTMLElement;
name: HTMLElement;
state: HTMLElement;
stateLabel: HTMLSpanElement;
}
interface IErrorTemplateData {
label: HTMLElement;
}
interface ILoadMoreTemplateData {
label: HTMLElement;
}
interface IStackFrameTemplateData {
stackFrame: HTMLElement;
label: HTMLElement;
file: HTMLElement;
fileName: HTMLElement;
lineNumber: HTMLElement;
}
export class CallStackRenderer implements tree.IRenderer {
private static THREAD_TEMPLATE_ID = 'thread';
private static STACK_FRAME_TEMPLATE_ID = 'stackFrame';
private static ERROR_TEMPLATE_ID = 'error';
private static LOAD_MORE_TEMPLATE_ID = 'loadMore';
constructor( @IWorkspaceContextService private contextService: IWorkspaceContextService) {
// noop
}
public getHeight(tree: tree.ITree, element: any): number {
return 22;
}
public getTemplateId(tree: tree.ITree, element: any): string {
if (element instanceof model.Thread) {
return CallStackRenderer.THREAD_TEMPLATE_ID;
}
if (element instanceof model.StackFrame) {
return CallStackRenderer.STACK_FRAME_TEMPLATE_ID;
}
if (typeof element === 'string') {
return CallStackRenderer.ERROR_TEMPLATE_ID;
}
return CallStackRenderer.LOAD_MORE_TEMPLATE_ID;
}
public renderTemplate(tree: tree.ITree, templateId: string, container: HTMLElement): any {
if (templateId === CallStackRenderer.LOAD_MORE_TEMPLATE_ID) {
let data: ILoadMoreTemplateData = Object.create(null);
data.label = dom.append(container, $('.load-more'));
return data;
}
if (templateId === CallStackRenderer.ERROR_TEMPLATE_ID) {
let data: ILoadMoreTemplateData = Object.create(null);
data.label = dom.append(container, $('.error'));
return data;
}
if (templateId === CallStackRenderer.THREAD_TEMPLATE_ID) {
let data: IThreadTemplateData = Object.create(null);
data.thread = dom.append(container, $('.thread'));
data.name = dom.append(data.thread, $('.name'));
data.state = dom.append(data.thread, $('.state'));
data.stateLabel = dom.append(data.state, $('span.label'));
return data;
}
let data: IStackFrameTemplateData = Object.create(null);
data.stackFrame = dom.append(container, $('.stack-frame'));
data.label = dom.append(data.stackFrame, $('span.label'));
data.file = dom.append(data.stackFrame, $('.file'));
data.fileName = dom.append(data.file, $('span.file-name'));
data.lineNumber = dom.append(data.file, $('span.line-number'));
return data;
}
public renderElement(tree: tree.ITree, element: any, templateId: string, templateData: any): void {
if (templateId === CallStackRenderer.THREAD_TEMPLATE_ID) {
this.renderThread(element, templateData);
} else if (templateId === CallStackRenderer.STACK_FRAME_TEMPLATE_ID) {
this.renderStackFrame(element, templateData);
} else if (templateId === CallStackRenderer.ERROR_TEMPLATE_ID) {
this.renderError(element, templateData);
} else {
this.renderLoadMore(element, templateData);
}
}
private renderThread(thread: debug.IThread, data: IThreadTemplateData): void {
data.thread.title = nls.localize('thread', "Thread");
data.name.textContent = thread.name;
data.stateLabel.textContent = thread.stopped ? nls.localize('paused', "paused")
: nls.localize({ key: 'running', comment: ['indicates state'] }, "running");
}
private renderError(element: string, data: IErrorTemplateData) {
data.label.textContent = element;
data.label.title = element;
}
private renderLoadMore(element: any, data: ILoadMoreTemplateData): void {
data.label.textContent = nls.localize('loadMoreStackFrames', "Load More Stack Frames");
}
private renderStackFrame(stackFrame: debug.IStackFrame, data: IStackFrameTemplateData): void {
stackFrame.source.available ? dom.removeClass(data.stackFrame, 'disabled') : dom.addClass(data.stackFrame, 'disabled');
data.file.title = stackFrame.source.uri.fsPath;
data.label.textContent = stackFrame.name;
data.label.title = stackFrame.name;
data.fileName.textContent = getSourceName(stackFrame.source, this.contextService);
if (stackFrame.lineNumber !== undefined) {
data.lineNumber.textContent = `${stackFrame.lineNumber}`;
dom.removeClass(data.lineNumber, 'unavailable');
} else {
dom.addClass(data.lineNumber, 'unavailable');
}
}
public disposeTemplate(tree: tree.ITree, templateId: string, templateData: any): void {
// noop
}
}
export class CallstackAccessibilityProvider implements tree.IAccessibilityProvider {
constructor( @IWorkspaceContextService private contextService: IWorkspaceContextService) {
// noop
}
public getAriaLabel(tree: tree.ITree, element: any): string {
if (element instanceof model.Thread) {
return nls.localize('threadAriaLabel', "Thread {0}, callstack, debug", (<model.Thread>element).name);
}
if (element instanceof model.StackFrame) {
return nls.localize('stackFrameAriaLabel', "Stack Frame {0} line {1} {2}, callstack, debug", (<model.StackFrame>element).name, (<model.StackFrame>element).lineNumber, getSourceName((<model.StackFrame>element).source, this.contextService));
}
return null;
}
}
// variables
export class VariablesActionProvider implements renderer.IActionProvider {
constructor(private instantiationService: IInstantiationService) {
// noop
}
public hasActions(tree: tree.ITree, element: any): boolean {
return false;
}
public getActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
return TPromise.as([]);
}
public hasSecondaryActions(tree: tree.ITree, element: any): boolean {
return element instanceof model.Variable;
}
public getSecondaryActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
let actions: actions.Action[] = [];
const variable = <model.Variable>element;
if (variable.reference === 0) {
actions.push(this.instantiationService.createInstance(debugactions.SetValueAction, debugactions.SetValueAction.ID, debugactions.SetValueAction.LABEL, variable));
actions.push(this.instantiationService.createInstance(CopyValueAction, CopyValueAction.ID, CopyValueAction.LABEL, variable));
actions.push(new actionbar.Separator());
}
actions.push(this.instantiationService.createInstance(debugactions.AddToWatchExpressionsAction, debugactions.AddToWatchExpressionsAction.ID, debugactions.AddToWatchExpressionsAction.LABEL, variable));
return TPromise.as(actions);
}
public getActionItem(tree: tree.ITree, element: any, action: actions.IAction): actionbar.IActionItem {
return null;
}
}
export class VariablesDataSource implements tree.IDataSource {
public getId(tree: tree.ITree, element: any): string {
return element.getId();
}
public hasChildren(tree: tree.ITree, element: any): boolean {
if (element instanceof viewmodel.ViewModel || element instanceof model.Scope) {
return true;
}
let variable = <model.Variable>element;
return variable.reference !== 0 && !strings.equalsIgnoreCase(variable.value, 'null');
}
public getChildren(tree: tree.ITree, element: any): TPromise<any> {
if (element instanceof viewmodel.ViewModel) {
let focusedStackFrame = (<viewmodel.ViewModel>element).getFocusedStackFrame();
return focusedStackFrame ? focusedStackFrame.getScopes() : TPromise.as([]);
}
let scope = <model.Scope>element;
return scope.getChildren();
}
public getParent(tree: tree.ITree, element: any): TPromise<any> {
return TPromise.as(null);
}
}
interface IScopeTemplateData {
name: HTMLElement;
}
export interface IVariableTemplateData {
expression: HTMLElement;
name: HTMLElement;
value: HTMLElement;
}
export class VariablesRenderer implements tree.IRenderer {
private static SCOPE_TEMPLATE_ID = 'scope';
private static VARIABLE_TEMPLATE_ID = 'variable';
constructor(
@debug.IDebugService private debugService: debug.IDebugService,
@IContextViewService private contextViewService: IContextViewService
) {
// noop
}
public getHeight(tree: tree.ITree, element: any): number {
return 22;
}
public getTemplateId(tree: tree.ITree, element: any): string {
if (element instanceof model.Scope) {
return VariablesRenderer.SCOPE_TEMPLATE_ID;
}
if (element instanceof model.Variable) {
return VariablesRenderer.VARIABLE_TEMPLATE_ID;
}
return null;
}
public renderTemplate(tree: tree.ITree, templateId: string, container: HTMLElement): any {
if (templateId === VariablesRenderer.SCOPE_TEMPLATE_ID) {
let data: IScopeTemplateData = Object.create(null);
data.name = dom.append(container, $('.scope'));
return data;
}
let data: IVariableTemplateData = Object.create(null);
data.expression = dom.append(container, $('.expression'));
data.name = dom.append(data.expression, $('span.name'));
data.value = dom.append(data.expression, $('span.value'));
return data;
}
public renderElement(tree: tree.ITree, element: any, templateId: string, templateData: any): void {
if (templateId === VariablesRenderer.SCOPE_TEMPLATE_ID) {
this.renderScope(element, templateData);
} else {
const variable = <model.Variable>element;
if (variable === this.debugService.getViewModel().getSelectedExpression() || variable.errorMessage) {
renderRenameBox(this.debugService, this.contextViewService, tree, variable, (<IVariableTemplateData>templateData).expression, {
initialValue: variable.value,
ariaLabel: nls.localize('variableValueAriaLabel', "Type new variable value"),
validationOptions: {
validation: (value: string) => variable.errorMessage ? ({ content: variable.errorMessage }) : null
}
});
} else {
renderVariable(tree, variable, templateData, true);
}
}
}
private renderScope(scope: model.Scope, data: IScopeTemplateData): void {
data.name.textContent = scope.name;
}
public disposeTemplate(tree: tree.ITree, templateId: string, templateData: any): void {
// noop
}
}
export class VariablesAccessibilityProvider implements tree.IAccessibilityProvider {
public getAriaLabel(tree: tree.ITree, element: any): string {
if (element instanceof model.Scope) {
return nls.localize('variableScopeAriaLabel', "Scope {0}, variables, debug", (<model.Scope>element).name);
}
if (element instanceof model.Variable) {
return nls.localize('variableAriaLabel', "{0} value {1}, variables, debug", (<model.Variable>element).name, (<model.Variable>element).value);
}
return null;
}
}
export class VariablesController extends BaseDebugController {
constructor(debugService: debug.IDebugService, contextMenuService: IContextMenuService, actionProvider: renderer.IActionProvider) {
super(debugService, contextMenuService, actionProvider);
this.downKeyBindingDispatcher.set(KeyCode.Enter, this.setSelectedExpression.bind(this));
}
protected onLeftClick(tree: tree.ITree, element: any, event: IMouseEvent): boolean {
// double click on primitive value: open input box to be able to set the value
if (element instanceof model.Variable && event.detail === 2) {
const expression = <debug.IExpression>element;
if (expression.reference === 0) {
this.debugService.getViewModel().setSelectedExpression(expression);
}
return true;
}
return super.onLeftClick(tree, element, event);
}
protected setSelectedExpression(tree: tree.ITree, event: KeyboardEvent): boolean {
const element = tree.getFocus();
if (element instanceof model.Variable && element.reference === 0) {
this.debugService.getViewModel().setSelectedExpression(element);
return true;
}
return false;
}
}
// watch expressions
export class WatchExpressionsActionProvider implements renderer.IActionProvider {
private instantiationService: IInstantiationService;
constructor(instantiationService: IInstantiationService) {
this.instantiationService = instantiationService;
}
public hasActions(tree: tree.ITree, element: any): boolean {
return element instanceof model.Expression && !!element.name;
}
public hasSecondaryActions(tree: tree.ITree, element: any): boolean {
return true;
}
public getActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
return TPromise.as(this.getExpressionActions());
}
public getExpressionActions(): actions.IAction[] {
return [this.instantiationService.createInstance(debugactions.RemoveWatchExpressionAction, debugactions.RemoveWatchExpressionAction.ID, debugactions.RemoveWatchExpressionAction.LABEL)];
}
public getSecondaryActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
const actions: actions.Action[] = [];
if (element instanceof model.Expression) {
const expression = <model.Expression>element;
actions.push(this.instantiationService.createInstance(debugactions.AddWatchExpressionAction, debugactions.AddWatchExpressionAction.ID, debugactions.AddWatchExpressionAction.LABEL));
actions.push(this.instantiationService.createInstance(debugactions.RenameWatchExpressionAction, debugactions.RenameWatchExpressionAction.ID, debugactions.RenameWatchExpressionAction.LABEL, expression));
if (expression.reference === 0) {
actions.push(this.instantiationService.createInstance(CopyValueAction, CopyValueAction.ID, CopyValueAction.LABEL, expression.value));
}
actions.push(new actionbar.Separator());
actions.push(this.instantiationService.createInstance(debugactions.RemoveWatchExpressionAction, debugactions.RemoveWatchExpressionAction.ID, debugactions.RemoveWatchExpressionAction.LABEL));
actions.push(this.instantiationService.createInstance(debugactions.RemoveAllWatchExpressionsAction, debugactions.RemoveAllWatchExpressionsAction.ID, debugactions.RemoveAllWatchExpressionsAction.LABEL));
} else {
actions.push(this.instantiationService.createInstance(debugactions.AddWatchExpressionAction, debugactions.AddWatchExpressionAction.ID, debugactions.AddWatchExpressionAction.LABEL));
if (element instanceof model.Variable) {
const variable = <model.Variable>element;
if (variable.reference === 0) {
actions.push(this.instantiationService.createInstance(CopyValueAction, CopyValueAction.ID, CopyValueAction.LABEL, variable.value));
}
actions.push(new actionbar.Separator());
}
actions.push(this.instantiationService.createInstance(debugactions.RemoveAllWatchExpressionsAction, debugactions.RemoveAllWatchExpressionsAction.ID, debugactions.RemoveAllWatchExpressionsAction.LABEL));
}
return TPromise.as(actions);
}
public getActionItem(tree: tree.ITree, element: any, action: actions.IAction): actionbar.IActionItem {
return null;
}
}
export class WatchExpressionsDataSource implements tree.IDataSource {
public getId(tree: tree.ITree, element: any): string {
return element.getId();
}
public hasChildren(tree: tree.ITree, element: any): boolean {
if (element instanceof model.Model) {
return true;
}
const watchExpression = <model.Expression>element;
return watchExpression.reference !== 0 && !strings.equalsIgnoreCase(watchExpression.value, 'null');
}
public getChildren(tree: tree.ITree, element: any): TPromise<any> {
if (element instanceof model.Model) {
return TPromise.as((<model.Model>element).getWatchExpressions());
}
let expression = <model.Expression>element;
return expression.getChildren();
}
public getParent(tree: tree.ITree, element: any): TPromise<any> {
return TPromise.as(null);
}
}
interface IWatchExpressionTemplateData extends IVariableTemplateData {
actionBar: actionbar.ActionBar;
}
export class WatchExpressionsRenderer implements tree.IRenderer {
private static WATCH_EXPRESSION_TEMPLATE_ID = 'watchExpression';
private static VARIABLE_TEMPLATE_ID = 'variables';
private toDispose: lifecycle.IDisposable[];
private actionProvider: WatchExpressionsActionProvider;
constructor(
actionProvider: renderer.IActionProvider,
private actionRunner: actions.IActionRunner,
@debug.IDebugService private debugService: debug.IDebugService,
@IContextViewService private contextViewService: IContextViewService
) {
this.toDispose = [];
this.actionProvider = <WatchExpressionsActionProvider>actionProvider;
}
public getHeight(tree: tree.ITree, element: any): number {
return 22;
}
public getTemplateId(tree: tree.ITree, element: any): string {
if (element instanceof model.Expression) {
return WatchExpressionsRenderer.WATCH_EXPRESSION_TEMPLATE_ID;
}
return WatchExpressionsRenderer.VARIABLE_TEMPLATE_ID;
}
public renderTemplate(tree: tree.ITree, templateId: string, container: HTMLElement): any {
let data: IWatchExpressionTemplateData = Object.create(null);
if (templateId === WatchExpressionsRenderer.WATCH_EXPRESSION_TEMPLATE_ID) {
data.actionBar = new actionbar.ActionBar(container, { actionRunner: this.actionRunner });
data.actionBar.push(this.actionProvider.getExpressionActions(), { icon: true, label: false });
}
data.expression = dom.append(container, $('.expression'));
data.name = dom.append(data.expression, $('span.name'));
data.value = dom.append(data.expression, $('span.value'));
return data;
}
public renderElement(tree: tree.ITree, element: any, templateId: string, templateData: any): void {
if (templateId === WatchExpressionsRenderer.WATCH_EXPRESSION_TEMPLATE_ID) {
this.renderWatchExpression(tree, element, templateData);
} else {
renderVariable(tree, element, templateData, true);
}
}
private renderWatchExpression(tree: tree.ITree, watchExpression: debug.IExpression, data: IWatchExpressionTemplateData): void {
let selectedExpression = this.debugService.getViewModel().getSelectedExpression();
if ((selectedExpression instanceof model.Expression && selectedExpression.getId() === watchExpression.getId()) || (watchExpression instanceof model.Expression && !watchExpression.name)) {
renderRenameBox(this.debugService, this.contextViewService, tree, watchExpression, data.expression, {
initialValue: watchExpression.name,
placeholder: nls.localize('watchExpressionPlaceholder', "Expression to watch"),
ariaLabel: nls.localize('watchExpressionInputAriaLabel', "Type watch expression")
});
}
data.actionBar.context = watchExpression;
data.name.textContent = watchExpression.name;
if (watchExpression.value) {
data.name.textContent += ':';
renderExpressionValue(watchExpression, data.value, true, MAX_VALUE_RENDER_LENGTH_IN_VIEWLET);
data.name.title = watchExpression.type ? watchExpression.type : watchExpression.value;
}
}
public disposeTemplate(tree: tree.ITree, templateId: string, templateData: any): void {
if (templateId === WatchExpressionsRenderer.WATCH_EXPRESSION_TEMPLATE_ID) {
(<IWatchExpressionTemplateData>templateData).actionBar.dispose();
}
}
public dispose(): void {
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
export class WatchExpressionsAccessibilityProvider implements tree.IAccessibilityProvider {
public getAriaLabel(tree: tree.ITree, element: any): string {
if (element instanceof model.Expression) {
return nls.localize('watchExpressionAriaLabel', "{0} value {1}, watch, debug", (<model.Expression>element).name, (<model.Expression>element).value);
}
if (element instanceof model.Variable) {
return nls.localize('watchVariableAriaLabel', "{0} value {1}, watch, debug", (<model.Variable>element).name, (<model.Variable>element).value);
}
return null;
}
}
export class WatchExpressionsController extends BaseDebugController {
constructor(debugService: debug.IDebugService, contextMenuService: IContextMenuService, actionProvider: renderer.IActionProvider) {
super(debugService, contextMenuService, actionProvider);
if (isMacintosh) {
this.downKeyBindingDispatcher.set(KeyCode.Enter, this.onRename.bind(this));
} else {
this.downKeyBindingDispatcher.set(KeyCode.F2, this.onRename.bind(this));
}
}
protected onLeftClick(tree: tree.ITree, element: any, event: IMouseEvent): boolean {
// double click on primitive value: open input box to be able to select and copy value.
if (element instanceof model.Expression && event.detail === 2) {
const expression = <debug.IExpression>element;
if (expression.reference === 0) {
this.debugService.getViewModel().setSelectedExpression(expression);
}
return true;
}
return super.onLeftClick(tree, element, event);
}
protected onRename(tree: tree.ITree, event: KeyboardEvent): boolean {
const element = tree.getFocus();
if (element instanceof model.Expression) {
const watchExpression = <model.Expression>element;
if (watchExpression.reference === 0) {
this.debugService.getViewModel().setSelectedExpression(watchExpression);
}
return true;
}
return false;
}
protected onDelete(tree: tree.ITree, event: IKeyboardEvent): boolean {
const element = tree.getFocus();
if (element instanceof model.Expression) {
const we = <model.Expression>element;
this.debugService.removeWatchExpressions(we.getId());
return true;
}
return false;
}
}
// breakpoints
export class BreakpointsActionProvider implements renderer.IActionProvider {
constructor(private instantiationService: IInstantiationService) {
// noop
}
public hasActions(tree: tree.ITree, element: any): boolean {
return element instanceof model.Breakpoint;
}
public hasSecondaryActions(tree: tree.ITree, element: any): boolean {
return element instanceof model.Breakpoint || element instanceof model.ExceptionBreakpoint || element instanceof model.FunctionBreakpoint;
}
public getActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
if (element instanceof model.Breakpoint) {
return TPromise.as(this.getBreakpointActions());
}
return TPromise.as([]);
}
public getBreakpointActions(): actions.IAction[] {
return [this.instantiationService.createInstance(debugactions.RemoveBreakpointAction, debugactions.RemoveBreakpointAction.ID, debugactions.RemoveBreakpointAction.LABEL)];
}
public getSecondaryActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
const actions: actions.Action[] = [this.instantiationService.createInstance(debugactions.ToggleEnablementAction, debugactions.ToggleEnablementAction.ID, debugactions.ToggleEnablementAction.LABEL)];
actions.push(new actionbar.Separator());
if (element instanceof model.Breakpoint || element instanceof model.FunctionBreakpoint) {
actions.push(this.instantiationService.createInstance(debugactions.RemoveBreakpointAction, debugactions.RemoveBreakpointAction.ID, debugactions.RemoveBreakpointAction.LABEL));
}
actions.push(this.instantiationService.createInstance(debugactions.RemoveAllBreakpointsAction, debugactions.RemoveAllBreakpointsAction.ID, debugactions.RemoveAllBreakpointsAction.LABEL));
actions.push(new actionbar.Separator());
actions.push(this.instantiationService.createInstance(debugactions.ToggleBreakpointsActivatedAction, debugactions.ToggleBreakpointsActivatedAction.ID, debugactions.ToggleBreakpointsActivatedAction.ACTIVATE_LABEL));
actions.push(new actionbar.Separator());
actions.push(this.instantiationService.createInstance(debugactions.EnableAllBreakpointsAction, debugactions.EnableAllBreakpointsAction.ID, debugactions.EnableAllBreakpointsAction.LABEL));
actions.push(this.instantiationService.createInstance(debugactions.DisableAllBreakpointsAction, debugactions.DisableAllBreakpointsAction.ID, debugactions.DisableAllBreakpointsAction.LABEL));
actions.push(new actionbar.Separator());
actions.push(this.instantiationService.createInstance(debugactions.AddFunctionBreakpointAction, debugactions.AddFunctionBreakpointAction.ID, debugactions.AddFunctionBreakpointAction.LABEL));
if (element instanceof model.FunctionBreakpoint) {
actions.push(this.instantiationService.createInstance(debugactions.RenameFunctionBreakpointAction, debugactions.RenameFunctionBreakpointAction.ID, debugactions.RenameFunctionBreakpointAction.LABEL));
}
actions.push(new actionbar.Separator());
actions.push(this.instantiationService.createInstance(debugactions.ReapplyBreakpointsAction, debugactions.ReapplyBreakpointsAction.ID, debugactions.ReapplyBreakpointsAction.LABEL));
return TPromise.as(actions);
}
public getActionItem(tree: tree.ITree, element: any, action: actions.IAction): actionbar.IActionItem {
return null;
}
}
export class BreakpointsDataSource implements tree.IDataSource {
public getId(tree: tree.ITree, element: any): string {
return element.getId();
}
public hasChildren(tree: tree.ITree, element: any): boolean {
return element instanceof model.Model;
}
public getChildren(tree: tree.ITree, element: any): TPromise<any> {
const model = <model.Model>element;
const exBreakpoints = <debug.IEnablement[]>model.getExceptionBreakpoints();
return TPromise.as(exBreakpoints.concat(model.getFunctionBreakpoints()).concat(model.getBreakpoints()));
}
public getParent(tree: tree.ITree, element: any): TPromise<any> {
return TPromise.as(null);
}
}
interface IExceptionBreakpointTemplateData {
breakpoint: HTMLElement;
name: HTMLElement;
checkbox: HTMLInputElement;
toDisposeBeforeRender: lifecycle.IDisposable[];
}
interface IBreakpointTemplateData extends IExceptionBreakpointTemplateData {
actionBar: actionbar.ActionBar;
lineNumber: HTMLElement;
filePath: HTMLElement;
}
interface IFunctionBreakpointTemplateData extends IExceptionBreakpointTemplateData {
actionBar: actionbar.ActionBar;
}
export class BreakpointsRenderer implements tree.IRenderer {
private static EXCEPTION_BREAKPOINT_TEMPLATE_ID = 'exceptionBreakpoint';
private static FUNCTION_BREAKPOINT_TEMPLATE_ID = 'functionBreakpoint';
private static BREAKPOINT_TEMPLATE_ID = 'breakpoint';
constructor(
private actionProvider: BreakpointsActionProvider,
private actionRunner: actions.IActionRunner,
@IWorkspaceContextService private contextService: IWorkspaceContextService,
@debug.IDebugService private debugService: debug.IDebugService,
@IContextViewService private contextViewService: IContextViewService
) {
// noop
}
public getHeight(tree: tree.ITree, element: any): number {
return 22;
}
public getTemplateId(tree: tree.ITree, element: any): string {
if (element instanceof model.Breakpoint) {
return BreakpointsRenderer.BREAKPOINT_TEMPLATE_ID;
}
if (element instanceof model.FunctionBreakpoint) {
return BreakpointsRenderer.FUNCTION_BREAKPOINT_TEMPLATE_ID;
}
if (element instanceof model.ExceptionBreakpoint) {
return BreakpointsRenderer.EXCEPTION_BREAKPOINT_TEMPLATE_ID;
}
return null;
}
public renderTemplate(tree: tree.ITree, templateId: string, container: HTMLElement): any {
const data: IBreakpointTemplateData = Object.create(null);
if (templateId === BreakpointsRenderer.BREAKPOINT_TEMPLATE_ID || templateId === BreakpointsRenderer.FUNCTION_BREAKPOINT_TEMPLATE_ID) {
data.actionBar = new actionbar.ActionBar(container, { actionRunner: this.actionRunner });
data.actionBar.push(this.actionProvider.getBreakpointActions(), { icon: true, label: false });
}
data.breakpoint = dom.append(container, $('.breakpoint'));
data.toDisposeBeforeRender = [];
data.checkbox = <HTMLInputElement>$('input');
data.checkbox.type = 'checkbox';
dom.append(data.breakpoint, data.checkbox);
data.name = dom.append(data.breakpoint, $('span.name'));
if (templateId === BreakpointsRenderer.BREAKPOINT_TEMPLATE_ID) {
data.lineNumber = dom.append(data.breakpoint, $('span.line-number'));
data.filePath = dom.append(data.breakpoint, $('span.file-path'));
}
return data;
}
public renderElement(tree: tree.ITree, element: any, templateId: string, templateData: any): void {
templateData.toDisposeBeforeRender = lifecycle.dispose(templateData.toDisposeBeforeRender);
templateData.toDisposeBeforeRender.push(dom.addStandardDisposableListener(templateData.checkbox, 'change', (e) => {
this.debugService.enableOrDisableBreakpoints(!element.enabled, element);
}));
if (templateId === BreakpointsRenderer.EXCEPTION_BREAKPOINT_TEMPLATE_ID) {
this.renderExceptionBreakpoint(element, templateData);
} else if (templateId === BreakpointsRenderer.FUNCTION_BREAKPOINT_TEMPLATE_ID) {
this.renderFunctionBreakpoint(tree, element, templateData);
} else {
this.renderBreakpoint(tree, element, templateData);
}
}
private renderExceptionBreakpoint(exceptionBreakpoint: debug.IExceptionBreakpoint, data: IExceptionBreakpointTemplateData): void {
data.name.textContent = exceptionBreakpoint.label || `${exceptionBreakpoint.filter} exceptions`;;
data.breakpoint.title = data.name.textContent;
data.checkbox.checked = exceptionBreakpoint.enabled;
}
private renderFunctionBreakpoint(tree: tree.ITree, functionBreakpoint: debug.IFunctionBreakpoint, data: IFunctionBreakpointTemplateData): void {
const selected = this.debugService.getViewModel().getSelectedFunctionBreakpoint();
if (!functionBreakpoint.name || (selected && selected.getId() === functionBreakpoint.getId())) {
renderRenameBox(this.debugService, this.contextViewService, tree, functionBreakpoint, data.breakpoint, {
initialValue: functionBreakpoint.name,
placeholder: nls.localize('functionBreakpointPlaceholder', "Function to break on"),
ariaLabel: nls.localize('functionBreakPointInputAriaLabel', "Type function breakpoint")
});
} else {
data.name.textContent = functionBreakpoint.name;
data.checkbox.checked = functionBreakpoint.enabled;
data.breakpoint.title = functionBreakpoint.name;
// Mark function breakpoints as disabled if deactivated or if debug type does not support them #9099
const session = this.debugService.getViewModel().activeSession;
if ((session && !session.configuration.capabilities.supportsFunctionBreakpoints) || !this.debugService.getModel().areBreakpointsActivated()) {
tree.addTraits('disabled', [functionBreakpoint]);
if (session && !session.configuration.capabilities.supportsFunctionBreakpoints) {
data.breakpoint.title = nls.localize('functionBreakpointsNotSupported', "Function breakpoints are not supported by this debug type");
}
} else {
tree.removeTraits('disabled', [functionBreakpoint]);
}
}
data.actionBar.context = functionBreakpoint;
}
private renderBreakpoint(tree: tree.ITree, breakpoint: debug.IBreakpoint, data: IBreakpointTemplateData): void {
this.debugService.getModel().areBreakpointsActivated() ? tree.removeTraits('disabled', [breakpoint]) : tree.addTraits('disabled', [breakpoint]);
data.name.textContent = labels.getPathLabel(paths.basename(breakpoint.source.uri.fsPath), this.contextService);
data.lineNumber.textContent = breakpoint.desiredLineNumber !== breakpoint.lineNumber ? breakpoint.desiredLineNumber + ' \u2192 ' + breakpoint.lineNumber : '' + breakpoint.lineNumber;
data.filePath.textContent = labels.getPathLabel(paths.dirname(breakpoint.source.uri.fsPath), this.contextService);
data.checkbox.checked = breakpoint.enabled;
data.actionBar.context = breakpoint;
const debugActive = this.debugService.state === debug.State.Running || this.debugService.state === debug.State.Stopped || this.debugService.state === debug.State.Initializing;
if (debugActive && !breakpoint.verified) {
tree.addTraits('disabled', [breakpoint]);
if (breakpoint.message) {
data.breakpoint.title = breakpoint.message;
}
} else if (breakpoint.condition || breakpoint.hitCondition) {
data.breakpoint.title = breakpoint.condition ? breakpoint.condition : breakpoint.hitCondition;
}
}
public disposeTemplate(tree: tree.ITree, templateId: string, templateData: any): void {
if (templateId === BreakpointsRenderer.BREAKPOINT_TEMPLATE_ID || templateId === BreakpointsRenderer.FUNCTION_BREAKPOINT_TEMPLATE_ID) {
templateData.actionBar.dispose();
}
}
}
export class BreakpointsAccessibilityProvider implements tree.IAccessibilityProvider {
constructor( @IWorkspaceContextService private contextService: IWorkspaceContextService) {
// noop
}
public getAriaLabel(tree: tree.ITree, element: any): string {
if (element instanceof model.Breakpoint) {
return nls.localize('breakpointAriaLabel', "Breakpoint line {0} {1}, breakpoints, debug", (<model.Breakpoint>element).lineNumber, getSourceName((<model.Breakpoint>element).source, this.contextService));
}
if (element instanceof model.FunctionBreakpoint) {
return nls.localize('functionBreakpointAriaLabel', "Function breakpoint {0}, breakpoints, debug", (<model.FunctionBreakpoint>element).name);
}
if (element instanceof model.ExceptionBreakpoint) {
return nls.localize('exceptionBreakpointAriaLabel', "Exception breakpoint {0}, breakpoints, debug", (<model.ExceptionBreakpoint>element).filter);
}
return null;
}
}
export class BreakpointsController extends BaseDebugController {
constructor(debugService: debug.IDebugService, contextMenuService: IContextMenuService, actionProvider: renderer.IActionProvider) {
super(debugService, contextMenuService, actionProvider);
if (isMacintosh) {
this.downKeyBindingDispatcher.set(KeyCode.Enter, this.onRename.bind(this));
} else {
this.downKeyBindingDispatcher.set(KeyCode.F2, this.onRename.bind(this));
}
}
protected onLeftClick(tree: tree.ITree, element: any, event: IMouseEvent): boolean {
if (element instanceof model.FunctionBreakpoint && event.detail === 2) {
this.debugService.getViewModel().setSelectedFunctionBreakpoint(element);
return true;
}
if (element instanceof model.Breakpoint) {
this.openBreakpointSource(element, event, true);
}
return super.onLeftClick(tree, element, event);
}
protected onRename(tree: tree.ITree, event: IKeyboardEvent): boolean {
const element = tree.getFocus();
if (element instanceof model.FunctionBreakpoint && element.name) {
this.debugService.getViewModel().setSelectedFunctionBreakpoint(element);
return true;
}
if (element instanceof model.Breakpoint) {
this.openBreakpointSource(element, event, false);
}
return super.onEnter(tree, event);
}
protected onSpace(tree: tree.ITree, event: IKeyboardEvent): boolean {
super.onSpace(tree, event);
const element = <debug.IEnablement>tree.getFocus();
this.debugService.enableOrDisableBreakpoints(!element.enabled, element).done(null, errors.onUnexpectedError);
return true;
}
protected onDelete(tree: tree.ITree, event: IKeyboardEvent): boolean {
const element = tree.getFocus();
if (element instanceof model.Breakpoint) {
this.debugService.removeBreakpoints((<model.Breakpoint>element).getId()).done(null, errors.onUnexpectedError);
return true;
} else if (element instanceof model.FunctionBreakpoint) {
const fbp = <model.FunctionBreakpoint>element;
this.debugService.removeFunctionBreakpoints(fbp.getId()).done(null, errors.onUnexpectedError);
return true;
}
return false;
}
private openBreakpointSource(breakpoint: debug.IBreakpoint, event: IKeyboardEvent | IMouseEvent, preserveFocus: boolean): void {
if (!breakpoint.source.inMemory) {
const sideBySide = (event && (event.ctrlKey || event.metaKey));
this.debugService.openOrRevealSource(breakpoint.source, breakpoint.lineNumber, preserveFocus, sideBySide).done(null, errors.onUnexpectedError);
}
}
}
| src/vs/workbench/parts/debug/electron-browser/debugViewer.ts | 1 | https://github.com/microsoft/vscode/commit/bb194502143f100abe468b1328a54e33c62fd514 | [
0.9991488456726074,
0.021159959957003593,
0.00016080534260254353,
0.00017457630019634962,
0.13637033104896545
] |
{
"id": 2,
"code_window": [
"\t\t}\n",
"\n",
"\t\tconst threads = (<model.Model>element).getThreads(session.getId());\n",
"\t\treturn TPromise.as(Object.keys(threads).map(ref => threads[ref]));\n",
"\t}\n",
"\n",
"\tprivate getThreadChildren(thread: debug.IThread): TPromise<any> {\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst session = <debug.IRawDebugSession>element;\n",
"\t\tconst threads = this.debugService.getModel().getThreads(session.getId());\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugViewer.ts",
"type": "replace",
"edit_start_line_idx": 370
} | /*---------------------------------------------------------------------------------------------
* 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 { MarkedString, CompletionItemKind, CompletionItem } from 'vscode-languageserver';
import Strings = require('../utils/strings');
import { JSONWorkerContribution, JSONPath, CompletionsCollector } from 'vscode-json-languageservice';
import * as nls from 'vscode-nls';
const localize = nls.loadMessageBundle();
let globProperties: CompletionItem[] = [
{ kind: CompletionItemKind.Value, label: localize('assocLabelFile', "Files with Extension"), insertText: '"*.{{extension}}": "{{language}}"', documentation: localize('assocDescriptionFile', "Map all files matching the glob pattern in their filename to the language with the given identifier.") },
{ kind: CompletionItemKind.Value, label: localize('assocLabelPath', "Files with Path"), insertText: '"/{{path to file}}/*.{{extension}}": "{{language}}"', documentation: localize('assocDescriptionPath', "Map all files matching the absolute path glob pattern in their path to the language with the given identifier.") }
];
export class FileAssociationContribution implements JSONWorkerContribution {
private languageIds: string[];
constructor() {
}
public setLanguageIds(ids: string[]): void {
this.languageIds = ids;
}
private isSettingsFile(resource: string): boolean {
return Strings.endsWith(resource, '/settings.json');
}
public collectDefaultCompletions(resource: string, result: CompletionsCollector): Thenable<any> {
return null;
}
public collectPropertyCompletions(resource: string, location: JSONPath, currentWord: string, addValue: boolean, isLast: boolean, result: CompletionsCollector): Thenable<any> {
if (this.isSettingsFile(resource) && location.length === 1 && location[0] === 'files.associations') {
globProperties.forEach(e => {
e.filterText = e.insertText;
result.add(e);
});
}
return null;
}
public collectValueCompletions(resource: string, location: JSONPath, currentKey: string, result: CompletionsCollector): Thenable<any> {
if (this.isSettingsFile(resource) && location.length === 1 && location[0] === 'files.associations') {
this.languageIds.forEach(l => {
result.add({
kind: CompletionItemKind.Value,
label: l,
insertText: JSON.stringify('{{' + l + '}}'),
filterText: JSON.stringify(l)
});
});
}
return null;
}
public getInfoContribution(resource: string, location: JSONPath): Thenable<MarkedString[]> {
return null;
}
} | extensions/json/server/src/jsoncontributions/fileAssociationContribution.ts | 0 | https://github.com/microsoft/vscode/commit/bb194502143f100abe468b1328a54e33c62fd514 | [
0.00017744320211932063,
0.0001740604784572497,
0.00017086252046283334,
0.00017342669889330864,
0.0000022896763312019175
] |
{
"id": 2,
"code_window": [
"\t\t}\n",
"\n",
"\t\tconst threads = (<model.Model>element).getThreads(session.getId());\n",
"\t\treturn TPromise.as(Object.keys(threads).map(ref => threads[ref]));\n",
"\t}\n",
"\n",
"\tprivate getThreadChildren(thread: debug.IThread): TPromise<any> {\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst session = <debug.IRawDebugSession>element;\n",
"\t\tconst threads = this.debugService.getModel().getThreads(session.getId());\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugViewer.ts",
"type": "replace",
"edit_start_line_idx": 370
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import fs = require('fs');
import ts = require('typescript');
import path = require('path');
var util = require('gulp-util');
function log(message: any, ...rest: any[]): void {
util.log(util.colors.cyan('[monaco.d.ts]'), message, ...rest);
}
const SRC = path.join(__dirname, '../../src');
const OUT_ROOT = path.join(__dirname, '../../');
const RECIPE_PATH = path.join(__dirname, './monaco.d.ts.recipe');
const DECLARATION_PATH = path.join(__dirname, '../../src/vs/monaco.d.ts');
var CURRENT_PROCESSING_RULE = '';
function logErr(message: any, ...rest: any[]): void {
util.log(util.colors.red('[monaco.d.ts]'), 'WHILE HANDLING RULE: ', CURRENT_PROCESSING_RULE);
util.log(util.colors.red('[monaco.d.ts]'), message, ...rest);
}
function moduleIdToPath(out:string, moduleId:string): string {
if (/\.d\.ts/.test(moduleId)) {
return path.join(SRC, moduleId);
}
return path.join(OUT_ROOT, out, moduleId) + '.d.ts';
}
let SOURCE_FILE_MAP: {[moduleId:string]:ts.SourceFile;} = {};
function getSourceFile(out:string, moduleId:string): ts.SourceFile {
if (!SOURCE_FILE_MAP[moduleId]) {
let filePath = moduleIdToPath(out, moduleId);
let fileContents: string;
try {
fileContents = fs.readFileSync(filePath).toString();
} catch (err) {
logErr('CANNOT FIND FILE ' + filePath);
return null;
}
let sourceFile = ts.createSourceFile(filePath, fileContents, ts.ScriptTarget.ES5);
SOURCE_FILE_MAP[moduleId] = sourceFile;
}
return SOURCE_FILE_MAP[moduleId];
}
type TSTopLevelDeclaration = ts.InterfaceDeclaration | ts.EnumDeclaration | ts.ClassDeclaration | ts.TypeAliasDeclaration | ts.FunctionDeclaration | ts.ModuleDeclaration;
type TSTopLevelDeclare = TSTopLevelDeclaration | ts.VariableStatement;
function isDeclaration(a:TSTopLevelDeclare): a is TSTopLevelDeclaration {
return (
a.kind === ts.SyntaxKind.InterfaceDeclaration
|| a.kind === ts.SyntaxKind.EnumDeclaration
|| a.kind === ts.SyntaxKind.ClassDeclaration
|| a.kind === ts.SyntaxKind.TypeAliasDeclaration
|| a.kind === ts.SyntaxKind.FunctionDeclaration
|| a.kind === ts.SyntaxKind.ModuleDeclaration
);
}
function visitTopLevelDeclarations(sourceFile:ts.SourceFile, visitor:(node:TSTopLevelDeclare)=>boolean): void {
let stop = false;
let visit = (node: ts.Node): void => {
if (stop) {
return;
}
switch (node.kind) {
case ts.SyntaxKind.InterfaceDeclaration:
case ts.SyntaxKind.EnumDeclaration:
case ts.SyntaxKind.ClassDeclaration:
case ts.SyntaxKind.VariableStatement:
case ts.SyntaxKind.TypeAliasDeclaration:
case ts.SyntaxKind.FunctionDeclaration:
case ts.SyntaxKind.ModuleDeclaration:
stop = visitor(<TSTopLevelDeclare>node);
}
// if (node.kind !== ts.SyntaxKind.SourceFile) {
// if (getNodeText(sourceFile, node).indexOf('SymbolKind') >= 0) {
// console.log('FOUND TEXT IN NODE: ' + ts.SyntaxKind[node.kind]);
// console.log(getNodeText(sourceFile, node));
// }
// }
if (stop) {
return;
}
ts.forEachChild(node, visit);
};
visit(sourceFile);
}
function getAllTopLevelDeclarations(sourceFile:ts.SourceFile): TSTopLevelDeclare[] {
let all:TSTopLevelDeclare[] = [];
visitTopLevelDeclarations(sourceFile, (node) => {
if (node.kind === ts.SyntaxKind.InterfaceDeclaration || node.kind === ts.SyntaxKind.ClassDeclaration || node.kind === ts.SyntaxKind.ModuleDeclaration) {
let interfaceDeclaration = <ts.InterfaceDeclaration>node;
let triviaStart = interfaceDeclaration.pos;
let triviaEnd = interfaceDeclaration.name.pos;
let triviaText = getNodeText(sourceFile, { pos: triviaStart, end: triviaEnd });
// // let nodeText = getNodeText(sourceFile, node);
// if (getNodeText(sourceFile, node).indexOf('SymbolKind') >= 0) {
// console.log('TRIVIA: ', triviaText);
// }
if (triviaText.indexOf('@internal') === -1) {
all.push(node);
}
} else {
let nodeText = getNodeText(sourceFile, node);
if (nodeText.indexOf('@internal') === -1) {
all.push(node);
}
}
return false /*continue*/;
});
return all;
}
function getTopLevelDeclaration(sourceFile:ts.SourceFile, typeName:string): TSTopLevelDeclare {
let result:TSTopLevelDeclare = null;
visitTopLevelDeclarations(sourceFile, (node) => {
if (isDeclaration(node)) {
if (node.name.text === typeName) {
result = node;
return true /*stop*/;
}
return false /*continue*/;
}
// node is ts.VariableStatement
if (getNodeText(sourceFile, node).indexOf(typeName) >= 0) {
result = node;
return true /*stop*/;
}
return false /*continue*/;
});
return result;
}
function getNodeText(sourceFile:ts.SourceFile, node:{pos:number; end:number;}): string {
return sourceFile.getFullText().substring(node.pos, node.end);
}
function getMassagedTopLevelDeclarationText(sourceFile:ts.SourceFile, declaration: TSTopLevelDeclare): string {
let result = getNodeText(sourceFile, declaration);
// if (result.indexOf('MonacoWorker') >= 0) {
// console.log('here!');
// // console.log(ts.SyntaxKind[declaration.kind]);
// }
if (declaration.kind === ts.SyntaxKind.InterfaceDeclaration || declaration.kind === ts.SyntaxKind.ClassDeclaration) {
let interfaceDeclaration = <ts.InterfaceDeclaration | ts.ClassDeclaration>declaration;
let members:ts.NodeArray<ts.Node> = interfaceDeclaration.members;
members.forEach((member) => {
try {
let memberText = getNodeText(sourceFile, member);
if (memberText.indexOf('@internal') >= 0 || memberText.indexOf('private') >= 0) {
// console.log('BEFORE: ', result);
result = result.replace(memberText, '');
// console.log('AFTER: ', result);
}
} catch (err) {
// life..
}
});
}
result = result.replace(/export default/g, 'export');
result = result.replace(/export declare/g, 'export');
return result;
}
function format(text:string): string {
let options = getDefaultOptions();
// Parse the source text
let sourceFile = ts.createSourceFile('file.ts', text, ts.ScriptTarget.Latest, /*setParentPointers*/ true);
// Get the formatting edits on the input sources
let edits = (<any>ts).formatting.formatDocument(sourceFile, getRuleProvider(options), options);
// Apply the edits on the input code
return applyEdits(text, edits);
function getRuleProvider(options: ts.FormatCodeOptions) {
// Share this between multiple formatters using the same options.
// This represents the bulk of the space the formatter uses.
let ruleProvider = new (<any>ts).formatting.RulesProvider();
ruleProvider.ensureUpToDate(options);
return ruleProvider;
}
function applyEdits(text: string, edits: ts.TextChange[]): string {
// Apply edits in reverse on the existing text
let result = text;
for (let i = edits.length - 1; i >= 0; i--) {
let change = edits[i];
let head = result.slice(0, change.span.start);
let tail = result.slice(change.span.start + change.span.length);
result = head + change.newText + tail;
}
return result;
}
function getDefaultOptions(): ts.FormatCodeOptions {
return {
IndentSize: 4,
TabSize: 4,
NewLineCharacter: '\r\n',
ConvertTabsToSpaces: true,
IndentStyle: ts.IndentStyle.Block,
InsertSpaceAfterCommaDelimiter: true,
InsertSpaceAfterSemicolonInForStatements: true,
InsertSpaceBeforeAndAfterBinaryOperators: true,
InsertSpaceAfterKeywordsInControlFlowStatements: true,
InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: true,
PlaceOpenBraceOnNewLineForFunctions: false,
PlaceOpenBraceOnNewLineForControlBlocks: false,
};
}
}
function createReplacer(data:string): (str:string)=>string {
data = data || '';
let rawDirectives = data.split(';');
let directives: [RegExp,string][] = [];
rawDirectives.forEach((rawDirective) => {
if (rawDirective.length === 0) {
return;
}
let pieces = rawDirective.split('=>');
let findStr = pieces[0];
let replaceStr = pieces[1];
findStr = findStr.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&');
findStr = '\\b' + findStr + '\\b';
directives.push([new RegExp(findStr, 'g'), replaceStr]);
});
return (str:string)=> {
for (let i = 0; i < directives.length; i++) {
str = str.replace(directives[i][0], directives[i][1]);
}
return str;
};
}
function generateDeclarationFile(out:string, recipe:string): string {
let lines = recipe.split(/\r\n|\n|\r/);
let result = [];
lines.forEach(line => {
let m1 = line.match(/^\s*#include\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
if (m1) {
CURRENT_PROCESSING_RULE = line;
let moduleId = m1[1];
let sourceFile = getSourceFile(out, moduleId);
if (!sourceFile) {
return;
}
let replacer = createReplacer(m1[2]);
let typeNames = m1[3].split(/,/);
typeNames.forEach((typeName) => {
typeName = typeName.trim();
if (typeName.length === 0) {
return;
}
let declaration = getTopLevelDeclaration(sourceFile, typeName);
if (!declaration) {
logErr('Cannot find type ' + typeName);
return;
}
result.push(replacer(getMassagedTopLevelDeclarationText(sourceFile, declaration)));
});
return;
}
let m2 = line.match(/^\s*#includeAll\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
if (m2) {
CURRENT_PROCESSING_RULE = line;
let moduleId = m2[1];
let sourceFile = getSourceFile(out, moduleId);
if (!sourceFile) {
return;
}
let replacer = createReplacer(m2[2]);
let typeNames = m2[3].split(/,/);
let typesToExcludeMap: {[typeName:string]:boolean;} = {};
let typesToExcludeArr: string[] = [];
typeNames.forEach((typeName) => {
typeName = typeName.trim();
if (typeName.length === 0) {
return;
}
typesToExcludeMap[typeName] = true;
typesToExcludeArr.push(typeName);
});
getAllTopLevelDeclarations(sourceFile).forEach((declaration) => {
if (isDeclaration(declaration)) {
if (typesToExcludeMap[declaration.name.text]) {
return;
}
} else {
// node is ts.VariableStatement
let nodeText = getNodeText(sourceFile, declaration);
for (let i = 0; i < typesToExcludeArr.length; i++) {
if (nodeText.indexOf(typesToExcludeArr[i]) >= 0) {
return;
}
}
}
result.push(replacer(getMassagedTopLevelDeclarationText(sourceFile, declaration)));
});
return;
}
result.push(line);
});
let resultTxt = result.join('\n');
resultTxt = resultTxt.replace(/\bURI\b/g, 'Uri');
resultTxt = resultTxt.replace(/\bEvent</g, 'IEvent<');
resultTxt = resultTxt.replace(/\bTPromise</g, 'Promise<');
resultTxt = format(resultTxt);
resultTxt = resultTxt.replace(/\r\n/g, '\n');
return resultTxt;
}
export function getFilesToWatch(out:string): string[] {
let recipe = fs.readFileSync(RECIPE_PATH).toString();
let lines = recipe.split(/\r\n|\n|\r/);
let result = [];
lines.forEach(line => {
let m1 = line.match(/^\s*#include\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
if (m1) {
let moduleId = m1[1];
result.push(moduleIdToPath(out, moduleId));
return;
}
let m2 = line.match(/^\s*#includeAll\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
if (m2) {
let moduleId = m2[1];
result.push(moduleIdToPath(out, moduleId));
return;
}
});
return result;
}
export interface IMonacoDeclarationResult {
content: string;
filePath: string;
isTheSame: boolean;
}
export function run(out:string): IMonacoDeclarationResult {
log('Starting monaco.d.ts generation');
SOURCE_FILE_MAP = {};
let recipe = fs.readFileSync(RECIPE_PATH).toString();
let result = generateDeclarationFile(out, recipe);
let currentContent = fs.readFileSync(DECLARATION_PATH).toString();
log('Finished monaco.d.ts generation');
return {
content: result,
filePath: DECLARATION_PATH,
isTheSame: currentContent === result
};
}
export function complainErrors() {
logErr('Not running monaco.d.ts generation due to compile errors');
} | build/monaco/api.ts | 0 | https://github.com/microsoft/vscode/commit/bb194502143f100abe468b1328a54e33c62fd514 | [
0.0006897590938024223,
0.00018556625582277775,
0.00016550830332562327,
0.00017379004566464573,
0.00007978846406331286
] |
{
"id": 2,
"code_window": [
"\t\t}\n",
"\n",
"\t\tconst threads = (<model.Model>element).getThreads(session.getId());\n",
"\t\treturn TPromise.as(Object.keys(threads).map(ref => threads[ref]));\n",
"\t}\n",
"\n",
"\tprivate getThreadChildren(thread: debug.IThread): TPromise<any> {\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst session = <debug.IRawDebugSession>element;\n",
"\t\tconst threads = this.debugService.getModel().getThreads(session.getId());\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugViewer.ts",
"type": "replace",
"edit_start_line_idx": 370
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export class ArraySet<T> {
private _elements: T[];
constructor(elements: T[] = []) {
this._elements = elements.slice();
}
get size(): number {
return this._elements.length;
}
set(element: T): void {
this.unset(element);
this._elements.push(element);
}
contains(element: T): boolean {
return this._elements.indexOf(element) > -1;
}
unset(element: T): void {
const index = this._elements.indexOf(element);
if (index > -1) {
this._elements.splice(index, 1);
}
}
get elements(): T[] {
return this._elements.slice();
}
} | src/vs/base/common/set.ts | 0 | https://github.com/microsoft/vscode/commit/bb194502143f100abe468b1328a54e33c62fd514 | [
0.0001754226250341162,
0.00016806588973850012,
0.0001619310351088643,
0.00016745492757763714,
0.000005193452125240583
] |
{
"id": 3,
"code_window": [
"\t\t}));\n",
"\n",
"\t\tthis.toDispose.push(model.onDidChangeCallStack(() => {\n",
"\t\t\tconst session = this.debugService.getViewModel().activeSession;\n",
"\t\t\tconst threads = session ? model.getThreads(session.getId()) : Object.create(null);\n",
"\t\t\tconst threadsArray = Object.keys(threads).map(ref => threads[ref]);\n",
"\t\t\t// Only show the threads in the call stack if there is more than 1 thread.\n",
"\t\t\tconst newTreeInput = threadsArray.length === 1 ? threadsArray[0] : model;\n",
"\n",
"\t\t\tif (this.tree.getInput() === newTreeInput) {\n",
"\t\t\t\tthis.tree.refresh().done(null, errors.onUnexpectedError);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tlet newTreeInput: any = this.debugService.getModel();\n",
"\t\t\tconst sessions = this.debugService.getModel().getSessions();\n",
"\t\t\tif (sessions.length === 1) {\n",
"\t\t\t\tconst threads = sessions[0] ? model.getThreads(sessions[0].getId()) : Object.create(null);\n",
"\t\t\t\tconst threadsArray = Object.keys(threads).map(ref => threads[ref]);\n",
"\t\t\t\t// Only show the threads in the call stack if there is more than 1 thread.\n",
"\t\t\t\tnewTreeInput = threadsArray.length === 1 ? threadsArray[0] : sessions[0];\n",
"\t\t\t}\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugViews.ts",
"type": "replace",
"edit_start_line_idx": 292
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import nls = require('vs/nls');
import { TPromise } from 'vs/base/common/winjs.base';
import lifecycle = require('vs/base/common/lifecycle');
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import paths = require('vs/base/common/paths');
import async = require('vs/base/common/async');
import errors = require('vs/base/common/errors');
import strings = require('vs/base/common/strings');
import { isMacintosh } from 'vs/base/common/platform';
import dom = require('vs/base/browser/dom');
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import labels = require('vs/base/common/labels');
import actions = require('vs/base/common/actions');
import actionbar = require('vs/base/browser/ui/actionbar/actionbar');
import tree = require('vs/base/parts/tree/browser/tree');
import { InputBox, IInputValidationOptions } from 'vs/base/browser/ui/inputbox/inputBox';
import treedefaults = require('vs/base/parts/tree/browser/treeDefaults');
import renderer = require('vs/base/parts/tree/browser/actionsRenderer');
import debug = require('vs/workbench/parts/debug/common/debug');
import model = require('vs/workbench/parts/debug/common/debugModel');
import viewmodel = require('vs/workbench/parts/debug/common/debugViewModel');
import debugactions = require('vs/workbench/parts/debug/browser/debugActions');
import { CopyValueAction } from 'vs/workbench/parts/debug/electron-browser/electronDebugActions';
import { IContextViewService, IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
const $ = dom.$;
const booleanRegex = /^true|false$/i;
const stringRegex = /^(['"]).*\1$/;
const MAX_VALUE_RENDER_LENGTH_IN_VIEWLET = 1024;
export function renderExpressionValue(expressionOrValue: debug.IExpression | string, container: HTMLElement, showChanged: boolean, maxValueRenderLength?: number): void {
let value = typeof expressionOrValue === 'string' ? expressionOrValue : expressionOrValue.value;
// remove stale classes
container.className = 'value';
// when resolving expressions we represent errors from the server as a variable with name === null.
if (value === null || ((expressionOrValue instanceof model.Expression || expressionOrValue instanceof model.Variable) && !expressionOrValue.available)) {
dom.addClass(container, 'unavailable');
if (value !== model.Expression.DEFAULT_VALUE) {
dom.addClass(container, 'error');
}
} else if (!isNaN(+value)) {
dom.addClass(container, 'number');
} else if (booleanRegex.test(value)) {
dom.addClass(container, 'boolean');
} else if (stringRegex.test(value)) {
dom.addClass(container, 'string');
}
if (showChanged && (<any>expressionOrValue).valueChanged) {
// value changed color has priority over other colors.
container.className = 'value changed';
}
if (maxValueRenderLength && value.length > maxValueRenderLength) {
value = value.substr(0, maxValueRenderLength) + '...';
}
container.textContent = value;
container.title = value;
}
export function renderVariable(tree: tree.ITree, variable: model.Variable, data: IVariableTemplateData, showChanged: boolean): void {
if (variable.available) {
data.name.textContent = variable.name;
data.name.title = variable.type ? variable.type : '';
}
if (variable.value) {
data.name.textContent += ':';
renderExpressionValue(variable, data.value, showChanged, MAX_VALUE_RENDER_LENGTH_IN_VIEWLET);
data.value.title = variable.value;
} else {
data.value.textContent = '';
data.value.title = '';
}
}
interface IRenameBoxOptions {
initialValue: string;
ariaLabel: string;
placeholder?: string;
validationOptions?: IInputValidationOptions;
}
function renderRenameBox(debugService: debug.IDebugService, contextViewService: IContextViewService, tree: tree.ITree, element: any, container: HTMLElement, options: IRenameBoxOptions): void {
let inputBoxContainer = dom.append(container, $('.inputBoxContainer'));
let inputBox = new InputBox(inputBoxContainer, contextViewService, {
validationOptions: options.validationOptions,
placeholder: options.placeholder,
ariaLabel: options.ariaLabel
});
inputBox.value = options.initialValue ? options.initialValue : '';
inputBox.focus();
inputBox.select();
let disposed = false;
const toDispose: [lifecycle.IDisposable] = [inputBox];
const wrapUp = async.once((renamed: boolean) => {
if (!disposed) {
disposed = true;
if (element instanceof model.Expression && renamed && inputBox.value) {
debugService.renameWatchExpression(element.getId(), inputBox.value).done(null, errors.onUnexpectedError);
} else if (element instanceof model.Expression && !element.name) {
debugService.removeWatchExpressions(element.getId());
} else if (element instanceof model.FunctionBreakpoint && renamed && inputBox.value) {
debugService.renameFunctionBreakpoint(element.getId(), inputBox.value).done(null, errors.onUnexpectedError);
} else if (element instanceof model.FunctionBreakpoint && !element.name) {
debugService.removeFunctionBreakpoints(element.getId()).done(null, errors.onUnexpectedError);
} else if (element instanceof model.Variable) {
(<model.Variable>element).errorMessage = null;
if (renamed && element.value !== inputBox.value) {
debugService.setVariable(element, inputBox.value)
// if everything went fine we need to refresh that tree element since his value updated
.done(() => tree.refresh(element, false), errors.onUnexpectedError);
}
}
tree.clearHighlight();
tree.DOMFocus();
tree.setFocus(element);
// need to remove the input box since this template will be reused.
container.removeChild(inputBoxContainer);
lifecycle.dispose(toDispose);
}
});
toDispose.push(dom.addStandardDisposableListener(inputBox.inputElement, 'keydown', (e: IKeyboardEvent) => {
const isEscape = e.equals(KeyCode.Escape);
const isEnter = e.equals(KeyCode.Enter);
if (isEscape || isEnter) {
wrapUp(isEnter);
}
}));
toDispose.push(dom.addDisposableListener(inputBox.inputElement, 'blur', () => {
wrapUp(true);
}));
}
function getSourceName(source: Source, contextService: IWorkspaceContextService): string {
if (source.inMemory) {
return source.name;
}
return labels.getPathLabel(paths.basename(source.uri.fsPath), contextService);
}
export class BaseDebugController extends treedefaults.DefaultController {
constructor(
protected debugService: debug.IDebugService,
private contextMenuService: IContextMenuService,
private actionProvider: renderer.IActionProvider,
private focusOnContextMenu = true
) {
super();
if (isMacintosh) {
this.downKeyBindingDispatcher.set(KeyMod.CtrlCmd | KeyCode.Backspace, this.onDelete.bind(this));
} else {
this.downKeyBindingDispatcher.set(KeyCode.Delete, this.onDelete.bind(this));
this.downKeyBindingDispatcher.set(KeyMod.Shift | KeyCode.Delete, this.onDelete.bind(this));
}
}
public onContextMenu(tree: tree.ITree, element: debug.IEnablement, event: tree.ContextMenuEvent): boolean {
if (event.target && event.target.tagName && event.target.tagName.toLowerCase() === 'input') {
return false;
}
event.preventDefault();
event.stopPropagation();
if (this.focusOnContextMenu) {
tree.setFocus(element);
}
if (this.actionProvider.hasSecondaryActions(tree, element)) {
const anchor = { x: event.posx + 1, y: event.posy };
this.contextMenuService.showContextMenu({
getAnchor: () => anchor,
getActions: () => this.actionProvider.getSecondaryActions(tree, element),
onHide: (wasCancelled?: boolean) => {
if (wasCancelled) {
tree.DOMFocus();
}
},
getActionsContext: () => element
});
return true;
}
return false;
}
protected onDelete(tree: tree.ITree, event: IKeyboardEvent): boolean {
return false;
}
}
// call stack
class ThreadAndSessionId {
constructor(public sessionId: string, public threadId: number) { }
}
export class CallStackController extends BaseDebugController {
protected onLeftClick(tree: tree.ITree, element: any, event: IMouseEvent): boolean {
if (element instanceof ThreadAndSessionId) {
return this.showMoreStackFrames(tree, element);
}
if (element instanceof model.StackFrame) {
this.focusStackFrame(element, event, true);
}
return super.onLeftClick(tree, element, event);
}
protected onEnter(tree: tree.ITree, event: IKeyboardEvent): boolean {
const element = tree.getFocus();
if (element instanceof ThreadAndSessionId) {
return this.showMoreStackFrames(tree, element);
}
if (element instanceof model.StackFrame) {
this.focusStackFrame(element, event, false);
}
return super.onEnter(tree, event);
}
protected onUp(tree: tree.ITree, event: IKeyboardEvent): boolean {
super.onUp(tree, event);
this.focusStackFrame(tree.getFocus(), event, true);
return true;
}
protected onPageUp(tree: tree.ITree, event: IKeyboardEvent): boolean {
super.onPageUp(tree, event);
this.focusStackFrame(tree.getFocus(), event, true);
return true;
}
protected onDown(tree: tree.ITree, event: IKeyboardEvent): boolean {
super.onDown(tree, event);
this.focusStackFrame(tree.getFocus(), event, true);
return true;
}
protected onPageDown(tree: tree.ITree, event: IKeyboardEvent): boolean {
super.onPageDown(tree, event);
this.focusStackFrame(tree.getFocus(), event, true);
return true;
}
// user clicked / pressed on 'Load More Stack Frames', get those stack frames and refresh the tree.
private showMoreStackFrames(tree: tree.ITree, threadAndSessionId: ThreadAndSessionId): boolean {
const thread = this.debugService.getModel().getThreads(threadAndSessionId.sessionId)[threadAndSessionId.threadId];
if (thread) {
thread.getCallStack(true)
.done(() => tree.refresh(), errors.onUnexpectedError);
}
return true;
}
private focusStackFrame(stackFrame: debug.IStackFrame, event: IKeyboardEvent | IMouseEvent, preserveFocus: boolean): void {
this.debugService.setFocusedStackFrameAndEvaluate(stackFrame).done(null, errors.onUnexpectedError);
if (stackFrame) {
const sideBySide = (event && (event.ctrlKey || event.metaKey));
this.debugService.openOrRevealSource(stackFrame.source, stackFrame.lineNumber, preserveFocus, sideBySide).done(null, errors.onUnexpectedError);
}
}
}
export class CallStackActionProvider implements renderer.IActionProvider {
constructor( @IInstantiationService private instantiationService: IInstantiationService, @debug.IDebugService private debugService: debug.IDebugService) {
// noop
}
public hasActions(tree: tree.ITree, element: any): boolean {
return false;
}
public getActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
return TPromise.as([]);
}
public hasSecondaryActions(tree: tree.ITree, element: any): boolean {
return element instanceof model.Thread || element instanceof model.StackFrame;
}
public getSecondaryActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
const actions: actions.Action[] = [];
if (element instanceof model.Thread) {
const thread = <model.Thread>element;
if (thread.stopped) {
actions.push(this.instantiationService.createInstance(debugactions.ContinueAction, debugactions.ContinueAction.ID, debugactions.ContinueAction.LABEL));
actions.push(this.instantiationService.createInstance(debugactions.StepOverAction, debugactions.StepOverAction.ID, debugactions.StepOverAction.LABEL));
actions.push(this.instantiationService.createInstance(debugactions.StepIntoAction, debugactions.StepIntoAction.ID, debugactions.StepIntoAction.LABEL));
actions.push(this.instantiationService.createInstance(debugactions.StepOutAction, debugactions.StepOutAction.ID, debugactions.StepOutAction.LABEL));
} else {
actions.push(this.instantiationService.createInstance(debugactions.PauseAction, debugactions.PauseAction.ID, debugactions.PauseAction.LABEL));
}
} else if (element instanceof model.StackFrame) {
const capabilities = this.debugService.getViewModel().activeSession.configuration.capabilities;
if (typeof capabilities.supportsRestartFrame === 'boolean' && capabilities.supportsRestartFrame) {
actions.push(this.instantiationService.createInstance(debugactions.RestartFrameAction, debugactions.RestartFrameAction.ID, debugactions.RestartFrameAction.LABEL));
}
}
return TPromise.as(actions);
}
public getActionItem(tree: tree.ITree, element: any, action: actions.IAction): actionbar.IActionItem {
return null;
}
}
export class CallStackDataSource implements tree.IDataSource {
constructor( @debug.IDebugService private debugService: debug.IDebugService) {
// noop
}
public getId(tree: tree.ITree, element: any): string {
if (typeof element === 'number') {
return element.toString();
}
if (typeof element === 'string') {
return element;
}
return element.getId();
}
public hasChildren(tree: tree.ITree, element: any): boolean {
return element instanceof model.Model || (element instanceof model.Thread && (<model.Thread>element).stopped);
}
public getChildren(tree: tree.ITree, element: any): TPromise<any> {
if (element instanceof model.Thread) {
return this.getThreadChildren(element);
}
// TODO@Isidor FIX THIS
const session = this.debugService.getViewModel().activeSession;
if (!session) {
return TPromise.as([]);
}
const threads = (<model.Model>element).getThreads(session.getId());
return TPromise.as(Object.keys(threads).map(ref => threads[ref]));
}
private getThreadChildren(thread: debug.IThread): TPromise<any> {
return thread.getCallStack().then((callStack: any[]) => {
if (thread.stoppedDetails && thread.stoppedDetails.framesErrorMessage) {
return callStack.concat([thread.stoppedDetails.framesErrorMessage]);
}
if (thread.stoppedDetails && thread.stoppedDetails.totalFrames > callStack.length) {
return callStack.concat([new ThreadAndSessionId(thread.sessionId, thread.threadId)]);
}
return callStack;
});
}
public getParent(tree: tree.ITree, element: any): TPromise<any> {
return TPromise.as(null);
}
}
interface IThreadTemplateData {
thread: HTMLElement;
name: HTMLElement;
state: HTMLElement;
stateLabel: HTMLSpanElement;
}
interface IErrorTemplateData {
label: HTMLElement;
}
interface ILoadMoreTemplateData {
label: HTMLElement;
}
interface IStackFrameTemplateData {
stackFrame: HTMLElement;
label: HTMLElement;
file: HTMLElement;
fileName: HTMLElement;
lineNumber: HTMLElement;
}
export class CallStackRenderer implements tree.IRenderer {
private static THREAD_TEMPLATE_ID = 'thread';
private static STACK_FRAME_TEMPLATE_ID = 'stackFrame';
private static ERROR_TEMPLATE_ID = 'error';
private static LOAD_MORE_TEMPLATE_ID = 'loadMore';
constructor( @IWorkspaceContextService private contextService: IWorkspaceContextService) {
// noop
}
public getHeight(tree: tree.ITree, element: any): number {
return 22;
}
public getTemplateId(tree: tree.ITree, element: any): string {
if (element instanceof model.Thread) {
return CallStackRenderer.THREAD_TEMPLATE_ID;
}
if (element instanceof model.StackFrame) {
return CallStackRenderer.STACK_FRAME_TEMPLATE_ID;
}
if (typeof element === 'string') {
return CallStackRenderer.ERROR_TEMPLATE_ID;
}
return CallStackRenderer.LOAD_MORE_TEMPLATE_ID;
}
public renderTemplate(tree: tree.ITree, templateId: string, container: HTMLElement): any {
if (templateId === CallStackRenderer.LOAD_MORE_TEMPLATE_ID) {
let data: ILoadMoreTemplateData = Object.create(null);
data.label = dom.append(container, $('.load-more'));
return data;
}
if (templateId === CallStackRenderer.ERROR_TEMPLATE_ID) {
let data: ILoadMoreTemplateData = Object.create(null);
data.label = dom.append(container, $('.error'));
return data;
}
if (templateId === CallStackRenderer.THREAD_TEMPLATE_ID) {
let data: IThreadTemplateData = Object.create(null);
data.thread = dom.append(container, $('.thread'));
data.name = dom.append(data.thread, $('.name'));
data.state = dom.append(data.thread, $('.state'));
data.stateLabel = dom.append(data.state, $('span.label'));
return data;
}
let data: IStackFrameTemplateData = Object.create(null);
data.stackFrame = dom.append(container, $('.stack-frame'));
data.label = dom.append(data.stackFrame, $('span.label'));
data.file = dom.append(data.stackFrame, $('.file'));
data.fileName = dom.append(data.file, $('span.file-name'));
data.lineNumber = dom.append(data.file, $('span.line-number'));
return data;
}
public renderElement(tree: tree.ITree, element: any, templateId: string, templateData: any): void {
if (templateId === CallStackRenderer.THREAD_TEMPLATE_ID) {
this.renderThread(element, templateData);
} else if (templateId === CallStackRenderer.STACK_FRAME_TEMPLATE_ID) {
this.renderStackFrame(element, templateData);
} else if (templateId === CallStackRenderer.ERROR_TEMPLATE_ID) {
this.renderError(element, templateData);
} else {
this.renderLoadMore(element, templateData);
}
}
private renderThread(thread: debug.IThread, data: IThreadTemplateData): void {
data.thread.title = nls.localize('thread', "Thread");
data.name.textContent = thread.name;
data.stateLabel.textContent = thread.stopped ? nls.localize('paused', "paused")
: nls.localize({ key: 'running', comment: ['indicates state'] }, "running");
}
private renderError(element: string, data: IErrorTemplateData) {
data.label.textContent = element;
data.label.title = element;
}
private renderLoadMore(element: any, data: ILoadMoreTemplateData): void {
data.label.textContent = nls.localize('loadMoreStackFrames', "Load More Stack Frames");
}
private renderStackFrame(stackFrame: debug.IStackFrame, data: IStackFrameTemplateData): void {
stackFrame.source.available ? dom.removeClass(data.stackFrame, 'disabled') : dom.addClass(data.stackFrame, 'disabled');
data.file.title = stackFrame.source.uri.fsPath;
data.label.textContent = stackFrame.name;
data.label.title = stackFrame.name;
data.fileName.textContent = getSourceName(stackFrame.source, this.contextService);
if (stackFrame.lineNumber !== undefined) {
data.lineNumber.textContent = `${stackFrame.lineNumber}`;
dom.removeClass(data.lineNumber, 'unavailable');
} else {
dom.addClass(data.lineNumber, 'unavailable');
}
}
public disposeTemplate(tree: tree.ITree, templateId: string, templateData: any): void {
// noop
}
}
export class CallstackAccessibilityProvider implements tree.IAccessibilityProvider {
constructor( @IWorkspaceContextService private contextService: IWorkspaceContextService) {
// noop
}
public getAriaLabel(tree: tree.ITree, element: any): string {
if (element instanceof model.Thread) {
return nls.localize('threadAriaLabel', "Thread {0}, callstack, debug", (<model.Thread>element).name);
}
if (element instanceof model.StackFrame) {
return nls.localize('stackFrameAriaLabel', "Stack Frame {0} line {1} {2}, callstack, debug", (<model.StackFrame>element).name, (<model.StackFrame>element).lineNumber, getSourceName((<model.StackFrame>element).source, this.contextService));
}
return null;
}
}
// variables
export class VariablesActionProvider implements renderer.IActionProvider {
constructor(private instantiationService: IInstantiationService) {
// noop
}
public hasActions(tree: tree.ITree, element: any): boolean {
return false;
}
public getActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
return TPromise.as([]);
}
public hasSecondaryActions(tree: tree.ITree, element: any): boolean {
return element instanceof model.Variable;
}
public getSecondaryActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
let actions: actions.Action[] = [];
const variable = <model.Variable>element;
if (variable.reference === 0) {
actions.push(this.instantiationService.createInstance(debugactions.SetValueAction, debugactions.SetValueAction.ID, debugactions.SetValueAction.LABEL, variable));
actions.push(this.instantiationService.createInstance(CopyValueAction, CopyValueAction.ID, CopyValueAction.LABEL, variable));
actions.push(new actionbar.Separator());
}
actions.push(this.instantiationService.createInstance(debugactions.AddToWatchExpressionsAction, debugactions.AddToWatchExpressionsAction.ID, debugactions.AddToWatchExpressionsAction.LABEL, variable));
return TPromise.as(actions);
}
public getActionItem(tree: tree.ITree, element: any, action: actions.IAction): actionbar.IActionItem {
return null;
}
}
export class VariablesDataSource implements tree.IDataSource {
public getId(tree: tree.ITree, element: any): string {
return element.getId();
}
public hasChildren(tree: tree.ITree, element: any): boolean {
if (element instanceof viewmodel.ViewModel || element instanceof model.Scope) {
return true;
}
let variable = <model.Variable>element;
return variable.reference !== 0 && !strings.equalsIgnoreCase(variable.value, 'null');
}
public getChildren(tree: tree.ITree, element: any): TPromise<any> {
if (element instanceof viewmodel.ViewModel) {
let focusedStackFrame = (<viewmodel.ViewModel>element).getFocusedStackFrame();
return focusedStackFrame ? focusedStackFrame.getScopes() : TPromise.as([]);
}
let scope = <model.Scope>element;
return scope.getChildren();
}
public getParent(tree: tree.ITree, element: any): TPromise<any> {
return TPromise.as(null);
}
}
interface IScopeTemplateData {
name: HTMLElement;
}
export interface IVariableTemplateData {
expression: HTMLElement;
name: HTMLElement;
value: HTMLElement;
}
export class VariablesRenderer implements tree.IRenderer {
private static SCOPE_TEMPLATE_ID = 'scope';
private static VARIABLE_TEMPLATE_ID = 'variable';
constructor(
@debug.IDebugService private debugService: debug.IDebugService,
@IContextViewService private contextViewService: IContextViewService
) {
// noop
}
public getHeight(tree: tree.ITree, element: any): number {
return 22;
}
public getTemplateId(tree: tree.ITree, element: any): string {
if (element instanceof model.Scope) {
return VariablesRenderer.SCOPE_TEMPLATE_ID;
}
if (element instanceof model.Variable) {
return VariablesRenderer.VARIABLE_TEMPLATE_ID;
}
return null;
}
public renderTemplate(tree: tree.ITree, templateId: string, container: HTMLElement): any {
if (templateId === VariablesRenderer.SCOPE_TEMPLATE_ID) {
let data: IScopeTemplateData = Object.create(null);
data.name = dom.append(container, $('.scope'));
return data;
}
let data: IVariableTemplateData = Object.create(null);
data.expression = dom.append(container, $('.expression'));
data.name = dom.append(data.expression, $('span.name'));
data.value = dom.append(data.expression, $('span.value'));
return data;
}
public renderElement(tree: tree.ITree, element: any, templateId: string, templateData: any): void {
if (templateId === VariablesRenderer.SCOPE_TEMPLATE_ID) {
this.renderScope(element, templateData);
} else {
const variable = <model.Variable>element;
if (variable === this.debugService.getViewModel().getSelectedExpression() || variable.errorMessage) {
renderRenameBox(this.debugService, this.contextViewService, tree, variable, (<IVariableTemplateData>templateData).expression, {
initialValue: variable.value,
ariaLabel: nls.localize('variableValueAriaLabel', "Type new variable value"),
validationOptions: {
validation: (value: string) => variable.errorMessage ? ({ content: variable.errorMessage }) : null
}
});
} else {
renderVariable(tree, variable, templateData, true);
}
}
}
private renderScope(scope: model.Scope, data: IScopeTemplateData): void {
data.name.textContent = scope.name;
}
public disposeTemplate(tree: tree.ITree, templateId: string, templateData: any): void {
// noop
}
}
export class VariablesAccessibilityProvider implements tree.IAccessibilityProvider {
public getAriaLabel(tree: tree.ITree, element: any): string {
if (element instanceof model.Scope) {
return nls.localize('variableScopeAriaLabel', "Scope {0}, variables, debug", (<model.Scope>element).name);
}
if (element instanceof model.Variable) {
return nls.localize('variableAriaLabel', "{0} value {1}, variables, debug", (<model.Variable>element).name, (<model.Variable>element).value);
}
return null;
}
}
export class VariablesController extends BaseDebugController {
constructor(debugService: debug.IDebugService, contextMenuService: IContextMenuService, actionProvider: renderer.IActionProvider) {
super(debugService, contextMenuService, actionProvider);
this.downKeyBindingDispatcher.set(KeyCode.Enter, this.setSelectedExpression.bind(this));
}
protected onLeftClick(tree: tree.ITree, element: any, event: IMouseEvent): boolean {
// double click on primitive value: open input box to be able to set the value
if (element instanceof model.Variable && event.detail === 2) {
const expression = <debug.IExpression>element;
if (expression.reference === 0) {
this.debugService.getViewModel().setSelectedExpression(expression);
}
return true;
}
return super.onLeftClick(tree, element, event);
}
protected setSelectedExpression(tree: tree.ITree, event: KeyboardEvent): boolean {
const element = tree.getFocus();
if (element instanceof model.Variable && element.reference === 0) {
this.debugService.getViewModel().setSelectedExpression(element);
return true;
}
return false;
}
}
// watch expressions
export class WatchExpressionsActionProvider implements renderer.IActionProvider {
private instantiationService: IInstantiationService;
constructor(instantiationService: IInstantiationService) {
this.instantiationService = instantiationService;
}
public hasActions(tree: tree.ITree, element: any): boolean {
return element instanceof model.Expression && !!element.name;
}
public hasSecondaryActions(tree: tree.ITree, element: any): boolean {
return true;
}
public getActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
return TPromise.as(this.getExpressionActions());
}
public getExpressionActions(): actions.IAction[] {
return [this.instantiationService.createInstance(debugactions.RemoveWatchExpressionAction, debugactions.RemoveWatchExpressionAction.ID, debugactions.RemoveWatchExpressionAction.LABEL)];
}
public getSecondaryActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
const actions: actions.Action[] = [];
if (element instanceof model.Expression) {
const expression = <model.Expression>element;
actions.push(this.instantiationService.createInstance(debugactions.AddWatchExpressionAction, debugactions.AddWatchExpressionAction.ID, debugactions.AddWatchExpressionAction.LABEL));
actions.push(this.instantiationService.createInstance(debugactions.RenameWatchExpressionAction, debugactions.RenameWatchExpressionAction.ID, debugactions.RenameWatchExpressionAction.LABEL, expression));
if (expression.reference === 0) {
actions.push(this.instantiationService.createInstance(CopyValueAction, CopyValueAction.ID, CopyValueAction.LABEL, expression.value));
}
actions.push(new actionbar.Separator());
actions.push(this.instantiationService.createInstance(debugactions.RemoveWatchExpressionAction, debugactions.RemoveWatchExpressionAction.ID, debugactions.RemoveWatchExpressionAction.LABEL));
actions.push(this.instantiationService.createInstance(debugactions.RemoveAllWatchExpressionsAction, debugactions.RemoveAllWatchExpressionsAction.ID, debugactions.RemoveAllWatchExpressionsAction.LABEL));
} else {
actions.push(this.instantiationService.createInstance(debugactions.AddWatchExpressionAction, debugactions.AddWatchExpressionAction.ID, debugactions.AddWatchExpressionAction.LABEL));
if (element instanceof model.Variable) {
const variable = <model.Variable>element;
if (variable.reference === 0) {
actions.push(this.instantiationService.createInstance(CopyValueAction, CopyValueAction.ID, CopyValueAction.LABEL, variable.value));
}
actions.push(new actionbar.Separator());
}
actions.push(this.instantiationService.createInstance(debugactions.RemoveAllWatchExpressionsAction, debugactions.RemoveAllWatchExpressionsAction.ID, debugactions.RemoveAllWatchExpressionsAction.LABEL));
}
return TPromise.as(actions);
}
public getActionItem(tree: tree.ITree, element: any, action: actions.IAction): actionbar.IActionItem {
return null;
}
}
export class WatchExpressionsDataSource implements tree.IDataSource {
public getId(tree: tree.ITree, element: any): string {
return element.getId();
}
public hasChildren(tree: tree.ITree, element: any): boolean {
if (element instanceof model.Model) {
return true;
}
const watchExpression = <model.Expression>element;
return watchExpression.reference !== 0 && !strings.equalsIgnoreCase(watchExpression.value, 'null');
}
public getChildren(tree: tree.ITree, element: any): TPromise<any> {
if (element instanceof model.Model) {
return TPromise.as((<model.Model>element).getWatchExpressions());
}
let expression = <model.Expression>element;
return expression.getChildren();
}
public getParent(tree: tree.ITree, element: any): TPromise<any> {
return TPromise.as(null);
}
}
interface IWatchExpressionTemplateData extends IVariableTemplateData {
actionBar: actionbar.ActionBar;
}
export class WatchExpressionsRenderer implements tree.IRenderer {
private static WATCH_EXPRESSION_TEMPLATE_ID = 'watchExpression';
private static VARIABLE_TEMPLATE_ID = 'variables';
private toDispose: lifecycle.IDisposable[];
private actionProvider: WatchExpressionsActionProvider;
constructor(
actionProvider: renderer.IActionProvider,
private actionRunner: actions.IActionRunner,
@debug.IDebugService private debugService: debug.IDebugService,
@IContextViewService private contextViewService: IContextViewService
) {
this.toDispose = [];
this.actionProvider = <WatchExpressionsActionProvider>actionProvider;
}
public getHeight(tree: tree.ITree, element: any): number {
return 22;
}
public getTemplateId(tree: tree.ITree, element: any): string {
if (element instanceof model.Expression) {
return WatchExpressionsRenderer.WATCH_EXPRESSION_TEMPLATE_ID;
}
return WatchExpressionsRenderer.VARIABLE_TEMPLATE_ID;
}
public renderTemplate(tree: tree.ITree, templateId: string, container: HTMLElement): any {
let data: IWatchExpressionTemplateData = Object.create(null);
if (templateId === WatchExpressionsRenderer.WATCH_EXPRESSION_TEMPLATE_ID) {
data.actionBar = new actionbar.ActionBar(container, { actionRunner: this.actionRunner });
data.actionBar.push(this.actionProvider.getExpressionActions(), { icon: true, label: false });
}
data.expression = dom.append(container, $('.expression'));
data.name = dom.append(data.expression, $('span.name'));
data.value = dom.append(data.expression, $('span.value'));
return data;
}
public renderElement(tree: tree.ITree, element: any, templateId: string, templateData: any): void {
if (templateId === WatchExpressionsRenderer.WATCH_EXPRESSION_TEMPLATE_ID) {
this.renderWatchExpression(tree, element, templateData);
} else {
renderVariable(tree, element, templateData, true);
}
}
private renderWatchExpression(tree: tree.ITree, watchExpression: debug.IExpression, data: IWatchExpressionTemplateData): void {
let selectedExpression = this.debugService.getViewModel().getSelectedExpression();
if ((selectedExpression instanceof model.Expression && selectedExpression.getId() === watchExpression.getId()) || (watchExpression instanceof model.Expression && !watchExpression.name)) {
renderRenameBox(this.debugService, this.contextViewService, tree, watchExpression, data.expression, {
initialValue: watchExpression.name,
placeholder: nls.localize('watchExpressionPlaceholder', "Expression to watch"),
ariaLabel: nls.localize('watchExpressionInputAriaLabel', "Type watch expression")
});
}
data.actionBar.context = watchExpression;
data.name.textContent = watchExpression.name;
if (watchExpression.value) {
data.name.textContent += ':';
renderExpressionValue(watchExpression, data.value, true, MAX_VALUE_RENDER_LENGTH_IN_VIEWLET);
data.name.title = watchExpression.type ? watchExpression.type : watchExpression.value;
}
}
public disposeTemplate(tree: tree.ITree, templateId: string, templateData: any): void {
if (templateId === WatchExpressionsRenderer.WATCH_EXPRESSION_TEMPLATE_ID) {
(<IWatchExpressionTemplateData>templateData).actionBar.dispose();
}
}
public dispose(): void {
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
export class WatchExpressionsAccessibilityProvider implements tree.IAccessibilityProvider {
public getAriaLabel(tree: tree.ITree, element: any): string {
if (element instanceof model.Expression) {
return nls.localize('watchExpressionAriaLabel', "{0} value {1}, watch, debug", (<model.Expression>element).name, (<model.Expression>element).value);
}
if (element instanceof model.Variable) {
return nls.localize('watchVariableAriaLabel', "{0} value {1}, watch, debug", (<model.Variable>element).name, (<model.Variable>element).value);
}
return null;
}
}
export class WatchExpressionsController extends BaseDebugController {
constructor(debugService: debug.IDebugService, contextMenuService: IContextMenuService, actionProvider: renderer.IActionProvider) {
super(debugService, contextMenuService, actionProvider);
if (isMacintosh) {
this.downKeyBindingDispatcher.set(KeyCode.Enter, this.onRename.bind(this));
} else {
this.downKeyBindingDispatcher.set(KeyCode.F2, this.onRename.bind(this));
}
}
protected onLeftClick(tree: tree.ITree, element: any, event: IMouseEvent): boolean {
// double click on primitive value: open input box to be able to select and copy value.
if (element instanceof model.Expression && event.detail === 2) {
const expression = <debug.IExpression>element;
if (expression.reference === 0) {
this.debugService.getViewModel().setSelectedExpression(expression);
}
return true;
}
return super.onLeftClick(tree, element, event);
}
protected onRename(tree: tree.ITree, event: KeyboardEvent): boolean {
const element = tree.getFocus();
if (element instanceof model.Expression) {
const watchExpression = <model.Expression>element;
if (watchExpression.reference === 0) {
this.debugService.getViewModel().setSelectedExpression(watchExpression);
}
return true;
}
return false;
}
protected onDelete(tree: tree.ITree, event: IKeyboardEvent): boolean {
const element = tree.getFocus();
if (element instanceof model.Expression) {
const we = <model.Expression>element;
this.debugService.removeWatchExpressions(we.getId());
return true;
}
return false;
}
}
// breakpoints
export class BreakpointsActionProvider implements renderer.IActionProvider {
constructor(private instantiationService: IInstantiationService) {
// noop
}
public hasActions(tree: tree.ITree, element: any): boolean {
return element instanceof model.Breakpoint;
}
public hasSecondaryActions(tree: tree.ITree, element: any): boolean {
return element instanceof model.Breakpoint || element instanceof model.ExceptionBreakpoint || element instanceof model.FunctionBreakpoint;
}
public getActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
if (element instanceof model.Breakpoint) {
return TPromise.as(this.getBreakpointActions());
}
return TPromise.as([]);
}
public getBreakpointActions(): actions.IAction[] {
return [this.instantiationService.createInstance(debugactions.RemoveBreakpointAction, debugactions.RemoveBreakpointAction.ID, debugactions.RemoveBreakpointAction.LABEL)];
}
public getSecondaryActions(tree: tree.ITree, element: any): TPromise<actions.IAction[]> {
const actions: actions.Action[] = [this.instantiationService.createInstance(debugactions.ToggleEnablementAction, debugactions.ToggleEnablementAction.ID, debugactions.ToggleEnablementAction.LABEL)];
actions.push(new actionbar.Separator());
if (element instanceof model.Breakpoint || element instanceof model.FunctionBreakpoint) {
actions.push(this.instantiationService.createInstance(debugactions.RemoveBreakpointAction, debugactions.RemoveBreakpointAction.ID, debugactions.RemoveBreakpointAction.LABEL));
}
actions.push(this.instantiationService.createInstance(debugactions.RemoveAllBreakpointsAction, debugactions.RemoveAllBreakpointsAction.ID, debugactions.RemoveAllBreakpointsAction.LABEL));
actions.push(new actionbar.Separator());
actions.push(this.instantiationService.createInstance(debugactions.ToggleBreakpointsActivatedAction, debugactions.ToggleBreakpointsActivatedAction.ID, debugactions.ToggleBreakpointsActivatedAction.ACTIVATE_LABEL));
actions.push(new actionbar.Separator());
actions.push(this.instantiationService.createInstance(debugactions.EnableAllBreakpointsAction, debugactions.EnableAllBreakpointsAction.ID, debugactions.EnableAllBreakpointsAction.LABEL));
actions.push(this.instantiationService.createInstance(debugactions.DisableAllBreakpointsAction, debugactions.DisableAllBreakpointsAction.ID, debugactions.DisableAllBreakpointsAction.LABEL));
actions.push(new actionbar.Separator());
actions.push(this.instantiationService.createInstance(debugactions.AddFunctionBreakpointAction, debugactions.AddFunctionBreakpointAction.ID, debugactions.AddFunctionBreakpointAction.LABEL));
if (element instanceof model.FunctionBreakpoint) {
actions.push(this.instantiationService.createInstance(debugactions.RenameFunctionBreakpointAction, debugactions.RenameFunctionBreakpointAction.ID, debugactions.RenameFunctionBreakpointAction.LABEL));
}
actions.push(new actionbar.Separator());
actions.push(this.instantiationService.createInstance(debugactions.ReapplyBreakpointsAction, debugactions.ReapplyBreakpointsAction.ID, debugactions.ReapplyBreakpointsAction.LABEL));
return TPromise.as(actions);
}
public getActionItem(tree: tree.ITree, element: any, action: actions.IAction): actionbar.IActionItem {
return null;
}
}
export class BreakpointsDataSource implements tree.IDataSource {
public getId(tree: tree.ITree, element: any): string {
return element.getId();
}
public hasChildren(tree: tree.ITree, element: any): boolean {
return element instanceof model.Model;
}
public getChildren(tree: tree.ITree, element: any): TPromise<any> {
const model = <model.Model>element;
const exBreakpoints = <debug.IEnablement[]>model.getExceptionBreakpoints();
return TPromise.as(exBreakpoints.concat(model.getFunctionBreakpoints()).concat(model.getBreakpoints()));
}
public getParent(tree: tree.ITree, element: any): TPromise<any> {
return TPromise.as(null);
}
}
interface IExceptionBreakpointTemplateData {
breakpoint: HTMLElement;
name: HTMLElement;
checkbox: HTMLInputElement;
toDisposeBeforeRender: lifecycle.IDisposable[];
}
interface IBreakpointTemplateData extends IExceptionBreakpointTemplateData {
actionBar: actionbar.ActionBar;
lineNumber: HTMLElement;
filePath: HTMLElement;
}
interface IFunctionBreakpointTemplateData extends IExceptionBreakpointTemplateData {
actionBar: actionbar.ActionBar;
}
export class BreakpointsRenderer implements tree.IRenderer {
private static EXCEPTION_BREAKPOINT_TEMPLATE_ID = 'exceptionBreakpoint';
private static FUNCTION_BREAKPOINT_TEMPLATE_ID = 'functionBreakpoint';
private static BREAKPOINT_TEMPLATE_ID = 'breakpoint';
constructor(
private actionProvider: BreakpointsActionProvider,
private actionRunner: actions.IActionRunner,
@IWorkspaceContextService private contextService: IWorkspaceContextService,
@debug.IDebugService private debugService: debug.IDebugService,
@IContextViewService private contextViewService: IContextViewService
) {
// noop
}
public getHeight(tree: tree.ITree, element: any): number {
return 22;
}
public getTemplateId(tree: tree.ITree, element: any): string {
if (element instanceof model.Breakpoint) {
return BreakpointsRenderer.BREAKPOINT_TEMPLATE_ID;
}
if (element instanceof model.FunctionBreakpoint) {
return BreakpointsRenderer.FUNCTION_BREAKPOINT_TEMPLATE_ID;
}
if (element instanceof model.ExceptionBreakpoint) {
return BreakpointsRenderer.EXCEPTION_BREAKPOINT_TEMPLATE_ID;
}
return null;
}
public renderTemplate(tree: tree.ITree, templateId: string, container: HTMLElement): any {
const data: IBreakpointTemplateData = Object.create(null);
if (templateId === BreakpointsRenderer.BREAKPOINT_TEMPLATE_ID || templateId === BreakpointsRenderer.FUNCTION_BREAKPOINT_TEMPLATE_ID) {
data.actionBar = new actionbar.ActionBar(container, { actionRunner: this.actionRunner });
data.actionBar.push(this.actionProvider.getBreakpointActions(), { icon: true, label: false });
}
data.breakpoint = dom.append(container, $('.breakpoint'));
data.toDisposeBeforeRender = [];
data.checkbox = <HTMLInputElement>$('input');
data.checkbox.type = 'checkbox';
dom.append(data.breakpoint, data.checkbox);
data.name = dom.append(data.breakpoint, $('span.name'));
if (templateId === BreakpointsRenderer.BREAKPOINT_TEMPLATE_ID) {
data.lineNumber = dom.append(data.breakpoint, $('span.line-number'));
data.filePath = dom.append(data.breakpoint, $('span.file-path'));
}
return data;
}
public renderElement(tree: tree.ITree, element: any, templateId: string, templateData: any): void {
templateData.toDisposeBeforeRender = lifecycle.dispose(templateData.toDisposeBeforeRender);
templateData.toDisposeBeforeRender.push(dom.addStandardDisposableListener(templateData.checkbox, 'change', (e) => {
this.debugService.enableOrDisableBreakpoints(!element.enabled, element);
}));
if (templateId === BreakpointsRenderer.EXCEPTION_BREAKPOINT_TEMPLATE_ID) {
this.renderExceptionBreakpoint(element, templateData);
} else if (templateId === BreakpointsRenderer.FUNCTION_BREAKPOINT_TEMPLATE_ID) {
this.renderFunctionBreakpoint(tree, element, templateData);
} else {
this.renderBreakpoint(tree, element, templateData);
}
}
private renderExceptionBreakpoint(exceptionBreakpoint: debug.IExceptionBreakpoint, data: IExceptionBreakpointTemplateData): void {
data.name.textContent = exceptionBreakpoint.label || `${exceptionBreakpoint.filter} exceptions`;;
data.breakpoint.title = data.name.textContent;
data.checkbox.checked = exceptionBreakpoint.enabled;
}
private renderFunctionBreakpoint(tree: tree.ITree, functionBreakpoint: debug.IFunctionBreakpoint, data: IFunctionBreakpointTemplateData): void {
const selected = this.debugService.getViewModel().getSelectedFunctionBreakpoint();
if (!functionBreakpoint.name || (selected && selected.getId() === functionBreakpoint.getId())) {
renderRenameBox(this.debugService, this.contextViewService, tree, functionBreakpoint, data.breakpoint, {
initialValue: functionBreakpoint.name,
placeholder: nls.localize('functionBreakpointPlaceholder', "Function to break on"),
ariaLabel: nls.localize('functionBreakPointInputAriaLabel', "Type function breakpoint")
});
} else {
data.name.textContent = functionBreakpoint.name;
data.checkbox.checked = functionBreakpoint.enabled;
data.breakpoint.title = functionBreakpoint.name;
// Mark function breakpoints as disabled if deactivated or if debug type does not support them #9099
const session = this.debugService.getViewModel().activeSession;
if ((session && !session.configuration.capabilities.supportsFunctionBreakpoints) || !this.debugService.getModel().areBreakpointsActivated()) {
tree.addTraits('disabled', [functionBreakpoint]);
if (session && !session.configuration.capabilities.supportsFunctionBreakpoints) {
data.breakpoint.title = nls.localize('functionBreakpointsNotSupported', "Function breakpoints are not supported by this debug type");
}
} else {
tree.removeTraits('disabled', [functionBreakpoint]);
}
}
data.actionBar.context = functionBreakpoint;
}
private renderBreakpoint(tree: tree.ITree, breakpoint: debug.IBreakpoint, data: IBreakpointTemplateData): void {
this.debugService.getModel().areBreakpointsActivated() ? tree.removeTraits('disabled', [breakpoint]) : tree.addTraits('disabled', [breakpoint]);
data.name.textContent = labels.getPathLabel(paths.basename(breakpoint.source.uri.fsPath), this.contextService);
data.lineNumber.textContent = breakpoint.desiredLineNumber !== breakpoint.lineNumber ? breakpoint.desiredLineNumber + ' \u2192 ' + breakpoint.lineNumber : '' + breakpoint.lineNumber;
data.filePath.textContent = labels.getPathLabel(paths.dirname(breakpoint.source.uri.fsPath), this.contextService);
data.checkbox.checked = breakpoint.enabled;
data.actionBar.context = breakpoint;
const debugActive = this.debugService.state === debug.State.Running || this.debugService.state === debug.State.Stopped || this.debugService.state === debug.State.Initializing;
if (debugActive && !breakpoint.verified) {
tree.addTraits('disabled', [breakpoint]);
if (breakpoint.message) {
data.breakpoint.title = breakpoint.message;
}
} else if (breakpoint.condition || breakpoint.hitCondition) {
data.breakpoint.title = breakpoint.condition ? breakpoint.condition : breakpoint.hitCondition;
}
}
public disposeTemplate(tree: tree.ITree, templateId: string, templateData: any): void {
if (templateId === BreakpointsRenderer.BREAKPOINT_TEMPLATE_ID || templateId === BreakpointsRenderer.FUNCTION_BREAKPOINT_TEMPLATE_ID) {
templateData.actionBar.dispose();
}
}
}
export class BreakpointsAccessibilityProvider implements tree.IAccessibilityProvider {
constructor( @IWorkspaceContextService private contextService: IWorkspaceContextService) {
// noop
}
public getAriaLabel(tree: tree.ITree, element: any): string {
if (element instanceof model.Breakpoint) {
return nls.localize('breakpointAriaLabel', "Breakpoint line {0} {1}, breakpoints, debug", (<model.Breakpoint>element).lineNumber, getSourceName((<model.Breakpoint>element).source, this.contextService));
}
if (element instanceof model.FunctionBreakpoint) {
return nls.localize('functionBreakpointAriaLabel', "Function breakpoint {0}, breakpoints, debug", (<model.FunctionBreakpoint>element).name);
}
if (element instanceof model.ExceptionBreakpoint) {
return nls.localize('exceptionBreakpointAriaLabel', "Exception breakpoint {0}, breakpoints, debug", (<model.ExceptionBreakpoint>element).filter);
}
return null;
}
}
export class BreakpointsController extends BaseDebugController {
constructor(debugService: debug.IDebugService, contextMenuService: IContextMenuService, actionProvider: renderer.IActionProvider) {
super(debugService, contextMenuService, actionProvider);
if (isMacintosh) {
this.downKeyBindingDispatcher.set(KeyCode.Enter, this.onRename.bind(this));
} else {
this.downKeyBindingDispatcher.set(KeyCode.F2, this.onRename.bind(this));
}
}
protected onLeftClick(tree: tree.ITree, element: any, event: IMouseEvent): boolean {
if (element instanceof model.FunctionBreakpoint && event.detail === 2) {
this.debugService.getViewModel().setSelectedFunctionBreakpoint(element);
return true;
}
if (element instanceof model.Breakpoint) {
this.openBreakpointSource(element, event, true);
}
return super.onLeftClick(tree, element, event);
}
protected onRename(tree: tree.ITree, event: IKeyboardEvent): boolean {
const element = tree.getFocus();
if (element instanceof model.FunctionBreakpoint && element.name) {
this.debugService.getViewModel().setSelectedFunctionBreakpoint(element);
return true;
}
if (element instanceof model.Breakpoint) {
this.openBreakpointSource(element, event, false);
}
return super.onEnter(tree, event);
}
protected onSpace(tree: tree.ITree, event: IKeyboardEvent): boolean {
super.onSpace(tree, event);
const element = <debug.IEnablement>tree.getFocus();
this.debugService.enableOrDisableBreakpoints(!element.enabled, element).done(null, errors.onUnexpectedError);
return true;
}
protected onDelete(tree: tree.ITree, event: IKeyboardEvent): boolean {
const element = tree.getFocus();
if (element instanceof model.Breakpoint) {
this.debugService.removeBreakpoints((<model.Breakpoint>element).getId()).done(null, errors.onUnexpectedError);
return true;
} else if (element instanceof model.FunctionBreakpoint) {
const fbp = <model.FunctionBreakpoint>element;
this.debugService.removeFunctionBreakpoints(fbp.getId()).done(null, errors.onUnexpectedError);
return true;
}
return false;
}
private openBreakpointSource(breakpoint: debug.IBreakpoint, event: IKeyboardEvent | IMouseEvent, preserveFocus: boolean): void {
if (!breakpoint.source.inMemory) {
const sideBySide = (event && (event.ctrlKey || event.metaKey));
this.debugService.openOrRevealSource(breakpoint.source, breakpoint.lineNumber, preserveFocus, sideBySide).done(null, errors.onUnexpectedError);
}
}
}
| src/vs/workbench/parts/debug/electron-browser/debugViewer.ts | 1 | https://github.com/microsoft/vscode/commit/bb194502143f100abe468b1328a54e33c62fd514 | [
0.9623364806175232,
0.007709946017712355,
0.00016003685595933348,
0.00016918143955990672,
0.08405262976884842
] |
{
"id": 3,
"code_window": [
"\t\t}));\n",
"\n",
"\t\tthis.toDispose.push(model.onDidChangeCallStack(() => {\n",
"\t\t\tconst session = this.debugService.getViewModel().activeSession;\n",
"\t\t\tconst threads = session ? model.getThreads(session.getId()) : Object.create(null);\n",
"\t\t\tconst threadsArray = Object.keys(threads).map(ref => threads[ref]);\n",
"\t\t\t// Only show the threads in the call stack if there is more than 1 thread.\n",
"\t\t\tconst newTreeInput = threadsArray.length === 1 ? threadsArray[0] : model;\n",
"\n",
"\t\t\tif (this.tree.getInput() === newTreeInput) {\n",
"\t\t\t\tthis.tree.refresh().done(null, errors.onUnexpectedError);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tlet newTreeInput: any = this.debugService.getModel();\n",
"\t\t\tconst sessions = this.debugService.getModel().getSessions();\n",
"\t\t\tif (sessions.length === 1) {\n",
"\t\t\t\tconst threads = sessions[0] ? model.getThreads(sessions[0].getId()) : Object.create(null);\n",
"\t\t\t\tconst threadsArray = Object.keys(threads).map(ref => threads[ref]);\n",
"\t\t\t\t// Only show the threads in the call stack if there is more than 1 thread.\n",
"\t\t\t\tnewTreeInput = threadsArray.length === 1 ? threadsArray[0] : sessions[0];\n",
"\t\t\t}\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugViews.ts",
"type": "replace",
"edit_start_line_idx": 292
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import 'vs/css!./keybindings';
import * as nls from 'vs/nls';
import { IHTMLContentElement } from 'vs/base/common/htmlContent';
import { KeyCode } from 'vs/base/common/keyCodes';
import { Keybinding } from 'vs/base/common/keybinding';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import Severity from 'vs/base/common/severity';
import { isFalsyOrEmpty } from 'vs/base/common/arrays';
import * as dom from 'vs/base/browser/dom';
import { IKeyboardEvent, StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { ICommandService, CommandsRegistry, ICommandHandlerDescription } from 'vs/platform/commands/common/commands';
import { KeybindingResolver } from 'vs/platform/keybinding/common/keybindingResolver';
import { IKeybindingItem, IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { KeybindingsRegistry } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { IStatusbarService } from 'vs/platform/statusbar/common/statusbar';
import { IMessageService } from 'vs/platform/message/common/message';
import Event, { Emitter } from 'vs/base/common/event';
export abstract class KeybindingService implements IKeybindingService {
public _serviceBrand: any;
protected toDispose: IDisposable[] = [];
private _cachedResolver: KeybindingResolver;
private _firstTimeComputingResolver: boolean;
private _currentChord: number;
private _currentChordStatusMessage: IDisposable;
private _onDidUpdateKeybindings: Emitter<void>;
private _contextKeyService: IContextKeyService;
protected _commandService: ICommandService;
private _statusService: IStatusbarService;
private _messageService: IMessageService;
constructor(
contextKeyService: IContextKeyService,
commandService: ICommandService,
messageService: IMessageService,
statusService?: IStatusbarService
) {
this._contextKeyService = contextKeyService;
this._commandService = commandService;
this._statusService = statusService;
this._messageService = messageService;
this._cachedResolver = null;
this._firstTimeComputingResolver = true;
this._currentChord = 0;
this._currentChordStatusMessage = null;
this._onDidUpdateKeybindings = new Emitter<void>();
this.toDispose.push(this._onDidUpdateKeybindings);
}
public dispose(): void {
this.toDispose = dispose(this.toDispose);
}
protected _beginListening(domNode: HTMLElement): void {
this.toDispose.push(dom.addDisposableListener(domNode, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => {
let keyEvent = new StandardKeyboardEvent(e);
this._dispatch(keyEvent);
}));
}
private _getResolver(): KeybindingResolver {
if (!this._cachedResolver) {
this._cachedResolver = new KeybindingResolver(KeybindingsRegistry.getDefaultKeybindings(), this._getExtraKeybindings(this._firstTimeComputingResolver));
this._firstTimeComputingResolver = false;
}
return this._cachedResolver;
}
get onDidUpdateKeybindings(): Event<void> {
return this._onDidUpdateKeybindings ? this._onDidUpdateKeybindings.event : Event.None; // Sinon stubbing walks properties on prototype
}
public getLabelFor(keybinding: Keybinding): string {
return keybinding._toUSLabel();
}
public getHTMLLabelFor(keybinding: Keybinding): IHTMLContentElement[] {
return keybinding._toUSHTMLLabel();
}
public getAriaLabelFor(keybinding: Keybinding): string {
return keybinding._toUSAriaLabel();
}
public getElectronAcceleratorFor(keybinding: Keybinding): string {
return keybinding._toElectronAccelerator();
}
protected updateResolver(): void {
this._cachedResolver = null;
this._onDidUpdateKeybindings.fire();
}
protected _getExtraKeybindings(isFirstTime: boolean): IKeybindingItem[] {
return [];
}
public getDefaultKeybindings(): string {
return this._getResolver().getDefaultKeybindings() + '\n\n' + this._getAllCommandsAsComment();
}
public customKeybindingsCount(): number {
return 0;
}
public lookupKeybindings(commandId: string): Keybinding[] {
return this._getResolver().lookupKeybinding(commandId);
}
private _getAllCommandsAsComment(): string {
const commands = CommandsRegistry.getCommands();
const unboundCommands: string[] = [];
const boundCommands = this._getResolver().getDefaultBoundCommands();
for (let id in commands) {
if (id[0] === '_' || id.indexOf('vscode.') === 0) { // private command
continue;
}
if (typeof commands[id].description === 'object'
&& !isFalsyOrEmpty((<ICommandHandlerDescription>commands[id].description).args)) { // command with args
continue;
}
if (boundCommands[id]) {
continue;
}
unboundCommands.push(id);
}
let pretty = unboundCommands.sort().join('\n// - ');
return '// ' + nls.localize('unboundCommands', "Here are other available commands: ") + '\n// - ' + pretty;
}
protected _dispatch(e: IKeyboardEvent): void {
let isModifierKey = (e.keyCode === KeyCode.Ctrl || e.keyCode === KeyCode.Shift || e.keyCode === KeyCode.Alt || e.keyCode === KeyCode.Meta);
if (isModifierKey) {
return;
}
let contextValue = this._contextKeyService.getContextValue(e.target);
// console.log(JSON.stringify(contextValue, null, '\t'));
let resolveResult = this._getResolver().resolve(contextValue, this._currentChord, e.asKeybinding());
if (resolveResult && resolveResult.enterChord) {
e.preventDefault();
this._currentChord = resolveResult.enterChord;
if (this._statusService) {
let firstPartLabel = this.getLabelFor(new Keybinding(this._currentChord));
this._currentChordStatusMessage = this._statusService.setStatusMessage(nls.localize('first.chord', "({0}) was pressed. Waiting for second key of chord...", firstPartLabel));
}
return;
}
if (this._statusService && this._currentChord) {
if (!resolveResult || !resolveResult.commandId) {
let firstPartLabel = this.getLabelFor(new Keybinding(this._currentChord));
let chordPartLabel = this.getLabelFor(new Keybinding(e.asKeybinding()));
this._statusService.setStatusMessage(nls.localize('missing.chord', "The key combination ({0}, {1}) is not a command.", firstPartLabel, chordPartLabel), 10 * 1000 /* 10s */);
e.preventDefault();
}
}
if (this._currentChordStatusMessage) {
this._currentChordStatusMessage.dispose();
this._currentChordStatusMessage = null;
}
this._currentChord = 0;
if (resolveResult && resolveResult.commandId) {
if (!/^\^/.test(resolveResult.commandId)) {
e.preventDefault();
}
let commandId = resolveResult.commandId.replace(/^\^/, '');
this._commandService.executeCommand(commandId, {}).done(undefined, err => {
this._messageService.show(Severity.Warning, err);
});
}
}
} | src/vs/platform/keybinding/browser/keybindingServiceImpl.ts | 0 | https://github.com/microsoft/vscode/commit/bb194502143f100abe468b1328a54e33c62fd514 | [
0.0011629265500232577,
0.00022169081785250455,
0.00016072348807938397,
0.0001710500509943813,
0.00021612101409118623
] |
{
"id": 3,
"code_window": [
"\t\t}));\n",
"\n",
"\t\tthis.toDispose.push(model.onDidChangeCallStack(() => {\n",
"\t\t\tconst session = this.debugService.getViewModel().activeSession;\n",
"\t\t\tconst threads = session ? model.getThreads(session.getId()) : Object.create(null);\n",
"\t\t\tconst threadsArray = Object.keys(threads).map(ref => threads[ref]);\n",
"\t\t\t// Only show the threads in the call stack if there is more than 1 thread.\n",
"\t\t\tconst newTreeInput = threadsArray.length === 1 ? threadsArray[0] : model;\n",
"\n",
"\t\t\tif (this.tree.getInput() === newTreeInput) {\n",
"\t\t\t\tthis.tree.refresh().done(null, errors.onUnexpectedError);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tlet newTreeInput: any = this.debugService.getModel();\n",
"\t\t\tconst sessions = this.debugService.getModel().getSessions();\n",
"\t\t\tif (sessions.length === 1) {\n",
"\t\t\t\tconst threads = sessions[0] ? model.getThreads(sessions[0].getId()) : Object.create(null);\n",
"\t\t\t\tconst threadsArray = Object.keys(threads).map(ref => threads[ref]);\n",
"\t\t\t\t// Only show the threads in the call stack if there is more than 1 thread.\n",
"\t\t\t\tnewTreeInput = threadsArray.length === 1 ? threadsArray[0] : sessions[0];\n",
"\t\t\t}\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugViews.ts",
"type": "replace",
"edit_start_line_idx": 292
} | [
{
"c": "pick",
"t": "commit-command.function.git-rebase.meta.support",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.support.function.git-rebase rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.support.function.git-rebase rgb(4, 81, 165)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.support.function.git-rebase rgb(156, 220, 254)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.support.function.git-rebase rgb(4, 81, 165)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.support.function.git-rebase rgb(212, 212, 212)"
}
},
{
"c": " ",
"t": "commit-command.git-rebase.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "1fc6c95",
"t": "commit-command.constant.git-rebase.meta.sha",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.constant.sha.git-rebase rgb(181, 206, 168)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.constant.sha.git-rebase rgb(9, 136, 90)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.constant.sha.git-rebase rgb(181, 206, 168)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.constant.sha.git-rebase rgb(9, 136, 90)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.constant.sha.git-rebase rgb(181, 206, 168)"
}
},
{
"c": " ",
"t": "commit-command.git-rebase.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "Patch A",
"t": "commit-command.commit-message.git-rebase.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "squash",
"t": "commit-command.function.git-rebase.meta.support",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.support.function.git-rebase rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.support.function.git-rebase rgb(4, 81, 165)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.support.function.git-rebase rgb(156, 220, 254)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.support.function.git-rebase rgb(4, 81, 165)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.support.function.git-rebase rgb(212, 212, 212)"
}
},
{
"c": " ",
"t": "commit-command.git-rebase.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "fa39187",
"t": "commit-command.constant.git-rebase.meta.sha",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.constant.sha.git-rebase rgb(181, 206, 168)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.constant.sha.git-rebase rgb(9, 136, 90)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.constant.sha.git-rebase rgb(181, 206, 168)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.constant.sha.git-rebase rgb(9, 136, 90)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.constant.sha.git-rebase rgb(181, 206, 168)"
}
},
{
"c": " ",
"t": "commit-command.git-rebase.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "Something to add to patch A",
"t": "commit-command.commit-message.git-rebase.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "pick",
"t": "commit-command.function.git-rebase.meta.support",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.support.function.git-rebase rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.support.function.git-rebase rgb(4, 81, 165)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.support.function.git-rebase rgb(156, 220, 254)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.support.function.git-rebase rgb(4, 81, 165)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.support.function.git-rebase rgb(212, 212, 212)"
}
},
{
"c": " ",
"t": "commit-command.git-rebase.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "7b36971",
"t": "commit-command.constant.git-rebase.meta.sha",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.constant.sha.git-rebase rgb(181, 206, 168)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.constant.sha.git-rebase rgb(9, 136, 90)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.constant.sha.git-rebase rgb(181, 206, 168)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.constant.sha.git-rebase rgb(9, 136, 90)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.constant.sha.git-rebase rgb(181, 206, 168)"
}
},
{
"c": " ",
"t": "commit-command.git-rebase.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "Something to move before patch B",
"t": "commit-command.commit-message.git-rebase.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "pick",
"t": "commit-command.function.git-rebase.meta.support",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.support.function.git-rebase rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.support.function.git-rebase rgb(4, 81, 165)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.support.function.git-rebase rgb(156, 220, 254)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.support.function.git-rebase rgb(4, 81, 165)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.support.function.git-rebase rgb(212, 212, 212)"
}
},
{
"c": " ",
"t": "commit-command.git-rebase.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "6b2481b",
"t": "commit-command.constant.git-rebase.meta.sha",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.constant.sha.git-rebase rgb(181, 206, 168)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.constant.sha.git-rebase rgb(9, 136, 90)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.constant.sha.git-rebase rgb(181, 206, 168)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.constant.sha.git-rebase rgb(9, 136, 90)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.constant.sha.git-rebase rgb(181, 206, 168)"
}
},
{
"c": " ",
"t": "commit-command.git-rebase.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "Patch B",
"t": "commit-command.commit-message.git-rebase.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "fixup",
"t": "commit-command.function.git-rebase.meta.support",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.support.function.git-rebase rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.support.function.git-rebase rgb(4, 81, 165)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.support.function.git-rebase rgb(156, 220, 254)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.support.function.git-rebase rgb(4, 81, 165)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.support.function.git-rebase rgb(212, 212, 212)"
}
},
{
"c": " ",
"t": "commit-command.git-rebase.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "c619268",
"t": "commit-command.constant.git-rebase.meta.sha",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.constant.sha.git-rebase rgb(181, 206, 168)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.constant.sha.git-rebase rgb(9, 136, 90)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.constant.sha.git-rebase rgb(181, 206, 168)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.constant.sha.git-rebase rgb(9, 136, 90)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.constant.sha.git-rebase rgb(181, 206, 168)"
}
},
{
"c": " ",
"t": "commit-command.git-rebase.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "A fix for Patch B",
"t": "commit-command.commit-message.git-rebase.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "edit",
"t": "commit-command.function.git-rebase.meta.support",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.support.function.git-rebase rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.support.function.git-rebase rgb(4, 81, 165)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.support.function.git-rebase rgb(156, 220, 254)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.support.function.git-rebase rgb(4, 81, 165)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.support.function.git-rebase rgb(212, 212, 212)"
}
},
{
"c": " ",
"t": "commit-command.git-rebase.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "dd1475d",
"t": "commit-command.constant.git-rebase.meta.sha",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.constant.sha.git-rebase rgb(181, 206, 168)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.constant.sha.git-rebase rgb(9, 136, 90)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.constant.sha.git-rebase rgb(181, 206, 168)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.constant.sha.git-rebase rgb(9, 136, 90)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.constant.sha.git-rebase rgb(181, 206, 168)"
}
},
{
"c": " ",
"t": "commit-command.git-rebase.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "Something I want to split",
"t": "commit-command.commit-message.git-rebase.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "reword",
"t": "commit-command.function.git-rebase.meta.support",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.support.function.git-rebase rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.support.function.git-rebase rgb(4, 81, 165)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.support.function.git-rebase rgb(156, 220, 254)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.support.function.git-rebase rgb(4, 81, 165)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.support.function.git-rebase rgb(212, 212, 212)"
}
},
{
"c": " ",
"t": "commit-command.git-rebase.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "4ca2acc",
"t": "commit-command.constant.git-rebase.meta.sha",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.constant.sha.git-rebase rgb(181, 206, 168)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.constant.sha.git-rebase rgb(9, 136, 90)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.constant.sha.git-rebase rgb(181, 206, 168)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.constant.sha.git-rebase rgb(9, 136, 90)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.constant.sha.git-rebase rgb(181, 206, 168)"
}
},
{
"c": " ",
"t": "commit-command.git-rebase.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "i cant' typ goods",
"t": "commit-command.commit-message.git-rebase.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "#",
"t": "comment.definition.git-rebase.line.number-sign.punctuation",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgb(96, 139, 78)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgb(0, 128, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgb(96, 139, 78)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgb(0, 128, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgb(124, 166, 104)"
}
},
{
"c": " Commands:",
"t": "comment.git-rebase.line.number-sign",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgb(96, 139, 78)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgb(0, 128, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgb(96, 139, 78)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgb(0, 128, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgb(124, 166, 104)"
}
},
{
"c": "#",
"t": "comment.definition.git-rebase.line.number-sign.punctuation",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgb(96, 139, 78)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgb(0, 128, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgb(96, 139, 78)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgb(0, 128, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgb(124, 166, 104)"
}
},
{
"c": " p, pick = use commit",
"t": "comment.git-rebase.line.number-sign",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgb(96, 139, 78)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgb(0, 128, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgb(96, 139, 78)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgb(0, 128, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgb(124, 166, 104)"
}
},
{
"c": "#",
"t": "comment.definition.git-rebase.line.number-sign.punctuation",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgb(96, 139, 78)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgb(0, 128, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgb(96, 139, 78)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgb(0, 128, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgb(124, 166, 104)"
}
},
{
"c": " r, reword = use commit, but edit the commit message",
"t": "comment.git-rebase.line.number-sign",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgb(96, 139, 78)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgb(0, 128, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgb(96, 139, 78)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgb(0, 128, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgb(124, 166, 104)"
}
},
{
"c": "#",
"t": "comment.definition.git-rebase.line.number-sign.punctuation",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgb(96, 139, 78)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgb(0, 128, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgb(96, 139, 78)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgb(0, 128, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgb(124, 166, 104)"
}
},
{
"c": " e, edit = use commit, but stop for amending",
"t": "comment.git-rebase.line.number-sign",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgb(96, 139, 78)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgb(0, 128, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgb(96, 139, 78)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgb(0, 128, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgb(124, 166, 104)"
}
},
{
"c": "#",
"t": "comment.definition.git-rebase.line.number-sign.punctuation",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgb(96, 139, 78)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgb(0, 128, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgb(96, 139, 78)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgb(0, 128, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgb(124, 166, 104)"
}
},
{
"c": " s, squash = use commit, but meld into previous commit",
"t": "comment.git-rebase.line.number-sign",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgb(96, 139, 78)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgb(0, 128, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgb(96, 139, 78)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgb(0, 128, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgb(124, 166, 104)"
}
},
{
"c": "#",
"t": "comment.definition.git-rebase.line.number-sign.punctuation",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgb(96, 139, 78)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgb(0, 128, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgb(96, 139, 78)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgb(0, 128, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgb(124, 166, 104)"
}
},
{
"c": " f, fixup = like \"squash\", but discard this commit's log message",
"t": "comment.git-rebase.line.number-sign",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgb(96, 139, 78)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgb(0, 128, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgb(96, 139, 78)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgb(0, 128, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgb(124, 166, 104)"
}
},
{
"c": "#",
"t": "comment.definition.git-rebase.line.number-sign.punctuation",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgb(96, 139, 78)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgb(0, 128, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgb(96, 139, 78)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgb(0, 128, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgb(124, 166, 104)"
}
},
{
"c": " x, exec = run command (the rest of the line) using shell",
"t": "comment.git-rebase.line.number-sign",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgb(96, 139, 78)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgb(0, 128, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgb(96, 139, 78)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgb(0, 128, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgb(124, 166, 104)"
}
}
] | extensions/git/test/colorize-results/git-rebase-todo.json | 0 | https://github.com/microsoft/vscode/commit/bb194502143f100abe468b1328a54e33c62fd514 | [
0.00017698478768579662,
0.00017410487635061145,
0.00016550751752220094,
0.0001745170447975397,
0.000002347871713936911
] |
{
"id": 3,
"code_window": [
"\t\t}));\n",
"\n",
"\t\tthis.toDispose.push(model.onDidChangeCallStack(() => {\n",
"\t\t\tconst session = this.debugService.getViewModel().activeSession;\n",
"\t\t\tconst threads = session ? model.getThreads(session.getId()) : Object.create(null);\n",
"\t\t\tconst threadsArray = Object.keys(threads).map(ref => threads[ref]);\n",
"\t\t\t// Only show the threads in the call stack if there is more than 1 thread.\n",
"\t\t\tconst newTreeInput = threadsArray.length === 1 ? threadsArray[0] : model;\n",
"\n",
"\t\t\tif (this.tree.getInput() === newTreeInput) {\n",
"\t\t\t\tthis.tree.refresh().done(null, errors.onUnexpectedError);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tlet newTreeInput: any = this.debugService.getModel();\n",
"\t\t\tconst sessions = this.debugService.getModel().getSessions();\n",
"\t\t\tif (sessions.length === 1) {\n",
"\t\t\t\tconst threads = sessions[0] ? model.getThreads(sessions[0].getId()) : Object.create(null);\n",
"\t\t\t\tconst threadsArray = Object.keys(threads).map(ref => threads[ref]);\n",
"\t\t\t\t// Only show the threads in the call stack if there is more than 1 thread.\n",
"\t\t\t\tnewTreeInput = threadsArray.length === 1 ? threadsArray[0] : sessions[0];\n",
"\t\t\t}\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugViews.ts",
"type": "replace",
"edit_start_line_idx": 292
} | /*---------------------------------------------------------------------------------------------
* 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 { TPromise } from 'vs/base/common/winjs.base';
import { getNextTickChannel } from 'vs/base/parts/ipc/common/ipc';
import { Client } from 'vs/base/parts/ipc/node/ipc.cp';
import uri from 'vs/base/common/uri';
import { EventType } from 'vs/platform/files/common/files';
import { toFileChangesEvent, IRawFileChange } from 'vs/workbench/services/files/node/watcher/common';
import { IEventService } from 'vs/platform/event/common/event';
import { IWatcherChannel, WatcherChannelClient } from 'vs/workbench/services/files/node/watcher/unix/watcherIpc';
export class FileWatcher {
private static MAX_RESTARTS = 5;
private isDisposed: boolean;
private restartCounter: number;
constructor(
private basePath: string,
private ignored: string[],
private eventEmitter: IEventService,
private errorLogger: (msg: string) => void,
private verboseLogging: boolean
) {
this.isDisposed = false;
this.restartCounter = 0;
}
public startWatching(): () => void {
const args = ['--type=watcherService'];
const client = new Client(
uri.parse(require.toUrl('bootstrap')).fsPath,
{
serverName: 'Watcher',
args,
env: {
AMD_ENTRYPOINT: 'vs/workbench/services/files/node/watcher/unix/watcherApp',
PIPE_LOGGING: 'true',
VERBOSE_LOGGING: this.verboseLogging
}
}
);
const channel = getNextTickChannel(client.getChannel<IWatcherChannel>('watcher'));
const service = new WatcherChannelClient(channel);
// Start watching
service.watch({ basePath: this.basePath, ignored: this.ignored, verboseLogging: this.verboseLogging }).then(null, (err) => {
if (!(err instanceof Error && err.name === 'Canceled' && err.message === 'Canceled')) {
return TPromise.wrapError(err); // the service lib uses the promise cancel error to indicate the process died, we do not want to bubble this up
}
}, (events: IRawFileChange[]) => this.onRawFileEvents(events)).done(() => {
// our watcher app should never be completed because it keeps on watching. being in here indicates
// that the watcher process died and we want to restart it here. we only do it a max number of times
if (!this.isDisposed) {
if (this.restartCounter <= FileWatcher.MAX_RESTARTS) {
this.errorLogger('Watcher terminated unexpectedly and is restarted again...');
this.restartCounter++;
this.startWatching();
} else {
this.errorLogger('Watcher failed to start after retrying for some time, giving up. Please report this as a bug report!');
}
}
}, this.errorLogger);
return () => {
client.dispose();
this.isDisposed = true;
};
}
private onRawFileEvents(events: IRawFileChange[]): void {
// Emit through broadcast service
if (events.length > 0) {
this.eventEmitter.emit(EventType.FILE_CHANGES, toFileChangesEvent(events));
}
}
} | src/vs/workbench/services/files/node/watcher/unix/watcherService.ts | 0 | https://github.com/microsoft/vscode/commit/bb194502143f100abe468b1328a54e33c62fd514 | [
0.00017516054504085332,
0.0001689133350737393,
0.00016233453061431646,
0.00016867430531419814,
0.000003928884780179942
] |
{
"id": 0,
"code_window": [
"import React, { Fragment } from 'react';\n",
"import { styled, withTheme } from '@storybook/theming';\n",
"import { ScrollArea, TabsState } from '@storybook/components';\n",
"import { SizeMe } from 'react-sizeme';\n",
"import Result from './Result';\n",
"import provideJestResult, { Test } from '../hoc/provideJestResult';\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { ScrollArea, TabsState, Link, Placeholder } from '@storybook/components';\n"
],
"file_path": "addons/jest/src/components/Panel.tsx",
"type": "replace",
"edit_start_line_idx": 2
} | import React, { Fragment } from 'react';
import { styled, withTheme } from '@storybook/theming';
import { ScrollArea, TabsState } from '@storybook/components';
import { SizeMe } from 'react-sizeme';
import Result from './Result';
import provideJestResult, { Test } from '../hoc/provideJestResult';
const List = styled.ul({
listStyle: 'none',
fontSize: 14,
padding: 0,
margin: 0,
});
const Item = styled.li({
display: 'block',
padding: 0,
});
const NoTests = styled.div({
padding: '10px 20px',
flex: 1,
});
const ProgressWrapper = styled.div({
position: 'relative',
height: '10px',
});
const SuiteHead = styled.div({
display: 'flex',
alignItems: 'baseline',
position: 'absolute',
zIndex: 2,
right: '50px',
marginTop: '15px',
});
const SuiteTotals = styled(({ successNumber, failedNumber, result, className, width }) => (
<div className={className}>
<Fragment>
{width > 325 ? (
<div>
{result.assertionResults.length} {result.assertionResults.length > 1 ? `tests` : `test`}
</div>
) : null}
{width > 280 ? (
<div>
{result.endTime - result.startTime}
ms
</div>
) : null}
</Fragment>
</div>
))(({ theme }) => ({
display: 'flex',
alignItems: 'center',
color: theme.color.dark,
fontSize: '14px',
marginTop: '-5px',
'& > *': {
marginRight: 10,
},
}));
const SuiteProgress = styled(({ successNumber, result, className }) => (
<div className={className} role="progressbar">
<span style={{ width: `${(successNumber / result.assertionResults.length) * 100}%` }} />
</div>
))(({ theme }) => ({
width: '30px',
backgroundColor: theme.color.negative,
height: '6px',
top: '3px',
position: 'absolute',
left: 0,
overflow: 'hidden',
appearance: 'none',
'& > span': {
backgroundColor: theme.color.positive,
bottom: 0,
position: 'absolute',
left: 0,
top: 0,
},
}));
interface ContentProps {
tests: Test[];
className?: string;
}
const Content = styled(({ tests, className }: ContentProps) => (
<div className={className}>
{tests.map(({ name, result }) => {
if (!result) {
return <NoTests key={name}>This story has tests configured, but no file was found</NoTests>;
}
const successNumber = result.assertionResults.filter(({ status }) => status === 'passed')
.length;
const failedNumber = result.assertionResults.length - successNumber;
const passingRate = ((successNumber / result.assertionResults.length) * 100).toFixed(2);
return (
<SizeMe refreshMode="debounce">
{({ size }: { size: any }) => {
const { width } = size;
return (
<section key={name}>
<SuiteHead>
<SuiteTotals {...{ successNumber, failedNumber, result, passingRate, width }} />
{width > 240 ? (
<ProgressWrapper>
<SuiteProgress {...{ successNumber, failedNumber, result }} />
</ProgressWrapper>
) : null}
</SuiteHead>
<TabsState initial="failing-tests" backgroundColor="rgba(0,0,0,.05)">
<div id="failing-tests" title={`${failedNumber} Failed`} color="#FF4400">
<List>
{result.assertionResults.map(res => {
return res.status === 'failed' ? (
<Item key={res.fullName || res.title}>
<Result {...res} />
</Item>
) : null;
})}
</List>
</div>
<div id="passing-tests" title={`${successNumber} Passed`} color="#66BF3C">
<List>
{result.assertionResults.map(res => {
return res.status === 'passed' ? (
<Item key={res.fullName || res.title}>
<Result {...res} />
</Item>
) : null;
})}
</List>
</div>
</TabsState>
</section>
);
}}
</SizeMe>
);
})}
</div>
))({
flex: '1 1 0%',
});
const ContentWithTheme = withTheme(Content);
interface PanelProps {
tests: null | Test[];
}
const Panel = ({ tests }: PanelProps) => (
<ScrollArea vertical>
{tests ? (
<ContentWithTheme tests={tests} />
) : (
<NoTests>This story has no tests configured</NoTests>
)}
</ScrollArea>
);
Panel.defaultProps = {
tests: null,
};
export default provideJestResult(Panel);
| addons/jest/src/components/Panel.tsx | 1 | https://github.com/storybookjs/storybook/commit/8388e6b58dd930ec07e8bacd8f5b3865425201fc | [
0.9939193725585938,
0.05553404241800308,
0.00016393860278185457,
0.00019053670985158533,
0.22759217023849487
] |
{
"id": 0,
"code_window": [
"import React, { Fragment } from 'react';\n",
"import { styled, withTheme } from '@storybook/theming';\n",
"import { ScrollArea, TabsState } from '@storybook/components';\n",
"import { SizeMe } from 'react-sizeme';\n",
"import Result from './Result';\n",
"import provideJestResult, { Test } from '../hoc/provideJestResult';\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { ScrollArea, TabsState, Link, Placeholder } from '@storybook/components';\n"
],
"file_path": "addons/jest/src/components/Panel.tsx",
"type": "replace",
"edit_start_line_idx": 2
} | /* eslint-disable */
import React from 'react';
import Button from './Button';
import { storiesOf } from '@storybook/react';
export default {
title: 'foo',
};
const bar = 1;
storiesOf('foo', module).add('bar', () => <Button />);
| lib/codemod/src/transforms/__testfixtures__/storiesof-to-csf/module.output.js | 0 | https://github.com/storybookjs/storybook/commit/8388e6b58dd930ec07e8bacd8f5b3865425201fc | [
0.000170299899764359,
0.00016817654250189662,
0.00016605319979134947,
0.00016817654250189662,
0.0000021233499865047634
] |
{
"id": 0,
"code_window": [
"import React, { Fragment } from 'react';\n",
"import { styled, withTheme } from '@storybook/theming';\n",
"import { ScrollArea, TabsState } from '@storybook/components';\n",
"import { SizeMe } from 'react-sizeme';\n",
"import Result from './Result';\n",
"import provideJestResult, { Test } from '../hoc/provideJestResult';\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { ScrollArea, TabsState, Link, Placeholder } from '@storybook/components';\n"
],
"file_path": "addons/jest/src/components/Panel.tsx",
"type": "replace",
"edit_start_line_idx": 2
} | import path from 'path';
import fs from 'fs';
import types, { supportedFrameworks } from './project_types';
import { getBowerJson, getPackageJson } from './helpers';
function detectFramework(dependencies) {
if (!dependencies) {
return false;
}
if (
dependencies.devDependencies &&
(dependencies.devDependencies['vue-loader'] || dependencies.devDependencies.vueify)
) {
return types.SFC_VUE;
}
if (
(dependencies.dependencies && dependencies.dependencies.vue) ||
(dependencies.devDependencies && dependencies.devDependencies.vue) ||
(dependencies.dependencies && dependencies.dependencies.nuxt) ||
(dependencies.devDependencies && dependencies.devDependencies.nuxt)
) {
return types.VUE;
}
if (
(dependencies.dependencies && dependencies.dependencies['ember-cli']) ||
(dependencies.devDependencies && dependencies.devDependencies['ember-cli'])
) {
return types.EMBER;
}
if (
(dependencies.dependencies && dependencies.dependencies['react-scripts']) ||
(dependencies.devDependencies && dependencies.devDependencies['react-scripts']) ||
// For projects using a custom/forked `react-scripts` package.
fs.existsSync(path.join(process.cwd(), '/node_modules/.bin/react-scripts'))
) {
return types.REACT_SCRIPTS;
}
if (
((dependencies.devDependencies && dependencies.devDependencies.webpack) ||
(dependencies.dependencies && dependencies.dependencies.webpack)) &&
((dependencies.devDependencies && dependencies.devDependencies.react) ||
(dependencies.dependencies && dependencies.dependencies.react))
) {
return types.WEBPACK_REACT;
}
if (dependencies.peerDependencies && dependencies.peerDependencies.react) {
return types.REACT_PROJECT;
}
if (
(dependencies.dependencies && dependencies.dependencies['react-native']) ||
(dependencies.dependencies && dependencies.dependencies['react-native-scripts']) ||
(dependencies.devDependencies && dependencies.devDependencies['react-native-scripts'])
) {
return types.REACT_NATIVE;
}
if (
(dependencies.dependencies && dependencies.dependencies.react) ||
(dependencies.devDependencies && dependencies.devDependencies.react)
) {
return types.REACT;
}
if (
(dependencies.dependencies && dependencies.dependencies['@angular/core']) ||
(dependencies.devDependencies && dependencies.devDependencies['@angular/core'])
) {
return types.ANGULAR;
}
if (
(dependencies.dependencies && dependencies.dependencies['@polymer/polymer']) ||
(dependencies.devDependencies && dependencies.devDependencies['@polymer/polymer']) ||
(dependencies.dependencies && dependencies.dependencies.polymer) ||
(dependencies.devDependencies && dependencies.devDependencies.polymer)
) {
return types.POLYMER;
}
if (
(dependencies.dependencies && dependencies.dependencies.mithril) ||
(dependencies.devDependencies && dependencies.devDependencies.mithril)
) {
return types.MITHRIL;
}
if (
(dependencies.dependencies && dependencies.dependencies.marko) ||
(dependencies.devDependencies && dependencies.devDependencies.marko)
) {
return types.MARKO;
}
if (
(dependencies.dependencies && dependencies.dependencies.riot) ||
(dependencies.devDependencies && dependencies.devDependencies.riot)
) {
return types.RIOT;
}
if (
(dependencies.dependencies && dependencies.dependencies.preact) ||
(dependencies.devDependencies && dependencies.devDependencies.preact)
) {
return types.PREACT;
}
if (
(dependencies.dependencies && dependencies.dependencies.rax) ||
(dependencies.devDependencies && dependencies.devDependencies.rax)
) {
return types.RAX;
}
return false;
}
export function isStorybookInstalled(dependencies, force) {
if (!dependencies) {
return false;
}
if (!force && dependencies.devDependencies) {
if (
supportedFrameworks.reduce(
(storybookPresent, framework) =>
storybookPresent || dependencies.devDependencies[`@storybook/${framework}`],
false
)
) {
return types.ALREADY_HAS_STORYBOOK;
}
if (
dependencies.devDependencies['@kadira/storybook'] ||
dependencies.devDependencies['@kadira/react-native-storybook']
) {
return types.UPDATE_PACKAGE_ORGANIZATIONS;
}
}
return false;
}
export default function detect(options) {
if (options.html) {
return types.HTML;
}
const packageJson = getPackageJson();
const bowerJson = getBowerJson();
if (!packageJson && !bowerJson) {
return types.UNDETECTED;
}
if (fs.existsSync(path.resolve('.meteor'))) {
return types.METEOR;
}
const storyBookInstalled = isStorybookInstalled(packageJson, options.force);
if (storyBookInstalled) {
return storyBookInstalled;
}
return detectFramework(packageJson) || detectFramework(bowerJson) || types.UNDETECTED;
}
| lib/cli/lib/detect.js | 0 | https://github.com/storybookjs/storybook/commit/8388e6b58dd930ec07e8bacd8f5b3865425201fc | [
0.00019104090461041778,
0.00017471490718889982,
0.00016711026546545327,
0.00017431072774343193,
0.0000053097564887139015
] |
{
"id": 0,
"code_window": [
"import React, { Fragment } from 'react';\n",
"import { styled, withTheme } from '@storybook/theming';\n",
"import { ScrollArea, TabsState } from '@storybook/components';\n",
"import { SizeMe } from 'react-sizeme';\n",
"import Result from './Result';\n",
"import provideJestResult, { Test } from '../hoc/provideJestResult';\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { ScrollArea, TabsState, Link, Placeholder } from '@storybook/components';\n"
],
"file_path": "addons/jest/src/components/Panel.tsx",
"type": "replace",
"edit_start_line_idx": 2
} | /* eslint-disable no-underscore-dangle */
import { logger } from '@storybook/client-logger';
import { mockChannel } from '@storybook/addons';
import ClientApi from './client_api';
import ConfigApi from './config_api';
import StoryStore from './story_store';
export const getContext = (() => decorateStory => {
const channel = mockChannel();
const storyStore = new StoryStore({ channel });
const clientApi = new ClientApi({ storyStore, decorateStory });
const { clearDecorators } = clientApi;
const configApi = new ConfigApi({ clearDecorators, storyStore, channel, clientApi });
return {
configApi,
storyStore,
channel,
clientApi,
};
})();
jest.mock('@storybook/client-logger', () => ({
logger: { warn: jest.fn(), log: jest.fn() },
}));
describe('preview.client_api', () => {
describe('setAddon', () => {
it('should register addons', () => {
const { clientApi } = getContext(undefined);
let data;
clientApi.setAddon({
aa() {
data = 'foo';
},
});
clientApi.storiesOf('none', module).aa();
expect(data).toBe('foo');
});
it('should not remove previous addons', () => {
const { clientApi } = getContext(undefined);
const data = [];
clientApi.setAddon({
aa() {
data.push('foo');
},
});
clientApi.setAddon({
bb() {
data.push('bar');
},
});
clientApi
.storiesOf('none', module)
.aa()
.bb();
expect(data).toEqual(['foo', 'bar']);
});
it('should call with the clientApi context', () => {
const { clientApi } = getContext(undefined);
let data;
clientApi.setAddon({
aa() {
data = typeof this.add;
},
});
clientApi.storiesOf('none', module).aa();
expect(data).toBe('function');
});
it('should be able to access addons added previously', () => {
const { clientApi } = getContext(undefined);
let data;
clientApi.setAddon({
aa() {
data = 'foo';
},
});
clientApi.setAddon({
bb() {
this.aa();
},
});
clientApi.storiesOf('none', module).bb();
expect(data).toBe('foo');
});
it('should be able to access the current kind', () => {
const { clientApi } = getContext(undefined);
const kind = 'dfdwf3e3';
let data;
clientApi.setAddon({
aa() {
data = this.kind;
},
});
clientApi.storiesOf(kind, module).aa();
expect(data).toBe(kind);
});
});
describe('addParameters', () => {
it('should add parameters', () => {
const { clientApi } = getContext(undefined);
clientApi.addParameters({ a: '1' });
// @ts-ignore
expect(clientApi._globalParameters).toEqual({ a: '1', options: {} });
});
it('should merge options', () => {
const { clientApi } = getContext(undefined);
clientApi.addParameters({ options: { a: '1' } });
clientApi.addParameters({ options: { b: '2' } });
// @ts-ignore
expect(clientApi._globalParameters).toEqual({ options: { a: '1', b: '2' } });
});
it('should override specific properties in options', () => {
const { clientApi } = getContext(undefined);
clientApi.addParameters({ backgrounds: ['value'], options: { a: '1', b: '3' } });
clientApi.addParameters({ options: { a: '2' } });
// @ts-ignore
expect(clientApi._globalParameters).toEqual({
backgrounds: ['value'],
options: { a: '2', b: '3' },
});
});
it('should replace top level properties and override specific properties in options', () => {
const { clientApi } = getContext(undefined);
clientApi.addParameters({ backgrounds: ['value'], options: { a: '1', b: '3' } });
clientApi.addParameters({ backgrounds: [], options: { a: '2' } });
// @ts-ignore
expect(clientApi._globalParameters).toEqual({
backgrounds: [],
options: { a: '2', b: '3' },
});
});
it('should deep merge in options', () => {
const { clientApi } = getContext(undefined);
clientApi.addParameters({ options: { a: '1', b: '2', theming: { c: '3' } } });
clientApi.addParameters({ options: { theming: { c: '4', d: '5' } } });
// @ts-ignore
expect(clientApi._globalParameters).toEqual({
options: { a: '1', b: '2', theming: { c: '4', d: '5' } },
});
});
});
describe('addDecorator', () => {
it('should add local decorators', () => {
const {
clientApi: { storiesOf },
storyStore,
} = getContext(undefined);
storiesOf('kind', module)
.addDecorator(fn => `aa-${fn()}`)
.add('name', () => 'Hello');
expect(storyStore.fromId('kind--name').storyFn()).toBe('aa-Hello');
});
it('should add global decorators', () => {
const {
clientApi: { addDecorator, storiesOf },
storyStore,
} = getContext(undefined);
addDecorator(fn => `bb-${fn()}`);
storiesOf('kind', module).add('name', () => 'Hello');
const f = storyStore.fromId('x');
expect(storyStore.fromId('kind--name').storyFn()).toBe('bb-Hello');
});
it('should utilize both decorators at once', () => {
const {
clientApi: { addDecorator, storiesOf },
storyStore,
} = getContext(undefined);
addDecorator(fn => `aa-${fn()}`);
storiesOf('kind', module)
.addDecorator(fn => `bb-${fn()}`)
.add('name', () => 'Hello');
expect(storyStore.fromId('kind--name').storyFn()).toBe('aa-bb-Hello');
});
it('should pass the context', () => {
const {
clientApi: { storiesOf },
storyStore,
} = getContext(undefined);
storiesOf('kind', module)
.addDecorator(fn => `aa-${fn()}`)
.add('name', c => `${c.kind}-${c.name}`);
const result = storyStore.fromId('kind--name').storyFn();
expect(result).toBe(`aa-kind-name`);
});
it('should have access to the context', () => {
const {
clientApi: { storiesOf },
storyStore,
} = getContext(undefined);
storiesOf('kind', module)
.addDecorator((fn, { kind, name }) => `${kind}-${name}-${fn()}`)
.add('name', () => 'Hello');
const result = storyStore.fromId('kind--name').storyFn();
expect(result).toBe(`kind-name-Hello`);
});
});
describe('clearDecorators', () => {
it('should remove all global decorators', () => {
const { clientApi } = getContext(undefined);
// @ts-ignore
clientApi._globalDecorators = 1234;
clientApi.clearDecorators();
// @ts-ignore
expect(clientApi._globalDecorators).toEqual([]);
});
});
describe('getStorybook', () => {
it('should transform the storybook to an array with filenames', () => {
const {
clientApi: { getStorybook, storiesOf },
} = getContext(undefined);
let book;
book = getStorybook();
expect(book).toEqual([]);
storiesOf('kind 1', module)
.add('name 1', () => '1')
.add('name 2', () => '2');
storiesOf('kind 2', module)
.add('name 1', () => '1')
.add('name 2', () => '2');
book = getStorybook();
expect(book).toEqual([
expect.objectContaining({
fileName: expect.any(String),
kind: 'kind 1',
stories: [
{
name: 'name 1',
render: expect.any(Function),
},
{
name: 'name 2',
render: expect.any(Function),
},
],
}),
expect.objectContaining({
fileName: expect.any(String),
kind: 'kind 2',
stories: [
{
name: 'name 1',
render: expect.any(Function),
},
{
name: 'name 2',
render: expect.any(Function),
},
],
}),
]);
});
it('reads filename from module', () => {
const {
clientApi: { getStorybook, storiesOf },
} = getContext(undefined);
const fn = jest.fn();
storiesOf('kind', { id: 'foo.js' }).add('name', fn);
const storybook = getStorybook();
expect(storybook).toEqual([
{
kind: 'kind',
fileName: 'foo.js',
stories: [
{
name: 'name',
render: expect.any(Function),
},
],
},
]);
});
it('should stringify ids from module', () => {
const {
clientApi: { getStorybook, storiesOf },
} = getContext(undefined);
const fn = jest.fn();
storiesOf('kind', { id: 1211 }).add('name', fn);
const storybook = getStorybook();
expect(storybook).toEqual([
{
kind: 'kind',
fileName: '1211',
stories: [
{
name: 'name',
render: expect.any(Function),
},
],
},
]);
});
});
describe('hot module loading', () => {
class MockModule {
id = 'mock-module-id';
hot = {
callbacks: [],
dispose(fn) {
this.callbacks.push(fn);
},
reload() {
this.callbacks.forEach(fn => fn());
},
};
}
it('should increment store revision when the module reloads', () => {
const {
storyStore,
clientApi: { storiesOf },
} = getContext(undefined);
const module = new MockModule();
expect(storyStore.getRevision()).toEqual(0);
storiesOf('kind', module);
module.hot.reload();
expect(storyStore.getRevision()).toEqual(1);
});
it('should replace a kind when the module reloads', () => {
const {
clientApi: { storiesOf, getStorybook },
} = getContext(undefined);
const module = new MockModule();
const stories = [jest.fn(), jest.fn()];
expect(getStorybook()).toEqual([]);
storiesOf('kind', module).add('story', stories[0]);
const firstStorybook = getStorybook();
expect(firstStorybook).toEqual([
{
fileName: expect.any(String),
kind: 'kind',
stories: [{ name: 'story', render: expect.anything() }],
},
]);
firstStorybook[0].stories[0].render();
expect(stories[0]).toHaveBeenCalled();
module.hot.reload();
expect(getStorybook()).toEqual([]);
storiesOf('kind', module).add('story', stories[1]);
const secondStorybook = getStorybook();
expect(secondStorybook).toEqual([
{
fileName: expect.any(String),
kind: 'kind',
stories: [{ name: 'story', render: expect.anything() }],
},
]);
secondStorybook[0].stories[0].render();
expect(stories[1]).toHaveBeenCalled();
expect(logger.warn).not.toHaveBeenCalled();
});
});
describe('parameters', () => {
it('collects parameters across different modalities', () => {
const {
storyStore,
clientApi: { storiesOf, addParameters },
} = getContext(undefined);
addParameters({ a: 'global', b: 'global', c: 'global' });
const kind = storiesOf('kind', module);
kind.addParameters({ b: 'kind', c: 'kind' });
kind.add('name', jest.fn(), { c: 'story' });
expect(storyStore.fromId('kind--name').parameters).toEqual({
a: 'global',
b: 'kind',
c: 'story',
fileName: expect.any(String),
options: expect.any(Object),
});
});
it('combines object parameters per-key', () => {
const {
storyStore,
clientApi: { storiesOf, addParameters },
} = getContext(undefined);
addParameters({
addon1: 'global string value',
addon2: ['global array value'],
addon3: {
global: true,
sub: { global: true },
},
options: expect.any(Object),
});
storiesOf('kind', module)
.addParameters({
addon1: 'local string value',
addon2: ['local array value'],
addon3: {
local: true,
sub: {
local: true,
},
},
})
.add('name', jest.fn(), {
addon1: 'local string value',
addon2: ['local array value'],
addon3: {
local: true,
sub: {
local: true,
},
},
});
expect(storyStore.fromId('kind--name').parameters).toEqual({
addon1: 'local string value',
addon2: ['local array value'],
addon3: {
global: true,
local: true,
sub: {
global: true,
local: true,
},
},
fileName: expect.any(String),
options: expect.any(Object),
});
});
});
describe('storiesOf', () => {
describe('add', () => {
it('should replace stories when adding the same story', () => {
const stories = [jest.fn().mockReturnValue('story1'), jest.fn().mockReturnValue('story2')];
const {
clientApi: { storiesOf, getStorybook },
} = getContext(undefined);
expect(getStorybook()).toEqual([]);
storiesOf('kind', module).add('story', stories[0]);
{
const book = getStorybook();
expect(book).toHaveLength(1);
const entry = book[0];
expect(entry.kind).toMatch('kind');
expect(entry.stories).toHaveLength(1);
expect(entry.stories[0].name).toBe('story');
// v3 returns the same function we passed in
if (jest.isMockFunction(entry.stories[0].render)) {
expect(entry.stories[0].render).toBe(stories[0]);
} else {
expect(entry.stories[0].render()).toBe('story1');
}
}
storiesOf('kind', module).add('story', stories[1]);
// @ts-ignore
expect(logger.warn.mock.calls[0][0]).toMatch(
/Story with id kind--story already exists in the store/
);
{
const book = getStorybook();
expect(book).toHaveLength(1);
const entry = book[0];
expect(entry.kind).toMatch('kind');
expect(entry.stories).toHaveLength(1);
expect(entry.stories[0].name).toBe('story');
// v3 returns the same function we passed in
if (jest.isMockFunction(entry.stories[0].render)) {
expect(entry.stories[0].render).toBe(stories[0]);
} else {
expect(entry.stories[0].render()).toBe('story2');
}
}
});
});
});
});
| lib/client-api/src/client_api.test.ts | 0 | https://github.com/storybookjs/storybook/commit/8388e6b58dd930ec07e8bacd8f5b3865425201fc | [
0.00017827979172579944,
0.00017326866509392858,
0.0001659488771110773,
0.00017382104124408215,
0.000003068077148782322
] |
{
"id": 1,
"code_window": [
" padding: 0,\n",
"});\n",
"\n",
"const NoTests = styled.div({\n",
" padding: '10px 20px',\n",
" flex: 1,\n",
"});\n",
"\n",
"const ProgressWrapper = styled.div({\n",
" position: 'relative',\n",
" height: '10px',\n",
"});\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "addons/jest/src/components/Panel.tsx",
"type": "replace",
"edit_start_line_idx": 19
} | import React, { Fragment } from 'react';
import { styled, withTheme } from '@storybook/theming';
import { ScrollArea, TabsState } from '@storybook/components';
import { SizeMe } from 'react-sizeme';
import Result from './Result';
import provideJestResult, { Test } from '../hoc/provideJestResult';
const List = styled.ul({
listStyle: 'none',
fontSize: 14,
padding: 0,
margin: 0,
});
const Item = styled.li({
display: 'block',
padding: 0,
});
const NoTests = styled.div({
padding: '10px 20px',
flex: 1,
});
const ProgressWrapper = styled.div({
position: 'relative',
height: '10px',
});
const SuiteHead = styled.div({
display: 'flex',
alignItems: 'baseline',
position: 'absolute',
zIndex: 2,
right: '50px',
marginTop: '15px',
});
const SuiteTotals = styled(({ successNumber, failedNumber, result, className, width }) => (
<div className={className}>
<Fragment>
{width > 325 ? (
<div>
{result.assertionResults.length} {result.assertionResults.length > 1 ? `tests` : `test`}
</div>
) : null}
{width > 280 ? (
<div>
{result.endTime - result.startTime}
ms
</div>
) : null}
</Fragment>
</div>
))(({ theme }) => ({
display: 'flex',
alignItems: 'center',
color: theme.color.dark,
fontSize: '14px',
marginTop: '-5px',
'& > *': {
marginRight: 10,
},
}));
const SuiteProgress = styled(({ successNumber, result, className }) => (
<div className={className} role="progressbar">
<span style={{ width: `${(successNumber / result.assertionResults.length) * 100}%` }} />
</div>
))(({ theme }) => ({
width: '30px',
backgroundColor: theme.color.negative,
height: '6px',
top: '3px',
position: 'absolute',
left: 0,
overflow: 'hidden',
appearance: 'none',
'& > span': {
backgroundColor: theme.color.positive,
bottom: 0,
position: 'absolute',
left: 0,
top: 0,
},
}));
interface ContentProps {
tests: Test[];
className?: string;
}
const Content = styled(({ tests, className }: ContentProps) => (
<div className={className}>
{tests.map(({ name, result }) => {
if (!result) {
return <NoTests key={name}>This story has tests configured, but no file was found</NoTests>;
}
const successNumber = result.assertionResults.filter(({ status }) => status === 'passed')
.length;
const failedNumber = result.assertionResults.length - successNumber;
const passingRate = ((successNumber / result.assertionResults.length) * 100).toFixed(2);
return (
<SizeMe refreshMode="debounce">
{({ size }: { size: any }) => {
const { width } = size;
return (
<section key={name}>
<SuiteHead>
<SuiteTotals {...{ successNumber, failedNumber, result, passingRate, width }} />
{width > 240 ? (
<ProgressWrapper>
<SuiteProgress {...{ successNumber, failedNumber, result }} />
</ProgressWrapper>
) : null}
</SuiteHead>
<TabsState initial="failing-tests" backgroundColor="rgba(0,0,0,.05)">
<div id="failing-tests" title={`${failedNumber} Failed`} color="#FF4400">
<List>
{result.assertionResults.map(res => {
return res.status === 'failed' ? (
<Item key={res.fullName || res.title}>
<Result {...res} />
</Item>
) : null;
})}
</List>
</div>
<div id="passing-tests" title={`${successNumber} Passed`} color="#66BF3C">
<List>
{result.assertionResults.map(res => {
return res.status === 'passed' ? (
<Item key={res.fullName || res.title}>
<Result {...res} />
</Item>
) : null;
})}
</List>
</div>
</TabsState>
</section>
);
}}
</SizeMe>
);
})}
</div>
))({
flex: '1 1 0%',
});
const ContentWithTheme = withTheme(Content);
interface PanelProps {
tests: null | Test[];
}
const Panel = ({ tests }: PanelProps) => (
<ScrollArea vertical>
{tests ? (
<ContentWithTheme tests={tests} />
) : (
<NoTests>This story has no tests configured</NoTests>
)}
</ScrollArea>
);
Panel.defaultProps = {
tests: null,
};
export default provideJestResult(Panel);
| addons/jest/src/components/Panel.tsx | 1 | https://github.com/storybookjs/storybook/commit/8388e6b58dd930ec07e8bacd8f5b3865425201fc | [
0.9978118538856506,
0.13718447089195251,
0.0001654920488363132,
0.0001762672036420554,
0.31995993852615356
] |
{
"id": 1,
"code_window": [
" padding: 0,\n",
"});\n",
"\n",
"const NoTests = styled.div({\n",
" padding: '10px 20px',\n",
" flex: 1,\n",
"});\n",
"\n",
"const ProgressWrapper = styled.div({\n",
" position: 'relative',\n",
" height: '10px',\n",
"});\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "addons/jest/src/components/Panel.tsx",
"type": "replace",
"edit_start_line_idx": 19
} | /* eslint-disable global-require */
module.exports = {
Welcome: require('./dist/demo/Welcome').default,
Button: require('./dist/demo/Button').default,
};
| app/react/demo.js | 0 | https://github.com/storybookjs/storybook/commit/8388e6b58dd930ec07e8bacd8f5b3865425201fc | [
0.00017494773783255368,
0.00017494773783255368,
0.00017494773783255368,
0.00017494773783255368,
0
] |
{
"id": 1,
"code_window": [
" padding: 0,\n",
"});\n",
"\n",
"const NoTests = styled.div({\n",
" padding: '10px 20px',\n",
" flex: 1,\n",
"});\n",
"\n",
"const ProgressWrapper = styled.div({\n",
" position: 'relative',\n",
" height: '10px',\n",
"});\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "addons/jest/src/components/Panel.tsx",
"type": "replace",
"edit_start_line_idx": 19
} | import { Story, Preview, Meta } from '@storybook/addon-docs/blocks';
import { action } from '@storybook/addon-actions';
# Storybook Docs for HTML
<Meta title="Addons|Docs" />
## Story definition
Hallelujah! HTML is working out of the box without modification.
How you like them apples?!
<Story name="heading" height="100px">
{'<h1>Hello World</h1>'}
</Story>
## Function stories
<Story name="function" height="100px">
{() => {
const btn = document.createElement('button');
btn.innerHTML = 'Hello Button';
btn.addEventListener('click', action('Click'));
return btn;
}}
</Story>
## Story reference
You can also reference an existing story from within your MDX file.
<Story id="welcome--welcome" height="800px" />
| examples/html-kitchen-sink/stories/addon-docs.stories.mdx | 0 | https://github.com/storybookjs/storybook/commit/8388e6b58dd930ec07e8bacd8f5b3865425201fc | [
0.00017632667731959373,
0.00017471000319346786,
0.00017329129332210869,
0.00017461100651416928,
0.0000010777571333164815
] |
{
"id": 1,
"code_window": [
" padding: 0,\n",
"});\n",
"\n",
"const NoTests = styled.div({\n",
" padding: '10px 20px',\n",
" flex: 1,\n",
"});\n",
"\n",
"const ProgressWrapper = styled.div({\n",
" position: 'relative',\n",
" height: '10px',\n",
"});\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "addons/jest/src/components/Panel.tsx",
"type": "replace",
"edit_start_line_idx": 19
} | module.exports = {
presets: [
['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', corejs: '3' }],
['babel-preset-rax', { development: process.env.BABEL_ENV === 'development' }],
],
};
| examples/rax-kitchen-sink/.babelrc.js | 0 | https://github.com/storybookjs/storybook/commit/8388e6b58dd930ec07e8bacd8f5b3865425201fc | [
0.00017361430218443274,
0.00017361430218443274,
0.00017361430218443274,
0.00017361430218443274,
0
] |
{
"id": 2,
"code_window": [
"const Content = styled(({ tests, className }: ContentProps) => (\n",
" <div className={className}>\n",
" {tests.map(({ name, result }) => {\n",
" if (!result) {\n",
" return <NoTests key={name}>This story has tests configured, but no file was found</NoTests>;\n",
" }\n",
"\n",
" const successNumber = result.assertionResults.filter(({ status }) => status === 'passed')\n",
" .length;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return (\n",
" <Placeholder key={name}>\n",
" This story has tests configured, but no file was found\n",
" </Placeholder>\n",
" );\n"
],
"file_path": "addons/jest/src/components/Panel.tsx",
"type": "replace",
"edit_start_line_idx": 97
} | import React, { Fragment } from 'react';
import { styled, withTheme } from '@storybook/theming';
import { ScrollArea, TabsState } from '@storybook/components';
import { SizeMe } from 'react-sizeme';
import Result from './Result';
import provideJestResult, { Test } from '../hoc/provideJestResult';
const List = styled.ul({
listStyle: 'none',
fontSize: 14,
padding: 0,
margin: 0,
});
const Item = styled.li({
display: 'block',
padding: 0,
});
const NoTests = styled.div({
padding: '10px 20px',
flex: 1,
});
const ProgressWrapper = styled.div({
position: 'relative',
height: '10px',
});
const SuiteHead = styled.div({
display: 'flex',
alignItems: 'baseline',
position: 'absolute',
zIndex: 2,
right: '50px',
marginTop: '15px',
});
const SuiteTotals = styled(({ successNumber, failedNumber, result, className, width }) => (
<div className={className}>
<Fragment>
{width > 325 ? (
<div>
{result.assertionResults.length} {result.assertionResults.length > 1 ? `tests` : `test`}
</div>
) : null}
{width > 280 ? (
<div>
{result.endTime - result.startTime}
ms
</div>
) : null}
</Fragment>
</div>
))(({ theme }) => ({
display: 'flex',
alignItems: 'center',
color: theme.color.dark,
fontSize: '14px',
marginTop: '-5px',
'& > *': {
marginRight: 10,
},
}));
const SuiteProgress = styled(({ successNumber, result, className }) => (
<div className={className} role="progressbar">
<span style={{ width: `${(successNumber / result.assertionResults.length) * 100}%` }} />
</div>
))(({ theme }) => ({
width: '30px',
backgroundColor: theme.color.negative,
height: '6px',
top: '3px',
position: 'absolute',
left: 0,
overflow: 'hidden',
appearance: 'none',
'& > span': {
backgroundColor: theme.color.positive,
bottom: 0,
position: 'absolute',
left: 0,
top: 0,
},
}));
interface ContentProps {
tests: Test[];
className?: string;
}
const Content = styled(({ tests, className }: ContentProps) => (
<div className={className}>
{tests.map(({ name, result }) => {
if (!result) {
return <NoTests key={name}>This story has tests configured, but no file was found</NoTests>;
}
const successNumber = result.assertionResults.filter(({ status }) => status === 'passed')
.length;
const failedNumber = result.assertionResults.length - successNumber;
const passingRate = ((successNumber / result.assertionResults.length) * 100).toFixed(2);
return (
<SizeMe refreshMode="debounce">
{({ size }: { size: any }) => {
const { width } = size;
return (
<section key={name}>
<SuiteHead>
<SuiteTotals {...{ successNumber, failedNumber, result, passingRate, width }} />
{width > 240 ? (
<ProgressWrapper>
<SuiteProgress {...{ successNumber, failedNumber, result }} />
</ProgressWrapper>
) : null}
</SuiteHead>
<TabsState initial="failing-tests" backgroundColor="rgba(0,0,0,.05)">
<div id="failing-tests" title={`${failedNumber} Failed`} color="#FF4400">
<List>
{result.assertionResults.map(res => {
return res.status === 'failed' ? (
<Item key={res.fullName || res.title}>
<Result {...res} />
</Item>
) : null;
})}
</List>
</div>
<div id="passing-tests" title={`${successNumber} Passed`} color="#66BF3C">
<List>
{result.assertionResults.map(res => {
return res.status === 'passed' ? (
<Item key={res.fullName || res.title}>
<Result {...res} />
</Item>
) : null;
})}
</List>
</div>
</TabsState>
</section>
);
}}
</SizeMe>
);
})}
</div>
))({
flex: '1 1 0%',
});
const ContentWithTheme = withTheme(Content);
interface PanelProps {
tests: null | Test[];
}
const Panel = ({ tests }: PanelProps) => (
<ScrollArea vertical>
{tests ? (
<ContentWithTheme tests={tests} />
) : (
<NoTests>This story has no tests configured</NoTests>
)}
</ScrollArea>
);
Panel.defaultProps = {
tests: null,
};
export default provideJestResult(Panel);
| addons/jest/src/components/Panel.tsx | 1 | https://github.com/storybookjs/storybook/commit/8388e6b58dd930ec07e8bacd8f5b3865425201fc | [
0.9988799691200256,
0.31476080417633057,
0.00016405305359512568,
0.0020251069217920303,
0.44433242082595825
] |
{
"id": 2,
"code_window": [
"const Content = styled(({ tests, className }: ContentProps) => (\n",
" <div className={className}>\n",
" {tests.map(({ name, result }) => {\n",
" if (!result) {\n",
" return <NoTests key={name}>This story has tests configured, but no file was found</NoTests>;\n",
" }\n",
"\n",
" const successNumber = result.assertionResults.filter(({ status }) => status === 'passed')\n",
" .length;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return (\n",
" <Placeholder key={name}>\n",
" This story has tests configured, but no file was found\n",
" </Placeholder>\n",
" );\n"
],
"file_path": "addons/jest/src/components/Panel.tsx",
"type": "replace",
"edit_start_line_idx": 97
} | ---
id: 'community'
title: 'Community'
---
Storybook is maintained by a [community of users](https://github.com/storybookjs/storybook/graphs/contributors). It's easy to get involved and all contributions are welcome!
You can read about how to get involved in detail in our [Contribution Guide](https://github.com/storybookjs/storybook/blob/master/CONTRIBUTING.md) but at a high level, a good place to get started is:
1. Report issues at the [issue tracker](https://github.com/storybookjs/storybook/issues).
2. Help us to triage issues above, by answering questions, helping to create [reproductions](https://github.com/storybookjs/storybook/blob/master/CONTRIBUTING.md#reproductions), and clarifying feature requests.
3. Pitch in with a PR, especially those marked ["good first issue"](https://github.com/storybookjs/storybook/labels/good%20first%20issue).
| docs/src/pages/basics/community/index.md | 0 | https://github.com/storybookjs/storybook/commit/8388e6b58dd930ec07e8bacd8f5b3865425201fc | [
0.00017303011554758996,
0.0001727900526020676,
0.00017254998965654522,
0.0001727900526020676,
2.4006294552236795e-7
] |
{
"id": 2,
"code_window": [
"const Content = styled(({ tests, className }: ContentProps) => (\n",
" <div className={className}>\n",
" {tests.map(({ name, result }) => {\n",
" if (!result) {\n",
" return <NoTests key={name}>This story has tests configured, but no file was found</NoTests>;\n",
" }\n",
"\n",
" const successNumber = result.assertionResults.filter(({ status }) => status === 'passed')\n",
" .length;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return (\n",
" <Placeholder key={name}>\n",
" This story has tests configured, but no file was found\n",
" </Placeholder>\n",
" );\n"
],
"file_path": "addons/jest/src/components/Panel.tsx",
"type": "replace",
"edit_start_line_idx": 97
} | export const version = '5.2.0-beta.20';
| lib/api/src/version.ts | 0 | https://github.com/storybookjs/storybook/commit/8388e6b58dd930ec07e8bacd8f5b3865425201fc | [
0.00017354909505229443,
0.00017354909505229443,
0.00017354909505229443,
0.00017354909505229443,
0
] |
{
"id": 2,
"code_window": [
"const Content = styled(({ tests, className }: ContentProps) => (\n",
" <div className={className}>\n",
" {tests.map(({ name, result }) => {\n",
" if (!result) {\n",
" return <NoTests key={name}>This story has tests configured, but no file was found</NoTests>;\n",
" }\n",
"\n",
" const successNumber = result.assertionResults.filter(({ status }) => status === 'passed')\n",
" .length;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return (\n",
" <Placeholder key={name}>\n",
" This story has tests configured, but no file was found\n",
" </Placeholder>\n",
" );\n"
],
"file_path": "addons/jest/src/components/Panel.tsx",
"type": "replace",
"edit_start_line_idx": 97
} | module.exports = require('./dist/preact');
| addons/centered/preact.js | 0 | https://github.com/storybookjs/storybook/commit/8388e6b58dd930ec07e8bacd8f5b3865425201fc | [
0.00017550242773722857,
0.00017550242773722857,
0.00017550242773722857,
0.00017550242773722857,
0
] |
{
"id": 3,
"code_window": [
" <ScrollArea vertical>\n",
" {tests ? (\n",
" <ContentWithTheme tests={tests} />\n",
" ) : (\n",
" <NoTests>This story has no tests configured</NoTests>\n",
" )}\n",
" </ScrollArea>\n",
");\n",
"\n",
"Panel.defaultProps = {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Placeholder>\n",
" <Fragment>No tests found</Fragment>\n",
" <Fragment>\n",
" Learn how to{' '}\n",
" <Link\n",
" href=\"https://github.com/storybookjs/storybook/tree/master/addons/jest\"\n",
" target=\"_blank\"\n",
" withArrow\n",
" >\n",
" add Jest test results to your story\n",
" </Link>\n",
" </Fragment>\n",
" </Placeholder>\n"
],
"file_path": "addons/jest/src/components/Panel.tsx",
"type": "replace",
"edit_start_line_idx": 165
} | import React, { Fragment } from 'react';
import { styled, withTheme } from '@storybook/theming';
import { ScrollArea, TabsState } from '@storybook/components';
import { SizeMe } from 'react-sizeme';
import Result from './Result';
import provideJestResult, { Test } from '../hoc/provideJestResult';
const List = styled.ul({
listStyle: 'none',
fontSize: 14,
padding: 0,
margin: 0,
});
const Item = styled.li({
display: 'block',
padding: 0,
});
const NoTests = styled.div({
padding: '10px 20px',
flex: 1,
});
const ProgressWrapper = styled.div({
position: 'relative',
height: '10px',
});
const SuiteHead = styled.div({
display: 'flex',
alignItems: 'baseline',
position: 'absolute',
zIndex: 2,
right: '50px',
marginTop: '15px',
});
const SuiteTotals = styled(({ successNumber, failedNumber, result, className, width }) => (
<div className={className}>
<Fragment>
{width > 325 ? (
<div>
{result.assertionResults.length} {result.assertionResults.length > 1 ? `tests` : `test`}
</div>
) : null}
{width > 280 ? (
<div>
{result.endTime - result.startTime}
ms
</div>
) : null}
</Fragment>
</div>
))(({ theme }) => ({
display: 'flex',
alignItems: 'center',
color: theme.color.dark,
fontSize: '14px',
marginTop: '-5px',
'& > *': {
marginRight: 10,
},
}));
const SuiteProgress = styled(({ successNumber, result, className }) => (
<div className={className} role="progressbar">
<span style={{ width: `${(successNumber / result.assertionResults.length) * 100}%` }} />
</div>
))(({ theme }) => ({
width: '30px',
backgroundColor: theme.color.negative,
height: '6px',
top: '3px',
position: 'absolute',
left: 0,
overflow: 'hidden',
appearance: 'none',
'& > span': {
backgroundColor: theme.color.positive,
bottom: 0,
position: 'absolute',
left: 0,
top: 0,
},
}));
interface ContentProps {
tests: Test[];
className?: string;
}
const Content = styled(({ tests, className }: ContentProps) => (
<div className={className}>
{tests.map(({ name, result }) => {
if (!result) {
return <NoTests key={name}>This story has tests configured, but no file was found</NoTests>;
}
const successNumber = result.assertionResults.filter(({ status }) => status === 'passed')
.length;
const failedNumber = result.assertionResults.length - successNumber;
const passingRate = ((successNumber / result.assertionResults.length) * 100).toFixed(2);
return (
<SizeMe refreshMode="debounce">
{({ size }: { size: any }) => {
const { width } = size;
return (
<section key={name}>
<SuiteHead>
<SuiteTotals {...{ successNumber, failedNumber, result, passingRate, width }} />
{width > 240 ? (
<ProgressWrapper>
<SuiteProgress {...{ successNumber, failedNumber, result }} />
</ProgressWrapper>
) : null}
</SuiteHead>
<TabsState initial="failing-tests" backgroundColor="rgba(0,0,0,.05)">
<div id="failing-tests" title={`${failedNumber} Failed`} color="#FF4400">
<List>
{result.assertionResults.map(res => {
return res.status === 'failed' ? (
<Item key={res.fullName || res.title}>
<Result {...res} />
</Item>
) : null;
})}
</List>
</div>
<div id="passing-tests" title={`${successNumber} Passed`} color="#66BF3C">
<List>
{result.assertionResults.map(res => {
return res.status === 'passed' ? (
<Item key={res.fullName || res.title}>
<Result {...res} />
</Item>
) : null;
})}
</List>
</div>
</TabsState>
</section>
);
}}
</SizeMe>
);
})}
</div>
))({
flex: '1 1 0%',
});
const ContentWithTheme = withTheme(Content);
interface PanelProps {
tests: null | Test[];
}
const Panel = ({ tests }: PanelProps) => (
<ScrollArea vertical>
{tests ? (
<ContentWithTheme tests={tests} />
) : (
<NoTests>This story has no tests configured</NoTests>
)}
</ScrollArea>
);
Panel.defaultProps = {
tests: null,
};
export default provideJestResult(Panel);
| addons/jest/src/components/Panel.tsx | 1 | https://github.com/storybookjs/storybook/commit/8388e6b58dd930ec07e8bacd8f5b3865425201fc | [
0.9715339541435242,
0.055170029401779175,
0.0001656064996495843,
0.0001732827804517001,
0.22225937247276306
] |
{
"id": 3,
"code_window": [
" <ScrollArea vertical>\n",
" {tests ? (\n",
" <ContentWithTheme tests={tests} />\n",
" ) : (\n",
" <NoTests>This story has no tests configured</NoTests>\n",
" )}\n",
" </ScrollArea>\n",
");\n",
"\n",
"Panel.defaultProps = {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Placeholder>\n",
" <Fragment>No tests found</Fragment>\n",
" <Fragment>\n",
" Learn how to{' '}\n",
" <Link\n",
" href=\"https://github.com/storybookjs/storybook/tree/master/addons/jest\"\n",
" target=\"_blank\"\n",
" withArrow\n",
" >\n",
" add Jest test results to your story\n",
" </Link>\n",
" </Fragment>\n",
" </Placeholder>\n"
],
"file_path": "addons/jest/src/components/Panel.tsx",
"type": "replace",
"edit_start_line_idx": 165
} | import React, { Component } from 'react';
import PropTypes from 'prop-types';
// A small utility to add before/afterEach to stories.
class WithLifecyle extends Component {
constructor(props, ...rest) {
super(props, ...rest);
props.beforeEach();
}
componentWillUnmount() {
const { afterEach } = this.props;
afterEach();
}
render() {
const { storyFn } = this.props;
return storyFn();
}
}
WithLifecyle.propTypes = {
storyFn: PropTypes.func.isRequired,
beforeEach: PropTypes.func,
afterEach: PropTypes.func,
};
WithLifecyle.defaultProps = {
beforeEach: () => {},
afterEach: () => {},
};
export default ({ beforeEach, afterEach }) => storyFn => (
<WithLifecyle beforeEach={beforeEach} afterEach={afterEach} storyFn={storyFn} />
);
| lib/ui/src/libs/withLifecycleDecorator.js | 0 | https://github.com/storybookjs/storybook/commit/8388e6b58dd930ec07e8bacd8f5b3865425201fc | [
0.0002437429066048935,
0.0001949315337697044,
0.00017309711256530136,
0.00018144305795431137,
0.00002876733742596116
] |
{
"id": 3,
"code_window": [
" <ScrollArea vertical>\n",
" {tests ? (\n",
" <ContentWithTheme tests={tests} />\n",
" ) : (\n",
" <NoTests>This story has no tests configured</NoTests>\n",
" )}\n",
" </ScrollArea>\n",
");\n",
"\n",
"Panel.defaultProps = {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Placeholder>\n",
" <Fragment>No tests found</Fragment>\n",
" <Fragment>\n",
" Learn how to{' '}\n",
" <Link\n",
" href=\"https://github.com/storybookjs/storybook/tree/master/addons/jest\"\n",
" target=\"_blank\"\n",
" withArrow\n",
" >\n",
" add Jest test results to your story\n",
" </Link>\n",
" </Fragment>\n",
" </Placeholder>\n"
],
"file_path": "addons/jest/src/components/Panel.tsx",
"type": "replace",
"edit_start_line_idx": 165
} | import React, { forwardRef } from 'react';
import PropTypes from 'prop-types';
import BaseButton from './BaseButton';
const ForwardedRefButton = forwardRef((props, ref) => <BaseButton {...props} forwardedRef={ref} />);
ForwardedRefButton.defaultProps = {
disabled: false,
onClick: () => {},
style: {},
};
ForwardedRefButton.propTypes = {
/** Boolean indicating whether the button should render as disabled */
disabled: PropTypes.bool,
/** button label. */
label: PropTypes.string.isRequired,
/** onClick handler */
onClick: PropTypes.func,
/** Custom styles */
style: PropTypes.shape({}),
};
export default ForwardedRefButton;
| examples/official-storybook/components/ForwardedRefButton.js | 0 | https://github.com/storybookjs/storybook/commit/8388e6b58dd930ec07e8bacd8f5b3865425201fc | [
0.00017644104082137346,
0.00017485127318650484,
0.00017189790378324687,
0.00017621490405872464,
0.0000020903939912386704
] |
{
"id": 3,
"code_window": [
" <ScrollArea vertical>\n",
" {tests ? (\n",
" <ContentWithTheme tests={tests} />\n",
" ) : (\n",
" <NoTests>This story has no tests configured</NoTests>\n",
" )}\n",
" </ScrollArea>\n",
");\n",
"\n",
"Panel.defaultProps = {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Placeholder>\n",
" <Fragment>No tests found</Fragment>\n",
" <Fragment>\n",
" Learn how to{' '}\n",
" <Link\n",
" href=\"https://github.com/storybookjs/storybook/tree/master/addons/jest\"\n",
" target=\"_blank\"\n",
" withArrow\n",
" >\n",
" add Jest test results to your story\n",
" </Link>\n",
" </Fragment>\n",
" </Placeholder>\n"
],
"file_path": "addons/jest/src/components/Panel.tsx",
"type": "replace",
"edit_start_line_idx": 165
} | import React, { FunctionComponent, ReactNode } from 'react';
import { styled } from '@storybook/theming';
import { Link } from '../typography/link/link';
const Title = styled.div`
font-weight: ${props => props.theme.typography.weight.black};
`;
const Desc = styled.span``;
const Links = styled.div`
margin-top: 8px;
text-align: center;
> * {
margin: 0 8px;
font-weight: ${props => props.theme.typography.weight.black};
}
`;
const Message = styled.div`
color: ${props => props.theme.color.darker};
line-height: 18px;
`;
const MessageWrapper = styled.div`
padding: 15px;
width: 280px;
box-sizing: border-box;
`;
export interface TooltipMessageProps {
title?: ReactNode;
desc?: ReactNode;
links?: {
title: string;
href?: string;
onClick?: () => void;
}[];
}
export const TooltipMessage: FunctionComponent<TooltipMessageProps> = ({ title, desc, links }) => {
return (
<MessageWrapper>
<Message>
{title && <Title>{title}</Title>}
{desc && <Desc>{desc}</Desc>}
</Message>
{links && (
<Links>
{links.map(({ title: linkTitle, ...other }) => (
<Link {...other} key={linkTitle}>
{linkTitle}
</Link>
))}
</Links>
)}
</MessageWrapper>
);
};
TooltipMessage.defaultProps = {
title: null,
desc: null,
links: null,
};
| lib/components/src/tooltip/TooltipMessage.tsx | 0 | https://github.com/storybookjs/storybook/commit/8388e6b58dd930ec07e8bacd8f5b3865425201fc | [
0.00022034189896658063,
0.0001771490351529792,
0.00016516982577741146,
0.00017049243615474552,
0.000017789327102946118
] |
{
"id": 4,
"code_window": [
"\n",
" render() {\n",
" const { active } = this.props;\n",
" const { tests } = this.state;\n",
"\n",
" return active && tests ? <Component tests={tests} /> : null;\n",
" }\n",
" };\n",
"\n",
"export default provideTests;"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return active ? <Component tests={tests} /> : null;\n"
],
"file_path": "addons/jest/src/hoc/provideJestResult.tsx",
"type": "replace",
"edit_start_line_idx": 78
} | import React, { Fragment } from 'react';
import { styled, withTheme } from '@storybook/theming';
import { ScrollArea, TabsState } from '@storybook/components';
import { SizeMe } from 'react-sizeme';
import Result from './Result';
import provideJestResult, { Test } from '../hoc/provideJestResult';
const List = styled.ul({
listStyle: 'none',
fontSize: 14,
padding: 0,
margin: 0,
});
const Item = styled.li({
display: 'block',
padding: 0,
});
const NoTests = styled.div({
padding: '10px 20px',
flex: 1,
});
const ProgressWrapper = styled.div({
position: 'relative',
height: '10px',
});
const SuiteHead = styled.div({
display: 'flex',
alignItems: 'baseline',
position: 'absolute',
zIndex: 2,
right: '50px',
marginTop: '15px',
});
const SuiteTotals = styled(({ successNumber, failedNumber, result, className, width }) => (
<div className={className}>
<Fragment>
{width > 325 ? (
<div>
{result.assertionResults.length} {result.assertionResults.length > 1 ? `tests` : `test`}
</div>
) : null}
{width > 280 ? (
<div>
{result.endTime - result.startTime}
ms
</div>
) : null}
</Fragment>
</div>
))(({ theme }) => ({
display: 'flex',
alignItems: 'center',
color: theme.color.dark,
fontSize: '14px',
marginTop: '-5px',
'& > *': {
marginRight: 10,
},
}));
const SuiteProgress = styled(({ successNumber, result, className }) => (
<div className={className} role="progressbar">
<span style={{ width: `${(successNumber / result.assertionResults.length) * 100}%` }} />
</div>
))(({ theme }) => ({
width: '30px',
backgroundColor: theme.color.negative,
height: '6px',
top: '3px',
position: 'absolute',
left: 0,
overflow: 'hidden',
appearance: 'none',
'& > span': {
backgroundColor: theme.color.positive,
bottom: 0,
position: 'absolute',
left: 0,
top: 0,
},
}));
interface ContentProps {
tests: Test[];
className?: string;
}
const Content = styled(({ tests, className }: ContentProps) => (
<div className={className}>
{tests.map(({ name, result }) => {
if (!result) {
return <NoTests key={name}>This story has tests configured, but no file was found</NoTests>;
}
const successNumber = result.assertionResults.filter(({ status }) => status === 'passed')
.length;
const failedNumber = result.assertionResults.length - successNumber;
const passingRate = ((successNumber / result.assertionResults.length) * 100).toFixed(2);
return (
<SizeMe refreshMode="debounce">
{({ size }: { size: any }) => {
const { width } = size;
return (
<section key={name}>
<SuiteHead>
<SuiteTotals {...{ successNumber, failedNumber, result, passingRate, width }} />
{width > 240 ? (
<ProgressWrapper>
<SuiteProgress {...{ successNumber, failedNumber, result }} />
</ProgressWrapper>
) : null}
</SuiteHead>
<TabsState initial="failing-tests" backgroundColor="rgba(0,0,0,.05)">
<div id="failing-tests" title={`${failedNumber} Failed`} color="#FF4400">
<List>
{result.assertionResults.map(res => {
return res.status === 'failed' ? (
<Item key={res.fullName || res.title}>
<Result {...res} />
</Item>
) : null;
})}
</List>
</div>
<div id="passing-tests" title={`${successNumber} Passed`} color="#66BF3C">
<List>
{result.assertionResults.map(res => {
return res.status === 'passed' ? (
<Item key={res.fullName || res.title}>
<Result {...res} />
</Item>
) : null;
})}
</List>
</div>
</TabsState>
</section>
);
}}
</SizeMe>
);
})}
</div>
))({
flex: '1 1 0%',
});
const ContentWithTheme = withTheme(Content);
interface PanelProps {
tests: null | Test[];
}
const Panel = ({ tests }: PanelProps) => (
<ScrollArea vertical>
{tests ? (
<ContentWithTheme tests={tests} />
) : (
<NoTests>This story has no tests configured</NoTests>
)}
</ScrollArea>
);
Panel.defaultProps = {
tests: null,
};
export default provideJestResult(Panel);
| addons/jest/src/components/Panel.tsx | 1 | https://github.com/storybookjs/storybook/commit/8388e6b58dd930ec07e8bacd8f5b3865425201fc | [
0.0018194918520748615,
0.00044768204679712653,
0.00016502925427630544,
0.00017472678155172616,
0.0005366528639569879
] |
{
"id": 4,
"code_window": [
"\n",
" render() {\n",
" const { active } = this.props;\n",
" const { tests } = this.state;\n",
"\n",
" return active && tests ? <Component tests={tests} /> : null;\n",
" }\n",
" };\n",
"\n",
"export default provideTests;"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return active ? <Component tests={tests} /> : null;\n"
],
"file_path": "addons/jest/src/hoc/provideJestResult.tsx",
"type": "replace",
"edit_start_line_idx": 78
} | # Manual Setup
First, install the `@storybook/react-native` module
```sh
yarn add @storybook/react-native --dev
```
Create a new directory called `storybook` in your project root and create an entry file (index.js) as given below.
(Don't forget to replace "MyApplicationName" with your app name).
**storybook/index.js**
```js
import { AppRegistry } from 'react-native';
import { getStorybookUI, configure } from '@storybook/react-native';
import './rn-addons';
// import stories
configure(() => {
// eslint-disable-next-line global-require
require('./stories');
}, module);
const StorybookUIRoot = getStorybookUI();
AppRegistry.registerComponent('MyApplicationName', () => StorybookUIRoot);
export default StorybookUIRoot;
```
Create a file called `rn-addons.js`
In this file you can import on device addons.
**storybook/rn-addons.js**
```
import '@storybook/addon-ondevice-knobs/register';
import '@storybook/addon-ondevice-notes/register';
...
```
Then write your first story in the `stories` directory like this:
```js
import { storiesOf } from '@storybook/react-native';
import React from 'react';
import { View, Text } from 'react-native';
const style = {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF'
};
const CenteredView = ({ children }) => (
<View style={style}>
{children}
</View>
);
storiesOf('CenteredView', module)
.add('default view', () => (
<CenteredView>
<Text>Hello Storybook</Text>
</CenteredView>
));
```
Finally replace your app entry with
```js
import './storybook';
```
For example, if your entry app is named App.js/index.js (Expo/Vanilla). You can replace it with the following.
```
import StorybookUI from './storybook';
export default StorybookUI;
```
If you cannot replace your entry point just make sure that the component exported from `./storybook` is displayed
somewhere in your app. `StorybookUI` is simply a RN `View` component that can be embedded anywhere in your
RN application, e.g. on a tab or within an admin screen.
## Server support
If you want to support having a storybook server running install storybook server `npm install --save-dev @storybook/react-native-server`
and add following NPM script into your `package.json` file:
```json
{
"scripts": {
"storybook": "storybook start"
}
}
```
If you want to have addons inside browser, create a file named `addons.js` file in `storybook`. Here is a list of default addons:
**storybook/addons.js**
```js
import '@storybook/addon-actions';
import '@storybook/addon-links';
```
| app/react-native/docs/manual-setup.md | 0 | https://github.com/storybookjs/storybook/commit/8388e6b58dd930ec07e8bacd8f5b3865425201fc | [
0.00017604210006538779,
0.00017144704179372638,
0.00016503459482919425,
0.00017247055075131357,
0.0000032020523121900624
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.