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": 7, "code_window": [ " action=lambda self, *args, **kwargs: f\"{self.__class__.__name__}.put\",\n", " object_ref=False,\n", " log_to_statsd=False,\n", " )\n", " def put_headless(self, pk: int) -> Response:\n", " \"\"\"\n", " Add statsd metrics to builtin FAB PUT endpoint\n", " \"\"\"\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " @handle_api_exception\n" ], "file_path": "superset/views/base_api.py", "type": "add", "edit_start_line_idx": 440 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { Behavior, DataRecord, FilterState, QueryFormData, } from '@superset-ui/core'; import { RefObject } from 'react'; import { PluginFilterHooks, PluginFilterStylesProps } from '../types'; interface PluginFilterGroupByCustomizeProps { defaultValue?: string[] | null; inputRef?: RefObject<HTMLInputElement>; multiSelect: boolean; } export type PluginFilterGroupByQueryFormData = QueryFormData & PluginFilterStylesProps & PluginFilterGroupByCustomizeProps; export type PluginFilterGroupByProps = PluginFilterStylesProps & { behaviors: Behavior[]; data: DataRecord[]; filterState: FilterState; formData: PluginFilterGroupByQueryFormData; inputRef: RefObject<HTMLInputElement>; } & PluginFilterHooks; export const DEFAULT_FORM_DATA: PluginFilterGroupByCustomizeProps = { defaultValue: null, multiSelect: false, };
superset-frontend/src/filters/components/GroupBy/types.ts
0
https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f
[ 0.00017474099877290428, 0.00017105511506088078, 0.000165956313139759, 0.00017156728426925838, 0.0000034102451991202543 ]
{ "id": 7, "code_window": [ " action=lambda self, *args, **kwargs: f\"{self.__class__.__name__}.put\",\n", " object_ref=False,\n", " log_to_statsd=False,\n", " )\n", " def put_headless(self, pk: int) -> Response:\n", " \"\"\"\n", " Add statsd metrics to builtin FAB PUT endpoint\n", " \"\"\"\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " @handle_api_exception\n" ], "file_path": "superset/views/base_api.py", "type": "add", "edit_start_line_idx": 440 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """rename pie label type Revision ID: 41ce8799acc3 Revises: e11ccdd12658 Create Date: 2021-02-10 12:32:27.385579 """ # revision identifiers, used by Alembic. revision = "41ce8799acc3" down_revision = "e11ccdd12658" import json from alembic import op from sqlalchemy import and_, Column, Integer, String, Text from sqlalchemy.ext.declarative import declarative_base from superset import db Base = declarative_base() class Slice(Base): """Declarative class to do query in upgrade""" __tablename__ = "slices" id = Column(Integer, primary_key=True) viz_type = Column(String(250)) params = Column(Text) def upgrade(): bind = op.get_bind() session = db.Session(bind=bind) slices = ( session.query(Slice) .filter(and_(Slice.viz_type == "pie", Slice.params.like("%pie_label_type%"))) .all() ) changes = 0 for slc in slices: try: params = json.loads(slc.params) pie_label_type = params.pop("pie_label_type", None) if pie_label_type: changes += 1 params["label_type"] = pie_label_type slc.params = json.dumps(params, sort_keys=True) except Exception as e: print(e) print(f"Parsing params for slice {slc.id} failed.") pass session.commit() session.close() print(f"Updated {changes} pie chart labels.") def downgrade(): bind = op.get_bind() session = db.Session(bind=bind) slices = ( session.query(Slice) .filter(and_(Slice.viz_type == "pie", Slice.params.like("%label_type%"))) .all() ) changes = 0 for slc in slices: try: params = json.loads(slc.params) label_type = params.pop("label_type", None) if label_type: changes += 1 params["pie_label_type"] = label_type slc.params = json.dumps(params, sort_keys=True) except Exception as e: print(e) print(f"Parsing params for slice {slc.id} failed.") pass session.commit() session.close() print(f"Updated {changes} pie chart labels.")
superset/migrations/versions/41ce8799acc3_rename_pie_label_type.py
0
https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f
[ 0.00017680141900200397, 0.0001709888456389308, 0.00016577364294789732, 0.00017004286928568035, 0.0000030290243557828944 ]
{ "id": 8, "code_window": [ " object_ref=False,\n", " log_to_statsd=False,\n", " )\n", " def delete_headless(self, pk: int) -> Response:\n", " \"\"\"\n", " Add statsd metrics to builtin FAB DELETE endpoint\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " @handle_api_exception\n" ], "file_path": "superset/views/base_api.py", "type": "add", "edit_start_line_idx": 453 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import functools import logging from typing import Any, Callable, cast, Dict, List, Optional, Set, Tuple, Type, Union from flask import Blueprint, g, request, Response from flask_appbuilder import AppBuilder, Model, ModelRestApi from flask_appbuilder.api import expose, protect, rison, safe from flask_appbuilder.models.filters import BaseFilter, Filters from flask_appbuilder.models.sqla.filters import FilterStartsWith from flask_appbuilder.models.sqla.interface import SQLAInterface from flask_babel import lazy_gettext as _ from marshmallow import fields, Schema from sqlalchemy import and_, distinct, func from sqlalchemy.orm.query import Query from superset.exceptions import InvalidPayloadFormatError from superset.extensions import db, event_logger, security_manager from superset.models.core import FavStar from superset.models.dashboard import Dashboard from superset.models.slice import Slice from superset.schemas import error_payload_content from superset.sql_lab import Query as SqllabQuery from superset.stats_logger import BaseStatsLogger from superset.superset_typing import FlaskResponse from superset.utils.core import time_function logger = logging.getLogger(__name__) get_related_schema = { "type": "object", "properties": { "page_size": {"type": "integer"}, "page": {"type": "integer"}, "include_ids": {"type": "array", "items": {"type": "integer"}}, "filter": {"type": "string"}, }, } class RelatedResultResponseSchema(Schema): value = fields.Integer(description="The related item identifier") text = fields.String(description="The related item string representation") class RelatedResponseSchema(Schema): count = fields.Integer(description="The total number of related values") result = fields.List(fields.Nested(RelatedResultResponseSchema)) class DistinctResultResponseSchema(Schema): text = fields.String(description="The distinct item") class DistincResponseSchema(Schema): count = fields.Integer(description="The total number of distinct values") result = fields.List(fields.Nested(DistinctResultResponseSchema)) def requires_json(f: Callable[..., Any]) -> Callable[..., Any]: """ Require JSON-like formatted request to the REST API """ def wraps(self: "BaseSupersetModelRestApi", *args: Any, **kwargs: Any) -> Response: if not request.is_json: raise InvalidPayloadFormatError(message="Request is not JSON") return f(self, *args, **kwargs) return functools.update_wrapper(wraps, f) def requires_form_data(f: Callable[..., Any]) -> Callable[..., Any]: """ Require 'multipart/form-data' as request MIME type """ def wraps(self: "BaseSupersetModelRestApi", *args: Any, **kwargs: Any) -> Response: if not request.mimetype == "multipart/form-data": raise InvalidPayloadFormatError( message="Request MIME type is not 'multipart/form-data'" ) return f(self, *args, **kwargs) return functools.update_wrapper(wraps, f) def statsd_metrics(f: Callable[..., Any]) -> Callable[..., Any]: """ Handle sending all statsd metrics from the REST API """ def wraps(self: "BaseSupersetModelRestApi", *args: Any, **kwargs: Any) -> Response: try: duration, response = time_function(f, self, *args, **kwargs) except Exception as ex: self.incr_stats("error", f.__name__) raise ex self.send_stats_metrics(response, f.__name__, duration) return response return functools.update_wrapper(wraps, f) class RelatedFieldFilter: # data class to specify what filter to use on a /related endpoint # pylint: disable=too-few-public-methods def __init__(self, field_name: str, filter_class: Type[BaseFilter]): self.field_name = field_name self.filter_class = filter_class class BaseFavoriteFilter(BaseFilter): # pylint: disable=too-few-public-methods """ Base Custom filter for the GET list that filters all dashboards, slices that a user has favored or not """ name = _("Is favorite") arg_name = "" class_name = "" """ The FavStar class_name to user """ model: Type[Union[Dashboard, Slice, SqllabQuery]] = Dashboard """ The SQLAlchemy model """ def apply(self, query: Query, value: Any) -> Query: # If anonymous user filter nothing if security_manager.current_user is None: return query users_favorite_query = db.session.query(FavStar.obj_id).filter( and_( FavStar.user_id == g.user.get_id(), FavStar.class_name == self.class_name, ) ) if value: return query.filter(and_(self.model.id.in_(users_favorite_query))) return query.filter(and_(~self.model.id.in_(users_favorite_query))) class BaseSupersetModelRestApi(ModelRestApi): """ Extends FAB's ModelResApi to implement specific superset generic functionality """ csrf_exempt = False method_permission_name = { "bulk_delete": "delete", "data": "list", "data_from_cache": "list", "delete": "delete", "distinct": "list", "export": "mulexport", "import_": "add", "get": "show", "get_list": "list", "info": "list", "post": "add", "put": "edit", "refresh": "edit", "related": "list", "related_objects": "list", "schemas": "list", "select_star": "list", "table_metadata": "list", "test_connection": "post", "thumbnail": "list", "viz_types": "list", } order_rel_fields: Dict[str, Tuple[str, str]] = {} """ Impose ordering on related fields query:: order_rel_fields = { "<RELATED_FIELD>": ("<RELATED_FIELD_FIELD>", "<asc|desc>"), ... } """ related_field_filters: Dict[str, Union[RelatedFieldFilter, str]] = {} """ Declare the filters for related fields:: related_fields = { "<RELATED_FIELD>": <RelatedFieldFilter>) } """ filter_rel_fields: Dict[str, BaseFilter] = {} """ Declare the related field base filter:: filter_rel_fields_field = { "<RELATED_FIELD>": "<FILTER>") } """ allowed_rel_fields: Set[str] = set() # Declare a set of allowed related fields that the `related` endpoint supports. text_field_rel_fields: Dict[str, str] = {} """ Declare an alternative for the human readable representation of the Model object:: text_field_rel_fields = { "<RELATED_FIELD>": "<RELATED_OBJECT_FIELD>" } """ allowed_distinct_fields: Set[str] = set() add_columns: List[str] edit_columns: List[str] list_columns: List[str] show_columns: List[str] responses = { "400": {"description": "Bad request", "content": error_payload_content}, "401": {"description": "Unauthorized", "content": error_payload_content}, "403": {"description": "Forbidden", "content": error_payload_content}, "404": {"description": "Not found", "content": error_payload_content}, "422": { "description": "Could not process entity", "content": error_payload_content, }, "500": {"description": "Fatal error", "content": error_payload_content}, } def __init__(self) -> None: super().__init__() # Setup statsd self.stats_logger = BaseStatsLogger() # Add base API spec base query parameter schemas if self.apispec_parameter_schemas is None: # type: ignore self.apispec_parameter_schemas = {} self.apispec_parameter_schemas["get_related_schema"] = get_related_schema self.openapi_spec_component_schemas: Tuple[ Type[Schema], ... ] = self.openapi_spec_component_schemas + ( RelatedResponseSchema, DistincResponseSchema, ) def create_blueprint( self, appbuilder: AppBuilder, *args: Any, **kwargs: Any ) -> Blueprint: self.stats_logger = self.appbuilder.get_app.config["STATS_LOGGER"] return super().create_blueprint(appbuilder, *args, **kwargs) def _init_properties(self) -> None: """ Lock down initial not configured REST API columns. We want to just expose model ids, if something is misconfigured. By default FAB exposes all available columns on a Model """ model_id = self.datamodel.get_pk_name() if self.list_columns is None and not self.list_model_schema: self.list_columns = [model_id] if self.show_columns is None and not self.show_model_schema: self.show_columns = [model_id] if self.edit_columns is None and not self.edit_model_schema: self.edit_columns = [model_id] if self.add_columns is None and not self.add_model_schema: self.add_columns = [model_id] super()._init_properties() def _get_related_filter( self, datamodel: SQLAInterface, column_name: str, value: str ) -> Filters: filter_field = self.related_field_filters.get(column_name) if isinstance(filter_field, str): filter_field = RelatedFieldFilter(cast(str, filter_field), FilterStartsWith) filter_field = cast(RelatedFieldFilter, filter_field) search_columns = [filter_field.field_name] if filter_field else None filters = datamodel.get_filters(search_columns) base_filters = self.filter_rel_fields.get(column_name) if base_filters: filters.add_filter_list(base_filters) if value and filter_field: filters.add_filter( filter_field.field_name, filter_field.filter_class, value ) return filters def _get_distinct_filter(self, column_name: str, value: str) -> Filters: filter_field = RelatedFieldFilter(column_name, FilterStartsWith) filter_field = cast(RelatedFieldFilter, filter_field) search_columns = [filter_field.field_name] if filter_field else None filters = self.datamodel.get_filters(search_columns) filters.add_filter_list(self.base_filters) if value and filter_field: filters.add_filter( filter_field.field_name, filter_field.filter_class, value ) return filters def _get_text_for_model(self, model: Model, column_name: str) -> str: if column_name in self.text_field_rel_fields: model_column_name = self.text_field_rel_fields.get(column_name) if model_column_name: return getattr(model, model_column_name) return str(model) def _get_result_from_rows( self, datamodel: SQLAInterface, rows: List[Model], column_name: str ) -> List[Dict[str, Any]]: return [ { "value": datamodel.get_pk_value(row), "text": self._get_text_for_model(row, column_name), } for row in rows ] def _add_extra_ids_to_result( self, datamodel: SQLAInterface, column_name: str, ids: List[int], result: List[Dict[str, Any]], ) -> None: if ids: # Filter out already present values on the result values = [row["value"] for row in result] ids = [id_ for id_ in ids if id_ not in values] pk_col = datamodel.get_pk() # Fetch requested values from ids extra_rows = db.session.query(datamodel.obj).filter(pk_col.in_(ids)).all() result += self._get_result_from_rows(datamodel, extra_rows, column_name) def incr_stats(self, action: str, func_name: str) -> None: """ Proxy function for statsd.incr to impose a key structure for REST API's :param action: String with an action name eg: error, success :param func_name: The function name """ self.stats_logger.incr(f"{self.__class__.__name__}.{func_name}.{action}") def timing_stats(self, action: str, func_name: str, value: float) -> None: """ Proxy function for statsd.incr to impose a key structure for REST API's :param action: String with an action name eg: error, success :param func_name: The function name :param value: A float with the time it took for the endpoint to execute """ self.stats_logger.timing( f"{self.__class__.__name__}.{func_name}.{action}", value ) def send_stats_metrics( self, response: Response, key: str, time_delta: Optional[float] = None ) -> None: """ Helper function to handle sending statsd metrics :param response: flask response object, will evaluate if it was an error :param key: The function name :param time_delta: Optional time it took for the endpoint to execute """ if 200 <= response.status_code < 400: self.incr_stats("success", key) else: self.incr_stats("error", key) if time_delta: self.timing_stats("time", key, time_delta) @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.info", object_ref=False, log_to_statsd=False, ) def info_headless(self, **kwargs: Any) -> Response: """ Add statsd metrics to builtin FAB _info endpoint """ duration, response = time_function(super().info_headless, **kwargs) self.send_stats_metrics(response, self.info.__name__, duration) return response @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.get", object_ref=False, log_to_statsd=False, ) def get_headless(self, pk: int, **kwargs: Any) -> Response: """ Add statsd metrics to builtin FAB GET endpoint """ duration, response = time_function(super().get_headless, pk, **kwargs) self.send_stats_metrics(response, self.get.__name__, duration) return response @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.get_list", object_ref=False, log_to_statsd=False, ) def get_list_headless(self, **kwargs: Any) -> Response: """ Add statsd metrics to builtin FAB GET list endpoint """ duration, response = time_function(super().get_list_headless, **kwargs) self.send_stats_metrics(response, self.get_list.__name__, duration) return response @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.post", object_ref=False, log_to_statsd=False, ) def post_headless(self) -> Response: """ Add statsd metrics to builtin FAB POST endpoint """ duration, response = time_function(super().post_headless) self.send_stats_metrics(response, self.post.__name__, duration) return response @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.put", object_ref=False, log_to_statsd=False, ) def put_headless(self, pk: int) -> Response: """ Add statsd metrics to builtin FAB PUT endpoint """ duration, response = time_function(super().put_headless, pk) self.send_stats_metrics(response, self.put.__name__, duration) return response @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.delete", object_ref=False, log_to_statsd=False, ) def delete_headless(self, pk: int) -> Response: """ Add statsd metrics to builtin FAB DELETE endpoint """ duration, response = time_function(super().delete_headless, pk) self.send_stats_metrics(response, self.delete.__name__, duration) return response @expose("/related/<column_name>", methods=["GET"]) @protect() @safe @statsd_metrics @rison(get_related_schema) def related(self, column_name: str, **kwargs: Any) -> FlaskResponse: """Get related fields data --- get: parameters: - in: path schema: type: string name: column_name - in: query name: q content: application/json: schema: $ref: '#/components/schemas/get_related_schema' responses: 200: description: Related column data content: application/json: schema: schema: $ref: "#/components/schemas/RelatedResponseSchema" 400: $ref: '#/components/responses/400' 401: $ref: '#/components/responses/401' 404: $ref: '#/components/responses/404' 500: $ref: '#/components/responses/500' """ if column_name not in self.allowed_rel_fields: self.incr_stats("error", self.related.__name__) return self.response_404() args = kwargs.get("rison", {}) # handle pagination page, page_size = self._handle_page_args(args) ids = args.get("include_ids") if page and ids: # pagination with forced ids is not supported return self.response_422() try: datamodel = self.datamodel.get_related_interface(column_name) except KeyError: return self.response_404() page, page_size = self._sanitize_page_args(page, page_size) # handle ordering order_field = self.order_rel_fields.get(column_name) if order_field: order_column, order_direction = order_field else: order_column, order_direction = "", "" # handle filters filters = self._get_related_filter(datamodel, column_name, args.get("filter")) # Make the query total_rows, rows = datamodel.query( filters, order_column, order_direction, page=page, page_size=page_size ) # produce response result = self._get_result_from_rows(datamodel, rows, column_name) # If ids are specified make sure we fetch and include them on the response if ids: self._add_extra_ids_to_result(datamodel, column_name, ids, result) total_rows = len(result) return self.response(200, count=total_rows, result=result) @expose("/distinct/<column_name>", methods=["GET"]) @protect() @safe @statsd_metrics @rison(get_related_schema) def distinct(self, column_name: str, **kwargs: Any) -> FlaskResponse: """Get distinct values from field data --- get: parameters: - in: path schema: type: string name: column_name - in: query name: q content: application/json: schema: $ref: '#/components/schemas/get_related_schema' responses: 200: description: Distinct field data content: application/json: schema: schema: $ref: "#/components/schemas/DistincResponseSchema" 400: $ref: '#/components/responses/400' 401: $ref: '#/components/responses/401' 404: $ref: '#/components/responses/404' 500: $ref: '#/components/responses/500' """ if column_name not in self.allowed_distinct_fields: self.incr_stats("error", self.related.__name__) return self.response_404() args = kwargs.get("rison", {}) # handle pagination page, page_size = self._sanitize_page_args(*self._handle_page_args(args)) # Create generic base filters with added request filter filters = self._get_distinct_filter(column_name, args.get("filter")) # Make the query query_count = self.appbuilder.get_session.query( func.count(distinct(getattr(self.datamodel.obj, column_name))) ) count = self.datamodel.apply_filters(query_count, filters).scalar() if count == 0: return self.response(200, count=count, result=[]) query = self.appbuilder.get_session.query( distinct(getattr(self.datamodel.obj, column_name)) ) # Apply generic base filters with added request filter query = self.datamodel.apply_filters(query, filters) # Apply sort query = self.datamodel.apply_order_by(query, column_name, "asc") # Apply pagination result = self.datamodel.apply_pagination(query, page, page_size).all() # produce response result = [ {"text": item[0], "value": item[0]} for item in result if item[0] is not None ] return self.response(200, count=count, result=result)
superset/views/base_api.py
1
https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f
[ 0.9763200283050537, 0.03634060174226761, 0.0001646710152272135, 0.00017699928139336407, 0.17203477025032043 ]
{ "id": 8, "code_window": [ " object_ref=False,\n", " log_to_statsd=False,\n", " )\n", " def delete_headless(self, pk: int) -> Response:\n", " \"\"\"\n", " Add statsd metrics to builtin FAB DELETE endpoint\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " @handle_api_exception\n" ], "file_path": "superset/views/base_api.py", "type": "add", "edit_start_line_idx": 453 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { SyntheticEvent } from 'react'; import domToImage, { Options } from 'dom-to-image'; import kebabCase from 'lodash/kebabCase'; import { t } from '@superset-ui/core'; import { addWarningToast } from 'src/components/MessageToasts/actions'; /** * @remark * same as https://github.com/apache/superset/blob/c53bc4ddf9808a8bb6916bbe3cb31935d33a2420/superset-frontend/src/assets/stylesheets/less/variables.less#L34 */ const GRAY_BACKGROUND_COLOR = '#F5F5F5'; /** * generate a consistent file stem from a description and date * * @param description title or description of content of file * @param date date when file was generated */ const generateFileStem = (description: string, date = new Date()) => `${kebabCase(description)}-${date.toISOString().replace(/[: ]/g, '-')}`; /** * Create an event handler for turning an element into an image * * @param selector css selector of the parent element which should be turned into image * @param description name or a short description of what is being printed. * Value will be normalized, and a date as well as a file extension will be added. * @param domToImageOptions dom-to-image Options object. * @param isExactSelector if false, searches for the closest ancestor that matches selector. * @returns event handler */ export default function downloadAsImage( selector: string, description: string, domToImageOptions: Options = {}, isExactSelector = false, ) { return (event: SyntheticEvent) => { const elementToPrint = isExactSelector ? document.querySelector(selector) : event.currentTarget.closest(selector); if (!elementToPrint) { return addWarningToast( t('Image download failed, please refresh and try again.'), ); } // Mapbox controls are loaded from different origin, causing CORS error // See https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL#exceptions const filter = (node: Element) => { if (typeof node.className === 'string') { return ( node.className !== 'mapboxgl-control-container' && !node.className.includes('ant-dropdown') ); } return true; }; return domToImage .toJpeg(elementToPrint, { quality: 0.95, bgcolor: GRAY_BACKGROUND_COLOR, filter, }) .then(dataUrl => { const link = document.createElement('a'); link.download = `${generateFileStem(description)}.jpg`; link.href = dataUrl; link.click(); }) .catch(e => { console.error('Creating image failed', e); }); }; }
superset-frontend/src/utils/downloadAsImage.ts
0
https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f
[ 0.00017489618039689958, 0.00017285969806835055, 0.00016949104610830545, 0.0001734258548822254, 0.0000019016007399841328 ]
{ "id": 8, "code_window": [ " object_ref=False,\n", " log_to_statsd=False,\n", " )\n", " def delete_headless(self, pk: int) -> Response:\n", " \"\"\"\n", " Add statsd metrics to builtin FAB DELETE endpoint\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " @handle_api_exception\n" ], "file_path": "superset/views/base_api.py", "type": "add", "edit_start_line_idx": 453 }
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> # Change Log All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. # [0.18.0](https://github.com/apache-superset/superset-ui/compare/v0.17.87...v0.18.0) (2021-08-30) **Note:** Version bump only for package @superset-ui/legacy-plugin-chart-chord ## [0.17.61](https://github.com/apache-superset/superset-ui/compare/v0.17.60...v0.17.61) (2021-07-02) **Note:** Version bump only for package @superset-ui/legacy-plugin-chart-chord
superset-frontend/plugins/legacy-plugin-chart-chord/CHANGELOG.md
0
https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f
[ 0.00017874174227472395, 0.00017430420848540962, 0.00016909395344555378, 0.00017469056183472276, 0.0000035527862110029673 ]
{ "id": 8, "code_window": [ " object_ref=False,\n", " log_to_statsd=False,\n", " )\n", " def delete_headless(self, pk: int) -> Response:\n", " \"\"\"\n", " Add statsd metrics to builtin FAB DELETE endpoint\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " @handle_api_exception\n" ], "file_path": "superset/views/base_api.py", "type": "add", "edit_start_line_idx": 453 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import logging from typing import Optional from flask_appbuilder.models.sqla import Model from flask_appbuilder.security.sqla.models import User from flask_babel import lazy_gettext as _ from superset.commands.base import BaseCommand from superset.dao.exceptions import DAODeleteFailedError from superset.databases.commands.exceptions import ( DatabaseDeleteDatasetsExistFailedError, DatabaseDeleteFailedError, DatabaseDeleteFailedReportsExistError, DatabaseNotFoundError, ) from superset.databases.dao import DatabaseDAO from superset.models.core import Database from superset.reports.dao import ReportScheduleDAO logger = logging.getLogger(__name__) class DeleteDatabaseCommand(BaseCommand): def __init__(self, user: User, model_id: int): self._actor = user self._model_id = model_id self._model: Optional[Database] = None def run(self) -> Model: self.validate() try: database = DatabaseDAO.delete(self._model) except DAODeleteFailedError as ex: logger.exception(ex.exception) raise DatabaseDeleteFailedError() from ex return database def validate(self) -> None: # Validate/populate model exists self._model = DatabaseDAO.find_by_id(self._model_id) if not self._model: raise DatabaseNotFoundError() # Check there are no associated ReportSchedules reports = ReportScheduleDAO.find_by_database_id(self._model_id) if reports: report_names = [report.name for report in reports] raise DatabaseDeleteFailedReportsExistError( _("There are associated alerts or reports: %s" % ",".join(report_names)) ) # Check if there are datasets for this database if self._model.tables: raise DatabaseDeleteDatasetsExistFailedError()
superset/databases/commands/delete.py
0
https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f
[ 0.0002212743420386687, 0.0001794102427083999, 0.00016861125186551362, 0.00017255939019378275, 0.00001732746750349179 ]
{ "id": 9, "code_window": [ " @safe\n", " @statsd_metrics\n", " @rison(get_related_schema)\n", " def related(self, column_name: str, **kwargs: Any) -> FlaskResponse:\n", " \"\"\"Get related fields data\n", " ---\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " @handle_api_exception\n" ], "file_path": "superset/views/base_api.py", "type": "add", "edit_start_line_idx": 466 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import functools import logging from typing import Any, Callable, cast, Dict, List, Optional, Set, Tuple, Type, Union from flask import Blueprint, g, request, Response from flask_appbuilder import AppBuilder, Model, ModelRestApi from flask_appbuilder.api import expose, protect, rison, safe from flask_appbuilder.models.filters import BaseFilter, Filters from flask_appbuilder.models.sqla.filters import FilterStartsWith from flask_appbuilder.models.sqla.interface import SQLAInterface from flask_babel import lazy_gettext as _ from marshmallow import fields, Schema from sqlalchemy import and_, distinct, func from sqlalchemy.orm.query import Query from superset.exceptions import InvalidPayloadFormatError from superset.extensions import db, event_logger, security_manager from superset.models.core import FavStar from superset.models.dashboard import Dashboard from superset.models.slice import Slice from superset.schemas import error_payload_content from superset.sql_lab import Query as SqllabQuery from superset.stats_logger import BaseStatsLogger from superset.superset_typing import FlaskResponse from superset.utils.core import time_function logger = logging.getLogger(__name__) get_related_schema = { "type": "object", "properties": { "page_size": {"type": "integer"}, "page": {"type": "integer"}, "include_ids": {"type": "array", "items": {"type": "integer"}}, "filter": {"type": "string"}, }, } class RelatedResultResponseSchema(Schema): value = fields.Integer(description="The related item identifier") text = fields.String(description="The related item string representation") class RelatedResponseSchema(Schema): count = fields.Integer(description="The total number of related values") result = fields.List(fields.Nested(RelatedResultResponseSchema)) class DistinctResultResponseSchema(Schema): text = fields.String(description="The distinct item") class DistincResponseSchema(Schema): count = fields.Integer(description="The total number of distinct values") result = fields.List(fields.Nested(DistinctResultResponseSchema)) def requires_json(f: Callable[..., Any]) -> Callable[..., Any]: """ Require JSON-like formatted request to the REST API """ def wraps(self: "BaseSupersetModelRestApi", *args: Any, **kwargs: Any) -> Response: if not request.is_json: raise InvalidPayloadFormatError(message="Request is not JSON") return f(self, *args, **kwargs) return functools.update_wrapper(wraps, f) def requires_form_data(f: Callable[..., Any]) -> Callable[..., Any]: """ Require 'multipart/form-data' as request MIME type """ def wraps(self: "BaseSupersetModelRestApi", *args: Any, **kwargs: Any) -> Response: if not request.mimetype == "multipart/form-data": raise InvalidPayloadFormatError( message="Request MIME type is not 'multipart/form-data'" ) return f(self, *args, **kwargs) return functools.update_wrapper(wraps, f) def statsd_metrics(f: Callable[..., Any]) -> Callable[..., Any]: """ Handle sending all statsd metrics from the REST API """ def wraps(self: "BaseSupersetModelRestApi", *args: Any, **kwargs: Any) -> Response: try: duration, response = time_function(f, self, *args, **kwargs) except Exception as ex: self.incr_stats("error", f.__name__) raise ex self.send_stats_metrics(response, f.__name__, duration) return response return functools.update_wrapper(wraps, f) class RelatedFieldFilter: # data class to specify what filter to use on a /related endpoint # pylint: disable=too-few-public-methods def __init__(self, field_name: str, filter_class: Type[BaseFilter]): self.field_name = field_name self.filter_class = filter_class class BaseFavoriteFilter(BaseFilter): # pylint: disable=too-few-public-methods """ Base Custom filter for the GET list that filters all dashboards, slices that a user has favored or not """ name = _("Is favorite") arg_name = "" class_name = "" """ The FavStar class_name to user """ model: Type[Union[Dashboard, Slice, SqllabQuery]] = Dashboard """ The SQLAlchemy model """ def apply(self, query: Query, value: Any) -> Query: # If anonymous user filter nothing if security_manager.current_user is None: return query users_favorite_query = db.session.query(FavStar.obj_id).filter( and_( FavStar.user_id == g.user.get_id(), FavStar.class_name == self.class_name, ) ) if value: return query.filter(and_(self.model.id.in_(users_favorite_query))) return query.filter(and_(~self.model.id.in_(users_favorite_query))) class BaseSupersetModelRestApi(ModelRestApi): """ Extends FAB's ModelResApi to implement specific superset generic functionality """ csrf_exempt = False method_permission_name = { "bulk_delete": "delete", "data": "list", "data_from_cache": "list", "delete": "delete", "distinct": "list", "export": "mulexport", "import_": "add", "get": "show", "get_list": "list", "info": "list", "post": "add", "put": "edit", "refresh": "edit", "related": "list", "related_objects": "list", "schemas": "list", "select_star": "list", "table_metadata": "list", "test_connection": "post", "thumbnail": "list", "viz_types": "list", } order_rel_fields: Dict[str, Tuple[str, str]] = {} """ Impose ordering on related fields query:: order_rel_fields = { "<RELATED_FIELD>": ("<RELATED_FIELD_FIELD>", "<asc|desc>"), ... } """ related_field_filters: Dict[str, Union[RelatedFieldFilter, str]] = {} """ Declare the filters for related fields:: related_fields = { "<RELATED_FIELD>": <RelatedFieldFilter>) } """ filter_rel_fields: Dict[str, BaseFilter] = {} """ Declare the related field base filter:: filter_rel_fields_field = { "<RELATED_FIELD>": "<FILTER>") } """ allowed_rel_fields: Set[str] = set() # Declare a set of allowed related fields that the `related` endpoint supports. text_field_rel_fields: Dict[str, str] = {} """ Declare an alternative for the human readable representation of the Model object:: text_field_rel_fields = { "<RELATED_FIELD>": "<RELATED_OBJECT_FIELD>" } """ allowed_distinct_fields: Set[str] = set() add_columns: List[str] edit_columns: List[str] list_columns: List[str] show_columns: List[str] responses = { "400": {"description": "Bad request", "content": error_payload_content}, "401": {"description": "Unauthorized", "content": error_payload_content}, "403": {"description": "Forbidden", "content": error_payload_content}, "404": {"description": "Not found", "content": error_payload_content}, "422": { "description": "Could not process entity", "content": error_payload_content, }, "500": {"description": "Fatal error", "content": error_payload_content}, } def __init__(self) -> None: super().__init__() # Setup statsd self.stats_logger = BaseStatsLogger() # Add base API spec base query parameter schemas if self.apispec_parameter_schemas is None: # type: ignore self.apispec_parameter_schemas = {} self.apispec_parameter_schemas["get_related_schema"] = get_related_schema self.openapi_spec_component_schemas: Tuple[ Type[Schema], ... ] = self.openapi_spec_component_schemas + ( RelatedResponseSchema, DistincResponseSchema, ) def create_blueprint( self, appbuilder: AppBuilder, *args: Any, **kwargs: Any ) -> Blueprint: self.stats_logger = self.appbuilder.get_app.config["STATS_LOGGER"] return super().create_blueprint(appbuilder, *args, **kwargs) def _init_properties(self) -> None: """ Lock down initial not configured REST API columns. We want to just expose model ids, if something is misconfigured. By default FAB exposes all available columns on a Model """ model_id = self.datamodel.get_pk_name() if self.list_columns is None and not self.list_model_schema: self.list_columns = [model_id] if self.show_columns is None and not self.show_model_schema: self.show_columns = [model_id] if self.edit_columns is None and not self.edit_model_schema: self.edit_columns = [model_id] if self.add_columns is None and not self.add_model_schema: self.add_columns = [model_id] super()._init_properties() def _get_related_filter( self, datamodel: SQLAInterface, column_name: str, value: str ) -> Filters: filter_field = self.related_field_filters.get(column_name) if isinstance(filter_field, str): filter_field = RelatedFieldFilter(cast(str, filter_field), FilterStartsWith) filter_field = cast(RelatedFieldFilter, filter_field) search_columns = [filter_field.field_name] if filter_field else None filters = datamodel.get_filters(search_columns) base_filters = self.filter_rel_fields.get(column_name) if base_filters: filters.add_filter_list(base_filters) if value and filter_field: filters.add_filter( filter_field.field_name, filter_field.filter_class, value ) return filters def _get_distinct_filter(self, column_name: str, value: str) -> Filters: filter_field = RelatedFieldFilter(column_name, FilterStartsWith) filter_field = cast(RelatedFieldFilter, filter_field) search_columns = [filter_field.field_name] if filter_field else None filters = self.datamodel.get_filters(search_columns) filters.add_filter_list(self.base_filters) if value and filter_field: filters.add_filter( filter_field.field_name, filter_field.filter_class, value ) return filters def _get_text_for_model(self, model: Model, column_name: str) -> str: if column_name in self.text_field_rel_fields: model_column_name = self.text_field_rel_fields.get(column_name) if model_column_name: return getattr(model, model_column_name) return str(model) def _get_result_from_rows( self, datamodel: SQLAInterface, rows: List[Model], column_name: str ) -> List[Dict[str, Any]]: return [ { "value": datamodel.get_pk_value(row), "text": self._get_text_for_model(row, column_name), } for row in rows ] def _add_extra_ids_to_result( self, datamodel: SQLAInterface, column_name: str, ids: List[int], result: List[Dict[str, Any]], ) -> None: if ids: # Filter out already present values on the result values = [row["value"] for row in result] ids = [id_ for id_ in ids if id_ not in values] pk_col = datamodel.get_pk() # Fetch requested values from ids extra_rows = db.session.query(datamodel.obj).filter(pk_col.in_(ids)).all() result += self._get_result_from_rows(datamodel, extra_rows, column_name) def incr_stats(self, action: str, func_name: str) -> None: """ Proxy function for statsd.incr to impose a key structure for REST API's :param action: String with an action name eg: error, success :param func_name: The function name """ self.stats_logger.incr(f"{self.__class__.__name__}.{func_name}.{action}") def timing_stats(self, action: str, func_name: str, value: float) -> None: """ Proxy function for statsd.incr to impose a key structure for REST API's :param action: String with an action name eg: error, success :param func_name: The function name :param value: A float with the time it took for the endpoint to execute """ self.stats_logger.timing( f"{self.__class__.__name__}.{func_name}.{action}", value ) def send_stats_metrics( self, response: Response, key: str, time_delta: Optional[float] = None ) -> None: """ Helper function to handle sending statsd metrics :param response: flask response object, will evaluate if it was an error :param key: The function name :param time_delta: Optional time it took for the endpoint to execute """ if 200 <= response.status_code < 400: self.incr_stats("success", key) else: self.incr_stats("error", key) if time_delta: self.timing_stats("time", key, time_delta) @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.info", object_ref=False, log_to_statsd=False, ) def info_headless(self, **kwargs: Any) -> Response: """ Add statsd metrics to builtin FAB _info endpoint """ duration, response = time_function(super().info_headless, **kwargs) self.send_stats_metrics(response, self.info.__name__, duration) return response @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.get", object_ref=False, log_to_statsd=False, ) def get_headless(self, pk: int, **kwargs: Any) -> Response: """ Add statsd metrics to builtin FAB GET endpoint """ duration, response = time_function(super().get_headless, pk, **kwargs) self.send_stats_metrics(response, self.get.__name__, duration) return response @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.get_list", object_ref=False, log_to_statsd=False, ) def get_list_headless(self, **kwargs: Any) -> Response: """ Add statsd metrics to builtin FAB GET list endpoint """ duration, response = time_function(super().get_list_headless, **kwargs) self.send_stats_metrics(response, self.get_list.__name__, duration) return response @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.post", object_ref=False, log_to_statsd=False, ) def post_headless(self) -> Response: """ Add statsd metrics to builtin FAB POST endpoint """ duration, response = time_function(super().post_headless) self.send_stats_metrics(response, self.post.__name__, duration) return response @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.put", object_ref=False, log_to_statsd=False, ) def put_headless(self, pk: int) -> Response: """ Add statsd metrics to builtin FAB PUT endpoint """ duration, response = time_function(super().put_headless, pk) self.send_stats_metrics(response, self.put.__name__, duration) return response @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.delete", object_ref=False, log_to_statsd=False, ) def delete_headless(self, pk: int) -> Response: """ Add statsd metrics to builtin FAB DELETE endpoint """ duration, response = time_function(super().delete_headless, pk) self.send_stats_metrics(response, self.delete.__name__, duration) return response @expose("/related/<column_name>", methods=["GET"]) @protect() @safe @statsd_metrics @rison(get_related_schema) def related(self, column_name: str, **kwargs: Any) -> FlaskResponse: """Get related fields data --- get: parameters: - in: path schema: type: string name: column_name - in: query name: q content: application/json: schema: $ref: '#/components/schemas/get_related_schema' responses: 200: description: Related column data content: application/json: schema: schema: $ref: "#/components/schemas/RelatedResponseSchema" 400: $ref: '#/components/responses/400' 401: $ref: '#/components/responses/401' 404: $ref: '#/components/responses/404' 500: $ref: '#/components/responses/500' """ if column_name not in self.allowed_rel_fields: self.incr_stats("error", self.related.__name__) return self.response_404() args = kwargs.get("rison", {}) # handle pagination page, page_size = self._handle_page_args(args) ids = args.get("include_ids") if page and ids: # pagination with forced ids is not supported return self.response_422() try: datamodel = self.datamodel.get_related_interface(column_name) except KeyError: return self.response_404() page, page_size = self._sanitize_page_args(page, page_size) # handle ordering order_field = self.order_rel_fields.get(column_name) if order_field: order_column, order_direction = order_field else: order_column, order_direction = "", "" # handle filters filters = self._get_related_filter(datamodel, column_name, args.get("filter")) # Make the query total_rows, rows = datamodel.query( filters, order_column, order_direction, page=page, page_size=page_size ) # produce response result = self._get_result_from_rows(datamodel, rows, column_name) # If ids are specified make sure we fetch and include them on the response if ids: self._add_extra_ids_to_result(datamodel, column_name, ids, result) total_rows = len(result) return self.response(200, count=total_rows, result=result) @expose("/distinct/<column_name>", methods=["GET"]) @protect() @safe @statsd_metrics @rison(get_related_schema) def distinct(self, column_name: str, **kwargs: Any) -> FlaskResponse: """Get distinct values from field data --- get: parameters: - in: path schema: type: string name: column_name - in: query name: q content: application/json: schema: $ref: '#/components/schemas/get_related_schema' responses: 200: description: Distinct field data content: application/json: schema: schema: $ref: "#/components/schemas/DistincResponseSchema" 400: $ref: '#/components/responses/400' 401: $ref: '#/components/responses/401' 404: $ref: '#/components/responses/404' 500: $ref: '#/components/responses/500' """ if column_name not in self.allowed_distinct_fields: self.incr_stats("error", self.related.__name__) return self.response_404() args = kwargs.get("rison", {}) # handle pagination page, page_size = self._sanitize_page_args(*self._handle_page_args(args)) # Create generic base filters with added request filter filters = self._get_distinct_filter(column_name, args.get("filter")) # Make the query query_count = self.appbuilder.get_session.query( func.count(distinct(getattr(self.datamodel.obj, column_name))) ) count = self.datamodel.apply_filters(query_count, filters).scalar() if count == 0: return self.response(200, count=count, result=[]) query = self.appbuilder.get_session.query( distinct(getattr(self.datamodel.obj, column_name)) ) # Apply generic base filters with added request filter query = self.datamodel.apply_filters(query, filters) # Apply sort query = self.datamodel.apply_order_by(query, column_name, "asc") # Apply pagination result = self.datamodel.apply_pagination(query, page, page_size).all() # produce response result = [ {"text": item[0], "value": item[0]} for item in result if item[0] is not None ] return self.response(200, count=count, result=result)
superset/views/base_api.py
1
https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f
[ 0.9923330545425415, 0.05402177572250366, 0.00016534679161850363, 0.0006274938932619989, 0.19150324165821075 ]
{ "id": 9, "code_window": [ " @safe\n", " @statsd_metrics\n", " @rison(get_related_schema)\n", " def related(self, column_name: str, **kwargs: Any) -> FlaskResponse:\n", " \"\"\"Get related fields data\n", " ---\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " @handle_api_exception\n" ], "file_path": "superset/views/base_api.py", "type": "add", "edit_start_line_idx": 466 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import logging from typing import Optional from flask import flash from flask_appbuilder import expose from werkzeug.utils import redirect from superset import db, event_logger from superset.models import core as models from superset.superset_typing import FlaskResponse from superset.views.base import BaseSupersetView logger = logging.getLogger(__name__) class R(BaseSupersetView): # pylint: disable=invalid-name """used for short urls""" @staticmethod def _validate_url(url: Optional[str] = None) -> bool: if url and ( url.startswith("//superset/dashboard/") or url.startswith("//superset/explore/") ): return True return False @event_logger.log_this @expose("/<int:url_id>") def index(self, url_id: int) -> FlaskResponse: url = db.session.query(models.Url).get(url_id) if url and url.url: explore_url = "//superset/explore/?" if url.url.startswith(explore_url): explore_url += f"r={url_id}" return redirect(explore_url[1:]) if self._validate_url(url.url): return redirect(url.url[1:]) return redirect("/") flash("URL to nowhere...", "danger") return redirect("/")
superset/views/redirects.py
0
https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f
[ 0.0002717625757213682, 0.00018940751033369452, 0.00016707759641576558, 0.00017423128883820027, 0.000036930628994014114 ]
{ "id": 9, "code_window": [ " @safe\n", " @statsd_metrics\n", " @rison(get_related_schema)\n", " def related(self, column_name: str, **kwargs: Any) -> FlaskResponse:\n", " \"\"\"Get related fields data\n", " ---\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " @handle_api_exception\n" ], "file_path": "superset/views/base_api.py", "type": "add", "edit_start_line_idx": 466 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import json import pickle from typing import Any, Dict, Iterator from uuid import uuid3 import pytest from sqlalchemy.orm import Session from superset import db from superset.key_value.models import KeyValueEntry from superset.key_value.types import KeyValueResource from superset.key_value.utils import decode_permalink_id, encode_permalink_key from superset.models.slice import Slice from tests.integration_tests.base_tests import login from tests.integration_tests.fixtures.client import client from tests.integration_tests.fixtures.world_bank_dashboard import ( load_world_bank_dashboard_with_slices, load_world_bank_data, ) from tests.integration_tests.test_app import app @pytest.fixture def chart(load_world_bank_dashboard_with_slices) -> Slice: with app.app_context() as ctx: session: Session = ctx.app.appbuilder.get_session chart = session.query(Slice).filter_by(slice_name="World's Population").one() return chart @pytest.fixture def form_data(chart) -> Dict[str, Any]: datasource = f"{chart.datasource.id}__{chart.datasource.type}" return { "chart_id": chart.id, "datasource": datasource, } @pytest.fixture def permalink_salt() -> Iterator[str]: from superset.key_value.shared_entries import get_permalink_salt, get_uuid_namespace from superset.key_value.types import SharedKey key = SharedKey.EXPLORE_PERMALINK_SALT salt = get_permalink_salt(key) yield salt namespace = get_uuid_namespace(salt) db.session.query(KeyValueEntry).filter_by( resource=KeyValueResource.APP, uuid=uuid3(namespace, key), ) db.session.commit() def test_post(client, form_data: Dict[str, Any], permalink_salt: str): login(client, "admin") resp = client.post(f"api/v1/explore/permalink", json={"formData": form_data}) assert resp.status_code == 201 data = json.loads(resp.data.decode("utf-8")) key = data["key"] url = data["url"] assert key in url id_ = decode_permalink_id(key, permalink_salt) db.session.query(KeyValueEntry).filter_by(id=id_).delete() db.session.commit() def test_post_access_denied(client, form_data): login(client, "gamma") resp = client.post(f"api/v1/explore/permalink", json={"formData": form_data}) assert resp.status_code == 404 def test_get_missing_chart(client, chart, permalink_salt: str) -> None: from superset.key_value.models import KeyValueEntry chart_id = 1234 entry = KeyValueEntry( resource=KeyValueResource.EXPLORE_PERMALINK, value=pickle.dumps( { "chartId": chart_id, "datasetId": chart.datasource.id, "formData": { "slice_id": chart_id, "datasource": f"{chart.datasource.id}__{chart.datasource.type}", }, } ), ) db.session.add(entry) db.session.commit() key = encode_permalink_key(entry.id, permalink_salt) login(client, "admin") resp = client.get(f"api/v1/explore/permalink/{key}") assert resp.status_code == 404 db.session.delete(entry) db.session.commit() def test_post_invalid_schema(client) -> None: login(client, "admin") resp = client.post(f"api/v1/explore/permalink", json={"abc": 123}) assert resp.status_code == 400 def test_get(client, form_data: Dict[str, Any], permalink_salt: str) -> None: login(client, "admin") resp = client.post(f"api/v1/explore/permalink", json={"formData": form_data}) data = json.loads(resp.data.decode("utf-8")) key = data["key"] resp = client.get(f"api/v1/explore/permalink/{key}") assert resp.status_code == 200 result = json.loads(resp.data.decode("utf-8")) assert result["state"]["formData"] == form_data id_ = decode_permalink_id(key, permalink_salt) db.session.query(KeyValueEntry).filter_by(id=id_).delete() db.session.commit()
tests/integration_tests/explore/permalink/api_tests.py
0
https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f
[ 0.0001753530523274094, 0.00017140053387265652, 0.00016678075189702213, 0.00017109312466345727, 0.0000028165850380901247 ]
{ "id": 9, "code_window": [ " @safe\n", " @statsd_metrics\n", " @rison(get_related_schema)\n", " def related(self, column_name: str, **kwargs: Any) -> FlaskResponse:\n", " \"\"\"Get related fields data\n", " ---\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " @handle_api_exception\n" ], "file_path": "superset/views/base_api.py", "type": "add", "edit_start_line_idx": 466 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from collections import defaultdict from superset import security_manager def cleanup_permissions() -> None: # 1. Clean up duplicates. pvms = security_manager.get_session.query( security_manager.permissionview_model ).all() print("# of permission view menues is: {}".format(len(pvms))) pvms_dict = defaultdict(list) for pvm in pvms: pvms_dict[(pvm.permission, pvm.view_menu)].append(pvm) duplicates = [v for v in pvms_dict.values() if len(v) > 1] len(duplicates) for pvm_list in duplicates: first_prm = pvm_list[0] roles = set(first_prm.role) for pvm in pvm_list[1:]: roles = roles.union(pvm.role) security_manager.get_session.delete(pvm) first_prm.roles = list(roles) security_manager.get_session.commit() pvms = security_manager.get_session.query( security_manager.permissionview_model ).all() print("Stage 1: # of permission view menues is: {}".format(len(pvms))) # 2. Clean up None permissions or view menues pvms = security_manager.get_session.query( security_manager.permissionview_model ).all() for pvm in pvms: if not (pvm.view_menu and pvm.permission): security_manager.get_session.delete(pvm) security_manager.get_session.commit() pvms = security_manager.get_session.query( security_manager.permissionview_model ).all() print("Stage 2: # of permission view menues is: {}".format(len(pvms))) # 3. Delete empty permission view menues from roles roles = security_manager.get_session.query(security_manager.role_model).all() for role in roles: role.permissions = [p for p in role.permissions if p] security_manager.get_session.commit() # 4. Delete empty roles from permission view menues pvms = security_manager.get_session.query( security_manager.permissionview_model ).all() for pvm in pvms: pvm.role = [r for r in pvm.role if r] security_manager.get_session.commit() cleanup_permissions()
scripts/permissions_cleanup.py
0
https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f
[ 0.00017698679585009813, 0.0001744080800563097, 0.0001711788645479828, 0.00017502537230029702, 0.000002045920155069325 ]
{ "id": 10, "code_window": [ " @expose(\"/distinct/<column_name>\", methods=[\"GET\"])\n", " @protect()\n", " @safe\n", " @statsd_metrics\n", " @rison(get_related_schema)\n", " def distinct(self, column_name: str, **kwargs: Any) -> FlaskResponse:\n", " \"\"\"Get distinct values from field data\n", " ---\n", " get:\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " @handle_api_exception\n" ], "file_path": "superset/views/base_api.py", "type": "add", "edit_start_line_idx": 544 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import functools import logging from typing import Any, Callable, cast, Dict, List, Optional, Set, Tuple, Type, Union from flask import Blueprint, g, request, Response from flask_appbuilder import AppBuilder, Model, ModelRestApi from flask_appbuilder.api import expose, protect, rison, safe from flask_appbuilder.models.filters import BaseFilter, Filters from flask_appbuilder.models.sqla.filters import FilterStartsWith from flask_appbuilder.models.sqla.interface import SQLAInterface from flask_babel import lazy_gettext as _ from marshmallow import fields, Schema from sqlalchemy import and_, distinct, func from sqlalchemy.orm.query import Query from superset.exceptions import InvalidPayloadFormatError from superset.extensions import db, event_logger, security_manager from superset.models.core import FavStar from superset.models.dashboard import Dashboard from superset.models.slice import Slice from superset.schemas import error_payload_content from superset.sql_lab import Query as SqllabQuery from superset.stats_logger import BaseStatsLogger from superset.superset_typing import FlaskResponse from superset.utils.core import time_function logger = logging.getLogger(__name__) get_related_schema = { "type": "object", "properties": { "page_size": {"type": "integer"}, "page": {"type": "integer"}, "include_ids": {"type": "array", "items": {"type": "integer"}}, "filter": {"type": "string"}, }, } class RelatedResultResponseSchema(Schema): value = fields.Integer(description="The related item identifier") text = fields.String(description="The related item string representation") class RelatedResponseSchema(Schema): count = fields.Integer(description="The total number of related values") result = fields.List(fields.Nested(RelatedResultResponseSchema)) class DistinctResultResponseSchema(Schema): text = fields.String(description="The distinct item") class DistincResponseSchema(Schema): count = fields.Integer(description="The total number of distinct values") result = fields.List(fields.Nested(DistinctResultResponseSchema)) def requires_json(f: Callable[..., Any]) -> Callable[..., Any]: """ Require JSON-like formatted request to the REST API """ def wraps(self: "BaseSupersetModelRestApi", *args: Any, **kwargs: Any) -> Response: if not request.is_json: raise InvalidPayloadFormatError(message="Request is not JSON") return f(self, *args, **kwargs) return functools.update_wrapper(wraps, f) def requires_form_data(f: Callable[..., Any]) -> Callable[..., Any]: """ Require 'multipart/form-data' as request MIME type """ def wraps(self: "BaseSupersetModelRestApi", *args: Any, **kwargs: Any) -> Response: if not request.mimetype == "multipart/form-data": raise InvalidPayloadFormatError( message="Request MIME type is not 'multipart/form-data'" ) return f(self, *args, **kwargs) return functools.update_wrapper(wraps, f) def statsd_metrics(f: Callable[..., Any]) -> Callable[..., Any]: """ Handle sending all statsd metrics from the REST API """ def wraps(self: "BaseSupersetModelRestApi", *args: Any, **kwargs: Any) -> Response: try: duration, response = time_function(f, self, *args, **kwargs) except Exception as ex: self.incr_stats("error", f.__name__) raise ex self.send_stats_metrics(response, f.__name__, duration) return response return functools.update_wrapper(wraps, f) class RelatedFieldFilter: # data class to specify what filter to use on a /related endpoint # pylint: disable=too-few-public-methods def __init__(self, field_name: str, filter_class: Type[BaseFilter]): self.field_name = field_name self.filter_class = filter_class class BaseFavoriteFilter(BaseFilter): # pylint: disable=too-few-public-methods """ Base Custom filter for the GET list that filters all dashboards, slices that a user has favored or not """ name = _("Is favorite") arg_name = "" class_name = "" """ The FavStar class_name to user """ model: Type[Union[Dashboard, Slice, SqllabQuery]] = Dashboard """ The SQLAlchemy model """ def apply(self, query: Query, value: Any) -> Query: # If anonymous user filter nothing if security_manager.current_user is None: return query users_favorite_query = db.session.query(FavStar.obj_id).filter( and_( FavStar.user_id == g.user.get_id(), FavStar.class_name == self.class_name, ) ) if value: return query.filter(and_(self.model.id.in_(users_favorite_query))) return query.filter(and_(~self.model.id.in_(users_favorite_query))) class BaseSupersetModelRestApi(ModelRestApi): """ Extends FAB's ModelResApi to implement specific superset generic functionality """ csrf_exempt = False method_permission_name = { "bulk_delete": "delete", "data": "list", "data_from_cache": "list", "delete": "delete", "distinct": "list", "export": "mulexport", "import_": "add", "get": "show", "get_list": "list", "info": "list", "post": "add", "put": "edit", "refresh": "edit", "related": "list", "related_objects": "list", "schemas": "list", "select_star": "list", "table_metadata": "list", "test_connection": "post", "thumbnail": "list", "viz_types": "list", } order_rel_fields: Dict[str, Tuple[str, str]] = {} """ Impose ordering on related fields query:: order_rel_fields = { "<RELATED_FIELD>": ("<RELATED_FIELD_FIELD>", "<asc|desc>"), ... } """ related_field_filters: Dict[str, Union[RelatedFieldFilter, str]] = {} """ Declare the filters for related fields:: related_fields = { "<RELATED_FIELD>": <RelatedFieldFilter>) } """ filter_rel_fields: Dict[str, BaseFilter] = {} """ Declare the related field base filter:: filter_rel_fields_field = { "<RELATED_FIELD>": "<FILTER>") } """ allowed_rel_fields: Set[str] = set() # Declare a set of allowed related fields that the `related` endpoint supports. text_field_rel_fields: Dict[str, str] = {} """ Declare an alternative for the human readable representation of the Model object:: text_field_rel_fields = { "<RELATED_FIELD>": "<RELATED_OBJECT_FIELD>" } """ allowed_distinct_fields: Set[str] = set() add_columns: List[str] edit_columns: List[str] list_columns: List[str] show_columns: List[str] responses = { "400": {"description": "Bad request", "content": error_payload_content}, "401": {"description": "Unauthorized", "content": error_payload_content}, "403": {"description": "Forbidden", "content": error_payload_content}, "404": {"description": "Not found", "content": error_payload_content}, "422": { "description": "Could not process entity", "content": error_payload_content, }, "500": {"description": "Fatal error", "content": error_payload_content}, } def __init__(self) -> None: super().__init__() # Setup statsd self.stats_logger = BaseStatsLogger() # Add base API spec base query parameter schemas if self.apispec_parameter_schemas is None: # type: ignore self.apispec_parameter_schemas = {} self.apispec_parameter_schemas["get_related_schema"] = get_related_schema self.openapi_spec_component_schemas: Tuple[ Type[Schema], ... ] = self.openapi_spec_component_schemas + ( RelatedResponseSchema, DistincResponseSchema, ) def create_blueprint( self, appbuilder: AppBuilder, *args: Any, **kwargs: Any ) -> Blueprint: self.stats_logger = self.appbuilder.get_app.config["STATS_LOGGER"] return super().create_blueprint(appbuilder, *args, **kwargs) def _init_properties(self) -> None: """ Lock down initial not configured REST API columns. We want to just expose model ids, if something is misconfigured. By default FAB exposes all available columns on a Model """ model_id = self.datamodel.get_pk_name() if self.list_columns is None and not self.list_model_schema: self.list_columns = [model_id] if self.show_columns is None and not self.show_model_schema: self.show_columns = [model_id] if self.edit_columns is None and not self.edit_model_schema: self.edit_columns = [model_id] if self.add_columns is None and not self.add_model_schema: self.add_columns = [model_id] super()._init_properties() def _get_related_filter( self, datamodel: SQLAInterface, column_name: str, value: str ) -> Filters: filter_field = self.related_field_filters.get(column_name) if isinstance(filter_field, str): filter_field = RelatedFieldFilter(cast(str, filter_field), FilterStartsWith) filter_field = cast(RelatedFieldFilter, filter_field) search_columns = [filter_field.field_name] if filter_field else None filters = datamodel.get_filters(search_columns) base_filters = self.filter_rel_fields.get(column_name) if base_filters: filters.add_filter_list(base_filters) if value and filter_field: filters.add_filter( filter_field.field_name, filter_field.filter_class, value ) return filters def _get_distinct_filter(self, column_name: str, value: str) -> Filters: filter_field = RelatedFieldFilter(column_name, FilterStartsWith) filter_field = cast(RelatedFieldFilter, filter_field) search_columns = [filter_field.field_name] if filter_field else None filters = self.datamodel.get_filters(search_columns) filters.add_filter_list(self.base_filters) if value and filter_field: filters.add_filter( filter_field.field_name, filter_field.filter_class, value ) return filters def _get_text_for_model(self, model: Model, column_name: str) -> str: if column_name in self.text_field_rel_fields: model_column_name = self.text_field_rel_fields.get(column_name) if model_column_name: return getattr(model, model_column_name) return str(model) def _get_result_from_rows( self, datamodel: SQLAInterface, rows: List[Model], column_name: str ) -> List[Dict[str, Any]]: return [ { "value": datamodel.get_pk_value(row), "text": self._get_text_for_model(row, column_name), } for row in rows ] def _add_extra_ids_to_result( self, datamodel: SQLAInterface, column_name: str, ids: List[int], result: List[Dict[str, Any]], ) -> None: if ids: # Filter out already present values on the result values = [row["value"] for row in result] ids = [id_ for id_ in ids if id_ not in values] pk_col = datamodel.get_pk() # Fetch requested values from ids extra_rows = db.session.query(datamodel.obj).filter(pk_col.in_(ids)).all() result += self._get_result_from_rows(datamodel, extra_rows, column_name) def incr_stats(self, action: str, func_name: str) -> None: """ Proxy function for statsd.incr to impose a key structure for REST API's :param action: String with an action name eg: error, success :param func_name: The function name """ self.stats_logger.incr(f"{self.__class__.__name__}.{func_name}.{action}") def timing_stats(self, action: str, func_name: str, value: float) -> None: """ Proxy function for statsd.incr to impose a key structure for REST API's :param action: String with an action name eg: error, success :param func_name: The function name :param value: A float with the time it took for the endpoint to execute """ self.stats_logger.timing( f"{self.__class__.__name__}.{func_name}.{action}", value ) def send_stats_metrics( self, response: Response, key: str, time_delta: Optional[float] = None ) -> None: """ Helper function to handle sending statsd metrics :param response: flask response object, will evaluate if it was an error :param key: The function name :param time_delta: Optional time it took for the endpoint to execute """ if 200 <= response.status_code < 400: self.incr_stats("success", key) else: self.incr_stats("error", key) if time_delta: self.timing_stats("time", key, time_delta) @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.info", object_ref=False, log_to_statsd=False, ) def info_headless(self, **kwargs: Any) -> Response: """ Add statsd metrics to builtin FAB _info endpoint """ duration, response = time_function(super().info_headless, **kwargs) self.send_stats_metrics(response, self.info.__name__, duration) return response @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.get", object_ref=False, log_to_statsd=False, ) def get_headless(self, pk: int, **kwargs: Any) -> Response: """ Add statsd metrics to builtin FAB GET endpoint """ duration, response = time_function(super().get_headless, pk, **kwargs) self.send_stats_metrics(response, self.get.__name__, duration) return response @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.get_list", object_ref=False, log_to_statsd=False, ) def get_list_headless(self, **kwargs: Any) -> Response: """ Add statsd metrics to builtin FAB GET list endpoint """ duration, response = time_function(super().get_list_headless, **kwargs) self.send_stats_metrics(response, self.get_list.__name__, duration) return response @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.post", object_ref=False, log_to_statsd=False, ) def post_headless(self) -> Response: """ Add statsd metrics to builtin FAB POST endpoint """ duration, response = time_function(super().post_headless) self.send_stats_metrics(response, self.post.__name__, duration) return response @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.put", object_ref=False, log_to_statsd=False, ) def put_headless(self, pk: int) -> Response: """ Add statsd metrics to builtin FAB PUT endpoint """ duration, response = time_function(super().put_headless, pk) self.send_stats_metrics(response, self.put.__name__, duration) return response @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.delete", object_ref=False, log_to_statsd=False, ) def delete_headless(self, pk: int) -> Response: """ Add statsd metrics to builtin FAB DELETE endpoint """ duration, response = time_function(super().delete_headless, pk) self.send_stats_metrics(response, self.delete.__name__, duration) return response @expose("/related/<column_name>", methods=["GET"]) @protect() @safe @statsd_metrics @rison(get_related_schema) def related(self, column_name: str, **kwargs: Any) -> FlaskResponse: """Get related fields data --- get: parameters: - in: path schema: type: string name: column_name - in: query name: q content: application/json: schema: $ref: '#/components/schemas/get_related_schema' responses: 200: description: Related column data content: application/json: schema: schema: $ref: "#/components/schemas/RelatedResponseSchema" 400: $ref: '#/components/responses/400' 401: $ref: '#/components/responses/401' 404: $ref: '#/components/responses/404' 500: $ref: '#/components/responses/500' """ if column_name not in self.allowed_rel_fields: self.incr_stats("error", self.related.__name__) return self.response_404() args = kwargs.get("rison", {}) # handle pagination page, page_size = self._handle_page_args(args) ids = args.get("include_ids") if page and ids: # pagination with forced ids is not supported return self.response_422() try: datamodel = self.datamodel.get_related_interface(column_name) except KeyError: return self.response_404() page, page_size = self._sanitize_page_args(page, page_size) # handle ordering order_field = self.order_rel_fields.get(column_name) if order_field: order_column, order_direction = order_field else: order_column, order_direction = "", "" # handle filters filters = self._get_related_filter(datamodel, column_name, args.get("filter")) # Make the query total_rows, rows = datamodel.query( filters, order_column, order_direction, page=page, page_size=page_size ) # produce response result = self._get_result_from_rows(datamodel, rows, column_name) # If ids are specified make sure we fetch and include them on the response if ids: self._add_extra_ids_to_result(datamodel, column_name, ids, result) total_rows = len(result) return self.response(200, count=total_rows, result=result) @expose("/distinct/<column_name>", methods=["GET"]) @protect() @safe @statsd_metrics @rison(get_related_schema) def distinct(self, column_name: str, **kwargs: Any) -> FlaskResponse: """Get distinct values from field data --- get: parameters: - in: path schema: type: string name: column_name - in: query name: q content: application/json: schema: $ref: '#/components/schemas/get_related_schema' responses: 200: description: Distinct field data content: application/json: schema: schema: $ref: "#/components/schemas/DistincResponseSchema" 400: $ref: '#/components/responses/400' 401: $ref: '#/components/responses/401' 404: $ref: '#/components/responses/404' 500: $ref: '#/components/responses/500' """ if column_name not in self.allowed_distinct_fields: self.incr_stats("error", self.related.__name__) return self.response_404() args = kwargs.get("rison", {}) # handle pagination page, page_size = self._sanitize_page_args(*self._handle_page_args(args)) # Create generic base filters with added request filter filters = self._get_distinct_filter(column_name, args.get("filter")) # Make the query query_count = self.appbuilder.get_session.query( func.count(distinct(getattr(self.datamodel.obj, column_name))) ) count = self.datamodel.apply_filters(query_count, filters).scalar() if count == 0: return self.response(200, count=count, result=[]) query = self.appbuilder.get_session.query( distinct(getattr(self.datamodel.obj, column_name)) ) # Apply generic base filters with added request filter query = self.datamodel.apply_filters(query, filters) # Apply sort query = self.datamodel.apply_order_by(query, column_name, "asc") # Apply pagination result = self.datamodel.apply_pagination(query, page, page_size).all() # produce response result = [ {"text": item[0], "value": item[0]} for item in result if item[0] is not None ] return self.response(200, count=count, result=result)
superset/views/base_api.py
1
https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f
[ 0.9988560676574707, 0.08488588035106659, 0.000163483084179461, 0.001104893395677209, 0.2530323565006256 ]
{ "id": 10, "code_window": [ " @expose(\"/distinct/<column_name>\", methods=[\"GET\"])\n", " @protect()\n", " @safe\n", " @statsd_metrics\n", " @rison(get_related_schema)\n", " def distinct(self, column_name: str, **kwargs: Any) -> FlaskResponse:\n", " \"\"\"Get distinct values from field data\n", " ---\n", " get:\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " @handle_api_exception\n" ], "file_path": "superset/views/base_api.py", "type": "add", "edit_start_line_idx": 544 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from typing import Any, Dict from marshmallow import Schema from sqlalchemy.orm import Session from superset.commands.importers.v1 import ImportModelsCommand from superset.databases.commands.exceptions import DatabaseImportError from superset.databases.commands.importers.v1.utils import import_database from superset.databases.dao import DatabaseDAO from superset.databases.schemas import ImportV1DatabaseSchema from superset.datasets.commands.importers.v1.utils import import_dataset from superset.datasets.schemas import ImportV1DatasetSchema class ImportDatabasesCommand(ImportModelsCommand): """Import databases""" dao = DatabaseDAO model_name = "database" prefix = "databases/" schemas: Dict[str, Schema] = { "databases/": ImportV1DatabaseSchema(), "datasets/": ImportV1DatasetSchema(), } import_error = DatabaseImportError @staticmethod def _import( session: Session, configs: Dict[str, Any], overwrite: bool = False ) -> None: # first import databases database_ids: Dict[str, int] = {} for file_name, config in configs.items(): if file_name.startswith("databases/"): database = import_database(session, config, overwrite=overwrite) database_ids[str(database.uuid)] = database.id # import related datasets for file_name, config in configs.items(): if ( file_name.startswith("datasets/") and config["database_uuid"] in database_ids ): config["database_id"] = database_ids[config["database_uuid"]] # overwrite=False prevents deleting any non-imported columns/metrics import_dataset(session, config, overwrite=False)
superset/databases/commands/importers/v1/__init__.py
0
https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f
[ 0.0012138711754232645, 0.0003206531691830605, 0.0001649147307034582, 0.00017403680249117315, 0.0003646698605734855 ]
{ "id": 10, "code_window": [ " @expose(\"/distinct/<column_name>\", methods=[\"GET\"])\n", " @protect()\n", " @safe\n", " @statsd_metrics\n", " @rison(get_related_schema)\n", " def distinct(self, column_name: str, **kwargs: Any) -> FlaskResponse:\n", " \"\"\"Get distinct values from field data\n", " ---\n", " get:\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " @handle_api_exception\n" ], "file_path": "superset/views/base_api.py", "type": "add", "edit_start_line_idx": 544 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Optional from flask_babel import gettext as _ class SupersetErrorType(str, Enum): """ Types of errors that can exist within Superset. Keep in sync with superset-frontend/src/components/ErrorMessage/types.ts and docs/src/pages/docs/Miscellaneous/issue_codes.mdx """ # Frontend errors FRONTEND_CSRF_ERROR = "FRONTEND_CSRF_ERROR" FRONTEND_NETWORK_ERROR = "FRONTEND_NETWORK_ERROR" FRONTEND_TIMEOUT_ERROR = "FRONTEND_TIMEOUT_ERROR" # DB Engine errors GENERIC_DB_ENGINE_ERROR = "GENERIC_DB_ENGINE_ERROR" COLUMN_DOES_NOT_EXIST_ERROR = "COLUMN_DOES_NOT_EXIST_ERROR" TABLE_DOES_NOT_EXIST_ERROR = "TABLE_DOES_NOT_EXIST_ERROR" SCHEMA_DOES_NOT_EXIST_ERROR = "SCHEMA_DOES_NOT_EXIST_ERROR" CONNECTION_INVALID_USERNAME_ERROR = "CONNECTION_INVALID_USERNAME_ERROR" CONNECTION_INVALID_PASSWORD_ERROR = "CONNECTION_INVALID_PASSWORD_ERROR" CONNECTION_INVALID_HOSTNAME_ERROR = "CONNECTION_INVALID_HOSTNAME_ERROR" CONNECTION_PORT_CLOSED_ERROR = "CONNECTION_PORT_CLOSED_ERROR" CONNECTION_INVALID_PORT_ERROR = "CONNECTION_INVALID_PORT_ERROR" CONNECTION_HOST_DOWN_ERROR = "CONNECTION_HOST_DOWN_ERROR" CONNECTION_ACCESS_DENIED_ERROR = "CONNECTION_ACCESS_DENIED_ERROR" CONNECTION_UNKNOWN_DATABASE_ERROR = "CONNECTION_UNKNOWN_DATABASE_ERROR" CONNECTION_DATABASE_PERMISSIONS_ERROR = "CONNECTION_DATABASE_PERMISSIONS_ERROR" CONNECTION_MISSING_PARAMETERS_ERROR = "CONNECTION_MISSING_PARAMETERS_ERROR" OBJECT_DOES_NOT_EXIST_ERROR = "OBJECT_DOES_NOT_EXIST_ERROR" SYNTAX_ERROR = "SYNTAX_ERROR" CONNECTION_DATABASE_TIMEOUT = "CONNECTION_DATABASE_TIMEOUT" # Viz errors VIZ_GET_DF_ERROR = "VIZ_GET_DF_ERROR" UNKNOWN_DATASOURCE_TYPE_ERROR = "UNKNOWN_DATASOURCE_TYPE_ERROR" FAILED_FETCHING_DATASOURCE_INFO_ERROR = "FAILED_FETCHING_DATASOURCE_INFO_ERROR" # Security access errors TABLE_SECURITY_ACCESS_ERROR = "TABLE_SECURITY_ACCESS_ERROR" DATASOURCE_SECURITY_ACCESS_ERROR = "DATASOURCE_SECURITY_ACCESS_ERROR" DATABASE_SECURITY_ACCESS_ERROR = "DATABASE_SECURITY_ACCESS_ERROR" QUERY_SECURITY_ACCESS_ERROR = "QUERY_SECURITY_ACCESS_ERROR" MISSING_OWNERSHIP_ERROR = "MISSING_OWNERSHIP_ERROR" USER_ACTIVITY_SECURITY_ACCESS_ERROR = "USER_ACTIVITY_SECURITY_ACCESS_ERROR" # Other errors BACKEND_TIMEOUT_ERROR = "BACKEND_TIMEOUT_ERROR" DATABASE_NOT_FOUND_ERROR = "DATABASE_NOT_FOUND_ERROR" # Sql Lab errors MISSING_TEMPLATE_PARAMS_ERROR = "MISSING_TEMPLATE_PARAMS_ERROR" INVALID_TEMPLATE_PARAMS_ERROR = "INVALID_TEMPLATE_PARAMS_ERROR" RESULTS_BACKEND_NOT_CONFIGURED_ERROR = "RESULTS_BACKEND_NOT_CONFIGURED_ERROR" DML_NOT_ALLOWED_ERROR = "DML_NOT_ALLOWED_ERROR" INVALID_CTAS_QUERY_ERROR = "INVALID_CTAS_QUERY_ERROR" INVALID_CVAS_QUERY_ERROR = "INVALID_CVAS_QUERY_ERROR" SQLLAB_TIMEOUT_ERROR = "SQLLAB_TIMEOUT_ERROR" RESULTS_BACKEND_ERROR = "RESULTS_BACKEND_ERROR" ASYNC_WORKERS_ERROR = "ASYNC_WORKERS_ERROR" ADHOC_SUBQUERY_NOT_ALLOWED_ERROR = "ADHOC_SUBQUERY_NOT_ALLOWED_ERROR" # Generic errors GENERIC_COMMAND_ERROR = "GENERIC_COMMAND_ERROR" GENERIC_BACKEND_ERROR = "GENERIC_BACKEND_ERROR" # API errors INVALID_PAYLOAD_FORMAT_ERROR = "INVALID_PAYLOAD_FORMAT_ERROR" INVALID_PAYLOAD_SCHEMA_ERROR = "INVALID_PAYLOAD_SCHEMA_ERROR" ISSUE_CODES = { 1000: _("The datasource is too large to query."), 1001: _("The database is under an unusual load."), 1002: _("The database returned an unexpected error."), 1003: _( "There is a syntax error in the SQL query. " "Perhaps there was a misspelling or a typo." ), 1004: _("The column was deleted or renamed in the database."), 1005: _("The table was deleted or renamed in the database."), 1006: _("One or more parameters specified in the query are missing."), 1007: _("The hostname provided can't be resolved."), 1008: _("The port is closed."), 1009: _("The host might be down, and can't be reached on the provided port."), 1010: _("Superset encountered an error while running a command."), 1011: _("Superset encountered an unexpected error."), 1012: _("The username provided when connecting to a database is not valid."), 1013: _("The password provided when connecting to a database is not valid."), 1014: _("Either the username or the password is wrong."), 1015: _("Either the database is spelled incorrectly or does not exist."), 1016: _("The schema was deleted or renamed in the database."), 1017: _("User doesn't have the proper permissions."), 1018: _("One or more parameters needed to configure a database are missing."), 1019: _("The submitted payload has the incorrect format."), 1020: _("The submitted payload has the incorrect schema."), 1021: _("Results backend needed for asynchronous queries is not configured."), 1022: _("Database does not allow data manipulation."), 1023: _( "The CTAS (create table as select) doesn't have a " "SELECT statement at the end. Please make sure your query has a " "SELECT as its last statement. Then, try running your query again." ), 1024: _("CVAS (create view as select) query has more than one statement."), 1025: _("CVAS (create view as select) query is not a SELECT statement."), 1026: _("Query is too complex and takes too long to run."), 1027: _("The database is currently running too many queries."), 1028: _("One or more parameters specified in the query are malformatted."), 1029: _("The object does not exist in the given database."), 1030: _("The query has a syntax error."), 1031: _("The results backend no longer has the data from the query."), 1032: _("The query associated with the results was deleted."), 1033: _( "The results stored in the backend were stored in a " "different format, and no longer can be deserialized." ), 1034: _("The port number is invalid."), 1035: _("Failed to start remote query on a worker."), 1036: _("The database was deleted."), 1037: _("Custom SQL fields cannot contain sub-queries."), } ERROR_TYPES_TO_ISSUE_CODES_MAPPING = { SupersetErrorType.ADHOC_SUBQUERY_NOT_ALLOWED_ERROR: [1037], SupersetErrorType.BACKEND_TIMEOUT_ERROR: [1000, 1001], SupersetErrorType.GENERIC_DB_ENGINE_ERROR: [1002], SupersetErrorType.COLUMN_DOES_NOT_EXIST_ERROR: [1003, 1004], SupersetErrorType.TABLE_DOES_NOT_EXIST_ERROR: [1003, 1005], SupersetErrorType.SCHEMA_DOES_NOT_EXIST_ERROR: [1003, 1016], SupersetErrorType.MISSING_TEMPLATE_PARAMS_ERROR: [1006], SupersetErrorType.INVALID_TEMPLATE_PARAMS_ERROR: [1028], SupersetErrorType.RESULTS_BACKEND_NOT_CONFIGURED_ERROR: [1021], SupersetErrorType.DML_NOT_ALLOWED_ERROR: [1022], SupersetErrorType.CONNECTION_INVALID_HOSTNAME_ERROR: [1007], SupersetErrorType.CONNECTION_PORT_CLOSED_ERROR: [1008], SupersetErrorType.CONNECTION_HOST_DOWN_ERROR: [1009], SupersetErrorType.GENERIC_COMMAND_ERROR: [1010], SupersetErrorType.GENERIC_BACKEND_ERROR: [1011], SupersetErrorType.CONNECTION_INVALID_USERNAME_ERROR: [1012], SupersetErrorType.CONNECTION_INVALID_PASSWORD_ERROR: [1013], SupersetErrorType.CONNECTION_ACCESS_DENIED_ERROR: [1014, 1015], SupersetErrorType.CONNECTION_UNKNOWN_DATABASE_ERROR: [1015], SupersetErrorType.CONNECTION_DATABASE_PERMISSIONS_ERROR: [1017], SupersetErrorType.CONNECTION_MISSING_PARAMETERS_ERROR: [1018], SupersetErrorType.INVALID_PAYLOAD_FORMAT_ERROR: [1019], SupersetErrorType.INVALID_PAYLOAD_SCHEMA_ERROR: [1020], SupersetErrorType.INVALID_CTAS_QUERY_ERROR: [1023], SupersetErrorType.INVALID_CVAS_QUERY_ERROR: [1024, 1025], SupersetErrorType.SQLLAB_TIMEOUT_ERROR: [1026, 1027], SupersetErrorType.OBJECT_DOES_NOT_EXIST_ERROR: [1029], SupersetErrorType.SYNTAX_ERROR: [1030], SupersetErrorType.RESULTS_BACKEND_ERROR: [1031, 1032, 1033], SupersetErrorType.CONNECTION_INVALID_PORT_ERROR: [1034], SupersetErrorType.ASYNC_WORKERS_ERROR: [1035], SupersetErrorType.DATABASE_NOT_FOUND_ERROR: [1011, 1036], SupersetErrorType.CONNECTION_DATABASE_TIMEOUT: [1001, 1009], } class ErrorLevel(str, Enum): """ Levels of errors that can exist within Superset. Keep in sync with superset-frontend/src/components/ErrorMessage/types.ts """ INFO = "info" WARNING = "warning" ERROR = "error" @dataclass class SupersetError: """ An error that is returned to a client. """ message: str error_type: SupersetErrorType level: ErrorLevel extra: Optional[Dict[str, Any]] = None def __post_init__(self) -> None: """ Mutates the extra params with user facing error codes that map to backend errors. """ issue_codes = ERROR_TYPES_TO_ISSUE_CODES_MAPPING.get(self.error_type) if issue_codes: self.extra = self.extra or {} self.extra.update( { "issue_codes": [ { "code": issue_code, "message": ( f"Issue {issue_code} - {ISSUE_CODES[issue_code]}" ), } for issue_code in issue_codes ] } ) def to_dict(self) -> Dict[str, Any]: rv = {"message": self.message, "error_type": self.error_type} if self.extra: rv["extra"] = self.extra # type: ignore return rv
superset/errors.py
0
https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f
[ 0.003193574259057641, 0.0006151553825475276, 0.00016440147010143846, 0.00017549442418385297, 0.0009159031324088573 ]
{ "id": 10, "code_window": [ " @expose(\"/distinct/<column_name>\", methods=[\"GET\"])\n", " @protect()\n", " @safe\n", " @statsd_metrics\n", " @rison(get_related_schema)\n", " def distinct(self, column_name: str, **kwargs: Any) -> FlaskResponse:\n", " \"\"\"Get distinct values from field data\n", " ---\n", " get:\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " @handle_api_exception\n" ], "file_path": "superset/views/base_api.py", "type": "add", "edit_start_line_idx": 544 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React, { ReactNode } from 'react'; import { useDrop } from 'react-dnd'; import { t, useTheme } from '@superset-ui/core'; import ControlHeader from 'src/explore/components/ControlHeader'; import { AddControlLabel, DndLabelsContainer, HeaderContainer, } from 'src/explore/components/controls/OptionControls'; import { DatasourcePanelDndItem, DndItemValue, } from 'src/explore/components/DatasourcePanel/types'; import Icons from 'src/components/Icons'; import { DndItemType } from '../../DndItemType'; export type DndSelectLabelProps = { name: string; accept: DndItemType | DndItemType[]; ghostButtonText?: string; onDrop: (item: DatasourcePanelDndItem) => void; canDrop: (item: DatasourcePanelDndItem) => boolean; canDropValue?: (value: DndItemValue) => boolean; onDropValue?: (value: DndItemValue) => void; valuesRenderer: () => ReactNode; displayGhostButton?: boolean; onClickGhostButton?: () => void; }; export default function DndSelectLabel({ displayGhostButton = true, accept, ...props }: DndSelectLabelProps) { const theme = useTheme(); const [{ isOver, canDrop }, datasourcePanelDrop] = useDrop({ accept, drop: (item: DatasourcePanelDndItem) => { props.onDrop(item); props.onDropValue?.(item.value); }, canDrop: (item: DatasourcePanelDndItem) => props.canDrop(item) && (props.canDropValue?.(item.value) ?? true), collect: monitor => ({ isOver: monitor.isOver(), canDrop: monitor.canDrop(), type: monitor.getItemType(), }), }); function renderGhostButton() { return ( <AddControlLabel cancelHover={!props.onClickGhostButton} onClick={props.onClickGhostButton} > <Icons.PlusSmall iconColor={theme.colors.grayscale.light1} /> {t(props.ghostButtonText || 'Drop columns here')} </AddControlLabel> ); } return ( <div ref={datasourcePanelDrop}> <HeaderContainer> <ControlHeader {...props} /> </HeaderContainer> <DndLabelsContainer canDrop={canDrop} isOver={isOver}> {props.valuesRenderer()} {displayGhostButton && renderGhostButton()} </DndLabelsContainer> </div> ); }
superset-frontend/src/explore/components/controls/DndColumnSelectControl/DndSelectLabel.tsx
0
https://github.com/apache/superset/commit/4513cc475831c3fd4869b44255edf91dabe18e0f
[ 0.00017802329966798425, 0.00017407102859579027, 0.00016534033056814224, 0.00017459195805713534, 0.0000037513252664211905 ]
{ "id": 0, "code_window": [ " return {\n", " a: this.a\n", " }\n", " },\n", " render() {\n", " return [h(ChildA), h(ChildB), h(ChildC), h(ChildD), h(ChildE)]\n", " }\n", " })\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " return [\n", " h(ChildA),\n", " h(ChildB),\n", " h(ChildC),\n", " h(ChildD),\n", " h(ChildE),\n", " h(ChildF),\n", " h(ChildG),\n", " h(ChildH)\n", " ]\n" ], "file_path": "packages/runtime-core/__tests__/apiOptions.spec.ts", "type": "replace", "edit_start_line_idx": 255 }
import { ComponentInternalInstance, Data, SetupContext, ComponentInternalOptions, Component, ConcreteComponent, InternalRenderFunction } from './component' import { isFunction, extend, isString, isObject, isArray, EMPTY_OBJ, NOOP, hasOwn, isPromise } from '@vue/shared' import { computed } from './apiComputed' import { watch, WatchOptions, WatchCallback } from './apiWatch' import { provide, inject } from './apiInject' import { onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onErrorCaptured, onRenderTracked, onBeforeUnmount, onUnmounted, onActivated, onDeactivated, onRenderTriggered, DebuggerHook, ErrorCapturedHook } from './apiLifecycle' import { reactive, ComputedGetter, WritableComputedOptions, toRaw } from '@vue/reactivity' import { ComponentObjectPropsOptions, ExtractPropTypes } from './componentProps' import { EmitsOptions } from './componentEmits' import { Directive } from './directives' import { CreateComponentPublicInstance, ComponentPublicInstance } from './componentPublicInstance' import { warn } from './warning' import { VNodeChild } from './vnode' /** * Interface for declaring custom options. * * @example * ```ts * declare module '@vue/runtime-core' { * interface ComponentCustomOptions { * beforeRouteUpdate?( * to: Route, * from: Route, * next: () => void * ): void * } * } * ``` */ export interface ComponentCustomOptions {} export type RenderFunction = () => VNodeChild export type UnwrapAsyncBindings<T> = T extends Promise<infer S> ? S : T export interface ComponentOptionsBase< Props, RawBindings, D, C extends ComputedOptions, M extends MethodOptions, Mixin extends ComponentOptionsMixin, Extends extends ComponentOptionsMixin, E extends EmitsOptions, EE extends string = string > extends LegacyOptions<Props, D, C, M, Mixin, Extends>, ComponentInternalOptions, ComponentCustomOptions { setup?: ( this: void, props: Props, ctx: SetupContext<E> ) => RawBindings | RenderFunction | void name?: string template?: string | object // can be a direct DOM node // Note: we are intentionally using the signature-less `Function` type here // since any type with signature will cause the whole inference to fail when // the return expression contains reference to `this`. // Luckily `render()` doesn't need any arguments nor does it care about return // type. render?: Function components?: Record<string, Component> directives?: Record<string, Directive> inheritAttrs?: boolean emits?: (E | EE[]) & ThisType<void> serverPrefetch?(): Promise<any> // Internal ------------------------------------------------------------------ /** * SSR only. This is produced by compiler-ssr and attached in compiler-sfc * not user facing, so the typing is lax and for test only. * * @internal */ ssrRender?: ( ctx: any, push: (item: any) => void, parentInstance: ComponentInternalInstance, attrs: Data | undefined, // for compiler-optimized bindings $props: ComponentInternalInstance['props'], $setup: ComponentInternalInstance['setupState'], $data: ComponentInternalInstance['data'], $options: ComponentInternalInstance['ctx'] ) => void /** * marker for AsyncComponentWrapper * @internal */ __asyncLoader?: () => Promise<ConcreteComponent> /** * cache for merged $options * @internal */ __merged?: ComponentOptions // Type differentiators ------------------------------------------------------ // Note these are internal but need to be exposed in d.ts for type inference // to work! // type-only differentiator to separate OptionWithoutProps from a constructor // type returned by defineComponent() or FunctionalComponent call?: (this: unknown, ...args: unknown[]) => never // type-only differentiators for built-in Vnode types __isFragment?: never __isTeleport?: never __isSuspense?: never } export type ComponentOptionsWithoutProps< Props = {}, RawBindings = {}, D = {}, C extends ComputedOptions = {}, M extends MethodOptions = {}, Mixin extends ComponentOptionsMixin = ComponentOptionsMixin, Extends extends ComponentOptionsMixin = ComponentOptionsMixin, E extends EmitsOptions = EmitsOptions, EE extends string = string > = ComponentOptionsBase<Props, RawBindings, D, C, M, Mixin, Extends, E, EE> & { props?: undefined } & ThisType< CreateComponentPublicInstance< {}, RawBindings, D, C, M, Mixin, Extends, E, Readonly<Props> > > export type ComponentOptionsWithArrayProps< PropNames extends string = string, RawBindings = {}, D = {}, C extends ComputedOptions = {}, M extends MethodOptions = {}, Mixin extends ComponentOptionsMixin = ComponentOptionsMixin, Extends extends ComponentOptionsMixin = ComponentOptionsMixin, E extends EmitsOptions = EmitsOptions, EE extends string = string, Props = Readonly<{ [key in PropNames]?: any }> > = ComponentOptionsBase<Props, RawBindings, D, C, M, Mixin, Extends, E, EE> & { props: PropNames[] } & ThisType< CreateComponentPublicInstance< Props, RawBindings, D, C, M, Mixin, Extends, E > > export type ComponentOptionsWithObjectProps< PropsOptions = ComponentObjectPropsOptions, RawBindings = {}, D = {}, C extends ComputedOptions = {}, M extends MethodOptions = {}, Mixin extends ComponentOptionsMixin = ComponentOptionsMixin, Extends extends ComponentOptionsMixin = ComponentOptionsMixin, E extends EmitsOptions = EmitsOptions, EE extends string = string, Props = Readonly<ExtractPropTypes<PropsOptions>> > = ComponentOptionsBase<Props, RawBindings, D, C, M, Mixin, Extends, E, EE> & { props: PropsOptions & ThisType<void> } & ThisType< CreateComponentPublicInstance< Props, RawBindings, D, C, M, Mixin, Extends, E > > export type ComponentOptions = | ComponentOptionsWithoutProps<any, any, any, any, any> | ComponentOptionsWithObjectProps<any, any, any, any, any> | ComponentOptionsWithArrayProps<any, any, any, any, any> export type ComponentOptionsMixin = ComponentOptionsBase< any, any, any, any, any, any, any, any, any > export type ComputedOptions = Record< string, ComputedGetter<any> | WritableComputedOptions<any> > export interface MethodOptions { [key: string]: Function } export type ExtractComputedReturns<T extends any> = { [key in keyof T]: T[key] extends { get: (...args: any[]) => infer TReturn } ? TReturn : T[key] extends (...args: any[]) => infer TReturn ? TReturn : never } type WatchOptionItem = | string | WatchCallback | { handler: WatchCallback | string } & WatchOptions type ComponentWatchOptionItem = WatchOptionItem | WatchOptionItem[] type ComponentWatchOptions = Record<string, ComponentWatchOptionItem> type ComponentInjectOptions = | string[] | Record< string | symbol, string | symbol | { from: string | symbol; default?: unknown } > interface LegacyOptions< Props, D, C extends ComputedOptions, M extends MethodOptions, Mixin extends ComponentOptionsMixin, Extends extends ComponentOptionsMixin > { // allow any custom options [key: string]: any // state // Limitation: we cannot expose RawBindings on the `this` context for data // since that leads to some sort of circular inference and breaks ThisType // for the entire component. data?: ( this: CreateComponentPublicInstance<Props>, vm: CreateComponentPublicInstance<Props> ) => D computed?: C methods?: M watch?: ComponentWatchOptions provide?: Data | Function inject?: ComponentInjectOptions // composition mixins?: Mixin[] extends?: Extends // lifecycle beforeCreate?(): void created?(): void beforeMount?(): void mounted?(): void beforeUpdate?(): void updated?(): void activated?(): void deactivated?(): void beforeUnmount?(): void unmounted?(): void renderTracked?: DebuggerHook renderTriggered?: DebuggerHook errorCaptured?: ErrorCapturedHook // runtime compile only delimiters?: [string, string] } export type OptionTypesKeys = 'P' | 'B' | 'D' | 'C' | 'M' export type OptionTypesType< P = {}, B = {}, D = {}, C extends ComputedOptions = {}, M extends MethodOptions = {} > = { P: P B: B D: D C: C M: M } const enum OptionTypes { PROPS = 'Props', DATA = 'Data', COMPUTED = 'Computed', METHODS = 'Methods', INJECT = 'Inject' } function createDuplicateChecker() { const cache = Object.create(null) return (type: OptionTypes, key: string) => { if (cache[key]) { warn(`${type} property "${key}" is already defined in ${cache[key]}.`) } else { cache[key] = type } } } type DataFn = (vm: ComponentPublicInstance) => any export let isInBeforeCreate = false export function applyOptions( instance: ComponentInternalInstance, options: ComponentOptions, deferredData: DataFn[] = [], deferredWatch: ComponentWatchOptions[] = [], asMixin: boolean = false ) { const { // composition mixins, extends: extendsOptions, // state data: dataOptions, computed: computedOptions, methods, watch: watchOptions, provide: provideOptions, inject: injectOptions, // assets components, directives, // lifecycle beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeUnmount, unmounted, render, renderTracked, renderTriggered, errorCaptured } = options const publicThis = instance.proxy! const ctx = instance.ctx const globalMixins = instance.appContext.mixins if (asMixin && render && instance.render === NOOP) { instance.render = render as InternalRenderFunction } // applyOptions is called non-as-mixin once per instance if (!asMixin) { isInBeforeCreate = true callSyncHook('beforeCreate', options, publicThis, globalMixins) isInBeforeCreate = false // global mixins are applied first applyMixins(instance, globalMixins, deferredData, deferredWatch) } // extending a base component... if (extendsOptions) { applyOptions(instance, extendsOptions, deferredData, deferredWatch, true) } // local mixins if (mixins) { applyMixins(instance, mixins, deferredData, deferredWatch) } const checkDuplicateProperties = __DEV__ ? createDuplicateChecker() : null if (__DEV__) { const [propsOptions] = instance.propsOptions if (propsOptions) { for (const key in propsOptions) { checkDuplicateProperties!(OptionTypes.PROPS, key) } } } // options initialization order (to be consistent with Vue 2): // - props (already done outside of this function) // - inject // - methods // - data (deferred since it relies on `this` access) // - computed // - watch (deferred since it relies on `this` access) if (injectOptions) { if (isArray(injectOptions)) { for (let i = 0; i < injectOptions.length; i++) { const key = injectOptions[i] ctx[key] = inject(key) if (__DEV__) { checkDuplicateProperties!(OptionTypes.INJECT, key) } } } else { for (const key in injectOptions) { const opt = injectOptions[key] if (isObject(opt)) { ctx[key] = inject( opt.from, opt.default, true /* treat default function as factory */ ) } else { ctx[key] = inject(opt) } if (__DEV__) { checkDuplicateProperties!(OptionTypes.INJECT, key) } } } } if (methods) { for (const key in methods) { const methodHandler = (methods as MethodOptions)[key] if (isFunction(methodHandler)) { ctx[key] = methodHandler.bind(publicThis) if (__DEV__) { checkDuplicateProperties!(OptionTypes.METHODS, key) } } else if (__DEV__) { warn( `Method "${key}" has type "${typeof methodHandler}" in the component definition. ` + `Did you reference the function correctly?` ) } } } if (!asMixin) { if (deferredData.length) { deferredData.forEach(dataFn => resolveData(instance, dataFn, publicThis)) } if (dataOptions) { resolveData(instance, dataOptions, publicThis) } if (__DEV__) { const rawData = toRaw(instance.data) for (const key in rawData) { checkDuplicateProperties!(OptionTypes.DATA, key) // expose data on ctx during dev if (key[0] !== '$' && key[0] !== '_') { Object.defineProperty(ctx, key, { configurable: true, enumerable: true, get: () => rawData[key], set: NOOP }) } } } } else if (dataOptions) { deferredData.push(dataOptions as DataFn) } if (computedOptions) { for (const key in computedOptions) { const opt = (computedOptions as ComputedOptions)[key] const get = isFunction(opt) ? opt.bind(publicThis, publicThis) : isFunction(opt.get) ? opt.get.bind(publicThis, publicThis) : NOOP if (__DEV__ && get === NOOP) { warn(`Computed property "${key}" has no getter.`) } const set = !isFunction(opt) && isFunction(opt.set) ? opt.set.bind(publicThis) : __DEV__ ? () => { warn( `Write operation failed: computed property "${key}" is readonly.` ) } : NOOP const c = computed({ get, set }) Object.defineProperty(ctx, key, { enumerable: true, configurable: true, get: () => c.value, set: v => (c.value = v) }) if (__DEV__) { checkDuplicateProperties!(OptionTypes.COMPUTED, key) } } } if (watchOptions) { deferredWatch.push(watchOptions) } if (!asMixin && deferredWatch.length) { deferredWatch.forEach(watchOptions => { for (const key in watchOptions) { createWatcher(watchOptions[key], ctx, publicThis, key) } }) } if (provideOptions) { const provides = isFunction(provideOptions) ? provideOptions.call(publicThis) : provideOptions for (const key in provides) { provide(key, provides[key]) } } // asset options. // To reduce memory usage, only components with mixins or extends will have // resolved asset registry attached to instance. if (asMixin) { if (components) { extend( instance.components || (instance.components = extend( {}, (instance.type as ComponentOptions).components ) as Record<string, ConcreteComponent>), components ) } if (directives) { extend( instance.directives || (instance.directives = extend( {}, (instance.type as ComponentOptions).directives )), directives ) } } // lifecycle options if (!asMixin) { callSyncHook('created', options, publicThis, globalMixins) } if (beforeMount) { onBeforeMount(beforeMount.bind(publicThis)) } if (mounted) { onMounted(mounted.bind(publicThis)) } if (beforeUpdate) { onBeforeUpdate(beforeUpdate.bind(publicThis)) } if (updated) { onUpdated(updated.bind(publicThis)) } if (activated) { onActivated(activated.bind(publicThis)) } if (deactivated) { onDeactivated(deactivated.bind(publicThis)) } if (errorCaptured) { onErrorCaptured(errorCaptured.bind(publicThis)) } if (renderTracked) { onRenderTracked(renderTracked.bind(publicThis)) } if (renderTriggered) { onRenderTriggered(renderTriggered.bind(publicThis)) } if (beforeUnmount) { onBeforeUnmount(beforeUnmount.bind(publicThis)) } if (unmounted) { onUnmounted(unmounted.bind(publicThis)) } } function callSyncHook( name: 'beforeCreate' | 'created', options: ComponentOptions, ctx: ComponentPublicInstance, globalMixins: ComponentOptions[] ) { callHookFromMixins(name, globalMixins, ctx) const { extends: base, mixins } = options if (base) { callHookFromExtends(name, base, ctx) } if (mixins) { callHookFromMixins(name, mixins, ctx) } const selfHook = options[name] if (selfHook) { selfHook.call(ctx) } } function callHookFromExtends( name: 'beforeCreate' | 'created', base: ComponentOptions, ctx: ComponentPublicInstance ) { if (base.extends) { callHookFromExtends(name, base.extends, ctx) } const baseHook = base[name] if (baseHook) { baseHook.call(ctx) } } function callHookFromMixins( name: 'beforeCreate' | 'created', mixins: ComponentOptions[], ctx: ComponentPublicInstance ) { for (let i = 0; i < mixins.length; i++) { const chainedMixins = mixins[i].mixins if (chainedMixins) { callHookFromMixins(name, chainedMixins, ctx) } const fn = mixins[i][name] if (fn) { fn.call(ctx) } } } function applyMixins( instance: ComponentInternalInstance, mixins: ComponentOptions[], deferredData: DataFn[], deferredWatch: ComponentWatchOptions[] ) { for (let i = 0; i < mixins.length; i++) { applyOptions(instance, mixins[i], deferredData, deferredWatch, true) } } function resolveData( instance: ComponentInternalInstance, dataFn: DataFn, publicThis: ComponentPublicInstance ) { if (__DEV__ && !isFunction(dataFn)) { warn( `The data option must be a function. ` + `Plain object usage is no longer supported.` ) } const data = dataFn.call(publicThis, publicThis) if (__DEV__ && isPromise(data)) { warn( `data() returned a Promise - note data() cannot be async; If you ` + `intend to perform data fetching before component renders, use ` + `async setup() + <Suspense>.` ) } if (!isObject(data)) { __DEV__ && warn(`data() should return an object.`) } else if (instance.data === EMPTY_OBJ) { instance.data = reactive(data) } else { // existing data: this is a mixin or extends. extend(instance.data, data) } } function createWatcher( raw: ComponentWatchOptionItem, ctx: Data, publicThis: ComponentPublicInstance, key: string ) { const getter = () => (publicThis as any)[key] if (isString(raw)) { const handler = ctx[raw] if (isFunction(handler)) { watch(getter, handler as WatchCallback) } else if (__DEV__) { warn(`Invalid watch handler specified by key "${raw}"`, handler) } } else if (isFunction(raw)) { watch(getter, raw.bind(publicThis)) } else if (isObject(raw)) { if (isArray(raw)) { raw.forEach(r => createWatcher(r, ctx, publicThis, key)) } else { const handler = isFunction(raw.handler) ? raw.handler.bind(publicThis) : (ctx[raw.handler] as WatchCallback) if (isFunction(handler)) { watch(getter, handler, raw) } else if (__DEV__) { warn(`Invalid watch handler specified by key "${raw.handler}"`, handler) } } } else if (__DEV__) { warn(`Invalid watch option: "${key}"`) } } export function resolveMergedOptions( instance: ComponentInternalInstance ): ComponentOptions { const raw = instance.type as ComponentOptions const { __merged, mixins, extends: extendsOptions } = raw if (__merged) return __merged const globalMixins = instance.appContext.mixins if (!globalMixins.length && !mixins && !extendsOptions) return raw const options = {} globalMixins.forEach(m => mergeOptions(options, m, instance)) mergeOptions(options, raw, instance) return (raw.__merged = options) } function mergeOptions(to: any, from: any, instance: ComponentInternalInstance) { const strats = instance.appContext.config.optionMergeStrategies const { mixins, extends: extendsOptions } = from extendsOptions && mergeOptions(to, extendsOptions, instance) mixins && mixins.forEach((m: ComponentOptionsMixin) => mergeOptions(to, m, instance)) for (const key in from) { if (strats && hasOwn(strats, key)) { to[key] = strats[key](to[key], from[key], instance.proxy, key) } else { to[key] = from[key] } } }
packages/runtime-core/src/componentOptions.ts
1
https://github.com/vuejs/core/commit/313dd06065b1782d67f6881fbd42ae92a7f9cade
[ 0.3486531674861908, 0.004884256981313229, 0.0001643646537559107, 0.0001689725904725492, 0.038779936730861664 ]
{ "id": 0, "code_window": [ " return {\n", " a: this.a\n", " }\n", " },\n", " render() {\n", " return [h(ChildA), h(ChildB), h(ChildC), h(ChildD), h(ChildE)]\n", " }\n", " })\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " return [\n", " h(ChildA),\n", " h(ChildB),\n", " h(ChildC),\n", " h(ChildD),\n", " h(ChildE),\n", " h(ChildF),\n", " h(ChildG),\n", " h(ChildH)\n", " ]\n" ], "file_path": "packages/runtime-core/__tests__/apiOptions.spec.ts", "type": "replace", "edit_start_line_idx": 255 }
// This directory contains a number of d.ts assertions using tsd: // https://github.com/SamVerschueren/tsd // The tests checks type errors and will probably show up red in VSCode, and // it's intended. We cannot use directives like @ts-ignore or @ts-nocheck since // that would suppress the errors that should be caught. export * from '@vue/runtime-dom' export function describe(_name: string, _fn: () => void): void export function expectType<T>(value: T): void export function expectError<T>(value: T): void export function expectAssignable<T, T2 extends T = T>(value: T2): void
test-dts/index.d.ts
0
https://github.com/vuejs/core/commit/313dd06065b1782d67f6881fbd42ae92a7f9cade
[ 0.00018253795860800892, 0.00017662117897998542, 0.0001707043993519619, 0.00017662117897998542, 0.000005916779628023505 ]
{ "id": 0, "code_window": [ " return {\n", " a: this.a\n", " }\n", " },\n", " render() {\n", " return [h(ChildA), h(ChildB), h(ChildC), h(ChildD), h(ChildE)]\n", " }\n", " })\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " return [\n", " h(ChildA),\n", " h(ChildB),\n", " h(ChildC),\n", " h(ChildD),\n", " h(ChildE),\n", " h(ChildF),\n", " h(ChildG),\n", " h(ChildH)\n", " ]\n" ], "file_path": "packages/runtime-core/__tests__/apiOptions.spec.ts", "type": "replace", "edit_start_line_idx": 255 }
import { onBeforeMount, h, nodeOps, render, serializeInner, onMounted, ref, onBeforeUpdate, nextTick, onUpdated, onBeforeUnmount, onUnmounted, onRenderTracked, reactive, TrackOpTypes, onRenderTriggered } from '@vue/runtime-test' import { ITERATE_KEY, DebuggerEvent, TriggerOpTypes } from '@vue/reactivity' // reference: https://vue-composition-api-rfc.netlify.com/api.html#lifecycle-hooks describe('api: lifecycle hooks', () => { it('onBeforeMount', () => { const root = nodeOps.createElement('div') const fn = jest.fn(() => { // should be called before inner div is rendered expect(serializeInner(root)).toBe(``) }) const Comp = { setup() { onBeforeMount(fn) return () => h('div') } } render(h(Comp), root) expect(fn).toHaveBeenCalledTimes(1) }) it('onMounted', () => { const root = nodeOps.createElement('div') const fn = jest.fn(() => { // should be called after inner div is rendered expect(serializeInner(root)).toBe(`<div></div>`) }) const Comp = { setup() { onMounted(fn) return () => h('div') } } render(h(Comp), root) expect(fn).toHaveBeenCalledTimes(1) }) it('onBeforeUpdate', async () => { const count = ref(0) const root = nodeOps.createElement('div') const fn = jest.fn(() => { // should be called before inner div is updated expect(serializeInner(root)).toBe(`<div>0</div>`) }) const Comp = { setup() { onBeforeUpdate(fn) return () => h('div', count.value) } } render(h(Comp), root) count.value++ await nextTick() expect(fn).toHaveBeenCalledTimes(1) expect(serializeInner(root)).toBe(`<div>1</div>`) }) it('state mutation in onBeforeUpdate', async () => { const count = ref(0) const root = nodeOps.createElement('div') const fn = jest.fn(() => { // should be called before inner div is updated expect(serializeInner(root)).toBe(`<div>0</div>`) count.value++ }) const renderSpy = jest.fn() const Comp = { setup() { onBeforeUpdate(fn) return () => { renderSpy() return h('div', count.value) } } } render(h(Comp), root) expect(renderSpy).toHaveBeenCalledTimes(1) count.value++ await nextTick() expect(fn).toHaveBeenCalledTimes(1) expect(renderSpy).toHaveBeenCalledTimes(2) expect(serializeInner(root)).toBe(`<div>2</div>`) }) it('onUpdated', async () => { const count = ref(0) const root = nodeOps.createElement('div') const fn = jest.fn(() => { // should be called after inner div is updated expect(serializeInner(root)).toBe(`<div>1</div>`) }) const Comp = { setup() { onUpdated(fn) return () => h('div', count.value) } } render(h(Comp), root) count.value++ await nextTick() expect(fn).toHaveBeenCalledTimes(1) }) it('onBeforeUnmount', async () => { const toggle = ref(true) const root = nodeOps.createElement('div') const fn = jest.fn(() => { // should be called before inner div is removed expect(serializeInner(root)).toBe(`<div></div>`) }) const Comp = { setup() { return () => (toggle.value ? h(Child) : null) } } const Child = { setup() { onBeforeUnmount(fn) return () => h('div') } } render(h(Comp), root) toggle.value = false await nextTick() expect(fn).toHaveBeenCalledTimes(1) }) it('onUnmounted', async () => { const toggle = ref(true) const root = nodeOps.createElement('div') const fn = jest.fn(() => { // should be called after inner div is removed expect(serializeInner(root)).toBe(`<!---->`) }) const Comp = { setup() { return () => (toggle.value ? h(Child) : null) } } const Child = { setup() { onUnmounted(fn) return () => h('div') } } render(h(Comp), root) toggle.value = false await nextTick() expect(fn).toHaveBeenCalledTimes(1) }) it('onBeforeUnmount in onMounted', async () => { const toggle = ref(true) const root = nodeOps.createElement('div') const fn = jest.fn(() => { // should be called before inner div is removed expect(serializeInner(root)).toBe(`<div></div>`) }) const Comp = { setup() { return () => (toggle.value ? h(Child) : null) } } const Child = { setup() { onMounted(() => { onBeforeUnmount(fn) }) return () => h('div') } } render(h(Comp), root) toggle.value = false await nextTick() expect(fn).toHaveBeenCalledTimes(1) }) it('lifecycle call order', async () => { const count = ref(0) const root = nodeOps.createElement('div') const calls: string[] = [] const Root = { setup() { onBeforeMount(() => calls.push('root onBeforeMount')) onMounted(() => calls.push('root onMounted')) onBeforeUpdate(() => calls.push('root onBeforeUpdate')) onUpdated(() => calls.push('root onUpdated')) onBeforeUnmount(() => calls.push('root onBeforeUnmount')) onUnmounted(() => calls.push('root onUnmounted')) return () => h(Mid, { count: count.value }) } } const Mid = { setup(props: any) { onBeforeMount(() => calls.push('mid onBeforeMount')) onMounted(() => calls.push('mid onMounted')) onBeforeUpdate(() => calls.push('mid onBeforeUpdate')) onUpdated(() => calls.push('mid onUpdated')) onBeforeUnmount(() => calls.push('mid onBeforeUnmount')) onUnmounted(() => calls.push('mid onUnmounted')) return () => h(Child, { count: props.count }) } } const Child = { setup(props: any) { onBeforeMount(() => calls.push('child onBeforeMount')) onMounted(() => calls.push('child onMounted')) onBeforeUpdate(() => calls.push('child onBeforeUpdate')) onUpdated(() => calls.push('child onUpdated')) onBeforeUnmount(() => calls.push('child onBeforeUnmount')) onUnmounted(() => calls.push('child onUnmounted')) return () => h('div', props.count) } } // mount render(h(Root), root) expect(calls).toEqual([ 'root onBeforeMount', 'mid onBeforeMount', 'child onBeforeMount', 'child onMounted', 'mid onMounted', 'root onMounted' ]) calls.length = 0 // update count.value++ await nextTick() expect(calls).toEqual([ 'root onBeforeUpdate', 'mid onBeforeUpdate', 'child onBeforeUpdate', 'child onUpdated', 'mid onUpdated', 'root onUpdated' ]) calls.length = 0 // unmount render(null, root) expect(calls).toEqual([ 'root onBeforeUnmount', 'mid onBeforeUnmount', 'child onBeforeUnmount', 'child onUnmounted', 'mid onUnmounted', 'root onUnmounted' ]) }) it('onRenderTracked', () => { const events: DebuggerEvent[] = [] const onTrack = jest.fn((e: DebuggerEvent) => { events.push(e) }) const obj = reactive({ foo: 1, bar: 2 }) const Comp = { setup() { onRenderTracked(onTrack) return () => h('div', [obj.foo, 'bar' in obj, Object.keys(obj).join('')]) } } render(h(Comp), nodeOps.createElement('div')) expect(onTrack).toHaveBeenCalledTimes(3) expect(events).toMatchObject([ { target: obj, type: TrackOpTypes.GET, key: 'foo' }, { target: obj, type: TrackOpTypes.HAS, key: 'bar' }, { target: obj, type: TrackOpTypes.ITERATE, key: ITERATE_KEY } ]) }) it('onRenderTriggered', async () => { const events: DebuggerEvent[] = [] const onTrigger = jest.fn((e: DebuggerEvent) => { events.push(e) }) const obj = reactive({ foo: 1, bar: 2 }) const Comp = { setup() { onRenderTriggered(onTrigger) return () => h('div', [obj.foo, 'bar' in obj, Object.keys(obj).join('')]) } } render(h(Comp), nodeOps.createElement('div')) obj.foo++ await nextTick() expect(onTrigger).toHaveBeenCalledTimes(1) expect(events[0]).toMatchObject({ type: TriggerOpTypes.SET, key: 'foo', oldValue: 1, newValue: 2 }) // @ts-ignore delete obj.bar await nextTick() expect(onTrigger).toHaveBeenCalledTimes(2) expect(events[1]).toMatchObject({ type: TriggerOpTypes.DELETE, key: 'bar', oldValue: 2 }) ;(obj as any).baz = 3 await nextTick() expect(onTrigger).toHaveBeenCalledTimes(3) expect(events[2]).toMatchObject({ type: TriggerOpTypes.ADD, key: 'baz', newValue: 3 }) }) })
packages/runtime-core/__tests__/apiLifecycle.spec.ts
0
https://github.com/vuejs/core/commit/313dd06065b1782d67f6881fbd42ae92a7f9cade
[ 0.9952452778816223, 0.36224794387817383, 0.00016689607582520694, 0.001368137658573687, 0.4719794988632202 ]
{ "id": 0, "code_window": [ " return {\n", " a: this.a\n", " }\n", " },\n", " render() {\n", " return [h(ChildA), h(ChildB), h(ChildC), h(ChildD), h(ChildE)]\n", " }\n", " })\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " return [\n", " h(ChildA),\n", " h(ChildB),\n", " h(ChildC),\n", " h(ChildD),\n", " h(ChildE),\n", " h(ChildF),\n", " h(ChildG),\n", " h(ChildH)\n", " ]\n" ], "file_path": "packages/runtime-core/__tests__/apiOptions.spec.ts", "type": "replace", "edit_start_line_idx": 255 }
The MIT License (MIT) Copyright (c) 2018-present, Yuxi (Evan) You Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
packages/server-renderer/LICENSE
0
https://github.com/vuejs/core/commit/313dd06065b1782d67f6881fbd42ae92a7f9cade
[ 0.00017210864461958408, 0.00017075891082640737, 0.000168720303918235, 0.00017144774028565735, 0.0000014665362186860875 ]
{ "id": 1, "code_window": [ " b: {\n", " from: 'a'\n", " }\n", " })\n", " const ChildD = defineChild({\n", " b: {\n", " from: 'c',\n", " default: 2\n", " }\n", " })\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const ChildD = defineChild(\n", " {\n", " a: {\n", " default: () => 0\n", " }\n", " },\n", " 'a'\n", " )\n", " const ChildE = defineChild({\n" ], "file_path": "packages/runtime-core/__tests__/apiOptions.spec.ts", "type": "replace", "edit_start_line_idx": 274 }
import { h, nodeOps, render, serializeInner, triggerEvent, TestElement, nextTick, renderToString, ref, defineComponent } from '@vue/runtime-test' describe('api: options', () => { test('data', async () => { const Comp = defineComponent({ data() { return { foo: 1 } }, render() { return h( 'div', { onClick: () => { this.foo++ } }, this.foo ) } }) const root = nodeOps.createElement('div') render(h(Comp), root) expect(serializeInner(root)).toBe(`<div>1</div>`) triggerEvent(root.children[0] as TestElement, 'click') await nextTick() expect(serializeInner(root)).toBe(`<div>2</div>`) }) test('computed', async () => { const Comp = defineComponent({ data() { return { foo: 1 } }, computed: { bar(): number { return this.foo + 1 }, baz: (vm): number => vm.bar + 1 }, render() { return h( 'div', { onClick: () => { this.foo++ } }, this.bar + this.baz ) } }) const root = nodeOps.createElement('div') render(h(Comp), root) expect(serializeInner(root)).toBe(`<div>5</div>`) triggerEvent(root.children[0] as TestElement, 'click') await nextTick() expect(serializeInner(root)).toBe(`<div>7</div>`) }) test('methods', async () => { const Comp = defineComponent({ data() { return { foo: 1 } }, methods: { inc() { this.foo++ } }, render() { return h( 'div', { onClick: this.inc }, this.foo ) } }) const root = nodeOps.createElement('div') render(h(Comp), root) expect(serializeInner(root)).toBe(`<div>1</div>`) triggerEvent(root.children[0] as TestElement, 'click') await nextTick() expect(serializeInner(root)).toBe(`<div>2</div>`) }) test('watch', async () => { function returnThis(this: any) { return this } const spyA = jest.fn(returnThis) const spyB = jest.fn(returnThis) const spyC = jest.fn(returnThis) const spyD = jest.fn(returnThis) let ctx: any const Comp = { data() { return { foo: 1, bar: 2, baz: { qux: 3 }, qux: 4 } }, watch: { // string method name foo: 'onFooChange', // direct function bar: spyB, baz: { handler: spyC, deep: true }, qux: { handler: 'onQuxChange' } }, methods: { onFooChange: spyA, onQuxChange: spyD }, render() { ctx = this } } const root = nodeOps.createElement('div') render(h(Comp), root) function assertCall(spy: jest.Mock, callIndex: number, args: any[]) { expect(spy.mock.calls[callIndex].slice(0, 2)).toMatchObject(args) expect(spy).toHaveReturnedWith(ctx) } ctx.foo++ await nextTick() expect(spyA).toHaveBeenCalledTimes(1) assertCall(spyA, 0, [2, 1]) ctx.bar++ await nextTick() expect(spyB).toHaveBeenCalledTimes(1) assertCall(spyB, 0, [3, 2]) ctx.baz.qux++ await nextTick() expect(spyC).toHaveBeenCalledTimes(1) // new and old objects have same identity assertCall(spyC, 0, [{ qux: 4 }, { qux: 4 }]) ctx.qux++ await nextTick() expect(spyD).toHaveBeenCalledTimes(1) assertCall(spyD, 0, [5, 4]) }) test('watch array', async () => { function returnThis(this: any) { return this } const spyA = jest.fn(returnThis) const spyB = jest.fn(returnThis) const spyC = jest.fn(returnThis) let ctx: any const Comp = { data() { return { foo: 1, bar: 2, baz: { qux: 3 } } }, watch: { // string method name foo: ['onFooChange'], // direct function bar: [spyB], baz: [ { handler: spyC, deep: true } ] }, methods: { onFooChange: spyA }, render() { ctx = this } } const root = nodeOps.createElement('div') render(h(Comp), root) function assertCall(spy: jest.Mock, callIndex: number, args: any[]) { expect(spy.mock.calls[callIndex].slice(0, 2)).toMatchObject(args) expect(spy).toHaveReturnedWith(ctx) } ctx.foo++ await nextTick() expect(spyA).toHaveBeenCalledTimes(1) assertCall(spyA, 0, [2, 1]) ctx.bar++ await nextTick() expect(spyB).toHaveBeenCalledTimes(1) assertCall(spyB, 0, [3, 2]) ctx.baz.qux++ await nextTick() expect(spyC).toHaveBeenCalledTimes(1) // new and old objects have same identity assertCall(spyC, 0, [{ qux: 4 }, { qux: 4 }]) }) test('provide/inject', () => { const Root = defineComponent({ data() { return { a: 1 } }, provide() { return { a: this.a } }, render() { return [h(ChildA), h(ChildB), h(ChildC), h(ChildD), h(ChildE)] } }) const defineChild = (injectOptions: any, injectedKey = 'b') => ({ inject: injectOptions, render() { return this[injectedKey] } } as any) const ChildA = defineChild(['a'], 'a') const ChildB = defineChild({ b: 'a' }) const ChildC = defineChild({ b: { from: 'a' } }) const ChildD = defineChild({ b: { from: 'c', default: 2 } }) const ChildE = defineChild({ b: { from: 'c', default: () => 3 } }) expect(renderToString(h(Root))).toBe(`11123`) }) test('lifecycle', async () => { const count = ref(0) const root = nodeOps.createElement('div') const calls: string[] = [] const Root = { beforeCreate() { calls.push('root beforeCreate') }, created() { calls.push('root created') }, beforeMount() { calls.push('root onBeforeMount') }, mounted() { calls.push('root onMounted') }, beforeUpdate() { calls.push('root onBeforeUpdate') }, updated() { calls.push('root onUpdated') }, beforeUnmount() { calls.push('root onBeforeUnmount') }, unmounted() { calls.push('root onUnmounted') }, render() { return h(Mid, { count: count.value }) } } const Mid = { beforeCreate() { calls.push('mid beforeCreate') }, created() { calls.push('mid created') }, beforeMount() { calls.push('mid onBeforeMount') }, mounted() { calls.push('mid onMounted') }, beforeUpdate() { calls.push('mid onBeforeUpdate') }, updated() { calls.push('mid onUpdated') }, beforeUnmount() { calls.push('mid onBeforeUnmount') }, unmounted() { calls.push('mid onUnmounted') }, render(this: any) { return h(Child, { count: this.$props.count }) } } const Child = { beforeCreate() { calls.push('child beforeCreate') }, created() { calls.push('child created') }, beforeMount() { calls.push('child onBeforeMount') }, mounted() { calls.push('child onMounted') }, beforeUpdate() { calls.push('child onBeforeUpdate') }, updated() { calls.push('child onUpdated') }, beforeUnmount() { calls.push('child onBeforeUnmount') }, unmounted() { calls.push('child onUnmounted') }, render(this: any) { return h('div', this.$props.count) } } // mount render(h(Root), root) expect(calls).toEqual([ 'root beforeCreate', 'root created', 'root onBeforeMount', 'mid beforeCreate', 'mid created', 'mid onBeforeMount', 'child beforeCreate', 'child created', 'child onBeforeMount', 'child onMounted', 'mid onMounted', 'root onMounted' ]) calls.length = 0 // update count.value++ await nextTick() expect(calls).toEqual([ 'root onBeforeUpdate', 'mid onBeforeUpdate', 'child onBeforeUpdate', 'child onUpdated', 'mid onUpdated', 'root onUpdated' ]) calls.length = 0 // unmount render(null, root) expect(calls).toEqual([ 'root onBeforeUnmount', 'mid onBeforeUnmount', 'child onBeforeUnmount', 'child onUnmounted', 'mid onUnmounted', 'root onUnmounted' ]) }) test('mixins', () => { const calls: string[] = [] const mixinA = { data() { return { a: 1 } }, created(this: any) { calls.push('mixinA created') expect(this.a).toBe(1) expect(this.b).toBe(2) expect(this.c).toBe(4) }, mounted() { calls.push('mixinA mounted') } } const mixinB = { props: { bP: { type: String } }, data() { return { b: 2 } }, created(this: any) { calls.push('mixinB created') expect(this.a).toBe(1) expect(this.b).toBe(2) expect(this.bP).toBeUndefined() expect(this.c).toBe(4) expect(this.cP1).toBeUndefined() }, mounted() { calls.push('mixinB mounted') } } const mixinC = defineComponent({ props: ['cP1', 'cP2'], data() { return { c: 3 } }, created() { calls.push('mixinC created') // component data() should overwrite mixin field with same key expect(this.c).toBe(4) expect(this.cP1).toBeUndefined() }, mounted() { calls.push('mixinC mounted') } }) const Comp = defineComponent({ props: { aaa: String }, mixins: [defineComponent(mixinA), defineComponent(mixinB), mixinC], data() { return { c: 4, z: 4 } }, created() { calls.push('comp created') expect(this.a).toBe(1) expect(this.b).toBe(2) expect(this.bP).toBeUndefined() expect(this.c).toBe(4) expect(this.cP2).toBeUndefined() expect(this.z).toBe(4) }, mounted() { calls.push('comp mounted') }, render() { return `${this.a}${this.b}${this.c}` } }) expect(renderToString(h(Comp))).toBe(`124`) expect(calls).toEqual([ 'mixinA created', 'mixinB created', 'mixinC created', 'comp created', 'mixinA mounted', 'mixinB mounted', 'mixinC mounted', 'comp mounted' ]) }) test('render from mixin', () => { const Comp = { mixins: [ { render: () => 'from mixin' } ] } expect(renderToString(h(Comp))).toBe('from mixin') }) test('extends', () => { const calls: string[] = [] const Base = { data() { return { a: 1, b: 1 } }, methods: { sayA() {} }, mounted(this: any) { expect(this.a).toBe(1) expect(this.b).toBe(2) calls.push('base') } } const Comp = defineComponent({ extends: defineComponent(Base), data() { return { b: 2 } }, mounted() { calls.push('comp') }, render() { return `${this.a}${this.b}` } }) expect(renderToString(h(Comp))).toBe(`12`) expect(calls).toEqual(['base', 'comp']) }) test('extends with mixins', () => { const calls: string[] = [] const Base = { data() { return { a: 1, x: 'base' } }, methods: { sayA() {} }, mounted(this: any) { expect(this.a).toBe(1) expect(this.b).toBeTruthy() expect(this.c).toBe(2) calls.push('base') } } const Mixin = { data() { return { b: true, x: 'mixin' } }, mounted(this: any) { expect(this.a).toBe(1) expect(this.b).toBeTruthy() expect(this.c).toBe(2) calls.push('mixin') } } const Comp = defineComponent({ extends: defineComponent(Base), mixins: [defineComponent(Mixin)], data() { return { c: 2 } }, mounted() { calls.push('comp') }, render() { return `${this.a}${this.b}${this.c}${this.x}` } }) expect(renderToString(h(Comp))).toBe(`1true2mixin`) expect(calls).toEqual(['base', 'mixin', 'comp']) }) test('beforeCreate/created in extends and mixins', () => { const calls: string[] = [] const BaseA = { beforeCreate() { calls.push('beforeCreateA') }, created() { calls.push('createdA') } } const BaseB = { extends: BaseA, beforeCreate() { calls.push('beforeCreateB') }, created() { calls.push('createdB') } } const MixinA = { beforeCreate() { calls.push('beforeCreateC') }, created() { calls.push('createdC') } } const MixinB = { mixins: [MixinA], beforeCreate() { calls.push('beforeCreateD') }, created() { calls.push('createdD') } } const Comp = { extends: BaseB, mixins: [MixinB], beforeCreate() { calls.push('selfBeforeCreate') }, created() { calls.push('selfCreated') }, render() {} } renderToString(h(Comp)) expect(calls).toEqual([ 'beforeCreateA', 'beforeCreateB', 'beforeCreateC', 'beforeCreateD', 'selfBeforeCreate', 'createdA', 'createdB', 'createdC', 'createdD', 'selfCreated' ]) }) test('flatten merged options', async () => { const MixinBase = { msg1: 'base' } const ExtendsBase = { msg2: 'base' } const Mixin = { mixins: [MixinBase] } const Extends = { extends: ExtendsBase } const Comp = defineComponent({ extends: defineComponent(Extends), mixins: [defineComponent(Mixin)], render() { return `${this.$options.msg1},${this.$options.msg2}` } }) expect(renderToString(h(Comp))).toBe('base,base') }) test('options defined in component have higher priority', async () => { const Mixin = { msg1: 'base' } const Extends = { msg2: 'base' } const Comp = defineComponent({ msg1: 'local', msg2: 'local', extends: defineComponent(Extends), mixins: [defineComponent(Mixin)], render() { return `${this.$options.msg1},${this.$options.msg2}` } }) expect(renderToString(h(Comp))).toBe('local,local') }) test('accessing setup() state from options', async () => { const Comp = defineComponent({ setup() { return { count: ref(0) } }, data() { return { plusOne: (this as any).count + 1 } }, computed: { plusTwo(): number { return this.count + 2 } }, methods: { inc() { this.count++ } }, render() { return h( 'div', { onClick: this.inc }, `${this.count},${this.plusOne},${this.plusTwo}` ) } }) const root = nodeOps.createElement('div') render(h(Comp), root) expect(serializeInner(root)).toBe(`<div>0,1,2</div>`) triggerEvent(root.children[0] as TestElement, 'click') await nextTick() expect(serializeInner(root)).toBe(`<div>1,1,3</div>`) }) // #1016 test('watcher initialization should be deferred in mixins', async () => { const mixin1 = { data() { return { mixin1Data: 'mixin1' } }, methods: {} } const watchSpy = jest.fn() const mixin2 = { watch: { mixin3Data: watchSpy } } const mixin3 = { data() { return { mixin3Data: 'mixin3' } }, methods: {} } let vm: any const Comp = { mixins: [mixin1, mixin2, mixin3], render() {}, created() { vm = this } } const root = nodeOps.createElement('div') render(h(Comp), root) // should have no warnings vm.mixin3Data = 'hello' await nextTick() expect(watchSpy.mock.calls[0].slice(0, 2)).toEqual(['hello', 'mixin3']) }) describe('warnings', () => { test('Expected a function as watch handler', () => { const Comp = { watch: { foo: 'notExistingMethod', foo2: { handler: 'notExistingMethod2' } }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( 'Invalid watch handler specified by key "notExistingMethod"' ).toHaveBeenWarned() expect( 'Invalid watch handler specified by key "notExistingMethod2"' ).toHaveBeenWarned() }) test('Invalid watch option', () => { const Comp = { watch: { foo: true }, render() {} } const root = nodeOps.createElement('div') // @ts-ignore render(h(Comp), root) expect('Invalid watch option: "foo"').toHaveBeenWarned() }) test('computed with setter and no getter', () => { const Comp = { computed: { foo: { set() {} } }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect('Computed property "foo" has no getter.').toHaveBeenWarned() }) test('assigning to computed with no setter', () => { let instance: any const Comp = { computed: { foo: { get() {} } }, mounted() { instance = this }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) instance.foo = 1 expect( 'Write operation failed: computed property "foo" is readonly' ).toHaveBeenWarned() }) test('inject property is already declared in props', () => { const Comp = { data() { return { a: 1 } }, provide() { return { a: this.a } }, render() { return [h(ChildA)] } } as any const ChildA = { props: { a: Number }, inject: ['a'], render() { return this.a } } as any const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Inject property "a" is already defined in Props.` ).toHaveBeenWarned() }) test('methods property is not a function', () => { const Comp = { methods: { foo: 1 }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Method "foo" has type "number" in the component definition. ` + `Did you reference the function correctly?` ).toHaveBeenWarned() }) test('methods property is already declared in props', () => { const Comp = { props: { foo: Number }, methods: { foo() {} }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Methods property "foo" is already defined in Props.` ).toHaveBeenWarned() }) test('methods property is already declared in inject', () => { const Comp = { data() { return { a: 1 } }, provide() { return { a: this.a } }, render() { return [h(ChildA)] } } as any const ChildA = { methods: { a: () => null }, inject: ['a'], render() { return this.a } } as any const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Methods property "a" is already defined in Inject.` ).toHaveBeenWarned() }) test('data property is already declared in props', () => { const Comp = { props: { foo: Number }, data: () => ({ foo: 1 }), render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Data property "foo" is already defined in Props.` ).toHaveBeenWarned() }) test('data property is already declared in inject', () => { const Comp = { data() { return { a: 1 } }, provide() { return { a: this.a } }, render() { return [h(ChildA)] } } as any const ChildA = { data() { return { a: 1 } }, inject: ['a'], render() { return this.a } } as any const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Data property "a" is already defined in Inject.` ).toHaveBeenWarned() }) test('data property is already declared in methods', () => { const Comp = { data: () => ({ foo: 1 }), methods: { foo() {} }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Data property "foo" is already defined in Methods.` ).toHaveBeenWarned() }) test('computed property is already declared in props', () => { const Comp = { props: { foo: Number }, computed: { foo() {} }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Computed property "foo" is already defined in Props.` ).toHaveBeenWarned() }) test('computed property is already declared in inject', () => { const Comp = { data() { return { a: 1 } }, provide() { return { a: this.a } }, render() { return [h(ChildA)] } } as any const ChildA = { computed: { a: { get() {}, set() {} } }, inject: ['a'], render() { return this.a } } as any const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Computed property "a" is already defined in Inject.` ).toHaveBeenWarned() }) test('computed property is already declared in methods', () => { const Comp = { computed: { foo() {} }, methods: { foo() {} }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Computed property "foo" is already defined in Methods.` ).toHaveBeenWarned() }) test('computed property is already declared in data', () => { const Comp = { data: () => ({ foo: 1 }), computed: { foo() {} }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Computed property "foo" is already defined in Data.` ).toHaveBeenWarned() }) }) })
packages/runtime-core/__tests__/apiOptions.spec.ts
1
https://github.com/vuejs/core/commit/313dd06065b1782d67f6881fbd42ae92a7f9cade
[ 0.9983224272727966, 0.017497822642326355, 0.0001639861147850752, 0.00017183873569592834, 0.12963464856147766 ]
{ "id": 1, "code_window": [ " b: {\n", " from: 'a'\n", " }\n", " })\n", " const ChildD = defineChild({\n", " b: {\n", " from: 'c',\n", " default: 2\n", " }\n", " })\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const ChildD = defineChild(\n", " {\n", " a: {\n", " default: () => 0\n", " }\n", " },\n", " 'a'\n", " )\n", " const ChildE = defineChild({\n" ], "file_path": "packages/runtime-core/__tests__/apiOptions.spec.ts", "type": "replace", "edit_start_line_idx": 274 }
import { DirectiveTransform, ElementTypes, transformModel, findProp, NodeTypes, createDOMCompilerError, DOMErrorCodes, createObjectProperty, createSimpleExpression, createCallExpression, PlainElementNode, ExpressionNode, createConditionalExpression, createInterpolation, hasDynamicKeyVBind } from '@vue/compiler-dom' import { SSR_LOOSE_EQUAL, SSR_LOOSE_CONTAIN, SSR_RENDER_DYNAMIC_MODEL } from '../runtimeHelpers' import { DirectiveTransformResult } from 'packages/compiler-core/src/transform' export const ssrTransformModel: DirectiveTransform = (dir, node, context) => { const model = dir.exp! function checkDuplicatedValue() { const value = findProp(node, 'value') if (value) { context.onError( createDOMCompilerError( DOMErrorCodes.X_V_MODEL_UNNECESSARY_VALUE, value.loc ) ) } } if (node.tagType === ElementTypes.ELEMENT) { const res: DirectiveTransformResult = { props: [] } const defaultProps = [ // default value binding for text type inputs createObjectProperty(`value`, model) ] if (node.tag === 'input') { const type = findProp(node, 'type') if (type) { const value = findValueBinding(node) if (type.type === NodeTypes.DIRECTIVE) { // dynamic type res.ssrTagParts = [ createCallExpression(context.helper(SSR_RENDER_DYNAMIC_MODEL), [ type.exp!, model, value ]) ] } else if (type.value) { // static type switch (type.value.content) { case 'radio': res.props = [ createObjectProperty( `checked`, createCallExpression(context.helper(SSR_LOOSE_EQUAL), [ model, value ]) ) ] break case 'checkbox': res.props = [ createObjectProperty( `checked`, createConditionalExpression( createCallExpression(`Array.isArray`, [model]), createCallExpression(context.helper(SSR_LOOSE_CONTAIN), [ model, value ]), model ) ) ] break case 'file': context.onError( createDOMCompilerError( DOMErrorCodes.X_V_MODEL_ON_FILE_INPUT_ELEMENT, dir.loc ) ) break default: checkDuplicatedValue() res.props = defaultProps break } } } else if (hasDynamicKeyVBind(node)) { // dynamic type due to dynamic v-bind // NOOP, handled in ssrTransformElement due to need to rewrite // the entire props expression } else { // text type checkDuplicatedValue() res.props = defaultProps } } else if (node.tag === 'textarea') { checkDuplicatedValue() node.children = [createInterpolation(model, model.loc)] } else if (node.tag === 'select') { // NOOP // select relies on client-side directive to set initial selected state. } else { context.onError( createDOMCompilerError( DOMErrorCodes.X_V_MODEL_ON_INVALID_ELEMENT, dir.loc ) ) } return res } else { // component v-model return transformModel(dir, node, context) } } function findValueBinding(node: PlainElementNode): ExpressionNode { const valueBinding = findProp(node, 'value') return valueBinding ? valueBinding.type === NodeTypes.DIRECTIVE ? valueBinding.exp! : createSimpleExpression(valueBinding.value!.content, true) : createSimpleExpression(`null`, false) }
packages/compiler-ssr/src/transforms/ssrVModel.ts
0
https://github.com/vuejs/core/commit/313dd06065b1782d67f6881fbd42ae92a7f9cade
[ 0.0001751239615259692, 0.00017236049461644143, 0.00016702598077245057, 0.00017208632198162377, 0.000002332386657144525 ]
{ "id": 1, "code_window": [ " b: {\n", " from: 'a'\n", " }\n", " })\n", " const ChildD = defineChild({\n", " b: {\n", " from: 'c',\n", " default: 2\n", " }\n", " })\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const ChildD = defineChild(\n", " {\n", " a: {\n", " default: () => 0\n", " }\n", " },\n", " 'a'\n", " )\n", " const ChildE = defineChild({\n" ], "file_path": "packages/runtime-core/__tests__/apiOptions.spec.ts", "type": "replace", "edit_start_line_idx": 274 }
import { createApp, h, nodeOps, serializeInner, provide, inject, resolveComponent, resolveDirective, withDirectives, Plugin, ref, getCurrentInstance, defineComponent } from '@vue/runtime-test' describe('api: createApp', () => { test('mount', () => { const Comp = defineComponent({ props: { count: { default: 0 } }, setup(props) { return () => props.count } }) const root1 = nodeOps.createElement('div') createApp(Comp).mount(root1) expect(serializeInner(root1)).toBe(`0`) // mount with props const root2 = nodeOps.createElement('div') const app2 = createApp(Comp, { count: 1 }) app2.mount(root2) expect(serializeInner(root2)).toBe(`1`) // remount warning const root3 = nodeOps.createElement('div') app2.mount(root3) expect(serializeInner(root3)).toBe(``) expect(`already been mounted`).toHaveBeenWarned() }) test('unmount', () => { const Comp = defineComponent({ props: { count: { default: 0 } }, setup(props) { return () => props.count } }) const root = nodeOps.createElement('div') const app = createApp(Comp) app.mount(root) app.unmount(root) expect(serializeInner(root)).toBe(``) }) test('provide', () => { const Root = { setup() { // test override provide('foo', 3) return () => h(Child) } } const Child = { setup() { const foo = inject('foo') const bar = inject('bar') try { inject('__proto__') } catch (e) {} return () => `${foo},${bar}` } } const app = createApp(Root) app.provide('foo', 1) app.provide('bar', 2) const root = nodeOps.createElement('div') app.mount(root) expect(serializeInner(root)).toBe(`3,2`) expect('[Vue warn]: injection "__proto__" not found.').toHaveBeenWarned() }) test('component', () => { const Root = { // local override components: { BarBaz: () => 'barbaz-local!' }, setup() { // resolve in setup const FooBar = resolveComponent('foo-bar') as any return () => { // resolve in render const BarBaz = resolveComponent('bar-baz') as any return h('div', [h(FooBar), h(BarBaz)]) } } } const app = createApp(Root) const FooBar = () => 'foobar!' app.component('FooBar', FooBar) expect(app.component('FooBar')).toBe(FooBar) app.component('BarBaz', () => 'barbaz!') app.component('BarBaz', () => 'barbaz!') expect( 'Component "BarBaz" has already been registered in target app.' ).toHaveBeenWarnedTimes(1) const root = nodeOps.createElement('div') app.mount(root) expect(serializeInner(root)).toBe(`<div>foobar!barbaz-local!</div>`) }) test('directive', () => { const spy1 = jest.fn() const spy2 = jest.fn() const spy3 = jest.fn() const Root = { // local override directives: { BarBaz: { mounted: spy3 } }, setup() { // resolve in setup const FooBar = resolveDirective('foo-bar')! return () => { // resolve in render const BarBaz = resolveDirective('bar-baz')! return withDirectives(h('div'), [[FooBar], [BarBaz]]) } } } const app = createApp(Root) const FooBar = { mounted: spy1 } app.directive('FooBar', FooBar) expect(app.directive('FooBar')).toBe(FooBar) app.directive('BarBaz', { mounted: spy2 }) app.directive('BarBaz', { mounted: spy2 }) expect( 'Directive "BarBaz" has already been registered in target app.' ).toHaveBeenWarnedTimes(1) const root = nodeOps.createElement('div') app.mount(root) expect(spy1).toHaveBeenCalled() expect(spy2).not.toHaveBeenCalled() expect(spy3).toHaveBeenCalled() app.directive('bind', FooBar) expect( `Do not use built-in directive ids as custom directive id: bind` ).toHaveBeenWarned() }) test('mixin', () => { const calls: string[] = [] const mixinA = { data() { return { a: 1 } }, created(this: any) { calls.push('mixinA created') expect(this.a).toBe(1) expect(this.b).toBe(2) expect(this.c).toBe(3) }, mounted() { calls.push('mixinA mounted') } } const mixinB = { name: 'mixinB', data() { return { b: 2 } }, created(this: any) { calls.push('mixinB created') expect(this.a).toBe(1) expect(this.b).toBe(2) expect(this.c).toBe(3) }, mounted() { calls.push('mixinB mounted') } } const Comp = { data() { return { c: 3 } }, created(this: any) { calls.push('comp created') expect(this.a).toBe(1) expect(this.b).toBe(2) expect(this.c).toBe(3) }, mounted() { calls.push('comp mounted') }, render(this: any) { return `${this.a}${this.b}${this.c}` } } const app = createApp(Comp) app.mixin(mixinA) app.mixin(mixinB) app.mixin(mixinA) app.mixin(mixinB) expect( 'Mixin has already been applied to target app' ).toHaveBeenWarnedTimes(2) expect( 'Mixin has already been applied to target app: mixinB' ).toHaveBeenWarnedTimes(1) const root = nodeOps.createElement('div') app.mount(root) expect(serializeInner(root)).toBe(`123`) expect(calls).toEqual([ 'mixinA created', 'mixinB created', 'comp created', 'mixinA mounted', 'mixinB mounted', 'comp mounted' ]) }) test('use', () => { const PluginA: Plugin = app => app.provide('foo', 1) const PluginB: Plugin = { install: (app, arg1, arg2) => app.provide('bar', arg1 + arg2) } class PluginC { someProperty = {} static install() { app.provide('baz', 2) } } const PluginD: any = undefined const Root = { setup() { const foo = inject('foo') const bar = inject('bar') return () => `${foo},${bar}` } } const app = createApp(Root) app.use(PluginA) app.use(PluginB, 1, 1) app.use(PluginC) const root = nodeOps.createElement('div') app.mount(root) expect(serializeInner(root)).toBe(`1,2`) app.use(PluginA) expect( `Plugin has already been applied to target app` ).toHaveBeenWarnedTimes(1) app.use(PluginD) expect( `A plugin must either be a function or an object with an "install" ` + `function.` ).toHaveBeenWarnedTimes(1) }) test('config.errorHandler', () => { const error = new Error() const count = ref(0) const handler = jest.fn((err, instance, info) => { expect(err).toBe(error) expect((instance as any).count).toBe(count.value) expect(info).toBe(`render function`) }) const Root = { setup() { const count = ref(0) return { count } }, render() { throw error } } const app = createApp(Root) app.config.errorHandler = handler app.mount(nodeOps.createElement('div')) expect(handler).toHaveBeenCalled() }) test('config.warnHandler', () => { let ctx: any const handler = jest.fn((msg, instance, trace) => { expect(msg).toMatch(`Component is missing template or render function`) expect(instance).toBe(ctx.proxy) expect(trace).toMatch(`Hello`) }) const Root = { name: 'Hello', setup() { ctx = getCurrentInstance() } } const app = createApp(Root) app.config.warnHandler = handler app.mount(nodeOps.createElement('div')) expect(handler).toHaveBeenCalledTimes(1) }) describe('config.isNativeTag', () => { const isNativeTag = jest.fn(tag => tag === 'div') test('Component.name', () => { const Root = { name: 'div', render() { return null } } const app = createApp(Root) Object.defineProperty(app.config, 'isNativeTag', { value: isNativeTag, writable: false }) app.mount(nodeOps.createElement('div')) expect( `Do not use built-in or reserved HTML elements as component id: div` ).toHaveBeenWarned() }) test('Component.components', () => { const Root = { components: { div: () => 'div' }, render() { return null } } const app = createApp(Root) Object.defineProperty(app.config, 'isNativeTag', { value: isNativeTag, writable: false }) app.mount(nodeOps.createElement('div')) expect( `Do not use built-in or reserved HTML elements as component id: div` ).toHaveBeenWarned() }) test('Component.directives', () => { const Root = { directives: { bind: () => {} }, render() { return null } } const app = createApp(Root) Object.defineProperty(app.config, 'isNativeTag', { value: isNativeTag, writable: false }) app.mount(nodeOps.createElement('div')) expect( `Do not use built-in directive ids as custom directive id: bind` ).toHaveBeenWarned() }) test('register using app.component', () => { const app = createApp({ render() {} }) Object.defineProperty(app.config, 'isNativeTag', { value: isNativeTag, writable: false }) app.component('div', () => 'div') app.mount(nodeOps.createElement('div')) expect( `Do not use built-in or reserved HTML elements as component id: div` ).toHaveBeenWarned() }) }) test('config.optionMergeStrategies', () => { let merged: string const App = defineComponent({ render() {}, mixins: [{ foo: 'mixin' }], extends: { foo: 'extends' }, foo: 'local', beforeCreate() { merged = this.$options.foo } }) const app = createApp(App) app.mixin({ foo: 'global' }) app.config.optionMergeStrategies.foo = (a, b) => (a ? `${a},` : ``) + b app.mount(nodeOps.createElement('div')) expect(merged!).toBe('global,extends,mixin,local') }) test('config.globalProperties', () => { const app = createApp({ render() { return this.foo } }) app.config.globalProperties.foo = 'hello' const root = nodeOps.createElement('div') app.mount(root) expect(serializeInner(root)).toBe('hello') }) })
packages/runtime-core/__tests__/apiCreateApp.spec.ts
0
https://github.com/vuejs/core/commit/313dd06065b1782d67f6881fbd42ae92a7f9cade
[ 0.0038812803104519844, 0.00027475281967781484, 0.00016307113401126117, 0.00017008735449053347, 0.0005406870623119175 ]
{ "id": 1, "code_window": [ " b: {\n", " from: 'a'\n", " }\n", " })\n", " const ChildD = defineChild({\n", " b: {\n", " from: 'c',\n", " default: 2\n", " }\n", " })\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const ChildD = defineChild(\n", " {\n", " a: {\n", " default: () => 0\n", " }\n", " },\n", " 'a'\n", " )\n", " const ChildE = defineChild({\n" ], "file_path": "packages/runtime-core/__tests__/apiOptions.spec.ts", "type": "replace", "edit_start_line_idx": 274 }
import { patchProp } from '../src/patchProp' import { xlinkNS } from '../src/modules/attrs' describe('runtime-dom: attrs patching', () => { test('xlink attributes', () => { const el = document.createElementNS('http://www.w3.org/2000/svg', 'use') patchProp(el, 'xlink:href', null, 'a', true) expect(el.getAttributeNS(xlinkNS, 'href')).toBe('a') patchProp(el, 'xlink:href', 'a', null, true) expect(el.getAttributeNS(xlinkNS, 'href')).toBe(null) }) test('boolean attributes', () => { const el = document.createElement('input') patchProp(el, 'readonly', null, true) expect(el.getAttribute('readonly')).toBe('') patchProp(el, 'readonly', true, false) expect(el.getAttribute('readonly')).toBe(null) }) test('attributes', () => { const el = document.createElement('div') patchProp(el, 'foo', null, 'a') expect(el.getAttribute('foo')).toBe('a') patchProp(el, 'foo', 'a', null) expect(el.getAttribute('foo')).toBe(null) }) // #949 test('onxxx but non-listener attributes', () => { const el = document.createElement('div') patchProp(el, 'onwards', null, 'a') expect(el.getAttribute('onwards')).toBe('a') patchProp(el, 'onwards', 'a', null) expect(el.getAttribute('onwards')).toBe(null) }) })
packages/runtime-dom/__tests__/patchAttrs.spec.ts
0
https://github.com/vuejs/core/commit/313dd06065b1782d67f6881fbd42ae92a7f9cade
[ 0.00017392233712598681, 0.00017005969129968435, 0.00016694811347406358, 0.00016968415002338588, 0.000002744027824519435 ]
{ "id": 2, "code_window": [ " default: 2\n", " }\n", " })\n", " const ChildE = defineChild({\n", " b: {\n", " from: 'c',\n", " default: () => 3\n", " }\n", " })\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const ChildF = defineChild({\n" ], "file_path": "packages/runtime-core/__tests__/apiOptions.spec.ts", "type": "replace", "edit_start_line_idx": 280 }
import { h, nodeOps, render, serializeInner, triggerEvent, TestElement, nextTick, renderToString, ref, defineComponent } from '@vue/runtime-test' describe('api: options', () => { test('data', async () => { const Comp = defineComponent({ data() { return { foo: 1 } }, render() { return h( 'div', { onClick: () => { this.foo++ } }, this.foo ) } }) const root = nodeOps.createElement('div') render(h(Comp), root) expect(serializeInner(root)).toBe(`<div>1</div>`) triggerEvent(root.children[0] as TestElement, 'click') await nextTick() expect(serializeInner(root)).toBe(`<div>2</div>`) }) test('computed', async () => { const Comp = defineComponent({ data() { return { foo: 1 } }, computed: { bar(): number { return this.foo + 1 }, baz: (vm): number => vm.bar + 1 }, render() { return h( 'div', { onClick: () => { this.foo++ } }, this.bar + this.baz ) } }) const root = nodeOps.createElement('div') render(h(Comp), root) expect(serializeInner(root)).toBe(`<div>5</div>`) triggerEvent(root.children[0] as TestElement, 'click') await nextTick() expect(serializeInner(root)).toBe(`<div>7</div>`) }) test('methods', async () => { const Comp = defineComponent({ data() { return { foo: 1 } }, methods: { inc() { this.foo++ } }, render() { return h( 'div', { onClick: this.inc }, this.foo ) } }) const root = nodeOps.createElement('div') render(h(Comp), root) expect(serializeInner(root)).toBe(`<div>1</div>`) triggerEvent(root.children[0] as TestElement, 'click') await nextTick() expect(serializeInner(root)).toBe(`<div>2</div>`) }) test('watch', async () => { function returnThis(this: any) { return this } const spyA = jest.fn(returnThis) const spyB = jest.fn(returnThis) const spyC = jest.fn(returnThis) const spyD = jest.fn(returnThis) let ctx: any const Comp = { data() { return { foo: 1, bar: 2, baz: { qux: 3 }, qux: 4 } }, watch: { // string method name foo: 'onFooChange', // direct function bar: spyB, baz: { handler: spyC, deep: true }, qux: { handler: 'onQuxChange' } }, methods: { onFooChange: spyA, onQuxChange: spyD }, render() { ctx = this } } const root = nodeOps.createElement('div') render(h(Comp), root) function assertCall(spy: jest.Mock, callIndex: number, args: any[]) { expect(spy.mock.calls[callIndex].slice(0, 2)).toMatchObject(args) expect(spy).toHaveReturnedWith(ctx) } ctx.foo++ await nextTick() expect(spyA).toHaveBeenCalledTimes(1) assertCall(spyA, 0, [2, 1]) ctx.bar++ await nextTick() expect(spyB).toHaveBeenCalledTimes(1) assertCall(spyB, 0, [3, 2]) ctx.baz.qux++ await nextTick() expect(spyC).toHaveBeenCalledTimes(1) // new and old objects have same identity assertCall(spyC, 0, [{ qux: 4 }, { qux: 4 }]) ctx.qux++ await nextTick() expect(spyD).toHaveBeenCalledTimes(1) assertCall(spyD, 0, [5, 4]) }) test('watch array', async () => { function returnThis(this: any) { return this } const spyA = jest.fn(returnThis) const spyB = jest.fn(returnThis) const spyC = jest.fn(returnThis) let ctx: any const Comp = { data() { return { foo: 1, bar: 2, baz: { qux: 3 } } }, watch: { // string method name foo: ['onFooChange'], // direct function bar: [spyB], baz: [ { handler: spyC, deep: true } ] }, methods: { onFooChange: spyA }, render() { ctx = this } } const root = nodeOps.createElement('div') render(h(Comp), root) function assertCall(spy: jest.Mock, callIndex: number, args: any[]) { expect(spy.mock.calls[callIndex].slice(0, 2)).toMatchObject(args) expect(spy).toHaveReturnedWith(ctx) } ctx.foo++ await nextTick() expect(spyA).toHaveBeenCalledTimes(1) assertCall(spyA, 0, [2, 1]) ctx.bar++ await nextTick() expect(spyB).toHaveBeenCalledTimes(1) assertCall(spyB, 0, [3, 2]) ctx.baz.qux++ await nextTick() expect(spyC).toHaveBeenCalledTimes(1) // new and old objects have same identity assertCall(spyC, 0, [{ qux: 4 }, { qux: 4 }]) }) test('provide/inject', () => { const Root = defineComponent({ data() { return { a: 1 } }, provide() { return { a: this.a } }, render() { return [h(ChildA), h(ChildB), h(ChildC), h(ChildD), h(ChildE)] } }) const defineChild = (injectOptions: any, injectedKey = 'b') => ({ inject: injectOptions, render() { return this[injectedKey] } } as any) const ChildA = defineChild(['a'], 'a') const ChildB = defineChild({ b: 'a' }) const ChildC = defineChild({ b: { from: 'a' } }) const ChildD = defineChild({ b: { from: 'c', default: 2 } }) const ChildE = defineChild({ b: { from: 'c', default: () => 3 } }) expect(renderToString(h(Root))).toBe(`11123`) }) test('lifecycle', async () => { const count = ref(0) const root = nodeOps.createElement('div') const calls: string[] = [] const Root = { beforeCreate() { calls.push('root beforeCreate') }, created() { calls.push('root created') }, beforeMount() { calls.push('root onBeforeMount') }, mounted() { calls.push('root onMounted') }, beforeUpdate() { calls.push('root onBeforeUpdate') }, updated() { calls.push('root onUpdated') }, beforeUnmount() { calls.push('root onBeforeUnmount') }, unmounted() { calls.push('root onUnmounted') }, render() { return h(Mid, { count: count.value }) } } const Mid = { beforeCreate() { calls.push('mid beforeCreate') }, created() { calls.push('mid created') }, beforeMount() { calls.push('mid onBeforeMount') }, mounted() { calls.push('mid onMounted') }, beforeUpdate() { calls.push('mid onBeforeUpdate') }, updated() { calls.push('mid onUpdated') }, beforeUnmount() { calls.push('mid onBeforeUnmount') }, unmounted() { calls.push('mid onUnmounted') }, render(this: any) { return h(Child, { count: this.$props.count }) } } const Child = { beforeCreate() { calls.push('child beforeCreate') }, created() { calls.push('child created') }, beforeMount() { calls.push('child onBeforeMount') }, mounted() { calls.push('child onMounted') }, beforeUpdate() { calls.push('child onBeforeUpdate') }, updated() { calls.push('child onUpdated') }, beforeUnmount() { calls.push('child onBeforeUnmount') }, unmounted() { calls.push('child onUnmounted') }, render(this: any) { return h('div', this.$props.count) } } // mount render(h(Root), root) expect(calls).toEqual([ 'root beforeCreate', 'root created', 'root onBeforeMount', 'mid beforeCreate', 'mid created', 'mid onBeforeMount', 'child beforeCreate', 'child created', 'child onBeforeMount', 'child onMounted', 'mid onMounted', 'root onMounted' ]) calls.length = 0 // update count.value++ await nextTick() expect(calls).toEqual([ 'root onBeforeUpdate', 'mid onBeforeUpdate', 'child onBeforeUpdate', 'child onUpdated', 'mid onUpdated', 'root onUpdated' ]) calls.length = 0 // unmount render(null, root) expect(calls).toEqual([ 'root onBeforeUnmount', 'mid onBeforeUnmount', 'child onBeforeUnmount', 'child onUnmounted', 'mid onUnmounted', 'root onUnmounted' ]) }) test('mixins', () => { const calls: string[] = [] const mixinA = { data() { return { a: 1 } }, created(this: any) { calls.push('mixinA created') expect(this.a).toBe(1) expect(this.b).toBe(2) expect(this.c).toBe(4) }, mounted() { calls.push('mixinA mounted') } } const mixinB = { props: { bP: { type: String } }, data() { return { b: 2 } }, created(this: any) { calls.push('mixinB created') expect(this.a).toBe(1) expect(this.b).toBe(2) expect(this.bP).toBeUndefined() expect(this.c).toBe(4) expect(this.cP1).toBeUndefined() }, mounted() { calls.push('mixinB mounted') } } const mixinC = defineComponent({ props: ['cP1', 'cP2'], data() { return { c: 3 } }, created() { calls.push('mixinC created') // component data() should overwrite mixin field with same key expect(this.c).toBe(4) expect(this.cP1).toBeUndefined() }, mounted() { calls.push('mixinC mounted') } }) const Comp = defineComponent({ props: { aaa: String }, mixins: [defineComponent(mixinA), defineComponent(mixinB), mixinC], data() { return { c: 4, z: 4 } }, created() { calls.push('comp created') expect(this.a).toBe(1) expect(this.b).toBe(2) expect(this.bP).toBeUndefined() expect(this.c).toBe(4) expect(this.cP2).toBeUndefined() expect(this.z).toBe(4) }, mounted() { calls.push('comp mounted') }, render() { return `${this.a}${this.b}${this.c}` } }) expect(renderToString(h(Comp))).toBe(`124`) expect(calls).toEqual([ 'mixinA created', 'mixinB created', 'mixinC created', 'comp created', 'mixinA mounted', 'mixinB mounted', 'mixinC mounted', 'comp mounted' ]) }) test('render from mixin', () => { const Comp = { mixins: [ { render: () => 'from mixin' } ] } expect(renderToString(h(Comp))).toBe('from mixin') }) test('extends', () => { const calls: string[] = [] const Base = { data() { return { a: 1, b: 1 } }, methods: { sayA() {} }, mounted(this: any) { expect(this.a).toBe(1) expect(this.b).toBe(2) calls.push('base') } } const Comp = defineComponent({ extends: defineComponent(Base), data() { return { b: 2 } }, mounted() { calls.push('comp') }, render() { return `${this.a}${this.b}` } }) expect(renderToString(h(Comp))).toBe(`12`) expect(calls).toEqual(['base', 'comp']) }) test('extends with mixins', () => { const calls: string[] = [] const Base = { data() { return { a: 1, x: 'base' } }, methods: { sayA() {} }, mounted(this: any) { expect(this.a).toBe(1) expect(this.b).toBeTruthy() expect(this.c).toBe(2) calls.push('base') } } const Mixin = { data() { return { b: true, x: 'mixin' } }, mounted(this: any) { expect(this.a).toBe(1) expect(this.b).toBeTruthy() expect(this.c).toBe(2) calls.push('mixin') } } const Comp = defineComponent({ extends: defineComponent(Base), mixins: [defineComponent(Mixin)], data() { return { c: 2 } }, mounted() { calls.push('comp') }, render() { return `${this.a}${this.b}${this.c}${this.x}` } }) expect(renderToString(h(Comp))).toBe(`1true2mixin`) expect(calls).toEqual(['base', 'mixin', 'comp']) }) test('beforeCreate/created in extends and mixins', () => { const calls: string[] = [] const BaseA = { beforeCreate() { calls.push('beforeCreateA') }, created() { calls.push('createdA') } } const BaseB = { extends: BaseA, beforeCreate() { calls.push('beforeCreateB') }, created() { calls.push('createdB') } } const MixinA = { beforeCreate() { calls.push('beforeCreateC') }, created() { calls.push('createdC') } } const MixinB = { mixins: [MixinA], beforeCreate() { calls.push('beforeCreateD') }, created() { calls.push('createdD') } } const Comp = { extends: BaseB, mixins: [MixinB], beforeCreate() { calls.push('selfBeforeCreate') }, created() { calls.push('selfCreated') }, render() {} } renderToString(h(Comp)) expect(calls).toEqual([ 'beforeCreateA', 'beforeCreateB', 'beforeCreateC', 'beforeCreateD', 'selfBeforeCreate', 'createdA', 'createdB', 'createdC', 'createdD', 'selfCreated' ]) }) test('flatten merged options', async () => { const MixinBase = { msg1: 'base' } const ExtendsBase = { msg2: 'base' } const Mixin = { mixins: [MixinBase] } const Extends = { extends: ExtendsBase } const Comp = defineComponent({ extends: defineComponent(Extends), mixins: [defineComponent(Mixin)], render() { return `${this.$options.msg1},${this.$options.msg2}` } }) expect(renderToString(h(Comp))).toBe('base,base') }) test('options defined in component have higher priority', async () => { const Mixin = { msg1: 'base' } const Extends = { msg2: 'base' } const Comp = defineComponent({ msg1: 'local', msg2: 'local', extends: defineComponent(Extends), mixins: [defineComponent(Mixin)], render() { return `${this.$options.msg1},${this.$options.msg2}` } }) expect(renderToString(h(Comp))).toBe('local,local') }) test('accessing setup() state from options', async () => { const Comp = defineComponent({ setup() { return { count: ref(0) } }, data() { return { plusOne: (this as any).count + 1 } }, computed: { plusTwo(): number { return this.count + 2 } }, methods: { inc() { this.count++ } }, render() { return h( 'div', { onClick: this.inc }, `${this.count},${this.plusOne},${this.plusTwo}` ) } }) const root = nodeOps.createElement('div') render(h(Comp), root) expect(serializeInner(root)).toBe(`<div>0,1,2</div>`) triggerEvent(root.children[0] as TestElement, 'click') await nextTick() expect(serializeInner(root)).toBe(`<div>1,1,3</div>`) }) // #1016 test('watcher initialization should be deferred in mixins', async () => { const mixin1 = { data() { return { mixin1Data: 'mixin1' } }, methods: {} } const watchSpy = jest.fn() const mixin2 = { watch: { mixin3Data: watchSpy } } const mixin3 = { data() { return { mixin3Data: 'mixin3' } }, methods: {} } let vm: any const Comp = { mixins: [mixin1, mixin2, mixin3], render() {}, created() { vm = this } } const root = nodeOps.createElement('div') render(h(Comp), root) // should have no warnings vm.mixin3Data = 'hello' await nextTick() expect(watchSpy.mock.calls[0].slice(0, 2)).toEqual(['hello', 'mixin3']) }) describe('warnings', () => { test('Expected a function as watch handler', () => { const Comp = { watch: { foo: 'notExistingMethod', foo2: { handler: 'notExistingMethod2' } }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( 'Invalid watch handler specified by key "notExistingMethod"' ).toHaveBeenWarned() expect( 'Invalid watch handler specified by key "notExistingMethod2"' ).toHaveBeenWarned() }) test('Invalid watch option', () => { const Comp = { watch: { foo: true }, render() {} } const root = nodeOps.createElement('div') // @ts-ignore render(h(Comp), root) expect('Invalid watch option: "foo"').toHaveBeenWarned() }) test('computed with setter and no getter', () => { const Comp = { computed: { foo: { set() {} } }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect('Computed property "foo" has no getter.').toHaveBeenWarned() }) test('assigning to computed with no setter', () => { let instance: any const Comp = { computed: { foo: { get() {} } }, mounted() { instance = this }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) instance.foo = 1 expect( 'Write operation failed: computed property "foo" is readonly' ).toHaveBeenWarned() }) test('inject property is already declared in props', () => { const Comp = { data() { return { a: 1 } }, provide() { return { a: this.a } }, render() { return [h(ChildA)] } } as any const ChildA = { props: { a: Number }, inject: ['a'], render() { return this.a } } as any const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Inject property "a" is already defined in Props.` ).toHaveBeenWarned() }) test('methods property is not a function', () => { const Comp = { methods: { foo: 1 }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Method "foo" has type "number" in the component definition. ` + `Did you reference the function correctly?` ).toHaveBeenWarned() }) test('methods property is already declared in props', () => { const Comp = { props: { foo: Number }, methods: { foo() {} }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Methods property "foo" is already defined in Props.` ).toHaveBeenWarned() }) test('methods property is already declared in inject', () => { const Comp = { data() { return { a: 1 } }, provide() { return { a: this.a } }, render() { return [h(ChildA)] } } as any const ChildA = { methods: { a: () => null }, inject: ['a'], render() { return this.a } } as any const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Methods property "a" is already defined in Inject.` ).toHaveBeenWarned() }) test('data property is already declared in props', () => { const Comp = { props: { foo: Number }, data: () => ({ foo: 1 }), render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Data property "foo" is already defined in Props.` ).toHaveBeenWarned() }) test('data property is already declared in inject', () => { const Comp = { data() { return { a: 1 } }, provide() { return { a: this.a } }, render() { return [h(ChildA)] } } as any const ChildA = { data() { return { a: 1 } }, inject: ['a'], render() { return this.a } } as any const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Data property "a" is already defined in Inject.` ).toHaveBeenWarned() }) test('data property is already declared in methods', () => { const Comp = { data: () => ({ foo: 1 }), methods: { foo() {} }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Data property "foo" is already defined in Methods.` ).toHaveBeenWarned() }) test('computed property is already declared in props', () => { const Comp = { props: { foo: Number }, computed: { foo() {} }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Computed property "foo" is already defined in Props.` ).toHaveBeenWarned() }) test('computed property is already declared in inject', () => { const Comp = { data() { return { a: 1 } }, provide() { return { a: this.a } }, render() { return [h(ChildA)] } } as any const ChildA = { computed: { a: { get() {}, set() {} } }, inject: ['a'], render() { return this.a } } as any const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Computed property "a" is already defined in Inject.` ).toHaveBeenWarned() }) test('computed property is already declared in methods', () => { const Comp = { computed: { foo() {} }, methods: { foo() {} }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Computed property "foo" is already defined in Methods.` ).toHaveBeenWarned() }) test('computed property is already declared in data', () => { const Comp = { data: () => ({ foo: 1 }), computed: { foo() {} }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Computed property "foo" is already defined in Data.` ).toHaveBeenWarned() }) }) })
packages/runtime-core/__tests__/apiOptions.spec.ts
1
https://github.com/vuejs/core/commit/313dd06065b1782d67f6881fbd42ae92a7f9cade
[ 0.9982483386993408, 0.018359024077653885, 0.0001639167167013511, 0.00017014140030369163, 0.1292688101530075 ]
{ "id": 2, "code_window": [ " default: 2\n", " }\n", " })\n", " const ChildE = defineChild({\n", " b: {\n", " from: 'c',\n", " default: () => 3\n", " }\n", " })\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const ChildF = defineChild({\n" ], "file_path": "packages/runtime-core/__tests__/apiOptions.spec.ts", "type": "replace", "edit_start_line_idx": 280 }
import { SourceLocation, CompilerError, createCompilerError, ErrorCodes } from '@vue/compiler-core' export interface DOMCompilerError extends CompilerError { code: DOMErrorCodes } export function createDOMCompilerError( code: DOMErrorCodes, loc?: SourceLocation ): DOMCompilerError { return createCompilerError( code, loc, __DEV__ || !__BROWSER__ ? DOMErrorMessages : undefined ) } export const enum DOMErrorCodes { X_V_HTML_NO_EXPRESSION = ErrorCodes.__EXTEND_POINT__, X_V_HTML_WITH_CHILDREN, X_V_TEXT_NO_EXPRESSION, X_V_TEXT_WITH_CHILDREN, X_V_MODEL_ON_INVALID_ELEMENT, X_V_MODEL_ARG_ON_ELEMENT, X_V_MODEL_ON_FILE_INPUT_ELEMENT, X_V_MODEL_UNNECESSARY_VALUE, X_V_SHOW_NO_EXPRESSION, X_TRANSITION_INVALID_CHILDREN, X_IGNORED_SIDE_EFFECT_TAG, __EXTEND_POINT__ } export const DOMErrorMessages: { [code: number]: string } = { [DOMErrorCodes.X_V_HTML_NO_EXPRESSION]: `v-html is missing expression.`, [DOMErrorCodes.X_V_HTML_WITH_CHILDREN]: `v-html will override element children.`, [DOMErrorCodes.X_V_TEXT_NO_EXPRESSION]: `v-text is missing expression.`, [DOMErrorCodes.X_V_TEXT_WITH_CHILDREN]: `v-text will override element children.`, [DOMErrorCodes.X_V_MODEL_ON_INVALID_ELEMENT]: `v-model can only be used on <input>, <textarea> and <select> elements.`, [DOMErrorCodes.X_V_MODEL_ARG_ON_ELEMENT]: `v-model argument is not supported on plain elements.`, [DOMErrorCodes.X_V_MODEL_ON_FILE_INPUT_ELEMENT]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`, [DOMErrorCodes.X_V_MODEL_UNNECESSARY_VALUE]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`, [DOMErrorCodes.X_V_SHOW_NO_EXPRESSION]: `v-show is missing expression.`, [DOMErrorCodes.X_TRANSITION_INVALID_CHILDREN]: `<Transition> expects exactly one child element or component.`, [DOMErrorCodes.X_IGNORED_SIDE_EFFECT_TAG]: `Tags with side effect (<script> and <style>) are ignored in client component templates.` }
packages/compiler-dom/src/errors.ts
0
https://github.com/vuejs/core/commit/313dd06065b1782d67f6881fbd42ae92a7f9cade
[ 0.0017737867310643196, 0.0006784419529139996, 0.000169668099260889, 0.0004495545581448823, 0.0005852176109328866 ]
{ "id": 2, "code_window": [ " default: 2\n", " }\n", " })\n", " const ChildE = defineChild({\n", " b: {\n", " from: 'c',\n", " default: () => 3\n", " }\n", " })\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const ChildF = defineChild({\n" ], "file_path": "packages/runtime-core/__tests__/apiOptions.spec.ts", "type": "replace", "edit_start_line_idx": 280 }
const fs = require('fs') const chalk = require('chalk') const targets = (exports.targets = fs.readdirSync('packages').filter(f => { if (!fs.statSync(`packages/${f}`).isDirectory()) { return false } const pkg = require(`../packages/${f}/package.json`) if (pkg.private && !pkg.buildOptions) { return false } return true })) exports.fuzzyMatchTarget = (partialTargets, includeAllMatching) => { const matched = [] partialTargets.forEach(partialTarget => { for (const target of targets) { if (target.match(partialTarget)) { matched.push(target) if (!includeAllMatching) { break } } } }) if (matched.length) { return matched } else { console.log() console.error( ` ${chalk.bgRed.white(' ERROR ')} ${chalk.red( `Target ${chalk.underline(partialTargets)} not found!` )}` ) console.log() process.exit(1) } }
scripts/utils.js
0
https://github.com/vuejs/core/commit/313dd06065b1782d67f6881fbd42ae92a7f9cade
[ 0.0001748203212628141, 0.0001709852513158694, 0.00016438910097349435, 0.00017374496383126825, 0.000004157532657700358 ]
{ "id": 2, "code_window": [ " default: 2\n", " }\n", " })\n", " const ChildE = defineChild({\n", " b: {\n", " from: 'c',\n", " default: () => 3\n", " }\n", " })\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const ChildF = defineChild({\n" ], "file_path": "packages/runtime-core/__tests__/apiOptions.spec.ts", "type": "replace", "edit_start_line_idx": 280 }
import { isArray } from '@vue/shared' import { ComponentInternalInstance, callWithAsyncErrorHandling } from '@vue/runtime-core' import { ErrorCodes } from 'packages/runtime-core/src/errorHandling' interface Invoker extends EventListener { value: EventValue attached: number } type EventValue = Function | Function[] // Async edge case fix requires storing an event listener's attach timestamp. let _getNow: () => number = Date.now // Determine what event timestamp the browser is using. Annoyingly, the // timestamp can either be hi-res (relative to page load) or low-res // (relative to UNIX epoch), so in order to compare time we have to use the // same timestamp type when saving the flush timestamp. if ( typeof document !== 'undefined' && _getNow() > document.createEvent('Event').timeStamp ) { // if the low-res timestamp which is bigger than the event timestamp // (which is evaluated AFTER) it means the event is using a hi-res timestamp, // and we need to use the hi-res version for event listeners as well. _getNow = () => performance.now() } // To avoid the overhead of repeatedly calling performance.now(), we cache // and use the same timestamp for all event listeners attached in the same tick. let cachedNow: number = 0 const p = Promise.resolve() const reset = () => { cachedNow = 0 } const getNow = () => cachedNow || (p.then(reset), (cachedNow = _getNow())) export function addEventListener( el: Element, event: string, handler: EventListener, options?: EventListenerOptions ) { el.addEventListener(event, handler, options) } export function removeEventListener( el: Element, event: string, handler: EventListener, options?: EventListenerOptions ) { el.removeEventListener(event, handler, options) } export function patchEvent( el: Element & { _vei?: Record<string, Invoker | undefined> }, rawName: string, prevValue: EventValue | null, nextValue: EventValue | null, instance: ComponentInternalInstance | null = null ) { // vei = vue event invokers const invokers = el._vei || (el._vei = {}) const existingInvoker = invokers[rawName] if (nextValue && existingInvoker) { // patch existingInvoker.value = nextValue } else { const [name, options] = parseName(rawName) if (nextValue) { // add const invoker = (invokers[rawName] = createInvoker(nextValue, instance)) addEventListener(el, name, invoker, options) } else if (existingInvoker) { // remove removeEventListener(el, name, existingInvoker, options) invokers[rawName] = undefined } } } const optionsModifierRE = /(?:Once|Passive|Capture)$/ function parseName(name: string): [string, EventListenerOptions | undefined] { let options: EventListenerOptions | undefined if (optionsModifierRE.test(name)) { options = {} let m while ((m = name.match(optionsModifierRE))) { name = name.slice(0, name.length - m[0].length) ;(options as any)[m[0].toLowerCase()] = true options } } return [name.slice(2).toLowerCase(), options] } function createInvoker( initialValue: EventValue, instance: ComponentInternalInstance | null ) { const invoker: Invoker = (e: Event) => { // async edge case #6566: inner click event triggers patch, event handler // attached to outer element during patch, and triggered again. This // happens because browsers fire microtask ticks between event propagation. // the solution is simple: we save the timestamp when a handler is attached, // and the handler would only fire if the event passed to it was fired // AFTER it was attached. const timeStamp = e.timeStamp || _getNow() if (timeStamp >= invoker.attached - 1) { callWithAsyncErrorHandling( patchStopImmediatePropagation(e, invoker.value), instance, ErrorCodes.NATIVE_EVENT_HANDLER, [e] ) } } invoker.value = initialValue invoker.attached = getNow() return invoker } function patchStopImmediatePropagation( e: Event, value: EventValue ): EventValue { if (isArray(value)) { const originalStop = e.stopImmediatePropagation e.stopImmediatePropagation = () => { originalStop.call(e) ;(e as any)._stopped = true } return value.map(fn => (e: Event) => !(e as any)._stopped && fn(e)) } else { return value } }
packages/runtime-dom/src/modules/events.ts
0
https://github.com/vuejs/core/commit/313dd06065b1782d67f6881fbd42ae92a7f9cade
[ 0.00023383463849313557, 0.00017455390479881316, 0.00016525143291801214, 0.0001715654943836853, 0.00001610883919056505 ]
{ "id": 3, "code_window": [ " from: 'c',\n", " default: () => 3\n", " }\n", " })\n", " expect(renderToString(h(Root))).toBe(`11123`)\n", " })\n", "\n", " test('lifecycle', async () => {\n", " const count = ref(0)\n", " const root = nodeOps.createElement('div')\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const ChildG = defineChild({\n", " b: {\n", " default: 4\n", " }\n", " })\n", " const ChildH = defineChild({\n", " b: {\n", " default: () => 5\n", " }\n", " })\n", " expect(renderToString(h(Root))).toBe(`11112345`)\n" ], "file_path": "packages/runtime-core/__tests__/apiOptions.spec.ts", "type": "replace", "edit_start_line_idx": 286 }
import { h, nodeOps, render, serializeInner, triggerEvent, TestElement, nextTick, renderToString, ref, defineComponent } from '@vue/runtime-test' describe('api: options', () => { test('data', async () => { const Comp = defineComponent({ data() { return { foo: 1 } }, render() { return h( 'div', { onClick: () => { this.foo++ } }, this.foo ) } }) const root = nodeOps.createElement('div') render(h(Comp), root) expect(serializeInner(root)).toBe(`<div>1</div>`) triggerEvent(root.children[0] as TestElement, 'click') await nextTick() expect(serializeInner(root)).toBe(`<div>2</div>`) }) test('computed', async () => { const Comp = defineComponent({ data() { return { foo: 1 } }, computed: { bar(): number { return this.foo + 1 }, baz: (vm): number => vm.bar + 1 }, render() { return h( 'div', { onClick: () => { this.foo++ } }, this.bar + this.baz ) } }) const root = nodeOps.createElement('div') render(h(Comp), root) expect(serializeInner(root)).toBe(`<div>5</div>`) triggerEvent(root.children[0] as TestElement, 'click') await nextTick() expect(serializeInner(root)).toBe(`<div>7</div>`) }) test('methods', async () => { const Comp = defineComponent({ data() { return { foo: 1 } }, methods: { inc() { this.foo++ } }, render() { return h( 'div', { onClick: this.inc }, this.foo ) } }) const root = nodeOps.createElement('div') render(h(Comp), root) expect(serializeInner(root)).toBe(`<div>1</div>`) triggerEvent(root.children[0] as TestElement, 'click') await nextTick() expect(serializeInner(root)).toBe(`<div>2</div>`) }) test('watch', async () => { function returnThis(this: any) { return this } const spyA = jest.fn(returnThis) const spyB = jest.fn(returnThis) const spyC = jest.fn(returnThis) const spyD = jest.fn(returnThis) let ctx: any const Comp = { data() { return { foo: 1, bar: 2, baz: { qux: 3 }, qux: 4 } }, watch: { // string method name foo: 'onFooChange', // direct function bar: spyB, baz: { handler: spyC, deep: true }, qux: { handler: 'onQuxChange' } }, methods: { onFooChange: spyA, onQuxChange: spyD }, render() { ctx = this } } const root = nodeOps.createElement('div') render(h(Comp), root) function assertCall(spy: jest.Mock, callIndex: number, args: any[]) { expect(spy.mock.calls[callIndex].slice(0, 2)).toMatchObject(args) expect(spy).toHaveReturnedWith(ctx) } ctx.foo++ await nextTick() expect(spyA).toHaveBeenCalledTimes(1) assertCall(spyA, 0, [2, 1]) ctx.bar++ await nextTick() expect(spyB).toHaveBeenCalledTimes(1) assertCall(spyB, 0, [3, 2]) ctx.baz.qux++ await nextTick() expect(spyC).toHaveBeenCalledTimes(1) // new and old objects have same identity assertCall(spyC, 0, [{ qux: 4 }, { qux: 4 }]) ctx.qux++ await nextTick() expect(spyD).toHaveBeenCalledTimes(1) assertCall(spyD, 0, [5, 4]) }) test('watch array', async () => { function returnThis(this: any) { return this } const spyA = jest.fn(returnThis) const spyB = jest.fn(returnThis) const spyC = jest.fn(returnThis) let ctx: any const Comp = { data() { return { foo: 1, bar: 2, baz: { qux: 3 } } }, watch: { // string method name foo: ['onFooChange'], // direct function bar: [spyB], baz: [ { handler: spyC, deep: true } ] }, methods: { onFooChange: spyA }, render() { ctx = this } } const root = nodeOps.createElement('div') render(h(Comp), root) function assertCall(spy: jest.Mock, callIndex: number, args: any[]) { expect(spy.mock.calls[callIndex].slice(0, 2)).toMatchObject(args) expect(spy).toHaveReturnedWith(ctx) } ctx.foo++ await nextTick() expect(spyA).toHaveBeenCalledTimes(1) assertCall(spyA, 0, [2, 1]) ctx.bar++ await nextTick() expect(spyB).toHaveBeenCalledTimes(1) assertCall(spyB, 0, [3, 2]) ctx.baz.qux++ await nextTick() expect(spyC).toHaveBeenCalledTimes(1) // new and old objects have same identity assertCall(spyC, 0, [{ qux: 4 }, { qux: 4 }]) }) test('provide/inject', () => { const Root = defineComponent({ data() { return { a: 1 } }, provide() { return { a: this.a } }, render() { return [h(ChildA), h(ChildB), h(ChildC), h(ChildD), h(ChildE)] } }) const defineChild = (injectOptions: any, injectedKey = 'b') => ({ inject: injectOptions, render() { return this[injectedKey] } } as any) const ChildA = defineChild(['a'], 'a') const ChildB = defineChild({ b: 'a' }) const ChildC = defineChild({ b: { from: 'a' } }) const ChildD = defineChild({ b: { from: 'c', default: 2 } }) const ChildE = defineChild({ b: { from: 'c', default: () => 3 } }) expect(renderToString(h(Root))).toBe(`11123`) }) test('lifecycle', async () => { const count = ref(0) const root = nodeOps.createElement('div') const calls: string[] = [] const Root = { beforeCreate() { calls.push('root beforeCreate') }, created() { calls.push('root created') }, beforeMount() { calls.push('root onBeforeMount') }, mounted() { calls.push('root onMounted') }, beforeUpdate() { calls.push('root onBeforeUpdate') }, updated() { calls.push('root onUpdated') }, beforeUnmount() { calls.push('root onBeforeUnmount') }, unmounted() { calls.push('root onUnmounted') }, render() { return h(Mid, { count: count.value }) } } const Mid = { beforeCreate() { calls.push('mid beforeCreate') }, created() { calls.push('mid created') }, beforeMount() { calls.push('mid onBeforeMount') }, mounted() { calls.push('mid onMounted') }, beforeUpdate() { calls.push('mid onBeforeUpdate') }, updated() { calls.push('mid onUpdated') }, beforeUnmount() { calls.push('mid onBeforeUnmount') }, unmounted() { calls.push('mid onUnmounted') }, render(this: any) { return h(Child, { count: this.$props.count }) } } const Child = { beforeCreate() { calls.push('child beforeCreate') }, created() { calls.push('child created') }, beforeMount() { calls.push('child onBeforeMount') }, mounted() { calls.push('child onMounted') }, beforeUpdate() { calls.push('child onBeforeUpdate') }, updated() { calls.push('child onUpdated') }, beforeUnmount() { calls.push('child onBeforeUnmount') }, unmounted() { calls.push('child onUnmounted') }, render(this: any) { return h('div', this.$props.count) } } // mount render(h(Root), root) expect(calls).toEqual([ 'root beforeCreate', 'root created', 'root onBeforeMount', 'mid beforeCreate', 'mid created', 'mid onBeforeMount', 'child beforeCreate', 'child created', 'child onBeforeMount', 'child onMounted', 'mid onMounted', 'root onMounted' ]) calls.length = 0 // update count.value++ await nextTick() expect(calls).toEqual([ 'root onBeforeUpdate', 'mid onBeforeUpdate', 'child onBeforeUpdate', 'child onUpdated', 'mid onUpdated', 'root onUpdated' ]) calls.length = 0 // unmount render(null, root) expect(calls).toEqual([ 'root onBeforeUnmount', 'mid onBeforeUnmount', 'child onBeforeUnmount', 'child onUnmounted', 'mid onUnmounted', 'root onUnmounted' ]) }) test('mixins', () => { const calls: string[] = [] const mixinA = { data() { return { a: 1 } }, created(this: any) { calls.push('mixinA created') expect(this.a).toBe(1) expect(this.b).toBe(2) expect(this.c).toBe(4) }, mounted() { calls.push('mixinA mounted') } } const mixinB = { props: { bP: { type: String } }, data() { return { b: 2 } }, created(this: any) { calls.push('mixinB created') expect(this.a).toBe(1) expect(this.b).toBe(2) expect(this.bP).toBeUndefined() expect(this.c).toBe(4) expect(this.cP1).toBeUndefined() }, mounted() { calls.push('mixinB mounted') } } const mixinC = defineComponent({ props: ['cP1', 'cP2'], data() { return { c: 3 } }, created() { calls.push('mixinC created') // component data() should overwrite mixin field with same key expect(this.c).toBe(4) expect(this.cP1).toBeUndefined() }, mounted() { calls.push('mixinC mounted') } }) const Comp = defineComponent({ props: { aaa: String }, mixins: [defineComponent(mixinA), defineComponent(mixinB), mixinC], data() { return { c: 4, z: 4 } }, created() { calls.push('comp created') expect(this.a).toBe(1) expect(this.b).toBe(2) expect(this.bP).toBeUndefined() expect(this.c).toBe(4) expect(this.cP2).toBeUndefined() expect(this.z).toBe(4) }, mounted() { calls.push('comp mounted') }, render() { return `${this.a}${this.b}${this.c}` } }) expect(renderToString(h(Comp))).toBe(`124`) expect(calls).toEqual([ 'mixinA created', 'mixinB created', 'mixinC created', 'comp created', 'mixinA mounted', 'mixinB mounted', 'mixinC mounted', 'comp mounted' ]) }) test('render from mixin', () => { const Comp = { mixins: [ { render: () => 'from mixin' } ] } expect(renderToString(h(Comp))).toBe('from mixin') }) test('extends', () => { const calls: string[] = [] const Base = { data() { return { a: 1, b: 1 } }, methods: { sayA() {} }, mounted(this: any) { expect(this.a).toBe(1) expect(this.b).toBe(2) calls.push('base') } } const Comp = defineComponent({ extends: defineComponent(Base), data() { return { b: 2 } }, mounted() { calls.push('comp') }, render() { return `${this.a}${this.b}` } }) expect(renderToString(h(Comp))).toBe(`12`) expect(calls).toEqual(['base', 'comp']) }) test('extends with mixins', () => { const calls: string[] = [] const Base = { data() { return { a: 1, x: 'base' } }, methods: { sayA() {} }, mounted(this: any) { expect(this.a).toBe(1) expect(this.b).toBeTruthy() expect(this.c).toBe(2) calls.push('base') } } const Mixin = { data() { return { b: true, x: 'mixin' } }, mounted(this: any) { expect(this.a).toBe(1) expect(this.b).toBeTruthy() expect(this.c).toBe(2) calls.push('mixin') } } const Comp = defineComponent({ extends: defineComponent(Base), mixins: [defineComponent(Mixin)], data() { return { c: 2 } }, mounted() { calls.push('comp') }, render() { return `${this.a}${this.b}${this.c}${this.x}` } }) expect(renderToString(h(Comp))).toBe(`1true2mixin`) expect(calls).toEqual(['base', 'mixin', 'comp']) }) test('beforeCreate/created in extends and mixins', () => { const calls: string[] = [] const BaseA = { beforeCreate() { calls.push('beforeCreateA') }, created() { calls.push('createdA') } } const BaseB = { extends: BaseA, beforeCreate() { calls.push('beforeCreateB') }, created() { calls.push('createdB') } } const MixinA = { beforeCreate() { calls.push('beforeCreateC') }, created() { calls.push('createdC') } } const MixinB = { mixins: [MixinA], beforeCreate() { calls.push('beforeCreateD') }, created() { calls.push('createdD') } } const Comp = { extends: BaseB, mixins: [MixinB], beforeCreate() { calls.push('selfBeforeCreate') }, created() { calls.push('selfCreated') }, render() {} } renderToString(h(Comp)) expect(calls).toEqual([ 'beforeCreateA', 'beforeCreateB', 'beforeCreateC', 'beforeCreateD', 'selfBeforeCreate', 'createdA', 'createdB', 'createdC', 'createdD', 'selfCreated' ]) }) test('flatten merged options', async () => { const MixinBase = { msg1: 'base' } const ExtendsBase = { msg2: 'base' } const Mixin = { mixins: [MixinBase] } const Extends = { extends: ExtendsBase } const Comp = defineComponent({ extends: defineComponent(Extends), mixins: [defineComponent(Mixin)], render() { return `${this.$options.msg1},${this.$options.msg2}` } }) expect(renderToString(h(Comp))).toBe('base,base') }) test('options defined in component have higher priority', async () => { const Mixin = { msg1: 'base' } const Extends = { msg2: 'base' } const Comp = defineComponent({ msg1: 'local', msg2: 'local', extends: defineComponent(Extends), mixins: [defineComponent(Mixin)], render() { return `${this.$options.msg1},${this.$options.msg2}` } }) expect(renderToString(h(Comp))).toBe('local,local') }) test('accessing setup() state from options', async () => { const Comp = defineComponent({ setup() { return { count: ref(0) } }, data() { return { plusOne: (this as any).count + 1 } }, computed: { plusTwo(): number { return this.count + 2 } }, methods: { inc() { this.count++ } }, render() { return h( 'div', { onClick: this.inc }, `${this.count},${this.plusOne},${this.plusTwo}` ) } }) const root = nodeOps.createElement('div') render(h(Comp), root) expect(serializeInner(root)).toBe(`<div>0,1,2</div>`) triggerEvent(root.children[0] as TestElement, 'click') await nextTick() expect(serializeInner(root)).toBe(`<div>1,1,3</div>`) }) // #1016 test('watcher initialization should be deferred in mixins', async () => { const mixin1 = { data() { return { mixin1Data: 'mixin1' } }, methods: {} } const watchSpy = jest.fn() const mixin2 = { watch: { mixin3Data: watchSpy } } const mixin3 = { data() { return { mixin3Data: 'mixin3' } }, methods: {} } let vm: any const Comp = { mixins: [mixin1, mixin2, mixin3], render() {}, created() { vm = this } } const root = nodeOps.createElement('div') render(h(Comp), root) // should have no warnings vm.mixin3Data = 'hello' await nextTick() expect(watchSpy.mock.calls[0].slice(0, 2)).toEqual(['hello', 'mixin3']) }) describe('warnings', () => { test('Expected a function as watch handler', () => { const Comp = { watch: { foo: 'notExistingMethod', foo2: { handler: 'notExistingMethod2' } }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( 'Invalid watch handler specified by key "notExistingMethod"' ).toHaveBeenWarned() expect( 'Invalid watch handler specified by key "notExistingMethod2"' ).toHaveBeenWarned() }) test('Invalid watch option', () => { const Comp = { watch: { foo: true }, render() {} } const root = nodeOps.createElement('div') // @ts-ignore render(h(Comp), root) expect('Invalid watch option: "foo"').toHaveBeenWarned() }) test('computed with setter and no getter', () => { const Comp = { computed: { foo: { set() {} } }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect('Computed property "foo" has no getter.').toHaveBeenWarned() }) test('assigning to computed with no setter', () => { let instance: any const Comp = { computed: { foo: { get() {} } }, mounted() { instance = this }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) instance.foo = 1 expect( 'Write operation failed: computed property "foo" is readonly' ).toHaveBeenWarned() }) test('inject property is already declared in props', () => { const Comp = { data() { return { a: 1 } }, provide() { return { a: this.a } }, render() { return [h(ChildA)] } } as any const ChildA = { props: { a: Number }, inject: ['a'], render() { return this.a } } as any const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Inject property "a" is already defined in Props.` ).toHaveBeenWarned() }) test('methods property is not a function', () => { const Comp = { methods: { foo: 1 }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Method "foo" has type "number" in the component definition. ` + `Did you reference the function correctly?` ).toHaveBeenWarned() }) test('methods property is already declared in props', () => { const Comp = { props: { foo: Number }, methods: { foo() {} }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Methods property "foo" is already defined in Props.` ).toHaveBeenWarned() }) test('methods property is already declared in inject', () => { const Comp = { data() { return { a: 1 } }, provide() { return { a: this.a } }, render() { return [h(ChildA)] } } as any const ChildA = { methods: { a: () => null }, inject: ['a'], render() { return this.a } } as any const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Methods property "a" is already defined in Inject.` ).toHaveBeenWarned() }) test('data property is already declared in props', () => { const Comp = { props: { foo: Number }, data: () => ({ foo: 1 }), render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Data property "foo" is already defined in Props.` ).toHaveBeenWarned() }) test('data property is already declared in inject', () => { const Comp = { data() { return { a: 1 } }, provide() { return { a: this.a } }, render() { return [h(ChildA)] } } as any const ChildA = { data() { return { a: 1 } }, inject: ['a'], render() { return this.a } } as any const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Data property "a" is already defined in Inject.` ).toHaveBeenWarned() }) test('data property is already declared in methods', () => { const Comp = { data: () => ({ foo: 1 }), methods: { foo() {} }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Data property "foo" is already defined in Methods.` ).toHaveBeenWarned() }) test('computed property is already declared in props', () => { const Comp = { props: { foo: Number }, computed: { foo() {} }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Computed property "foo" is already defined in Props.` ).toHaveBeenWarned() }) test('computed property is already declared in inject', () => { const Comp = { data() { return { a: 1 } }, provide() { return { a: this.a } }, render() { return [h(ChildA)] } } as any const ChildA = { computed: { a: { get() {}, set() {} } }, inject: ['a'], render() { return this.a } } as any const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Computed property "a" is already defined in Inject.` ).toHaveBeenWarned() }) test('computed property is already declared in methods', () => { const Comp = { computed: { foo() {} }, methods: { foo() {} }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Computed property "foo" is already defined in Methods.` ).toHaveBeenWarned() }) test('computed property is already declared in data', () => { const Comp = { data: () => ({ foo: 1 }), computed: { foo() {} }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Computed property "foo" is already defined in Data.` ).toHaveBeenWarned() }) }) })
packages/runtime-core/__tests__/apiOptions.spec.ts
1
https://github.com/vuejs/core/commit/313dd06065b1782d67f6881fbd42ae92a7f9cade
[ 0.9951595664024353, 0.04368971288204193, 0.00016318920825142413, 0.00017327099340036511, 0.1902921199798584 ]
{ "id": 3, "code_window": [ " from: 'c',\n", " default: () => 3\n", " }\n", " })\n", " expect(renderToString(h(Root))).toBe(`11123`)\n", " })\n", "\n", " test('lifecycle', async () => {\n", " const count = ref(0)\n", " const root = nodeOps.createElement('div')\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const ChildG = defineChild({\n", " b: {\n", " default: 4\n", " }\n", " })\n", " const ChildH = defineChild({\n", " b: {\n", " default: () => 5\n", " }\n", " })\n", " expect(renderToString(h(Root))).toBe(`11112345`)\n" ], "file_path": "packages/runtime-core/__tests__/apiOptions.spec.ts", "type": "replace", "edit_start_line_idx": 286 }
import { describe, h, defineComponent, ref, Fragment, Teleport, Suspense, Component, expectError, expectAssignable } from './index' describe('h inference w/ element', () => { // key h('div', { key: 1 }) h('div', { key: 'foo' }) // @ts-expect-error expectError(h('div', { key: [] })) // @ts-expect-error expectError(h('div', { key: {} })) // ref h('div', { ref: 'foo' }) h('div', { ref: ref(null) }) h('div', { ref: _el => {} }) // @ts-expect-error expectError(h('div', { ref: [] })) // @ts-expect-error expectError(h('div', { ref: {} })) // @ts-expect-error expectError(h('div', { ref: 123 })) // slots const slots = { default: () => {} } // RawSlots h('div', {}, slots) }) describe('h inference w/ Fragment', () => { // only accepts array children h(Fragment, ['hello']) h(Fragment, { key: 123 }, ['hello']) // @ts-expect-error expectError(h(Fragment, 'foo')) // @ts-expect-error expectError(h(Fragment, { key: 123 }, 'bar')) }) describe('h inference w/ Teleport', () => { h(Teleport, { to: '#foo' }, 'hello') // @ts-expect-error expectError(h(Teleport)) // @ts-expect-error expectError(h(Teleport, {})) // @ts-expect-error expectError(h(Teleport, { to: '#foo' })) }) describe('h inference w/ Suspense', () => { h(Suspense, { onRecede: () => {}, onResolve: () => {} }, 'hello') h(Suspense, 'foo') h(Suspense, () => 'foo') h(Suspense, null, { default: () => 'foo' }) // @ts-expect-error expectError(h(Suspense, { onResolve: 1 })) }) describe('h inference w/ functional component', () => { const Func = (_props: { foo: string; bar?: number }) => '' h(Func, { foo: 'hello' }) h(Func, { foo: 'hello', bar: 123 }) // @ts-expect-error expectError(h(Func, { foo: 123 })) // @ts-expect-error expectError(h(Func, {})) // @ts-expect-error expectError(h(Func, { bar: 123 })) }) describe('h support w/ plain object component', () => { const Foo = { props: { foo: String } } h(Foo, { foo: 'ok' }) h(Foo, { foo: 'ok', class: 'extra' }) // no inference in this case }) describe('h inference w/ defineComponent', () => { const Foo = defineComponent({ props: { foo: String, bar: { type: Number, required: true } } }) h(Foo, { bar: 1 }) h(Foo, { bar: 1, foo: 'ok' }) // should allow extraneous props (attrs fallthrough) h(Foo, { bar: 1, foo: 'ok', class: 'extra' }) // @ts-expect-error should fail on missing required prop expectError(h(Foo, {})) // @ts-expect-error expectError(h(Foo, { foo: 'ok' })) // @ts-expect-error should fail on wrong type expectError(h(Foo, { bar: 1, foo: 1 })) }) // describe('h inference w/ defineComponent + optional props', () => { // const Foo = defineComponent({ // setup(_props: { foo?: string; bar: number }) {} // }) // h(Foo, { bar: 1 }) // h(Foo, { bar: 1, foo: 'ok' }) // // should allow extraneous props (attrs fallthrough) // h(Foo, { bar: 1, foo: 'ok', class: 'extra' }) // // @ts-expect-error should fail on missing required prop // expectError(h(Foo, {})) // // @ts-expect-error // expectError(h(Foo, { foo: 'ok' })) // // @ts-expect-error should fail on wrong type // expectError(h(Foo, { bar: 1, foo: 1 })) // }) // describe('h inference w/ defineComponent + direct function', () => { // const Foo = defineComponent((_props: { foo?: string; bar: number }) => {}) // h(Foo, { bar: 1 }) // h(Foo, { bar: 1, foo: 'ok' }) // // should allow extraneous props (attrs fallthrough) // h(Foo, { bar: 1, foo: 'ok', class: 'extra' }) // // @ts-expect-error should fail on missing required prop // expectError(h(Foo, {})) // // @ts-expect-error // expectError(h(Foo, { foo: 'ok' })) // // @ts-expect-error should fail on wrong type // expectError(h(Foo, { bar: 1, foo: 1 })) // }) // #922 describe('h support for generic component type', () => { function foo(bar: Component) { h(bar) h(bar, 'hello') // @ts-expect-error h(bar, { id: 'ok' }, 'hello') } foo({}) }) // #993 describe('describeComponent extends Component', () => { // functional expectAssignable<Component>( defineComponent((_props: { foo?: string; bar: number }) => {}) ) // typed props expectAssignable<Component>(defineComponent({})) // prop arrays expectAssignable<Component>( defineComponent({ props: ['a', 'b'] }) ) // prop object expectAssignable<Component>( defineComponent({ props: { foo: String, bar: { type: Number, required: true } } }) ) }) // #1385 describe('component w/ props w/ default value', () => { const MyComponent = defineComponent({ props: { message: { type: String, default: 'hello' } } }) h(MyComponent, {}) })
test-dts/h.test-d.ts
0
https://github.com/vuejs/core/commit/313dd06065b1782d67f6881fbd42ae92a7f9cade
[ 0.00019133478053845465, 0.00017188691708724946, 0.00016494114242959768, 0.0001713099773041904, 0.000005316632268659305 ]
{ "id": 3, "code_window": [ " from: 'c',\n", " default: () => 3\n", " }\n", " })\n", " expect(renderToString(h(Root))).toBe(`11123`)\n", " })\n", "\n", " test('lifecycle', async () => {\n", " const count = ref(0)\n", " const root = nodeOps.createElement('div')\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const ChildG = defineChild({\n", " b: {\n", " default: 4\n", " }\n", " })\n", " const ChildH = defineChild({\n", " b: {\n", " default: () => 5\n", " }\n", " })\n", " expect(renderToString(h(Root))).toBe(`11112345`)\n" ], "file_path": "packages/runtime-core/__tests__/apiOptions.spec.ts", "type": "replace", "edit_start_line_idx": 286 }
import { ssrRenderList } from '../src/helpers/ssrRenderList' describe('ssr: renderList', () => { let stack: string[] = [] beforeEach(() => { stack = [] }) it('should render items in an array', () => { ssrRenderList(['1', '2', '3'], (item, index) => stack.push(`node ${index}: ${item}`) ) expect(stack).toEqual(['node 0: 1', 'node 1: 2', 'node 2: 3']) }) it('should render characters of a string', () => { ssrRenderList('abc', (item, index) => stack.push(`node ${index}: ${item}`)) expect(stack).toEqual(['node 0: a', 'node 1: b', 'node 2: c']) }) it('should render integers 1 through N when given a number N', () => { ssrRenderList(3, (item, index) => stack.push(`node ${index}: ${item}`)) expect(stack).toEqual(['node 0: 1', 'node 1: 2', 'node 2: 3']) }) it('should render properties in an object', () => { ssrRenderList({ a: 1, b: 2, c: 3 }, (item, key, index) => stack.push(`node ${index}/${key}: ${item}`) ) expect(stack).toEqual(['node 0/a: 1', 'node 1/b: 2', 'node 2/c: 3']) }) it('should render an item for entry in an iterable', () => { const iterable = function*() { yield 1 yield 2 yield 3 } ssrRenderList(iterable(), (item, index) => stack.push(`node ${index}: ${item}`) ) expect(stack).toEqual(['node 0: 1', 'node 1: 2', 'node 2: 3']) }) it('should not render items when source is undefined', () => { ssrRenderList(undefined, (item, index) => stack.push(`node ${index}: ${item}`) ) expect(stack).toEqual([]) }) })
packages/server-renderer/__tests__/ssrRenderList.spec.ts
0
https://github.com/vuejs/core/commit/313dd06065b1782d67f6881fbd42ae92a7f9cade
[ 0.0001776605931809172, 0.00017206095799338073, 0.00016864438657648861, 0.00017137458780780435, 0.0000032650696084601805 ]
{ "id": 3, "code_window": [ " from: 'c',\n", " default: () => 3\n", " }\n", " })\n", " expect(renderToString(h(Root))).toBe(`11123`)\n", " })\n", "\n", " test('lifecycle', async () => {\n", " const count = ref(0)\n", " const root = nodeOps.createElement('div')\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const ChildG = defineChild({\n", " b: {\n", " default: 4\n", " }\n", " })\n", " const ChildH = defineChild({\n", " b: {\n", " default: () => 5\n", " }\n", " })\n", " expect(renderToString(h(Root))).toBe(`11112345`)\n" ], "file_path": "packages/runtime-core/__tests__/apiOptions.spec.ts", "type": "replace", "edit_start_line_idx": 286 }
// Note: emits and listener fallthrough is tested in // ./rendererAttrsFallthrough.spec.ts. import { render, defineComponent, h, nodeOps } from '@vue/runtime-test' import { isEmitListener } from '../src/componentEmits' describe('component: emit', () => { test('trigger handlers', () => { const Foo = defineComponent({ render() {}, created() { // the `emit` function is bound on component instances this.$emit('foo') this.$emit('bar') this.$emit('!baz') } }) const onfoo = jest.fn() const onBar = jest.fn() const onBaz = jest.fn() const Comp = () => h(Foo, { onfoo, onBar, ['on!baz']: onBaz }) render(h(Comp), nodeOps.createElement('div')) expect(onfoo).not.toHaveBeenCalled() // only capitalized or special chars are considered event listeners expect(onBar).toHaveBeenCalled() expect(onBaz).toHaveBeenCalled() }) // for v-model:foo-bar usage in DOM templates test('trigger hyphenated events for update:xxx events', () => { const Foo = defineComponent({ render() {}, created() { this.$emit('update:fooProp') this.$emit('update:barProp') } }) const fooSpy = jest.fn() const barSpy = jest.fn() const Comp = () => h(Foo, { 'onUpdate:fooProp': fooSpy, 'onUpdate:bar-prop': barSpy }) render(h(Comp), nodeOps.createElement('div')) expect(fooSpy).toHaveBeenCalled() expect(barSpy).toHaveBeenCalled() }) test('should trigger array of listeners', async () => { const Child = defineComponent({ setup(_, { emit }) { emit('foo', 1) return () => h('div') } }) const fn1 = jest.fn() const fn2 = jest.fn() const App = { setup() { return () => h(Child, { onFoo: [fn1, fn2] }) } } render(h(App), nodeOps.createElement('div')) expect(fn1).toHaveBeenCalledTimes(1) expect(fn1).toHaveBeenCalledWith(1) expect(fn2).toHaveBeenCalledTimes(1) expect(fn1).toHaveBeenCalledWith(1) }) test('warning for undeclared event (array)', () => { const Foo = defineComponent({ emits: ['foo'], render() {}, created() { // @ts-ignore this.$emit('bar') } }) render(h(Foo), nodeOps.createElement('div')) expect( `Component emitted event "bar" but it is neither declared` ).toHaveBeenWarned() }) test('warning for undeclared event (object)', () => { const Foo = defineComponent({ emits: { foo: null }, render() {}, created() { // @ts-ignore this.$emit('bar') } }) render(h(Foo), nodeOps.createElement('div')) expect( `Component emitted event "bar" but it is neither declared` ).toHaveBeenWarned() }) test('should not warn if has equivalent onXXX prop', () => { const Foo = defineComponent({ props: ['onFoo'], emits: [], render() {}, created() { // @ts-ignore this.$emit('foo') } }) render(h(Foo), nodeOps.createElement('div')) expect( `Component emitted event "bar" but it is neither declared` ).not.toHaveBeenWarned() }) test('validator warning', () => { const Foo = defineComponent({ emits: { foo: (arg: number) => arg > 0 }, render() {}, created() { this.$emit('foo', -1) } }) render(h(Foo), nodeOps.createElement('div')) expect(`event validation failed for event "foo"`).toHaveBeenWarned() }) test('merging from mixins', () => { const mixin = { emits: { foo: (arg: number) => arg > 0 } } const Foo = defineComponent({ mixins: [mixin], render() {}, created() { this.$emit('foo', -1) } }) render(h(Foo), nodeOps.createElement('div')) expect(`event validation failed for event "foo"`).toHaveBeenWarned() }) test('.once', () => { const Foo = defineComponent({ render() {}, emits: { foo: null }, created() { this.$emit('foo') this.$emit('foo') } }) const fn = jest.fn() render( h(Foo, { onFooOnce: fn }), nodeOps.createElement('div') ) expect(fn).toHaveBeenCalledTimes(1) }) test('isEmitListener', () => { const options = { click: null } expect(isEmitListener(options, 'onClick')).toBe(true) expect(isEmitListener(options, 'onclick')).toBe(false) expect(isEmitListener(options, 'onBlick')).toBe(false) // .once listeners expect(isEmitListener(options, 'onClickOnce')).toBe(true) expect(isEmitListener(options, 'onclickOnce')).toBe(false) }) })
packages/runtime-core/__tests__/componentEmits.spec.ts
0
https://github.com/vuejs/core/commit/313dd06065b1782d67f6881fbd42ae92a7f9cade
[ 0.0015781576512381434, 0.000387908483389765, 0.00016628848970867693, 0.00021369924070313573, 0.00035358380409888923 ]
{ "id": 4, "code_window": [ " | string[]\n", " | Record<\n", " string | symbol,\n", " string | symbol | { from: string | symbol; default?: unknown }\n", " >\n", "\n", "interface LegacyOptions<\n", " Props,\n", " D,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " string | symbol | { from?: string | symbol; default?: unknown }\n" ], "file_path": "packages/runtime-core/src/componentOptions.ts", "type": "replace", "edit_start_line_idx": 277 }
import { h, nodeOps, render, serializeInner, triggerEvent, TestElement, nextTick, renderToString, ref, defineComponent } from '@vue/runtime-test' describe('api: options', () => { test('data', async () => { const Comp = defineComponent({ data() { return { foo: 1 } }, render() { return h( 'div', { onClick: () => { this.foo++ } }, this.foo ) } }) const root = nodeOps.createElement('div') render(h(Comp), root) expect(serializeInner(root)).toBe(`<div>1</div>`) triggerEvent(root.children[0] as TestElement, 'click') await nextTick() expect(serializeInner(root)).toBe(`<div>2</div>`) }) test('computed', async () => { const Comp = defineComponent({ data() { return { foo: 1 } }, computed: { bar(): number { return this.foo + 1 }, baz: (vm): number => vm.bar + 1 }, render() { return h( 'div', { onClick: () => { this.foo++ } }, this.bar + this.baz ) } }) const root = nodeOps.createElement('div') render(h(Comp), root) expect(serializeInner(root)).toBe(`<div>5</div>`) triggerEvent(root.children[0] as TestElement, 'click') await nextTick() expect(serializeInner(root)).toBe(`<div>7</div>`) }) test('methods', async () => { const Comp = defineComponent({ data() { return { foo: 1 } }, methods: { inc() { this.foo++ } }, render() { return h( 'div', { onClick: this.inc }, this.foo ) } }) const root = nodeOps.createElement('div') render(h(Comp), root) expect(serializeInner(root)).toBe(`<div>1</div>`) triggerEvent(root.children[0] as TestElement, 'click') await nextTick() expect(serializeInner(root)).toBe(`<div>2</div>`) }) test('watch', async () => { function returnThis(this: any) { return this } const spyA = jest.fn(returnThis) const spyB = jest.fn(returnThis) const spyC = jest.fn(returnThis) const spyD = jest.fn(returnThis) let ctx: any const Comp = { data() { return { foo: 1, bar: 2, baz: { qux: 3 }, qux: 4 } }, watch: { // string method name foo: 'onFooChange', // direct function bar: spyB, baz: { handler: spyC, deep: true }, qux: { handler: 'onQuxChange' } }, methods: { onFooChange: spyA, onQuxChange: spyD }, render() { ctx = this } } const root = nodeOps.createElement('div') render(h(Comp), root) function assertCall(spy: jest.Mock, callIndex: number, args: any[]) { expect(spy.mock.calls[callIndex].slice(0, 2)).toMatchObject(args) expect(spy).toHaveReturnedWith(ctx) } ctx.foo++ await nextTick() expect(spyA).toHaveBeenCalledTimes(1) assertCall(spyA, 0, [2, 1]) ctx.bar++ await nextTick() expect(spyB).toHaveBeenCalledTimes(1) assertCall(spyB, 0, [3, 2]) ctx.baz.qux++ await nextTick() expect(spyC).toHaveBeenCalledTimes(1) // new and old objects have same identity assertCall(spyC, 0, [{ qux: 4 }, { qux: 4 }]) ctx.qux++ await nextTick() expect(spyD).toHaveBeenCalledTimes(1) assertCall(spyD, 0, [5, 4]) }) test('watch array', async () => { function returnThis(this: any) { return this } const spyA = jest.fn(returnThis) const spyB = jest.fn(returnThis) const spyC = jest.fn(returnThis) let ctx: any const Comp = { data() { return { foo: 1, bar: 2, baz: { qux: 3 } } }, watch: { // string method name foo: ['onFooChange'], // direct function bar: [spyB], baz: [ { handler: spyC, deep: true } ] }, methods: { onFooChange: spyA }, render() { ctx = this } } const root = nodeOps.createElement('div') render(h(Comp), root) function assertCall(spy: jest.Mock, callIndex: number, args: any[]) { expect(spy.mock.calls[callIndex].slice(0, 2)).toMatchObject(args) expect(spy).toHaveReturnedWith(ctx) } ctx.foo++ await nextTick() expect(spyA).toHaveBeenCalledTimes(1) assertCall(spyA, 0, [2, 1]) ctx.bar++ await nextTick() expect(spyB).toHaveBeenCalledTimes(1) assertCall(spyB, 0, [3, 2]) ctx.baz.qux++ await nextTick() expect(spyC).toHaveBeenCalledTimes(1) // new and old objects have same identity assertCall(spyC, 0, [{ qux: 4 }, { qux: 4 }]) }) test('provide/inject', () => { const Root = defineComponent({ data() { return { a: 1 } }, provide() { return { a: this.a } }, render() { return [h(ChildA), h(ChildB), h(ChildC), h(ChildD), h(ChildE)] } }) const defineChild = (injectOptions: any, injectedKey = 'b') => ({ inject: injectOptions, render() { return this[injectedKey] } } as any) const ChildA = defineChild(['a'], 'a') const ChildB = defineChild({ b: 'a' }) const ChildC = defineChild({ b: { from: 'a' } }) const ChildD = defineChild({ b: { from: 'c', default: 2 } }) const ChildE = defineChild({ b: { from: 'c', default: () => 3 } }) expect(renderToString(h(Root))).toBe(`11123`) }) test('lifecycle', async () => { const count = ref(0) const root = nodeOps.createElement('div') const calls: string[] = [] const Root = { beforeCreate() { calls.push('root beforeCreate') }, created() { calls.push('root created') }, beforeMount() { calls.push('root onBeforeMount') }, mounted() { calls.push('root onMounted') }, beforeUpdate() { calls.push('root onBeforeUpdate') }, updated() { calls.push('root onUpdated') }, beforeUnmount() { calls.push('root onBeforeUnmount') }, unmounted() { calls.push('root onUnmounted') }, render() { return h(Mid, { count: count.value }) } } const Mid = { beforeCreate() { calls.push('mid beforeCreate') }, created() { calls.push('mid created') }, beforeMount() { calls.push('mid onBeforeMount') }, mounted() { calls.push('mid onMounted') }, beforeUpdate() { calls.push('mid onBeforeUpdate') }, updated() { calls.push('mid onUpdated') }, beforeUnmount() { calls.push('mid onBeforeUnmount') }, unmounted() { calls.push('mid onUnmounted') }, render(this: any) { return h(Child, { count: this.$props.count }) } } const Child = { beforeCreate() { calls.push('child beforeCreate') }, created() { calls.push('child created') }, beforeMount() { calls.push('child onBeforeMount') }, mounted() { calls.push('child onMounted') }, beforeUpdate() { calls.push('child onBeforeUpdate') }, updated() { calls.push('child onUpdated') }, beforeUnmount() { calls.push('child onBeforeUnmount') }, unmounted() { calls.push('child onUnmounted') }, render(this: any) { return h('div', this.$props.count) } } // mount render(h(Root), root) expect(calls).toEqual([ 'root beforeCreate', 'root created', 'root onBeforeMount', 'mid beforeCreate', 'mid created', 'mid onBeforeMount', 'child beforeCreate', 'child created', 'child onBeforeMount', 'child onMounted', 'mid onMounted', 'root onMounted' ]) calls.length = 0 // update count.value++ await nextTick() expect(calls).toEqual([ 'root onBeforeUpdate', 'mid onBeforeUpdate', 'child onBeforeUpdate', 'child onUpdated', 'mid onUpdated', 'root onUpdated' ]) calls.length = 0 // unmount render(null, root) expect(calls).toEqual([ 'root onBeforeUnmount', 'mid onBeforeUnmount', 'child onBeforeUnmount', 'child onUnmounted', 'mid onUnmounted', 'root onUnmounted' ]) }) test('mixins', () => { const calls: string[] = [] const mixinA = { data() { return { a: 1 } }, created(this: any) { calls.push('mixinA created') expect(this.a).toBe(1) expect(this.b).toBe(2) expect(this.c).toBe(4) }, mounted() { calls.push('mixinA mounted') } } const mixinB = { props: { bP: { type: String } }, data() { return { b: 2 } }, created(this: any) { calls.push('mixinB created') expect(this.a).toBe(1) expect(this.b).toBe(2) expect(this.bP).toBeUndefined() expect(this.c).toBe(4) expect(this.cP1).toBeUndefined() }, mounted() { calls.push('mixinB mounted') } } const mixinC = defineComponent({ props: ['cP1', 'cP2'], data() { return { c: 3 } }, created() { calls.push('mixinC created') // component data() should overwrite mixin field with same key expect(this.c).toBe(4) expect(this.cP1).toBeUndefined() }, mounted() { calls.push('mixinC mounted') } }) const Comp = defineComponent({ props: { aaa: String }, mixins: [defineComponent(mixinA), defineComponent(mixinB), mixinC], data() { return { c: 4, z: 4 } }, created() { calls.push('comp created') expect(this.a).toBe(1) expect(this.b).toBe(2) expect(this.bP).toBeUndefined() expect(this.c).toBe(4) expect(this.cP2).toBeUndefined() expect(this.z).toBe(4) }, mounted() { calls.push('comp mounted') }, render() { return `${this.a}${this.b}${this.c}` } }) expect(renderToString(h(Comp))).toBe(`124`) expect(calls).toEqual([ 'mixinA created', 'mixinB created', 'mixinC created', 'comp created', 'mixinA mounted', 'mixinB mounted', 'mixinC mounted', 'comp mounted' ]) }) test('render from mixin', () => { const Comp = { mixins: [ { render: () => 'from mixin' } ] } expect(renderToString(h(Comp))).toBe('from mixin') }) test('extends', () => { const calls: string[] = [] const Base = { data() { return { a: 1, b: 1 } }, methods: { sayA() {} }, mounted(this: any) { expect(this.a).toBe(1) expect(this.b).toBe(2) calls.push('base') } } const Comp = defineComponent({ extends: defineComponent(Base), data() { return { b: 2 } }, mounted() { calls.push('comp') }, render() { return `${this.a}${this.b}` } }) expect(renderToString(h(Comp))).toBe(`12`) expect(calls).toEqual(['base', 'comp']) }) test('extends with mixins', () => { const calls: string[] = [] const Base = { data() { return { a: 1, x: 'base' } }, methods: { sayA() {} }, mounted(this: any) { expect(this.a).toBe(1) expect(this.b).toBeTruthy() expect(this.c).toBe(2) calls.push('base') } } const Mixin = { data() { return { b: true, x: 'mixin' } }, mounted(this: any) { expect(this.a).toBe(1) expect(this.b).toBeTruthy() expect(this.c).toBe(2) calls.push('mixin') } } const Comp = defineComponent({ extends: defineComponent(Base), mixins: [defineComponent(Mixin)], data() { return { c: 2 } }, mounted() { calls.push('comp') }, render() { return `${this.a}${this.b}${this.c}${this.x}` } }) expect(renderToString(h(Comp))).toBe(`1true2mixin`) expect(calls).toEqual(['base', 'mixin', 'comp']) }) test('beforeCreate/created in extends and mixins', () => { const calls: string[] = [] const BaseA = { beforeCreate() { calls.push('beforeCreateA') }, created() { calls.push('createdA') } } const BaseB = { extends: BaseA, beforeCreate() { calls.push('beforeCreateB') }, created() { calls.push('createdB') } } const MixinA = { beforeCreate() { calls.push('beforeCreateC') }, created() { calls.push('createdC') } } const MixinB = { mixins: [MixinA], beforeCreate() { calls.push('beforeCreateD') }, created() { calls.push('createdD') } } const Comp = { extends: BaseB, mixins: [MixinB], beforeCreate() { calls.push('selfBeforeCreate') }, created() { calls.push('selfCreated') }, render() {} } renderToString(h(Comp)) expect(calls).toEqual([ 'beforeCreateA', 'beforeCreateB', 'beforeCreateC', 'beforeCreateD', 'selfBeforeCreate', 'createdA', 'createdB', 'createdC', 'createdD', 'selfCreated' ]) }) test('flatten merged options', async () => { const MixinBase = { msg1: 'base' } const ExtendsBase = { msg2: 'base' } const Mixin = { mixins: [MixinBase] } const Extends = { extends: ExtendsBase } const Comp = defineComponent({ extends: defineComponent(Extends), mixins: [defineComponent(Mixin)], render() { return `${this.$options.msg1},${this.$options.msg2}` } }) expect(renderToString(h(Comp))).toBe('base,base') }) test('options defined in component have higher priority', async () => { const Mixin = { msg1: 'base' } const Extends = { msg2: 'base' } const Comp = defineComponent({ msg1: 'local', msg2: 'local', extends: defineComponent(Extends), mixins: [defineComponent(Mixin)], render() { return `${this.$options.msg1},${this.$options.msg2}` } }) expect(renderToString(h(Comp))).toBe('local,local') }) test('accessing setup() state from options', async () => { const Comp = defineComponent({ setup() { return { count: ref(0) } }, data() { return { plusOne: (this as any).count + 1 } }, computed: { plusTwo(): number { return this.count + 2 } }, methods: { inc() { this.count++ } }, render() { return h( 'div', { onClick: this.inc }, `${this.count},${this.plusOne},${this.plusTwo}` ) } }) const root = nodeOps.createElement('div') render(h(Comp), root) expect(serializeInner(root)).toBe(`<div>0,1,2</div>`) triggerEvent(root.children[0] as TestElement, 'click') await nextTick() expect(serializeInner(root)).toBe(`<div>1,1,3</div>`) }) // #1016 test('watcher initialization should be deferred in mixins', async () => { const mixin1 = { data() { return { mixin1Data: 'mixin1' } }, methods: {} } const watchSpy = jest.fn() const mixin2 = { watch: { mixin3Data: watchSpy } } const mixin3 = { data() { return { mixin3Data: 'mixin3' } }, methods: {} } let vm: any const Comp = { mixins: [mixin1, mixin2, mixin3], render() {}, created() { vm = this } } const root = nodeOps.createElement('div') render(h(Comp), root) // should have no warnings vm.mixin3Data = 'hello' await nextTick() expect(watchSpy.mock.calls[0].slice(0, 2)).toEqual(['hello', 'mixin3']) }) describe('warnings', () => { test('Expected a function as watch handler', () => { const Comp = { watch: { foo: 'notExistingMethod', foo2: { handler: 'notExistingMethod2' } }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( 'Invalid watch handler specified by key "notExistingMethod"' ).toHaveBeenWarned() expect( 'Invalid watch handler specified by key "notExistingMethod2"' ).toHaveBeenWarned() }) test('Invalid watch option', () => { const Comp = { watch: { foo: true }, render() {} } const root = nodeOps.createElement('div') // @ts-ignore render(h(Comp), root) expect('Invalid watch option: "foo"').toHaveBeenWarned() }) test('computed with setter and no getter', () => { const Comp = { computed: { foo: { set() {} } }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect('Computed property "foo" has no getter.').toHaveBeenWarned() }) test('assigning to computed with no setter', () => { let instance: any const Comp = { computed: { foo: { get() {} } }, mounted() { instance = this }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) instance.foo = 1 expect( 'Write operation failed: computed property "foo" is readonly' ).toHaveBeenWarned() }) test('inject property is already declared in props', () => { const Comp = { data() { return { a: 1 } }, provide() { return { a: this.a } }, render() { return [h(ChildA)] } } as any const ChildA = { props: { a: Number }, inject: ['a'], render() { return this.a } } as any const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Inject property "a" is already defined in Props.` ).toHaveBeenWarned() }) test('methods property is not a function', () => { const Comp = { methods: { foo: 1 }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Method "foo" has type "number" in the component definition. ` + `Did you reference the function correctly?` ).toHaveBeenWarned() }) test('methods property is already declared in props', () => { const Comp = { props: { foo: Number }, methods: { foo() {} }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Methods property "foo" is already defined in Props.` ).toHaveBeenWarned() }) test('methods property is already declared in inject', () => { const Comp = { data() { return { a: 1 } }, provide() { return { a: this.a } }, render() { return [h(ChildA)] } } as any const ChildA = { methods: { a: () => null }, inject: ['a'], render() { return this.a } } as any const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Methods property "a" is already defined in Inject.` ).toHaveBeenWarned() }) test('data property is already declared in props', () => { const Comp = { props: { foo: Number }, data: () => ({ foo: 1 }), render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Data property "foo" is already defined in Props.` ).toHaveBeenWarned() }) test('data property is already declared in inject', () => { const Comp = { data() { return { a: 1 } }, provide() { return { a: this.a } }, render() { return [h(ChildA)] } } as any const ChildA = { data() { return { a: 1 } }, inject: ['a'], render() { return this.a } } as any const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Data property "a" is already defined in Inject.` ).toHaveBeenWarned() }) test('data property is already declared in methods', () => { const Comp = { data: () => ({ foo: 1 }), methods: { foo() {} }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Data property "foo" is already defined in Methods.` ).toHaveBeenWarned() }) test('computed property is already declared in props', () => { const Comp = { props: { foo: Number }, computed: { foo() {} }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Computed property "foo" is already defined in Props.` ).toHaveBeenWarned() }) test('computed property is already declared in inject', () => { const Comp = { data() { return { a: 1 } }, provide() { return { a: this.a } }, render() { return [h(ChildA)] } } as any const ChildA = { computed: { a: { get() {}, set() {} } }, inject: ['a'], render() { return this.a } } as any const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Computed property "a" is already defined in Inject.` ).toHaveBeenWarned() }) test('computed property is already declared in methods', () => { const Comp = { computed: { foo() {} }, methods: { foo() {} }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Computed property "foo" is already defined in Methods.` ).toHaveBeenWarned() }) test('computed property is already declared in data', () => { const Comp = { data: () => ({ foo: 1 }), computed: { foo() {} }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Computed property "foo" is already defined in Data.` ).toHaveBeenWarned() }) }) })
packages/runtime-core/__tests__/apiOptions.spec.ts
1
https://github.com/vuejs/core/commit/313dd06065b1782d67f6881fbd42ae92a7f9cade
[ 0.0007762208697386086, 0.00018574317800812423, 0.00016677517851348966, 0.00017435655172448605, 0.00006585527444258332 ]
{ "id": 4, "code_window": [ " | string[]\n", " | Record<\n", " string | symbol,\n", " string | symbol | { from: string | symbol; default?: unknown }\n", " >\n", "\n", "interface LegacyOptions<\n", " Props,\n", " D,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " string | symbol | { from?: string | symbol; default?: unknown }\n" ], "file_path": "packages/runtime-core/src/componentOptions.ts", "type": "replace", "edit_start_line_idx": 277 }
/* Produces production builds and stitches together d.ts files. To specify the package to build, simply pass its name and the desired build formats to output (defaults to `buildOptions.formats` specified in that package, or "esm,cjs"): ``` # name supports fuzzy match. will build all packages with name containing "dom": yarn build dom # specify the format to output yarn build core --formats cjs ``` */ const fs = require('fs-extra') const path = require('path') const chalk = require('chalk') const execa = require('execa') const { gzipSync } = require('zlib') const { compress } = require('brotli') const { targets: allTargets, fuzzyMatchTarget } = require('./utils') const args = require('minimist')(process.argv.slice(2)) const targets = args._ const formats = args.formats || args.f const devOnly = args.devOnly || args.d const prodOnly = !devOnly && (args.prodOnly || args.p) const sourceMap = args.sourcemap || args.s const isRelease = args.release const buildTypes = args.t || args.types || isRelease const buildAllMatching = args.all || args.a const commit = execa.sync('git', ['rev-parse', 'HEAD']).stdout.slice(0, 7) run() async function run() { if (isRelease) { // remove build cache for release builds to avoid outdated enum values await fs.remove(path.resolve(__dirname, '../node_modules/.rts2_cache')) } if (!targets.length) { await buildAll(allTargets) checkAllSizes(allTargets) } else { await buildAll(fuzzyMatchTarget(targets, buildAllMatching)) checkAllSizes(fuzzyMatchTarget(targets, buildAllMatching)) } } async function buildAll(targets) { for (const target of targets) { await build(target) } } async function build(target) { const pkgDir = path.resolve(`packages/${target}`) const pkg = require(`${pkgDir}/package.json`) // only build published packages for release if (isRelease && pkg.private) { return } // if building a specific format, do not remove dist. if (!formats) { await fs.remove(`${pkgDir}/dist`) } const env = (pkg.buildOptions && pkg.buildOptions.env) || (devOnly ? 'development' : 'production') await execa( 'rollup', [ '-c', '--environment', [ `COMMIT:${commit}`, `NODE_ENV:${env}`, `TARGET:${target}`, formats ? `FORMATS:${formats}` : ``, buildTypes ? `TYPES:true` : ``, prodOnly ? `PROD_ONLY:true` : ``, sourceMap ? `SOURCE_MAP:true` : `` ] .filter(Boolean) .join(',') ], { stdio: 'inherit' } ) if (buildTypes && pkg.types) { console.log() console.log( chalk.bold(chalk.yellow(`Rolling up type definitions for ${target}...`)) ) // build types const { Extractor, ExtractorConfig } = require('@microsoft/api-extractor') const extractorConfigPath = path.resolve(pkgDir, `api-extractor.json`) const extractorConfig = ExtractorConfig.loadFileAndPrepare( extractorConfigPath ) const extractorResult = Extractor.invoke(extractorConfig, { localBuild: true, showVerboseMessages: true }) if (extractorResult.succeeded) { // concat additional d.ts to rolled-up dts const typesDir = path.resolve(pkgDir, 'types') if (await fs.exists(typesDir)) { const dtsPath = path.resolve(pkgDir, pkg.types) const existing = await fs.readFile(dtsPath, 'utf-8') const typeFiles = await fs.readdir(typesDir) const toAdd = await Promise.all( typeFiles.map(file => { return fs.readFile(path.resolve(typesDir, file), 'utf-8') }) ) await fs.writeFile(dtsPath, existing + '\n' + toAdd.join('\n')) } console.log( chalk.bold(chalk.green(`API Extractor completed successfully.`)) ) } else { console.error( `API Extractor completed with ${extractorResult.errorCount} errors` + ` and ${extractorResult.warningCount} warnings` ) process.exitCode = 1 } await fs.remove(`${pkgDir}/dist/packages`) } } function checkAllSizes(targets) { if (devOnly) { return } console.log() for (const target of targets) { checkSize(target) } console.log() } function checkSize(target) { const pkgDir = path.resolve(`packages/${target}`) checkFileSize(`${pkgDir}/dist/${target}.global.prod.js`) } function checkFileSize(filePath) { if (!fs.existsSync(filePath)) { return } const file = fs.readFileSync(filePath) const minSize = (file.length / 1024).toFixed(2) + 'kb' const gzipped = gzipSync(file) const gzippedSize = (gzipped.length / 1024).toFixed(2) + 'kb' const compressed = compress(file) const compressedSize = (compressed.length / 1024).toFixed(2) + 'kb' console.log( `${chalk.gray( chalk.bold(path.basename(filePath)) )} min:${minSize} / gzip:${gzippedSize} / brotli:${compressedSize}` ) }
scripts/build.js
0
https://github.com/vuejs/core/commit/313dd06065b1782d67f6881fbd42ae92a7f9cade
[ 0.00017766600649338216, 0.00017373060109093785, 0.00016464840155094862, 0.0001749516959534958, 0.0000034194176805613097 ]
{ "id": 4, "code_window": [ " | string[]\n", " | Record<\n", " string | symbol,\n", " string | symbol | { from: string | symbol; default?: unknown }\n", " >\n", "\n", "interface LegacyOptions<\n", " Props,\n", " D,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " string | symbol | { from?: string | symbol; default?: unknown }\n" ], "file_path": "packages/runtime-core/src/componentOptions.ts", "type": "replace", "edit_start_line_idx": 277 }
<script src="../../dist/vue.global.js"></script> <script> // math helper... function valueToPoint (value, index, total) { var x = 0 var y = -value * 0.8 var angle = Math.PI * 2 / total * index var cos = Math.cos(angle) var sin = Math.sin(angle) var tx = x * cos - y * sin + 100 var ty = x * sin + y * cos + 100 return { x: tx, y: ty } } const AxisLabel = { template: '<text :x="point.x" :y="point.y">{{stat.label}}</text>', props: { stat: Object, index: Number, total: Number }, computed: { point: function () { return valueToPoint( +this.stat.value + 10, this.index, this.total ) } } } </script> <!-- template for the polygraph component. --> <script type="text/x-template" id="polygraph-template"> <g> <polygon :points="points"></polygon> <circle cx="100" cy="100" r="80"></circle> <axis-label v-for="(stat, index) in stats" :stat="stat" :index="index" :total="stats.length"> </axis-label> </g> </script> <script> const Polygraph = { props: ['stats'], template: '#polygraph-template', computed: { // a computed property for the polygon's points points() { const total = this.stats.length return this.stats.map((stat, i) => { const point = valueToPoint(stat.value, i, total) return point.x + ',' + point.y }).join(' ') } }, components: { AxisLabel } } </script> <!-- demo root element --> <div id="demo"> <!-- Use the polygraph component --> <svg width="200" height="200"> <polygraph :stats="stats"></polygraph> </svg> <!-- controls --> <div v-for="stat in stats"> <label>{{stat.label}}</label> <input type="range" v-model="stat.value" min="0" max="100"> <span>{{stat.value}}</span> <button @click="remove(stat)" class="remove">X</button> </div> <form id="add"> <input name="newlabel" v-model="newLabel"> <button @click="add">Add a Stat</button> </form> <pre id="raw">{{ stats }}</pre> </div> <script> const globalStats = [ { label: 'A', value: 100 }, { label: 'B', value: 100 }, { label: 'C', value: 100 }, { label: 'D', value: 100 }, { label: 'E', value: 100 }, { label: 'F', value: 100 } ] Vue.createApp({ components: { Polygraph }, data: () => ({ newLabel: '', stats: globalStats }), methods: { add(e) { e.preventDefault() if (!this.newLabel) return this.stats.push({ label: this.newLabel, value: 100 }) this.newLabel = '' }, remove(stat) { if (this.stats.length > 3) { this.stats.splice(this.stats.indexOf(stat), 1) } else { alert('Can\'t delete more!') } } } }).mount('#demo') </script> <style> body { font-family: Helvetica Neue, Arial, sans-serif; } polygon { fill: #42b983; opacity: .75; } circle { fill: transparent; stroke: #999; } text { font-family: Helvetica Neue, Arial, sans-serif; font-size: 10px; fill: #666; } label { display: inline-block; margin-left: 10px; width: 20px; } #raw { position: absolute; top: 0; left: 300px; } </style>
packages/vue/examples/classic/svg.html
0
https://github.com/vuejs/core/commit/313dd06065b1782d67f6881fbd42ae92a7f9cade
[ 0.00019089595298282802, 0.00017529487377032638, 0.00016938683984335512, 0.0001749460498103872, 0.000004604354671755573 ]
{ "id": 4, "code_window": [ " | string[]\n", " | Record<\n", " string | symbol,\n", " string | symbol | { from: string | symbol; default?: unknown }\n", " >\n", "\n", "interface LegacyOptions<\n", " Props,\n", " D,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " string | symbol | { from?: string | symbol; default?: unknown }\n" ], "file_path": "packages/runtime-core/src/componentOptions.ts", "type": "replace", "edit_start_line_idx": 277 }
export const enum SlotFlags { /** * Stable slots that only reference slot props or context state. The slot * can fully capture its own dependencies so when passed down the parent won't * need to force the child to update. */ STABLE = 1, /** * Slots that reference scope variables (v-for or an outer slot prop), or * has conditional structure (v-if, v-for). The parent will need to force * the child to update because the slot does not fully capture its dependencies. */ DYNAMIC = 2, /** * `<slot/>` being forwarded into a child component. Whether the parent needs * to update the child is dependent on what kind of slots the parent itself * received. This has to be refined at runtime, when the child's vnode * is being created (in `normalizeChildren`) */ FORWARDED = 3 }
packages/shared/src/slotFlags.ts
0
https://github.com/vuejs/core/commit/313dd06065b1782d67f6881fbd42ae92a7f9cade
[ 0.000264487141976133, 0.0002043140266323462, 0.00016759216669015586, 0.00018086278578266501, 0.000042892344936262816 ]
{ "id": 5, "code_window": [ " for (const key in injectOptions) {\n", " const opt = injectOptions[key]\n", " if (isObject(opt)) {\n", " ctx[key] = inject(\n", " opt.from,\n", " opt.default,\n", " true /* treat default function as factory */\n", " )\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " opt.from || key,\n" ], "file_path": "packages/runtime-core/src/componentOptions.ts", "type": "replace", "edit_start_line_idx": 462 }
import { h, nodeOps, render, serializeInner, triggerEvent, TestElement, nextTick, renderToString, ref, defineComponent } from '@vue/runtime-test' describe('api: options', () => { test('data', async () => { const Comp = defineComponent({ data() { return { foo: 1 } }, render() { return h( 'div', { onClick: () => { this.foo++ } }, this.foo ) } }) const root = nodeOps.createElement('div') render(h(Comp), root) expect(serializeInner(root)).toBe(`<div>1</div>`) triggerEvent(root.children[0] as TestElement, 'click') await nextTick() expect(serializeInner(root)).toBe(`<div>2</div>`) }) test('computed', async () => { const Comp = defineComponent({ data() { return { foo: 1 } }, computed: { bar(): number { return this.foo + 1 }, baz: (vm): number => vm.bar + 1 }, render() { return h( 'div', { onClick: () => { this.foo++ } }, this.bar + this.baz ) } }) const root = nodeOps.createElement('div') render(h(Comp), root) expect(serializeInner(root)).toBe(`<div>5</div>`) triggerEvent(root.children[0] as TestElement, 'click') await nextTick() expect(serializeInner(root)).toBe(`<div>7</div>`) }) test('methods', async () => { const Comp = defineComponent({ data() { return { foo: 1 } }, methods: { inc() { this.foo++ } }, render() { return h( 'div', { onClick: this.inc }, this.foo ) } }) const root = nodeOps.createElement('div') render(h(Comp), root) expect(serializeInner(root)).toBe(`<div>1</div>`) triggerEvent(root.children[0] as TestElement, 'click') await nextTick() expect(serializeInner(root)).toBe(`<div>2</div>`) }) test('watch', async () => { function returnThis(this: any) { return this } const spyA = jest.fn(returnThis) const spyB = jest.fn(returnThis) const spyC = jest.fn(returnThis) const spyD = jest.fn(returnThis) let ctx: any const Comp = { data() { return { foo: 1, bar: 2, baz: { qux: 3 }, qux: 4 } }, watch: { // string method name foo: 'onFooChange', // direct function bar: spyB, baz: { handler: spyC, deep: true }, qux: { handler: 'onQuxChange' } }, methods: { onFooChange: spyA, onQuxChange: spyD }, render() { ctx = this } } const root = nodeOps.createElement('div') render(h(Comp), root) function assertCall(spy: jest.Mock, callIndex: number, args: any[]) { expect(spy.mock.calls[callIndex].slice(0, 2)).toMatchObject(args) expect(spy).toHaveReturnedWith(ctx) } ctx.foo++ await nextTick() expect(spyA).toHaveBeenCalledTimes(1) assertCall(spyA, 0, [2, 1]) ctx.bar++ await nextTick() expect(spyB).toHaveBeenCalledTimes(1) assertCall(spyB, 0, [3, 2]) ctx.baz.qux++ await nextTick() expect(spyC).toHaveBeenCalledTimes(1) // new and old objects have same identity assertCall(spyC, 0, [{ qux: 4 }, { qux: 4 }]) ctx.qux++ await nextTick() expect(spyD).toHaveBeenCalledTimes(1) assertCall(spyD, 0, [5, 4]) }) test('watch array', async () => { function returnThis(this: any) { return this } const spyA = jest.fn(returnThis) const spyB = jest.fn(returnThis) const spyC = jest.fn(returnThis) let ctx: any const Comp = { data() { return { foo: 1, bar: 2, baz: { qux: 3 } } }, watch: { // string method name foo: ['onFooChange'], // direct function bar: [spyB], baz: [ { handler: spyC, deep: true } ] }, methods: { onFooChange: spyA }, render() { ctx = this } } const root = nodeOps.createElement('div') render(h(Comp), root) function assertCall(spy: jest.Mock, callIndex: number, args: any[]) { expect(spy.mock.calls[callIndex].slice(0, 2)).toMatchObject(args) expect(spy).toHaveReturnedWith(ctx) } ctx.foo++ await nextTick() expect(spyA).toHaveBeenCalledTimes(1) assertCall(spyA, 0, [2, 1]) ctx.bar++ await nextTick() expect(spyB).toHaveBeenCalledTimes(1) assertCall(spyB, 0, [3, 2]) ctx.baz.qux++ await nextTick() expect(spyC).toHaveBeenCalledTimes(1) // new and old objects have same identity assertCall(spyC, 0, [{ qux: 4 }, { qux: 4 }]) }) test('provide/inject', () => { const Root = defineComponent({ data() { return { a: 1 } }, provide() { return { a: this.a } }, render() { return [h(ChildA), h(ChildB), h(ChildC), h(ChildD), h(ChildE)] } }) const defineChild = (injectOptions: any, injectedKey = 'b') => ({ inject: injectOptions, render() { return this[injectedKey] } } as any) const ChildA = defineChild(['a'], 'a') const ChildB = defineChild({ b: 'a' }) const ChildC = defineChild({ b: { from: 'a' } }) const ChildD = defineChild({ b: { from: 'c', default: 2 } }) const ChildE = defineChild({ b: { from: 'c', default: () => 3 } }) expect(renderToString(h(Root))).toBe(`11123`) }) test('lifecycle', async () => { const count = ref(0) const root = nodeOps.createElement('div') const calls: string[] = [] const Root = { beforeCreate() { calls.push('root beforeCreate') }, created() { calls.push('root created') }, beforeMount() { calls.push('root onBeforeMount') }, mounted() { calls.push('root onMounted') }, beforeUpdate() { calls.push('root onBeforeUpdate') }, updated() { calls.push('root onUpdated') }, beforeUnmount() { calls.push('root onBeforeUnmount') }, unmounted() { calls.push('root onUnmounted') }, render() { return h(Mid, { count: count.value }) } } const Mid = { beforeCreate() { calls.push('mid beforeCreate') }, created() { calls.push('mid created') }, beforeMount() { calls.push('mid onBeforeMount') }, mounted() { calls.push('mid onMounted') }, beforeUpdate() { calls.push('mid onBeforeUpdate') }, updated() { calls.push('mid onUpdated') }, beforeUnmount() { calls.push('mid onBeforeUnmount') }, unmounted() { calls.push('mid onUnmounted') }, render(this: any) { return h(Child, { count: this.$props.count }) } } const Child = { beforeCreate() { calls.push('child beforeCreate') }, created() { calls.push('child created') }, beforeMount() { calls.push('child onBeforeMount') }, mounted() { calls.push('child onMounted') }, beforeUpdate() { calls.push('child onBeforeUpdate') }, updated() { calls.push('child onUpdated') }, beforeUnmount() { calls.push('child onBeforeUnmount') }, unmounted() { calls.push('child onUnmounted') }, render(this: any) { return h('div', this.$props.count) } } // mount render(h(Root), root) expect(calls).toEqual([ 'root beforeCreate', 'root created', 'root onBeforeMount', 'mid beforeCreate', 'mid created', 'mid onBeforeMount', 'child beforeCreate', 'child created', 'child onBeforeMount', 'child onMounted', 'mid onMounted', 'root onMounted' ]) calls.length = 0 // update count.value++ await nextTick() expect(calls).toEqual([ 'root onBeforeUpdate', 'mid onBeforeUpdate', 'child onBeforeUpdate', 'child onUpdated', 'mid onUpdated', 'root onUpdated' ]) calls.length = 0 // unmount render(null, root) expect(calls).toEqual([ 'root onBeforeUnmount', 'mid onBeforeUnmount', 'child onBeforeUnmount', 'child onUnmounted', 'mid onUnmounted', 'root onUnmounted' ]) }) test('mixins', () => { const calls: string[] = [] const mixinA = { data() { return { a: 1 } }, created(this: any) { calls.push('mixinA created') expect(this.a).toBe(1) expect(this.b).toBe(2) expect(this.c).toBe(4) }, mounted() { calls.push('mixinA mounted') } } const mixinB = { props: { bP: { type: String } }, data() { return { b: 2 } }, created(this: any) { calls.push('mixinB created') expect(this.a).toBe(1) expect(this.b).toBe(2) expect(this.bP).toBeUndefined() expect(this.c).toBe(4) expect(this.cP1).toBeUndefined() }, mounted() { calls.push('mixinB mounted') } } const mixinC = defineComponent({ props: ['cP1', 'cP2'], data() { return { c: 3 } }, created() { calls.push('mixinC created') // component data() should overwrite mixin field with same key expect(this.c).toBe(4) expect(this.cP1).toBeUndefined() }, mounted() { calls.push('mixinC mounted') } }) const Comp = defineComponent({ props: { aaa: String }, mixins: [defineComponent(mixinA), defineComponent(mixinB), mixinC], data() { return { c: 4, z: 4 } }, created() { calls.push('comp created') expect(this.a).toBe(1) expect(this.b).toBe(2) expect(this.bP).toBeUndefined() expect(this.c).toBe(4) expect(this.cP2).toBeUndefined() expect(this.z).toBe(4) }, mounted() { calls.push('comp mounted') }, render() { return `${this.a}${this.b}${this.c}` } }) expect(renderToString(h(Comp))).toBe(`124`) expect(calls).toEqual([ 'mixinA created', 'mixinB created', 'mixinC created', 'comp created', 'mixinA mounted', 'mixinB mounted', 'mixinC mounted', 'comp mounted' ]) }) test('render from mixin', () => { const Comp = { mixins: [ { render: () => 'from mixin' } ] } expect(renderToString(h(Comp))).toBe('from mixin') }) test('extends', () => { const calls: string[] = [] const Base = { data() { return { a: 1, b: 1 } }, methods: { sayA() {} }, mounted(this: any) { expect(this.a).toBe(1) expect(this.b).toBe(2) calls.push('base') } } const Comp = defineComponent({ extends: defineComponent(Base), data() { return { b: 2 } }, mounted() { calls.push('comp') }, render() { return `${this.a}${this.b}` } }) expect(renderToString(h(Comp))).toBe(`12`) expect(calls).toEqual(['base', 'comp']) }) test('extends with mixins', () => { const calls: string[] = [] const Base = { data() { return { a: 1, x: 'base' } }, methods: { sayA() {} }, mounted(this: any) { expect(this.a).toBe(1) expect(this.b).toBeTruthy() expect(this.c).toBe(2) calls.push('base') } } const Mixin = { data() { return { b: true, x: 'mixin' } }, mounted(this: any) { expect(this.a).toBe(1) expect(this.b).toBeTruthy() expect(this.c).toBe(2) calls.push('mixin') } } const Comp = defineComponent({ extends: defineComponent(Base), mixins: [defineComponent(Mixin)], data() { return { c: 2 } }, mounted() { calls.push('comp') }, render() { return `${this.a}${this.b}${this.c}${this.x}` } }) expect(renderToString(h(Comp))).toBe(`1true2mixin`) expect(calls).toEqual(['base', 'mixin', 'comp']) }) test('beforeCreate/created in extends and mixins', () => { const calls: string[] = [] const BaseA = { beforeCreate() { calls.push('beforeCreateA') }, created() { calls.push('createdA') } } const BaseB = { extends: BaseA, beforeCreate() { calls.push('beforeCreateB') }, created() { calls.push('createdB') } } const MixinA = { beforeCreate() { calls.push('beforeCreateC') }, created() { calls.push('createdC') } } const MixinB = { mixins: [MixinA], beforeCreate() { calls.push('beforeCreateD') }, created() { calls.push('createdD') } } const Comp = { extends: BaseB, mixins: [MixinB], beforeCreate() { calls.push('selfBeforeCreate') }, created() { calls.push('selfCreated') }, render() {} } renderToString(h(Comp)) expect(calls).toEqual([ 'beforeCreateA', 'beforeCreateB', 'beforeCreateC', 'beforeCreateD', 'selfBeforeCreate', 'createdA', 'createdB', 'createdC', 'createdD', 'selfCreated' ]) }) test('flatten merged options', async () => { const MixinBase = { msg1: 'base' } const ExtendsBase = { msg2: 'base' } const Mixin = { mixins: [MixinBase] } const Extends = { extends: ExtendsBase } const Comp = defineComponent({ extends: defineComponent(Extends), mixins: [defineComponent(Mixin)], render() { return `${this.$options.msg1},${this.$options.msg2}` } }) expect(renderToString(h(Comp))).toBe('base,base') }) test('options defined in component have higher priority', async () => { const Mixin = { msg1: 'base' } const Extends = { msg2: 'base' } const Comp = defineComponent({ msg1: 'local', msg2: 'local', extends: defineComponent(Extends), mixins: [defineComponent(Mixin)], render() { return `${this.$options.msg1},${this.$options.msg2}` } }) expect(renderToString(h(Comp))).toBe('local,local') }) test('accessing setup() state from options', async () => { const Comp = defineComponent({ setup() { return { count: ref(0) } }, data() { return { plusOne: (this as any).count + 1 } }, computed: { plusTwo(): number { return this.count + 2 } }, methods: { inc() { this.count++ } }, render() { return h( 'div', { onClick: this.inc }, `${this.count},${this.plusOne},${this.plusTwo}` ) } }) const root = nodeOps.createElement('div') render(h(Comp), root) expect(serializeInner(root)).toBe(`<div>0,1,2</div>`) triggerEvent(root.children[0] as TestElement, 'click') await nextTick() expect(serializeInner(root)).toBe(`<div>1,1,3</div>`) }) // #1016 test('watcher initialization should be deferred in mixins', async () => { const mixin1 = { data() { return { mixin1Data: 'mixin1' } }, methods: {} } const watchSpy = jest.fn() const mixin2 = { watch: { mixin3Data: watchSpy } } const mixin3 = { data() { return { mixin3Data: 'mixin3' } }, methods: {} } let vm: any const Comp = { mixins: [mixin1, mixin2, mixin3], render() {}, created() { vm = this } } const root = nodeOps.createElement('div') render(h(Comp), root) // should have no warnings vm.mixin3Data = 'hello' await nextTick() expect(watchSpy.mock.calls[0].slice(0, 2)).toEqual(['hello', 'mixin3']) }) describe('warnings', () => { test('Expected a function as watch handler', () => { const Comp = { watch: { foo: 'notExistingMethod', foo2: { handler: 'notExistingMethod2' } }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( 'Invalid watch handler specified by key "notExistingMethod"' ).toHaveBeenWarned() expect( 'Invalid watch handler specified by key "notExistingMethod2"' ).toHaveBeenWarned() }) test('Invalid watch option', () => { const Comp = { watch: { foo: true }, render() {} } const root = nodeOps.createElement('div') // @ts-ignore render(h(Comp), root) expect('Invalid watch option: "foo"').toHaveBeenWarned() }) test('computed with setter and no getter', () => { const Comp = { computed: { foo: { set() {} } }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect('Computed property "foo" has no getter.').toHaveBeenWarned() }) test('assigning to computed with no setter', () => { let instance: any const Comp = { computed: { foo: { get() {} } }, mounted() { instance = this }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) instance.foo = 1 expect( 'Write operation failed: computed property "foo" is readonly' ).toHaveBeenWarned() }) test('inject property is already declared in props', () => { const Comp = { data() { return { a: 1 } }, provide() { return { a: this.a } }, render() { return [h(ChildA)] } } as any const ChildA = { props: { a: Number }, inject: ['a'], render() { return this.a } } as any const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Inject property "a" is already defined in Props.` ).toHaveBeenWarned() }) test('methods property is not a function', () => { const Comp = { methods: { foo: 1 }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Method "foo" has type "number" in the component definition. ` + `Did you reference the function correctly?` ).toHaveBeenWarned() }) test('methods property is already declared in props', () => { const Comp = { props: { foo: Number }, methods: { foo() {} }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Methods property "foo" is already defined in Props.` ).toHaveBeenWarned() }) test('methods property is already declared in inject', () => { const Comp = { data() { return { a: 1 } }, provide() { return { a: this.a } }, render() { return [h(ChildA)] } } as any const ChildA = { methods: { a: () => null }, inject: ['a'], render() { return this.a } } as any const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Methods property "a" is already defined in Inject.` ).toHaveBeenWarned() }) test('data property is already declared in props', () => { const Comp = { props: { foo: Number }, data: () => ({ foo: 1 }), render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Data property "foo" is already defined in Props.` ).toHaveBeenWarned() }) test('data property is already declared in inject', () => { const Comp = { data() { return { a: 1 } }, provide() { return { a: this.a } }, render() { return [h(ChildA)] } } as any const ChildA = { data() { return { a: 1 } }, inject: ['a'], render() { return this.a } } as any const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Data property "a" is already defined in Inject.` ).toHaveBeenWarned() }) test('data property is already declared in methods', () => { const Comp = { data: () => ({ foo: 1 }), methods: { foo() {} }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Data property "foo" is already defined in Methods.` ).toHaveBeenWarned() }) test('computed property is already declared in props', () => { const Comp = { props: { foo: Number }, computed: { foo() {} }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Computed property "foo" is already defined in Props.` ).toHaveBeenWarned() }) test('computed property is already declared in inject', () => { const Comp = { data() { return { a: 1 } }, provide() { return { a: this.a } }, render() { return [h(ChildA)] } } as any const ChildA = { computed: { a: { get() {}, set() {} } }, inject: ['a'], render() { return this.a } } as any const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Computed property "a" is already defined in Inject.` ).toHaveBeenWarned() }) test('computed property is already declared in methods', () => { const Comp = { computed: { foo() {} }, methods: { foo() {} }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Computed property "foo" is already defined in Methods.` ).toHaveBeenWarned() }) test('computed property is already declared in data', () => { const Comp = { data: () => ({ foo: 1 }), computed: { foo() {} }, render() {} } const root = nodeOps.createElement('div') render(h(Comp), root) expect( `Computed property "foo" is already defined in Data.` ).toHaveBeenWarned() }) }) })
packages/runtime-core/__tests__/apiOptions.spec.ts
1
https://github.com/vuejs/core/commit/313dd06065b1782d67f6881fbd42ae92a7f9cade
[ 0.003971594385802746, 0.0002960788260679692, 0.00016335905820596963, 0.00017133334768004715, 0.0005121633876115084 ]
{ "id": 5, "code_window": [ " for (const key in injectOptions) {\n", " const opt = injectOptions[key]\n", " if (isObject(opt)) {\n", " ctx[key] = inject(\n", " opt.from,\n", " opt.default,\n", " true /* treat default function as factory */\n", " )\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " opt.from || key,\n" ], "file_path": "packages/runtime-core/src/componentOptions.ts", "type": "replace", "edit_start_line_idx": 462 }
import { toRaw, shallowReactive, trigger, TriggerOpTypes } from '@vue/reactivity' import { EMPTY_OBJ, camelize, hyphenate, capitalize, isString, isFunction, isArray, isObject, hasOwn, toRawType, PatchFlags, makeMap, isReservedProp, EMPTY_ARR, def, extend } from '@vue/shared' import { warn } from './warning' import { Data, ComponentInternalInstance, ComponentOptions, ConcreteComponent } from './component' import { isEmitListener } from './componentEmits' import { InternalObjectKey } from './vnode' import { AppContext } from './apiCreateApp' export type ComponentPropsOptions<P = Data> = | ComponentObjectPropsOptions<P> | string[] export type ComponentObjectPropsOptions<P = Data> = { [K in keyof P]: Prop<P[K]> | null } export type Prop<T, D = T> = PropOptions<T, D> | PropType<T> type DefaultFactory<T> = (props: Data) => T | null | undefined interface PropOptions<T = any, D = T> { type?: PropType<T> | true | null required?: boolean default?: D | DefaultFactory<D> | null | undefined | object validator?(value: unknown): boolean } export type PropType<T> = PropConstructor<T> | PropConstructor<T>[] type PropConstructor<T = any> = | { new (...args: any[]): T & object } | { (): T } | PropMethod<T> type PropMethod<T, TConstructor = any> = T extends (...args: any) => any // if is function with args ? { new (): TConstructor; (): T; readonly prototype: TConstructor } // Create Function like constructor : never type RequiredKeys<T, MakeDefaultRequired> = { [K in keyof T]: T[K] extends | { required: true } | (MakeDefaultRequired extends true ? { default: any } : never) ? K : never }[keyof T] type OptionalKeys<T, MakeDefaultRequired> = Exclude< keyof T, RequiredKeys<T, MakeDefaultRequired> > type InferPropType<T> = T extends null ? any // null & true would fail to infer : T extends { type: null | true } ? any // As TS issue https://github.com/Microsoft/TypeScript/issues/14829 // somehow `ObjectConstructor` when inferred from { (): T } becomes `any` // `BooleanConstructor` when inferred from PropConstructor(with PropMethod) becomes `Boolean` : T extends ObjectConstructor | { type: ObjectConstructor } ? Record<string, any> : T extends BooleanConstructor | { type: BooleanConstructor } ? boolean : T extends Prop<infer V, infer D> ? (unknown extends V ? D : V) : T export type ExtractPropTypes< O, MakeDefaultRequired extends boolean = true > = O extends object ? { [K in RequiredKeys<O, MakeDefaultRequired>]: InferPropType<O[K]> } & { [K in OptionalKeys<O, MakeDefaultRequired>]?: InferPropType<O[K]> } : { [K in string]: any } const enum BooleanFlags { shouldCast, shouldCastTrue } type NormalizedProp = | null | (PropOptions & { [BooleanFlags.shouldCast]?: boolean [BooleanFlags.shouldCastTrue]?: boolean }) // normalized value is a tuple of the actual normalized options // and an array of prop keys that need value casting (booleans and defaults) export type NormalizedProps = Record<string, NormalizedProp> export type NormalizedPropsOptions = [NormalizedProps, string[]] | [] export function initProps( instance: ComponentInternalInstance, rawProps: Data | null, isStateful: number, // result of bitwise flag comparison isSSR = false ) { const props: Data = {} const attrs: Data = {} def(attrs, InternalObjectKey, 1) setFullProps(instance, rawProps, props, attrs) // validation if (__DEV__) { validateProps(props, instance) } if (isStateful) { // stateful instance.props = isSSR ? props : shallowReactive(props) } else { if (!instance.type.props) { // functional w/ optional props, props === attrs instance.props = attrs } else { // functional w/ declared props instance.props = props } } instance.attrs = attrs } export function updateProps( instance: ComponentInternalInstance, rawProps: Data | null, rawPrevProps: Data | null, optimized: boolean ) { const { props, attrs, vnode: { patchFlag } } = instance const rawCurrentProps = toRaw(props) const [options] = instance.propsOptions if ( // always force full diff if hmr is enabled !(__DEV__ && instance.type.__hmrId) && (optimized || patchFlag > 0) && !(patchFlag & PatchFlags.FULL_PROPS) ) { if (patchFlag & PatchFlags.PROPS) { // Compiler-generated props & no keys change, just set the updated // the props. const propsToUpdate = instance.vnode.dynamicProps! for (let i = 0; i < propsToUpdate.length; i++) { const key = propsToUpdate[i] // PROPS flag guarantees rawProps to be non-null const value = rawProps![key] if (options) { // attr / props separation was done on init and will be consistent // in this code path, so just check if attrs have it. if (hasOwn(attrs, key)) { attrs[key] = value } else { const camelizedKey = camelize(key) props[camelizedKey] = resolvePropValue( options, rawCurrentProps, camelizedKey, value ) } } else { attrs[key] = value } } } } else { // full props update. setFullProps(instance, rawProps, props, attrs) // in case of dynamic props, check if we need to delete keys from // the props object let kebabKey: string for (const key in rawCurrentProps) { if ( !rawProps || // for camelCase (!hasOwn(rawProps, key) && // it's possible the original props was passed in as kebab-case // and converted to camelCase (#955) ((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey))) ) { if (options) { if ( rawPrevProps && // for camelCase (rawPrevProps[key] !== undefined || // for kebab-case rawPrevProps[kebabKey!] !== undefined) ) { props[key] = resolvePropValue( options, rawProps || EMPTY_OBJ, key, undefined ) } } else { delete props[key] } } } // in the case of functional component w/o props declaration, props and // attrs point to the same object so it should already have been updated. if (attrs !== rawCurrentProps) { for (const key in attrs) { if (!rawProps || !hasOwn(rawProps, key)) { delete attrs[key] } } } } // trigger updates for $attrs in case it's used in component slots trigger(instance, TriggerOpTypes.SET, '$attrs') if (__DEV__ && rawProps) { validateProps(props, instance) } } function setFullProps( instance: ComponentInternalInstance, rawProps: Data | null, props: Data, attrs: Data ) { const [options, needCastKeys] = instance.propsOptions if (rawProps) { for (const key in rawProps) { const value = rawProps[key] // key, ref are reserved and never passed down if (isReservedProp(key)) { continue } // prop option names are camelized during normalization, so to support // kebab -> camel conversion here we need to camelize the key. let camelKey if (options && hasOwn(options, (camelKey = camelize(key)))) { props[camelKey] = value } else if (!isEmitListener(instance.emitsOptions, key)) { // Any non-declared (either as a prop or an emitted event) props are put // into a separate `attrs` object for spreading. Make sure to preserve // original key casing attrs[key] = value } } } if (needCastKeys) { const rawCurrentProps = toRaw(props) for (let i = 0; i < needCastKeys.length; i++) { const key = needCastKeys[i] props[key] = resolvePropValue( options!, rawCurrentProps, key, rawCurrentProps[key] ) } } } function resolvePropValue( options: NormalizedProps, props: Data, key: string, value: unknown ) { const opt = options[key] if (opt != null) { const hasDefault = hasOwn(opt, 'default') // default values if (hasDefault && value === undefined) { const defaultValue = opt.default value = opt.type !== Function && isFunction(defaultValue) ? defaultValue(props) : defaultValue } // boolean casting if (opt[BooleanFlags.shouldCast]) { if (!hasOwn(props, key) && !hasDefault) { value = false } else if ( opt[BooleanFlags.shouldCastTrue] && (value === '' || value === hyphenate(key)) ) { value = true } } } return value } export function normalizePropsOptions( comp: ConcreteComponent, appContext: AppContext, asMixin = false ): NormalizedPropsOptions { const appId = appContext.app ? appContext.app._uid : -1 const cache = comp.__props || (comp.__props = {}) const cached = cache[appId] if (cached) { return cached } const raw = comp.props const normalized: NormalizedPropsOptions[0] = {} const needCastKeys: NormalizedPropsOptions[1] = [] // apply mixin/extends props let hasExtends = false if (__FEATURE_OPTIONS_API__ && !isFunction(comp)) { const extendProps = (raw: ComponentOptions) => { hasExtends = true const [props, keys] = normalizePropsOptions(raw, appContext, true) extend(normalized, props) if (keys) needCastKeys.push(...keys) } if (!asMixin && appContext.mixins.length) { appContext.mixins.forEach(extendProps) } if (comp.extends) { extendProps(comp.extends) } if (comp.mixins) { comp.mixins.forEach(extendProps) } } if (!raw && !hasExtends) { return (cache[appId] = EMPTY_ARR) } if (isArray(raw)) { for (let i = 0; i < raw.length; i++) { if (__DEV__ && !isString(raw[i])) { warn(`props must be strings when using array syntax.`, raw[i]) } const normalizedKey = camelize(raw[i]) if (validatePropName(normalizedKey)) { normalized[normalizedKey] = EMPTY_OBJ } } } else if (raw) { if (__DEV__ && !isObject(raw)) { warn(`invalid props options`, raw) } for (const key in raw) { const normalizedKey = camelize(key) if (validatePropName(normalizedKey)) { const opt = raw[key] const prop: NormalizedProp = (normalized[normalizedKey] = isArray(opt) || isFunction(opt) ? { type: opt } : opt) if (prop) { const booleanIndex = getTypeIndex(Boolean, prop.type) const stringIndex = getTypeIndex(String, prop.type) prop[BooleanFlags.shouldCast] = booleanIndex > -1 prop[BooleanFlags.shouldCastTrue] = stringIndex < 0 || booleanIndex < stringIndex // if the prop needs boolean casting or default value if (booleanIndex > -1 || hasOwn(prop, 'default')) { needCastKeys.push(normalizedKey) } } } } } return (cache[appId] = [normalized, needCastKeys]) } // use function string name to check type constructors // so that it works across vms / iframes. function getType(ctor: Prop<any>): string { const match = ctor && ctor.toString().match(/^\s*function (\w+)/) return match ? match[1] : '' } function isSameType(a: Prop<any>, b: Prop<any>): boolean { return getType(a) === getType(b) } function getTypeIndex( type: Prop<any>, expectedTypes: PropType<any> | void | null | true ): number { if (isArray(expectedTypes)) { for (let i = 0, len = expectedTypes.length; i < len; i++) { if (isSameType(expectedTypes[i], type)) { return i } } } else if (isFunction(expectedTypes)) { return isSameType(expectedTypes, type) ? 0 : -1 } return -1 } /** * dev only */ function validateProps(props: Data, instance: ComponentInternalInstance) { const rawValues = toRaw(props) const options = instance.propsOptions[0] for (const key in options) { let opt = options[key] if (opt == null) continue validateProp(key, rawValues[key], opt, !hasOwn(rawValues, key)) } } /** * dev only */ function validatePropName(key: string) { if (key[0] !== '$') { return true } else if (__DEV__) { warn(`Invalid prop name: "${key}" is a reserved property.`) } return false } /** * dev only */ function validateProp( name: string, value: unknown, prop: PropOptions, isAbsent: boolean ) { const { type, required, validator } = prop // required! if (required && isAbsent) { warn('Missing required prop: "' + name + '"') return } // missing but optional if (value == null && !prop.required) { return } // type check if (type != null && type !== true) { let isValid = false const types = isArray(type) ? type : [type] const expectedTypes = [] // value is valid as long as one of the specified types match for (let i = 0; i < types.length && !isValid; i++) { const { valid, expectedType } = assertType(value, types[i]) expectedTypes.push(expectedType || '') isValid = valid } if (!isValid) { warn(getInvalidTypeMessage(name, value, expectedTypes)) return } } // custom validator if (validator && !validator(value)) { warn('Invalid prop: custom validator check failed for prop "' + name + '".') } } const isSimpleType = /*#__PURE__*/ makeMap( 'String,Number,Boolean,Function,Symbol' ) type AssertionResult = { valid: boolean expectedType: string } /** * dev only */ function assertType(value: unknown, type: PropConstructor): AssertionResult { let valid const expectedType = getType(type) if (isSimpleType(expectedType)) { const t = typeof value valid = t === expectedType.toLowerCase() // for primitive wrapper objects if (!valid && t === 'object') { valid = value instanceof type } } else if (expectedType === 'Object') { valid = isObject(value) } else if (expectedType === 'Array') { valid = isArray(value) } else { valid = value instanceof type } return { valid, expectedType } } /** * dev only */ function getInvalidTypeMessage( name: string, value: unknown, expectedTypes: string[] ): string { let message = `Invalid prop: type check failed for prop "${name}".` + ` Expected ${expectedTypes.map(capitalize).join(', ')}` const expectedType = expectedTypes[0] const receivedType = toRawType(value) const expectedValue = styleValue(value, expectedType) const receivedValue = styleValue(value, receivedType) // check if we need to specify expected value if ( expectedTypes.length === 1 && isExplicable(expectedType) && !isBoolean(expectedType, receivedType) ) { message += ` with value ${expectedValue}` } message += `, got ${receivedType} ` // check if we need to specify received value if (isExplicable(receivedType)) { message += `with value ${receivedValue}.` } return message } /** * dev only */ function styleValue(value: unknown, type: string): string { if (type === 'String') { return `"${value}"` } else if (type === 'Number') { return `${Number(value)}` } else { return `${value}` } } /** * dev only */ function isExplicable(type: string): boolean { const explicitTypes = ['string', 'number', 'boolean'] return explicitTypes.some(elem => type.toLowerCase() === elem) } /** * dev only */ function isBoolean(...args: string[]): boolean { return args.some(elem => elem.toLowerCase() === 'boolean') }
packages/runtime-core/src/componentProps.ts
0
https://github.com/vuejs/core/commit/313dd06065b1782d67f6881fbd42ae92a7f9cade
[ 0.9500922560691833, 0.020269591361284256, 0.00016370287630707026, 0.00017268414376303554, 0.12321291118860245 ]
{ "id": 5, "code_window": [ " for (const key in injectOptions) {\n", " const opt = injectOptions[key]\n", " if (isObject(opt)) {\n", " ctx[key] = inject(\n", " opt.from,\n", " opt.default,\n", " true /* treat default function as factory */\n", " )\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " opt.from || key,\n" ], "file_path": "packages/runtime-core/src/componentOptions.ts", "type": "replace", "edit_start_line_idx": 462 }
const args = require('minimist')(process.argv.slice(2)) const fs = require('fs') const path = require('path') const chalk = require('chalk') const semver = require('semver') const currentVersion = require('../package.json').version const { prompt } = require('enquirer') const execa = require('execa') const preId = args.preid || semver.prerelease(currentVersion)[0] || 'alpha' const isDryRun = args.dry const skipTests = args.skipTests const skipBuild = args.skipBuild const packages = fs .readdirSync(path.resolve(__dirname, '../packages')) .filter(p => !p.endsWith('.ts') && !p.startsWith('.')) const skippedPackages = [] const versionIncrements = [ 'patch', 'minor', 'major', 'prepatch', 'preminor', 'premajor', 'prerelease' ] const inc = i => semver.inc(currentVersion, i, preId) const bin = name => path.resolve(__dirname, '../node_modules/.bin/' + name) const run = (bin, args, opts = {}) => execa(bin, args, { stdio: 'inherit', ...opts }) const dryRun = (bin, args, opts = {}) => console.log(chalk.blue(`[dryrun] ${bin} ${args.join(' ')}`), opts) const runIfNotDry = isDryRun ? dryRun : run const getPkgRoot = pkg => path.resolve(__dirname, '../packages/' + pkg) const step = msg => console.log(chalk.cyan(msg)) async function main() { let targetVersion = args._[0] if (!targetVersion) { // no explicit version, offer suggestions const { release } = await prompt({ type: 'select', name: 'release', message: 'Select release type', choices: versionIncrements.map(i => `${i} (${inc(i)})`).concat(['custom']) }) if (release === 'custom') { targetVersion = (await prompt({ type: 'input', name: 'version', message: 'Input custom version', initial: currentVersion })).version } else { targetVersion = release.match(/\((.*)\)/)[1] } } if (!semver.valid(targetVersion)) { throw new Error(`invalid target version: ${targetVersion}`) } const { yes } = await prompt({ type: 'confirm', name: 'yes', message: `Releasing v${targetVersion}. Confirm?` }) if (!yes) { return } // run tests before release step('\nRunning tests...') if (!skipTests && !isDryRun) { await run(bin('jest'), ['--clearCache']) await run('yarn', ['test']) } else { console.log(`(skipped)`) } // update all package versions and inter-dependencies step('\nUpdating cross dependencies...') updateVersions(targetVersion) // build all packages with types step('\nBuilding all packages...') if (!skipBuild && !isDryRun) { await run('yarn', ['build', '--release']) // test generated dts files step('\nVerifying type declarations...') await run('yarn', ['test-dts-only']) } else { console.log(`(skipped)`) } // generate changelog await run(`yarn`, ['changelog']) const { stdout } = await run('git', ['diff'], { stdio: 'pipe' }) if (stdout) { step('\nCommitting changes...') await runIfNotDry('git', ['add', '-A']) await runIfNotDry('git', ['commit', '-m', `release: v${targetVersion}`]) } else { console.log('No changes to commit.') } // publish packages step('\nPublishing packages...') for (const pkg of packages) { await publishPackage(pkg, targetVersion, runIfNotDry) } // push to GitHub step('\nPushing to GitHub...') await runIfNotDry('git', ['tag', `v${targetVersion}`]) await runIfNotDry('git', ['push', 'origin', `refs/tags/v${targetVersion}`]) await runIfNotDry('git', ['push']) if (isDryRun) { console.log(`\nDry run finished - run git diff to see package changes.`) } if (skippedPackages.length) { console.log( chalk.yellow( `The following packages are skipped and NOT published:\n- ${skippedPackages.join( '\n- ' )}` ) ) } console.log() } function updateVersions(version) { // 1. update root package.json updatePackage(path.resolve(__dirname, '..'), version) // 2. update all packages packages.forEach(p => updatePackage(getPkgRoot(p), version)) } function updatePackage(pkgRoot, version) { const pkgPath = path.resolve(pkgRoot, 'package.json') const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')) pkg.version = version updateDeps(pkg, 'dependencies', version) updateDeps(pkg, 'peerDependencies', version) fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n') } function updateDeps(pkg, depType, version) { const deps = pkg[depType] if (!deps) return Object.keys(deps).forEach(dep => { if ( dep === 'vue' || (dep.startsWith('@vue') && packages.includes(dep.replace(/^@vue\//, ''))) ) { console.log( chalk.yellow(`${pkg.name} -> ${depType} -> ${dep}@${version}`) ) deps[dep] = version } }) } async function publishPackage(pkgName, version, runIfNotDry) { if (skippedPackages.includes(pkgName)) { return } const pkgRoot = getPkgRoot(pkgName) const pkgPath = path.resolve(pkgRoot, 'package.json') const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')) if (pkg.private) { return } // for now (alpha/beta phase), every package except "vue" can be published as // `latest`, whereas "vue" will be published under the "next" tag. const releaseTag = pkgName === 'vue' ? 'next' : null // TODO use inferred release channel after official 3.0 release // const releaseTag = semver.prerelease(version)[0] || null step(`Publishing ${pkgName}...`) try { await runIfNotDry( 'yarn', [ 'publish', '--new-version', version, ...(releaseTag ? ['--tag', releaseTag] : []), '--access', 'public' ], { cwd: pkgRoot, stdio: 'pipe' } ) console.log(chalk.green(`Successfully published ${pkgName}@${version}`)) } catch (e) { if (e.stderr.match(/previously published/)) { console.log(chalk.red(`Skipping already published: ${pkgName}`)) } else { throw e } } } main().catch(err => { console.error(err) })
scripts/release.js
0
https://github.com/vuejs/core/commit/313dd06065b1782d67f6881fbd42ae92a7f9cade
[ 0.00017834237951319665, 0.00017037807265296578, 0.0001642186543904245, 0.0001706344191916287, 0.0000035055716125498293 ]
{ "id": 5, "code_window": [ " for (const key in injectOptions) {\n", " const opt = injectOptions[key]\n", " if (isObject(opt)) {\n", " ctx[key] = inject(\n", " opt.from,\n", " opt.default,\n", " true /* treat default function as factory */\n", " )\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " opt.from || key,\n" ], "file_path": "packages/runtime-core/src/componentOptions.ts", "type": "replace", "edit_start_line_idx": 462 }
import { ref, nodeOps, h, render, nextTick, defineComponent, reactive, serializeInner } from '@vue/runtime-test' // reference: https://vue-composition-api-rfc.netlify.com/api.html#template-refs describe('api: template refs', () => { it('string ref mount', () => { const root = nodeOps.createElement('div') const el = ref(null) const Comp = { setup() { return { refKey: el } }, render() { return h('div', { ref: 'refKey' }) } } render(h(Comp), root) expect(el.value).toBe(root.children[0]) }) it('string ref update', async () => { const root = nodeOps.createElement('div') const fooEl = ref(null) const barEl = ref(null) const refKey = ref('foo') const Comp = { setup() { return { foo: fooEl, bar: barEl } }, render() { return h('div', { ref: refKey.value }) } } render(h(Comp), root) expect(fooEl.value).toBe(root.children[0]) expect(barEl.value).toBe(null) refKey.value = 'bar' await nextTick() expect(fooEl.value).toBe(null) expect(barEl.value).toBe(root.children[0]) }) it('string ref unmount', async () => { const root = nodeOps.createElement('div') const el = ref(null) const toggle = ref(true) const Comp = { setup() { return { refKey: el } }, render() { return toggle.value ? h('div', { ref: 'refKey' }) : null } } render(h(Comp), root) expect(el.value).toBe(root.children[0]) toggle.value = false await nextTick() expect(el.value).toBe(null) }) it('function ref mount', () => { const root = nodeOps.createElement('div') const fn = jest.fn() const Comp = defineComponent(() => () => h('div', { ref: fn })) render(h(Comp), root) expect(fn.mock.calls[0][0]).toBe(root.children[0]) }) it('function ref update', async () => { const root = nodeOps.createElement('div') const fn1 = jest.fn() const fn2 = jest.fn() const fn = ref(fn1) const Comp = defineComponent(() => () => h('div', { ref: fn.value })) render(h(Comp), root) expect(fn1.mock.calls).toHaveLength(1) expect(fn1.mock.calls[0][0]).toBe(root.children[0]) expect(fn2.mock.calls).toHaveLength(0) fn.value = fn2 await nextTick() expect(fn1.mock.calls).toHaveLength(1) expect(fn2.mock.calls).toHaveLength(1) expect(fn2.mock.calls[0][0]).toBe(root.children[0]) }) it('function ref unmount', async () => { const root = nodeOps.createElement('div') const fn = jest.fn() const toggle = ref(true) const Comp = defineComponent(() => () => toggle.value ? h('div', { ref: fn }) : null ) render(h(Comp), root) expect(fn.mock.calls[0][0]).toBe(root.children[0]) toggle.value = false await nextTick() expect(fn.mock.calls[1][0]).toBe(null) }) it('render function ref mount', () => { const root = nodeOps.createElement('div') const el = ref(null) const Comp = { setup() { return () => h('div', { ref: el }) } } render(h(Comp), root) expect(el.value).toBe(root.children[0]) }) it('render function ref update', async () => { const root = nodeOps.createElement('div') const refs = { foo: ref(null), bar: ref(null) } const refKey = ref<keyof typeof refs>('foo') const Comp = { setup() { return () => h('div', { ref: refs[refKey.value] }) } } render(h(Comp), root) expect(refs.foo.value).toBe(root.children[0]) expect(refs.bar.value).toBe(null) refKey.value = 'bar' await nextTick() expect(refs.foo.value).toBe(null) expect(refs.bar.value).toBe(root.children[0]) }) it('render function ref unmount', async () => { const root = nodeOps.createElement('div') const el = ref(null) const toggle = ref(true) const Comp = { setup() { return () => (toggle.value ? h('div', { ref: el }) : null) } } render(h(Comp), root) expect(el.value).toBe(root.children[0]) toggle.value = false await nextTick() expect(el.value).toBe(null) }) test('string ref inside slots', async () => { const root = nodeOps.createElement('div') const spy = jest.fn() const Child = { render(this: any) { return this.$slots.default() } } const Comp = { render() { return h(Child, () => { return h('div', { ref: 'foo' }) }) }, mounted(this: any) { spy(this.$refs.foo.tag) } } render(h(Comp), root) expect(spy).toHaveBeenCalledWith('div') }) it('should work with direct reactive property', () => { const root = nodeOps.createElement('div') const state = reactive({ refKey: null }) const Comp = { setup() { return state }, render() { return h('div', { ref: 'refKey' }) } } render(h(Comp), root) expect(state.refKey).toBe(root.children[0]) }) test('multiple root refs', () => { const root = nodeOps.createElement('div') const refKey1 = ref(null) const refKey2 = ref(null) const refKey3 = ref(null) const Comp = { setup() { return { refKey1, refKey2, refKey3 } }, render() { return [ h('div', { ref: 'refKey1' }), h('div', { ref: 'refKey2' }), h('div', { ref: 'refKey3' }) ] } } render(h(Comp), root) expect(refKey1.value).toBe(root.children[1]) expect(refKey2.value).toBe(root.children[2]) expect(refKey3.value).toBe(root.children[3]) }) // #1505 test('reactive template ref in the same template', async () => { const Comp = { setup() { const el = ref() return { el } }, render(this: any) { return h('div', { id: 'foo', ref: 'el' }, this.el && this.el.props.id) } } const root = nodeOps.createElement('div') render(h(Comp), root) // ref not ready on first render, but should queue an update immediately expect(serializeInner(root)).toBe(`<div id="foo"></div>`) await nextTick() // ref should be updated expect(serializeInner(root)).toBe(`<div id="foo">foo</div>`) }) // #1834 test('exchange refs', async () => { const refToggle = ref(false) const spy = jest.fn() const Comp = { render(this: any) { return [ h('p', { ref: refToggle.value ? 'foo' : 'bar' }), h('i', { ref: refToggle.value ? 'bar' : 'foo' }) ] }, mounted(this: any) { spy(this.$refs.foo.tag, this.$refs.bar.tag) }, updated(this: any) { spy(this.$refs.foo.tag, this.$refs.bar.tag) } } const root = nodeOps.createElement('div') render(h(Comp), root) expect(spy.mock.calls[0][0]).toBe('i') expect(spy.mock.calls[0][1]).toBe('p') refToggle.value = true await nextTick() expect(spy.mock.calls[1][0]).toBe('p') expect(spy.mock.calls[1][1]).toBe('i') }) // #1789 test('toggle the same ref to different elements', async () => { const refToggle = ref(false) const spy = jest.fn() const Comp = { render(this: any) { return refToggle.value ? h('p', { ref: 'foo' }) : h('i', { ref: 'foo' }) }, mounted(this: any) { spy(this.$refs.foo.tag) }, updated(this: any) { spy(this.$refs.foo.tag) } } const root = nodeOps.createElement('div') render(h(Comp), root) expect(spy.mock.calls[0][0]).toBe('i') refToggle.value = true await nextTick() expect(spy.mock.calls[1][0]).toBe('p') }) })
packages/runtime-core/__tests__/apiTemplateRef.spec.ts
0
https://github.com/vuejs/core/commit/313dd06065b1782d67f6881fbd42ae92a7f9cade
[ 0.00017773937724996358, 0.00017118545656558126, 0.00016332167433574796, 0.00017148534243460745, 0.0000030266642170317937 ]
{ "id": 0, "code_window": [ "export interface RefUnwrapBailTypes {}\n", "\n", "export type ShallowUnwrapRef<T> = {\n", " [K in keyof T]: T[K] extends Ref<infer V> ? V : T[K]\n", "}\n", "\n", "export type UnwrapRef<T> = T extends Ref<infer V>\n", " ? UnwrapRefSimple<V>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " [K in keyof T]: T[K] extends Ref<infer V>\n", " ? V\n", " : T[K] extends Ref<infer V> | undefined // if `V` is `unknown` that means it does not extend `Ref` and is undefined\n", " ? unknown extends V ? undefined : V | undefined\n", " : T[K]\n" ], "file_path": "packages/reactivity/src/ref.ts", "type": "replace", "edit_start_line_idx": 207 }
import { describe, Component, defineComponent, PropType, ref, Ref, expectError, expectType, ShallowUnwrapRef, FunctionalComponent, ComponentPublicInstance, toRefs } from './index' declare function extractComponentOptions<Props, RawBindings>( obj: Component<Props, RawBindings> ): { props: Props rawBindings: RawBindings setup: ShallowUnwrapRef<RawBindings> } describe('object props', () => { interface ExpectedProps { a?: number | undefined b: string e?: Function bb: string bbb: string cc?: string[] | undefined dd: { n: 1 } ee?: () => string ff?: (a: number, b: string) => { a: boolean } ccc?: string[] | undefined ddd: string[] eee: () => { a: string } fff: (a: number, b: string) => { a: boolean } hhh: boolean ggg: 'foo' | 'bar' ffff: (a: number, b: string) => { a: boolean } validated?: string object?: object } interface ExpectedRefs { a: Ref<number | undefined> b: Ref<string> e: Ref<Function | undefined> bb: Ref<string> bbb: Ref<string> cc: Ref<string[] | undefined> dd: Ref<{ n: 1 }> ee: Ref<(() => string) | undefined> ff: Ref<((a: number, b: string) => { a: boolean }) | undefined> ccc: Ref<string[] | undefined> ddd: Ref<string[]> eee: Ref<() => { a: string }> fff: Ref<(a: number, b: string) => { a: boolean }> hhh: Ref<boolean> ggg: Ref<'foo' | 'bar'> ffff: Ref<(a: number, b: string) => { a: boolean }> validated: Ref<string | undefined> object: Ref<object | undefined> } describe('defineComponent', () => { const MyComponent = defineComponent({ props: { a: Number, // required should make property non-void b: { type: String, required: true }, e: Function, // default value should infer type and make it non-void bb: { default: 'hello' }, bbb: { // Note: default function value requires arrow syntax + explicit // annotation default: (props: any) => (props.bb as string) || 'foo' }, // explicit type casting cc: Array as PropType<string[]>, // required + type casting dd: { type: Object as PropType<{ n: 1 }>, required: true }, // return type ee: Function as PropType<() => string>, // arguments + object return ff: Function as PropType<(a: number, b: string) => { a: boolean }>, // explicit type casting with constructor ccc: Array as () => string[], // required + contructor type casting ddd: { type: Array as () => string[], required: true }, // required + object return eee: { type: Function as PropType<() => { a: string }>, required: true }, // required + arguments + object return fff: { type: Function as PropType<(a: number, b: string) => { a: boolean }>, required: true }, hhh: { type: Boolean, required: true }, // default + type casting ggg: { type: String as PropType<'foo' | 'bar'>, default: 'foo' }, // default + function ffff: { type: Function as PropType<(a: number, b: string) => { a: boolean }>, default: (_a: number, _b: string) => ({ a: true }) }, validated: { type: String, // validator requires explicit annotation validator: (val: unknown) => val !== '' }, object: Object as PropType<object> }, setup(props) { const refs = toRefs(props) expectType<ExpectedRefs['a']>(refs.a) expectType<ExpectedRefs['b']>(refs.b) expectType<ExpectedRefs['e']>(refs.e) expectType<ExpectedRefs['bb']>(refs.bb) expectType<ExpectedRefs['bbb']>(refs.bbb) expectType<ExpectedRefs['cc']>(refs.cc) expectType<ExpectedRefs['dd']>(refs.dd) expectType<ExpectedRefs['ee']>(refs.ee) expectType<ExpectedRefs['ff']>(refs.ff) expectType<ExpectedRefs['ccc']>(refs.ccc) expectType<ExpectedRefs['ddd']>(refs.ddd) expectType<ExpectedRefs['eee']>(refs.eee) expectType<ExpectedRefs['fff']>(refs.fff) expectType<ExpectedRefs['hhh']>(refs.hhh) expectType<ExpectedRefs['ggg']>(refs.ggg) expectType<ExpectedRefs['ffff']>(refs.ffff) expectType<ExpectedRefs['validated']>(refs.validated) expectType<ExpectedRefs['object']>(refs.object) return { setupA: 1, setupB: ref(1), setupC: { a: ref(2) }, setupProps: props } } }) const { props, rawBindings, setup } = extractComponentOptions(MyComponent) // props expectType<ExpectedProps['a']>(props.a) expectType<ExpectedProps['b']>(props.b) expectType<ExpectedProps['e']>(props.e) expectType<ExpectedProps['bb']>(props.bb) expectType<ExpectedProps['bbb']>(props.bbb) expectType<ExpectedProps['cc']>(props.cc) expectType<ExpectedProps['dd']>(props.dd) expectType<ExpectedProps['ee']>(props.ee) expectType<ExpectedProps['ff']>(props.ff) expectType<ExpectedProps['ccc']>(props.ccc) expectType<ExpectedProps['ddd']>(props.ddd) expectType<ExpectedProps['eee']>(props.eee) expectType<ExpectedProps['fff']>(props.fff) expectType<ExpectedProps['hhh']>(props.hhh) expectType<ExpectedProps['ggg']>(props.ggg) expectType<ExpectedProps['ffff']>(props.ffff) expectType<ExpectedProps['validated']>(props.validated) expectType<ExpectedProps['object']>(props.object) // raw bindings expectType<Number>(rawBindings.setupA) expectType<Ref<Number>>(rawBindings.setupB) expectType<Ref<Number>>(rawBindings.setupC.a) expectType<Number>(rawBindings.setupA) // raw bindings props expectType<ExpectedProps['a']>(rawBindings.setupProps.a) expectType<ExpectedProps['b']>(rawBindings.setupProps.b) expectType<ExpectedProps['e']>(rawBindings.setupProps.e) expectType<ExpectedProps['bb']>(rawBindings.setupProps.bb) expectType<ExpectedProps['bbb']>(rawBindings.setupProps.bbb) expectType<ExpectedProps['cc']>(rawBindings.setupProps.cc) expectType<ExpectedProps['dd']>(rawBindings.setupProps.dd) expectType<ExpectedProps['ee']>(rawBindings.setupProps.ee) expectType<ExpectedProps['ff']>(rawBindings.setupProps.ff) expectType<ExpectedProps['ccc']>(rawBindings.setupProps.ccc) expectType<ExpectedProps['ddd']>(rawBindings.setupProps.ddd) expectType<ExpectedProps['eee']>(rawBindings.setupProps.eee) expectType<ExpectedProps['fff']>(rawBindings.setupProps.fff) expectType<ExpectedProps['hhh']>(rawBindings.setupProps.hhh) expectType<ExpectedProps['ggg']>(rawBindings.setupProps.ggg) expectType<ExpectedProps['ffff']>(rawBindings.setupProps.ffff) expectType<ExpectedProps['validated']>(rawBindings.setupProps.validated) // setup expectType<Number>(setup.setupA) expectType<Number>(setup.setupB) expectType<Ref<Number>>(setup.setupC.a) expectType<Number>(setup.setupA) // raw bindings props expectType<ExpectedProps['a']>(setup.setupProps.a) expectType<ExpectedProps['b']>(setup.setupProps.b) expectType<ExpectedProps['e']>(setup.setupProps.e) expectType<ExpectedProps['bb']>(setup.setupProps.bb) expectType<ExpectedProps['bbb']>(setup.setupProps.bbb) expectType<ExpectedProps['cc']>(setup.setupProps.cc) expectType<ExpectedProps['dd']>(setup.setupProps.dd) expectType<ExpectedProps['ee']>(setup.setupProps.ee) expectType<ExpectedProps['ff']>(setup.setupProps.ff) expectType<ExpectedProps['ccc']>(setup.setupProps.ccc) expectType<ExpectedProps['ddd']>(setup.setupProps.ddd) expectType<ExpectedProps['eee']>(setup.setupProps.eee) expectType<ExpectedProps['fff']>(setup.setupProps.fff) expectType<ExpectedProps['hhh']>(setup.setupProps.hhh) expectType<ExpectedProps['ggg']>(setup.setupProps.ggg) expectType<ExpectedProps['ffff']>(setup.setupProps.ffff) expectType<ExpectedProps['validated']>(setup.setupProps.validated) // instance const instance = new MyComponent() expectType<number>(instance.setupA) // @ts-expect-error instance.notExist }) describe('options', () => { const MyComponent = { props: { a: Number, // required should make property non-void b: { type: String, required: true }, e: Function, // default value should infer type and make it non-void bb: { default: 'hello' }, bbb: { // Note: default function value requires arrow syntax + explicit // annotation default: (props: any) => (props.bb as string) || 'foo' }, // explicit type casting cc: Array as PropType<string[]>, // required + type casting dd: { type: Object as PropType<{ n: 1 }>, required: true }, // return type ee: Function as PropType<() => string>, // arguments + object return ff: Function as PropType<(a: number, b: string) => { a: boolean }>, // explicit type casting with constructor ccc: Array as () => string[], // required + contructor type casting ddd: { type: Array as () => string[], required: true }, // required + object return eee: { type: Function as PropType<() => { a: string }>, required: true }, // required + arguments + object return fff: { type: Function as PropType<(a: number, b: string) => { a: boolean }>, required: true }, hhh: { type: Boolean, required: true }, // default + type casting ggg: { type: String as PropType<'foo' | 'bar'>, default: 'foo' }, // default + function ffff: { type: Function as PropType<(a: number, b: string) => { a: boolean }>, default: (_a: number, _b: string) => ({ a: true }) }, validated: { type: String, // validator requires explicit annotation validator: (val: unknown) => val !== '' }, object: Object as PropType<object> }, setup() { return { setupA: 1 } } } as const const { props, rawBindings, setup } = extractComponentOptions(MyComponent) // props expectType<ExpectedProps['a']>(props.a) expectType<ExpectedProps['b']>(props.b) expectType<ExpectedProps['e']>(props.e) expectType<ExpectedProps['bb']>(props.bb) expectType<ExpectedProps['bbb']>(props.bbb) expectType<ExpectedProps['cc']>(props.cc) expectType<ExpectedProps['dd']>(props.dd) expectType<ExpectedProps['ee']>(props.ee) expectType<ExpectedProps['ff']>(props.ff) expectType<ExpectedProps['ccc']>(props.ccc) expectType<ExpectedProps['ddd']>(props.ddd) expectType<ExpectedProps['eee']>(props.eee) expectType<ExpectedProps['fff']>(props.fff) expectType<ExpectedProps['hhh']>(props.hhh) expectType<ExpectedProps['ggg']>(props.ggg) // expectType<ExpectedProps['ffff']>(props.ffff) // todo fix expectType<ExpectedProps['validated']>(props.validated) expectType<ExpectedProps['object']>(props.object) // rawBindings expectType<Number>(rawBindings.setupA) //setup expectType<Number>(setup.setupA) }) }) describe('array props', () => { describe('defineComponent', () => { const MyComponent = defineComponent({ props: ['a', 'b'], setup() { return { c: 1 } } }) const { props, rawBindings, setup } = extractComponentOptions(MyComponent) // @ts-expect-error props should be readonly expectError((props.a = 1)) expectType<any>(props.a) expectType<any>(props.b) expectType<number>(rawBindings.c) expectType<number>(setup.c) }) describe('options', () => { const MyComponent = { props: ['a', 'b'] as const, setup() { return { c: 1 } } } const { props, rawBindings, setup } = extractComponentOptions(MyComponent) // @ts-expect-error props should be readonly expectError((props.a = 1)) // TODO infer the correct keys // expectType<any>(props.a) // expectType<any>(props.b) expectType<number>(rawBindings.c) expectType<number>(setup.c) }) }) describe('no props', () => { describe('defineComponent', () => { const MyComponent = defineComponent({ setup() { return { setupA: 1 } } }) const { rawBindings, setup } = extractComponentOptions(MyComponent) expectType<number>(rawBindings.setupA) expectType<number>(setup.setupA) // instance const instance = new MyComponent() expectType<number>(instance.setupA) // @ts-expect-error instance.notExist }) describe('options', () => { const MyComponent = { setup() { return { setupA: 1 } } } const { rawBindings, setup } = extractComponentOptions(MyComponent) expectType<number>(rawBindings.setupA) expectType<number>(setup.setupA) }) }) describe('functional', () => { // TODO `props.foo` is `number|undefined` // describe('defineComponent', () => { // const MyComponent = defineComponent((props: { foo: number }) => {}) // const { props } = extractComponentOptions(MyComponent) // expectType<number>(props.foo) // }) describe('function', () => { const MyComponent = (props: { foo: number }) => props.foo const { props } = extractComponentOptions(MyComponent) expectType<number>(props.foo) }) describe('typed', () => { const MyComponent: FunctionalComponent<{ foo: number }> = (_, _2) => {} const { props } = extractComponentOptions(MyComponent) expectType<number>(props.foo) }) }) declare type VueClass<Props = {}> = { new (): ComponentPublicInstance<Props> } describe('class', () => { const MyComponent: VueClass<{ foo: number }> = {} as any const { props } = extractComponentOptions(MyComponent) expectType<number>(props.foo) })
test-dts/component.test-d.ts
1
https://github.com/vuejs/core/commit/f6a5f09a3aaff4f156bd1d4cc5ae01331cffa427
[ 0.9987738728523254, 0.04176962375640869, 0.00016738373960833997, 0.00017214883700944483, 0.1994505673646927 ]
{ "id": 0, "code_window": [ "export interface RefUnwrapBailTypes {}\n", "\n", "export type ShallowUnwrapRef<T> = {\n", " [K in keyof T]: T[K] extends Ref<infer V> ? V : T[K]\n", "}\n", "\n", "export type UnwrapRef<T> = T extends Ref<infer V>\n", " ? UnwrapRefSimple<V>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " [K in keyof T]: T[K] extends Ref<infer V>\n", " ? V\n", " : T[K] extends Ref<infer V> | undefined // if `V` is `unknown` that means it does not extend `Ref` and is undefined\n", " ? unknown extends V ? undefined : V | undefined\n", " : T[K]\n" ], "file_path": "packages/reactivity/src/ref.ts", "type": "replace", "edit_start_line_idx": 207 }
import { effect, ReactiveEffect, trigger, track } from './effect' import { TriggerOpTypes, TrackOpTypes } from './operations' import { Ref } from './ref' import { isFunction, NOOP } from '@vue/shared' import { ReactiveFlags, toRaw } from './reactive' export interface ComputedRef<T = any> extends WritableComputedRef<T> { readonly value: T } export interface WritableComputedRef<T> extends Ref<T> { readonly effect: ReactiveEffect<T> } export type ComputedGetter<T> = (ctx?: any) => T export type ComputedSetter<T> = (v: T) => void export interface WritableComputedOptions<T> { get: ComputedGetter<T> set: ComputedSetter<T> } class ComputedRefImpl<T> { private _value!: T private _dirty = true public readonly effect: ReactiveEffect<T> public readonly __v_isRef = true; public readonly [ReactiveFlags.IS_READONLY]: boolean constructor( getter: ComputedGetter<T>, private readonly _setter: ComputedSetter<T>, isReadonly: boolean ) { this.effect = effect(getter, { lazy: true, scheduler: () => { if (!this._dirty) { this._dirty = true trigger(toRaw(this), TriggerOpTypes.SET, 'value') } } }) this[ReactiveFlags.IS_READONLY] = isReadonly } get value() { // the computed ref may get wrapped by other proxies e.g. readonly() #3376 const self = toRaw(this) if (self._dirty) { self._value = this.effect() self._dirty = false } track(self, TrackOpTypes.GET, 'value') return self._value } set value(newValue: T) { this._setter(newValue) } } export function computed<T>(getter: ComputedGetter<T>): ComputedRef<T> export function computed<T>( options: WritableComputedOptions<T> ): WritableComputedRef<T> export function computed<T>( getterOrOptions: ComputedGetter<T> | WritableComputedOptions<T> ) { let getter: ComputedGetter<T> let setter: ComputedSetter<T> if (isFunction(getterOrOptions)) { getter = getterOrOptions setter = __DEV__ ? () => { console.warn('Write operation failed: computed value is readonly') } : NOOP } else { getter = getterOrOptions.get setter = getterOrOptions.set } return new ComputedRefImpl( getter, setter, isFunction(getterOrOptions) || !getterOrOptions.set ) as any }
packages/reactivity/src/computed.ts
0
https://github.com/vuejs/core/commit/f6a5f09a3aaff4f156bd1d4cc5ae01331cffa427
[ 0.01161356270313263, 0.0014315206790342927, 0.00016857059381436557, 0.00019420035823713988, 0.0034012270625680685 ]
{ "id": 0, "code_window": [ "export interface RefUnwrapBailTypes {}\n", "\n", "export type ShallowUnwrapRef<T> = {\n", " [K in keyof T]: T[K] extends Ref<infer V> ? V : T[K]\n", "}\n", "\n", "export type UnwrapRef<T> = T extends Ref<infer V>\n", " ? UnwrapRefSimple<V>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " [K in keyof T]: T[K] extends Ref<infer V>\n", " ? V\n", " : T[K] extends Ref<infer V> | undefined // if `V` is `unknown` that means it does not extend `Ref` and is undefined\n", " ? unknown extends V ? undefined : V | undefined\n", " : T[K]\n" ], "file_path": "packages/reactivity/src/ref.ts", "type": "replace", "edit_start_line_idx": 207 }
import { registerRuntimeHelpers } from '@vue/compiler-core' export const V_MODEL_RADIO = Symbol(__DEV__ ? `vModelRadio` : ``) export const V_MODEL_CHECKBOX = Symbol(__DEV__ ? `vModelCheckbox` : ``) export const V_MODEL_TEXT = Symbol(__DEV__ ? `vModelText` : ``) export const V_MODEL_SELECT = Symbol(__DEV__ ? `vModelSelect` : ``) export const V_MODEL_DYNAMIC = Symbol(__DEV__ ? `vModelDynamic` : ``) export const V_ON_WITH_MODIFIERS = Symbol(__DEV__ ? `vOnModifiersGuard` : ``) export const V_ON_WITH_KEYS = Symbol(__DEV__ ? `vOnKeysGuard` : ``) export const V_SHOW = Symbol(__DEV__ ? `vShow` : ``) export const TRANSITION = Symbol(__DEV__ ? `Transition` : ``) export const TRANSITION_GROUP = Symbol(__DEV__ ? `TransitionGroup` : ``) registerRuntimeHelpers({ [V_MODEL_RADIO]: `vModelRadio`, [V_MODEL_CHECKBOX]: `vModelCheckbox`, [V_MODEL_TEXT]: `vModelText`, [V_MODEL_SELECT]: `vModelSelect`, [V_MODEL_DYNAMIC]: `vModelDynamic`, [V_ON_WITH_MODIFIERS]: `withModifiers`, [V_ON_WITH_KEYS]: `withKeys`, [V_SHOW]: `vShow`, [TRANSITION]: `Transition`, [TRANSITION_GROUP]: `TransitionGroup` })
packages/compiler-dom/src/runtimeHelpers.ts
0
https://github.com/vuejs/core/commit/f6a5f09a3aaff4f156bd1d4cc5ae01331cffa427
[ 0.00023961649276316166, 0.00020619509450625628, 0.00017084329738281667, 0.00020812544971704483, 0.00002810969999700319 ]
{ "id": 0, "code_window": [ "export interface RefUnwrapBailTypes {}\n", "\n", "export type ShallowUnwrapRef<T> = {\n", " [K in keyof T]: T[K] extends Ref<infer V> ? V : T[K]\n", "}\n", "\n", "export type UnwrapRef<T> = T extends Ref<infer V>\n", " ? UnwrapRefSimple<V>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " [K in keyof T]: T[K] extends Ref<infer V>\n", " ? V\n", " : T[K] extends Ref<infer V> | undefined // if `V` is `unknown` that means it does not extend `Ref` and is undefined\n", " ? unknown extends V ? undefined : V | undefined\n", " : T[K]\n" ], "file_path": "packages/reactivity/src/ref.ts", "type": "replace", "edit_start_line_idx": 207 }
import { compile } from '../src' export function getCompiledString(src: string): string { // Wrap src template in a root div so that it doesn't get injected // fallthrough attr. This results in less noise in generated snapshots // but also means this util can only be used for non-root cases. const { code } = compile(`<div>${src}</div>`) const match = code.match( /_push\(\`<div\${\s*_ssrRenderAttrs\(_attrs\)\s*}>([^]*)<\/div>\`\)/ ) if (!match) { throw new Error(`Unexpected compile result:\n${code}`) } return `\`${match[1]}\`` }
packages/compiler-ssr/__tests__/utils.ts
0
https://github.com/vuejs/core/commit/f6a5f09a3aaff4f156bd1d4cc5ae01331cffa427
[ 0.00017013403703458607, 0.0001692392397671938, 0.00016834444249980152, 0.0001692392397671938, 8.947972673922777e-7 ]
{ "id": 1, "code_window": [ " setupA: 1,\n", " setupB: ref(1),\n", " setupC: {\n", " a: ref(2)\n", " },\n", " setupProps: props\n", " }\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " setupD: undefined as Ref<number> | undefined,\n" ], "file_path": "test-dts/component.test-d.ts", "type": "add", "edit_start_line_idx": 161 }
import { describe, Component, defineComponent, PropType, ref, Ref, expectError, expectType, ShallowUnwrapRef, FunctionalComponent, ComponentPublicInstance, toRefs } from './index' declare function extractComponentOptions<Props, RawBindings>( obj: Component<Props, RawBindings> ): { props: Props rawBindings: RawBindings setup: ShallowUnwrapRef<RawBindings> } describe('object props', () => { interface ExpectedProps { a?: number | undefined b: string e?: Function bb: string bbb: string cc?: string[] | undefined dd: { n: 1 } ee?: () => string ff?: (a: number, b: string) => { a: boolean } ccc?: string[] | undefined ddd: string[] eee: () => { a: string } fff: (a: number, b: string) => { a: boolean } hhh: boolean ggg: 'foo' | 'bar' ffff: (a: number, b: string) => { a: boolean } validated?: string object?: object } interface ExpectedRefs { a: Ref<number | undefined> b: Ref<string> e: Ref<Function | undefined> bb: Ref<string> bbb: Ref<string> cc: Ref<string[] | undefined> dd: Ref<{ n: 1 }> ee: Ref<(() => string) | undefined> ff: Ref<((a: number, b: string) => { a: boolean }) | undefined> ccc: Ref<string[] | undefined> ddd: Ref<string[]> eee: Ref<() => { a: string }> fff: Ref<(a: number, b: string) => { a: boolean }> hhh: Ref<boolean> ggg: Ref<'foo' | 'bar'> ffff: Ref<(a: number, b: string) => { a: boolean }> validated: Ref<string | undefined> object: Ref<object | undefined> } describe('defineComponent', () => { const MyComponent = defineComponent({ props: { a: Number, // required should make property non-void b: { type: String, required: true }, e: Function, // default value should infer type and make it non-void bb: { default: 'hello' }, bbb: { // Note: default function value requires arrow syntax + explicit // annotation default: (props: any) => (props.bb as string) || 'foo' }, // explicit type casting cc: Array as PropType<string[]>, // required + type casting dd: { type: Object as PropType<{ n: 1 }>, required: true }, // return type ee: Function as PropType<() => string>, // arguments + object return ff: Function as PropType<(a: number, b: string) => { a: boolean }>, // explicit type casting with constructor ccc: Array as () => string[], // required + contructor type casting ddd: { type: Array as () => string[], required: true }, // required + object return eee: { type: Function as PropType<() => { a: string }>, required: true }, // required + arguments + object return fff: { type: Function as PropType<(a: number, b: string) => { a: boolean }>, required: true }, hhh: { type: Boolean, required: true }, // default + type casting ggg: { type: String as PropType<'foo' | 'bar'>, default: 'foo' }, // default + function ffff: { type: Function as PropType<(a: number, b: string) => { a: boolean }>, default: (_a: number, _b: string) => ({ a: true }) }, validated: { type: String, // validator requires explicit annotation validator: (val: unknown) => val !== '' }, object: Object as PropType<object> }, setup(props) { const refs = toRefs(props) expectType<ExpectedRefs['a']>(refs.a) expectType<ExpectedRefs['b']>(refs.b) expectType<ExpectedRefs['e']>(refs.e) expectType<ExpectedRefs['bb']>(refs.bb) expectType<ExpectedRefs['bbb']>(refs.bbb) expectType<ExpectedRefs['cc']>(refs.cc) expectType<ExpectedRefs['dd']>(refs.dd) expectType<ExpectedRefs['ee']>(refs.ee) expectType<ExpectedRefs['ff']>(refs.ff) expectType<ExpectedRefs['ccc']>(refs.ccc) expectType<ExpectedRefs['ddd']>(refs.ddd) expectType<ExpectedRefs['eee']>(refs.eee) expectType<ExpectedRefs['fff']>(refs.fff) expectType<ExpectedRefs['hhh']>(refs.hhh) expectType<ExpectedRefs['ggg']>(refs.ggg) expectType<ExpectedRefs['ffff']>(refs.ffff) expectType<ExpectedRefs['validated']>(refs.validated) expectType<ExpectedRefs['object']>(refs.object) return { setupA: 1, setupB: ref(1), setupC: { a: ref(2) }, setupProps: props } } }) const { props, rawBindings, setup } = extractComponentOptions(MyComponent) // props expectType<ExpectedProps['a']>(props.a) expectType<ExpectedProps['b']>(props.b) expectType<ExpectedProps['e']>(props.e) expectType<ExpectedProps['bb']>(props.bb) expectType<ExpectedProps['bbb']>(props.bbb) expectType<ExpectedProps['cc']>(props.cc) expectType<ExpectedProps['dd']>(props.dd) expectType<ExpectedProps['ee']>(props.ee) expectType<ExpectedProps['ff']>(props.ff) expectType<ExpectedProps['ccc']>(props.ccc) expectType<ExpectedProps['ddd']>(props.ddd) expectType<ExpectedProps['eee']>(props.eee) expectType<ExpectedProps['fff']>(props.fff) expectType<ExpectedProps['hhh']>(props.hhh) expectType<ExpectedProps['ggg']>(props.ggg) expectType<ExpectedProps['ffff']>(props.ffff) expectType<ExpectedProps['validated']>(props.validated) expectType<ExpectedProps['object']>(props.object) // raw bindings expectType<Number>(rawBindings.setupA) expectType<Ref<Number>>(rawBindings.setupB) expectType<Ref<Number>>(rawBindings.setupC.a) expectType<Number>(rawBindings.setupA) // raw bindings props expectType<ExpectedProps['a']>(rawBindings.setupProps.a) expectType<ExpectedProps['b']>(rawBindings.setupProps.b) expectType<ExpectedProps['e']>(rawBindings.setupProps.e) expectType<ExpectedProps['bb']>(rawBindings.setupProps.bb) expectType<ExpectedProps['bbb']>(rawBindings.setupProps.bbb) expectType<ExpectedProps['cc']>(rawBindings.setupProps.cc) expectType<ExpectedProps['dd']>(rawBindings.setupProps.dd) expectType<ExpectedProps['ee']>(rawBindings.setupProps.ee) expectType<ExpectedProps['ff']>(rawBindings.setupProps.ff) expectType<ExpectedProps['ccc']>(rawBindings.setupProps.ccc) expectType<ExpectedProps['ddd']>(rawBindings.setupProps.ddd) expectType<ExpectedProps['eee']>(rawBindings.setupProps.eee) expectType<ExpectedProps['fff']>(rawBindings.setupProps.fff) expectType<ExpectedProps['hhh']>(rawBindings.setupProps.hhh) expectType<ExpectedProps['ggg']>(rawBindings.setupProps.ggg) expectType<ExpectedProps['ffff']>(rawBindings.setupProps.ffff) expectType<ExpectedProps['validated']>(rawBindings.setupProps.validated) // setup expectType<Number>(setup.setupA) expectType<Number>(setup.setupB) expectType<Ref<Number>>(setup.setupC.a) expectType<Number>(setup.setupA) // raw bindings props expectType<ExpectedProps['a']>(setup.setupProps.a) expectType<ExpectedProps['b']>(setup.setupProps.b) expectType<ExpectedProps['e']>(setup.setupProps.e) expectType<ExpectedProps['bb']>(setup.setupProps.bb) expectType<ExpectedProps['bbb']>(setup.setupProps.bbb) expectType<ExpectedProps['cc']>(setup.setupProps.cc) expectType<ExpectedProps['dd']>(setup.setupProps.dd) expectType<ExpectedProps['ee']>(setup.setupProps.ee) expectType<ExpectedProps['ff']>(setup.setupProps.ff) expectType<ExpectedProps['ccc']>(setup.setupProps.ccc) expectType<ExpectedProps['ddd']>(setup.setupProps.ddd) expectType<ExpectedProps['eee']>(setup.setupProps.eee) expectType<ExpectedProps['fff']>(setup.setupProps.fff) expectType<ExpectedProps['hhh']>(setup.setupProps.hhh) expectType<ExpectedProps['ggg']>(setup.setupProps.ggg) expectType<ExpectedProps['ffff']>(setup.setupProps.ffff) expectType<ExpectedProps['validated']>(setup.setupProps.validated) // instance const instance = new MyComponent() expectType<number>(instance.setupA) // @ts-expect-error instance.notExist }) describe('options', () => { const MyComponent = { props: { a: Number, // required should make property non-void b: { type: String, required: true }, e: Function, // default value should infer type and make it non-void bb: { default: 'hello' }, bbb: { // Note: default function value requires arrow syntax + explicit // annotation default: (props: any) => (props.bb as string) || 'foo' }, // explicit type casting cc: Array as PropType<string[]>, // required + type casting dd: { type: Object as PropType<{ n: 1 }>, required: true }, // return type ee: Function as PropType<() => string>, // arguments + object return ff: Function as PropType<(a: number, b: string) => { a: boolean }>, // explicit type casting with constructor ccc: Array as () => string[], // required + contructor type casting ddd: { type: Array as () => string[], required: true }, // required + object return eee: { type: Function as PropType<() => { a: string }>, required: true }, // required + arguments + object return fff: { type: Function as PropType<(a: number, b: string) => { a: boolean }>, required: true }, hhh: { type: Boolean, required: true }, // default + type casting ggg: { type: String as PropType<'foo' | 'bar'>, default: 'foo' }, // default + function ffff: { type: Function as PropType<(a: number, b: string) => { a: boolean }>, default: (_a: number, _b: string) => ({ a: true }) }, validated: { type: String, // validator requires explicit annotation validator: (val: unknown) => val !== '' }, object: Object as PropType<object> }, setup() { return { setupA: 1 } } } as const const { props, rawBindings, setup } = extractComponentOptions(MyComponent) // props expectType<ExpectedProps['a']>(props.a) expectType<ExpectedProps['b']>(props.b) expectType<ExpectedProps['e']>(props.e) expectType<ExpectedProps['bb']>(props.bb) expectType<ExpectedProps['bbb']>(props.bbb) expectType<ExpectedProps['cc']>(props.cc) expectType<ExpectedProps['dd']>(props.dd) expectType<ExpectedProps['ee']>(props.ee) expectType<ExpectedProps['ff']>(props.ff) expectType<ExpectedProps['ccc']>(props.ccc) expectType<ExpectedProps['ddd']>(props.ddd) expectType<ExpectedProps['eee']>(props.eee) expectType<ExpectedProps['fff']>(props.fff) expectType<ExpectedProps['hhh']>(props.hhh) expectType<ExpectedProps['ggg']>(props.ggg) // expectType<ExpectedProps['ffff']>(props.ffff) // todo fix expectType<ExpectedProps['validated']>(props.validated) expectType<ExpectedProps['object']>(props.object) // rawBindings expectType<Number>(rawBindings.setupA) //setup expectType<Number>(setup.setupA) }) }) describe('array props', () => { describe('defineComponent', () => { const MyComponent = defineComponent({ props: ['a', 'b'], setup() { return { c: 1 } } }) const { props, rawBindings, setup } = extractComponentOptions(MyComponent) // @ts-expect-error props should be readonly expectError((props.a = 1)) expectType<any>(props.a) expectType<any>(props.b) expectType<number>(rawBindings.c) expectType<number>(setup.c) }) describe('options', () => { const MyComponent = { props: ['a', 'b'] as const, setup() { return { c: 1 } } } const { props, rawBindings, setup } = extractComponentOptions(MyComponent) // @ts-expect-error props should be readonly expectError((props.a = 1)) // TODO infer the correct keys // expectType<any>(props.a) // expectType<any>(props.b) expectType<number>(rawBindings.c) expectType<number>(setup.c) }) }) describe('no props', () => { describe('defineComponent', () => { const MyComponent = defineComponent({ setup() { return { setupA: 1 } } }) const { rawBindings, setup } = extractComponentOptions(MyComponent) expectType<number>(rawBindings.setupA) expectType<number>(setup.setupA) // instance const instance = new MyComponent() expectType<number>(instance.setupA) // @ts-expect-error instance.notExist }) describe('options', () => { const MyComponent = { setup() { return { setupA: 1 } } } const { rawBindings, setup } = extractComponentOptions(MyComponent) expectType<number>(rawBindings.setupA) expectType<number>(setup.setupA) }) }) describe('functional', () => { // TODO `props.foo` is `number|undefined` // describe('defineComponent', () => { // const MyComponent = defineComponent((props: { foo: number }) => {}) // const { props } = extractComponentOptions(MyComponent) // expectType<number>(props.foo) // }) describe('function', () => { const MyComponent = (props: { foo: number }) => props.foo const { props } = extractComponentOptions(MyComponent) expectType<number>(props.foo) }) describe('typed', () => { const MyComponent: FunctionalComponent<{ foo: number }> = (_, _2) => {} const { props } = extractComponentOptions(MyComponent) expectType<number>(props.foo) }) }) declare type VueClass<Props = {}> = { new (): ComponentPublicInstance<Props> } describe('class', () => { const MyComponent: VueClass<{ foo: number }> = {} as any const { props } = extractComponentOptions(MyComponent) expectType<number>(props.foo) })
test-dts/component.test-d.ts
1
https://github.com/vuejs/core/commit/f6a5f09a3aaff4f156bd1d4cc5ae01331cffa427
[ 0.15277288854122162, 0.004625129979103804, 0.00016544929530937225, 0.0003199463535565883, 0.02168712578713894 ]
{ "id": 1, "code_window": [ " setupA: 1,\n", " setupB: ref(1),\n", " setupC: {\n", " a: ref(2)\n", " },\n", " setupProps: props\n", " }\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " setupD: undefined as Ref<number> | undefined,\n" ], "file_path": "test-dts/component.test-d.ts", "type": "add", "edit_start_line_idx": 161 }
import { compile } from '../src' describe('ssr: v-for', () => { test('basic', () => { expect(compile(`<div v-for="i in list" />`).code).toMatchInlineSnapshot(` "const { ssrRenderList: _ssrRenderList } = require(\\"@vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { _push(\`<!--[-->\`) _ssrRenderList(_ctx.list, (i) => { _push(\`<div></div>\`) }) _push(\`<!--]-->\`) }" `) }) test('nested content', () => { expect(compile(`<div v-for="i in list">foo<span>bar</span></div>`).code) .toMatchInlineSnapshot(` "const { ssrRenderList: _ssrRenderList } = require(\\"@vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { _push(\`<!--[-->\`) _ssrRenderList(_ctx.list, (i) => { _push(\`<div>foo<span>bar</span></div>\`) }) _push(\`<!--]-->\`) }" `) }) test('nested v-for', () => { expect( compile( `<div v-for="row, i in list">` + `<div v-for="j in row">{{ i }},{{ j }}</div>` + `</div>` ).code ).toMatchInlineSnapshot(` "const { ssrInterpolate: _ssrInterpolate, ssrRenderList: _ssrRenderList } = require(\\"@vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { _push(\`<!--[-->\`) _ssrRenderList(_ctx.list, (row, i) => { _push(\`<div><!--[-->\`) _ssrRenderList(row, (j) => { _push(\`<div>\${ _ssrInterpolate(i) },\${ _ssrInterpolate(j) }</div>\`) }) _push(\`<!--]--></div>\`) }) _push(\`<!--]-->\`) }" `) }) test('template v-for (text)', () => { expect(compile(`<template v-for="i in list">{{ i }}</template>`).code) .toMatchInlineSnapshot(` "const { ssrInterpolate: _ssrInterpolate, ssrRenderList: _ssrRenderList } = require(\\"@vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { _push(\`<!--[-->\`) _ssrRenderList(_ctx.list, (i) => { _push(\`<!--[-->\${_ssrInterpolate(i)}<!--]-->\`) }) _push(\`<!--]-->\`) }" `) }) test('template v-for (single element)', () => { expect( compile(`<template v-for="i in list"><span>{{ i }}</span></template>`) .code ).toMatchInlineSnapshot(` "const { ssrInterpolate: _ssrInterpolate, ssrRenderList: _ssrRenderList } = require(\\"@vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { _push(\`<!--[-->\`) _ssrRenderList(_ctx.list, (i) => { _push(\`<span>\${_ssrInterpolate(i)}</span>\`) }) _push(\`<!--]-->\`) }" `) }) test('template v-for (multi element)', () => { expect( compile( `<template v-for="i in list"><span>{{ i }}</span><span>{{ i + 1 }}</span></template>` ).code ).toMatchInlineSnapshot(` "const { ssrInterpolate: _ssrInterpolate, ssrRenderList: _ssrRenderList } = require(\\"@vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { _push(\`<!--[-->\`) _ssrRenderList(_ctx.list, (i) => { _push(\`<!--[--><span>\${ _ssrInterpolate(i) }</span><span>\${ _ssrInterpolate(i + 1) }</span><!--]-->\`) }) _push(\`<!--]-->\`) }" `) }) test('render loop args should not be prefixed', () => { const { code } = compile( `<div v-for="{ foo }, index in list">{{ foo + bar + index }}</div>` ) expect(code).toMatch(`_ctx.bar`) expect(code).not.toMatch(`_ctx.foo`) expect(code).not.toMatch(`_ctx.index`) expect(code).toMatchInlineSnapshot(` "const { ssrInterpolate: _ssrInterpolate, ssrRenderList: _ssrRenderList } = require(\\"@vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { _push(\`<!--[-->\`) _ssrRenderList(_ctx.list, ({ foo }, index) => { _push(\`<div>\${_ssrInterpolate(foo + _ctx.bar + index)}</div>\`) }) _push(\`<!--]-->\`) }" `) }) })
packages/compiler-ssr/__tests__/ssrVFor.spec.ts
0
https://github.com/vuejs/core/commit/f6a5f09a3aaff4f156bd1d4cc5ae01331cffa427
[ 0.00020256219431757927, 0.00017522592679597437, 0.0001694128441158682, 0.00017172007937915623, 0.000008412982424488291 ]
{ "id": 1, "code_window": [ " setupA: 1,\n", " setupB: ref(1),\n", " setupC: {\n", " a: ref(2)\n", " },\n", " setupProps: props\n", " }\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " setupD: undefined as Ref<number> | undefined,\n" ], "file_path": "test-dts/component.test-d.ts", "type": "add", "edit_start_line_idx": 161 }
<script src="../../dist/vue.global.js"></script> <!-- DemoGrid component template --> <script type="text/x-template" id="grid-template"> <table v-if="filteredData.length"> <thead> <tr> <th v-for="key in columns" @click="sortBy(key)" :class="{ active: sortKey == key }"> {{ capitalize(key) }} <span class="arrow" :class="sortOrders[key] > 0 ? 'asc' : 'dsc'"> </span> </th> </tr> </thead> <tbody> <tr v-for="entry in filteredData"> <td v-for="key in columns"> {{entry[key]}} </td> </tr> </tbody> </table> <p v-else>No matches found.</p> </script> <!-- DemoGrid component script --> <script> const DemoGrid = { template: '#grid-template', props: { data: Array, columns: Array, filterKey: String }, data() { return { sortKey: '', sortOrders: this.columns.reduce((o, key) => (o[key] = 1, o), {}) } }, computed: { filteredData() { const sortKey = this.sortKey const filterKey = this.filterKey && this.filterKey.toLowerCase() const order = this.sortOrders[sortKey] || 1 let data = this.data if (filterKey) { data = data.filter(row => { return Object.keys(row).some(key => { return String(row[key]).toLowerCase().indexOf(filterKey) > -1 }) }) } if (sortKey) { data = data.slice().sort((a, b) => { a = a[sortKey] b = b[sortKey] return (a === b ? 0 : a > b ? 1 : -1) * order }) } return data } }, methods: { sortBy(key) { this.sortKey = key this.sortOrders[key] = this.sortOrders[key] * -1 }, capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1) } } } </script> <!-- App template (in DOM) --> <div id="demo"> <form id="search"> Search <input name="query" v-model="searchQuery"> </form> <demo-grid :data="gridData" :columns="gridColumns" :filter-key="searchQuery"> </demo-grid> </div> <!-- App script --> <script> Vue.createApp({ components: { DemoGrid }, data: () => ({ searchQuery: '', gridColumns: ['name', 'power'], gridData: [ { name: 'Chuck Norris', power: Infinity }, { name: 'Bruce Lee', power: 9000 }, { name: 'Jackie Chan', power: 7000 }, { name: 'Jet Li', power: 8000 } ] }) }).mount('#demo') </script> <style> body { font-family: Helvetica Neue, Arial, sans-serif; font-size: 14px; color: #444; } table { border: 2px solid #42b983; border-radius: 3px; background-color: #fff; } th { background-color: #42b983; color: rgba(255,255,255,0.66); cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } td { background-color: #f9f9f9; } th, td { min-width: 120px; padding: 10px 20px; } th.active { color: #fff; } th.active .arrow { opacity: 1; } .arrow { display: inline-block; vertical-align: middle; width: 0; height: 0; margin-left: 5px; opacity: 0.66; } .arrow.asc { border-left: 4px solid transparent; border-right: 4px solid transparent; border-bottom: 4px solid #fff; } .arrow.dsc { border-left: 4px solid transparent; border-right: 4px solid transparent; border-top: 4px solid #fff; } </style>
packages/vue/examples/classic/grid.html
0
https://github.com/vuejs/core/commit/f6a5f09a3aaff4f156bd1d4cc5ae01331cffa427
[ 0.0022117989137768745, 0.0002950059133581817, 0.00016461967607028782, 0.000170965664437972, 0.00047961773816496134 ]
{ "id": 1, "code_window": [ " setupA: 1,\n", " setupB: ref(1),\n", " setupC: {\n", " a: ref(2)\n", " },\n", " setupProps: props\n", " }\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " setupD: undefined as Ref<number> | undefined,\n" ], "file_path": "test-dts/component.test-d.ts", "type": "add", "edit_start_line_idx": 161 }
import Vue from '@vue/compat' import { nextTick } from '../../runtime-core/src/scheduler' import { DeprecationTypes, deprecationData, toggleDeprecationWarning } from '../../runtime-core/src/compat/compatConfig' beforeEach(() => { toggleDeprecationWarning(true) Vue.configureCompat({ MODE: 2, GLOBAL_MOUNT: 'suppress-warning', GLOBAL_EXTEND: 'suppress-warning' }) }) afterEach(() => { toggleDeprecationWarning(false) Vue.configureCompat({ MODE: 3 }) }) test('root data plain object', () => { const vm = new Vue({ data: { foo: 1 } as any, template: `{{ foo }}` }).$mount() expect(vm.$el.textContent).toBe('1') expect( deprecationData[DeprecationTypes.OPTIONS_DATA_FN].message ).toHaveBeenWarned() }) test('data deep merge', () => { const mixin = { data() { return { foo: { baz: 2 } } } } const vm = new Vue({ mixins: [mixin], data: () => ({ foo: { bar: 1 }, selfData: 3 }), template: `{{ { selfData, foo } }}` }).$mount() expect(vm.$el.textContent).toBe( JSON.stringify({ selfData: 3, foo: { baz: 2, bar: 1 } }, null, 2) ) expect( (deprecationData[DeprecationTypes.OPTIONS_DATA_MERGE].message as Function)( 'foo' ) ).toHaveBeenWarned() }) // #3852 test('data deep merge w/ extended constructor', () => { const App = Vue.extend({ template: `<pre>{{ { mixinData, selfData } }}</pre>`, mixins: [{ data: () => ({ mixinData: 'mixinData' }) }], data: () => ({ selfData: 'selfData' }) }) const vm = new App().$mount() expect(vm.$el.textContent).toBe( JSON.stringify( { mixinData: 'mixinData', selfData: 'selfData' }, null, 2 ) ) }) test('beforeDestroy/destroyed', async () => { const beforeDestroy = jest.fn() const destroyed = jest.fn() const child = { template: `foo`, beforeDestroy, destroyed } const vm = new Vue({ template: `<child v-if="ok"/>`, data() { return { ok: true } }, components: { child } }).$mount() as any vm.ok = false await nextTick() expect(beforeDestroy).toHaveBeenCalled() expect(destroyed).toHaveBeenCalled() expect( deprecationData[DeprecationTypes.OPTIONS_BEFORE_DESTROY].message ).toHaveBeenWarned() expect( deprecationData[DeprecationTypes.OPTIONS_DESTROYED].message ).toHaveBeenWarned() }) test('beforeDestroy/destroyed in Vue.extend components', async () => { const beforeDestroy = jest.fn() const destroyed = jest.fn() const child = Vue.extend({ template: `foo`, beforeDestroy, destroyed }) const vm = new Vue({ template: `<child v-if="ok"/>`, data() { return { ok: true } }, components: { child } }).$mount() as any vm.ok = false await nextTick() expect(beforeDestroy).toHaveBeenCalled() expect(destroyed).toHaveBeenCalled() expect( deprecationData[DeprecationTypes.OPTIONS_BEFORE_DESTROY].message ).toHaveBeenWarned() expect( deprecationData[DeprecationTypes.OPTIONS_DESTROYED].message ).toHaveBeenWarned() })
packages/vue-compat/__tests__/options.spec.ts
0
https://github.com/vuejs/core/commit/f6a5f09a3aaff4f156bd1d4cc5ae01331cffa427
[ 0.0001762708561727777, 0.00017219773144461215, 0.0001663866569288075, 0.00017308603855781257, 0.0000028851932256657165 ]
{ "id": 2, "code_window": [ " expectType<Number>(rawBindings.setupA)\n", " expectType<Ref<Number>>(rawBindings.setupB)\n", " expectType<Ref<Number>>(rawBindings.setupC.a)\n", " expectType<Number>(rawBindings.setupA)\n", "\n", " // raw bindings props\n", " expectType<ExpectedProps['a']>(rawBindings.setupProps.a)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " expectType<Ref<Number> | undefined>(rawBindings.setupD)\n" ], "file_path": "test-dts/component.test-d.ts", "type": "replace", "edit_start_line_idx": 192 }
import { describe, Component, defineComponent, PropType, ref, Ref, expectError, expectType, ShallowUnwrapRef, FunctionalComponent, ComponentPublicInstance, toRefs } from './index' declare function extractComponentOptions<Props, RawBindings>( obj: Component<Props, RawBindings> ): { props: Props rawBindings: RawBindings setup: ShallowUnwrapRef<RawBindings> } describe('object props', () => { interface ExpectedProps { a?: number | undefined b: string e?: Function bb: string bbb: string cc?: string[] | undefined dd: { n: 1 } ee?: () => string ff?: (a: number, b: string) => { a: boolean } ccc?: string[] | undefined ddd: string[] eee: () => { a: string } fff: (a: number, b: string) => { a: boolean } hhh: boolean ggg: 'foo' | 'bar' ffff: (a: number, b: string) => { a: boolean } validated?: string object?: object } interface ExpectedRefs { a: Ref<number | undefined> b: Ref<string> e: Ref<Function | undefined> bb: Ref<string> bbb: Ref<string> cc: Ref<string[] | undefined> dd: Ref<{ n: 1 }> ee: Ref<(() => string) | undefined> ff: Ref<((a: number, b: string) => { a: boolean }) | undefined> ccc: Ref<string[] | undefined> ddd: Ref<string[]> eee: Ref<() => { a: string }> fff: Ref<(a: number, b: string) => { a: boolean }> hhh: Ref<boolean> ggg: Ref<'foo' | 'bar'> ffff: Ref<(a: number, b: string) => { a: boolean }> validated: Ref<string | undefined> object: Ref<object | undefined> } describe('defineComponent', () => { const MyComponent = defineComponent({ props: { a: Number, // required should make property non-void b: { type: String, required: true }, e: Function, // default value should infer type and make it non-void bb: { default: 'hello' }, bbb: { // Note: default function value requires arrow syntax + explicit // annotation default: (props: any) => (props.bb as string) || 'foo' }, // explicit type casting cc: Array as PropType<string[]>, // required + type casting dd: { type: Object as PropType<{ n: 1 }>, required: true }, // return type ee: Function as PropType<() => string>, // arguments + object return ff: Function as PropType<(a: number, b: string) => { a: boolean }>, // explicit type casting with constructor ccc: Array as () => string[], // required + contructor type casting ddd: { type: Array as () => string[], required: true }, // required + object return eee: { type: Function as PropType<() => { a: string }>, required: true }, // required + arguments + object return fff: { type: Function as PropType<(a: number, b: string) => { a: boolean }>, required: true }, hhh: { type: Boolean, required: true }, // default + type casting ggg: { type: String as PropType<'foo' | 'bar'>, default: 'foo' }, // default + function ffff: { type: Function as PropType<(a: number, b: string) => { a: boolean }>, default: (_a: number, _b: string) => ({ a: true }) }, validated: { type: String, // validator requires explicit annotation validator: (val: unknown) => val !== '' }, object: Object as PropType<object> }, setup(props) { const refs = toRefs(props) expectType<ExpectedRefs['a']>(refs.a) expectType<ExpectedRefs['b']>(refs.b) expectType<ExpectedRefs['e']>(refs.e) expectType<ExpectedRefs['bb']>(refs.bb) expectType<ExpectedRefs['bbb']>(refs.bbb) expectType<ExpectedRefs['cc']>(refs.cc) expectType<ExpectedRefs['dd']>(refs.dd) expectType<ExpectedRefs['ee']>(refs.ee) expectType<ExpectedRefs['ff']>(refs.ff) expectType<ExpectedRefs['ccc']>(refs.ccc) expectType<ExpectedRefs['ddd']>(refs.ddd) expectType<ExpectedRefs['eee']>(refs.eee) expectType<ExpectedRefs['fff']>(refs.fff) expectType<ExpectedRefs['hhh']>(refs.hhh) expectType<ExpectedRefs['ggg']>(refs.ggg) expectType<ExpectedRefs['ffff']>(refs.ffff) expectType<ExpectedRefs['validated']>(refs.validated) expectType<ExpectedRefs['object']>(refs.object) return { setupA: 1, setupB: ref(1), setupC: { a: ref(2) }, setupProps: props } } }) const { props, rawBindings, setup } = extractComponentOptions(MyComponent) // props expectType<ExpectedProps['a']>(props.a) expectType<ExpectedProps['b']>(props.b) expectType<ExpectedProps['e']>(props.e) expectType<ExpectedProps['bb']>(props.bb) expectType<ExpectedProps['bbb']>(props.bbb) expectType<ExpectedProps['cc']>(props.cc) expectType<ExpectedProps['dd']>(props.dd) expectType<ExpectedProps['ee']>(props.ee) expectType<ExpectedProps['ff']>(props.ff) expectType<ExpectedProps['ccc']>(props.ccc) expectType<ExpectedProps['ddd']>(props.ddd) expectType<ExpectedProps['eee']>(props.eee) expectType<ExpectedProps['fff']>(props.fff) expectType<ExpectedProps['hhh']>(props.hhh) expectType<ExpectedProps['ggg']>(props.ggg) expectType<ExpectedProps['ffff']>(props.ffff) expectType<ExpectedProps['validated']>(props.validated) expectType<ExpectedProps['object']>(props.object) // raw bindings expectType<Number>(rawBindings.setupA) expectType<Ref<Number>>(rawBindings.setupB) expectType<Ref<Number>>(rawBindings.setupC.a) expectType<Number>(rawBindings.setupA) // raw bindings props expectType<ExpectedProps['a']>(rawBindings.setupProps.a) expectType<ExpectedProps['b']>(rawBindings.setupProps.b) expectType<ExpectedProps['e']>(rawBindings.setupProps.e) expectType<ExpectedProps['bb']>(rawBindings.setupProps.bb) expectType<ExpectedProps['bbb']>(rawBindings.setupProps.bbb) expectType<ExpectedProps['cc']>(rawBindings.setupProps.cc) expectType<ExpectedProps['dd']>(rawBindings.setupProps.dd) expectType<ExpectedProps['ee']>(rawBindings.setupProps.ee) expectType<ExpectedProps['ff']>(rawBindings.setupProps.ff) expectType<ExpectedProps['ccc']>(rawBindings.setupProps.ccc) expectType<ExpectedProps['ddd']>(rawBindings.setupProps.ddd) expectType<ExpectedProps['eee']>(rawBindings.setupProps.eee) expectType<ExpectedProps['fff']>(rawBindings.setupProps.fff) expectType<ExpectedProps['hhh']>(rawBindings.setupProps.hhh) expectType<ExpectedProps['ggg']>(rawBindings.setupProps.ggg) expectType<ExpectedProps['ffff']>(rawBindings.setupProps.ffff) expectType<ExpectedProps['validated']>(rawBindings.setupProps.validated) // setup expectType<Number>(setup.setupA) expectType<Number>(setup.setupB) expectType<Ref<Number>>(setup.setupC.a) expectType<Number>(setup.setupA) // raw bindings props expectType<ExpectedProps['a']>(setup.setupProps.a) expectType<ExpectedProps['b']>(setup.setupProps.b) expectType<ExpectedProps['e']>(setup.setupProps.e) expectType<ExpectedProps['bb']>(setup.setupProps.bb) expectType<ExpectedProps['bbb']>(setup.setupProps.bbb) expectType<ExpectedProps['cc']>(setup.setupProps.cc) expectType<ExpectedProps['dd']>(setup.setupProps.dd) expectType<ExpectedProps['ee']>(setup.setupProps.ee) expectType<ExpectedProps['ff']>(setup.setupProps.ff) expectType<ExpectedProps['ccc']>(setup.setupProps.ccc) expectType<ExpectedProps['ddd']>(setup.setupProps.ddd) expectType<ExpectedProps['eee']>(setup.setupProps.eee) expectType<ExpectedProps['fff']>(setup.setupProps.fff) expectType<ExpectedProps['hhh']>(setup.setupProps.hhh) expectType<ExpectedProps['ggg']>(setup.setupProps.ggg) expectType<ExpectedProps['ffff']>(setup.setupProps.ffff) expectType<ExpectedProps['validated']>(setup.setupProps.validated) // instance const instance = new MyComponent() expectType<number>(instance.setupA) // @ts-expect-error instance.notExist }) describe('options', () => { const MyComponent = { props: { a: Number, // required should make property non-void b: { type: String, required: true }, e: Function, // default value should infer type and make it non-void bb: { default: 'hello' }, bbb: { // Note: default function value requires arrow syntax + explicit // annotation default: (props: any) => (props.bb as string) || 'foo' }, // explicit type casting cc: Array as PropType<string[]>, // required + type casting dd: { type: Object as PropType<{ n: 1 }>, required: true }, // return type ee: Function as PropType<() => string>, // arguments + object return ff: Function as PropType<(a: number, b: string) => { a: boolean }>, // explicit type casting with constructor ccc: Array as () => string[], // required + contructor type casting ddd: { type: Array as () => string[], required: true }, // required + object return eee: { type: Function as PropType<() => { a: string }>, required: true }, // required + arguments + object return fff: { type: Function as PropType<(a: number, b: string) => { a: boolean }>, required: true }, hhh: { type: Boolean, required: true }, // default + type casting ggg: { type: String as PropType<'foo' | 'bar'>, default: 'foo' }, // default + function ffff: { type: Function as PropType<(a: number, b: string) => { a: boolean }>, default: (_a: number, _b: string) => ({ a: true }) }, validated: { type: String, // validator requires explicit annotation validator: (val: unknown) => val !== '' }, object: Object as PropType<object> }, setup() { return { setupA: 1 } } } as const const { props, rawBindings, setup } = extractComponentOptions(MyComponent) // props expectType<ExpectedProps['a']>(props.a) expectType<ExpectedProps['b']>(props.b) expectType<ExpectedProps['e']>(props.e) expectType<ExpectedProps['bb']>(props.bb) expectType<ExpectedProps['bbb']>(props.bbb) expectType<ExpectedProps['cc']>(props.cc) expectType<ExpectedProps['dd']>(props.dd) expectType<ExpectedProps['ee']>(props.ee) expectType<ExpectedProps['ff']>(props.ff) expectType<ExpectedProps['ccc']>(props.ccc) expectType<ExpectedProps['ddd']>(props.ddd) expectType<ExpectedProps['eee']>(props.eee) expectType<ExpectedProps['fff']>(props.fff) expectType<ExpectedProps['hhh']>(props.hhh) expectType<ExpectedProps['ggg']>(props.ggg) // expectType<ExpectedProps['ffff']>(props.ffff) // todo fix expectType<ExpectedProps['validated']>(props.validated) expectType<ExpectedProps['object']>(props.object) // rawBindings expectType<Number>(rawBindings.setupA) //setup expectType<Number>(setup.setupA) }) }) describe('array props', () => { describe('defineComponent', () => { const MyComponent = defineComponent({ props: ['a', 'b'], setup() { return { c: 1 } } }) const { props, rawBindings, setup } = extractComponentOptions(MyComponent) // @ts-expect-error props should be readonly expectError((props.a = 1)) expectType<any>(props.a) expectType<any>(props.b) expectType<number>(rawBindings.c) expectType<number>(setup.c) }) describe('options', () => { const MyComponent = { props: ['a', 'b'] as const, setup() { return { c: 1 } } } const { props, rawBindings, setup } = extractComponentOptions(MyComponent) // @ts-expect-error props should be readonly expectError((props.a = 1)) // TODO infer the correct keys // expectType<any>(props.a) // expectType<any>(props.b) expectType<number>(rawBindings.c) expectType<number>(setup.c) }) }) describe('no props', () => { describe('defineComponent', () => { const MyComponent = defineComponent({ setup() { return { setupA: 1 } } }) const { rawBindings, setup } = extractComponentOptions(MyComponent) expectType<number>(rawBindings.setupA) expectType<number>(setup.setupA) // instance const instance = new MyComponent() expectType<number>(instance.setupA) // @ts-expect-error instance.notExist }) describe('options', () => { const MyComponent = { setup() { return { setupA: 1 } } } const { rawBindings, setup } = extractComponentOptions(MyComponent) expectType<number>(rawBindings.setupA) expectType<number>(setup.setupA) }) }) describe('functional', () => { // TODO `props.foo` is `number|undefined` // describe('defineComponent', () => { // const MyComponent = defineComponent((props: { foo: number }) => {}) // const { props } = extractComponentOptions(MyComponent) // expectType<number>(props.foo) // }) describe('function', () => { const MyComponent = (props: { foo: number }) => props.foo const { props } = extractComponentOptions(MyComponent) expectType<number>(props.foo) }) describe('typed', () => { const MyComponent: FunctionalComponent<{ foo: number }> = (_, _2) => {} const { props } = extractComponentOptions(MyComponent) expectType<number>(props.foo) }) }) declare type VueClass<Props = {}> = { new (): ComponentPublicInstance<Props> } describe('class', () => { const MyComponent: VueClass<{ foo: number }> = {} as any const { props } = extractComponentOptions(MyComponent) expectType<number>(props.foo) })
test-dts/component.test-d.ts
1
https://github.com/vuejs/core/commit/f6a5f09a3aaff4f156bd1d4cc5ae01331cffa427
[ 0.9735206961631775, 0.029866868630051613, 0.0001649932237342, 0.00028557609766721725, 0.1425822675228119 ]
{ "id": 2, "code_window": [ " expectType<Number>(rawBindings.setupA)\n", " expectType<Ref<Number>>(rawBindings.setupB)\n", " expectType<Ref<Number>>(rawBindings.setupC.a)\n", " expectType<Number>(rawBindings.setupA)\n", "\n", " // raw bindings props\n", " expectType<ExpectedProps['a']>(rawBindings.setupProps.a)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " expectType<Ref<Number> | undefined>(rawBindings.setupD)\n" ], "file_path": "test-dts/component.test-d.ts", "type": "replace", "edit_start_line_idx": 192 }
'use strict' if (process.env.NODE_ENV === 'production') { module.exports = require('./dist/shared.cjs.prod.js') } else { module.exports = require('./dist/shared.cjs.js') }
packages/shared/index.js
0
https://github.com/vuejs/core/commit/f6a5f09a3aaff4f156bd1d4cc5ae01331cffa427
[ 0.00017533148638904095, 0.00017533148638904095, 0.00017533148638904095, 0.00017533148638904095, 0 ]
{ "id": 2, "code_window": [ " expectType<Number>(rawBindings.setupA)\n", " expectType<Ref<Number>>(rawBindings.setupB)\n", " expectType<Ref<Number>>(rawBindings.setupC.a)\n", " expectType<Number>(rawBindings.setupA)\n", "\n", " // raw bindings props\n", " expectType<ExpectedProps['a']>(rawBindings.setupProps.a)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " expectType<Ref<Number> | undefined>(rawBindings.setupD)\n" ], "file_path": "test-dts/component.test-d.ts", "type": "replace", "edit_start_line_idx": 192 }
import { DirectiveTransform } from '../transform' export const noopDirectiveTransform: DirectiveTransform = () => ({ props: [] })
packages/compiler-core/src/transforms/noopDirectiveTransform.ts
0
https://github.com/vuejs/core/commit/f6a5f09a3aaff4f156bd1d4cc5ae01331cffa427
[ 0.00018875065143220127, 0.00018875065143220127, 0.00018875065143220127, 0.00018875065143220127, 0 ]
{ "id": 2, "code_window": [ " expectType<Number>(rawBindings.setupA)\n", " expectType<Ref<Number>>(rawBindings.setupB)\n", " expectType<Ref<Number>>(rawBindings.setupC.a)\n", " expectType<Number>(rawBindings.setupA)\n", "\n", " // raw bindings props\n", " expectType<ExpectedProps['a']>(rawBindings.setupProps.a)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " expectType<Ref<Number> | undefined>(rawBindings.setupD)\n" ], "file_path": "test-dts/component.test-d.ts", "type": "replace", "edit_start_line_idx": 192 }
import { markRaw } from '@vue/reactivity' export const enum NodeTypes { TEXT = 'text', ELEMENT = 'element', COMMENT = 'comment' } export const enum NodeOpTypes { CREATE = 'create', INSERT = 'insert', REMOVE = 'remove', SET_TEXT = 'setText', SET_ELEMENT_TEXT = 'setElementText', PATCH = 'patch' } export interface TestElement { id: number type: NodeTypes.ELEMENT parentNode: TestElement | null tag: string children: TestNode[] props: Record<string, any> eventListeners: Record<string, Function | Function[]> | null } export interface TestText { id: number type: NodeTypes.TEXT parentNode: TestElement | null text: string } export interface TestComment { id: number type: NodeTypes.COMMENT parentNode: TestElement | null text: string } export type TestNode = TestElement | TestText | TestComment export interface NodeOp { type: NodeOpTypes nodeType?: NodeTypes tag?: string text?: string targetNode?: TestNode parentNode?: TestElement refNode?: TestNode | null propKey?: string propPrevValue?: any propNextValue?: any } let nodeId: number = 0 let recordedNodeOps: NodeOp[] = [] export function logNodeOp(op: NodeOp) { recordedNodeOps.push(op) } export function resetOps() { recordedNodeOps = [] } export function dumpOps(): NodeOp[] { const ops = recordedNodeOps.slice() resetOps() return ops } function createElement(tag: string): TestElement { const node: TestElement = { id: nodeId++, type: NodeTypes.ELEMENT, tag, children: [], props: {}, parentNode: null, eventListeners: null } logNodeOp({ type: NodeOpTypes.CREATE, nodeType: NodeTypes.ELEMENT, targetNode: node, tag }) // avoid test nodes from being observed markRaw(node) return node } function createText(text: string): TestText { const node: TestText = { id: nodeId++, type: NodeTypes.TEXT, text, parentNode: null } logNodeOp({ type: NodeOpTypes.CREATE, nodeType: NodeTypes.TEXT, targetNode: node, text }) // avoid test nodes from being observed markRaw(node) return node } function createComment(text: string): TestComment { const node: TestComment = { id: nodeId++, type: NodeTypes.COMMENT, text, parentNode: null } logNodeOp({ type: NodeOpTypes.CREATE, nodeType: NodeTypes.COMMENT, targetNode: node, text }) // avoid test nodes from being observed markRaw(node) return node } function setText(node: TestText, text: string) { logNodeOp({ type: NodeOpTypes.SET_TEXT, targetNode: node, text }) node.text = text } function insert(child: TestNode, parent: TestElement, ref?: TestNode | null) { let refIndex if (ref) { refIndex = parent.children.indexOf(ref) if (refIndex === -1) { console.error('ref: ', ref) console.error('parent: ', parent) throw new Error('ref is not a child of parent') } } logNodeOp({ type: NodeOpTypes.INSERT, targetNode: child, parentNode: parent, refNode: ref }) // remove the node first, but don't log it as a REMOVE op remove(child, false) // re-calculate the ref index because the child's removal may have affected it refIndex = ref ? parent.children.indexOf(ref) : -1 if (refIndex === -1) { parent.children.push(child) child.parentNode = parent } else { parent.children.splice(refIndex, 0, child) child.parentNode = parent } } function remove(child: TestNode, logOp: boolean = true) { const parent = child.parentNode if (parent) { if (logOp) { logNodeOp({ type: NodeOpTypes.REMOVE, targetNode: child, parentNode: parent }) } const i = parent.children.indexOf(child) if (i > -1) { parent.children.splice(i, 1) } else { console.error('target: ', child) console.error('parent: ', parent) throw Error('target is not a childNode of parent') } child.parentNode = null } } function setElementText(el: TestElement, text: string) { logNodeOp({ type: NodeOpTypes.SET_ELEMENT_TEXT, targetNode: el, text }) el.children.forEach(c => { c.parentNode = null }) if (!text) { el.children = [] } else { el.children = [ { id: nodeId++, type: NodeTypes.TEXT, text, parentNode: el } ] } } function parentNode(node: TestNode): TestElement | null { return node.parentNode } function nextSibling(node: TestNode): TestNode | null { const parent = node.parentNode if (!parent) { return null } const i = parent.children.indexOf(node) return parent.children[i + 1] || null } function querySelector(): any { throw new Error('querySelector not supported in test renderer.') } function setScopeId(el: TestElement, id: string) { el.props[id] = '' } export const nodeOps = { insert, remove, createElement, createText, createComment, setText, setElementText, parentNode, nextSibling, querySelector, setScopeId }
packages/runtime-test/src/nodeOps.ts
0
https://github.com/vuejs/core/commit/f6a5f09a3aaff4f156bd1d4cc5ae01331cffa427
[ 0.0001774902339093387, 0.00017430608568247408, 0.000165360834216699, 0.00017458279035054147, 0.0000025892359190038405 ]
{ "id": 3, "code_window": [ " // setup\n", " expectType<Number>(setup.setupA)\n", " expectType<Number>(setup.setupB)\n", " expectType<Ref<Number>>(setup.setupC.a)\n", " expectType<Number>(setup.setupA)\n", "\n", " // raw bindings props\n", " expectType<ExpectedProps['a']>(setup.setupProps.a)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " expectType<number | undefined>(setup.setupD)\n" ], "file_path": "test-dts/component.test-d.ts", "type": "replace", "edit_start_line_idx": 217 }
import { describe, Component, defineComponent, PropType, ref, Ref, expectError, expectType, ShallowUnwrapRef, FunctionalComponent, ComponentPublicInstance, toRefs } from './index' declare function extractComponentOptions<Props, RawBindings>( obj: Component<Props, RawBindings> ): { props: Props rawBindings: RawBindings setup: ShallowUnwrapRef<RawBindings> } describe('object props', () => { interface ExpectedProps { a?: number | undefined b: string e?: Function bb: string bbb: string cc?: string[] | undefined dd: { n: 1 } ee?: () => string ff?: (a: number, b: string) => { a: boolean } ccc?: string[] | undefined ddd: string[] eee: () => { a: string } fff: (a: number, b: string) => { a: boolean } hhh: boolean ggg: 'foo' | 'bar' ffff: (a: number, b: string) => { a: boolean } validated?: string object?: object } interface ExpectedRefs { a: Ref<number | undefined> b: Ref<string> e: Ref<Function | undefined> bb: Ref<string> bbb: Ref<string> cc: Ref<string[] | undefined> dd: Ref<{ n: 1 }> ee: Ref<(() => string) | undefined> ff: Ref<((a: number, b: string) => { a: boolean }) | undefined> ccc: Ref<string[] | undefined> ddd: Ref<string[]> eee: Ref<() => { a: string }> fff: Ref<(a: number, b: string) => { a: boolean }> hhh: Ref<boolean> ggg: Ref<'foo' | 'bar'> ffff: Ref<(a: number, b: string) => { a: boolean }> validated: Ref<string | undefined> object: Ref<object | undefined> } describe('defineComponent', () => { const MyComponent = defineComponent({ props: { a: Number, // required should make property non-void b: { type: String, required: true }, e: Function, // default value should infer type and make it non-void bb: { default: 'hello' }, bbb: { // Note: default function value requires arrow syntax + explicit // annotation default: (props: any) => (props.bb as string) || 'foo' }, // explicit type casting cc: Array as PropType<string[]>, // required + type casting dd: { type: Object as PropType<{ n: 1 }>, required: true }, // return type ee: Function as PropType<() => string>, // arguments + object return ff: Function as PropType<(a: number, b: string) => { a: boolean }>, // explicit type casting with constructor ccc: Array as () => string[], // required + contructor type casting ddd: { type: Array as () => string[], required: true }, // required + object return eee: { type: Function as PropType<() => { a: string }>, required: true }, // required + arguments + object return fff: { type: Function as PropType<(a: number, b: string) => { a: boolean }>, required: true }, hhh: { type: Boolean, required: true }, // default + type casting ggg: { type: String as PropType<'foo' | 'bar'>, default: 'foo' }, // default + function ffff: { type: Function as PropType<(a: number, b: string) => { a: boolean }>, default: (_a: number, _b: string) => ({ a: true }) }, validated: { type: String, // validator requires explicit annotation validator: (val: unknown) => val !== '' }, object: Object as PropType<object> }, setup(props) { const refs = toRefs(props) expectType<ExpectedRefs['a']>(refs.a) expectType<ExpectedRefs['b']>(refs.b) expectType<ExpectedRefs['e']>(refs.e) expectType<ExpectedRefs['bb']>(refs.bb) expectType<ExpectedRefs['bbb']>(refs.bbb) expectType<ExpectedRefs['cc']>(refs.cc) expectType<ExpectedRefs['dd']>(refs.dd) expectType<ExpectedRefs['ee']>(refs.ee) expectType<ExpectedRefs['ff']>(refs.ff) expectType<ExpectedRefs['ccc']>(refs.ccc) expectType<ExpectedRefs['ddd']>(refs.ddd) expectType<ExpectedRefs['eee']>(refs.eee) expectType<ExpectedRefs['fff']>(refs.fff) expectType<ExpectedRefs['hhh']>(refs.hhh) expectType<ExpectedRefs['ggg']>(refs.ggg) expectType<ExpectedRefs['ffff']>(refs.ffff) expectType<ExpectedRefs['validated']>(refs.validated) expectType<ExpectedRefs['object']>(refs.object) return { setupA: 1, setupB: ref(1), setupC: { a: ref(2) }, setupProps: props } } }) const { props, rawBindings, setup } = extractComponentOptions(MyComponent) // props expectType<ExpectedProps['a']>(props.a) expectType<ExpectedProps['b']>(props.b) expectType<ExpectedProps['e']>(props.e) expectType<ExpectedProps['bb']>(props.bb) expectType<ExpectedProps['bbb']>(props.bbb) expectType<ExpectedProps['cc']>(props.cc) expectType<ExpectedProps['dd']>(props.dd) expectType<ExpectedProps['ee']>(props.ee) expectType<ExpectedProps['ff']>(props.ff) expectType<ExpectedProps['ccc']>(props.ccc) expectType<ExpectedProps['ddd']>(props.ddd) expectType<ExpectedProps['eee']>(props.eee) expectType<ExpectedProps['fff']>(props.fff) expectType<ExpectedProps['hhh']>(props.hhh) expectType<ExpectedProps['ggg']>(props.ggg) expectType<ExpectedProps['ffff']>(props.ffff) expectType<ExpectedProps['validated']>(props.validated) expectType<ExpectedProps['object']>(props.object) // raw bindings expectType<Number>(rawBindings.setupA) expectType<Ref<Number>>(rawBindings.setupB) expectType<Ref<Number>>(rawBindings.setupC.a) expectType<Number>(rawBindings.setupA) // raw bindings props expectType<ExpectedProps['a']>(rawBindings.setupProps.a) expectType<ExpectedProps['b']>(rawBindings.setupProps.b) expectType<ExpectedProps['e']>(rawBindings.setupProps.e) expectType<ExpectedProps['bb']>(rawBindings.setupProps.bb) expectType<ExpectedProps['bbb']>(rawBindings.setupProps.bbb) expectType<ExpectedProps['cc']>(rawBindings.setupProps.cc) expectType<ExpectedProps['dd']>(rawBindings.setupProps.dd) expectType<ExpectedProps['ee']>(rawBindings.setupProps.ee) expectType<ExpectedProps['ff']>(rawBindings.setupProps.ff) expectType<ExpectedProps['ccc']>(rawBindings.setupProps.ccc) expectType<ExpectedProps['ddd']>(rawBindings.setupProps.ddd) expectType<ExpectedProps['eee']>(rawBindings.setupProps.eee) expectType<ExpectedProps['fff']>(rawBindings.setupProps.fff) expectType<ExpectedProps['hhh']>(rawBindings.setupProps.hhh) expectType<ExpectedProps['ggg']>(rawBindings.setupProps.ggg) expectType<ExpectedProps['ffff']>(rawBindings.setupProps.ffff) expectType<ExpectedProps['validated']>(rawBindings.setupProps.validated) // setup expectType<Number>(setup.setupA) expectType<Number>(setup.setupB) expectType<Ref<Number>>(setup.setupC.a) expectType<Number>(setup.setupA) // raw bindings props expectType<ExpectedProps['a']>(setup.setupProps.a) expectType<ExpectedProps['b']>(setup.setupProps.b) expectType<ExpectedProps['e']>(setup.setupProps.e) expectType<ExpectedProps['bb']>(setup.setupProps.bb) expectType<ExpectedProps['bbb']>(setup.setupProps.bbb) expectType<ExpectedProps['cc']>(setup.setupProps.cc) expectType<ExpectedProps['dd']>(setup.setupProps.dd) expectType<ExpectedProps['ee']>(setup.setupProps.ee) expectType<ExpectedProps['ff']>(setup.setupProps.ff) expectType<ExpectedProps['ccc']>(setup.setupProps.ccc) expectType<ExpectedProps['ddd']>(setup.setupProps.ddd) expectType<ExpectedProps['eee']>(setup.setupProps.eee) expectType<ExpectedProps['fff']>(setup.setupProps.fff) expectType<ExpectedProps['hhh']>(setup.setupProps.hhh) expectType<ExpectedProps['ggg']>(setup.setupProps.ggg) expectType<ExpectedProps['ffff']>(setup.setupProps.ffff) expectType<ExpectedProps['validated']>(setup.setupProps.validated) // instance const instance = new MyComponent() expectType<number>(instance.setupA) // @ts-expect-error instance.notExist }) describe('options', () => { const MyComponent = { props: { a: Number, // required should make property non-void b: { type: String, required: true }, e: Function, // default value should infer type and make it non-void bb: { default: 'hello' }, bbb: { // Note: default function value requires arrow syntax + explicit // annotation default: (props: any) => (props.bb as string) || 'foo' }, // explicit type casting cc: Array as PropType<string[]>, // required + type casting dd: { type: Object as PropType<{ n: 1 }>, required: true }, // return type ee: Function as PropType<() => string>, // arguments + object return ff: Function as PropType<(a: number, b: string) => { a: boolean }>, // explicit type casting with constructor ccc: Array as () => string[], // required + contructor type casting ddd: { type: Array as () => string[], required: true }, // required + object return eee: { type: Function as PropType<() => { a: string }>, required: true }, // required + arguments + object return fff: { type: Function as PropType<(a: number, b: string) => { a: boolean }>, required: true }, hhh: { type: Boolean, required: true }, // default + type casting ggg: { type: String as PropType<'foo' | 'bar'>, default: 'foo' }, // default + function ffff: { type: Function as PropType<(a: number, b: string) => { a: boolean }>, default: (_a: number, _b: string) => ({ a: true }) }, validated: { type: String, // validator requires explicit annotation validator: (val: unknown) => val !== '' }, object: Object as PropType<object> }, setup() { return { setupA: 1 } } } as const const { props, rawBindings, setup } = extractComponentOptions(MyComponent) // props expectType<ExpectedProps['a']>(props.a) expectType<ExpectedProps['b']>(props.b) expectType<ExpectedProps['e']>(props.e) expectType<ExpectedProps['bb']>(props.bb) expectType<ExpectedProps['bbb']>(props.bbb) expectType<ExpectedProps['cc']>(props.cc) expectType<ExpectedProps['dd']>(props.dd) expectType<ExpectedProps['ee']>(props.ee) expectType<ExpectedProps['ff']>(props.ff) expectType<ExpectedProps['ccc']>(props.ccc) expectType<ExpectedProps['ddd']>(props.ddd) expectType<ExpectedProps['eee']>(props.eee) expectType<ExpectedProps['fff']>(props.fff) expectType<ExpectedProps['hhh']>(props.hhh) expectType<ExpectedProps['ggg']>(props.ggg) // expectType<ExpectedProps['ffff']>(props.ffff) // todo fix expectType<ExpectedProps['validated']>(props.validated) expectType<ExpectedProps['object']>(props.object) // rawBindings expectType<Number>(rawBindings.setupA) //setup expectType<Number>(setup.setupA) }) }) describe('array props', () => { describe('defineComponent', () => { const MyComponent = defineComponent({ props: ['a', 'b'], setup() { return { c: 1 } } }) const { props, rawBindings, setup } = extractComponentOptions(MyComponent) // @ts-expect-error props should be readonly expectError((props.a = 1)) expectType<any>(props.a) expectType<any>(props.b) expectType<number>(rawBindings.c) expectType<number>(setup.c) }) describe('options', () => { const MyComponent = { props: ['a', 'b'] as const, setup() { return { c: 1 } } } const { props, rawBindings, setup } = extractComponentOptions(MyComponent) // @ts-expect-error props should be readonly expectError((props.a = 1)) // TODO infer the correct keys // expectType<any>(props.a) // expectType<any>(props.b) expectType<number>(rawBindings.c) expectType<number>(setup.c) }) }) describe('no props', () => { describe('defineComponent', () => { const MyComponent = defineComponent({ setup() { return { setupA: 1 } } }) const { rawBindings, setup } = extractComponentOptions(MyComponent) expectType<number>(rawBindings.setupA) expectType<number>(setup.setupA) // instance const instance = new MyComponent() expectType<number>(instance.setupA) // @ts-expect-error instance.notExist }) describe('options', () => { const MyComponent = { setup() { return { setupA: 1 } } } const { rawBindings, setup } = extractComponentOptions(MyComponent) expectType<number>(rawBindings.setupA) expectType<number>(setup.setupA) }) }) describe('functional', () => { // TODO `props.foo` is `number|undefined` // describe('defineComponent', () => { // const MyComponent = defineComponent((props: { foo: number }) => {}) // const { props } = extractComponentOptions(MyComponent) // expectType<number>(props.foo) // }) describe('function', () => { const MyComponent = (props: { foo: number }) => props.foo const { props } = extractComponentOptions(MyComponent) expectType<number>(props.foo) }) describe('typed', () => { const MyComponent: FunctionalComponent<{ foo: number }> = (_, _2) => {} const { props } = extractComponentOptions(MyComponent) expectType<number>(props.foo) }) }) declare type VueClass<Props = {}> = { new (): ComponentPublicInstance<Props> } describe('class', () => { const MyComponent: VueClass<{ foo: number }> = {} as any const { props } = extractComponentOptions(MyComponent) expectType<number>(props.foo) })
test-dts/component.test-d.ts
1
https://github.com/vuejs/core/commit/f6a5f09a3aaff4f156bd1d4cc5ae01331cffa427
[ 0.9825330972671509, 0.024815842509269714, 0.00016322983719874173, 0.00087225332390517, 0.14015458524227142 ]
{ "id": 3, "code_window": [ " // setup\n", " expectType<Number>(setup.setupA)\n", " expectType<Number>(setup.setupB)\n", " expectType<Ref<Number>>(setup.setupC.a)\n", " expectType<Number>(setup.setupA)\n", "\n", " // raw bindings props\n", " expectType<ExpectedProps['a']>(setup.setupProps.a)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " expectType<number | undefined>(setup.setupD)\n" ], "file_path": "test-dts/component.test-d.ts", "type": "replace", "edit_start_line_idx": 217 }
import { compile } from '../src' describe('ssr: v-for', () => { test('basic', () => { expect(compile(`<div v-for="i in list" />`).code).toMatchInlineSnapshot(` "const { ssrRenderList: _ssrRenderList } = require(\\"@vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { _push(\`<!--[-->\`) _ssrRenderList(_ctx.list, (i) => { _push(\`<div></div>\`) }) _push(\`<!--]-->\`) }" `) }) test('nested content', () => { expect(compile(`<div v-for="i in list">foo<span>bar</span></div>`).code) .toMatchInlineSnapshot(` "const { ssrRenderList: _ssrRenderList } = require(\\"@vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { _push(\`<!--[-->\`) _ssrRenderList(_ctx.list, (i) => { _push(\`<div>foo<span>bar</span></div>\`) }) _push(\`<!--]-->\`) }" `) }) test('nested v-for', () => { expect( compile( `<div v-for="row, i in list">` + `<div v-for="j in row">{{ i }},{{ j }}</div>` + `</div>` ).code ).toMatchInlineSnapshot(` "const { ssrInterpolate: _ssrInterpolate, ssrRenderList: _ssrRenderList } = require(\\"@vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { _push(\`<!--[-->\`) _ssrRenderList(_ctx.list, (row, i) => { _push(\`<div><!--[-->\`) _ssrRenderList(row, (j) => { _push(\`<div>\${ _ssrInterpolate(i) },\${ _ssrInterpolate(j) }</div>\`) }) _push(\`<!--]--></div>\`) }) _push(\`<!--]-->\`) }" `) }) test('template v-for (text)', () => { expect(compile(`<template v-for="i in list">{{ i }}</template>`).code) .toMatchInlineSnapshot(` "const { ssrInterpolate: _ssrInterpolate, ssrRenderList: _ssrRenderList } = require(\\"@vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { _push(\`<!--[-->\`) _ssrRenderList(_ctx.list, (i) => { _push(\`<!--[-->\${_ssrInterpolate(i)}<!--]-->\`) }) _push(\`<!--]-->\`) }" `) }) test('template v-for (single element)', () => { expect( compile(`<template v-for="i in list"><span>{{ i }}</span></template>`) .code ).toMatchInlineSnapshot(` "const { ssrInterpolate: _ssrInterpolate, ssrRenderList: _ssrRenderList } = require(\\"@vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { _push(\`<!--[-->\`) _ssrRenderList(_ctx.list, (i) => { _push(\`<span>\${_ssrInterpolate(i)}</span>\`) }) _push(\`<!--]-->\`) }" `) }) test('template v-for (multi element)', () => { expect( compile( `<template v-for="i in list"><span>{{ i }}</span><span>{{ i + 1 }}</span></template>` ).code ).toMatchInlineSnapshot(` "const { ssrInterpolate: _ssrInterpolate, ssrRenderList: _ssrRenderList } = require(\\"@vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { _push(\`<!--[-->\`) _ssrRenderList(_ctx.list, (i) => { _push(\`<!--[--><span>\${ _ssrInterpolate(i) }</span><span>\${ _ssrInterpolate(i + 1) }</span><!--]-->\`) }) _push(\`<!--]-->\`) }" `) }) test('render loop args should not be prefixed', () => { const { code } = compile( `<div v-for="{ foo }, index in list">{{ foo + bar + index }}</div>` ) expect(code).toMatch(`_ctx.bar`) expect(code).not.toMatch(`_ctx.foo`) expect(code).not.toMatch(`_ctx.index`) expect(code).toMatchInlineSnapshot(` "const { ssrInterpolate: _ssrInterpolate, ssrRenderList: _ssrRenderList } = require(\\"@vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { _push(\`<!--[-->\`) _ssrRenderList(_ctx.list, ({ foo }, index) => { _push(\`<div>\${_ssrInterpolate(foo + _ctx.bar + index)}</div>\`) }) _push(\`<!--]-->\`) }" `) }) })
packages/compiler-ssr/__tests__/ssrVFor.spec.ts
0
https://github.com/vuejs/core/commit/f6a5f09a3aaff4f156bd1d4cc5ae01331cffa427
[ 0.00017711982945911586, 0.0001716404949547723, 0.0001660819980315864, 0.0001720101572573185, 0.000003567681233107578 ]
{ "id": 3, "code_window": [ " // setup\n", " expectType<Number>(setup.setupA)\n", " expectType<Number>(setup.setupB)\n", " expectType<Ref<Number>>(setup.setupC.a)\n", " expectType<Number>(setup.setupA)\n", "\n", " // raw bindings props\n", " expectType<ExpectedProps['a']>(setup.setupProps.a)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " expectType<number | undefined>(setup.setupD)\n" ], "file_path": "test-dts/component.test-d.ts", "type": "replace", "edit_start_line_idx": 217 }
import { makeMap } from './makeMap' const GLOBALS_WHITE_LISTED = 'Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,' + 'decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,' + 'Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt' export const isGloballyWhitelisted = /*#__PURE__*/ makeMap(GLOBALS_WHITE_LISTED)
packages/shared/src/globalsWhitelist.ts
0
https://github.com/vuejs/core/commit/f6a5f09a3aaff4f156bd1d4cc5ae01331cffa427
[ 0.00019531682482920587, 0.00019531682482920587, 0.00019531682482920587, 0.00019531682482920587, 0 ]
{ "id": 3, "code_window": [ " // setup\n", " expectType<Number>(setup.setupA)\n", " expectType<Number>(setup.setupB)\n", " expectType<Ref<Number>>(setup.setupC.a)\n", " expectType<Number>(setup.setupA)\n", "\n", " // raw bindings props\n", " expectType<ExpectedProps['a']>(setup.setupProps.a)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " expectType<number | undefined>(setup.setupD)\n" ], "file_path": "test-dts/component.test-d.ts", "type": "replace", "edit_start_line_idx": 217 }
import { h, render, nextTick, defineComponent, vModelDynamic, withDirectives, VNode, ref } from '@vue/runtime-dom' const triggerEvent = (type: string, el: Element) => { const event = new Event(type) el.dispatchEvent(event) } const withVModel = (node: VNode, arg: any, mods?: any) => withDirectives(node, [[vModelDynamic, arg, '', mods]]) const setValue = function(this: any, value: any) { this.value = value } let root: any beforeEach(() => { root = document.createElement('div') as any }) describe('vModel', () => { it('should work with text input', async () => { const manualListener = jest.fn() const component = defineComponent({ data() { return { value: null } }, render() { return [ withVModel( h('input', { 'onUpdate:modelValue': setValue.bind(this), onInput: () => { manualListener(data.value) } }), this.value ) ] } }) render(h(component), root) const input = root.querySelector('input')! const data = root._vnode.component.data expect(input.value).toEqual('') input.value = 'foo' triggerEvent('input', input) await nextTick() expect(data.value).toEqual('foo') // #1931 expect(manualListener).toHaveBeenCalledWith('foo') data.value = 'bar' await nextTick() expect(input.value).toEqual('bar') data.value = undefined await nextTick() expect(input.value).toEqual('') }) it('should work with multiple listeners', async () => { const spy = jest.fn() const component = defineComponent({ data() { return { value: null } }, render() { return [ withVModel( h('input', { 'onUpdate:modelValue': [setValue.bind(this), spy] }), this.value ) ] } }) render(h(component), root) const input = root.querySelector('input')! const data = root._vnode.component.data input.value = 'foo' triggerEvent('input', input) await nextTick() expect(data.value).toEqual('foo') expect(spy).toHaveBeenCalledWith('foo') }) it('should work with updated listeners', async () => { const spy1 = jest.fn() const spy2 = jest.fn() const toggle = ref(true) const component = defineComponent({ render() { return [ withVModel( h('input', { 'onUpdate:modelValue': toggle.value ? spy1 : spy2 }), 'foo' ) ] } }) render(h(component), root) const input = root.querySelector('input')! input.value = 'foo' triggerEvent('input', input) await nextTick() expect(spy1).toHaveBeenCalledWith('foo') // update listener toggle.value = false await nextTick() input.value = 'bar' triggerEvent('input', input) await nextTick() expect(spy1).not.toHaveBeenCalledWith('bar') expect(spy2).toHaveBeenCalledWith('bar') }) it('should work with textarea', async () => { const component = defineComponent({ data() { return { value: null } }, render() { return [ withVModel( h('textarea', { 'onUpdate:modelValue': setValue.bind(this) }), this.value ) ] } }) render(h(component), root) const input = root.querySelector('textarea') const data = root._vnode.component.data input.value = 'foo' triggerEvent('input', input) await nextTick() expect(data.value).toEqual('foo') data.value = 'bar' await nextTick() expect(input.value).toEqual('bar') }) it('should support modifiers', async () => { const component = defineComponent({ data() { return { number: null, trim: null, lazy: null } }, render() { return [ withVModel( h('input', { class: 'number', 'onUpdate:modelValue': (val: any) => { this.number = val } }), this.number, { number: true } ), withVModel( h('input', { class: 'trim', 'onUpdate:modelValue': (val: any) => { this.trim = val } }), this.trim, { trim: true } ), withVModel( h('input', { class: 'lazy', 'onUpdate:modelValue': (val: any) => { this.lazy = val } }), this.lazy, { lazy: true } ) ] } }) render(h(component), root) const number = root.querySelector('.number') const trim = root.querySelector('.trim') const lazy = root.querySelector('.lazy') const data = root._vnode.component.data number.value = '+01.2' triggerEvent('input', number) await nextTick() expect(data.number).toEqual(1.2) trim.value = ' hello, world ' triggerEvent('input', trim) await nextTick() expect(data.trim).toEqual('hello, world') lazy.value = 'foo' triggerEvent('change', lazy) await nextTick() expect(data.lazy).toEqual('foo') }) it('should work with checkbox', async () => { const component = defineComponent({ data() { return { value: null } }, render() { return [ withVModel( h('input', { type: 'checkbox', 'onUpdate:modelValue': setValue.bind(this) }), this.value ) ] } }) render(h(component), root) const input = root.querySelector('input') const data = root._vnode.component.data input.checked = true triggerEvent('change', input) await nextTick() expect(data.value).toEqual(true) data.value = false await nextTick() expect(input.checked).toEqual(false) data.value = true await nextTick() expect(input.checked).toEqual(true) input.checked = false triggerEvent('change', input) await nextTick() expect(data.value).toEqual(false) }) it('should work with checkbox and true-value/false-value', async () => { const component = defineComponent({ data() { return { value: 'yes' } }, render() { return [ withVModel( h('input', { type: 'checkbox', 'true-value': 'yes', 'false-value': 'no', 'onUpdate:modelValue': setValue.bind(this) }), this.value ) ] } }) render(h(component), root) const input = root.querySelector('input') const data = root._vnode.component.data // DOM checked state should respect initial true-value/false-value expect(input.checked).toEqual(true) input.checked = false triggerEvent('change', input) await nextTick() expect(data.value).toEqual('no') data.value = 'yes' await nextTick() expect(input.checked).toEqual(true) data.value = 'no' await nextTick() expect(input.checked).toEqual(false) input.checked = true triggerEvent('change', input) await nextTick() expect(data.value).toEqual('yes') }) it('should work with checkbox and true-value/false-value with object values', async () => { const component = defineComponent({ data() { return { value: null } }, render() { return [ withVModel( h('input', { type: 'checkbox', 'true-value': { yes: 'yes' }, 'false-value': { no: 'no' }, 'onUpdate:modelValue': setValue.bind(this) }), this.value ) ] } }) render(h(component), root) const input = root.querySelector('input') const data = root._vnode.component.data input.checked = true triggerEvent('change', input) await nextTick() expect(data.value).toEqual({ yes: 'yes' }) data.value = { no: 'no' } await nextTick() expect(input.checked).toEqual(false) data.value = { yes: 'yes' } await nextTick() expect(input.checked).toEqual(true) input.checked = false triggerEvent('change', input) await nextTick() expect(data.value).toEqual({ no: 'no' }) }) it(`should support array as a checkbox model`, async () => { const component = defineComponent({ data() { return { value: [] } }, render() { return [ withVModel( h('input', { type: 'checkbox', class: 'foo', value: 'foo', 'onUpdate:modelValue': setValue.bind(this) }), this.value ), withVModel( h('input', { type: 'checkbox', class: 'bar', value: 'bar', 'onUpdate:modelValue': setValue.bind(this) }), this.value ) ] } }) render(h(component), root) const foo = root.querySelector('.foo') const bar = root.querySelector('.bar') const data = root._vnode.component.data foo.checked = true triggerEvent('change', foo) await nextTick() expect(data.value).toMatchObject(['foo']) bar.checked = true triggerEvent('change', bar) await nextTick() expect(data.value).toMatchObject(['foo', 'bar']) bar.checked = false triggerEvent('change', bar) await nextTick() expect(data.value).toMatchObject(['foo']) foo.checked = false triggerEvent('change', foo) await nextTick() expect(data.value).toMatchObject([]) data.value = ['foo'] await nextTick() expect(bar.checked).toEqual(false) expect(foo.checked).toEqual(true) data.value = ['bar'] await nextTick() expect(foo.checked).toEqual(false) expect(bar.checked).toEqual(true) data.value = [] await nextTick() expect(foo.checked).toEqual(false) expect(bar.checked).toEqual(false) }) it(`should support Set as a checkbox model`, async () => { const component = defineComponent({ data() { return { value: new Set() } }, render() { return [ withVModel( h('input', { type: 'checkbox', class: 'foo', value: 'foo', 'onUpdate:modelValue': setValue.bind(this) }), this.value ), withVModel( h('input', { type: 'checkbox', class: 'bar', value: 'bar', 'onUpdate:modelValue': setValue.bind(this) }), this.value ) ] } }) render(h(component), root) const foo = root.querySelector('.foo') const bar = root.querySelector('.bar') const data = root._vnode.component.data foo.checked = true triggerEvent('change', foo) await nextTick() expect(data.value).toMatchObject(new Set(['foo'])) bar.checked = true triggerEvent('change', bar) await nextTick() expect(data.value).toMatchObject(new Set(['foo', 'bar'])) bar.checked = false triggerEvent('change', bar) await nextTick() expect(data.value).toMatchObject(new Set(['foo'])) foo.checked = false triggerEvent('change', foo) await nextTick() expect(data.value).toMatchObject(new Set()) data.value = new Set(['foo']) await nextTick() expect(bar.checked).toEqual(false) expect(foo.checked).toEqual(true) data.value = new Set(['bar']) await nextTick() expect(foo.checked).toEqual(false) expect(bar.checked).toEqual(true) data.value = new Set() await nextTick() expect(foo.checked).toEqual(false) expect(bar.checked).toEqual(false) }) it('should work with radio', async () => { const component = defineComponent({ data() { return { value: null } }, render() { return [ withVModel( h('input', { type: 'radio', class: 'foo', value: 'foo', 'onUpdate:modelValue': setValue.bind(this) }), this.value ), withVModel( h('input', { type: 'radio', class: 'bar', value: 'bar', 'onUpdate:modelValue': setValue.bind(this) }), this.value ) ] } }) render(h(component), root) const foo = root.querySelector('.foo') const bar = root.querySelector('.bar') const data = root._vnode.component.data foo.checked = true triggerEvent('change', foo) await nextTick() expect(data.value).toEqual('foo') bar.checked = true triggerEvent('change', bar) await nextTick() expect(data.value).toEqual('bar') data.value = null await nextTick() expect(foo.checked).toEqual(false) expect(bar.checked).toEqual(false) data.value = 'foo' await nextTick() expect(foo.checked).toEqual(true) expect(bar.checked).toEqual(false) data.value = 'bar' await nextTick() expect(foo.checked).toEqual(false) expect(bar.checked).toEqual(true) }) it('should work with single select', async () => { const component = defineComponent({ data() { return { value: null } }, render() { return [ withVModel( h( 'select', { value: null, 'onUpdate:modelValue': setValue.bind(this) }, [h('option', { value: 'foo' }), h('option', { value: 'bar' })] ), this.value ) ] } }) render(h(component), root) const input = root.querySelector('select') const foo = root.querySelector('option[value=foo]') const bar = root.querySelector('option[value=bar]') const data = root._vnode.component.data foo.selected = true triggerEvent('change', input) await nextTick() expect(data.value).toEqual('foo') foo.selected = false bar.selected = true triggerEvent('change', input) await nextTick() expect(data.value).toEqual('bar') foo.selected = false bar.selected = false data.value = 'foo' await nextTick() expect(input.value).toEqual('foo') expect(foo.selected).toEqual(true) expect(bar.selected).toEqual(false) foo.selected = true bar.selected = false data.value = 'bar' await nextTick() expect(input.value).toEqual('bar') expect(foo.selected).toEqual(false) expect(bar.selected).toEqual(true) }) it('multiple select (model is Array)', async () => { const component = defineComponent({ data() { return { value: [] } }, render() { return [ withVModel( h( 'select', { value: null, multiple: true, 'onUpdate:modelValue': setValue.bind(this) }, [h('option', { value: 'foo' }), h('option', { value: 'bar' })] ), this.value ) ] } }) render(h(component), root) const input = root.querySelector('select') const foo = root.querySelector('option[value=foo]') const bar = root.querySelector('option[value=bar]') const data = root._vnode.component.data foo.selected = true triggerEvent('change', input) await nextTick() expect(data.value).toMatchObject(['foo']) foo.selected = false bar.selected = true triggerEvent('change', input) await nextTick() expect(data.value).toMatchObject(['bar']) foo.selected = true bar.selected = true triggerEvent('change', input) await nextTick() expect(data.value).toMatchObject(['foo', 'bar']) foo.selected = false bar.selected = false data.value = ['foo'] await nextTick() expect(input.value).toEqual('foo') expect(foo.selected).toEqual(true) expect(bar.selected).toEqual(false) foo.selected = false bar.selected = false data.value = ['foo', 'bar'] await nextTick() expect(foo.selected).toEqual(true) expect(bar.selected).toEqual(true) }) it('v-model.number should work with select tag', async () => { const component = defineComponent({ data() { return { value: null } }, render() { return [ withVModel( h( 'select', { value: null, 'onUpdate:modelValue': setValue.bind(this) }, [h('option', { value: '1' }), h('option', { value: '2' })] ), this.value, { number: true } ) ] } }) render(h(component), root) const input = root.querySelector('select') const one = root.querySelector('option[value="1"]') const data = root._vnode.component.data one.selected = true triggerEvent('change', input) await nextTick() expect(typeof data.value).toEqual('number') expect(data.value).toEqual(1) }) it('v-model.number should work with multiple select', async () => { const component = defineComponent({ data() { return { value: [] } }, render() { return [ withVModel( h( 'select', { value: null, multiple: true, 'onUpdate:modelValue': setValue.bind(this) }, [h('option', { value: '1' }), h('option', { value: '2' })] ), this.value, { number: true } ) ] } }) render(h(component), root) const input = root.querySelector('select') const one = root.querySelector('option[value="1"]') const two = root.querySelector('option[value="2"]') const data = root._vnode.component.data one.selected = true two.selected = false triggerEvent('change', input) await nextTick() expect(data.value).toMatchObject([1]) one.selected = false two.selected = true triggerEvent('change', input) await nextTick() expect(data.value).toMatchObject([2]) one.selected = true two.selected = true triggerEvent('change', input) await nextTick() expect(data.value).toMatchObject([1, 2]) one.selected = false two.selected = false data.value = [1] await nextTick() expect(one.selected).toEqual(true) expect(two.selected).toEqual(false) one.selected = false two.selected = false data.value = [1, 2] await nextTick() expect(one.selected).toEqual(true) expect(two.selected).toEqual(true) }) it('multiple select (model is Array, option value is object)', async () => { const fooValue = { foo: 1 } const barValue = { bar: 1 } const component = defineComponent({ data() { return { value: [] } }, render() { return [ withVModel( h( 'select', { value: null, multiple: true, 'onUpdate:modelValue': setValue.bind(this) }, [ h('option', { value: fooValue }), h('option', { value: barValue }) ] ), this.value ) ] } }) render(h(component), root) await nextTick() const input = root.querySelector('select') const [foo, bar] = root.querySelectorAll('option') const data = root._vnode.component.data foo.selected = true triggerEvent('change', input) await nextTick() expect(data.value).toMatchObject([fooValue]) foo.selected = false bar.selected = true triggerEvent('change', input) await nextTick() expect(data.value).toMatchObject([barValue]) foo.selected = true bar.selected = true triggerEvent('change', input) await nextTick() expect(data.value).toMatchObject([fooValue, barValue]) foo.selected = false bar.selected = false data.value = [fooValue, barValue] await nextTick() expect(foo.selected).toEqual(true) expect(bar.selected).toEqual(true) foo.selected = false bar.selected = false data.value = [{ foo: 1 }, { bar: 1 }] await nextTick() // looseEqual expect(foo.selected).toEqual(true) expect(bar.selected).toEqual(true) }) it('multiple select (model is Set)', async () => { const component = defineComponent({ data() { return { value: new Set() } }, render() { return [ withVModel( h( 'select', { value: null, multiple: true, 'onUpdate:modelValue': setValue.bind(this) }, [h('option', { value: 'foo' }), h('option', { value: 'bar' })] ), this.value ) ] } }) render(h(component), root) const input = root.querySelector('select') const foo = root.querySelector('option[value=foo]') const bar = root.querySelector('option[value=bar]') const data = root._vnode.component.data foo.selected = true triggerEvent('change', input) await nextTick() expect(data.value).toBeInstanceOf(Set) expect(data.value).toMatchObject(new Set(['foo'])) foo.selected = false bar.selected = true triggerEvent('change', input) await nextTick() expect(data.value).toBeInstanceOf(Set) expect(data.value).toMatchObject(new Set(['bar'])) foo.selected = true bar.selected = true triggerEvent('change', input) await nextTick() expect(data.value).toBeInstanceOf(Set) expect(data.value).toMatchObject(new Set(['foo', 'bar'])) foo.selected = false bar.selected = false data.value = new Set(['foo']) await nextTick() expect(input.value).toEqual('foo') expect(foo.selected).toEqual(true) expect(bar.selected).toEqual(false) foo.selected = false bar.selected = false data.value = new Set(['foo', 'bar']) await nextTick() expect(foo.selected).toEqual(true) expect(bar.selected).toEqual(true) }) it('multiple select (model is Set, option value is object)', async () => { const fooValue = { foo: 1 } const barValue = { bar: 1 } const component = defineComponent({ data() { return { value: new Set() } }, render() { return [ withVModel( h( 'select', { value: null, multiple: true, 'onUpdate:modelValue': setValue.bind(this) }, [ h('option', { value: fooValue }), h('option', { value: barValue }) ] ), this.value ) ] } }) render(h(component), root) await nextTick() const input = root.querySelector('select') const [foo, bar] = root.querySelectorAll('option') const data = root._vnode.component.data foo.selected = true triggerEvent('change', input) await nextTick() expect(data.value).toMatchObject(new Set([fooValue])) foo.selected = false bar.selected = true triggerEvent('change', input) await nextTick() expect(data.value).toMatchObject(new Set([barValue])) foo.selected = true bar.selected = true triggerEvent('change', input) await nextTick() expect(data.value).toMatchObject(new Set([fooValue, barValue])) foo.selected = false bar.selected = false data.value = new Set([fooValue, barValue]) await nextTick() expect(foo.selected).toEqual(true) expect(bar.selected).toEqual(true) foo.selected = false bar.selected = false data.value = new Set([{ foo: 1 }, { bar: 1 }]) await nextTick() // whithout looseEqual, here is different from Array expect(foo.selected).toEqual(false) expect(bar.selected).toEqual(false) }) it('should work with composition session', async () => { const component = defineComponent({ data() { return { value: '' } }, render() { return [ withVModel( h('input', { 'onUpdate:modelValue': setValue.bind(this) }), this.value ) ] } }) render(h(component), root) const input = root.querySelector('input')! const data = root._vnode.component.data expect(input.value).toEqual('') //developer.mozilla.org/en-US/docs/Web/API/Element/compositionstart_event //compositionstart event could be fired after a user starts entering a Chinese character using a Pinyin IME input.value = '使用拼音' triggerEvent('compositionstart', input) await nextTick() expect(data.value).toEqual('') // input event has no effect during composition session input.value = '使用拼音输入' triggerEvent('input', input) await nextTick() expect(data.value).toEqual('') // After compositionend event being fired, an input event will be automatically trigger triggerEvent('compositionend', input) await nextTick() expect(data.value).toEqual('使用拼音输入') }) })
packages/runtime-dom/__tests__/directives/vModel.spec.ts
0
https://github.com/vuejs/core/commit/f6a5f09a3aaff4f156bd1d4cc5ae01331cffa427
[ 0.00018100185843650252, 0.00017564601148478687, 0.0001595769717823714, 0.00017542214482091367, 0.0000037436354887177004 ]
{ "id": 4, "code_window": [ "\n", " // instance\n", " const instance = new MyComponent()\n", " expectType<number>(instance.setupA)\n", " // @ts-expect-error\n", " instance.notExist\n", " })\n", "\n", " describe('options', () => {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " expectType<number | undefined>(instance.setupD)\n" ], "file_path": "test-dts/component.test-d.ts", "type": "add", "edit_start_line_idx": 241 }
import { describe, Component, defineComponent, PropType, ref, Ref, expectError, expectType, ShallowUnwrapRef, FunctionalComponent, ComponentPublicInstance, toRefs } from './index' declare function extractComponentOptions<Props, RawBindings>( obj: Component<Props, RawBindings> ): { props: Props rawBindings: RawBindings setup: ShallowUnwrapRef<RawBindings> } describe('object props', () => { interface ExpectedProps { a?: number | undefined b: string e?: Function bb: string bbb: string cc?: string[] | undefined dd: { n: 1 } ee?: () => string ff?: (a: number, b: string) => { a: boolean } ccc?: string[] | undefined ddd: string[] eee: () => { a: string } fff: (a: number, b: string) => { a: boolean } hhh: boolean ggg: 'foo' | 'bar' ffff: (a: number, b: string) => { a: boolean } validated?: string object?: object } interface ExpectedRefs { a: Ref<number | undefined> b: Ref<string> e: Ref<Function | undefined> bb: Ref<string> bbb: Ref<string> cc: Ref<string[] | undefined> dd: Ref<{ n: 1 }> ee: Ref<(() => string) | undefined> ff: Ref<((a: number, b: string) => { a: boolean }) | undefined> ccc: Ref<string[] | undefined> ddd: Ref<string[]> eee: Ref<() => { a: string }> fff: Ref<(a: number, b: string) => { a: boolean }> hhh: Ref<boolean> ggg: Ref<'foo' | 'bar'> ffff: Ref<(a: number, b: string) => { a: boolean }> validated: Ref<string | undefined> object: Ref<object | undefined> } describe('defineComponent', () => { const MyComponent = defineComponent({ props: { a: Number, // required should make property non-void b: { type: String, required: true }, e: Function, // default value should infer type and make it non-void bb: { default: 'hello' }, bbb: { // Note: default function value requires arrow syntax + explicit // annotation default: (props: any) => (props.bb as string) || 'foo' }, // explicit type casting cc: Array as PropType<string[]>, // required + type casting dd: { type: Object as PropType<{ n: 1 }>, required: true }, // return type ee: Function as PropType<() => string>, // arguments + object return ff: Function as PropType<(a: number, b: string) => { a: boolean }>, // explicit type casting with constructor ccc: Array as () => string[], // required + contructor type casting ddd: { type: Array as () => string[], required: true }, // required + object return eee: { type: Function as PropType<() => { a: string }>, required: true }, // required + arguments + object return fff: { type: Function as PropType<(a: number, b: string) => { a: boolean }>, required: true }, hhh: { type: Boolean, required: true }, // default + type casting ggg: { type: String as PropType<'foo' | 'bar'>, default: 'foo' }, // default + function ffff: { type: Function as PropType<(a: number, b: string) => { a: boolean }>, default: (_a: number, _b: string) => ({ a: true }) }, validated: { type: String, // validator requires explicit annotation validator: (val: unknown) => val !== '' }, object: Object as PropType<object> }, setup(props) { const refs = toRefs(props) expectType<ExpectedRefs['a']>(refs.a) expectType<ExpectedRefs['b']>(refs.b) expectType<ExpectedRefs['e']>(refs.e) expectType<ExpectedRefs['bb']>(refs.bb) expectType<ExpectedRefs['bbb']>(refs.bbb) expectType<ExpectedRefs['cc']>(refs.cc) expectType<ExpectedRefs['dd']>(refs.dd) expectType<ExpectedRefs['ee']>(refs.ee) expectType<ExpectedRefs['ff']>(refs.ff) expectType<ExpectedRefs['ccc']>(refs.ccc) expectType<ExpectedRefs['ddd']>(refs.ddd) expectType<ExpectedRefs['eee']>(refs.eee) expectType<ExpectedRefs['fff']>(refs.fff) expectType<ExpectedRefs['hhh']>(refs.hhh) expectType<ExpectedRefs['ggg']>(refs.ggg) expectType<ExpectedRefs['ffff']>(refs.ffff) expectType<ExpectedRefs['validated']>(refs.validated) expectType<ExpectedRefs['object']>(refs.object) return { setupA: 1, setupB: ref(1), setupC: { a: ref(2) }, setupProps: props } } }) const { props, rawBindings, setup } = extractComponentOptions(MyComponent) // props expectType<ExpectedProps['a']>(props.a) expectType<ExpectedProps['b']>(props.b) expectType<ExpectedProps['e']>(props.e) expectType<ExpectedProps['bb']>(props.bb) expectType<ExpectedProps['bbb']>(props.bbb) expectType<ExpectedProps['cc']>(props.cc) expectType<ExpectedProps['dd']>(props.dd) expectType<ExpectedProps['ee']>(props.ee) expectType<ExpectedProps['ff']>(props.ff) expectType<ExpectedProps['ccc']>(props.ccc) expectType<ExpectedProps['ddd']>(props.ddd) expectType<ExpectedProps['eee']>(props.eee) expectType<ExpectedProps['fff']>(props.fff) expectType<ExpectedProps['hhh']>(props.hhh) expectType<ExpectedProps['ggg']>(props.ggg) expectType<ExpectedProps['ffff']>(props.ffff) expectType<ExpectedProps['validated']>(props.validated) expectType<ExpectedProps['object']>(props.object) // raw bindings expectType<Number>(rawBindings.setupA) expectType<Ref<Number>>(rawBindings.setupB) expectType<Ref<Number>>(rawBindings.setupC.a) expectType<Number>(rawBindings.setupA) // raw bindings props expectType<ExpectedProps['a']>(rawBindings.setupProps.a) expectType<ExpectedProps['b']>(rawBindings.setupProps.b) expectType<ExpectedProps['e']>(rawBindings.setupProps.e) expectType<ExpectedProps['bb']>(rawBindings.setupProps.bb) expectType<ExpectedProps['bbb']>(rawBindings.setupProps.bbb) expectType<ExpectedProps['cc']>(rawBindings.setupProps.cc) expectType<ExpectedProps['dd']>(rawBindings.setupProps.dd) expectType<ExpectedProps['ee']>(rawBindings.setupProps.ee) expectType<ExpectedProps['ff']>(rawBindings.setupProps.ff) expectType<ExpectedProps['ccc']>(rawBindings.setupProps.ccc) expectType<ExpectedProps['ddd']>(rawBindings.setupProps.ddd) expectType<ExpectedProps['eee']>(rawBindings.setupProps.eee) expectType<ExpectedProps['fff']>(rawBindings.setupProps.fff) expectType<ExpectedProps['hhh']>(rawBindings.setupProps.hhh) expectType<ExpectedProps['ggg']>(rawBindings.setupProps.ggg) expectType<ExpectedProps['ffff']>(rawBindings.setupProps.ffff) expectType<ExpectedProps['validated']>(rawBindings.setupProps.validated) // setup expectType<Number>(setup.setupA) expectType<Number>(setup.setupB) expectType<Ref<Number>>(setup.setupC.a) expectType<Number>(setup.setupA) // raw bindings props expectType<ExpectedProps['a']>(setup.setupProps.a) expectType<ExpectedProps['b']>(setup.setupProps.b) expectType<ExpectedProps['e']>(setup.setupProps.e) expectType<ExpectedProps['bb']>(setup.setupProps.bb) expectType<ExpectedProps['bbb']>(setup.setupProps.bbb) expectType<ExpectedProps['cc']>(setup.setupProps.cc) expectType<ExpectedProps['dd']>(setup.setupProps.dd) expectType<ExpectedProps['ee']>(setup.setupProps.ee) expectType<ExpectedProps['ff']>(setup.setupProps.ff) expectType<ExpectedProps['ccc']>(setup.setupProps.ccc) expectType<ExpectedProps['ddd']>(setup.setupProps.ddd) expectType<ExpectedProps['eee']>(setup.setupProps.eee) expectType<ExpectedProps['fff']>(setup.setupProps.fff) expectType<ExpectedProps['hhh']>(setup.setupProps.hhh) expectType<ExpectedProps['ggg']>(setup.setupProps.ggg) expectType<ExpectedProps['ffff']>(setup.setupProps.ffff) expectType<ExpectedProps['validated']>(setup.setupProps.validated) // instance const instance = new MyComponent() expectType<number>(instance.setupA) // @ts-expect-error instance.notExist }) describe('options', () => { const MyComponent = { props: { a: Number, // required should make property non-void b: { type: String, required: true }, e: Function, // default value should infer type and make it non-void bb: { default: 'hello' }, bbb: { // Note: default function value requires arrow syntax + explicit // annotation default: (props: any) => (props.bb as string) || 'foo' }, // explicit type casting cc: Array as PropType<string[]>, // required + type casting dd: { type: Object as PropType<{ n: 1 }>, required: true }, // return type ee: Function as PropType<() => string>, // arguments + object return ff: Function as PropType<(a: number, b: string) => { a: boolean }>, // explicit type casting with constructor ccc: Array as () => string[], // required + contructor type casting ddd: { type: Array as () => string[], required: true }, // required + object return eee: { type: Function as PropType<() => { a: string }>, required: true }, // required + arguments + object return fff: { type: Function as PropType<(a: number, b: string) => { a: boolean }>, required: true }, hhh: { type: Boolean, required: true }, // default + type casting ggg: { type: String as PropType<'foo' | 'bar'>, default: 'foo' }, // default + function ffff: { type: Function as PropType<(a: number, b: string) => { a: boolean }>, default: (_a: number, _b: string) => ({ a: true }) }, validated: { type: String, // validator requires explicit annotation validator: (val: unknown) => val !== '' }, object: Object as PropType<object> }, setup() { return { setupA: 1 } } } as const const { props, rawBindings, setup } = extractComponentOptions(MyComponent) // props expectType<ExpectedProps['a']>(props.a) expectType<ExpectedProps['b']>(props.b) expectType<ExpectedProps['e']>(props.e) expectType<ExpectedProps['bb']>(props.bb) expectType<ExpectedProps['bbb']>(props.bbb) expectType<ExpectedProps['cc']>(props.cc) expectType<ExpectedProps['dd']>(props.dd) expectType<ExpectedProps['ee']>(props.ee) expectType<ExpectedProps['ff']>(props.ff) expectType<ExpectedProps['ccc']>(props.ccc) expectType<ExpectedProps['ddd']>(props.ddd) expectType<ExpectedProps['eee']>(props.eee) expectType<ExpectedProps['fff']>(props.fff) expectType<ExpectedProps['hhh']>(props.hhh) expectType<ExpectedProps['ggg']>(props.ggg) // expectType<ExpectedProps['ffff']>(props.ffff) // todo fix expectType<ExpectedProps['validated']>(props.validated) expectType<ExpectedProps['object']>(props.object) // rawBindings expectType<Number>(rawBindings.setupA) //setup expectType<Number>(setup.setupA) }) }) describe('array props', () => { describe('defineComponent', () => { const MyComponent = defineComponent({ props: ['a', 'b'], setup() { return { c: 1 } } }) const { props, rawBindings, setup } = extractComponentOptions(MyComponent) // @ts-expect-error props should be readonly expectError((props.a = 1)) expectType<any>(props.a) expectType<any>(props.b) expectType<number>(rawBindings.c) expectType<number>(setup.c) }) describe('options', () => { const MyComponent = { props: ['a', 'b'] as const, setup() { return { c: 1 } } } const { props, rawBindings, setup } = extractComponentOptions(MyComponent) // @ts-expect-error props should be readonly expectError((props.a = 1)) // TODO infer the correct keys // expectType<any>(props.a) // expectType<any>(props.b) expectType<number>(rawBindings.c) expectType<number>(setup.c) }) }) describe('no props', () => { describe('defineComponent', () => { const MyComponent = defineComponent({ setup() { return { setupA: 1 } } }) const { rawBindings, setup } = extractComponentOptions(MyComponent) expectType<number>(rawBindings.setupA) expectType<number>(setup.setupA) // instance const instance = new MyComponent() expectType<number>(instance.setupA) // @ts-expect-error instance.notExist }) describe('options', () => { const MyComponent = { setup() { return { setupA: 1 } } } const { rawBindings, setup } = extractComponentOptions(MyComponent) expectType<number>(rawBindings.setupA) expectType<number>(setup.setupA) }) }) describe('functional', () => { // TODO `props.foo` is `number|undefined` // describe('defineComponent', () => { // const MyComponent = defineComponent((props: { foo: number }) => {}) // const { props } = extractComponentOptions(MyComponent) // expectType<number>(props.foo) // }) describe('function', () => { const MyComponent = (props: { foo: number }) => props.foo const { props } = extractComponentOptions(MyComponent) expectType<number>(props.foo) }) describe('typed', () => { const MyComponent: FunctionalComponent<{ foo: number }> = (_, _2) => {} const { props } = extractComponentOptions(MyComponent) expectType<number>(props.foo) }) }) declare type VueClass<Props = {}> = { new (): ComponentPublicInstance<Props> } describe('class', () => { const MyComponent: VueClass<{ foo: number }> = {} as any const { props } = extractComponentOptions(MyComponent) expectType<number>(props.foo) })
test-dts/component.test-d.ts
1
https://github.com/vuejs/core/commit/f6a5f09a3aaff4f156bd1d4cc5ae01331cffa427
[ 0.998271107673645, 0.04216526076197624, 0.00016693459474481642, 0.0002213286206824705, 0.19432130455970764 ]
{ "id": 4, "code_window": [ "\n", " // instance\n", " const instance = new MyComponent()\n", " expectType<number>(instance.setupA)\n", " // @ts-expect-error\n", " instance.notExist\n", " })\n", "\n", " describe('options', () => {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " expectType<number | undefined>(instance.setupD)\n" ], "file_path": "test-dts/component.test-d.ts", "type": "add", "edit_start_line_idx": 241 }
import { renderToString } from '../src/renderToString' import { createApp, h, withDirectives, vShow, vModelText, vModelRadio, vModelCheckbox } from 'vue' describe('ssr: directives', () => { describe('template v-show', () => { test('basic', async () => { expect( await renderToString( createApp({ template: `<div v-show="true"/>` }) ) ).toBe(`<div style=""></div>`) expect( await renderToString( createApp({ template: `<div v-show="false"/>` }) ) ).toBe(`<div style="display:none;"></div>`) }) test('with static style', async () => { expect( await renderToString( createApp({ template: `<div style="color:red" v-show="false"/>` }) ) ).toBe(`<div style="color:red;display:none;"></div>`) }) test('with dynamic style', async () => { expect( await renderToString( createApp({ data: () => ({ style: { color: 'red' } }), template: `<div :style="style" v-show="false"/>` }) ) ).toBe(`<div style="color:red;display:none;"></div>`) }) test('with static + dynamic style', async () => { expect( await renderToString( createApp({ data: () => ({ style: { color: 'red' } }), template: `<div :style="style" style="font-size:12;" v-show="false"/>` }) ) ).toBe(`<div style="color:red;font-size:12;display:none;"></div>`) }) }) describe('template v-model', () => { test('text', async () => { expect( await renderToString( createApp({ data: () => ({ text: 'hello' }), template: `<input v-model="text">` }) ) ).toBe(`<input value="hello">`) }) test('radio', async () => { expect( await renderToString( createApp({ data: () => ({ selected: 'foo' }), template: `<input type="radio" value="foo" v-model="selected">` }) ) ).toBe(`<input type="radio" value="foo" checked>`) expect( await renderToString( createApp({ data: () => ({ selected: 'foo' }), template: `<input type="radio" value="bar" v-model="selected">` }) ) ).toBe(`<input type="radio" value="bar">`) // non-string values expect( await renderToString( createApp({ data: () => ({ selected: 'foo' }), template: `<input type="radio" :value="{}" v-model="selected">` }) ) ).toBe(`<input type="radio">`) }) test('checkbox', async () => { expect( await renderToString( createApp({ data: () => ({ checked: true }), template: `<input type="checkbox" v-model="checked">` }) ) ).toBe(`<input type="checkbox" checked>`) expect( await renderToString( createApp({ data: () => ({ checked: false }), template: `<input type="checkbox" v-model="checked">` }) ) ).toBe(`<input type="checkbox">`) expect( await renderToString( createApp({ data: () => ({ checked: ['foo'] }), template: `<input type="checkbox" value="foo" v-model="checked">` }) ) ).toBe(`<input type="checkbox" value="foo" checked>`) expect( await renderToString( createApp({ data: () => ({ checked: [] }), template: `<input type="checkbox" value="foo" v-model="checked">` }) ) ).toBe(`<input type="checkbox" value="foo">`) }) test('textarea', async () => { expect( await renderToString( createApp({ data: () => ({ foo: 'hello' }), template: `<textarea v-model="foo"/>` }) ) ).toBe(`<textarea>hello</textarea>`) }) test('dynamic type', async () => { expect( await renderToString( createApp({ data: () => ({ type: 'text', model: 'hello' }), template: `<input :type="type" v-model="model">` }) ) ).toBe(`<input type="text" value="hello">`) expect( await renderToString( createApp({ data: () => ({ type: 'checkbox', model: true }), template: `<input :type="type" v-model="model">` }) ) ).toBe(`<input type="checkbox" checked>`) expect( await renderToString( createApp({ data: () => ({ type: 'checkbox', model: false }), template: `<input :type="type" v-model="model">` }) ) ).toBe(`<input type="checkbox">`) expect( await renderToString( createApp({ data: () => ({ type: 'checkbox', model: ['hello'] }), template: `<input :type="type" value="hello" v-model="model">` }) ) ).toBe(`<input type="checkbox" value="hello" checked>`) expect( await renderToString( createApp({ data: () => ({ type: 'checkbox', model: [] }), template: `<input :type="type" value="hello" v-model="model">` }) ) ).toBe(`<input type="checkbox" value="hello">`) expect( await renderToString( createApp({ data: () => ({ type: 'radio', model: 'hello' }), template: `<input :type="type" value="hello" v-model="model">` }) ) ).toBe(`<input type="radio" value="hello" checked>`) expect( await renderToString( createApp({ data: () => ({ type: 'radio', model: 'hello' }), template: `<input :type="type" value="bar" v-model="model">` }) ) ).toBe(`<input type="radio" value="bar">`) }) test('with v-bind', async () => { expect( await renderToString( createApp({ data: () => ({ obj: { type: 'radio', value: 'hello' }, model: 'hello' }), template: `<input v-bind="obj" v-model="model">` }) ) ).toBe(`<input type="radio" value="hello" checked>`) }) }) describe('vnode v-show', () => { test('basic', async () => { expect( await renderToString( createApp({ render() { return withDirectives(h('div'), [[vShow, true]]) } }) ) ).toBe(`<div></div>`) expect( await renderToString( createApp({ render() { return withDirectives(h('div'), [[vShow, false]]) } }) ) ).toBe(`<div style="display:none;"></div>`) }) test('with merge', async () => { expect( await renderToString( createApp({ render() { return withDirectives( h('div', { style: { color: 'red' } }), [[vShow, false]] ) } }) ) ).toBe(`<div style="color:red;display:none;"></div>`) }) }) describe('vnode v-model', () => { test('text', async () => { expect( await renderToString( createApp({ render() { return withDirectives(h('input'), [[vModelText, 'hello']]) } }) ) ).toBe(`<input value="hello">`) }) test('radio', async () => { expect( await renderToString( createApp({ render() { return withDirectives( h('input', { type: 'radio', value: 'hello' }), [[vModelRadio, 'hello']] ) } }) ) ).toBe(`<input type="radio" value="hello" checked>`) expect( await renderToString( createApp({ render() { return withDirectives( h('input', { type: 'radio', value: 'hello' }), [[vModelRadio, 'foo']] ) } }) ) ).toBe(`<input type="radio" value="hello">`) }) test('checkbox', async () => { expect( await renderToString( createApp({ render() { return withDirectives(h('input', { type: 'checkbox' }), [ [vModelCheckbox, true] ]) } }) ) ).toBe(`<input type="checkbox" checked>`) expect( await renderToString( createApp({ render() { return withDirectives(h('input', { type: 'checkbox' }), [ [vModelCheckbox, false] ]) } }) ) ).toBe(`<input type="checkbox">`) expect( await renderToString( createApp({ render() { return withDirectives( h('input', { type: 'checkbox', value: 'foo' }), [[vModelCheckbox, ['foo']]] ) } }) ) ).toBe(`<input type="checkbox" value="foo" checked>`) expect( await renderToString( createApp({ render() { return withDirectives( h('input', { type: 'checkbox', value: 'foo' }), [[vModelCheckbox, []]] ) } }) ) ).toBe(`<input type="checkbox" value="foo">`) }) }) test('custom directive w/ getSSRProps', async () => { expect( await renderToString( createApp({ render() { return withDirectives(h('div'), [ [ { getSSRProps({ value }) { return { id: value } } }, 'foo' ] ]) } }) ) ).toBe(`<div id="foo"></div>`) }) })
packages/server-renderer/__tests__/ssrDirectives.spec.ts
0
https://github.com/vuejs/core/commit/f6a5f09a3aaff4f156bd1d4cc5ae01331cffa427
[ 0.00017723911150824279, 0.0001720469881547615, 0.00016708461043890566, 0.00017189790378324687, 0.000002418393478365033 ]
{ "id": 4, "code_window": [ "\n", " // instance\n", " const instance = new MyComponent()\n", " expectType<number>(instance.setupA)\n", " // @ts-expect-error\n", " instance.notExist\n", " })\n", "\n", " describe('options', () => {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " expectType<number | undefined>(instance.setupD)\n" ], "file_path": "test-dts/component.test-d.ts", "type": "add", "edit_start_line_idx": 241 }
import { ObjectDirective, VNode, DirectiveHook, DirectiveBinding, warn } from '@vue/runtime-core' import { addEventListener } from '../modules/events' import { isArray, looseEqual, looseIndexOf, invokeArrayFns, toNumber, isSet } from '@vue/shared' type AssignerFn = (value: any) => void const getModelAssigner = (vnode: VNode): AssignerFn => { const fn = vnode.props!['onUpdate:modelValue'] return isArray(fn) ? value => invokeArrayFns(fn, value) : fn } function onCompositionStart(e: Event) { ;(e.target as any).composing = true } function onCompositionEnd(e: Event) { const target = e.target as any if (target.composing) { target.composing = false trigger(target, 'input') } } function trigger(el: HTMLElement, type: string) { const e = document.createEvent('HTMLEvents') e.initEvent(type, true, true) el.dispatchEvent(e) } type ModelDirective<T> = ObjectDirective<T & { _assign: AssignerFn }> // We are exporting the v-model runtime directly as vnode hooks so that it can // be tree-shaken in case v-model is never used. export const vModelText: ModelDirective< HTMLInputElement | HTMLTextAreaElement > = { created(el, { modifiers: { lazy, trim, number } }, vnode) { el._assign = getModelAssigner(vnode) const castToNumber = number || el.type === 'number' addEventListener(el, lazy ? 'change' : 'input', e => { if ((e.target as any).composing) return let domValue: string | number = el.value if (trim) { domValue = domValue.trim() } else if (castToNumber) { domValue = toNumber(domValue) } el._assign(domValue) }) if (trim) { addEventListener(el, 'change', () => { el.value = el.value.trim() }) } if (!lazy) { addEventListener(el, 'compositionstart', onCompositionStart) addEventListener(el, 'compositionend', onCompositionEnd) // Safari < 10.2 & UIWebView doesn't fire compositionend when // switching focus before confirming composition choice // this also fixes the issue where some browsers e.g. iOS Chrome // fires "change" instead of "input" on autocomplete. addEventListener(el, 'change', onCompositionEnd) } }, // set value on mounted so it's after min/max for type="range" mounted(el, { value }) { el.value = value == null ? '' : value }, beforeUpdate(el, { value, modifiers: { trim, number } }, vnode) { el._assign = getModelAssigner(vnode) // avoid clearing unresolved text. #2302 if ((el as any).composing) return if (document.activeElement === el) { if (trim && el.value.trim() === value) { return } if ((number || el.type === 'number') && toNumber(el.value) === value) { return } } const newValue = value == null ? '' : value if (el.value !== newValue) { el.value = newValue } } } export const vModelCheckbox: ModelDirective<HTMLInputElement> = { // #4096 array checkboxes need to be deep traversed deep: true, created(el, _, vnode) { el._assign = getModelAssigner(vnode) addEventListener(el, 'change', () => { const modelValue = (el as any)._modelValue const elementValue = getValue(el) const checked = el.checked const assign = el._assign if (isArray(modelValue)) { const index = looseIndexOf(modelValue, elementValue) const found = index !== -1 if (checked && !found) { assign(modelValue.concat(elementValue)) } else if (!checked && found) { const filtered = [...modelValue] filtered.splice(index, 1) assign(filtered) } } else if (isSet(modelValue)) { const cloned = new Set(modelValue) if (checked) { cloned.add(elementValue) } else { cloned.delete(elementValue) } assign(cloned) } else { assign(getCheckboxValue(el, checked)) } }) }, // set initial checked on mount to wait for true-value/false-value mounted: setChecked, beforeUpdate(el, binding, vnode) { el._assign = getModelAssigner(vnode) setChecked(el, binding, vnode) } } function setChecked( el: HTMLInputElement, { value, oldValue }: DirectiveBinding, vnode: VNode ) { // store the v-model value on the element so it can be accessed by the // change listener. ;(el as any)._modelValue = value if (isArray(value)) { el.checked = looseIndexOf(value, vnode.props!.value) > -1 } else if (isSet(value)) { el.checked = value.has(vnode.props!.value) } else if (value !== oldValue) { el.checked = looseEqual(value, getCheckboxValue(el, true)) } } export const vModelRadio: ModelDirective<HTMLInputElement> = { created(el, { value }, vnode) { el.checked = looseEqual(value, vnode.props!.value) el._assign = getModelAssigner(vnode) addEventListener(el, 'change', () => { el._assign(getValue(el)) }) }, beforeUpdate(el, { value, oldValue }, vnode) { el._assign = getModelAssigner(vnode) if (value !== oldValue) { el.checked = looseEqual(value, vnode.props!.value) } } } export const vModelSelect: ModelDirective<HTMLSelectElement> = { // <select multiple> value need to be deep traversed deep: true, created(el, { value, modifiers: { number } }, vnode) { const isSetModel = isSet(value) addEventListener(el, 'change', () => { const selectedVal = Array.prototype.filter .call(el.options, (o: HTMLOptionElement) => o.selected) .map( (o: HTMLOptionElement) => number ? toNumber(getValue(o)) : getValue(o) ) el._assign( el.multiple ? isSetModel ? new Set(selectedVal) : selectedVal : selectedVal[0] ) }) el._assign = getModelAssigner(vnode) }, // set value in mounted & updated because <select> relies on its children // <option>s. mounted(el, { value }) { setSelected(el, value) }, beforeUpdate(el, _binding, vnode) { el._assign = getModelAssigner(vnode) }, updated(el, { value }) { setSelected(el, value) } } function setSelected(el: HTMLSelectElement, value: any) { const isMultiple = el.multiple if (isMultiple && !isArray(value) && !isSet(value)) { __DEV__ && warn( `<select multiple v-model> expects an Array or Set value for its binding, ` + `but got ${Object.prototype.toString.call(value).slice(8, -1)}.` ) return } for (let i = 0, l = el.options.length; i < l; i++) { const option = el.options[i] const optionValue = getValue(option) if (isMultiple) { if (isArray(value)) { option.selected = looseIndexOf(value, optionValue) > -1 } else { option.selected = value.has(optionValue) } } else { if (looseEqual(getValue(option), value)) { if (el.selectedIndex !== i) el.selectedIndex = i return } } } if (!isMultiple && el.selectedIndex !== -1) { el.selectedIndex = -1 } } // retrieve raw value set via :value bindings function getValue(el: HTMLOptionElement | HTMLInputElement) { return '_value' in el ? (el as any)._value : el.value } // retrieve raw value for true-value and false-value set via :true-value or :false-value bindings function getCheckboxValue( el: HTMLInputElement & { _trueValue?: any; _falseValue?: any }, checked: boolean ) { const key = checked ? '_trueValue' : '_falseValue' return key in el ? el[key] : checked } export const vModelDynamic: ObjectDirective< HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement > = { created(el, binding, vnode) { callModelHook(el, binding, vnode, null, 'created') }, mounted(el, binding, vnode) { callModelHook(el, binding, vnode, null, 'mounted') }, beforeUpdate(el, binding, vnode, prevVNode) { callModelHook(el, binding, vnode, prevVNode, 'beforeUpdate') }, updated(el, binding, vnode, prevVNode) { callModelHook(el, binding, vnode, prevVNode, 'updated') } } function callModelHook( el: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement, binding: DirectiveBinding, vnode: VNode, prevVNode: VNode | null, hook: keyof ObjectDirective ) { let modelToUse: ObjectDirective switch (el.tagName) { case 'SELECT': modelToUse = vModelSelect break case 'TEXTAREA': modelToUse = vModelText break default: switch (vnode.props && vnode.props.type) { case 'checkbox': modelToUse = vModelCheckbox break case 'radio': modelToUse = vModelRadio break default: modelToUse = vModelText } } const fn = modelToUse[hook] as DirectiveHook fn && fn(el, binding, vnode, prevVNode) } // SSR vnode transforms if (__NODE_JS__) { vModelText.getSSRProps = ({ value }) => ({ value }) vModelRadio.getSSRProps = ({ value }, vnode) => { if (vnode.props && looseEqual(vnode.props.value, value)) { return { checked: true } } } vModelCheckbox.getSSRProps = ({ value }, vnode) => { if (isArray(value)) { if (vnode.props && looseIndexOf(value, vnode.props.value) > -1) { return { checked: true } } } else if (isSet(value)) { if (vnode.props && value.has(vnode.props.value)) { return { checked: true } } } else if (value) { return { checked: true } } } }
packages/runtime-dom/src/directives/vModel.ts
0
https://github.com/vuejs/core/commit/f6a5f09a3aaff4f156bd1d4cc5ae01331cffa427
[ 0.00021530385129153728, 0.00017562236462254077, 0.00016479416808579117, 0.00017393376037944108, 0.000010410548384243157 ]
{ "id": 4, "code_window": [ "\n", " // instance\n", " const instance = new MyComponent()\n", " expectType<number>(instance.setupA)\n", " // @ts-expect-error\n", " instance.notExist\n", " })\n", "\n", " describe('options', () => {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " expectType<number | undefined>(instance.setupD)\n" ], "file_path": "test-dts/component.test-d.ts", "type": "add", "edit_start_line_idx": 241 }
import { TextModes, ParserOptions, ElementNode, Namespaces, NodeTypes, isBuiltInType } from '@vue/compiler-core' import { makeMap, isVoidTag, isHTMLTag, isSVGTag } from '@vue/shared' import { TRANSITION, TRANSITION_GROUP } from './runtimeHelpers' import { decodeHtml } from './decodeHtml' import { decodeHtmlBrowser } from './decodeHtmlBrowser' const isRawTextContainer = /*#__PURE__*/ makeMap( 'style,iframe,script,noscript', true ) export const enum DOMNamespaces { HTML = Namespaces.HTML, SVG, MATH_ML } export const parserOptions: ParserOptions = { isVoidTag, isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag), isPreTag: tag => tag === 'pre', decodeEntities: __BROWSER__ ? decodeHtmlBrowser : decodeHtml, isBuiltInComponent: (tag: string): symbol | undefined => { if (isBuiltInType(tag, `Transition`)) { return TRANSITION } else if (isBuiltInType(tag, `TransitionGroup`)) { return TRANSITION_GROUP } }, // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher getNamespace(tag: string, parent: ElementNode | undefined): DOMNamespaces { let ns = parent ? parent.ns : DOMNamespaces.HTML if (parent && ns === DOMNamespaces.MATH_ML) { if (parent.tag === 'annotation-xml') { if (tag === 'svg') { return DOMNamespaces.SVG } if ( parent.props.some( a => a.type === NodeTypes.ATTRIBUTE && a.name === 'encoding' && a.value != null && (a.value.content === 'text/html' || a.value.content === 'application/xhtml+xml') ) ) { ns = DOMNamespaces.HTML } } else if ( /^m(?:[ions]|text)$/.test(parent.tag) && tag !== 'mglyph' && tag !== 'malignmark' ) { ns = DOMNamespaces.HTML } } else if (parent && ns === DOMNamespaces.SVG) { if ( parent.tag === 'foreignObject' || parent.tag === 'desc' || parent.tag === 'title' ) { ns = DOMNamespaces.HTML } } if (ns === DOMNamespaces.HTML) { if (tag === 'svg') { return DOMNamespaces.SVG } if (tag === 'math') { return DOMNamespaces.MATH_ML } } return ns }, // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments getTextMode({ tag, ns }: ElementNode): TextModes { if (ns === DOMNamespaces.HTML) { if (tag === 'textarea' || tag === 'title') { return TextModes.RCDATA } if (isRawTextContainer(tag)) { return TextModes.RAWTEXT } } return TextModes.DATA } }
packages/compiler-dom/src/parserOptions.ts
0
https://github.com/vuejs/core/commit/f6a5f09a3aaff4f156bd1d4cc5ae01331cffa427
[ 0.0002013047196669504, 0.00017715991998557, 0.00016923622752074152, 0.00017567504255566746, 0.000008208518011088017 ]
{ "id": 0, "code_window": [ " await this._session.send('Page.setInterceptFileChooserDialog', { enabled }).catch(() => {}); // target can be closed.\n", " }\n", "\n", " async reload(): Promise<void> {\n", " await this._session.send('Page.reload');\n", " }\n", "\n", " async goBack(): Promise<boolean> {\n", " const { success } = await this._session.send('Page.goBack', { frameId: this._page.mainFrame()._id });\n", " return success;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const mainFrame = this._page._frameManager.mainFrame();\n", " // This is a workaround for https://github.com/microsoft/playwright/issues/21145\n", " let hash = '';\n", " try {\n", " hash = (new URL(mainFrame.url())).hash;\n", " } catch (e) {\n", " // Ignore URL parsing error, if any.\n", " }\n", " if (hash.length) {\n", " const context = await mainFrame._utilityContext();\n", " await context.rawEvaluateJSON(`void window.location.reload();`);\n", " } else {\n", " await this._session.send('Page.reload');\n", " }\n" ], "file_path": "packages/playwright-core/src/server/firefox/ffPage.ts", "type": "replace", "edit_start_line_idx": 395 }
/** * Copyright 2018 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { test as it, expect } from './pageTest'; import url from 'url'; it('page.goBack should work @smoke', async ({ page, server }) => { expect(await page.goBack()).toBe(null); await page.goto(server.EMPTY_PAGE); await page.goto(server.PREFIX + '/grid.html'); let response = await page.goBack(); expect(response.ok()).toBe(true); expect(response.url()).toContain(server.EMPTY_PAGE); response = await page.goForward(); expect(response.ok()).toBe(true); expect(response.url()).toContain('/grid.html'); response = await page.goForward(); expect(response).toBe(null); }); it('page.goBack should work with HistoryAPI', async ({ page, server }) => { await page.goto(server.EMPTY_PAGE); await page.evaluate(() => { history.pushState({}, '', '/first.html'); history.pushState({}, '', '/second.html'); }); expect(page.url()).toBe(server.PREFIX + '/second.html'); await page.goBack(); expect(page.url()).toBe(server.PREFIX + '/first.html'); await page.goBack(); expect(page.url()).toBe(server.EMPTY_PAGE); await page.goForward(); expect(page.url()).toBe(server.PREFIX + '/first.html'); }); it('page.goBack should work for file urls', async ({ page, server, asset, browserName, platform, isAndroid }) => { it.fail(browserName === 'webkit' && platform === 'darwin', 'WebKit embedder fails to go back/forward to the file url.'); it.skip(isAndroid, 'No files on Android'); const url1 = url.pathToFileURL(asset('consolelog.html')).href; const url2 = server.PREFIX + '/consolelog.html'; await Promise.all([ page.waitForEvent('console', message => message.text() === 'here:' + url1), page.goto(url1), ]); await page.setContent(`<a href='${url2}'>url2</a>`); expect(page.url().toLowerCase()).toBe(url1.toLowerCase()); await Promise.all([ page.waitForEvent('console', message => message.text() === 'here:' + url2), page.click('a'), ]); expect(page.url()).toBe(url2); await Promise.all([ page.waitForEvent('console', message => message.text() === 'here:' + url1), page.goBack(), ]); expect(page.url().toLowerCase()).toBe(url1.toLowerCase()); // Should be able to evaluate in the new context, and // not reach for the old cross-process one. expect(await page.evaluate(() => window.scrollX)).toBe(0); // Should be able to screenshot. await page.screenshot(); await Promise.all([ page.waitForEvent('console', message => message.text() === 'here:' + url2), page.goForward(), ]); expect(page.url()).toBe(url2); expect(await page.evaluate(() => window.scrollX)).toBe(0); await page.screenshot(); }); it('goBack/goForward should work with bfcache-able pages', async ({ page, server }) => { await page.goto(server.PREFIX + '/cached/one-style.html'); await page.setContent(`<a href=${JSON.stringify(server.PREFIX + '/cached/one-style.html?foo')}>click me</a>`); await page.click('a'); let response = await page.goBack(); expect(response.url()).toBe(server.PREFIX + '/cached/one-style.html'); response = await page.goForward(); expect(response.url()).toBe(server.PREFIX + '/cached/one-style.html?foo'); }); it('page.reload should work', async ({ page, server }) => { await page.goto(server.EMPTY_PAGE); await page.evaluate(() => window['_foo'] = 10); await page.reload(); expect(await page.evaluate(() => window['_foo'])).toBe(undefined); }); it('page.reload should work with data url', async ({ page, server }) => { await page.goto('data:text/html,hello'); expect(await page.content()).toContain('hello'); expect(await page.reload()).toBe(null); expect(await page.content()).toContain('hello'); }); it('page.reload during renderer-initiated navigation', async ({ page, server }) => { await page.goto(server.PREFIX + '/one-style.html'); await page.setContent(`<form method='POST' action='/post'>Form is here<input type='submit'></form>`); server.setRoute('/post', (req, res) => {}); let callback; const reloadFailedPromise = new Promise(f => callback = f); page.once('request', async () => { await page.reload().catch(e => {}); callback(); }); const clickPromise = page.click('input[type=submit]').catch(e => {}); await reloadFailedPromise; await clickPromise; // Form submit should be canceled, and reload should eventually arrive // to the original one-style.html. await page.waitForSelector('text=hello'); }); it('page.reload should not resolve with same-document navigation', async ({ page, server }) => { await page.goto(server.EMPTY_PAGE); // 1. Make sure execution contexts are ready for fast evaluate. await page.evaluate('1'); // 2. Stall the reload request. let response; server.setRoute('/empty.html', (req, res) => { response = res; }); const requestPromise = server.waitForRequest('/empty.html'); // 3. Trigger push state that could resolve the reload. page.evaluate(() => { window.history.pushState({}, ''); }).catch(() => {}); // 4. Trigger the reload, it should not resolve. const reloadPromise = page.reload(); // 5. Trigger push state again, for the good measure :) page.evaluate(() => { window.history.pushState({}, ''); }).catch(() => {}); // 5. Serve the request, it should resolve the reload. await requestPromise; response.end('hello'); // 6. Check the reload response. const gotResponse = await reloadPromise; expect(await gotResponse.text()).toBe('hello'); }); it('page.reload should work with same origin redirect', async ({ page, server }) => { it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/16147' }); await page.goto(server.EMPTY_PAGE); server.setRedirect('/empty.html', server.PREFIX + '/title.html'); await page.reload(); await expect(page).toHaveURL(server.PREFIX + '/title.html'); }); it('page.reload should work with cross-origin redirect', async ({ page, server, browserName }) => { it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/16147' }); await page.goto(server.EMPTY_PAGE); server.setRedirect('/empty.html', server.CROSS_PROCESS_PREFIX + '/title.html'); await page.reload(); await expect(page).toHaveURL(server.CROSS_PROCESS_PREFIX + '/title.html'); }); it('page.reload should work on a page with a hash', async ({ page, server, browserName }) => { it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/21145' }); it.fixme(browserName === 'firefox'); await page.goto(server.EMPTY_PAGE + '#hash'); await page.reload(); await expect(page).toHaveURL(server.EMPTY_PAGE + '#hash'); }); it('page.goBack during renderer-initiated navigation', async ({ page, server }) => { await page.goto(server.PREFIX + '/one-style.html'); await page.goto(server.EMPTY_PAGE); await page.setContent(`<form method='POST' action='/post'>Form is here<input type='submit'></form>`); server.setRoute('/post', (req, res) => {}); let callback; const reloadFailedPromise = new Promise(f => callback = f); page.once('request', async () => { await page.goBack().catch(e => {}); callback(); }); const clickPromise = page.click('input[type=submit]').catch(e => {}); await reloadFailedPromise; await clickPromise; // Form submit should be canceled, and goBack should eventually arrive // to the original one-style.html. await page.waitForSelector('text=hello'); }); it('page.goForward during renderer-initiated navigation', async ({ page, server }) => { await page.goto(server.EMPTY_PAGE); await page.goto(server.PREFIX + '/one-style.html'); await page.goBack(); await page.setContent(`<form method='POST' action='/post'>Form is here<input type='submit'></form>`); server.setRoute('/post', (req, res) => {}); let callback; const reloadFailedPromise = new Promise(f => callback = f); page.once('request', async () => { await page.goForward().catch(e => {}); callback(); }); const clickPromise = page.click('input[type=submit]').catch(e => {}); await reloadFailedPromise; await clickPromise; // Form submit should be canceled, and goForward should eventually arrive // to the original one-style.html. await page.waitForSelector('text=hello'); }); it('regression test for issue 20791', async ({ page, server }) => { it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/20791' }); server.setRoute('/iframe.html', (req, res) => { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); // iframe access parent frame to log a value from it. res.end(` <!doctype html> <script type="text/javascript"> console.log(window.parent.foo); </script> `); }); server.setRoute('/main.html', (req, res) => { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end(` <!doctype html> <iframe id=myframe src="about:blank"></iframe> <script type="text/javascript"> setTimeout(() => window.foo = 'foo', 0); setTimeout(() => myframe.contentDocument.location.href = '${server.PREFIX}/iframe.html', 0); </script> `); }); const messages = []; page.on('console', msg => messages.push(msg.text())); await page.goto(server.PREFIX + '/main.html'); await expect.poll(() => messages).toEqual(['foo']); await page.reload(); await expect.poll(() => messages).toEqual(['foo', 'foo']); }); it('should reload proper page', async ({ page, server }) => { let mainRequest = 0, popupRequest = 0; server.setRoute('/main.html', (req, res) => { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end(`<!doctype html><h1>main: ${++mainRequest}</h1>`); }); server.setRoute('/popup.html', (req, res) => { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end(`<!doctype html><h1>popup: ${++popupRequest}</h1>`); }); await page.goto(server.PREFIX + '/main.html'); const [popup] = await Promise.all([ page.waitForEvent('popup'), page.evaluate(() => window.open('/popup.html')), ]); await expect(page.locator('h1')).toHaveText('main: 1'); await expect(popup.locator('h1')).toHaveText('popup: 1'); await page.reload(); await expect(page.locator('h1')).toHaveText('main: 2'); await expect(popup.locator('h1')).toHaveText('popup: 1'); await popup.reload(); await expect(page.locator('h1')).toHaveText('main: 2'); await expect(popup.locator('h1')).toHaveText('popup: 2'); });
tests/page/page-history.spec.ts
1
https://github.com/microsoft/playwright/commit/bfc895787fdff1c22b15ef775092585bc2c88791
[ 0.9944944977760315, 0.2599395215511322, 0.00016987175331451, 0.0011499205138534307, 0.41198721528053284 ]
{ "id": 0, "code_window": [ " await this._session.send('Page.setInterceptFileChooserDialog', { enabled }).catch(() => {}); // target can be closed.\n", " }\n", "\n", " async reload(): Promise<void> {\n", " await this._session.send('Page.reload');\n", " }\n", "\n", " async goBack(): Promise<boolean> {\n", " const { success } = await this._session.send('Page.goBack', { frameId: this._page.mainFrame()._id });\n", " return success;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const mainFrame = this._page._frameManager.mainFrame();\n", " // This is a workaround for https://github.com/microsoft/playwright/issues/21145\n", " let hash = '';\n", " try {\n", " hash = (new URL(mainFrame.url())).hash;\n", " } catch (e) {\n", " // Ignore URL parsing error, if any.\n", " }\n", " if (hash.length) {\n", " const context = await mainFrame._utilityContext();\n", " await context.rawEvaluateJSON(`void window.location.reload();`);\n", " } else {\n", " await this._session.send('Page.reload');\n", " }\n" ], "file_path": "packages/playwright-core/src/server/firefox/ffPage.ts", "type": "replace", "edit_start_line_idx": 395 }
/* Copyright (c) Microsoft Corporation. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ .call-log { display: flex; flex-direction: column; flex: auto; line-height: 20px; white-space: pre; overflow: auto; } .call-log-message { flex: none; padding: 3px 0 3px 36px; display: flex; align-items: center; } .call-log-call { display: flex; flex: none; flex-direction: column; border-top: 1px solid var(--vscode-panel-border); } .call-log-call-header { height: 24px; display: flex; align-items: center; padding: 0 2px; z-index: 2; } .call-log-call .codicon { padding: 0 4px; flex: none; } .call-log .codicon-check { color: #21a945; font-weight: bold; } .call-log-call.error { background-color: #fff0f0; border-top: 1px solid var(--vscode-panel-border); } .call-log-call.error .call-log-call-header, .call-log-message.error, .call-log .codicon-error { color: red; } .call-log-details { flex: 0 1 auto; overflow-x: hidden; text-overflow: ellipsis; } .call-log-url { color: var(--blue); } .call-log-selector { color: var(--orange); white-space: nowrap; } .call-log-time { flex: none; margin-left: 4px; color: var(--gray); } .call-log-call .codicon.preview { visibility: hidden; color: var(--vscode-sideBarTitle-foreground); cursor: pointer; } .call-log-call .codicon.preview:hover { color: inherit; } .call-log-call:hover .codicon.preview { visibility: visible; }
packages/recorder/src/callLog.css
0
https://github.com/microsoft/playwright/commit/bfc895787fdff1c22b15ef775092585bc2c88791
[ 0.00017846414993982762, 0.00017483788542449474, 0.00017107542953453958, 0.00017533666687086225, 0.0000021571026991296094 ]
{ "id": 0, "code_window": [ " await this._session.send('Page.setInterceptFileChooserDialog', { enabled }).catch(() => {}); // target can be closed.\n", " }\n", "\n", " async reload(): Promise<void> {\n", " await this._session.send('Page.reload');\n", " }\n", "\n", " async goBack(): Promise<boolean> {\n", " const { success } = await this._session.send('Page.goBack', { frameId: this._page.mainFrame()._id });\n", " return success;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const mainFrame = this._page._frameManager.mainFrame();\n", " // This is a workaround for https://github.com/microsoft/playwright/issues/21145\n", " let hash = '';\n", " try {\n", " hash = (new URL(mainFrame.url())).hash;\n", " } catch (e) {\n", " // Ignore URL parsing error, if any.\n", " }\n", " if (hash.length) {\n", " const context = await mainFrame._utilityContext();\n", " await context.rawEvaluateJSON(`void window.location.reload();`);\n", " } else {\n", " await this._session.send('Page.reload');\n", " }\n" ], "file_path": "packages/playwright-core/src/server/firefox/ffPage.ts", "type": "replace", "edit_start_line_idx": 395 }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <memory> #include "nsCOMPtr.h" #include "nsIRemoteDebuggingPipe.h" #include "nsThread.h" namespace mozilla { class nsRemoteDebuggingPipe final : public nsIRemoteDebuggingPipe { public: NS_DECL_THREADSAFE_ISUPPORTS NS_DECL_NSIREMOTEDEBUGGINGPIPE static already_AddRefed<nsIRemoteDebuggingPipe> GetSingleton(); nsRemoteDebuggingPipe(); private: void ReaderLoop(); void ReceiveMessage(const nsCString& aMessage); void Disconnected(); ~nsRemoteDebuggingPipe(); RefPtr<nsIRemoteDebuggingPipeClient> mClient; nsCOMPtr<nsIThread> mReaderThread; nsCOMPtr<nsIThread> mWriterThread; std::atomic<bool> m_terminated { false }; }; } // namespace mozilla
browser_patches/firefox/juggler/pipe/nsRemoteDebuggingPipe.h
0
https://github.com/microsoft/playwright/commit/bfc895787fdff1c22b15ef775092585bc2c88791
[ 0.00017699542513582855, 0.00016969273565337062, 0.0001649721380090341, 0.0001684016897343099, 0.000004484047167352401 ]
{ "id": 0, "code_window": [ " await this._session.send('Page.setInterceptFileChooserDialog', { enabled }).catch(() => {}); // target can be closed.\n", " }\n", "\n", " async reload(): Promise<void> {\n", " await this._session.send('Page.reload');\n", " }\n", "\n", " async goBack(): Promise<boolean> {\n", " const { success } = await this._session.send('Page.goBack', { frameId: this._page.mainFrame()._id });\n", " return success;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const mainFrame = this._page._frameManager.mainFrame();\n", " // This is a workaround for https://github.com/microsoft/playwright/issues/21145\n", " let hash = '';\n", " try {\n", " hash = (new URL(mainFrame.url())).hash;\n", " } catch (e) {\n", " // Ignore URL parsing error, if any.\n", " }\n", " if (hash.length) {\n", " const context = await mainFrame._utilityContext();\n", " await context.rawEvaluateJSON(`void window.location.reload();`);\n", " } else {\n", " await this._session.send('Page.reload');\n", " }\n" ], "file_path": "packages/playwright-core/src/server/firefox/ffPage.ts", "type": "replace", "edit_start_line_idx": 395 }
{ "compilerOptions": { "strict": true, "target": "ES2019", "noEmit": true, "moduleResolution": "node", }, "include": [ "test.ts" ] }
utils/generate_types/test/tsconfig.json
0
https://github.com/microsoft/playwright/commit/bfc895787fdff1c22b15ef775092585bc2c88791
[ 0.00017504216521047056, 0.00017284895875491202, 0.00017065573774743825, 0.00017284895875491202, 0.0000021932137315161526 ]
{ "id": 1, "code_window": [ " server.setRedirect('/empty.html', server.CROSS_PROCESS_PREFIX + '/title.html');\n", " await page.reload();\n", " await expect(page).toHaveURL(server.CROSS_PROCESS_PREFIX + '/title.html');\n", "});\n", "\n", "it('page.reload should work on a page with a hash', async ({ page, server, browserName }) => {\n", " it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/21145' });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "it('page.reload should work on a page with a hash', async ({ page, server }) => {\n" ], "file_path": "tests/page/page-history.spec.ts", "type": "replace", "edit_start_line_idx": 187 }
/** * Copyright 2018 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { test as it, expect } from './pageTest'; import url from 'url'; it('page.goBack should work @smoke', async ({ page, server }) => { expect(await page.goBack()).toBe(null); await page.goto(server.EMPTY_PAGE); await page.goto(server.PREFIX + '/grid.html'); let response = await page.goBack(); expect(response.ok()).toBe(true); expect(response.url()).toContain(server.EMPTY_PAGE); response = await page.goForward(); expect(response.ok()).toBe(true); expect(response.url()).toContain('/grid.html'); response = await page.goForward(); expect(response).toBe(null); }); it('page.goBack should work with HistoryAPI', async ({ page, server }) => { await page.goto(server.EMPTY_PAGE); await page.evaluate(() => { history.pushState({}, '', '/first.html'); history.pushState({}, '', '/second.html'); }); expect(page.url()).toBe(server.PREFIX + '/second.html'); await page.goBack(); expect(page.url()).toBe(server.PREFIX + '/first.html'); await page.goBack(); expect(page.url()).toBe(server.EMPTY_PAGE); await page.goForward(); expect(page.url()).toBe(server.PREFIX + '/first.html'); }); it('page.goBack should work for file urls', async ({ page, server, asset, browserName, platform, isAndroid }) => { it.fail(browserName === 'webkit' && platform === 'darwin', 'WebKit embedder fails to go back/forward to the file url.'); it.skip(isAndroid, 'No files on Android'); const url1 = url.pathToFileURL(asset('consolelog.html')).href; const url2 = server.PREFIX + '/consolelog.html'; await Promise.all([ page.waitForEvent('console', message => message.text() === 'here:' + url1), page.goto(url1), ]); await page.setContent(`<a href='${url2}'>url2</a>`); expect(page.url().toLowerCase()).toBe(url1.toLowerCase()); await Promise.all([ page.waitForEvent('console', message => message.text() === 'here:' + url2), page.click('a'), ]); expect(page.url()).toBe(url2); await Promise.all([ page.waitForEvent('console', message => message.text() === 'here:' + url1), page.goBack(), ]); expect(page.url().toLowerCase()).toBe(url1.toLowerCase()); // Should be able to evaluate in the new context, and // not reach for the old cross-process one. expect(await page.evaluate(() => window.scrollX)).toBe(0); // Should be able to screenshot. await page.screenshot(); await Promise.all([ page.waitForEvent('console', message => message.text() === 'here:' + url2), page.goForward(), ]); expect(page.url()).toBe(url2); expect(await page.evaluate(() => window.scrollX)).toBe(0); await page.screenshot(); }); it('goBack/goForward should work with bfcache-able pages', async ({ page, server }) => { await page.goto(server.PREFIX + '/cached/one-style.html'); await page.setContent(`<a href=${JSON.stringify(server.PREFIX + '/cached/one-style.html?foo')}>click me</a>`); await page.click('a'); let response = await page.goBack(); expect(response.url()).toBe(server.PREFIX + '/cached/one-style.html'); response = await page.goForward(); expect(response.url()).toBe(server.PREFIX + '/cached/one-style.html?foo'); }); it('page.reload should work', async ({ page, server }) => { await page.goto(server.EMPTY_PAGE); await page.evaluate(() => window['_foo'] = 10); await page.reload(); expect(await page.evaluate(() => window['_foo'])).toBe(undefined); }); it('page.reload should work with data url', async ({ page, server }) => { await page.goto('data:text/html,hello'); expect(await page.content()).toContain('hello'); expect(await page.reload()).toBe(null); expect(await page.content()).toContain('hello'); }); it('page.reload during renderer-initiated navigation', async ({ page, server }) => { await page.goto(server.PREFIX + '/one-style.html'); await page.setContent(`<form method='POST' action='/post'>Form is here<input type='submit'></form>`); server.setRoute('/post', (req, res) => {}); let callback; const reloadFailedPromise = new Promise(f => callback = f); page.once('request', async () => { await page.reload().catch(e => {}); callback(); }); const clickPromise = page.click('input[type=submit]').catch(e => {}); await reloadFailedPromise; await clickPromise; // Form submit should be canceled, and reload should eventually arrive // to the original one-style.html. await page.waitForSelector('text=hello'); }); it('page.reload should not resolve with same-document navigation', async ({ page, server }) => { await page.goto(server.EMPTY_PAGE); // 1. Make sure execution contexts are ready for fast evaluate. await page.evaluate('1'); // 2. Stall the reload request. let response; server.setRoute('/empty.html', (req, res) => { response = res; }); const requestPromise = server.waitForRequest('/empty.html'); // 3. Trigger push state that could resolve the reload. page.evaluate(() => { window.history.pushState({}, ''); }).catch(() => {}); // 4. Trigger the reload, it should not resolve. const reloadPromise = page.reload(); // 5. Trigger push state again, for the good measure :) page.evaluate(() => { window.history.pushState({}, ''); }).catch(() => {}); // 5. Serve the request, it should resolve the reload. await requestPromise; response.end('hello'); // 6. Check the reload response. const gotResponse = await reloadPromise; expect(await gotResponse.text()).toBe('hello'); }); it('page.reload should work with same origin redirect', async ({ page, server }) => { it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/16147' }); await page.goto(server.EMPTY_PAGE); server.setRedirect('/empty.html', server.PREFIX + '/title.html'); await page.reload(); await expect(page).toHaveURL(server.PREFIX + '/title.html'); }); it('page.reload should work with cross-origin redirect', async ({ page, server, browserName }) => { it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/16147' }); await page.goto(server.EMPTY_PAGE); server.setRedirect('/empty.html', server.CROSS_PROCESS_PREFIX + '/title.html'); await page.reload(); await expect(page).toHaveURL(server.CROSS_PROCESS_PREFIX + '/title.html'); }); it('page.reload should work on a page with a hash', async ({ page, server, browserName }) => { it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/21145' }); it.fixme(browserName === 'firefox'); await page.goto(server.EMPTY_PAGE + '#hash'); await page.reload(); await expect(page).toHaveURL(server.EMPTY_PAGE + '#hash'); }); it('page.goBack during renderer-initiated navigation', async ({ page, server }) => { await page.goto(server.PREFIX + '/one-style.html'); await page.goto(server.EMPTY_PAGE); await page.setContent(`<form method='POST' action='/post'>Form is here<input type='submit'></form>`); server.setRoute('/post', (req, res) => {}); let callback; const reloadFailedPromise = new Promise(f => callback = f); page.once('request', async () => { await page.goBack().catch(e => {}); callback(); }); const clickPromise = page.click('input[type=submit]').catch(e => {}); await reloadFailedPromise; await clickPromise; // Form submit should be canceled, and goBack should eventually arrive // to the original one-style.html. await page.waitForSelector('text=hello'); }); it('page.goForward during renderer-initiated navigation', async ({ page, server }) => { await page.goto(server.EMPTY_PAGE); await page.goto(server.PREFIX + '/one-style.html'); await page.goBack(); await page.setContent(`<form method='POST' action='/post'>Form is here<input type='submit'></form>`); server.setRoute('/post', (req, res) => {}); let callback; const reloadFailedPromise = new Promise(f => callback = f); page.once('request', async () => { await page.goForward().catch(e => {}); callback(); }); const clickPromise = page.click('input[type=submit]').catch(e => {}); await reloadFailedPromise; await clickPromise; // Form submit should be canceled, and goForward should eventually arrive // to the original one-style.html. await page.waitForSelector('text=hello'); }); it('regression test for issue 20791', async ({ page, server }) => { it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/20791' }); server.setRoute('/iframe.html', (req, res) => { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); // iframe access parent frame to log a value from it. res.end(` <!doctype html> <script type="text/javascript"> console.log(window.parent.foo); </script> `); }); server.setRoute('/main.html', (req, res) => { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end(` <!doctype html> <iframe id=myframe src="about:blank"></iframe> <script type="text/javascript"> setTimeout(() => window.foo = 'foo', 0); setTimeout(() => myframe.contentDocument.location.href = '${server.PREFIX}/iframe.html', 0); </script> `); }); const messages = []; page.on('console', msg => messages.push(msg.text())); await page.goto(server.PREFIX + '/main.html'); await expect.poll(() => messages).toEqual(['foo']); await page.reload(); await expect.poll(() => messages).toEqual(['foo', 'foo']); }); it('should reload proper page', async ({ page, server }) => { let mainRequest = 0, popupRequest = 0; server.setRoute('/main.html', (req, res) => { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end(`<!doctype html><h1>main: ${++mainRequest}</h1>`); }); server.setRoute('/popup.html', (req, res) => { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end(`<!doctype html><h1>popup: ${++popupRequest}</h1>`); }); await page.goto(server.PREFIX + '/main.html'); const [popup] = await Promise.all([ page.waitForEvent('popup'), page.evaluate(() => window.open('/popup.html')), ]); await expect(page.locator('h1')).toHaveText('main: 1'); await expect(popup.locator('h1')).toHaveText('popup: 1'); await page.reload(); await expect(page.locator('h1')).toHaveText('main: 2'); await expect(popup.locator('h1')).toHaveText('popup: 1'); await popup.reload(); await expect(page.locator('h1')).toHaveText('main: 2'); await expect(popup.locator('h1')).toHaveText('popup: 2'); });
tests/page/page-history.spec.ts
1
https://github.com/microsoft/playwright/commit/bfc895787fdff1c22b15ef775092585bc2c88791
[ 0.9951773881912231, 0.05954689532518387, 0.0001638384273974225, 0.0011488563613966107, 0.20662052929401398 ]
{ "id": 1, "code_window": [ " server.setRedirect('/empty.html', server.CROSS_PROCESS_PREFIX + '/title.html');\n", " await page.reload();\n", " await expect(page).toHaveURL(server.CROSS_PROCESS_PREFIX + '/title.html');\n", "});\n", "\n", "it('page.reload should work on a page with a hash', async ({ page, server, browserName }) => {\n", " it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/21145' });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "it('page.reload should work on a page with a hash', async ({ page, server }) => {\n" ], "file_path": "tests/page/page-history.spec.ts", "type": "replace", "edit_start_line_idx": 187 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import type * as channels from '@protocol/channels'; import { Browser } from './browser'; import { BrowserContext, prepareBrowserContextParams } from './browserContext'; import { ChannelOwner } from './channelOwner'; import type { LaunchOptions, LaunchServerOptions, ConnectOptions, LaunchPersistentContextOptions, BrowserContextOptions } from './types'; import { Connection } from './connection'; import { Events } from './events'; import type { ChildProcess } from 'child_process'; import { envObjectToArray } from './clientHelper'; import { assert, headersObjectToArray, monotonicTime } from '../utils'; import type * as api from '../../types/types'; import { kBrowserClosedError } from '../common/errors'; import { raceAgainstTimeout } from '../utils/timeoutRunner'; import type { Playwright } from './playwright'; export interface BrowserServerLauncher { launchServer(options?: LaunchServerOptions): Promise<api.BrowserServer>; } // This is here just for api generation and checking. export interface BrowserServer extends api.BrowserServer { process(): ChildProcess; wsEndpoint(): string; close(): Promise<void>; kill(): Promise<void>; } export class BrowserType extends ChannelOwner<channels.BrowserTypeChannel> implements api.BrowserType { _serverLauncher?: BrowserServerLauncher; _contexts = new Set<BrowserContext>(); _playwright!: Playwright; // Instrumentation. _defaultContextOptions?: BrowserContextOptions; _defaultLaunchOptions?: LaunchOptions; _defaultConnectOptions?: ConnectOptions; _onDidCreateContext?: (context: BrowserContext) => Promise<void>; _onWillCloseContext?: (context: BrowserContext) => Promise<void>; static from(browserType: channels.BrowserTypeChannel): BrowserType { return (browserType as any)._object; } executablePath(): string { if (!this._initializer.executablePath) throw new Error('Browser is not supported on current platform'); return this._initializer.executablePath; } name(): string { return this._initializer.name; } async launch(options: LaunchOptions = {}): Promise<Browser> { assert(!(options as any).userDataDir, 'userDataDir option is not supported in `browserType.launch`. Use `browserType.launchPersistentContext` instead'); assert(!(options as any).port, 'Cannot specify a port without launching as a server.'); if (this._defaultConnectOptions) return await this._connectInsteadOfLaunching(this._defaultConnectOptions, options); const logger = options.logger || this._defaultLaunchOptions?.logger; options = { ...this._defaultLaunchOptions, ...options }; const launchOptions: channels.BrowserTypeLaunchParams = { ...options, ignoreDefaultArgs: Array.isArray(options.ignoreDefaultArgs) ? options.ignoreDefaultArgs : undefined, ignoreAllDefaultArgs: !!options.ignoreDefaultArgs && !Array.isArray(options.ignoreDefaultArgs), env: options.env ? envObjectToArray(options.env) : undefined, }; return await this._wrapApiCall(async () => { const browser = Browser.from((await this._channel.launch(launchOptions)).browser); browser._logger = logger; browser._setBrowserType(this); return browser; }); } private async _connectInsteadOfLaunching(connectOptions: ConnectOptions, launchOptions: LaunchOptions): Promise<Browser> { return this._connect({ wsEndpoint: connectOptions.wsEndpoint, headers: { 'x-playwright-launch-options': JSON.stringify({ ...this._defaultLaunchOptions, ...launchOptions }), ...connectOptions.headers, }, _exposeNetwork: connectOptions._exposeNetwork, slowMo: connectOptions.slowMo, timeout: connectOptions.timeout ?? 3 * 60 * 1000, // 3 minutes }); } async launchServer(options: LaunchServerOptions = {}): Promise<api.BrowserServer> { if (!this._serverLauncher) throw new Error('Launching server is not supported'); options = { ...this._defaultLaunchOptions, ...options }; return this._serverLauncher.launchServer(options); } async launchPersistentContext(userDataDir: string, options: LaunchPersistentContextOptions = {}): Promise<BrowserContext> { const logger = options.logger || this._defaultLaunchOptions?.logger; assert(!(options as any).port, 'Cannot specify a port without launching as a server.'); options = { ...this._defaultLaunchOptions, ...this._defaultContextOptions, ...options }; const contextParams = await prepareBrowserContextParams(options); const persistentParams: channels.BrowserTypeLaunchPersistentContextParams = { ...contextParams, ignoreDefaultArgs: Array.isArray(options.ignoreDefaultArgs) ? options.ignoreDefaultArgs : undefined, ignoreAllDefaultArgs: !!options.ignoreDefaultArgs && !Array.isArray(options.ignoreDefaultArgs), env: options.env ? envObjectToArray(options.env) : undefined, channel: options.channel, userDataDir, }; return await this._wrapApiCall(async () => { const result = await this._channel.launchPersistentContext(persistentParams); const context = BrowserContext.from(result.context); context._options = contextParams; context._logger = logger; context._setBrowserType(this); await this._onDidCreateContext?.(context); return context; }); } connect(options: api.ConnectOptions & { wsEndpoint: string }): Promise<api.Browser>; connect(wsEndpoint: string, options?: api.ConnectOptions): Promise<api.Browser>; async connect(optionsOrWsEndpoint: string | (api.ConnectOptions & { wsEndpoint: string }), options?: api.ConnectOptions): Promise<Browser>{ if (typeof optionsOrWsEndpoint === 'string') return this._connect({ ...options, wsEndpoint: optionsOrWsEndpoint }); assert(optionsOrWsEndpoint.wsEndpoint, 'options.wsEndpoint is required'); return this._connect(optionsOrWsEndpoint); } async _connect(params: ConnectOptions): Promise<Browser> { const logger = params.logger; return await this._wrapApiCall(async () => { const deadline = params.timeout ? monotonicTime() + params.timeout : 0; const headers = { 'x-playwright-browser': this.name(), ...params.headers }; const localUtils = this._connection.localUtils(); const connectParams: channels.LocalUtilsConnectParams = { wsEndpoint: params.wsEndpoint, headers, exposeNetwork: params._exposeNetwork, slowMo: params.slowMo, timeout: params.timeout, }; if ((params as any).__testHookRedirectPortForwarding) connectParams.socksProxyRedirectPortForTest = (params as any).__testHookRedirectPortForwarding; const { pipe } = await localUtils._channel.connect(connectParams); const closePipe = () => pipe.close().catch(() => {}); const connection = new Connection(localUtils); connection.markAsRemote(); connection.on('close', closePipe); let browser: Browser; let closeError: string | undefined; const onPipeClosed = () => { // Emulate all pages, contexts and the browser closing upon disconnect. for (const context of browser?.contexts() || []) { for (const page of context.pages()) page._onClose(); context._onClose(); } browser?._didClose(); connection.close(closeError || kBrowserClosedError); }; pipe.on('closed', onPipeClosed); connection.onmessage = message => pipe.send({ message }).catch(onPipeClosed); pipe.on('message', ({ message }) => { try { connection!.dispatch(message); } catch (e) { closeError = e.toString(); closePipe(); } }); const result = await raceAgainstTimeout(async () => { // For tests. if ((params as any).__testHookBeforeCreateBrowser) await (params as any).__testHookBeforeCreateBrowser(); const playwright = await connection!.initializePlaywright(); if (!playwright._initializer.preLaunchedBrowser) { closePipe(); throw new Error('Malformed endpoint. Did you use BrowserType.launchServer method?'); } playwright._setSelectors(this._playwright.selectors); browser = Browser.from(playwright._initializer.preLaunchedBrowser!); browser._logger = logger; browser._shouldCloseConnectionOnClose = true; browser._setBrowserType(this); browser.on(Events.Browser.Disconnected, closePipe); return browser; }, deadline ? deadline - monotonicTime() : 0); if (!result.timedOut) { return result.result; } else { closePipe(); throw new Error(`Timeout ${params.timeout}ms exceeded`); } }); } connectOverCDP(options: api.ConnectOverCDPOptions & { wsEndpoint?: string }): Promise<api.Browser>; connectOverCDP(endpointURL: string, options?: api.ConnectOverCDPOptions): Promise<api.Browser>; connectOverCDP(endpointURLOrOptions: (api.ConnectOverCDPOptions & { wsEndpoint?: string })|string, options?: api.ConnectOverCDPOptions) { if (typeof endpointURLOrOptions === 'string') return this._connectOverCDP(endpointURLOrOptions, options); const endpointURL = 'endpointURL' in endpointURLOrOptions ? endpointURLOrOptions.endpointURL : endpointURLOrOptions.wsEndpoint; assert(endpointURL, 'Cannot connect over CDP without wsEndpoint.'); return this.connectOverCDP(endpointURL, endpointURLOrOptions); } async _connectOverCDP(endpointURL: string, params: api.ConnectOverCDPOptions = {}): Promise<Browser> { if (this.name() !== 'chromium') throw new Error('Connecting over CDP is only supported in Chromium.'); const headers = params.headers ? headersObjectToArray(params.headers) : undefined; const result = await this._channel.connectOverCDP({ endpointURL, headers, slowMo: params.slowMo, timeout: params.timeout }); const browser = Browser.from(result.browser); if (result.defaultContext) browser._contexts.add(BrowserContext.from(result.defaultContext)); browser._logger = params.logger; browser._setBrowserType(this); return browser; } }
packages/playwright-core/src/client/browserType.ts
0
https://github.com/microsoft/playwright/commit/bfc895787fdff1c22b15ef775092585bc2c88791
[ 0.0014791770372539759, 0.00022750213975086808, 0.00016415993741247803, 0.00016948668053373694, 0.0002570370561443269 ]
{ "id": 1, "code_window": [ " server.setRedirect('/empty.html', server.CROSS_PROCESS_PREFIX + '/title.html');\n", " await page.reload();\n", " await expect(page).toHaveURL(server.CROSS_PROCESS_PREFIX + '/title.html');\n", "});\n", "\n", "it('page.reload should work on a page with a hash', async ({ page, server, browserName }) => {\n", " it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/21145' });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "it('page.reload should work on a page with a hash', async ({ page, server }) => {\n" ], "file_path": "tests/page/page-history.spec.ts", "type": "replace", "edit_start_line_idx": 187 }
body { background-color: red; }
tests/assets/injectedstyle.css
0
https://github.com/microsoft/playwright/commit/bfc895787fdff1c22b15ef775092585bc2c88791
[ 0.0001659874978940934, 0.0001659874978940934, 0.0001659874978940934, 0.0001659874978940934, 0 ]
{ "id": 1, "code_window": [ " server.setRedirect('/empty.html', server.CROSS_PROCESS_PREFIX + '/title.html');\n", " await page.reload();\n", " await expect(page).toHaveURL(server.CROSS_PROCESS_PREFIX + '/title.html');\n", "});\n", "\n", "it('page.reload should work on a page with a hash', async ({ page, server, browserName }) => {\n", " it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/21145' });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "it('page.reload should work on a page with a hash', async ({ page, server }) => {\n" ], "file_path": "tests/page/page-history.spec.ts", "type": "replace", "edit_start_line_idx": 187 }
<div style="height: 1000px; width: 1000px; background: red">One</div> <div style="height: 1000px; width: 1000px; background: blue">Two</div> <div style="height: 1000px; width: 1000px; background: red">Three</div> <div style="height: 1000px; width: 1000px; background: blue">Four</div> <div style="height: 1000px; width: 1000px; background: red">Five</div> <iframe loading="lazy" src='./frame.html'></iframe>
tests/assets/frames/lazy-frame.html
0
https://github.com/microsoft/playwright/commit/bfc895787fdff1c22b15ef775092585bc2c88791
[ 0.00016927883552853018, 0.00016927883552853018, 0.00016927883552853018, 0.00016927883552853018, 0 ]
{ "id": 2, "code_window": [ " it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/21145' });\n", " it.fixme(browserName === 'firefox');\n", " await page.goto(server.EMPTY_PAGE + '#hash');\n", " await page.reload();\n", " await expect(page).toHaveURL(server.EMPTY_PAGE + '#hash');\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "tests/page/page-history.spec.ts", "type": "replace", "edit_start_line_idx": 189 }
/** * Copyright 2018 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { test as it, expect } from './pageTest'; import url from 'url'; it('page.goBack should work @smoke', async ({ page, server }) => { expect(await page.goBack()).toBe(null); await page.goto(server.EMPTY_PAGE); await page.goto(server.PREFIX + '/grid.html'); let response = await page.goBack(); expect(response.ok()).toBe(true); expect(response.url()).toContain(server.EMPTY_PAGE); response = await page.goForward(); expect(response.ok()).toBe(true); expect(response.url()).toContain('/grid.html'); response = await page.goForward(); expect(response).toBe(null); }); it('page.goBack should work with HistoryAPI', async ({ page, server }) => { await page.goto(server.EMPTY_PAGE); await page.evaluate(() => { history.pushState({}, '', '/first.html'); history.pushState({}, '', '/second.html'); }); expect(page.url()).toBe(server.PREFIX + '/second.html'); await page.goBack(); expect(page.url()).toBe(server.PREFIX + '/first.html'); await page.goBack(); expect(page.url()).toBe(server.EMPTY_PAGE); await page.goForward(); expect(page.url()).toBe(server.PREFIX + '/first.html'); }); it('page.goBack should work for file urls', async ({ page, server, asset, browserName, platform, isAndroid }) => { it.fail(browserName === 'webkit' && platform === 'darwin', 'WebKit embedder fails to go back/forward to the file url.'); it.skip(isAndroid, 'No files on Android'); const url1 = url.pathToFileURL(asset('consolelog.html')).href; const url2 = server.PREFIX + '/consolelog.html'; await Promise.all([ page.waitForEvent('console', message => message.text() === 'here:' + url1), page.goto(url1), ]); await page.setContent(`<a href='${url2}'>url2</a>`); expect(page.url().toLowerCase()).toBe(url1.toLowerCase()); await Promise.all([ page.waitForEvent('console', message => message.text() === 'here:' + url2), page.click('a'), ]); expect(page.url()).toBe(url2); await Promise.all([ page.waitForEvent('console', message => message.text() === 'here:' + url1), page.goBack(), ]); expect(page.url().toLowerCase()).toBe(url1.toLowerCase()); // Should be able to evaluate in the new context, and // not reach for the old cross-process one. expect(await page.evaluate(() => window.scrollX)).toBe(0); // Should be able to screenshot. await page.screenshot(); await Promise.all([ page.waitForEvent('console', message => message.text() === 'here:' + url2), page.goForward(), ]); expect(page.url()).toBe(url2); expect(await page.evaluate(() => window.scrollX)).toBe(0); await page.screenshot(); }); it('goBack/goForward should work with bfcache-able pages', async ({ page, server }) => { await page.goto(server.PREFIX + '/cached/one-style.html'); await page.setContent(`<a href=${JSON.stringify(server.PREFIX + '/cached/one-style.html?foo')}>click me</a>`); await page.click('a'); let response = await page.goBack(); expect(response.url()).toBe(server.PREFIX + '/cached/one-style.html'); response = await page.goForward(); expect(response.url()).toBe(server.PREFIX + '/cached/one-style.html?foo'); }); it('page.reload should work', async ({ page, server }) => { await page.goto(server.EMPTY_PAGE); await page.evaluate(() => window['_foo'] = 10); await page.reload(); expect(await page.evaluate(() => window['_foo'])).toBe(undefined); }); it('page.reload should work with data url', async ({ page, server }) => { await page.goto('data:text/html,hello'); expect(await page.content()).toContain('hello'); expect(await page.reload()).toBe(null); expect(await page.content()).toContain('hello'); }); it('page.reload during renderer-initiated navigation', async ({ page, server }) => { await page.goto(server.PREFIX + '/one-style.html'); await page.setContent(`<form method='POST' action='/post'>Form is here<input type='submit'></form>`); server.setRoute('/post', (req, res) => {}); let callback; const reloadFailedPromise = new Promise(f => callback = f); page.once('request', async () => { await page.reload().catch(e => {}); callback(); }); const clickPromise = page.click('input[type=submit]').catch(e => {}); await reloadFailedPromise; await clickPromise; // Form submit should be canceled, and reload should eventually arrive // to the original one-style.html. await page.waitForSelector('text=hello'); }); it('page.reload should not resolve with same-document navigation', async ({ page, server }) => { await page.goto(server.EMPTY_PAGE); // 1. Make sure execution contexts are ready for fast evaluate. await page.evaluate('1'); // 2. Stall the reload request. let response; server.setRoute('/empty.html', (req, res) => { response = res; }); const requestPromise = server.waitForRequest('/empty.html'); // 3. Trigger push state that could resolve the reload. page.evaluate(() => { window.history.pushState({}, ''); }).catch(() => {}); // 4. Trigger the reload, it should not resolve. const reloadPromise = page.reload(); // 5. Trigger push state again, for the good measure :) page.evaluate(() => { window.history.pushState({}, ''); }).catch(() => {}); // 5. Serve the request, it should resolve the reload. await requestPromise; response.end('hello'); // 6. Check the reload response. const gotResponse = await reloadPromise; expect(await gotResponse.text()).toBe('hello'); }); it('page.reload should work with same origin redirect', async ({ page, server }) => { it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/16147' }); await page.goto(server.EMPTY_PAGE); server.setRedirect('/empty.html', server.PREFIX + '/title.html'); await page.reload(); await expect(page).toHaveURL(server.PREFIX + '/title.html'); }); it('page.reload should work with cross-origin redirect', async ({ page, server, browserName }) => { it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/16147' }); await page.goto(server.EMPTY_PAGE); server.setRedirect('/empty.html', server.CROSS_PROCESS_PREFIX + '/title.html'); await page.reload(); await expect(page).toHaveURL(server.CROSS_PROCESS_PREFIX + '/title.html'); }); it('page.reload should work on a page with a hash', async ({ page, server, browserName }) => { it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/21145' }); it.fixme(browserName === 'firefox'); await page.goto(server.EMPTY_PAGE + '#hash'); await page.reload(); await expect(page).toHaveURL(server.EMPTY_PAGE + '#hash'); }); it('page.goBack during renderer-initiated navigation', async ({ page, server }) => { await page.goto(server.PREFIX + '/one-style.html'); await page.goto(server.EMPTY_PAGE); await page.setContent(`<form method='POST' action='/post'>Form is here<input type='submit'></form>`); server.setRoute('/post', (req, res) => {}); let callback; const reloadFailedPromise = new Promise(f => callback = f); page.once('request', async () => { await page.goBack().catch(e => {}); callback(); }); const clickPromise = page.click('input[type=submit]').catch(e => {}); await reloadFailedPromise; await clickPromise; // Form submit should be canceled, and goBack should eventually arrive // to the original one-style.html. await page.waitForSelector('text=hello'); }); it('page.goForward during renderer-initiated navigation', async ({ page, server }) => { await page.goto(server.EMPTY_PAGE); await page.goto(server.PREFIX + '/one-style.html'); await page.goBack(); await page.setContent(`<form method='POST' action='/post'>Form is here<input type='submit'></form>`); server.setRoute('/post', (req, res) => {}); let callback; const reloadFailedPromise = new Promise(f => callback = f); page.once('request', async () => { await page.goForward().catch(e => {}); callback(); }); const clickPromise = page.click('input[type=submit]').catch(e => {}); await reloadFailedPromise; await clickPromise; // Form submit should be canceled, and goForward should eventually arrive // to the original one-style.html. await page.waitForSelector('text=hello'); }); it('regression test for issue 20791', async ({ page, server }) => { it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/20791' }); server.setRoute('/iframe.html', (req, res) => { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); // iframe access parent frame to log a value from it. res.end(` <!doctype html> <script type="text/javascript"> console.log(window.parent.foo); </script> `); }); server.setRoute('/main.html', (req, res) => { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end(` <!doctype html> <iframe id=myframe src="about:blank"></iframe> <script type="text/javascript"> setTimeout(() => window.foo = 'foo', 0); setTimeout(() => myframe.contentDocument.location.href = '${server.PREFIX}/iframe.html', 0); </script> `); }); const messages = []; page.on('console', msg => messages.push(msg.text())); await page.goto(server.PREFIX + '/main.html'); await expect.poll(() => messages).toEqual(['foo']); await page.reload(); await expect.poll(() => messages).toEqual(['foo', 'foo']); }); it('should reload proper page', async ({ page, server }) => { let mainRequest = 0, popupRequest = 0; server.setRoute('/main.html', (req, res) => { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end(`<!doctype html><h1>main: ${++mainRequest}</h1>`); }); server.setRoute('/popup.html', (req, res) => { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end(`<!doctype html><h1>popup: ${++popupRequest}</h1>`); }); await page.goto(server.PREFIX + '/main.html'); const [popup] = await Promise.all([ page.waitForEvent('popup'), page.evaluate(() => window.open('/popup.html')), ]); await expect(page.locator('h1')).toHaveText('main: 1'); await expect(popup.locator('h1')).toHaveText('popup: 1'); await page.reload(); await expect(page.locator('h1')).toHaveText('main: 2'); await expect(popup.locator('h1')).toHaveText('popup: 1'); await popup.reload(); await expect(page.locator('h1')).toHaveText('main: 2'); await expect(popup.locator('h1')).toHaveText('popup: 2'); });
tests/page/page-history.spec.ts
1
https://github.com/microsoft/playwright/commit/bfc895787fdff1c22b15ef775092585bc2c88791
[ 0.7872978448867798, 0.03151901438832283, 0.00016587658319622278, 0.0013188181910663843, 0.14090092480182648 ]
{ "id": 2, "code_window": [ " it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/21145' });\n", " it.fixme(browserName === 'firefox');\n", " await page.goto(server.EMPTY_PAGE + '#hash');\n", " await page.reload();\n", " await expect(page).toHaveURL(server.EMPTY_PAGE + '#hash');\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "tests/page/page-history.spec.ts", "type": "replace", "edit_start_line_idx": 189 }
<!DOCTYPE html> <link rel='stylesheet' href='./one-style.css'> <div>hello, world!</div>
tests/assets/one-style.html
0
https://github.com/microsoft/playwright/commit/bfc895787fdff1c22b15ef775092585bc2c88791
[ 0.00017321745690423995, 0.00017321745690423995, 0.00017321745690423995, 0.00017321745690423995, 0 ]
{ "id": 2, "code_window": [ " it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/21145' });\n", " it.fixme(browserName === 'firefox');\n", " await page.goto(server.EMPTY_PAGE + '#hash');\n", " await page.reload();\n", " await expect(page).toHaveURL(server.EMPTY_PAGE + '#hash');\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "tests/page/page-history.spec.ts", "type": "replace", "edit_start_line_idx": 189 }
<!-- Copyright (c) Microsoft Corporation. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="icon" type="image/png" sizes="32x32" href="/icon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="/icon-16x16.png"> <link rel="manifest" href="/manifest.webmanifest"> <title>Playwright Trace Viewer</title> </head> <body> <div id="root"></div> <script type="module" src="/src/index.tsx"></script> <dialog id="fallback-error"> <p>The Playwright Trace Viewer must be loaded over the <code>http://</code> or <code>https://</code> protocols.</p> <p>For more information, please see the <a href="https://aka.ms/playwright/trace-viewer-file-protocol">docs</a>.</p> </dialog> <script> if (!/^https?:/.test(window.location.protocol)) document.getElementById("fallback-error").show(); </script> </body> </html>
packages/trace-viewer/index.html
0
https://github.com/microsoft/playwright/commit/bfc895787fdff1c22b15ef775092585bc2c88791
[ 0.00019002609769813716, 0.00018006816389970481, 0.00017574256344232708, 0.0001772519899532199, 0.000005871433131687809 ]
{ "id": 2, "code_window": [ " it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/21145' });\n", " it.fixme(browserName === 'firefox');\n", " await page.goto(server.EMPTY_PAGE + '#hash');\n", " await page.reload();\n", " await expect(page).toHaveURL(server.EMPTY_PAGE + '#hash');\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "tests/page/page-history.spec.ts", "type": "replace", "edit_start_line_idx": 189 }
<!doctype html> <html> <head> <title>Name radio-label-embedded-spinbutton</title> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/> <link rel="stylesheet" href="/wai-aria/scripts/manual.css"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/wai-aria/scripts/ATTAcomm.js"></script> <script> setup({explicit_timeout: true, explicit_done: true }); var theTest = new ATTAcomm( { "steps" : [ { "element" : "test", "test" : { "ATK" : [ [ "property", "name", "is", "foo 5 baz" ] ], "AXAPI" : [ [ "property", "AXDescription", "is", "foo 5 baz" ] ], "IAccessible2" : [ [ "property", "accName", "is", "foo 5 baz" ] ], "UIA" : [ [ "property", "Name", "is", "foo 5 baz" ] ] }, "title" : "step 1", "type" : "test" } ], "title" : "Name radio-label-embedded-spinbutton" } ) ; </script> </head> <body> <p>This test examines the ARIA properties for Name radio-label-embedded-spinbutton.</p> <input type="radio" id="test" /> <label for="test">foo <input role="spinbutton" type="number" value="5" min="1" max="10" aria-valuenow="5" aria-valuemin="1" aria-valuemax="10"> baz </label> <div id="manualMode"></div> <div id="log"></div> <div id="ATTAmessages"></div> </body> </html>
tests/assets/wpt/accname/name_radio-label-embedded-spinbutton-manual.html
0
https://github.com/microsoft/playwright/commit/bfc895787fdff1c22b15ef775092585bc2c88791
[ 0.0001756482379278168, 0.00017213872342836112, 0.0001687074254732579, 0.00017243533511646092, 0.0000023650129605812253 ]
{ "id": 0, "code_window": [ "\n", " final eventName = _getHostListenerEventName(meta);\n", " final params = _getHostListenerParams(meta);\n", " _host['(${eventName})'] = '${node.name}($params)';\n", " }\n", " }\n", " return null;\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", " if (_isAnnotation(meta, 'HostBinding') && node.isGetter) {\n", " final renamed = _getRenamedValue(meta);\n", " if (renamed != null) {\n", " _host['[${renamed}]'] = '${node.name}';\n", " } else {\n", " _host['[${node.name}]'] = '${node.name}';\n", " }\n", " }\n" ], "file_path": "modules_dart/transform/lib/src/transform/common/type_metadata_reader.dart", "type": "add", "edit_start_line_idx": 296 }
library angular2.test.transform.directive_processor.all_tests; import 'dart:async'; import 'package:barback/barback.dart'; import 'package:dart_style/dart_style.dart'; import 'package:guinness/guinness.dart'; import 'package:angular2/src/core/change_detection/change_detection.dart'; import 'package:angular2/src/platform/server/html_adapter.dart'; import 'package:angular2/src/core/linker/interfaces.dart' show LifecycleHooks; import 'package:angular2/src/transform/common/annotation_matcher.dart'; import 'package:angular2/src/transform/common/asset_reader.dart'; import 'package:angular2/src/transform/common/code/ng_deps_code.dart'; import 'package:angular2/src/transform/common/model/ng_deps_model.pb.dart'; import 'package:angular2/src/transform/common/model/reflection_info_model.pb.dart'; import 'package:angular2/src/transform/common/ng_meta.dart'; import 'package:angular2/src/transform/common/zone.dart' as zone; import 'package:angular2/src/transform/directive_processor/rewriter.dart'; import '../common/read_file.dart'; import '../common/recording_logger.dart'; var formatter = new DartFormatter(); main() { Html5LibDomAdapter.makeCurrent(); allTests(); } Expect _expectSelector(ReflectionInfoModel model) { expect(model.annotations.isNotEmpty).toBeTrue(); var componentAnnotation = model.annotations .firstWhere((e) => e.name == 'Component', orElse: () => null); expect(componentAnnotation).toBeNotNull(); var selectorArg = componentAnnotation.namedParameters .firstWhere((e) => e.name == 'selector', orElse: () => null); expect(selectorArg).toBeNotNull(); return expect(selectorArg.value); } void allTests() { it('should preserve parameter annotations.', () async { var model = (await _testCreateModel('parameter_metadata/soup.dart')).ngDeps; expect(model.reflectables.length).toBe(1); var reflectable = model.reflectables.first; expect(reflectable.parameters.length).toBe(2); expect(reflectable.parameters.first.typeName).toEqual('String'); expect(reflectable.parameters.first.metadata.length).toBe(1); expect(reflectable.parameters.first.metadata.first).toContain('Tasty'); expect(reflectable.parameters.first.paramName).toEqual('description'); var typeName = reflectable.parameters[1].typeName; expect(typeName == null || typeName.isEmpty).toBeTrue(); var secondParam = reflectable.parameters[1]; expect(secondParam.metadata.first).toContain('Inject(Salt)'); expect(secondParam.paramName).toEqual('salt'); }); describe('part support', () { var modelFuture = _testCreateModel('part_files/main.dart') .then((ngMeta) => ngMeta != null ? ngMeta.ngDeps : null); it('should include directives from the part.', () async { var model = await modelFuture; expect(model.reflectables.length).toBe(2); }); it('should list part contributions first.', () async { var model = await modelFuture; expect(model.reflectables.first.name).toEqual('PartComponent'); _expectSelector(model.reflectables.first).toEqual("'[part]'"); }); it('should list main contributions second.', () async { var model = await modelFuture; expect(model.reflectables[1].name).toEqual('MainComponent'); _expectSelector(model.reflectables[1]).toEqual("'[main]'"); }); it('should handle multiple `part` directives.', () async { var model = (await _testCreateModel('multiple_part_files/main.dart')).ngDeps; expect(model.reflectables.length).toEqual(3); _expectSelector(model.reflectables.first).toEqual("'[part1]'"); _expectSelector(model.reflectables[1]).toEqual("'[part2]'"); _expectSelector(model.reflectables[2]).toEqual("'[main]'"); }); it('should not generate anything for `part` files.', () async { expect(await _testCreateModel('part_files/part.dart')).toBeNull(); }); }); describe('custom annotations', () { it('should be recognized from package: imports', () async { var ngMeta = await _testCreateModel('custom_metadata/package_soup.dart', customDescriptors: [ const ClassDescriptor('Soup', 'package:soup/soup.dart', superClass: 'Component') ]); var model = ngMeta.ngDeps; expect(model.reflectables.length).toEqual(1); expect(model.reflectables.first.name).toEqual('PackageSoup'); }); it('should be recognized from relative imports', () async { var ngMeta = await _testCreateModel('custom_metadata/relative_soup.dart', assetId: new AssetId('soup', 'lib/relative_soup.dart'), customDescriptors: [ const ClassDescriptor('Soup', 'package:soup/annotations/soup.dart', superClass: 'Component') ]); var model = ngMeta.ngDeps; expect(model.reflectables.length).toEqual(1); expect(model.reflectables.first.name).toEqual('RelativeSoup'); }); it('should ignore annotations that are not imported', () async { var ngMeta = await _testCreateModel('custom_metadata/bad_soup.dart', customDescriptors: [ const ClassDescriptor('Soup', 'package:soup/soup.dart', superClass: 'Component') ]); expect(ngMeta.ngDeps == null || ngMeta.ngDeps.reflectables.isEmpty) .toBeTrue(); }); }); describe('interfaces', () { it('should include implemented types', () async { var model = (await _testCreateModel('interfaces_files/soup.dart')).ngDeps; expect(model.reflectables.first.interfaces).toBeNotNull(); expect(model.reflectables.first.interfaces.isNotEmpty).toBeTrue(); expect(model.reflectables.first.interfaces.contains('OnChanges')) .toBeTrue(); expect(model.reflectables.first.interfaces.contains('AnotherInterface')) .toBeTrue(); }); it('should not include transitively implemented types', () async { var model = (await _testCreateModel('interface_chain_files/soup.dart')).ngDeps; expect(model.reflectables.first.interfaces).toBeNotNull(); expect(model.reflectables.first.interfaces.isNotEmpty).toBeTrue(); expect(model.reflectables.first.interfaces.contains('PrimaryInterface')) .toBeTrue(); expect(model.reflectables.first.interfaces.contains('SecondaryInterface')) .toBeFalse(); expect(model.reflectables.first.interfaces.contains('TernaryInterface')) .toBeFalse(); }); it('should not include superclasses.', () async { var model = (await _testCreateModel('superclass_files/soup.dart')).ngDeps; var interfaces = model.reflectables.first.interfaces; expect(interfaces == null || interfaces.isEmpty).toBeTrue(); }); it('should populate multiple `lifecycle` values when necessary.', () async { var model = (await _testCreateModel( 'multiple_interface_lifecycle_files/soup.dart')).ngDeps; expect(model.reflectables.first.interfaces).toBeNotNull(); expect(model.reflectables.first.interfaces.isNotEmpty).toBeTrue(); expect(model.reflectables.first.interfaces.contains('OnChanges')) .toBeTrue(); expect(model.reflectables.first.interfaces.contains('OnDestroy')) .toBeTrue(); expect(model.reflectables.first.interfaces.contains('OnInit')).toBeTrue(); }); it('should not populate `lifecycle` when lifecycle superclass is present.', () async { var model = (await _testCreateModel('superclass_lifecycle_files/soup.dart')) .ngDeps; var interfaces = model.reflectables.first.interfaces; expect(interfaces == null || interfaces.isEmpty).toBeTrue(); }); it('should populate `lifecycle` with prefix when necessary.', () async { var model = (await _testCreateModel( 'prefixed_interface_lifecycle_files/soup.dart')).ngDeps; expect(model.reflectables.first.interfaces).toBeNotNull(); expect(model.reflectables.first.interfaces.isNotEmpty).toBeTrue(); expect(model.reflectables.first.interfaces .firstWhere((i) => i.contains('OnChanges'), orElse: () => null)) .toBeNotNull(); }); }); describe('property metadata', () { it('should be recorded on fields', () async { var model = (await _testCreateModel('prop_metadata_files/fields.dart')).ngDeps; expect(model.reflectables.first.propertyMetadata).toBeNotNull(); expect(model.reflectables.first.propertyMetadata.isNotEmpty).toBeTrue(); expect(model.reflectables.first.propertyMetadata.first.name) .toEqual('field'); expect(model.reflectables.first.propertyMetadata.first.annotations .firstWhere((a) => a.name == 'FieldDecorator', orElse: () => null)).toBeNotNull(); }); it('should be recorded on getters', () async { var model = (await _testCreateModel('prop_metadata_files/getters.dart')).ngDeps; expect(model.reflectables.first.propertyMetadata).toBeNotNull(); expect(model.reflectables.first.propertyMetadata.isNotEmpty).toBeTrue(); expect(model.reflectables.first.propertyMetadata.first.name) .toEqual('getVal'); var getDecoratorAnnotation = model .reflectables.first.propertyMetadata.first.annotations .firstWhere((a) => a.name == 'GetDecorator', orElse: () => null); expect(getDecoratorAnnotation).toBeNotNull(); expect(getDecoratorAnnotation.isConstObject).toBeFalse(); }); it('should gracefully handle const instances of annotations', () async { // Regression test for i/4481 var model = (await _testCreateModel('prop_metadata_files/override.dart')).ngDeps; expect(model.reflectables.first.propertyMetadata).toBeNotNull(); expect(model.reflectables.first.propertyMetadata.isNotEmpty).toBeTrue(); expect(model.reflectables.first.propertyMetadata.first.name) .toEqual('getVal'); var overrideAnnotation = model .reflectables.first.propertyMetadata.first.annotations .firstWhere((a) => a.name == 'override', orElse: () => null); expect(overrideAnnotation).toBeNotNull(); expect(overrideAnnotation.isConstObject).toBeTrue(); var buf = new StringBuffer(); new NgDepsWriter(buf).writeAnnotationModel(overrideAnnotation); expect(buf.toString()).toEqual('override'); }); it('should be recorded on setters', () async { var model = (await _testCreateModel('prop_metadata_files/setters.dart')).ngDeps; expect(model.reflectables.first.propertyMetadata).toBeNotNull(); expect(model.reflectables.first.propertyMetadata.isNotEmpty).toBeTrue(); expect(model.reflectables.first.propertyMetadata.first.name) .toEqual('setVal'); expect(model.reflectables.first.propertyMetadata.first.annotations .firstWhere((a) => a.name == 'SetDecorator', orElse: () => null)) .toBeNotNull(); }); it('should be coalesced when getters and setters have the same name', () async { var model = (await _testCreateModel( 'prop_metadata_files/getters_and_setters.dart')).ngDeps; expect(model.reflectables.first.propertyMetadata).toBeNotNull(); expect(model.reflectables.first.propertyMetadata.length).toBe(1); expect(model.reflectables.first.propertyMetadata.first.name) .toEqual('myVal'); expect(model.reflectables.first.propertyMetadata.first.annotations .firstWhere((a) => a.name == 'GetDecorator', orElse: () => null)) .toBeNotNull(); expect(model.reflectables.first.propertyMetadata.first.annotations .firstWhere((a) => a.name == 'SetDecorator', orElse: () => null)) .toBeNotNull(); }); }); it('should not throw/hang on invalid urls', () async { var logger = new RecordingLogger(); await _testCreateModel('invalid_url_files/hello.dart', logger: logger); expect(logger.hasErrors).toBeTrue(); expect(logger.logs) ..toContain('ERROR: ERROR: Invalid argument (url): ' '"Could not read asset at uri asset:/bad/absolute/url.html"'); }); it('should find and register static functions.', () async { var model = (await _testCreateModel('static_function_files/hello.dart')).ngDeps; var functionReflectable = model.reflectables.firstWhere((i) => i.isFunction, orElse: () => null); expect(functionReflectable)..toBeNotNull(); expect(functionReflectable.name).toEqual('getMessage'); }); describe('NgMeta', () { var fakeReader; beforeEach(() { fakeReader = new TestAssetReader(); }); it('should find direcive aliases patterns.', () async { var ngMeta = await _testCreateModel('directive_aliases_files/hello.dart'); expect(ngMeta.aliases).toContain('alias1'); expect(ngMeta.aliases['alias1']).toContain('HelloCmp'); expect(ngMeta.aliases).toContain('alias2'); expect(ngMeta.aliases['alias2'])..toContain('HelloCmp')..toContain('Foo'); }); it('should include hooks for implemented types (single)', () async { var ngMeta = await _testCreateModel('interfaces_files/soup.dart'); expect(ngMeta.types.isNotEmpty).toBeTrue(); expect(ngMeta.types['ChangingSoupComponent']).toBeNotNull(); expect(ngMeta.types['ChangingSoupComponent'].selector).toEqual('[soup]'); expect(ngMeta.types['ChangingSoupComponent'].lifecycleHooks) .toContain(LifecycleHooks.OnChanges); }); it('should include hooks for implemented types (many)', () async { var ngMeta = await _testCreateModel( 'multiple_interface_lifecycle_files/soup.dart'); expect(ngMeta.types.isNotEmpty).toBeTrue(); expect(ngMeta.types['MultiSoupComponent']).toBeNotNull(); expect(ngMeta.types['MultiSoupComponent'].selector).toEqual('[soup]'); expect(ngMeta.types['MultiSoupComponent'].lifecycleHooks) ..toContain(LifecycleHooks.OnChanges) ..toContain(LifecycleHooks.OnDestroy) ..toContain(LifecycleHooks.OnInit); }); it('should create type entries for Directives', () async { fakeReader ..addAsset(new AssetId('other_package', 'lib/template.html'), '') ..addAsset(new AssetId('other_package', 'lib/template.css'), ''); var ngMeta = await _testCreateModel( 'absolute_url_expression_files/hello.dart', reader: fakeReader); expect(ngMeta.types.isNotEmpty).toBeTrue(); expect(ngMeta.types['HelloCmp']).toBeNotNull(); expect(ngMeta.types['HelloCmp'].selector).toEqual('hello-app'); }); it('should populate all provided values for Components & Directives', () async { var ngMeta = await _testCreateModel('unusual_component_files/hello.dart'); expect(ngMeta.types.isNotEmpty).toBeTrue(); var component = ngMeta.types['UnusualComp']; expect(component).toBeNotNull(); expect(component.selector).toEqual('unusual-comp'); expect(component.isComponent).toBeTrue(); expect(component.exportAs).toEqual('ComponentExportAsValue'); expect(component.changeDetection) .toEqual(ChangeDetectionStrategy.CheckAlways); expect(component.inputs).toContain('aProperty'); expect(component.inputs['aProperty']).toEqual('aProperty'); expect(component.outputs).toContain('anEvent'); expect(component.outputs['anEvent']).toEqual('anEvent'); expect(component.hostAttributes).toContain('hostKey'); expect(component.hostAttributes['hostKey']).toEqual('hostValue'); var directive = ngMeta.types['UnusualDirective']; expect(directive).toBeNotNull(); expect(directive.selector).toEqual('unusual-directive'); expect(directive.isComponent).toBeFalse(); expect(directive.exportAs).toEqual('DirectiveExportAsValue'); expect(directive.inputs).toContain('aDirectiveProperty'); expect(directive.inputs['aDirectiveProperty']) .toEqual('aDirectiveProperty'); expect(directive.outputs).toContain('aDirectiveEvent'); expect(directive.outputs['aDirectiveEvent']).toEqual('aDirectiveEvent'); expect(directive.hostAttributes).toContain('directiveHostKey'); expect(directive.hostAttributes['directiveHostKey']) .toEqual('directiveHostValue'); }); it('should include hooks for implemented types (single)', () async { var ngMeta = await _testCreateModel('interfaces_files/soup.dart'); expect(ngMeta.types.isNotEmpty).toBeTrue(); expect(ngMeta.types['ChangingSoupComponent']).toBeNotNull(); expect(ngMeta.types['ChangingSoupComponent'].selector).toEqual('[soup]'); expect(ngMeta.types['ChangingSoupComponent'].lifecycleHooks) .toContain(LifecycleHooks.OnChanges); }); it('should include hooks for implemented types (many)', () async { var ngMeta = await _testCreateModel( 'multiple_interface_lifecycle_files/soup.dart'); expect(ngMeta.types.isNotEmpty).toBeTrue(); expect(ngMeta.types['MultiSoupComponent']).toBeNotNull(); expect(ngMeta.types['MultiSoupComponent'].selector).toEqual('[soup]'); expect(ngMeta.types['MultiSoupComponent'].lifecycleHooks) ..toContain(LifecycleHooks.OnChanges) ..toContain(LifecycleHooks.OnDestroy) ..toContain(LifecycleHooks.OnInit); }); it('should parse templates from View annotations', () async { fakeReader ..addAsset(new AssetId('other_package', 'lib/template.html'), '') ..addAsset(new AssetId('other_package', 'lib/template.css'), ''); var ngMeta = await _testCreateModel( 'absolute_url_expression_files/hello.dart', reader: fakeReader); expect(ngMeta.types.isNotEmpty).toBeTrue(); expect(ngMeta.types['HelloCmp']).toBeNotNull(); expect(ngMeta.types['HelloCmp'].template).toBeNotNull(); expect(ngMeta.types['HelloCmp'].template.templateUrl) .toEqual('asset:other_package/lib/template.html'); }); it('should handle prefixed annotations', () async { var model = (await _testCreateModel('prefixed_annotations_files/soup.dart')) .ngDeps; expect(model.reflectables.isEmpty).toBeFalse(); final annotations = model.reflectables.first.annotations; final viewAnnotation = annotations.firstWhere((m) => m.isView, orElse: () => null); final componentAnnotation = annotations.firstWhere((m) => m.isComponent, orElse: () => null); expect(viewAnnotation).toBeNotNull(); expect(viewAnnotation.namedParameters.first.name).toEqual('template'); expect(viewAnnotation.namedParameters.first.value).toContain('SoupView'); expect(componentAnnotation).toBeNotNull(); expect(componentAnnotation.namedParameters.first.name) .toEqual('selector'); expect(componentAnnotation.namedParameters.first.value) .toContain('[soup]'); }); }); describe('directives', () { final reflectableNamed = (NgDepsModel model, String name) { return model.reflectables .firstWhere((r) => r.name == name, orElse: () => null); }; it('should populate `directives` from @View value specified second.', () async { var model = (await _testCreateModel('directives_files/components.dart')).ngDeps; final componentFirst = reflectableNamed(model, 'ComponentFirst'); expect(componentFirst).toBeNotNull(); expect(componentFirst.directives).toBeNotNull(); expect(componentFirst.directives.length).toEqual(2); expect(componentFirst.directives.first) .toEqual(new PrefixedType()..name = 'Dep'); expect(componentFirst.directives[1]).toEqual(new PrefixedType() ..name = 'Dep' ..prefix = 'dep2'); }); it('should populate `directives` from @View value specified first.', () async { var model = (await _testCreateModel('directives_files/components.dart')).ngDeps; final viewFirst = reflectableNamed(model, 'ViewFirst'); expect(viewFirst).toBeNotNull(); expect(viewFirst.directives).toBeNotNull(); expect(viewFirst.directives.length).toEqual(2); expect(viewFirst.directives.first).toEqual(new PrefixedType() ..name = 'Dep' ..prefix = 'dep2'); expect(viewFirst.directives[1]).toEqual(new PrefixedType()..name = 'Dep'); }); it('should populate `directives` from @Component value with no @View.', () async { var model = (await _testCreateModel('directives_files/components.dart')).ngDeps; final componentOnly = reflectableNamed(model, 'ComponentOnly'); expect(componentOnly).toBeNotNull(); expect(componentOnly.directives).toBeNotNull(); expect(componentOnly.directives.length).toEqual(2); expect(componentOnly.directives.first) .toEqual(new PrefixedType()..name = 'Dep'); expect(componentOnly.directives[1]).toEqual(new PrefixedType() ..name = 'Dep' ..prefix = 'dep2'); }); it('should populate `pipes` from @View value specified second.', () async { var model = (await _testCreateModel('directives_files/components.dart')).ngDeps; final componentFirst = reflectableNamed(model, 'ComponentFirst'); expect(componentFirst).toBeNotNull(); expect(componentFirst.pipes).toBeNotNull(); expect(componentFirst.pipes.length).toEqual(2); expect(componentFirst.pipes.first) .toEqual(new PrefixedType()..name = 'PipeDep'); expect(componentFirst.pipes[1]).toEqual(new PrefixedType() ..name = 'PipeDep' ..prefix = 'dep2'); }); it('should populate `pipes` from @View value specified first.', () async { var model = (await _testCreateModel('directives_files/components.dart')).ngDeps; final viewFirst = reflectableNamed(model, 'ViewFirst'); expect(viewFirst).toBeNotNull(); expect(viewFirst.pipes).toBeNotNull(); expect(viewFirst.pipes.length).toEqual(2); expect(viewFirst.pipes.first).toEqual(new PrefixedType() ..name = 'PipeDep' ..prefix = 'dep2'); expect(viewFirst.pipes[1]).toEqual(new PrefixedType()..name = 'PipeDep'); }); it('should populate `pipes` from @Component value with no @View.', () async { var model = (await _testCreateModel('directives_files/components.dart')).ngDeps; final componentOnly = reflectableNamed(model, 'ComponentOnly'); expect(componentOnly).toBeNotNull(); expect(componentOnly.pipes).toBeNotNull(); expect(componentOnly.pipes.length).toEqual(2); expect(componentOnly.pipes.first) .toEqual(new PrefixedType()..name = 'PipeDep'); expect(componentOnly.pipes[1]).toEqual(new PrefixedType() ..name = 'PipeDep' ..prefix = 'dep2'); }); it('should merge `outputs` from the annotation and fields.', () async { var model = await _testCreateModel('directives_files/components.dart'); expect(model.types['ComponentWithOutputs'].outputs).toEqual( {'a': 'a', 'b': 'b', 'c': 'renamed', 'd': 'd', 'e': 'get-renamed'}); }); it('should merge `inputs` from the annotation and fields.', () async { var model = await _testCreateModel('directives_files/components.dart'); expect(model.types['ComponentWithInputs'].inputs).toEqual( {'a': 'a', 'b': 'b', 'c': 'renamed', 'd': 'd', 'e': 'set-renamed'}); }); it('should merge host bindings from the annotation and fields.', () async { var model = await _testCreateModel('directives_files/components.dart'); expect(model.types['ComponentWithHostBindings'].hostProperties) .toEqual({'a': 'a', 'b': 'b', 'renamed': 'c'}); }); it('should merge host listeners from the annotation and fields.', () async { var model = await _testCreateModel('directives_files/components.dart'); expect(model.types['ComponentWithHostListeners'].hostListeners).toEqual({ 'a': 'onA()', 'b': 'onB()', 'c': 'onC(\$event.target,\$event.target.value)' }); }); it('should warn if @Component has a `template` and @View is present.', () async { final logger = new RecordingLogger(); final model = await _testCreateModel('bad_directives_files/template.dart', logger: logger); var warning = logger.logs.firstWhere((l) => l.contains('WARN'), orElse: () => null); expect(warning).toBeNotNull(); expect(warning.toLowerCase()) .toContain('cannot specify view parameters on @component'); }); it('should warn if @Component has a `templateUrl` and @View is present.', () async { final logger = new RecordingLogger(); final model = await _testCreateModel( 'bad_directives_files/template_url.dart', logger: logger); var warning = logger.logs.firstWhere((l) => l.contains('WARN'), orElse: () => null); expect(warning).toBeNotNull(); expect(warning.toLowerCase()) .toContain('cannot specify view parameters on @component'); }); it('should warn if @Component has `directives` and @View is present.', () async { final logger = new RecordingLogger(); final model = await _testCreateModel( 'bad_directives_files/directives.dart', logger: logger); var warning = logger.logs.firstWhere((l) => l.contains('WARN'), orElse: () => null); expect(warning).toBeNotNull(); expect(warning.toLowerCase()) .toContain('cannot specify view parameters on @component'); }); it('should warn if @Component has `pipes` and @View is present.', () async { final logger = new RecordingLogger(); final model = await _testCreateModel('bad_directives_files/pipes.dart', logger: logger); var warning = logger.logs.firstWhere((l) => l.contains('WARN'), orElse: () => null); expect(warning).toBeNotNull(); expect(warning.toLowerCase()) .toContain('cannot specify view parameters on @component'); }); }); describe('pipes', () { it('should read the pipe name', () async { var model = await _testCreateModel('pipe_files/pipes.dart'); expect(model.types['NameOnlyPipe'].name).toEqual('nameOnly'); expect(model.types['NameOnlyPipe'].pure).toBe(false); }); it('should read the pure flag', () async { var model = await _testCreateModel('pipe_files/pipes.dart'); expect(model.types['NameAndPurePipe'].pure).toBe(true); }); }); } Future<NgMeta> _testCreateModel(String inputPath, {List<AnnotationDescriptor> customDescriptors: const [], AssetId assetId, AssetReader reader, TransformLogger logger}) { if (logger == null) logger = new RecordingLogger(); return zone.exec(() async { var inputId = _assetIdForPath(inputPath); if (reader == null) { reader = new TestAssetReader(); } if (assetId != null) { reader.addAsset(assetId, await reader.readAsString(inputId)); inputId = assetId; } var annotationMatcher = new AnnotationMatcher()..addAll(customDescriptors); return createNgMeta(reader, inputId, annotationMatcher); }, log: logger); } AssetId _assetIdForPath(String path) => new AssetId('angular2', 'test/transform/directive_processor/$path');
modules_dart/transform/test/transform/directive_processor/all_tests.dart
1
https://github.com/angular/angular/commit/a593ffa6f3d7cb6062e9e1957aae1382bfcb666f
[ 0.00018020608695223927, 0.00017649844812694937, 0.0001679995039012283, 0.00017693010158836842, 0.000002420516693746322 ]
{ "id": 0, "code_window": [ "\n", " final eventName = _getHostListenerEventName(meta);\n", " final params = _getHostListenerParams(meta);\n", " _host['(${eventName})'] = '${node.name}($params)';\n", " }\n", " }\n", " return null;\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", " if (_isAnnotation(meta, 'HostBinding') && node.isGetter) {\n", " final renamed = _getRenamedValue(meta);\n", " if (renamed != null) {\n", " _host['[${renamed}]'] = '${node.name}';\n", " } else {\n", " _host['[${node.name}]'] = '${node.name}';\n", " }\n", " }\n" ], "file_path": "modules_dart/transform/lib/src/transform/common/type_metadata_reader.dart", "type": "add", "edit_start_line_idx": 296 }
// Tun on full stack traces in errors to help debugging Error.stackTraceLimit=Infinity; jasmine.DEFAULT_TIMEOUT_INTERVAL = 100; // Cancel Karma's synchronous start, // we will call `__karma__.start()` later, once all the specs are loaded. __karma__.loaded = function() {}; System.config({ baseURL: '/base/', defaultJSExtensions: true, paths: { 'benchpress/*': 'dist/js/dev/es5/benchpress/*.js', 'angular2/*': 'dist/js/dev/es5/angular2/*.js', 'angular2_material/*': 'dist/js/dev/es5/angular2_material/*.js', 'rxjs/*': 'node_modules/rxjs/*.js' } }); // Set up the test injector, then import all the specs, execute their `main()` // method and kick off Karma (Jasmine). System.import('angular2/testing').then(function(testing) { return System.import('angular2/platform/testing/browser').then(function(testing_platform_browser) { testing.setBaseTestProviders(testing_platform_browser.TEST_BROWSER_PLATFORM_PROVIDERS, testing_platform_browser.TEST_BROWSER_APPLICATION_PROVIDERS); }); }).then(function() { return Promise.all( Object.keys(window.__karma__.files) // All files served by Karma. .filter(onlySpecFiles) .map(window.file2moduleName) // Normalize paths to module names. .map(function(path) { return System.import(path).then(function(module) { if (module.hasOwnProperty('main')) { module.main(); } else { throw new Error('Module ' + path + ' does not implement main() method.'); } }); })); }) .then(function() { __karma__.start(); }, function(error) { __karma__.error(error.stack || error); }); function onlySpecFiles(path) { return /_spec\.js$/.test(path); }
test-main.js
0
https://github.com/angular/angular/commit/a593ffa6f3d7cb6062e9e1957aae1382bfcb666f
[ 0.00017538883548695594, 0.00017302633204963058, 0.00016742493608035147, 0.0001741058222251013, 0.000002752224418145488 ]
{ "id": 0, "code_window": [ "\n", " final eventName = _getHostListenerEventName(meta);\n", " final params = _getHostListenerParams(meta);\n", " _host['(${eventName})'] = '${node.name}($params)';\n", " }\n", " }\n", " return null;\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", " if (_isAnnotation(meta, 'HostBinding') && node.isGetter) {\n", " final renamed = _getRenamedValue(meta);\n", " if (renamed != null) {\n", " _host['[${renamed}]'] = '${node.name}';\n", " } else {\n", " _host['[${node.name}]'] = '${node.name}';\n", " }\n", " }\n" ], "file_path": "modules_dart/transform/lib/src/transform/common/type_metadata_reader.dart", "type": "add", "edit_start_line_idx": 296 }
initReflector() {}
modules_dart/transform/test/transform/integration/empty_ng_deps_files/expected/bar.ng_deps.dart
0
https://github.com/angular/angular/commit/a593ffa6f3d7cb6062e9e1957aae1382bfcb666f
[ 0.0001723342720651999, 0.0001723342720651999, 0.0001723342720651999, 0.0001723342720651999, 0 ]
{ "id": 0, "code_window": [ "\n", " final eventName = _getHostListenerEventName(meta);\n", " final params = _getHostListenerParams(meta);\n", " _host['(${eventName})'] = '${node.name}($params)';\n", " }\n", " }\n", " return null;\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", " if (_isAnnotation(meta, 'HostBinding') && node.isGetter) {\n", " final renamed = _getRenamedValue(meta);\n", " if (renamed != null) {\n", " _host['[${renamed}]'] = '${node.name}';\n", " } else {\n", " _host['[${node.name}]'] = '${node.name}';\n", " }\n", " }\n" ], "file_path": "modules_dart/transform/lib/src/transform/common/type_metadata_reader.dart", "type": "add", "edit_start_line_idx": 296 }
/// <reference path="../typings/node/node.d.ts" /> /// <reference path="../typings/jasmine/jasmine.d.ts" /> console.warn( "Skipping all tests in broccoli-merge-trees.spec.ts because they require mock-fs which is currently incompatible with node 4.x. See: https://github.com/tschaub/mock-fs/issues/59"); /* let mockfs = require('mock-fs'); import fs = require('fs'); import {TreeDiffer} from './tree-differ'; import {MergeTrees} from './broccoli-merge-trees'; describe('MergeTrees', () => { afterEach(() => mockfs.restore()); function mergeTrees(inputPaths, cachePath, options) { return new MergeTrees(inputPaths, cachePath, options); } function MakeTreeDiffers(rootDirs) { let treeDiffers = rootDirs.map((rootDir) => new TreeDiffer('MergeTrees', rootDir)); treeDiffers.diffTrees = () => { return treeDiffers.map(tree => tree.diffTree()); }; return treeDiffers; } function read(path) { return fs.readFileSync(path, "utf-8"); } it('should copy the file from the right-most inputTree with overwrite=true', () => { let testDir: any = { 'tree1': {'foo.js': mockfs.file({content: 'tree1/foo.js content', mtime: new Date(1000)})}, 'tree2': {'foo.js': mockfs.file({content: 'tree2/foo.js content', mtime: new Date(1000)})}, 'tree3': {'foo.js': mockfs.file({content: 'tree3/foo.js content', mtime: new Date(1000)})} }; mockfs(testDir); let treeDiffer = MakeTreeDiffers(['tree1', 'tree2', 'tree3']); let treeMerger = mergeTrees(['tree1', 'tree2', 'tree3'], 'dest', {overwrite: true}); treeMerger.rebuild(treeDiffer.diffTrees()); expect(read('dest/foo.js')).toBe('tree3/foo.js content'); delete testDir.tree2['foo.js']; delete testDir.tree3['foo.js']; mockfs(testDir); treeMerger.rebuild(treeDiffer.diffTrees()); expect(read('dest/foo.js')).toBe('tree1/foo.js content'); testDir.tree2['foo.js'] = mockfs.file({content: 'tree2/foo.js content', mtime: new Date(1000)}); mockfs(testDir); treeMerger.rebuild(treeDiffer.diffTrees()); expect(read('dest/foo.js')).toBe('tree2/foo.js content'); }); it('should throw if duplicates are found during the initial build', () => { let testDir: any = { 'tree1': {'foo.js': mockfs.file({content: 'tree1/foo.js content', mtime: new Date(1000)})}, 'tree2': {'foo.js': mockfs.file({content: 'tree2/foo.js content', mtime: new Date(1000)})}, 'tree3': {'foo.js': mockfs.file({content: 'tree3/foo.js content', mtime: new Date(1000)})} }; mockfs(testDir); let treeDiffer = MakeTreeDiffers(['tree1', 'tree2', 'tree3']); let treeMerger = mergeTrees(['tree1', 'tree2', 'tree3'], 'dest', {}); expect(() => treeMerger.rebuild(treeDiffer.diffTrees())) .toThrowError( 'Duplicate path found while merging trees. Path: "foo.js".\n' + 'Either remove the duplicate or enable the "overwrite" option for this merge.'); testDir = { 'tree1': {'foo.js': mockfs.file({content: 'tree1/foo.js content', mtime: new Date(1000)})}, 'tree2': {}, 'tree3': {} }; mockfs(testDir); }); it('should throw if duplicates are found during rebuild', () => { let testDir = { 'tree1': {'foo.js': mockfs.file({content: 'tree1/foo.js content', mtime: new Date(1000)})}, 'tree2': {}, 'tree3': {} }; mockfs(testDir); let treeDiffer = MakeTreeDiffers(['tree1', 'tree2', 'tree3']); let treeMerger = mergeTrees(['tree1', 'tree2', 'tree3'], 'dest', {}); expect(() => treeMerger.rebuild(treeDiffer.diffTrees())).not.toThrow(); testDir.tree2['foo.js'] = mockfs.file({content: 'tree2/foo.js content', mtime: new Date(1000)}); mockfs(testDir); expect(() => treeMerger.rebuild(treeDiffer.diffTrees())) .toThrowError( 'Duplicate path found while merging trees. Path: "foo.js".\n' + 'Either remove the duplicate or enable the "overwrite" option for this merge.'); }); }); */
tools/broccoli/broccoli-merge-trees.spec.ts
0
https://github.com/angular/angular/commit/a593ffa6f3d7cb6062e9e1957aae1382bfcb666f
[ 0.00017998319526668638, 0.0001768130750861019, 0.00017155404202640057, 0.00017819562344811857, 0.00000284732345789962 ]
{ "id": 1, "code_window": [ " it('should merge host bindings from the annotation and fields.', () async {\n", " var model = await _testCreateModel('directives_files/components.dart');\n", " expect(model.types['ComponentWithHostBindings'].hostProperties)\n", " .toEqual({'a': 'a', 'b': 'b', 'renamed': 'c'});\n", " });\n", "\n", " it('should merge host listeners from the annotation and fields.', () async {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " .toEqual({'a': 'a', 'b': 'b', 'renamed': 'c', 'd': 'd', 'get-renamed': 'e'});\n" ], "file_path": "modules_dart/transform/test/transform/directive_processor/all_tests.dart", "type": "replace", "edit_start_line_idx": 554 }
library angular2.transform.common.type_metadata_reader; import 'dart:async'; import 'package:analyzer/analyzer.dart'; import 'package:angular2/src/compiler/directive_metadata.dart'; import 'package:angular2/src/compiler/template_compiler.dart'; import 'package:angular2/src/core/change_detection/change_detection.dart'; import 'package:angular2/src/core/linker/interfaces.dart' show LifecycleHooks; import 'package:angular2/src/core/metadata/view.dart' show ViewEncapsulation; import 'package:angular2/src/transform/common/annotation_matcher.dart'; import 'package:angular2/src/transform/common/interface_matcher.dart'; import 'package:angular2/src/transform/common/logging.dart'; import 'package:barback/barback.dart' show AssetId; import 'naive_eval.dart'; import 'url_resolver.dart'; class TypeMetadataReader { final _DirectiveMetadataVisitor _directiveVisitor; final _PipeMetadataVisitor _pipeVisitor; final TemplateCompiler _templateCompiler; TypeMetadataReader._( this._directiveVisitor, this._pipeVisitor, this._templateCompiler); /// Accepts an [AnnotationMatcher] which tests that an [Annotation] /// is a [Directive], [Component], or [View]. factory TypeMetadataReader(AnnotationMatcher annotationMatcher, InterfaceMatcher interfaceMatcher, TemplateCompiler templateCompiler) { var lifecycleVisitor = new _LifecycleHookVisitor(interfaceMatcher); var directiveVisitor = new _DirectiveMetadataVisitor(annotationMatcher, lifecycleVisitor); var pipeVisitor = new _PipeMetadataVisitor(annotationMatcher); return new TypeMetadataReader._( directiveVisitor, pipeVisitor, templateCompiler); } /// Reads *un-normalized* [CompileDirectiveMetadata]/[CompilePipeMetadata] from the /// [ClassDeclaration] `node`. /// /// `node` is expected to be a class which may have a [Directive] or [Component] /// annotation. If `node` does not have one of these annotations, this function /// returns `null`. /// /// `assetId` is the [AssetId] from which `node` was read, unless `node` was /// read from a part file, in which case `assetId` should be the [AssetId] of /// the parent file. Future<dynamic> readTypeMetadata(ClassDeclaration node, AssetId assetId) { _directiveVisitor.reset(assetId); _pipeVisitor.reset(assetId); node.accept(_directiveVisitor); node.accept(_pipeVisitor); if (_directiveVisitor.hasMetadata) { final metadata = _directiveVisitor.createMetadata(); return _templateCompiler.normalizeDirectiveMetadata(metadata); } else if (_pipeVisitor.hasMetadata) { return new Future.value(_pipeVisitor.createMetadata()); } else { return new Future.value(null); } } } /// Evaluates the [Map] represented by `expression` and adds all `key`, /// `value` pairs to `map`. If `expression` does not evaluate to a [Map], /// throws a descriptive [FormatException]. void _populateMap(Expression expression, Map map, String propertyName) { var evaluated = naiveEval(expression); if (evaluated is! Map) { throw new FormatException( 'Angular 2 expects a Map but could not understand the value for ' '$propertyName.', '$expression' /* source */); } evaluated.forEach((key, value) { if (value != null) { map[key] = '$value'; } }); } /// Evaluates the [List] represented by `expression` and adds all values, /// to `list`. If `expression` does not evaluate to a [List], throws a /// descriptive [FormatException]. void _populateList( Expression expression, List<String> list, String propertyName) { var evaluated = naiveEval(expression); if (evaluated is! List) { throw new FormatException( 'Angular 2 expects a List but could not understand the value for ' '$propertyName.', '$expression' /* source */); } list.addAll(evaluated.map((e) => e.toString())); } /// Evaluates `node` and expects that the result will be a string. If not, /// throws a [FormatException]. String _expressionToString(Expression node, String nodeDescription) { var value = naiveEval(node); if (value is! String) { throw new FormatException( 'Angular 2 could not understand the value ' 'in $nodeDescription.', '$node' /* source */); } return value; } /// Evaluates `node` and expects that the result will be a bool. If not, /// throws a [FormatException]. bool _expressionToBool(Expression node, String nodeDescription) { var value = naiveEval(node); if (value is! bool) { throw new FormatException( 'Angular 2 could not understand the value ' 'in $nodeDescription.', '$node' /* source */); } return value; } /// Visitor responsible for processing a [Directive] annotated /// [ClassDeclaration] and creating a [CompileDirectiveMetadata] object. class _DirectiveMetadataVisitor extends Object with RecursiveAstVisitor<Object> { /// Tests [Annotation]s to determine if they deifne a [Directive], /// [Component], [View], or none of these. final AnnotationMatcher _annotationMatcher; final _LifecycleHookVisitor _lifecycleVisitor; /// The [AssetId] we are currently processing. AssetId _assetId; _DirectiveMetadataVisitor(this._annotationMatcher, this._lifecycleVisitor) { reset(null); } /// Whether the visitor has found a [Component] or [Directive] annotation /// since the last call to `reset`. bool _hasMetadata = false; // Annotation fields CompileTypeMetadata _type; bool _isComponent; String _selector; String _exportAs; ChangeDetectionStrategy _changeDetection; List<String> _inputs; List<String> _outputs; Map<String, String> _host; List<LifecycleHooks> _lifecycleHooks; CompileTemplateMetadata _cmpTemplate; CompileTemplateMetadata _viewTemplate; void reset(AssetId assetId) { _lifecycleVisitor.reset(assetId); _assetId = assetId; _type = null; _isComponent = false; _hasMetadata = false; _selector = ''; _exportAs = null; _changeDetection = ChangeDetectionStrategy.Default; _inputs = <String>[]; _outputs = <String>[]; _host = <String, String>{}; _lifecycleHooks = null; _cmpTemplate = null; _viewTemplate = null; } bool get hasMetadata => _hasMetadata; get _template => _viewTemplate != null ? _viewTemplate : _cmpTemplate; CompileDirectiveMetadata createMetadata() { return CompileDirectiveMetadata.create( type: _type, isComponent: _isComponent, dynamicLoadable: true, // NOTE(kegluneq): For future optimization. selector: _selector, exportAs: _exportAs, changeDetection: _changeDetection, inputs: _inputs, outputs: _outputs, host: _host, lifecycleHooks: _lifecycleHooks, template: _template); } /// Ensures that we do not specify View values on an `@Component` annotation /// when there is a @View annotation present. void _validateTemplates() { if (_cmpTemplate != null && _viewTemplate != null) { var name = '(Unknown)'; if (_type != null && _type.name != null && _type.name.isNotEmpty) { name = _type.name; } log.warning( 'Cannot specify view parameters on @Component when a @View ' 'is present. Component name: ${name}', asset: _assetId); } } @override Object visitAnnotation(Annotation node) { var isComponent = _annotationMatcher.isComponent(node, _assetId); var isDirective = _annotationMatcher.isDirective(node, _assetId); if (isDirective) { if (_hasMetadata) { throw new FormatException( 'Only one Directive is allowed per class. ' 'Found unexpected "$node".', '$node' /* source */); } _isComponent = isComponent; _hasMetadata = true; if (isComponent) { _cmpTemplate = new _CompileTemplateMetadataVisitor().visitAnnotation(node); _validateTemplates(); } super.visitAnnotation(node); } else if (_annotationMatcher.isView(node, _assetId)) { if (_viewTemplate != null) { // TODO(kegluneq): Support multiple views on a single class. throw new FormatException( 'Only one View is allowed per class. ' 'Found unexpected "$node".', '$node' /* source */); } _viewTemplate = new _CompileTemplateMetadataVisitor().visitAnnotation(node); _validateTemplates(); } // Annotation we do not recognize - no need to visit. return null; } @override Object visitFieldDeclaration(FieldDeclaration node) { for (var variable in node.fields.variables) { for (var meta in node.metadata) { if (_isAnnotation(meta, 'Output')) { _addPropertyToType(_outputs, variable.name.toString(), meta); } if (_isAnnotation(meta, 'Input')) { _addPropertyToType(_inputs, variable.name.toString(), meta); } if (_isAnnotation(meta, 'HostBinding')) { final renamed = _getRenamedValue(meta); if (renamed != null) { _host['[${renamed}]'] = '${variable.name}'; } else { _host['[${variable.name}]'] = '${variable.name}'; } } } } return null; } @override Object visitMethodDeclaration(MethodDeclaration node) { for (var meta in node.metadata) { if (_isAnnotation(meta, 'Output') && node.isGetter) { _addPropertyToType(_outputs, node.name.toString(), meta); } if (_isAnnotation(meta, 'Input') && node.isSetter) { _addPropertyToType(_inputs, node.name.toString(), meta); } if (_isAnnotation(meta, 'HostListener')) { if (meta.arguments.arguments.length == 0 || meta.arguments.arguments.length > 2) { throw new ArgumentError( 'Incorrect value passed to HostListener. Expected 1 or 2.'); } final eventName = _getHostListenerEventName(meta); final params = _getHostListenerParams(meta); _host['(${eventName})'] = '${node.name}($params)'; } } return null; } void _addPropertyToType(List type, String name, Annotation meta) { final renamed = _getRenamedValue(meta); if (renamed != null) { type.add('${name}: ${renamed}'); } else { type.add('${name}'); } } //TODO Use AnnotationMatcher instead of string matching bool _isAnnotation(Annotation node, String annotationName) { var id = node.name; final name = id is PrefixedIdentifier ? '${id.identifier}' : '$id'; return name == annotationName; } String _getRenamedValue(Annotation node) { if (node.arguments.arguments.length == 1) { final renamed = naiveEval(node.arguments.arguments.single); if (renamed is! String) { throw new ArgumentError( 'Incorrect value. Expected a String, but got "${renamed}".'); } return renamed; } else { return null; } } String _getHostListenerEventName(Annotation node) { final name = naiveEval(node.arguments.arguments.first); if (name is! String) { throw new ArgumentError( 'Incorrect event name. Expected a String, but got "${name}".'); } return name; } String _getHostListenerParams(Annotation node) { if (node.arguments.arguments.length == 2) { return naiveEval(node.arguments.arguments[1]).join(','); } else { return ""; } } @override Object visitClassDeclaration(ClassDeclaration node) { node.metadata.accept(this); if (this._hasMetadata) { _type = new CompileTypeMetadata( moduleUrl: toAssetUri(_assetId), name: node.name.toString(), runtime: null // Intentionally `null`, cannot be provided here. ); _lifecycleHooks = node.implementsClause != null ? node.implementsClause.accept(_lifecycleVisitor) : const []; node.members.accept(this); } return null; } @override Object visitNamedExpression(NamedExpression node) { // TODO(kegluneq): Remove this limitation. if (node.name is! Label || node.name.label is! SimpleIdentifier) { throw new FormatException( 'Angular 2 currently only supports simple identifiers in directives.', '$node' /* source */); } var keyString = '${node.name.label}'; switch (keyString) { case 'selector': _populateSelector(node.expression); break; case 'inputs': _populateProperties(node.expression); break; case 'properties': _populateProperties(node.expression); break; case 'host': _populateHost(node.expression); break; case 'exportAs': _populateExportAs(node.expression); break; case 'changeDetection': _populateChangeDetection(node.expression); break; case 'outputs': _populateEvents(node.expression); break; case 'events': _populateEvents(node.expression); break; } return null; } void _populateSelector(Expression selectorValue) { _checkMeta(); _selector = _expressionToString(selectorValue, 'Directive#selector'); } void _checkMeta() { if (!_hasMetadata) { throw new ArgumentError('Incorrect value passed to readTypeMetadata. ' 'Expected type is ClassDeclaration'); } } void _populateProperties(Expression inputsValue) { _checkMeta(); _populateList(inputsValue, _inputs, 'Directive#inputs'); } void _populateHost(Expression hostValue) { _checkMeta(); _populateMap(hostValue, _host, 'Directive#host'); } void _populateExportAs(Expression exportAsValue) { _checkMeta(); _exportAs = _expressionToString(exportAsValue, 'Directive#exportAs'); } void _populateEvents(Expression outputsValue) { _checkMeta(); _populateList(outputsValue, _outputs, 'Directive#outputs'); } void _populateChangeDetection(Expression value) { _checkMeta(); _changeDetection = _changeDetectionStrategies[value.toSource()]; } static final Map<String, ChangeDetectionStrategy> _changeDetectionStrategies = new Map.fromIterable(ChangeDetectionStrategy.values, key: (v) => v.toString()); } /// Visitor responsible for parsing an [ImplementsClause] and returning a /// [List<LifecycleHooks>] that the [Directive] subscribes to. class _LifecycleHookVisitor extends SimpleAstVisitor<List<LifecycleHooks>> { /// Tests [Identifier]s of implemented interfaces to determine if they /// correspond to [LifecycleHooks] values. final InterfaceMatcher _ifaceMatcher; /// The [AssetId] we are currently processing. AssetId _assetId; _LifecycleHookVisitor(this._ifaceMatcher); void reset(AssetId assetId) { _assetId = assetId; } @override List<LifecycleHooks> visitImplementsClause(ImplementsClause node) { if (node == null || node.interfaces == null) return const []; return node.interfaces.map((TypeName ifaceTypeName) { var id = ifaceTypeName.name; if (_ifaceMatcher.isAfterContentChecked(id, _assetId)) { return LifecycleHooks.AfterContentChecked; } else if (_ifaceMatcher.isAfterContentInit(id, _assetId)) { return LifecycleHooks.AfterContentInit; } else if (_ifaceMatcher.isAfterViewChecked(id, _assetId)) { return LifecycleHooks.AfterViewChecked; } else if (_ifaceMatcher.isAfterViewInit(id, _assetId)) { return LifecycleHooks.AfterViewInit; } else if (_ifaceMatcher.isDoCheck(id, _assetId)) { return LifecycleHooks.DoCheck; } else if (_ifaceMatcher.isOnChange(id, _assetId)) { return LifecycleHooks.OnChanges; } else if (_ifaceMatcher.isOnDestroy(id, _assetId)) { return LifecycleHooks.OnDestroy; } else if (_ifaceMatcher.isOnInit(id, _assetId)) { return LifecycleHooks.OnInit; } return null; }).where((e) => e != null).toList(growable: false); } } /// Visitor responsible for parsing a @View [Annotation] and producing a /// [CompileTemplateMetadata]. class _CompileTemplateMetadataVisitor extends RecursiveAstVisitor<CompileTemplateMetadata> { ViewEncapsulation _encapsulation; String _template; String _templateUrl; List<String> _styles; List<String> _styleUrls; @override CompileTemplateMetadata visitAnnotation(Annotation node) { super.visitAnnotation(node); if (_encapsulation == null && _template == null && _templateUrl == null && _styles == null && _styleUrls == null) { return null; } return new CompileTemplateMetadata( encapsulation: _encapsulation, template: _template, templateUrl: _templateUrl, styles: _styles, styleUrls: _styleUrls); } @override CompileTemplateMetadata visitNamedExpression(NamedExpression node) { // TODO(kegluneq): Remove this limitation. if (node.name is! Label || node.name.label is! SimpleIdentifier) { throw new FormatException( 'Angular 2 currently only supports simple identifiers in directives.', '$node' /* source */); } var keyString = '${node.name.label}'; switch (keyString) { case 'encapsulation': _populateEncapsulation(node.expression); break; case 'template': _populateTemplate(node.expression); break; case 'templateUrl': _populateTemplateUrl(node.expression); break; case 'styles': _populateStyles(node.expression); break; case 'styleUrls': _populateStyleUrls(node.expression); break; } return null; } void _populateTemplate(Expression value) { _template = _expressionToString(value, 'View#template'); } void _populateTemplateUrl(Expression value) { _templateUrl = _expressionToString(value, 'View#templateUrl'); } void _populateStyles(Expression value) { _styles = <String>[]; _populateList(value, _styles, 'View#styles'); } void _populateStyleUrls(Expression value) { _styleUrls = <String>[]; _populateList(value, _styleUrls, 'View#styleUrls'); } void _populateEncapsulation(Expression value) { _encapsulation = _viewEncapsulationMap[value.toSource()]; } static final _viewEncapsulationMap = new Map.fromIterable(ViewEncapsulation.values, key: (v) => v.toString()); } /// Visitor responsible for processing a [Pipe] annotated /// [ClassDeclaration] and creating a [CompilePipeMetadata] object. class _PipeMetadataVisitor extends Object with RecursiveAstVisitor<Object> { /// Tests [Annotation]s to determine if they deifne a [Directive], /// [Component], [View], or none of these. final AnnotationMatcher _annotationMatcher; /// The [AssetId] we are currently processing. AssetId _assetId; _PipeMetadataVisitor(this._annotationMatcher) { reset(null); } /// Whether the visitor has found a [Pipe] annotation /// since the last call to `reset`. bool _hasMetadata = false; // Annotation fields CompileTypeMetadata _type; String _name; bool _pure; void reset(AssetId assetId) { _assetId = assetId; _hasMetadata = false; _type = null; _name = null; _pure = null; } bool get hasMetadata => _hasMetadata; CompilePipeMetadata createMetadata() { return new CompilePipeMetadata(type: _type, name: _name, pure: _pure); } @override Object visitAnnotation(Annotation node) { var isPipe = _annotationMatcher.isPipe(node, _assetId); if (isPipe) { if (_hasMetadata) { throw new FormatException( 'Only one Pipe is allowed per class. ' 'Found unexpected "$node".', '$node' /* source */); } _hasMetadata = true; super.visitAnnotation(node); } // Annotation we do not recognize - no need to visit. return null; } @override Object visitClassDeclaration(ClassDeclaration node) { node.metadata.accept(this); if (this._hasMetadata) { _type = new CompileTypeMetadata( moduleUrl: toAssetUri(_assetId), name: node.name.toString(), runtime: null // Intentionally `null`, cannot be provided here. ); node.members.accept(this); } return null; } @override Object visitNamedExpression(NamedExpression node) { // TODO(kegluneq): Remove this limitation. if (node.name is! Label || node.name.label is! SimpleIdentifier) { throw new FormatException( 'Angular 2 currently only supports simple identifiers in pipes.', '$node' /* source */); } var keyString = '${node.name.label}'; switch (keyString) { case 'name': _popuplateName(node.expression); break; case 'pure': _populatePure(node.expression); break; } return null; } void _checkMeta() { if (!_hasMetadata) { throw new ArgumentError('Incorrect value passed to readTypeMetadata. ' 'Expected type is ClassDeclaration'); } } void _popuplateName(Expression nameValue) { _checkMeta(); _name = _expressionToString(nameValue, 'Pipe#name'); } void _populatePure(Expression pureValue) { _checkMeta(); _pure = _expressionToBool(pureValue, 'Pipe#pure'); } }
modules_dart/transform/lib/src/transform/common/type_metadata_reader.dart
1
https://github.com/angular/angular/commit/a593ffa6f3d7cb6062e9e1957aae1382bfcb666f
[ 0.0017158042173832655, 0.00023618624254595488, 0.00016072855214588344, 0.00017087391461245716, 0.00022231764160096645 ]
{ "id": 1, "code_window": [ " it('should merge host bindings from the annotation and fields.', () async {\n", " var model = await _testCreateModel('directives_files/components.dart');\n", " expect(model.types['ComponentWithHostBindings'].hostProperties)\n", " .toEqual({'a': 'a', 'b': 'b', 'renamed': 'c'});\n", " });\n", "\n", " it('should merge host listeners from the annotation and fields.', () async {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " .toEqual({'a': 'a', 'b': 'b', 'renamed': 'c', 'd': 'd', 'get-renamed': 'e'});\n" ], "file_path": "modules_dart/transform/test/transform/directive_processor/all_tests.dart", "type": "replace", "edit_start_line_idx": 554 }
import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {bootstrap} from 'angular2/bootstrap'; import {Component, View} from 'angular2/core'; @Component({ selector: 'error-app', }) @View({ template: ` <button class="errorButton" (click)="createError()">create error</button>` }) export class ErrorComponent { createError(): void { throw new BaseException('Sourcemap test'); } } export function main() { bootstrap(ErrorComponent); }
modules/playground/src/sourcemap/index.ts
0
https://github.com/angular/angular/commit/a593ffa6f3d7cb6062e9e1957aae1382bfcb666f
[ 0.000173849388374947, 0.00017124552687164396, 0.0001686416653683409, 0.00017124552687164396, 0.000002603861503303051 ]
{ "id": 1, "code_window": [ " it('should merge host bindings from the annotation and fields.', () async {\n", " var model = await _testCreateModel('directives_files/components.dart');\n", " expect(model.types['ComponentWithHostBindings'].hostProperties)\n", " .toEqual({'a': 'a', 'b': 'b', 'renamed': 'c'});\n", " });\n", "\n", " it('should merge host listeners from the annotation and fields.', () async {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " .toEqual({'a': 'a', 'b': 'b', 'renamed': 'c', 'd': 'd', 'get-renamed': 'e'});\n" ], "file_path": "modules_dart/transform/test/transform/directive_processor/all_tests.dart", "type": "replace", "edit_start_line_idx": 554 }
library benchpress.test.firefox_extension.spec; main() {}
modules/benchpress/test/firefox_extension/spec.dart
0
https://github.com/angular/angular/commit/a593ffa6f3d7cb6062e9e1957aae1382bfcb666f
[ 0.00017024566477630287, 0.00017024566477630287, 0.00017024566477630287, 0.00017024566477630287, 0 ]
{ "id": 1, "code_window": [ " it('should merge host bindings from the annotation and fields.', () async {\n", " var model = await _testCreateModel('directives_files/components.dart');\n", " expect(model.types['ComponentWithHostBindings'].hostProperties)\n", " .toEqual({'a': 'a', 'b': 'b', 'renamed': 'c'});\n", " });\n", "\n", " it('should merge host listeners from the annotation and fields.', () async {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " .toEqual({'a': 'a', 'b': 'b', 'renamed': 'c', 'd': 'd', 'get-renamed': 'e'});\n" ], "file_path": "modules_dart/transform/test/transform/directive_processor/all_tests.dart", "type": "replace", "edit_start_line_idx": 554 }
'use strict'; describe('router', function () { var elt, $compile, $rootScope, $router, $compileProvider; beforeEach(function () { module('ng'); module('ngComponentRouter'); module(function($provide) { $provide.value('$routerRootComponent', 'app'); }); module(function (_$compileProvider_) { $compileProvider = _$compileProvider_; }); inject(function (_$compile_, _$rootScope_, _$router_) { $compile = _$compile_; $rootScope = _$rootScope_; $router = _$router_; }); }); it('should work with a provided root component', inject(function($location) { registerComponent('homeCmp', { template: 'Home' }); registerComponent('app', { template: '<div ng-outlet></div>', $routeConfig: [ { path: '/', component: 'homeCmp' } ] }); compile('<app></app>'); $location.path('/'); $rootScope.$digest(); expect(elt.text()).toBe('Home'); })); function registerComponent(name, options) { var controller = options.controller || function () {}; ['$onActivate', '$onDeactivate', '$onReuse', '$canReuse', '$canDeactivate'].forEach(function (hookName) { if (options[hookName]) { controller.prototype[hookName] = options[hookName]; } }); function factory() { return { template: options.template || '', controllerAs: name, controller: controller }; } if (options.$canActivate) { factory.$canActivate = options.$canActivate; } if (options.$routeConfig) { factory.$routeConfig = options.$routeConfig; } $compileProvider.directive(name, factory); } function compile(template) { elt = $compile('<div>' + template + '</div>')($rootScope); $rootScope.$digest(); return elt; } });
modules/angular1_router/test/integration/router_spec.js
0
https://github.com/angular/angular/commit/a593ffa6f3d7cb6062e9e1957aae1382bfcb666f
[ 0.00017296081932727247, 0.0001682274742051959, 0.00016429070092272013, 0.00016825750935822725, 0.00000266810275206808 ]
{ "id": 2, "code_window": [ " host: {'[a]': 'a'})\n", "class ComponentWithHostBindings {\n", " @HostBinding() Object b;\n", " @HostBinding('renamed') Object c;\n", "}\n", "\n", "@Component(\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", " Object _d;\n", " @HostBinding() Object get d => _d;\n", "\n", " Object _e;\n", " @HostBinding('get-renamed') Object get e => _e;\n" ], "file_path": "modules_dart/transform/test/transform/directive_processor/directives_files/components.dart", "type": "add", "edit_start_line_idx": 69 }
library angular2.test.transform.directive_processor.all_tests; import 'dart:async'; import 'package:barback/barback.dart'; import 'package:dart_style/dart_style.dart'; import 'package:guinness/guinness.dart'; import 'package:angular2/src/core/change_detection/change_detection.dart'; import 'package:angular2/src/platform/server/html_adapter.dart'; import 'package:angular2/src/core/linker/interfaces.dart' show LifecycleHooks; import 'package:angular2/src/transform/common/annotation_matcher.dart'; import 'package:angular2/src/transform/common/asset_reader.dart'; import 'package:angular2/src/transform/common/code/ng_deps_code.dart'; import 'package:angular2/src/transform/common/model/ng_deps_model.pb.dart'; import 'package:angular2/src/transform/common/model/reflection_info_model.pb.dart'; import 'package:angular2/src/transform/common/ng_meta.dart'; import 'package:angular2/src/transform/common/zone.dart' as zone; import 'package:angular2/src/transform/directive_processor/rewriter.dart'; import '../common/read_file.dart'; import '../common/recording_logger.dart'; var formatter = new DartFormatter(); main() { Html5LibDomAdapter.makeCurrent(); allTests(); } Expect _expectSelector(ReflectionInfoModel model) { expect(model.annotations.isNotEmpty).toBeTrue(); var componentAnnotation = model.annotations .firstWhere((e) => e.name == 'Component', orElse: () => null); expect(componentAnnotation).toBeNotNull(); var selectorArg = componentAnnotation.namedParameters .firstWhere((e) => e.name == 'selector', orElse: () => null); expect(selectorArg).toBeNotNull(); return expect(selectorArg.value); } void allTests() { it('should preserve parameter annotations.', () async { var model = (await _testCreateModel('parameter_metadata/soup.dart')).ngDeps; expect(model.reflectables.length).toBe(1); var reflectable = model.reflectables.first; expect(reflectable.parameters.length).toBe(2); expect(reflectable.parameters.first.typeName).toEqual('String'); expect(reflectable.parameters.first.metadata.length).toBe(1); expect(reflectable.parameters.first.metadata.first).toContain('Tasty'); expect(reflectable.parameters.first.paramName).toEqual('description'); var typeName = reflectable.parameters[1].typeName; expect(typeName == null || typeName.isEmpty).toBeTrue(); var secondParam = reflectable.parameters[1]; expect(secondParam.metadata.first).toContain('Inject(Salt)'); expect(secondParam.paramName).toEqual('salt'); }); describe('part support', () { var modelFuture = _testCreateModel('part_files/main.dart') .then((ngMeta) => ngMeta != null ? ngMeta.ngDeps : null); it('should include directives from the part.', () async { var model = await modelFuture; expect(model.reflectables.length).toBe(2); }); it('should list part contributions first.', () async { var model = await modelFuture; expect(model.reflectables.first.name).toEqual('PartComponent'); _expectSelector(model.reflectables.first).toEqual("'[part]'"); }); it('should list main contributions second.', () async { var model = await modelFuture; expect(model.reflectables[1].name).toEqual('MainComponent'); _expectSelector(model.reflectables[1]).toEqual("'[main]'"); }); it('should handle multiple `part` directives.', () async { var model = (await _testCreateModel('multiple_part_files/main.dart')).ngDeps; expect(model.reflectables.length).toEqual(3); _expectSelector(model.reflectables.first).toEqual("'[part1]'"); _expectSelector(model.reflectables[1]).toEqual("'[part2]'"); _expectSelector(model.reflectables[2]).toEqual("'[main]'"); }); it('should not generate anything for `part` files.', () async { expect(await _testCreateModel('part_files/part.dart')).toBeNull(); }); }); describe('custom annotations', () { it('should be recognized from package: imports', () async { var ngMeta = await _testCreateModel('custom_metadata/package_soup.dart', customDescriptors: [ const ClassDescriptor('Soup', 'package:soup/soup.dart', superClass: 'Component') ]); var model = ngMeta.ngDeps; expect(model.reflectables.length).toEqual(1); expect(model.reflectables.first.name).toEqual('PackageSoup'); }); it('should be recognized from relative imports', () async { var ngMeta = await _testCreateModel('custom_metadata/relative_soup.dart', assetId: new AssetId('soup', 'lib/relative_soup.dart'), customDescriptors: [ const ClassDescriptor('Soup', 'package:soup/annotations/soup.dart', superClass: 'Component') ]); var model = ngMeta.ngDeps; expect(model.reflectables.length).toEqual(1); expect(model.reflectables.first.name).toEqual('RelativeSoup'); }); it('should ignore annotations that are not imported', () async { var ngMeta = await _testCreateModel('custom_metadata/bad_soup.dart', customDescriptors: [ const ClassDescriptor('Soup', 'package:soup/soup.dart', superClass: 'Component') ]); expect(ngMeta.ngDeps == null || ngMeta.ngDeps.reflectables.isEmpty) .toBeTrue(); }); }); describe('interfaces', () { it('should include implemented types', () async { var model = (await _testCreateModel('interfaces_files/soup.dart')).ngDeps; expect(model.reflectables.first.interfaces).toBeNotNull(); expect(model.reflectables.first.interfaces.isNotEmpty).toBeTrue(); expect(model.reflectables.first.interfaces.contains('OnChanges')) .toBeTrue(); expect(model.reflectables.first.interfaces.contains('AnotherInterface')) .toBeTrue(); }); it('should not include transitively implemented types', () async { var model = (await _testCreateModel('interface_chain_files/soup.dart')).ngDeps; expect(model.reflectables.first.interfaces).toBeNotNull(); expect(model.reflectables.first.interfaces.isNotEmpty).toBeTrue(); expect(model.reflectables.first.interfaces.contains('PrimaryInterface')) .toBeTrue(); expect(model.reflectables.first.interfaces.contains('SecondaryInterface')) .toBeFalse(); expect(model.reflectables.first.interfaces.contains('TernaryInterface')) .toBeFalse(); }); it('should not include superclasses.', () async { var model = (await _testCreateModel('superclass_files/soup.dart')).ngDeps; var interfaces = model.reflectables.first.interfaces; expect(interfaces == null || interfaces.isEmpty).toBeTrue(); }); it('should populate multiple `lifecycle` values when necessary.', () async { var model = (await _testCreateModel( 'multiple_interface_lifecycle_files/soup.dart')).ngDeps; expect(model.reflectables.first.interfaces).toBeNotNull(); expect(model.reflectables.first.interfaces.isNotEmpty).toBeTrue(); expect(model.reflectables.first.interfaces.contains('OnChanges')) .toBeTrue(); expect(model.reflectables.first.interfaces.contains('OnDestroy')) .toBeTrue(); expect(model.reflectables.first.interfaces.contains('OnInit')).toBeTrue(); }); it('should not populate `lifecycle` when lifecycle superclass is present.', () async { var model = (await _testCreateModel('superclass_lifecycle_files/soup.dart')) .ngDeps; var interfaces = model.reflectables.first.interfaces; expect(interfaces == null || interfaces.isEmpty).toBeTrue(); }); it('should populate `lifecycle` with prefix when necessary.', () async { var model = (await _testCreateModel( 'prefixed_interface_lifecycle_files/soup.dart')).ngDeps; expect(model.reflectables.first.interfaces).toBeNotNull(); expect(model.reflectables.first.interfaces.isNotEmpty).toBeTrue(); expect(model.reflectables.first.interfaces .firstWhere((i) => i.contains('OnChanges'), orElse: () => null)) .toBeNotNull(); }); }); describe('property metadata', () { it('should be recorded on fields', () async { var model = (await _testCreateModel('prop_metadata_files/fields.dart')).ngDeps; expect(model.reflectables.first.propertyMetadata).toBeNotNull(); expect(model.reflectables.first.propertyMetadata.isNotEmpty).toBeTrue(); expect(model.reflectables.first.propertyMetadata.first.name) .toEqual('field'); expect(model.reflectables.first.propertyMetadata.first.annotations .firstWhere((a) => a.name == 'FieldDecorator', orElse: () => null)).toBeNotNull(); }); it('should be recorded on getters', () async { var model = (await _testCreateModel('prop_metadata_files/getters.dart')).ngDeps; expect(model.reflectables.first.propertyMetadata).toBeNotNull(); expect(model.reflectables.first.propertyMetadata.isNotEmpty).toBeTrue(); expect(model.reflectables.first.propertyMetadata.first.name) .toEqual('getVal'); var getDecoratorAnnotation = model .reflectables.first.propertyMetadata.first.annotations .firstWhere((a) => a.name == 'GetDecorator', orElse: () => null); expect(getDecoratorAnnotation).toBeNotNull(); expect(getDecoratorAnnotation.isConstObject).toBeFalse(); }); it('should gracefully handle const instances of annotations', () async { // Regression test for i/4481 var model = (await _testCreateModel('prop_metadata_files/override.dart')).ngDeps; expect(model.reflectables.first.propertyMetadata).toBeNotNull(); expect(model.reflectables.first.propertyMetadata.isNotEmpty).toBeTrue(); expect(model.reflectables.first.propertyMetadata.first.name) .toEqual('getVal'); var overrideAnnotation = model .reflectables.first.propertyMetadata.first.annotations .firstWhere((a) => a.name == 'override', orElse: () => null); expect(overrideAnnotation).toBeNotNull(); expect(overrideAnnotation.isConstObject).toBeTrue(); var buf = new StringBuffer(); new NgDepsWriter(buf).writeAnnotationModel(overrideAnnotation); expect(buf.toString()).toEqual('override'); }); it('should be recorded on setters', () async { var model = (await _testCreateModel('prop_metadata_files/setters.dart')).ngDeps; expect(model.reflectables.first.propertyMetadata).toBeNotNull(); expect(model.reflectables.first.propertyMetadata.isNotEmpty).toBeTrue(); expect(model.reflectables.first.propertyMetadata.first.name) .toEqual('setVal'); expect(model.reflectables.first.propertyMetadata.first.annotations .firstWhere((a) => a.name == 'SetDecorator', orElse: () => null)) .toBeNotNull(); }); it('should be coalesced when getters and setters have the same name', () async { var model = (await _testCreateModel( 'prop_metadata_files/getters_and_setters.dart')).ngDeps; expect(model.reflectables.first.propertyMetadata).toBeNotNull(); expect(model.reflectables.first.propertyMetadata.length).toBe(1); expect(model.reflectables.first.propertyMetadata.first.name) .toEqual('myVal'); expect(model.reflectables.first.propertyMetadata.first.annotations .firstWhere((a) => a.name == 'GetDecorator', orElse: () => null)) .toBeNotNull(); expect(model.reflectables.first.propertyMetadata.first.annotations .firstWhere((a) => a.name == 'SetDecorator', orElse: () => null)) .toBeNotNull(); }); }); it('should not throw/hang on invalid urls', () async { var logger = new RecordingLogger(); await _testCreateModel('invalid_url_files/hello.dart', logger: logger); expect(logger.hasErrors).toBeTrue(); expect(logger.logs) ..toContain('ERROR: ERROR: Invalid argument (url): ' '"Could not read asset at uri asset:/bad/absolute/url.html"'); }); it('should find and register static functions.', () async { var model = (await _testCreateModel('static_function_files/hello.dart')).ngDeps; var functionReflectable = model.reflectables.firstWhere((i) => i.isFunction, orElse: () => null); expect(functionReflectable)..toBeNotNull(); expect(functionReflectable.name).toEqual('getMessage'); }); describe('NgMeta', () { var fakeReader; beforeEach(() { fakeReader = new TestAssetReader(); }); it('should find direcive aliases patterns.', () async { var ngMeta = await _testCreateModel('directive_aliases_files/hello.dart'); expect(ngMeta.aliases).toContain('alias1'); expect(ngMeta.aliases['alias1']).toContain('HelloCmp'); expect(ngMeta.aliases).toContain('alias2'); expect(ngMeta.aliases['alias2'])..toContain('HelloCmp')..toContain('Foo'); }); it('should include hooks for implemented types (single)', () async { var ngMeta = await _testCreateModel('interfaces_files/soup.dart'); expect(ngMeta.types.isNotEmpty).toBeTrue(); expect(ngMeta.types['ChangingSoupComponent']).toBeNotNull(); expect(ngMeta.types['ChangingSoupComponent'].selector).toEqual('[soup]'); expect(ngMeta.types['ChangingSoupComponent'].lifecycleHooks) .toContain(LifecycleHooks.OnChanges); }); it('should include hooks for implemented types (many)', () async { var ngMeta = await _testCreateModel( 'multiple_interface_lifecycle_files/soup.dart'); expect(ngMeta.types.isNotEmpty).toBeTrue(); expect(ngMeta.types['MultiSoupComponent']).toBeNotNull(); expect(ngMeta.types['MultiSoupComponent'].selector).toEqual('[soup]'); expect(ngMeta.types['MultiSoupComponent'].lifecycleHooks) ..toContain(LifecycleHooks.OnChanges) ..toContain(LifecycleHooks.OnDestroy) ..toContain(LifecycleHooks.OnInit); }); it('should create type entries for Directives', () async { fakeReader ..addAsset(new AssetId('other_package', 'lib/template.html'), '') ..addAsset(new AssetId('other_package', 'lib/template.css'), ''); var ngMeta = await _testCreateModel( 'absolute_url_expression_files/hello.dart', reader: fakeReader); expect(ngMeta.types.isNotEmpty).toBeTrue(); expect(ngMeta.types['HelloCmp']).toBeNotNull(); expect(ngMeta.types['HelloCmp'].selector).toEqual('hello-app'); }); it('should populate all provided values for Components & Directives', () async { var ngMeta = await _testCreateModel('unusual_component_files/hello.dart'); expect(ngMeta.types.isNotEmpty).toBeTrue(); var component = ngMeta.types['UnusualComp']; expect(component).toBeNotNull(); expect(component.selector).toEqual('unusual-comp'); expect(component.isComponent).toBeTrue(); expect(component.exportAs).toEqual('ComponentExportAsValue'); expect(component.changeDetection) .toEqual(ChangeDetectionStrategy.CheckAlways); expect(component.inputs).toContain('aProperty'); expect(component.inputs['aProperty']).toEqual('aProperty'); expect(component.outputs).toContain('anEvent'); expect(component.outputs['anEvent']).toEqual('anEvent'); expect(component.hostAttributes).toContain('hostKey'); expect(component.hostAttributes['hostKey']).toEqual('hostValue'); var directive = ngMeta.types['UnusualDirective']; expect(directive).toBeNotNull(); expect(directive.selector).toEqual('unusual-directive'); expect(directive.isComponent).toBeFalse(); expect(directive.exportAs).toEqual('DirectiveExportAsValue'); expect(directive.inputs).toContain('aDirectiveProperty'); expect(directive.inputs['aDirectiveProperty']) .toEqual('aDirectiveProperty'); expect(directive.outputs).toContain('aDirectiveEvent'); expect(directive.outputs['aDirectiveEvent']).toEqual('aDirectiveEvent'); expect(directive.hostAttributes).toContain('directiveHostKey'); expect(directive.hostAttributes['directiveHostKey']) .toEqual('directiveHostValue'); }); it('should include hooks for implemented types (single)', () async { var ngMeta = await _testCreateModel('interfaces_files/soup.dart'); expect(ngMeta.types.isNotEmpty).toBeTrue(); expect(ngMeta.types['ChangingSoupComponent']).toBeNotNull(); expect(ngMeta.types['ChangingSoupComponent'].selector).toEqual('[soup]'); expect(ngMeta.types['ChangingSoupComponent'].lifecycleHooks) .toContain(LifecycleHooks.OnChanges); }); it('should include hooks for implemented types (many)', () async { var ngMeta = await _testCreateModel( 'multiple_interface_lifecycle_files/soup.dart'); expect(ngMeta.types.isNotEmpty).toBeTrue(); expect(ngMeta.types['MultiSoupComponent']).toBeNotNull(); expect(ngMeta.types['MultiSoupComponent'].selector).toEqual('[soup]'); expect(ngMeta.types['MultiSoupComponent'].lifecycleHooks) ..toContain(LifecycleHooks.OnChanges) ..toContain(LifecycleHooks.OnDestroy) ..toContain(LifecycleHooks.OnInit); }); it('should parse templates from View annotations', () async { fakeReader ..addAsset(new AssetId('other_package', 'lib/template.html'), '') ..addAsset(new AssetId('other_package', 'lib/template.css'), ''); var ngMeta = await _testCreateModel( 'absolute_url_expression_files/hello.dart', reader: fakeReader); expect(ngMeta.types.isNotEmpty).toBeTrue(); expect(ngMeta.types['HelloCmp']).toBeNotNull(); expect(ngMeta.types['HelloCmp'].template).toBeNotNull(); expect(ngMeta.types['HelloCmp'].template.templateUrl) .toEqual('asset:other_package/lib/template.html'); }); it('should handle prefixed annotations', () async { var model = (await _testCreateModel('prefixed_annotations_files/soup.dart')) .ngDeps; expect(model.reflectables.isEmpty).toBeFalse(); final annotations = model.reflectables.first.annotations; final viewAnnotation = annotations.firstWhere((m) => m.isView, orElse: () => null); final componentAnnotation = annotations.firstWhere((m) => m.isComponent, orElse: () => null); expect(viewAnnotation).toBeNotNull(); expect(viewAnnotation.namedParameters.first.name).toEqual('template'); expect(viewAnnotation.namedParameters.first.value).toContain('SoupView'); expect(componentAnnotation).toBeNotNull(); expect(componentAnnotation.namedParameters.first.name) .toEqual('selector'); expect(componentAnnotation.namedParameters.first.value) .toContain('[soup]'); }); }); describe('directives', () { final reflectableNamed = (NgDepsModel model, String name) { return model.reflectables .firstWhere((r) => r.name == name, orElse: () => null); }; it('should populate `directives` from @View value specified second.', () async { var model = (await _testCreateModel('directives_files/components.dart')).ngDeps; final componentFirst = reflectableNamed(model, 'ComponentFirst'); expect(componentFirst).toBeNotNull(); expect(componentFirst.directives).toBeNotNull(); expect(componentFirst.directives.length).toEqual(2); expect(componentFirst.directives.first) .toEqual(new PrefixedType()..name = 'Dep'); expect(componentFirst.directives[1]).toEqual(new PrefixedType() ..name = 'Dep' ..prefix = 'dep2'); }); it('should populate `directives` from @View value specified first.', () async { var model = (await _testCreateModel('directives_files/components.dart')).ngDeps; final viewFirst = reflectableNamed(model, 'ViewFirst'); expect(viewFirst).toBeNotNull(); expect(viewFirst.directives).toBeNotNull(); expect(viewFirst.directives.length).toEqual(2); expect(viewFirst.directives.first).toEqual(new PrefixedType() ..name = 'Dep' ..prefix = 'dep2'); expect(viewFirst.directives[1]).toEqual(new PrefixedType()..name = 'Dep'); }); it('should populate `directives` from @Component value with no @View.', () async { var model = (await _testCreateModel('directives_files/components.dart')).ngDeps; final componentOnly = reflectableNamed(model, 'ComponentOnly'); expect(componentOnly).toBeNotNull(); expect(componentOnly.directives).toBeNotNull(); expect(componentOnly.directives.length).toEqual(2); expect(componentOnly.directives.first) .toEqual(new PrefixedType()..name = 'Dep'); expect(componentOnly.directives[1]).toEqual(new PrefixedType() ..name = 'Dep' ..prefix = 'dep2'); }); it('should populate `pipes` from @View value specified second.', () async { var model = (await _testCreateModel('directives_files/components.dart')).ngDeps; final componentFirst = reflectableNamed(model, 'ComponentFirst'); expect(componentFirst).toBeNotNull(); expect(componentFirst.pipes).toBeNotNull(); expect(componentFirst.pipes.length).toEqual(2); expect(componentFirst.pipes.first) .toEqual(new PrefixedType()..name = 'PipeDep'); expect(componentFirst.pipes[1]).toEqual(new PrefixedType() ..name = 'PipeDep' ..prefix = 'dep2'); }); it('should populate `pipes` from @View value specified first.', () async { var model = (await _testCreateModel('directives_files/components.dart')).ngDeps; final viewFirst = reflectableNamed(model, 'ViewFirst'); expect(viewFirst).toBeNotNull(); expect(viewFirst.pipes).toBeNotNull(); expect(viewFirst.pipes.length).toEqual(2); expect(viewFirst.pipes.first).toEqual(new PrefixedType() ..name = 'PipeDep' ..prefix = 'dep2'); expect(viewFirst.pipes[1]).toEqual(new PrefixedType()..name = 'PipeDep'); }); it('should populate `pipes` from @Component value with no @View.', () async { var model = (await _testCreateModel('directives_files/components.dart')).ngDeps; final componentOnly = reflectableNamed(model, 'ComponentOnly'); expect(componentOnly).toBeNotNull(); expect(componentOnly.pipes).toBeNotNull(); expect(componentOnly.pipes.length).toEqual(2); expect(componentOnly.pipes.first) .toEqual(new PrefixedType()..name = 'PipeDep'); expect(componentOnly.pipes[1]).toEqual(new PrefixedType() ..name = 'PipeDep' ..prefix = 'dep2'); }); it('should merge `outputs` from the annotation and fields.', () async { var model = await _testCreateModel('directives_files/components.dart'); expect(model.types['ComponentWithOutputs'].outputs).toEqual( {'a': 'a', 'b': 'b', 'c': 'renamed', 'd': 'd', 'e': 'get-renamed'}); }); it('should merge `inputs` from the annotation and fields.', () async { var model = await _testCreateModel('directives_files/components.dart'); expect(model.types['ComponentWithInputs'].inputs).toEqual( {'a': 'a', 'b': 'b', 'c': 'renamed', 'd': 'd', 'e': 'set-renamed'}); }); it('should merge host bindings from the annotation and fields.', () async { var model = await _testCreateModel('directives_files/components.dart'); expect(model.types['ComponentWithHostBindings'].hostProperties) .toEqual({'a': 'a', 'b': 'b', 'renamed': 'c'}); }); it('should merge host listeners from the annotation and fields.', () async { var model = await _testCreateModel('directives_files/components.dart'); expect(model.types['ComponentWithHostListeners'].hostListeners).toEqual({ 'a': 'onA()', 'b': 'onB()', 'c': 'onC(\$event.target,\$event.target.value)' }); }); it('should warn if @Component has a `template` and @View is present.', () async { final logger = new RecordingLogger(); final model = await _testCreateModel('bad_directives_files/template.dart', logger: logger); var warning = logger.logs.firstWhere((l) => l.contains('WARN'), orElse: () => null); expect(warning).toBeNotNull(); expect(warning.toLowerCase()) .toContain('cannot specify view parameters on @component'); }); it('should warn if @Component has a `templateUrl` and @View is present.', () async { final logger = new RecordingLogger(); final model = await _testCreateModel( 'bad_directives_files/template_url.dart', logger: logger); var warning = logger.logs.firstWhere((l) => l.contains('WARN'), orElse: () => null); expect(warning).toBeNotNull(); expect(warning.toLowerCase()) .toContain('cannot specify view parameters on @component'); }); it('should warn if @Component has `directives` and @View is present.', () async { final logger = new RecordingLogger(); final model = await _testCreateModel( 'bad_directives_files/directives.dart', logger: logger); var warning = logger.logs.firstWhere((l) => l.contains('WARN'), orElse: () => null); expect(warning).toBeNotNull(); expect(warning.toLowerCase()) .toContain('cannot specify view parameters on @component'); }); it('should warn if @Component has `pipes` and @View is present.', () async { final logger = new RecordingLogger(); final model = await _testCreateModel('bad_directives_files/pipes.dart', logger: logger); var warning = logger.logs.firstWhere((l) => l.contains('WARN'), orElse: () => null); expect(warning).toBeNotNull(); expect(warning.toLowerCase()) .toContain('cannot specify view parameters on @component'); }); }); describe('pipes', () { it('should read the pipe name', () async { var model = await _testCreateModel('pipe_files/pipes.dart'); expect(model.types['NameOnlyPipe'].name).toEqual('nameOnly'); expect(model.types['NameOnlyPipe'].pure).toBe(false); }); it('should read the pure flag', () async { var model = await _testCreateModel('pipe_files/pipes.dart'); expect(model.types['NameAndPurePipe'].pure).toBe(true); }); }); } Future<NgMeta> _testCreateModel(String inputPath, {List<AnnotationDescriptor> customDescriptors: const [], AssetId assetId, AssetReader reader, TransformLogger logger}) { if (logger == null) logger = new RecordingLogger(); return zone.exec(() async { var inputId = _assetIdForPath(inputPath); if (reader == null) { reader = new TestAssetReader(); } if (assetId != null) { reader.addAsset(assetId, await reader.readAsString(inputId)); inputId = assetId; } var annotationMatcher = new AnnotationMatcher()..addAll(customDescriptors); return createNgMeta(reader, inputId, annotationMatcher); }, log: logger); } AssetId _assetIdForPath(String path) => new AssetId('angular2', 'test/transform/directive_processor/$path');
modules_dart/transform/test/transform/directive_processor/all_tests.dart
1
https://github.com/angular/angular/commit/a593ffa6f3d7cb6062e9e1957aae1382bfcb666f
[ 0.9981464147567749, 0.028484152629971504, 0.00016498960030730814, 0.00017303851200267673, 0.16048170626163483 ]
{ "id": 2, "code_window": [ " host: {'[a]': 'a'})\n", "class ComponentWithHostBindings {\n", " @HostBinding() Object b;\n", " @HostBinding('renamed') Object c;\n", "}\n", "\n", "@Component(\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", " Object _d;\n", " @HostBinding() Object get d => _d;\n", "\n", " Object _e;\n", " @HostBinding('get-renamed') Object get e => _e;\n" ], "file_path": "modules_dart/transform/test/transform/directive_processor/directives_files/components.dart", "type": "add", "edit_start_line_idx": 69 }
library dinner.package_soup; import 'package:angular2/angular2.dart'; import 'package:soup/soup.dart'; @Soup() @View(template: '') class PackageSoup { PackageSoup(); }
modules_dart/transform/test/transform/directive_processor/custom_metadata/package_soup.dart
0
https://github.com/angular/angular/commit/a593ffa6f3d7cb6062e9e1957aae1382bfcb666f
[ 0.00017520313849672675, 0.00017484687850810587, 0.00017449060396756977, 0.00017484687850810587, 3.5626726457849145e-7 ]
{ "id": 2, "code_window": [ " host: {'[a]': 'a'})\n", "class ComponentWithHostBindings {\n", " @HostBinding() Object b;\n", " @HostBinding('renamed') Object c;\n", "}\n", "\n", "@Component(\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", " Object _d;\n", " @HostBinding() Object get d => _d;\n", "\n", " Object _e;\n", " @HostBinding('get-renamed') Object get e => _e;\n" ], "file_path": "modules_dart/transform/test/transform/directive_processor/directives_files/components.dart", "type": "add", "edit_start_line_idx": 69 }
library bar.ng_deps.dart; import 'bar.dart'; import 'package:angular2/src/core/reflection/reflection.dart' as _ngRef; import 'package:angular2/src/core/metadata.dart'; import 'bar.template.dart' as _templates; import 'package:angular2/src/core/metadata.ng_deps.dart' as i0; export 'bar.dart'; var _visited = false; void initReflector() { if (_visited) return; _visited = true; _ngRef.reflector ..registerType( MyComponent, new _ngRef.ReflectionInfo(const [ const Component( outputs: ['eventName1', 'eventName2: propName2'], selector: '[soup]'), const View(template: ''), _templates.hostViewFactory_MyComponent ], const [], () => new MyComponent())) ..registerGetters( {'eventName1': (o) => o.eventName1, 'eventName2': (o) => o.eventName2}); i0.initReflector(); }
modules_dart/transform/test/transform/integration/event_getter_files/expected/bar.ng_deps.dart
0
https://github.com/angular/angular/commit/a593ffa6f3d7cb6062e9e1957aae1382bfcb666f
[ 0.002863760571926832, 0.0010691415518522263, 0.00016836545546539128, 0.00017529871547594666, 0.0012689904542639852 ]
{ "id": 2, "code_window": [ " host: {'[a]': 'a'})\n", "class ComponentWithHostBindings {\n", " @HostBinding() Object b;\n", " @HostBinding('renamed') Object c;\n", "}\n", "\n", "@Component(\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", " Object _d;\n", " @HostBinding() Object get d => _d;\n", "\n", " Object _e;\n", " @HostBinding('get-renamed') Object get e => _e;\n" ], "file_path": "modules_dart/transform/test/transform/directive_processor/directives_files/components.dart", "type": "add", "edit_start_line_idx": 69 }
import {Component} from 'angular2/core'; import {MinLengthValidator, MaxLengthValidator} from 'angular2/common'; // #docregion min @Component({ selector: 'min-cmp', directives: [MinLengthValidator], template: ` <form> <p>Year: <input ngControl="year" minlength="2"></p> </form> ` }) class MinLengthTestComponent { } // #enddocregion // #docregion max @Component({ selector: 'max-cmp', directives: [MaxLengthValidator], template: ` <form> <p>Year: <input ngControl="year" maxlength="4"></p> </form> ` }) class MaxLengthTestComponent { } // #enddocregion
modules/angular2/examples/common/forms/ts/validators/validators.ts
0
https://github.com/angular/angular/commit/a593ffa6f3d7cb6062e9e1957aae1382bfcb666f
[ 0.0003547571541275829, 0.00021982078033033758, 0.0001667694450588897, 0.00017887825379148126, 0.00007812387048033997 ]
{ "id": 0, "code_window": [ "\n", "\tasync reloadNote(props, options = null) {\n", "\t\tif (!options) options = {};\n", "\t\tif (!('noReloadIfLocalChanges' in options)) options.noReloadIfLocalChanges = false;\n", "\n", "\t\tconst stateNoteId = this.state.note ? this.state.note.id : null;\n", "\t\tconst noteId = props.noteId;\n", "\t\tlet loadingNewNote = stateNoteId !== noteId;\n", "\t\tthis.lastLoadedNoteId_ = noteId;\n", "\t\tconst note = noteId ? await Note.load(noteId) : null;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tawait this.saveIfNeeded();\n", "\n" ], "file_path": "ElectronClient/app/gui/NoteText.jsx", "type": "add", "edit_start_line_idx": 130 }
const { reg } = require('lib/registry.js'); const Folder = require('lib/models/Folder.js'); const BaseModel = require('lib/BaseModel.js'); const Note = require('lib/models/Note.js'); const shared = {}; shared.noteExists = async function(noteId) { const existingNote = await Note.load(noteId); return !!existingNote; } shared.saveNoteButton_press = async function(comp) { let note = Object.assign({}, comp.state.note); // Note has been deleted while user was modifying it. In that case, we // just save a new note by clearing the note ID. if (note.id && !(await shared.noteExists(note.id))) delete note.id; // reg.logger().info('Saving note: ', note); if (!note.parent_id) { let folder = await Folder.defaultFolder(); if (!folder) { //Log.warn('Cannot save note without a notebook'); return; } note.parent_id = folder.id; } let isNew = !note.id; let titleWasAutoAssigned = false; if (isNew && !note.title) { note.title = Note.defaultTitle(note); titleWasAutoAssigned = true; } // Save only the properties that have changed // let diff = null; // if (!isNew) { // diff = BaseModel.diffObjects(comp.state.lastSavedNote, note); // diff.type_ = note.type_; // diff.id = note.id; // } else { // diff = Object.assign({}, note); // } // const savedNote = await Note.save(diff); let options = {}; if (!isNew) { options.fields = BaseModel.diffObjectsFields(comp.state.lastSavedNote, note); } const savedNote = ('fields' in options) && !options.fields.length ? Object.assign({}, note) : await Note.save(note, { userSideValidation: true }); const stateNote = comp.state.note; // Re-assign any property that might have changed during saving (updated_time, etc.) note = Object.assign(note, savedNote); if (stateNote) { // But we preserve the current title and body because // the user might have changed them between the time // saveNoteButton_press was called and the note was // saved (it's done asynchronously). // // If the title was auto-assigned above, we don't restore // it from the state because it will be empty there. if (!titleWasAutoAssigned) note.title = stateNote.title; note.body = stateNote.body; } comp.setState({ lastSavedNote: Object.assign({}, note), note: note, }); if (isNew) Note.updateGeolocation(note.id); comp.refreshNoteMetadata(); } shared.saveOneProperty = async function(comp, name, value) { let note = Object.assign({}, comp.state.note); // Note has been deleted while user was modifying it. In that, we // just save a new note by clearing the note ID. if (note.id && !(await shared.noteExists(note.id))) delete note.id; // reg.logger().info('Saving note property: ', note.id, name, value); if (note.id) { let toSave = { id: note.id }; toSave[name] = value; toSave = await Note.save(toSave); note[name] = toSave[name]; comp.setState({ lastSavedNote: Object.assign({}, note), note: note, }); } else { note[name] = value; comp.setState({ note: note }); } } shared.noteComponent_change = function(comp, propName, propValue) { let note = Object.assign({}, comp.state.note); note[propName] = propValue; comp.setState({ note: note }); } shared.refreshNoteMetadata = async function(comp, force = null) { if (force !== true && !comp.state.showNoteMetadata) return; let noteMetadata = await Note.serializeAllProps(comp.state.note); comp.setState({ noteMetadata: noteMetadata }); } shared.isModified = function(comp) { if (!comp.state.note || !comp.state.lastSavedNote) return false; let diff = BaseModel.diffObjects(comp.state.note, comp.state.lastSavedNote); delete diff.type_; return !!Object.getOwnPropertyNames(diff).length; } shared.initState = async function(comp) { let note = null; let mode = 'view'; if (!comp.props.noteId) { note = comp.props.itemType == 'todo' ? Note.newTodo(comp.props.folderId) : Note.new(comp.props.folderId); mode = 'edit'; } else { note = await Note.load(comp.props.noteId); } const folder = Folder.byId(comp.props.folders, note.parent_id); comp.setState({ lastSavedNote: Object.assign({}, note), note: note, mode: mode, folder: folder, isLoading: false, }); comp.lastLoadedNoteId_ = note ? note.id : null; } shared.showMetadata_onPress = function(comp) { comp.setState({ showNoteMetadata: !comp.state.showNoteMetadata }); comp.refreshNoteMetadata(true); } shared.toggleIsTodo_onPress = function(comp) { let newNote = Note.toggleIsTodo(comp.state.note); let newState = { note: newNote }; comp.setState(newState); } module.exports = shared;
ReactNativeClient/lib/components/shared/note-screen-shared.js
1
https://github.com/laurent22/joplin/commit/1d7f30d441e2c0fb82bfd0750d3a4203c9636390
[ 0.9973325729370117, 0.640136182308197, 0.00017350277630612254, 0.981784462928772, 0.469634085893631 ]
{ "id": 0, "code_window": [ "\n", "\tasync reloadNote(props, options = null) {\n", "\t\tif (!options) options = {};\n", "\t\tif (!('noReloadIfLocalChanges' in options)) options.noReloadIfLocalChanges = false;\n", "\n", "\t\tconst stateNoteId = this.state.note ? this.state.note.id : null;\n", "\t\tconst noteId = props.noteId;\n", "\t\tlet loadingNewNote = stateNoteId !== noteId;\n", "\t\tthis.lastLoadedNoteId_ = noteId;\n", "\t\tconst note = noteId ? await Note.load(noteId) : null;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tawait this.saveIfNeeded();\n", "\n" ], "file_path": "ElectronClient/app/gui/NoteText.jsx", "type": "add", "edit_start_line_idx": 130 }
const { isHidden } = require('lib/path-utils.js'); const { Logger } = require('lib/logger.js'); class FileApi { constructor(baseDir, driver) { this.baseDir_ = baseDir; this.driver_ = driver; this.logger_ = new Logger(); this.syncTargetId_ = null; } driver() { return this.driver_; } setSyncTargetId(v) { this.syncTargetId_ = v; } syncTargetId() { if (this.syncTargetId_ === null) throw new Error('syncTargetId has not been set!!'); return this.syncTargetId_; } setLogger(l) { this.logger_ = l; } logger() { return this.logger_; } fullPath_(path) { let output = this.baseDir_; if (path != '') output += '/' + path; return output; } // DRIVER MUST RETURN PATHS RELATIVE TO `path` list(path = '', options = null) { if (!options) options = {}; if (!('includeHidden' in options)) options.includeHidden = false; if (!('context' in options)) options.context = null; this.logger().debug('list ' + this.baseDir_); return this.driver_.list(this.baseDir_, options).then((result) => { if (!options.includeHidden) { let temp = []; for (let i = 0; i < result.items.length; i++) { if (!isHidden(result.items[i].path)) temp.push(result.items[i]); } result.items = temp; } return result; }); } setTimestamp(path, timestampMs) { this.logger().debug('setTimestamp ' + this.fullPath_(path)); return this.driver_.setTimestamp(this.fullPath_(path), timestampMs); } mkdir(path) { this.logger().debug('mkdir ' + this.fullPath_(path)); return this.driver_.mkdir(this.fullPath_(path)); } stat(path) { this.logger().debug('stat ' + this.fullPath_(path)); return this.driver_.stat(this.fullPath_(path)).then((output) => { if (!output) return output; output.path = path; return output; }); } get(path, options = null) { if (!options) options = {}; if (!options.encoding) options.encoding = 'utf8'; this.logger().debug('get ' + this.fullPath_(path)); return this.driver_.get(this.fullPath_(path), options); } put(path, content, options = null) { this.logger().debug('put ' + this.fullPath_(path)); return this.driver_.put(this.fullPath_(path), content, options); } delete(path) { this.logger().debug('delete ' + this.fullPath_(path)); return this.driver_.delete(this.fullPath_(path)); } move(oldPath, newPath) { this.logger().debug('move ' + this.fullPath_(oldPath) + ' => ' + this.fullPath_(newPath)); return this.driver_.move(this.fullPath_(oldPath), this.fullPath_(newPath)); } format() { return this.driver_.format(); } delta(path, options = null) { this.logger().debug('delta ' + this.fullPath_(path)); return this.driver_.delta(this.fullPath_(path), options); } } module.exports = { FileApi };
ReactNativeClient/lib/file-api.js
0
https://github.com/laurent22/joplin/commit/1d7f30d441e2c0fb82bfd0750d3a4203c9636390
[ 0.0015959205338731408, 0.000343901599990204, 0.00016822264296934009, 0.0001711194054223597, 0.0004067517875228077 ]
{ "id": 0, "code_window": [ "\n", "\tasync reloadNote(props, options = null) {\n", "\t\tif (!options) options = {};\n", "\t\tif (!('noReloadIfLocalChanges' in options)) options.noReloadIfLocalChanges = false;\n", "\n", "\t\tconst stateNoteId = this.state.note ? this.state.note.id : null;\n", "\t\tconst noteId = props.noteId;\n", "\t\tlet loadingNewNote = stateNoteId !== noteId;\n", "\t\tthis.lastLoadedNoteId_ = noteId;\n", "\t\tconst note = noteId ? await Note.load(noteId) : null;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tawait this.saveIfNeeded();\n", "\n" ], "file_path": "ElectronClient/app/gui/NoteText.jsx", "type": "add", "edit_start_line_idx": 130 }
# About End-To-End Encryption (E2EE) 3. Now you need to synchronise all your notes so that thEnd-to-end encryption (E2EE) is a system where only the owner of the notes, notebooks, tags or resources can read them. It prevents potential eavesdroppers - including telecom providers, internet providers, and even the developer of Joplin from being able to access the data. The systems is designed to defeat any attempts at surveillance or tampering because no third parties can decipher the data being communicated or stored. There is a small overhead to using E2EE since data constantly have to be encrypted and decrypted so consider whether you really need the feature. # Enabling E2EE Due to the decentralised nature of Joplin, E2EE needs to be manually enabled on all the applications that you synchronise with. It is recommended to first enable it on the desktop or terminal application since they generally run on more powerful devices (unlike the mobile application), and so they can encrypt the initial data faster. To enable it, please follow these steps: 1. On your first device (eg. on the desktop application), go to the Encryption Config screen and click "Enable encryption" 2. Input your password. This is the Master Key password which will be used to encrypt all your notes. Make sure you do not forget it since, for security reason, it cannot be recovered. ey are sent encrypted to the sync target (eg. to OneDrive, Nextcloud, etc.). Wait for any synchronisation that might be in progress and click on "Synchronise". 4. Wait for this synchronisation operation to complete. Since all the data needs to be re-sent (encrypted) to the sync target, it may take a long time, especially if you have many notes and resources. Note that even if synchronisation seems stuck, most likely it is still running - do not cancel it and simply let it run over night if needed. 5. Once this first synchronisation operation is done, open the next device you are synchronising with. Click "Synchronise" and wait for the sync operation to complete. The device will receive the master key, and you will need to provide the password for it. At this point E2EE will be automatically enabled on this device. Once done, click Synchronise again and wait for it to complete. 6. Repeat step 5 for each device. Once all the devices are in sync with E2EE enabled, the encryption/decryption should be mostly transparent. Occasionally you may see encrypted items but they will get decrypted in the background eventually. # Disabling E2EE Follow the same procedure as above but instead disable E2EE on each device one by one. Again it might be simpler to do it one device at a time and to wait every time for the synchronisation to complete.
README_e2ee.md
0
https://github.com/laurent22/joplin/commit/1d7f30d441e2c0fb82bfd0750d3a4203c9636390
[ 0.00016497276374138892, 0.00016406520444434136, 0.00016230621258728206, 0.00016491662245243788, 0.000001244002874045691 ]
{ "id": 0, "code_window": [ "\n", "\tasync reloadNote(props, options = null) {\n", "\t\tif (!options) options = {};\n", "\t\tif (!('noReloadIfLocalChanges' in options)) options.noReloadIfLocalChanges = false;\n", "\n", "\t\tconst stateNoteId = this.state.note ? this.state.note.id : null;\n", "\t\tconst noteId = props.noteId;\n", "\t\tlet loadingNewNote = stateNoteId !== noteId;\n", "\t\tthis.lastLoadedNoteId_ = noteId;\n", "\t\tconst note = noteId ? await Note.load(noteId) : null;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tawait this.saveIfNeeded();\n", "\n" ], "file_path": "ElectronClient/app/gui/NoteText.jsx", "type": "add", "edit_start_line_idx": 130 }
{"Give focus to next pane":"","Give focus to previous pane":"","Enter command line mode":"","Exit command line mode":"","Edit the selected note":"","Cancel the current command.":"","Exit the application.":"","Delete the currently selected note or notebook.":"","To delete a tag, untag the associated notes.":"","Please select the note or notebook to be deleted first.":"","Set a to-do as completed / not completed":"","[t]oggle [c]onsole between maximized/minimized/hidden/visible.":"","Search":"","[t]oggle note [m]etadata.":"","[M]ake a new [n]ote":"","[M]ake a new [t]odo":"","[M]ake a new note[b]ook":"","Copy ([Y]ank) the [n]ote to a notebook.":"","Move the note to a notebook.":"","Press Ctrl+D or type \"exit\" to exit the application":"","More than one item match \"%s\". Please narrow down your query.":"","No notebook selected.":"","No notebook has been specified.":"","Y":"","n":"","N":"","y":"","Cancelling background synchronisation... Please wait.":"","No such command: %s":"","The command \"%s\" is only available in GUI mode":"","Cannot change encrypted item":"","Missing required argument: %s":"","%s: %s":"","Your choice: ":"","Invalid answer: %s":"","Attaches the given file to the note.":"","Cannot find \"%s\".":"","Displays the given note.":"","Displays the complete information about note.":"","Gets or sets a config value. If [value] is not provided, it will show the value of [name]. If neither [name] nor [value] is provided, it will list the current configuration.":"","Also displays unset and hidden config variables.":"","%s = %s (%s)":"","%s = %s":"","Duplicates the notes matching <note> to [notebook]. If no notebook is specified the note is duplicated in the current notebook.":"","Marks a to-do as done.":"","Note is not a to-do: \"%s\"":"","Manages E2EE configuration. Commands are `enable`, `disable`, `decrypt`, `status` and `target-status`.":"","Enter master password:":"","Operation cancelled":"","Starting decryption... Please wait as it may take several minutes depending on how much there is to decrypt.":"","Completed decryption.":"","Enabled":"","Disabled":"","Encryption is: %s":"","Edit note.":"","No text editor is defined. Please set it using `config editor <editor-path>`":"","No active notebook.":"","Note does not exist: \"%s\". Create it?":"","Starting to edit note. Close the editor to get back to the prompt.":"","Note has been saved.":"","Exits the application.":"","Exports Joplin data to the given directory. By default, it will export the complete database including notebooks, notes, tags and resources.":"","Exports only the given note.":"","Exports only the given notebook.":"","Displays a geolocation URL for the note.":"","Displays usage information.":"","Shortcuts are not available in CLI mode.":"","Type `help [command]` for more information about a command; or type `help all` for the complete usage information.":"","The possible commands are:":"","In any command, a note or notebook can be refered to by title or ID, or using the shortcuts `$n` or `$b` for, respectively, the currently selected note or notebook. `$c` can be used to refer to the currently selected item.":"","To move from one pane to another, press Tab or Shift+Tab.":"","Use the arrows and page up/down to scroll the lists and text areas (including this console).":"","To maximise/minimise the console, press \"TC\".":"","To enter command line mode, press \":\"":"","To exit command line mode, press ESCAPE":"","For the complete list of available keyboard shortcuts, type `help shortcuts`":"","Imports an Evernote notebook file (.enex file).":"","Do not ask for confirmation.":"","File \"%s\" will be imported into existing notebook \"%s\". Continue?":"","New notebook \"%s\" will be created and file \"%s\" will be imported into it. Continue?":"","Found: %d.":"","Created: %d.":"","Updated: %d.":"","Skipped: %d.":"","Resources: %d.":"","Tagged: %d.":"","Importing notes...":"","The notes have been imported: %s":"","Displays the notes in the current notebook. Use `ls /` to display the list of notebooks.":"","Displays only the first top <num> notes.":"","Sorts the item by <field> (eg. title, updated_time, created_time).":"","Reverses the sorting order.":"","Displays only the items of the specific type(s). Can be `n` for notes, `t` for to-dos, or `nt` for notes and to-dos (eg. `-tt` would display only the to-dos, while `-ttd` would display notes and to-dos.":"","Either \"text\" or \"json\"":"","Use long list format. Format is ID, NOTE_COUNT (for notebook), DATE, TODO_CHECKED (for to-dos), TITLE":"","Please select a notebook first.":"","Creates a new notebook.":"","Creates a new note.":"","Notes can only be created within a notebook.":"","Creates a new to-do.":"","Moves the notes matching <note> to [notebook].":"","Renames the given <item> (note or notebook) to <name>.":"","Deletes the given notebook.":"","Deletes the notebook without asking for confirmation.":"","Delete notebook? All notes within this notebook will also be deleted.":"","Deletes the notes matching <note-pattern>.":"","Deletes the notes without asking for confirmation.":"","%d notes match this pattern. Delete them?":"","Delete note?":"","Searches for the given <pattern> in all the notes.":"","Sets the property <name> of the given <note> to the given [value]. Possible properties are:\n\n%s":"","Displays summary about the notes and notebooks.":"","Synchronises with remote storage.":"","Sync to provided target (defaults to sync.target config value)":"","Synchronisation is already in progress.":"","Lock file is already being hold. If you know that no synchronisation is taking place, you may delete the lock file at \"%s\" and resume the operation.":"","Authentication was not completed (did not receive an authentication token).":"","Synchronisation target: %s (%s)":"","Cannot initialize synchroniser.":"","Starting synchronisation...":"","Cancelling... Please wait.":"","<tag-command> can be \"add\", \"remove\" or \"list\" to assign or remove [tag] from [note], or to list the notes associated with [tag]. The command `tag list` can be used to list all the tags.":"","Invalid command: \"%s\"":"","<todo-command> can either be \"toggle\" or \"clear\". Use \"toggle\" to toggle the given to-do between completed and uncompleted state (If the target is a regular note it will be converted to a to-do). Use \"clear\" to convert the to-do back to a regular note.":"","Marks a to-do as non-completed.":"","Switches to [notebook] - all further operations will happen within this notebook.":"","Displays version information":"","%s %s (%s)":"","Enum":"","Type: %s.":"","Possible values: %s.":"","Default: %s":"","Possible keys/values:":"","Fatal error:":"","The application has been authorised - you may now close this browser tab.":"","The application has been successfully authorised.":"","Please open the following URL in your browser to authenticate the application. The application will create a directory in \"Apps/Joplin\" and will only read and write files in this directory. It will have no access to any files outside this directory nor to any other personal data. No data will be shared with any third party.":"","Search:":"","Welcome to Joplin!\n\nType `:help shortcuts` for the list of keyboard shortcuts, or just `:help` for usage information.\n\nFor example, to create a notebook press `mb`; to create a note press `mn`.":"","One or more items are currently encrypted and you may need to supply a master password. To do so please type `e2ee decrypt`. If you have already supplied the password, the encrypted items are being decrypted in the background and will be available soon.":"","File":"","Save":"","New note":"","New to-do":"","New notebook":"","Import Evernote notes":"","Evernote Export Files":"","Quit":"","Edit":"","Copy":"","Cut":"","Paste":"","Search in all the notes":"","Tools":"","Synchronisation status":"","Encryption options":"","General Options":"","Help":"","Website and documentation":"","About Joplin":"","%s %s (%s, %s)":"","OK":"","Cancel":"","Notes and settings are stored in: %s":"","Disabling encryption means *all* your notes and attachments are going to be re-synchronised and sent unencrypted to the sync target. Do you wish to continue?":"","Enabling encryption means *all* your notes and attachments are going to be re-synchronised and sent encrypted to the sync target. Do not lose the password as, for security purposes, this will be the *only* way to decrypt the data! To enable encryption, please enter your password below.":"","Disable encryption":"","Enable encryption":"","Master Keys":"","Active":"","ID":"","Source":"","Created":"","Updated":"","Password":"","Password OK":"","Note: Only one master key is going to be used for encryption (the one marked as \"active\"). Any of the keys might be used for decryption, depending on how the notes or notebooks were originally encrypted.":"","Status":"","Encryption is:":"","Back":"","New notebook \"%s\" will be created and file \"%s\" will be imported into it":"","Please create a notebook first.":"","Note title:":"","Please create a notebook first":"","To-do title:":"","Notebook title:":"","Add or remove tags:":"","Separate each tag by a comma.":"","Rename notebook:":"","Set alarm:":"","Layout":"","Some items cannot be synchronised.":"","View them now":"","Some items cannot be decrypted.":"","Set the password":"","Add or remove tags":"","Switch between note and to-do type":"","Delete":"","Delete notes?":"","No notes in here. Create one by clicking on \"New note\".":"","There is currently no notebook. Create one by clicking on \"New notebook\".":"","Unsupported link or message: %s":"","Attach file":"","Set alarm":"","Refresh":"","Clear":"","OneDrive Login":"","Import":"","Options":"","Synchronisation Status":"","Encryption Options":"","Remove this tag from all the notes?":"","Remove this search from the sidebar?":"","Rename":"","Synchronise":"","Notebooks":"","Tags":"","Searches":"","Please select where the sync status should be exported to":"","Usage: %s":"","Unknown flag: %s":"","File system":"","OneDrive":"","OneDrive Dev (For testing only)":"","Unknown log level: %s":"","Unknown level ID: %s":"","Cannot refresh token: authentication data is missing. Starting the synchronisation again may fix the problem.":"","Could not synchronize with OneDrive.\n\nThis error often happens when using OneDrive for Business, which unfortunately cannot be supported.\n\nPlease consider using a regular OneDrive account.":"","Cannot access %s":"","Created local items: %d.":"","Updated local items: %d.":"","Created remote items: %d.":"","Updated remote items: %d.":"","Deleted local items: %d.":"","Deleted remote items: %d.":"","State: \"%s\".":"","Cancelling...":"","Completed: %s":"","Synchronisation is already in progress. State: %s":"","Encrypted":"","Encrypted items cannot be modified":"","Conflicts":"","A notebook with this title already exists: \"%s\"":"","Notebooks cannot be named \"%s\", which is a reserved title.":"","Untitled":"","This note does not have geolocation information.":"","Cannot copy note to \"%s\" notebook":"","Cannot move note to \"%s\" notebook":"","Text editor":"","The editor that will be used to open a note. If none is provided it will try to auto-detect the default editor.":"","Language":"","Date format":"","Time format":"","Theme":"","Light":"","Dark":"","Show uncompleted todos on top of the lists":"","Save geo-location with notes":"","Synchronisation interval":"","%d minutes":"","%d hour":"","%d hours":"","Automatically update the application":"","Show advanced options":"","Synchronisation target":"","The target to synchonise to. If synchronising with the file system, set `sync.2.path` to specify the target directory.":"","Directory to synchronise with (absolute path)":"","The path to synchronise with when file system synchronisation is enabled. See `sync.target`.":"","Invalid option value: \"%s\". Possible values are: %s.":"","Items that cannot be synchronised":"","%s (%s): %s":"","These items will remain on the device but will not be uploaded to the sync target. In order to find these items, either search for the title or the ID (which is displayed in brackets above).":"","Sync status (synced items / total items)":"","%s: %d/%d":"","Total: %d/%d":"","Conflicted: %d":"","To delete: %d":"","Folders":"","%s: %d notes":"","Coming alarms":"","On %s: %s":"","There are currently no notes. Create one by clicking on the (+) button.":"","Delete these notes?":"","Log":"","Export Debug Report":"","Encryption Config":"","Configuration":"","Move to notebook...":"","Move %d notes to notebook \"%s\"?":"","Press to set the decryption password.":"","Select date":"","Confirm":"","Cancel synchronisation":"","Master Key %s":"","Created: %s":"","Password:":"","Password cannot be empty":"","Enable":"","The notebook could not be saved: %s":"","Edit notebook":"","This note has been modified:":"","Save changes":"","Discard changes":"","Unsupported image type: %s":"","Attach photo":"","Attach any file":"","Convert to note":"","Convert to todo":"","Hide metadata":"","Show metadata":"","View on map":"","Delete notebook":"","Login with OneDrive":"","Click on the (+) button to create a new note or notebook. Click on the side menu to access your existing notebooks.":"","You currently have no notebook. Create one by clicking on (+) button.":"","Welcome":""}
ReactNativeClient/locales/en_GB.json
0
https://github.com/laurent22/joplin/commit/1d7f30d441e2c0fb82bfd0750d3a4203c9636390
[ 0.0002122553705703467, 0.0002122553705703467, 0.0002122553705703467, 0.0002122553705703467, 0 ]
{ "id": 1, "code_window": [ "\t\tconst noteId = props.noteId;\n", "\t\tlet loadingNewNote = stateNoteId !== noteId;\n", "\t\tthis.lastLoadedNoteId_ = noteId;\n", "\t\tconst note = noteId ? await Note.load(noteId) : null;\n", "\t\tif (noteId !== this.lastLoadedNoteId_) return; // Race condition - current note was changed while this one was loading\n", "\t\tif (!options.noReloadIfLocalChanges && this.isModified()) return;\n", "\n", "\t\t// If the note hasn't been changed, exit now\n", "\t\tif (this.state.note && note) {\n", "\t\t\tlet diff = Note.diffObjects(this.state.note, note);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (options.noReloadIfLocalChanges && this.isModified()) return;\n" ], "file_path": "ElectronClient/app/gui/NoteText.jsx", "type": "replace", "edit_start_line_idx": 136 }
const { reg } = require('lib/registry.js'); const Folder = require('lib/models/Folder.js'); const BaseModel = require('lib/BaseModel.js'); const Note = require('lib/models/Note.js'); const shared = {}; shared.noteExists = async function(noteId) { const existingNote = await Note.load(noteId); return !!existingNote; } shared.saveNoteButton_press = async function(comp) { let note = Object.assign({}, comp.state.note); // Note has been deleted while user was modifying it. In that case, we // just save a new note by clearing the note ID. if (note.id && !(await shared.noteExists(note.id))) delete note.id; // reg.logger().info('Saving note: ', note); if (!note.parent_id) { let folder = await Folder.defaultFolder(); if (!folder) { //Log.warn('Cannot save note without a notebook'); return; } note.parent_id = folder.id; } let isNew = !note.id; let titleWasAutoAssigned = false; if (isNew && !note.title) { note.title = Note.defaultTitle(note); titleWasAutoAssigned = true; } // Save only the properties that have changed // let diff = null; // if (!isNew) { // diff = BaseModel.diffObjects(comp.state.lastSavedNote, note); // diff.type_ = note.type_; // diff.id = note.id; // } else { // diff = Object.assign({}, note); // } // const savedNote = await Note.save(diff); let options = {}; if (!isNew) { options.fields = BaseModel.diffObjectsFields(comp.state.lastSavedNote, note); } const savedNote = ('fields' in options) && !options.fields.length ? Object.assign({}, note) : await Note.save(note, { userSideValidation: true }); const stateNote = comp.state.note; // Re-assign any property that might have changed during saving (updated_time, etc.) note = Object.assign(note, savedNote); if (stateNote) { // But we preserve the current title and body because // the user might have changed them between the time // saveNoteButton_press was called and the note was // saved (it's done asynchronously). // // If the title was auto-assigned above, we don't restore // it from the state because it will be empty there. if (!titleWasAutoAssigned) note.title = stateNote.title; note.body = stateNote.body; } comp.setState({ lastSavedNote: Object.assign({}, note), note: note, }); if (isNew) Note.updateGeolocation(note.id); comp.refreshNoteMetadata(); } shared.saveOneProperty = async function(comp, name, value) { let note = Object.assign({}, comp.state.note); // Note has been deleted while user was modifying it. In that, we // just save a new note by clearing the note ID. if (note.id && !(await shared.noteExists(note.id))) delete note.id; // reg.logger().info('Saving note property: ', note.id, name, value); if (note.id) { let toSave = { id: note.id }; toSave[name] = value; toSave = await Note.save(toSave); note[name] = toSave[name]; comp.setState({ lastSavedNote: Object.assign({}, note), note: note, }); } else { note[name] = value; comp.setState({ note: note }); } } shared.noteComponent_change = function(comp, propName, propValue) { let note = Object.assign({}, comp.state.note); note[propName] = propValue; comp.setState({ note: note }); } shared.refreshNoteMetadata = async function(comp, force = null) { if (force !== true && !comp.state.showNoteMetadata) return; let noteMetadata = await Note.serializeAllProps(comp.state.note); comp.setState({ noteMetadata: noteMetadata }); } shared.isModified = function(comp) { if (!comp.state.note || !comp.state.lastSavedNote) return false; let diff = BaseModel.diffObjects(comp.state.note, comp.state.lastSavedNote); delete diff.type_; return !!Object.getOwnPropertyNames(diff).length; } shared.initState = async function(comp) { let note = null; let mode = 'view'; if (!comp.props.noteId) { note = comp.props.itemType == 'todo' ? Note.newTodo(comp.props.folderId) : Note.new(comp.props.folderId); mode = 'edit'; } else { note = await Note.load(comp.props.noteId); } const folder = Folder.byId(comp.props.folders, note.parent_id); comp.setState({ lastSavedNote: Object.assign({}, note), note: note, mode: mode, folder: folder, isLoading: false, }); comp.lastLoadedNoteId_ = note ? note.id : null; } shared.showMetadata_onPress = function(comp) { comp.setState({ showNoteMetadata: !comp.state.showNoteMetadata }); comp.refreshNoteMetadata(true); } shared.toggleIsTodo_onPress = function(comp) { let newNote = Note.toggleIsTodo(comp.state.note); let newState = { note: newNote }; comp.setState(newState); } module.exports = shared;
ReactNativeClient/lib/components/shared/note-screen-shared.js
1
https://github.com/laurent22/joplin/commit/1d7f30d441e2c0fb82bfd0750d3a4203c9636390
[ 0.998229444026947, 0.6372648477554321, 0.00017407331324648112, 0.9670981168746948, 0.46902066469192505 ]
{ "id": 1, "code_window": [ "\t\tconst noteId = props.noteId;\n", "\t\tlet loadingNewNote = stateNoteId !== noteId;\n", "\t\tthis.lastLoadedNoteId_ = noteId;\n", "\t\tconst note = noteId ? await Note.load(noteId) : null;\n", "\t\tif (noteId !== this.lastLoadedNoteId_) return; // Race condition - current note was changed while this one was loading\n", "\t\tif (!options.noReloadIfLocalChanges && this.isModified()) return;\n", "\n", "\t\t// If the note hasn't been changed, exit now\n", "\t\tif (this.state.note && note) {\n", "\t\t\tlet diff = Note.diffObjects(this.state.note, note);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (options.noReloadIfLocalChanges && this.isModified()) return;\n" ], "file_path": "ElectronClient/app/gui/NoteText.jsx", "type": "replace", "edit_start_line_idx": 136 }
const { Log } = require('lib/log.js'); const { Database } = require('lib/database.js'); const { uuid } = require('lib/uuid.js'); const { time } = require('lib/time-utils.js'); class BaseModel { static modelType() { throw new Error('Must be overriden'); } static tableName() { throw new Error('Must be overriden'); } static addModelMd(model) { if (!model) return model; if (Array.isArray(model)) { let output = []; for (let i = 0; i < model.length; i++) { output.push(this.addModelMd(model[i])); } return output; } else { model = Object.assign({}, model); model.type_ = this.modelType(); return model; } } static logger() { return this.db().logger(); } static useUuid() { return false; } static byId(items, id) { for (let i = 0; i < items.length; i++) { if (items[i].id == id) return items[i]; } return null; } static hasField(name) { let fields = this.fieldNames(); return fields.indexOf(name) >= 0; } static fieldNames(withPrefix = false) { let output = this.db().tableFieldNames(this.tableName()); if (!withPrefix) return output; let p = withPrefix === true ? this.tableName() : withPrefix; let temp = []; for (let i = 0; i < output.length; i++) { temp.push(p + '.' + output[i]); } return temp; } static fieldType(name, defaultValue = null) { let fields = this.fields(); for (let i = 0; i < fields.length; i++) { if (fields[i].name == name) return fields[i].type; } if (defaultValue !== null) return defaultValue; throw new Error('Unknown field: ' + name); } static fields() { return this.db().tableFields(this.tableName()); } static new() { let fields = this.fields(); let output = {}; for (let i = 0; i < fields.length; i++) { let f = fields[i]; output[f.name] = f.default; } return output; } static modOptions(options) { if (!options) { options = {}; } else { options = Object.assign({}, options); } if (!('isNew' in options)) options.isNew = 'auto'; if (!('autoTimestamp' in options)) options.autoTimestamp = true; return options; } static count(options = null) { if (!options) options = {}; let sql = 'SELECT count(*) as total FROM `' + this.tableName() + '`'; if (options.where) sql += ' WHERE ' + options.where; return this.db().selectOne(sql).then((r) => { return r ? r['total'] : 0; }); } static load(id) { return this.loadByField('id', id); } static shortId(id) { return id.substr(0, 5); } // static minimalPartialId(id) { // let length = 2; // while (true) { // const partialId = id.substr(0, length); // const r = await this.db().selectOne('SELECT count(*) as total FROM `' + this.tableName() + '` WHERE `id` LIKE ?', [partialId + '%']); // if (r['total'] <= 1) return partialId; // } // } static loadByPartialId(partialId) { return this.modelSelectAll('SELECT * FROM `' + this.tableName() + '` WHERE `id` LIKE ?', [partialId + '%']); } static applySqlOptions(options, sql, params = null) { if (!options) options = {}; if (options.order && options.order.length) { let items = []; for (let i = 0; i < options.order.length; i++) { const o = options.order[i]; let item = o.by; if (options.caseInsensitive === true) item += ' COLLATE NOCASE'; if (o.dir) item += ' ' + o.dir; items.push(item); } sql += ' ORDER BY ' + items.join(', '); } if (options.limit) sql += ' LIMIT ' + options.limit; return { sql: sql, params: params }; } static async allIds(options = null) { let q = this.applySqlOptions(options, 'SELECT id FROM `' + this.tableName() + '`'); const rows = await this.db().selectAll(q.sql, q.params); return rows.map((r) => r.id); } static async all(options = null) { let q = this.applySqlOptions(options, 'SELECT * FROM `' + this.tableName() + '`'); return this.modelSelectAll(q.sql); } static async search(options = null) { if (!options) options = {}; if (!options.fields) options.fields = '*'; let conditions = options.conditions ? options.conditions.slice(0) : []; let params = options.conditionsParams ? options.conditionsParams.slice(0) : []; if (options.titlePattern) { let pattern = options.titlePattern.replace(/\*/g, '%'); conditions.push('title LIKE ?'); params.push(pattern); } if ('limit' in options && options.limit <= 0) return []; let sql = 'SELECT ' + this.db().escapeFields(options.fields) + ' FROM `' + this.tableName() + '`'; if (conditions.length) sql += ' WHERE ' + conditions.join(' AND '); let query = this.applySqlOptions(options, sql, params); return this.modelSelectAll(query.sql, query.params); } static modelSelectOne(sql, params = null) { if (params === null) params = []; return this.db().selectOne(sql, params).then((model) => { return this.filter(this.addModelMd(model)); }); } static modelSelectAll(sql, params = null) { if (params === null) params = []; return this.db().selectAll(sql, params).then((models) => { return this.filterArray(this.addModelMd(models)); }); } static loadByField(fieldName, fieldValue, options = null) { if (!options) options = {}; if (!('caseInsensitive' in options)) options.caseInsensitive = false; let sql = 'SELECT * FROM `' + this.tableName() + '` WHERE `' + fieldName + '` = ?'; if (options.caseInsensitive) sql += ' COLLATE NOCASE'; return this.modelSelectOne(sql, [fieldValue]); } static loadByTitle(fieldValue) { return this.modelSelectOne('SELECT * FROM `' + this.tableName() + '` WHERE `title` = ?', [fieldValue]); } static diffObjects(oldModel, newModel) { let output = {}; const fields = this.diffObjectsFields(oldModel, newModel); for (let i = 0; i < fields.length; i++) { output[fields[i]] = newModel[fields[i]]; } if ('type_' in newModel) output.type_ = newModel.type_; return output; // let output = {}; // let type = null; // for (let n in newModel) { // if (!newModel.hasOwnProperty(n)) continue; // if (n == 'type_') { // type = newModel[n]; // continue; // } // if (!(n in oldModel) || newModel[n] !== oldModel[n]) { // output[n] = newModel[n]; // } // } // if (type !== null) output.type_ = type; // return output; } static diffObjectsFields(oldModel, newModel) { let output = []; for (let n in newModel) { if (!newModel.hasOwnProperty(n)) continue; if (n == 'type_') continue; if (!(n in oldModel) || newModel[n] !== oldModel[n]) { output.push(n); } } return output; } static modelsAreSame(oldModel, newModel) { const diff = this.diffObjects(oldModel, newModel); delete diff.type_; return !Object.getOwnPropertyNames(diff).length; } static saveQuery(o, options) { let temp = {} let fieldNames = this.fieldNames(); for (let i = 0; i < fieldNames.length; i++) { let n = fieldNames[i]; if (n in o) temp[n] = o[n]; } o = temp; let query = {}; let modelId = o.id; const timeNow = time.unixMs(); if (options.autoTimestamp && this.hasField('updated_time')) { o.updated_time = timeNow; } // The purpose of user_updated_time is to allow the user to manually set the time of a note (in which case // options.autoTimestamp will be `false`). However note that if the item is later changed, this timestamp // will be set again to the current time. if (options.autoTimestamp && this.hasField('user_updated_time')) { o.user_updated_time = timeNow; } if (options.isNew) { if (this.useUuid() && !o.id) { modelId = uuid.create(); o.id = modelId; } if (!o.created_time && this.hasField('created_time')) { o.created_time = timeNow; } if (!o.user_created_time && this.hasField('user_created_time')) { o.user_created_time = o.created_time ? o.created_time : timeNow; } if (!o.user_updated_time && this.hasField('user_updated_time')) { o.user_updated_time = o.updated_time ? o.updated_time : timeNow; } query = Database.insertQuery(this.tableName(), o); } else { let where = { id: o.id }; let temp = Object.assign({}, o); delete temp.id; if (options.fields) { let filtered = {}; for (let i = 0; i < options.fields.length; i++) { const f = options.fields[i]; filtered[f] = o[f]; } temp = filtered; } query = Database.updateQuery(this.tableName(), temp, where); } query.id = modelId; query.modObject = o; return query; } static save(o, options = null) { options = this.modOptions(options); options.isNew = this.isNew(o, options); // Diff saving is an optimisation which takes a new version of the item and an old one, // do a diff and save only this diff. IMPORTANT: When using this make sure that both // models have been normalised using ItemClass.filter() const isDiffSaving = options && options.oldItem && !options.isNew; if (isDiffSaving) { const newObject = BaseModel.diffObjects(options.oldItem, o); newObject.type_ = o.type_; newObject.id = o.id; o = newObject; } o = this.filter(o); let queries = []; let saveQuery = this.saveQuery(o, options); let modelId = saveQuery.id; queries.push(saveQuery); if (options.nextQueries && options.nextQueries.length) { queries = queries.concat(options.nextQueries); } return this.db().transactionExecBatch(queries).then(() => { o = Object.assign({}, o); if (modelId) o.id = modelId; if ('updated_time' in saveQuery.modObject) o.updated_time = saveQuery.modObject.updated_time; if ('created_time' in saveQuery.modObject) o.created_time = saveQuery.modObject.created_time; if ('user_updated_time' in saveQuery.modObject) o.user_updated_time = saveQuery.modObject.user_updated_time; if ('user_created_time' in saveQuery.modObject) o.user_created_time = saveQuery.modObject.user_created_time; o = this.addModelMd(o); if (isDiffSaving) { for (let n in options.oldItem) { if (!options.oldItem.hasOwnProperty(n)) continue; if (n in o) continue; o[n] = options.oldItem[n]; } } return this.filter(o); }).catch((error) => { Log.error('Cannot save model', error); }); } static isNew(object, options) { if (options && ('isNew' in options)) { // options.isNew can be "auto" too if (options.isNew === true) return true; if (options.isNew === false) return false; } return !object.id; } static filterArray(models) { let output = []; for (let i = 0; i < models.length; i++) { output.push(this.filter(models[i])); } return output; } static filter(model) { if (!model) return model; let output = Object.assign({}, model); for (let n in output) { if (!output.hasOwnProperty(n)) continue; // The SQLite database doesn't have booleans so cast everything to int if (output[n] === true) { output[n] = 1; } else if (output[n] === false) { output[n] = 0; } else { const t = this.fieldType(n, Database.TYPE_UNKNOWN); if (t === Database.TYPE_INT) { output[n] = !n ? 0 : parseInt(output[n], 10); } } } return output; } static delete(id, options = null) { if (!id) throw new Error('Cannot delete object without an ID'); options = this.modOptions(options); return this.db().exec('DELETE FROM ' + this.tableName() + ' WHERE id = ?', [id]); } static batchDelete(ids, options = null) { if (!ids.length) return; options = this.modOptions(options); return this.db().exec('DELETE FROM ' + this.tableName() + ' WHERE id IN ("' + ids.join('","') + '")'); } static db() { if (!this.db_) throw new Error('Accessing database before it has been initialised'); return this.db_; } static isReady() { return !!this.db_; } } BaseModel.TYPE_NOTE = 1; BaseModel.TYPE_FOLDER = 2; BaseModel.TYPE_SETTING = 3; BaseModel.TYPE_RESOURCE = 4; BaseModel.TYPE_TAG = 5; BaseModel.TYPE_NOTE_TAG = 6; BaseModel.TYPE_SEARCH = 7; BaseModel.TYPE_ALARM = 8; BaseModel.TYPE_MASTER_KEY = 9; BaseModel.db_ = null; BaseModel.dispatch = function(o) {}; module.exports = BaseModel;
ReactNativeClient/lib/BaseModel.js
0
https://github.com/laurent22/joplin/commit/1d7f30d441e2c0fb82bfd0750d3a4203c9636390
[ 0.001202671672217548, 0.0002486378944013268, 0.00016141985543072224, 0.00017204039613716304, 0.00022440326574724168 ]
{ "id": 1, "code_window": [ "\t\tconst noteId = props.noteId;\n", "\t\tlet loadingNewNote = stateNoteId !== noteId;\n", "\t\tthis.lastLoadedNoteId_ = noteId;\n", "\t\tconst note = noteId ? await Note.load(noteId) : null;\n", "\t\tif (noteId !== this.lastLoadedNoteId_) return; // Race condition - current note was changed while this one was loading\n", "\t\tif (!options.noReloadIfLocalChanges && this.isModified()) return;\n", "\n", "\t\t// If the note hasn't been changed, exit now\n", "\t\tif (this.state.note && note) {\n", "\t\t\tlet diff = Note.diffObjects(this.state.note, note);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (options.noReloadIfLocalChanges && this.isModified()) return;\n" ], "file_path": "ElectronClient/app/gui/NoteText.jsx", "type": "replace", "edit_start_line_idx": 136 }
app/node_modules/ app/packageInfo.js dist/ app/lib/ app/gui/*.min.js .DS_Store
ElectronClient/.gitignore
0
https://github.com/laurent22/joplin/commit/1d7f30d441e2c0fb82bfd0750d3a4203c9636390
[ 0.00017326767556369305, 0.00017326767556369305, 0.00017326767556369305, 0.00017326767556369305, 0 ]
{ "id": 1, "code_window": [ "\t\tconst noteId = props.noteId;\n", "\t\tlet loadingNewNote = stateNoteId !== noteId;\n", "\t\tthis.lastLoadedNoteId_ = noteId;\n", "\t\tconst note = noteId ? await Note.load(noteId) : null;\n", "\t\tif (noteId !== this.lastLoadedNoteId_) return; // Race condition - current note was changed while this one was loading\n", "\t\tif (!options.noReloadIfLocalChanges && this.isModified()) return;\n", "\n", "\t\t// If the note hasn't been changed, exit now\n", "\t\tif (this.state.note && note) {\n", "\t\t\tlet diff = Note.diffObjects(this.state.note, note);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (options.noReloadIfLocalChanges && this.isModified()) return;\n" ], "file_path": "ElectronClient/app/gui/NoteText.jsx", "type": "replace", "edit_start_line_idx": 136 }
const { BaseCommand } = require('./base-command.js'); const { app } = require('./app.js'); const { _ } = require('lib/locale.js'); const { OneDriveApiNodeUtils } = require('./onedrive-api-node-utils.js'); const Setting = require('lib/models/Setting.js'); const BaseItem = require('lib/models/BaseItem.js'); const { Synchronizer } = require('lib/synchronizer.js'); const { reg } = require('lib/registry.js'); const { cliUtils } = require('./cli-utils.js'); const md5 = require('md5'); const locker = require('proper-lockfile'); const fs = require('fs-extra'); const osTmpdir = require('os-tmpdir'); class Command extends BaseCommand { constructor() { super(); this.syncTargetId_ = null; this.releaseLockFn_ = null; this.oneDriveApiUtils_ = null; } usage() { return 'sync'; } description() { return _('Synchronises with remote storage.'); } options() { return [ ['--target <target>', _('Sync to provided target (defaults to sync.target config value)')], ]; } static lockFile(filePath) { return new Promise((resolve, reject) => { locker.lock(filePath, { stale: 1000 * 60 * 5 }, (error, release) => { if (error) { reject(error); return; } resolve(release); }); }); } static isLocked(filePath) { return new Promise((resolve, reject) => { locker.check(filePath, (error, isLocked) => { if (error) { reject(error); return; } resolve(isLocked); }); }); } async doAuth(syncTargetId) { const syncTarget = reg.syncTarget(this.syncTargetId_); this.oneDriveApiUtils_ = new OneDriveApiNodeUtils(syncTarget.api()); const auth = await this.oneDriveApiUtils_.oauthDance({ log: (...s) => { return this.stdout(...s); } }); this.oneDriveApiUtils_ = null; return auth; } cancelAuth() { if (this.oneDriveApiUtils_) { this.oneDriveApiUtils_.cancelOAuthDance(); return; } } doingAuth() { return !!this.oneDriveApiUtils_; } async action(args) { this.releaseLockFn_ = null; // Lock is unique per profile/database const lockFilePath = osTmpdir() + '/synclock_' + md5(Setting.value('profileDir')); if (!await fs.pathExists(lockFilePath)) await fs.writeFile(lockFilePath, 'synclock'); try { if (await Command.isLocked(lockFilePath)) throw new Error(_('Synchronisation is already in progress.')); this.releaseLockFn_ = await Command.lockFile(lockFilePath); } catch (error) { if (error.code == 'ELOCKED') { const msg = _('Lock file is already being hold. If you know that no synchronisation is taking place, you may delete the lock file at "%s" and resume the operation.', error.file); this.stdout(msg); return; } throw error; } const cleanUp = () => { cliUtils.redrawDone(); if (this.releaseLockFn_) { this.releaseLockFn_(); this.releaseLockFn_ = null; } }; try { this.syncTargetId_ = Setting.value('sync.target'); if (args.options.target) this.syncTargetId_ = args.options.target; const syncTarget = reg.syncTarget(this.syncTargetId_); if (!syncTarget.isAuthenticated()) { app().gui().showConsole(); app().gui().maximizeConsole(); const auth = await this.doAuth(this.syncTargetId_); Setting.setValue('sync.' + this.syncTargetId_ + '.auth', auth ? JSON.stringify(auth) : null); if (!auth) { this.stdout(_('Authentication was not completed (did not receive an authentication token).')); return cleanUp(); } } const sync = await syncTarget.synchronizer(); let options = { onProgress: (report) => { let lines = Synchronizer.reportToLines(report); if (lines.length) cliUtils.redraw(lines.join(' ')); }, onMessage: (msg) => { cliUtils.redrawDone(); this.stdout(msg); }, }; this.stdout(_('Synchronisation target: %s (%s)', Setting.enumOptionLabel('sync.target', this.syncTargetId_), this.syncTargetId_)); if (!sync) throw new Error(_('Cannot initialize synchroniser.')); this.stdout(_('Starting synchronisation...')); const contextKey = 'sync.' + this.syncTargetId_ + '.context'; let context = Setting.value(contextKey); context = context ? JSON.parse(context) : {}; options.context = context; try { let newContext = await sync.start(options); Setting.setValue(contextKey, JSON.stringify(newContext)); } catch (error) { if (error.code == 'alreadyStarted') { this.stdout(error.message); } else { throw error; } } await app().refreshCurrentFolder(); } catch (error) { cleanUp(); throw error; } cleanUp(); } async cancel() { if (this.doingAuth()) { this.cancelAuth(); return; } const syncTargetId = this.syncTargetId_ ? this.syncTargetId_ : Setting.value('sync.target'); cliUtils.redrawDone(); this.stdout(_('Cancelling... Please wait.')); const syncTarget = reg.syncTarget(syncTargetId); if (syncTarget.isAuthenticated()) { const sync = await syncTarget.synchronizer(); if (sync) await sync.cancel(); } else { if (this.releaseLockFn_) this.releaseLockFn_(); this.releaseLockFn_ = null; } this.syncTargetId_ = null; } cancellable() { return true; } } module.exports = Command;
CliClient/app/command-sync.js
0
https://github.com/laurent22/joplin/commit/1d7f30d441e2c0fb82bfd0750d3a4203c9636390
[ 0.0014266035286709666, 0.00023027186398394406, 0.00015735656779725105, 0.00017154356464743614, 0.0002675355935934931 ]
{ "id": 2, "code_window": [ "\n", "\t// Note has been deleted while user was modifying it. In that case, we\n", "\t// just save a new note by clearing the note ID.\n", "\tif (note.id && !(await shared.noteExists(note.id))) delete note.id;\n", "\n", "\t// reg.logger().info('Saving note: ', note);\n", "\n", "\tif (!note.parent_id) {\n", "\t\tlet folder = await Folder.defaultFolder();\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "ReactNativeClient/lib/components/shared/note-screen-shared.js", "type": "replace", "edit_start_line_idx": 19 }
const { reg } = require('lib/registry.js'); const Folder = require('lib/models/Folder.js'); const BaseModel = require('lib/BaseModel.js'); const Note = require('lib/models/Note.js'); const shared = {}; shared.noteExists = async function(noteId) { const existingNote = await Note.load(noteId); return !!existingNote; } shared.saveNoteButton_press = async function(comp) { let note = Object.assign({}, comp.state.note); // Note has been deleted while user was modifying it. In that case, we // just save a new note by clearing the note ID. if (note.id && !(await shared.noteExists(note.id))) delete note.id; // reg.logger().info('Saving note: ', note); if (!note.parent_id) { let folder = await Folder.defaultFolder(); if (!folder) { //Log.warn('Cannot save note without a notebook'); return; } note.parent_id = folder.id; } let isNew = !note.id; let titleWasAutoAssigned = false; if (isNew && !note.title) { note.title = Note.defaultTitle(note); titleWasAutoAssigned = true; } // Save only the properties that have changed // let diff = null; // if (!isNew) { // diff = BaseModel.diffObjects(comp.state.lastSavedNote, note); // diff.type_ = note.type_; // diff.id = note.id; // } else { // diff = Object.assign({}, note); // } // const savedNote = await Note.save(diff); let options = {}; if (!isNew) { options.fields = BaseModel.diffObjectsFields(comp.state.lastSavedNote, note); } const savedNote = ('fields' in options) && !options.fields.length ? Object.assign({}, note) : await Note.save(note, { userSideValidation: true }); const stateNote = comp.state.note; // Re-assign any property that might have changed during saving (updated_time, etc.) note = Object.assign(note, savedNote); if (stateNote) { // But we preserve the current title and body because // the user might have changed them between the time // saveNoteButton_press was called and the note was // saved (it's done asynchronously). // // If the title was auto-assigned above, we don't restore // it from the state because it will be empty there. if (!titleWasAutoAssigned) note.title = stateNote.title; note.body = stateNote.body; } comp.setState({ lastSavedNote: Object.assign({}, note), note: note, }); if (isNew) Note.updateGeolocation(note.id); comp.refreshNoteMetadata(); } shared.saveOneProperty = async function(comp, name, value) { let note = Object.assign({}, comp.state.note); // Note has been deleted while user was modifying it. In that, we // just save a new note by clearing the note ID. if (note.id && !(await shared.noteExists(note.id))) delete note.id; // reg.logger().info('Saving note property: ', note.id, name, value); if (note.id) { let toSave = { id: note.id }; toSave[name] = value; toSave = await Note.save(toSave); note[name] = toSave[name]; comp.setState({ lastSavedNote: Object.assign({}, note), note: note, }); } else { note[name] = value; comp.setState({ note: note }); } } shared.noteComponent_change = function(comp, propName, propValue) { let note = Object.assign({}, comp.state.note); note[propName] = propValue; comp.setState({ note: note }); } shared.refreshNoteMetadata = async function(comp, force = null) { if (force !== true && !comp.state.showNoteMetadata) return; let noteMetadata = await Note.serializeAllProps(comp.state.note); comp.setState({ noteMetadata: noteMetadata }); } shared.isModified = function(comp) { if (!comp.state.note || !comp.state.lastSavedNote) return false; let diff = BaseModel.diffObjects(comp.state.note, comp.state.lastSavedNote); delete diff.type_; return !!Object.getOwnPropertyNames(diff).length; } shared.initState = async function(comp) { let note = null; let mode = 'view'; if (!comp.props.noteId) { note = comp.props.itemType == 'todo' ? Note.newTodo(comp.props.folderId) : Note.new(comp.props.folderId); mode = 'edit'; } else { note = await Note.load(comp.props.noteId); } const folder = Folder.byId(comp.props.folders, note.parent_id); comp.setState({ lastSavedNote: Object.assign({}, note), note: note, mode: mode, folder: folder, isLoading: false, }); comp.lastLoadedNoteId_ = note ? note.id : null; } shared.showMetadata_onPress = function(comp) { comp.setState({ showNoteMetadata: !comp.state.showNoteMetadata }); comp.refreshNoteMetadata(true); } shared.toggleIsTodo_onPress = function(comp) { let newNote = Note.toggleIsTodo(comp.state.note); let newState = { note: newNote }; comp.setState(newState); } module.exports = shared;
ReactNativeClient/lib/components/shared/note-screen-shared.js
1
https://github.com/laurent22/joplin/commit/1d7f30d441e2c0fb82bfd0750d3a4203c9636390
[ 0.997668445110321, 0.28124117851257324, 0.0003342432319186628, 0.056818652898073196, 0.404719740152359 ]
{ "id": 2, "code_window": [ "\n", "\t// Note has been deleted while user was modifying it. In that case, we\n", "\t// just save a new note by clearing the note ID.\n", "\tif (note.id && !(await shared.noteExists(note.id))) delete note.id;\n", "\n", "\t// reg.logger().info('Saving note: ', note);\n", "\n", "\tif (!note.parent_id) {\n", "\t\tlet folder = await Folder.defaultFolder();\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "ReactNativeClient/lib/components/shared/note-screen-shared.js", "type": "replace", "edit_start_line_idx": 19 }
const { _ } = require('lib/locale.js'); const { reg } = require('lib/registry.js'); class BaseCommand { constructor() { this.stdout_ = null; this.prompt_ = null; } usage() { throw new Error('Usage not defined'); } encryptionCheck(item) { if (item && item.encryption_applied) throw new Error(_('Cannot change encrypted item')); } description() { throw new Error('Description not defined'); } async action(args) { throw new Error('Action not defined'); } compatibleUis() { return ['cli', 'gui']; } supportsUi(ui) { return this.compatibleUis().indexOf(ui) >= 0; } aliases() { return []; } options() { return []; } hidden() { return false; } enabled() { return true; } cancellable() { return false; } async cancel() {} name() { let r = this.usage().split(' '); return r[0]; } setDispatcher(fn) { this.dispatcher_ = fn; } dispatch(action) { if (!this.dispatcher_) throw new Error('Dispatcher not defined'); return this.dispatcher_(action); } setStdout(fn) { this.stdout_ = fn; } stdout(text) { if (this.stdout_) this.stdout_(text); } setPrompt(fn) { this.prompt_ = fn; } async prompt(message, options = null) { if (!this.prompt_) throw new Error('Prompt is undefined'); return await this.prompt_(message, options); } metadata() { return { name: this.name(), usage: this.usage(), options: this.options(), hidden: this.hidden(), }; } logger() { return reg.logger(); } } module.exports = { BaseCommand };
CliClient/app/base-command.js
0
https://github.com/laurent22/joplin/commit/1d7f30d441e2c0fb82bfd0750d3a4203c9636390
[ 0.0010770817752927542, 0.0002664804342202842, 0.00016382671310566366, 0.00017580055282451212, 0.00025871896650642157 ]
{ "id": 2, "code_window": [ "\n", "\t// Note has been deleted while user was modifying it. In that case, we\n", "\t// just save a new note by clearing the note ID.\n", "\tif (note.id && !(await shared.noteExists(note.id))) delete note.id;\n", "\n", "\t// reg.logger().info('Saving note: ', note);\n", "\n", "\tif (!note.parent_id) {\n", "\t\tlet folder = await Folder.defaultFolder();\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "ReactNativeClient/lib/components/shared/note-screen-shared.js", "type": "replace", "edit_start_line_idx": 19 }
const React = require('react'); const { connect } = require('react-redux'); const { reg } = require('lib/registry.js'); const Folder = require('lib/models/Folder.js'); const { bridge } = require('electron').remote.require('./bridge'); const { Header } = require('./Header.min.js'); const { themeStyle } = require('../theme.js'); const { _ } = require('lib/locale.js'); const { filename, basename } = require('lib/path-utils.js'); const { importEnex } = require('lib/import-enex'); class ImportScreenComponent extends React.Component { componentWillMount() { this.setState({ doImport: true, filePath: this.props.filePath, messages: [], }); } componentWillReceiveProps(newProps) { if (newProps.filePath) { this.setState({ doImport: true, filePath: newProps.filePath, messages: [], }); this.doImport(); } } componentDidMount() { if (this.state.filePath && this.state.doImport) { this.doImport(); } } addMessage(key, text) { const messages = this.state.messages.slice(); let found = false; messages.push({ key: key, text: text }); this.setState({ messages: messages }); } uniqueMessages() { let output = []; const messages = this.state.messages.slice(); let foundKeys = []; for (let i = messages.length - 1; i >= 0; i--) { const msg = messages[i]; if (foundKeys.indexOf(msg.key) >= 0) continue; foundKeys.push(msg.key); output.unshift(msg); } return output; } async doImport() { const filePath = this.props.filePath; const folderTitle = await Folder.findUniqueFolderTitle(filename(filePath)); const messages = this.state.messages.slice(); this.addMessage('start', _('New notebook "%s" will be created and file "%s" will be imported into it', folderTitle, basename(filePath))); let lastProgress = ''; let progressCount = 0; const options = { onProgress: (progressState) => { let line = []; line.push(_('Found: %d.', progressState.loaded)); line.push(_('Created: %d.', progressState.created)); if (progressState.updated) line.push(_('Updated: %d.', progressState.updated)); if (progressState.skipped) line.push(_('Skipped: %d.', progressState.skipped)); if (progressState.resourcesCreated) line.push(_('Resources: %d.', progressState.resourcesCreated)); if (progressState.notesTagged) line.push(_('Tagged: %d.', progressState.notesTagged)); lastProgress = line.join(' '); this.addMessage('progress', lastProgress); }, onError: (error) => { // Don't display the error directly because most of the time it doesn't matter // (eg. for weird broken HTML, but the note is still imported) console.warn('When importing ENEX file', error); }, } const folder = await Folder.save({ title: folderTitle }); await importEnex(folder.id, filePath, options); this.addMessage('done', _('The notes have been imported: %s', lastProgress)); this.setState({ doImport: false }); } render() { const theme = themeStyle(this.props.theme); const style = this.props.style; const messages = this.uniqueMessages(); const messagesStyle = { padding: 10, fontSize: theme.fontSize, fontFamily: theme.fontFamily, backgroundColor: theme.backgroundColor, }; const headerStyle = { width: style.width, }; const messageComps = []; for (let i = 0; i < messages.length; i++) { messageComps.push(<div key={messages[i].key}>{messages[i].text}</div>); } return ( <div style={{}}> <Header style={headerStyle} /> <div style={messagesStyle}> {messageComps} </div> </div> ); } } const mapStateToProps = (state) => { return { theme: state.settings.theme, }; }; const ImportScreen = connect(mapStateToProps)(ImportScreenComponent); module.exports = { ImportScreen };
ElectronClient/app/gui/ImportScreen.jsx
0
https://github.com/laurent22/joplin/commit/1d7f30d441e2c0fb82bfd0750d3a4203c9636390
[ 0.7920393943786621, 0.05307384580373764, 0.00016695003432687372, 0.00017542814020998776, 0.1974971890449524 ]
{ "id": 2, "code_window": [ "\n", "\t// Note has been deleted while user was modifying it. In that case, we\n", "\t// just save a new note by clearing the note ID.\n", "\tif (note.id && !(await shared.noteExists(note.id))) delete note.id;\n", "\n", "\t// reg.logger().info('Saving note: ', note);\n", "\n", "\tif (!note.parent_id) {\n", "\t\tlet folder = await Folder.defaultFolder();\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "ReactNativeClient/lib/components/shared/note-screen-shared.js", "type": "replace", "edit_start_line_idx": 19 }
class SyncTargetRegistry { static classById(syncTargetId) { const info = SyncTargetRegistry.reg_[syncTargetId]; if (!info) throw new Error('Invalid id: ' + syncTargetId); return info.classRef; } static addClass(SyncTargetClass) { this.reg_[SyncTargetClass.id()] = { id: SyncTargetClass.id(), name: SyncTargetClass.targetName(), label: SyncTargetClass.label(), classRef: SyncTargetClass, }; } static nameToId(name) { for (let n in this.reg_) { if (!this.reg_.hasOwnProperty(n)) continue; if (this.reg_[n].name === name) return this.reg_[n].id; } throw new Error('Name not found: ' + name); } static idAndLabelPlainObject() { let output = {}; for (let n in this.reg_) { if (!this.reg_.hasOwnProperty(n)) continue; output[n] = this.reg_[n].label; } return output; } } SyncTargetRegistry.reg_ = {}; module.exports = SyncTargetRegistry;
ReactNativeClient/lib/SyncTargetRegistry.js
0
https://github.com/laurent22/joplin/commit/1d7f30d441e2c0fb82bfd0750d3a4203c9636390
[ 0.00017254671547561884, 0.00016723053704481572, 0.00015779274690430611, 0.00016929133562371135, 0.000005626972779282369 ]
{ "id": 3, "code_window": [ "\tif (!note.parent_id) {\n", "\t\tlet folder = await Folder.defaultFolder();\n", "\t\tif (!folder) {\n", "\t\t\t//Log.warn('Cannot save note without a notebook');\n", "\t\t\treturn;\n", "\t\t}\n", "\t\tnote.parent_id = folder.id;\n", "\t}\n", "\n", "\tlet isNew = !note.id;\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (!folder) return;\n" ], "file_path": "ReactNativeClient/lib/components/shared/note-screen-shared.js", "type": "replace", "edit_start_line_idx": 23 }
const { reg } = require('lib/registry.js'); const Folder = require('lib/models/Folder.js'); const BaseModel = require('lib/BaseModel.js'); const Note = require('lib/models/Note.js'); const shared = {}; shared.noteExists = async function(noteId) { const existingNote = await Note.load(noteId); return !!existingNote; } shared.saveNoteButton_press = async function(comp) { let note = Object.assign({}, comp.state.note); // Note has been deleted while user was modifying it. In that case, we // just save a new note by clearing the note ID. if (note.id && !(await shared.noteExists(note.id))) delete note.id; // reg.logger().info('Saving note: ', note); if (!note.parent_id) { let folder = await Folder.defaultFolder(); if (!folder) { //Log.warn('Cannot save note without a notebook'); return; } note.parent_id = folder.id; } let isNew = !note.id; let titleWasAutoAssigned = false; if (isNew && !note.title) { note.title = Note.defaultTitle(note); titleWasAutoAssigned = true; } // Save only the properties that have changed // let diff = null; // if (!isNew) { // diff = BaseModel.diffObjects(comp.state.lastSavedNote, note); // diff.type_ = note.type_; // diff.id = note.id; // } else { // diff = Object.assign({}, note); // } // const savedNote = await Note.save(diff); let options = {}; if (!isNew) { options.fields = BaseModel.diffObjectsFields(comp.state.lastSavedNote, note); } const savedNote = ('fields' in options) && !options.fields.length ? Object.assign({}, note) : await Note.save(note, { userSideValidation: true }); const stateNote = comp.state.note; // Re-assign any property that might have changed during saving (updated_time, etc.) note = Object.assign(note, savedNote); if (stateNote) { // But we preserve the current title and body because // the user might have changed them between the time // saveNoteButton_press was called and the note was // saved (it's done asynchronously). // // If the title was auto-assigned above, we don't restore // it from the state because it will be empty there. if (!titleWasAutoAssigned) note.title = stateNote.title; note.body = stateNote.body; } comp.setState({ lastSavedNote: Object.assign({}, note), note: note, }); if (isNew) Note.updateGeolocation(note.id); comp.refreshNoteMetadata(); } shared.saveOneProperty = async function(comp, name, value) { let note = Object.assign({}, comp.state.note); // Note has been deleted while user was modifying it. In that, we // just save a new note by clearing the note ID. if (note.id && !(await shared.noteExists(note.id))) delete note.id; // reg.logger().info('Saving note property: ', note.id, name, value); if (note.id) { let toSave = { id: note.id }; toSave[name] = value; toSave = await Note.save(toSave); note[name] = toSave[name]; comp.setState({ lastSavedNote: Object.assign({}, note), note: note, }); } else { note[name] = value; comp.setState({ note: note }); } } shared.noteComponent_change = function(comp, propName, propValue) { let note = Object.assign({}, comp.state.note); note[propName] = propValue; comp.setState({ note: note }); } shared.refreshNoteMetadata = async function(comp, force = null) { if (force !== true && !comp.state.showNoteMetadata) return; let noteMetadata = await Note.serializeAllProps(comp.state.note); comp.setState({ noteMetadata: noteMetadata }); } shared.isModified = function(comp) { if (!comp.state.note || !comp.state.lastSavedNote) return false; let diff = BaseModel.diffObjects(comp.state.note, comp.state.lastSavedNote); delete diff.type_; return !!Object.getOwnPropertyNames(diff).length; } shared.initState = async function(comp) { let note = null; let mode = 'view'; if (!comp.props.noteId) { note = comp.props.itemType == 'todo' ? Note.newTodo(comp.props.folderId) : Note.new(comp.props.folderId); mode = 'edit'; } else { note = await Note.load(comp.props.noteId); } const folder = Folder.byId(comp.props.folders, note.parent_id); comp.setState({ lastSavedNote: Object.assign({}, note), note: note, mode: mode, folder: folder, isLoading: false, }); comp.lastLoadedNoteId_ = note ? note.id : null; } shared.showMetadata_onPress = function(comp) { comp.setState({ showNoteMetadata: !comp.state.showNoteMetadata }); comp.refreshNoteMetadata(true); } shared.toggleIsTodo_onPress = function(comp) { let newNote = Note.toggleIsTodo(comp.state.note); let newState = { note: newNote }; comp.setState(newState); } module.exports = shared;
ReactNativeClient/lib/components/shared/note-screen-shared.js
1
https://github.com/laurent22/joplin/commit/1d7f30d441e2c0fb82bfd0750d3a4203c9636390
[ 0.9989190101623535, 0.30151769518852234, 0.00017673637194093317, 0.007658746559172869, 0.44979968667030334 ]
{ "id": 3, "code_window": [ "\tif (!note.parent_id) {\n", "\t\tlet folder = await Folder.defaultFolder();\n", "\t\tif (!folder) {\n", "\t\t\t//Log.warn('Cannot save note without a notebook');\n", "\t\t\treturn;\n", "\t\t}\n", "\t\tnote.parent_id = folder.id;\n", "\t}\n", "\n", "\tlet isNew = !note.id;\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (!folder) return;\n" ], "file_path": "ReactNativeClient/lib/components/shared/note-screen-shared.js", "type": "replace", "edit_start_line_idx": 23 }
const MarkdownIt = require('markdown-it'); const Entities = require('html-entities').AllHtmlEntities; const htmlentities = (new Entities()).encode; const Resource = require('lib/models/Resource.js'); const ModelCache = require('lib/ModelCache'); const { shim } = require('lib/shim.js'); const md5 = require('md5'); class MdToHtml { constructor(options = null) { if (!options) options = {}; this.supportsResourceLinks_ = !!options.supportsResourceLinks; this.loadedResources_ = {}; this.cachedContent_ = null; this.cachedContentKey_ = null; this.modelCache_ = new ModelCache(); // Must include last "/" this.resourceBaseUrl_ = ('resourceBaseUrl' in options) ? options.resourceBaseUrl : null; } makeContentKey(resources, body, style, options) { let k = []; for (let n in resources) { if (!resources.hasOwnProperty(n)) continue; const r = resources[n]; k.push(r.id); } k.push(md5(body)); k.push(md5(JSON.stringify(style))); k.push(md5(JSON.stringify(options))); return k.join('_'); } renderAttrs_(attrs) { if (!attrs) return ''; let output = []; for (let i = 0; i < attrs.length; i++) { const n = attrs[i][0]; const v = attrs[i].length >= 2 ? attrs[i][1] : null; if (n === 'alt' && !v) { continue; } else if (n === 'src') { output.push('src="' + htmlentities(v) + '"'); } else { output.push(n + '="' + (v ? htmlentities(v) : '') + '"'); } } return output.join(' '); } getAttr_(attrs, name) { for (let i = 0; i < attrs.length; i++) { if (attrs[i][0] === name) return attrs[i].length > 1 ? attrs[i][1] : null; } return null; } setAttr_(attrs, name, value) { for (let i = 0; i < attrs.length; i++) { if (attrs[i][0] === name) { attrs[i][1] = value; return attrs; } } attrs.push([name, value]); return attrs; } renderImage_(attrs, options) { const loadResource = async (id) => { console.info('Loading resource: ' + id); // Initially set to to an empty object to make // it clear that it is being loaded. Otherwise // it sometimes results in multiple calls to // loadResource() for the same resource. this.loadedResources_[id] = {}; const resource = await Resource.load(id); //const resource = await this.modelCache_.load(Resource, id); if (!resource) { // Can happen for example if an image is attached to a note, but the resource hasn't // been downloaded from the sync target yet. console.warn('Cannot load resource: ' + id); return; } this.loadedResources_[id] = resource; if (options.onResourceLoaded) options.onResourceLoaded(); } const title = this.getAttr_(attrs, 'title'); const href = this.getAttr_(attrs, 'src'); if (!Resource.isResourceUrl(href)) { return '<img title="' + htmlentities(title) + '" src="' + href + '"/>'; } const resourceId = Resource.urlToId(href); const resource = this.loadedResources_[resourceId]; if (!resource) { loadResource(resourceId); return ''; } if (!resource.id) return ''; // Resource is being loaded const mime = resource.mime ? resource.mime.toLowerCase() : ''; if (mime == 'image/png' || mime == 'image/jpg' || mime == 'image/jpeg' || mime == 'image/gif') { let src = './' + Resource.filename(resource); if (this.resourceBaseUrl_ !== null) src = this.resourceBaseUrl_ + src; let output = '<img title="' + htmlentities(title) + '" src="' + src + '"/>'; return output; } return '[Image: ' + htmlentities(resource.title) + ' (' + htmlentities(mime) + ')]'; } renderOpenLink_(attrs, options) { let href = this.getAttr_(attrs, 'href'); const text = this.getAttr_(attrs, 'text'); const isResourceUrl = Resource.isResourceUrl(href); const title = isResourceUrl ? this.getAttr_(attrs, 'title') : href; if (isResourceUrl && !this.supportsResourceLinks_) { // In mobile, links to local resources, such as PDF, etc. currently aren't supported. // Ideally they should be opened in the user's browser. return '<span style="opacity: 0.5">(Resource not yet supported: '; //+ htmlentities(text) + ']'; } else { if (isResourceUrl) { const resourceId = Resource.pathToId(href); href = 'joplin://' + resourceId; } const js = options.postMessageSyntax + "(" + JSON.stringify(href) + "); return false;"; let output = "<a title='" + htmlentities(title) + "' href='#' onclick='" + js + "'>"; return output; } } renderCloseLink_(attrs, options) { const href = this.getAttr_(attrs, 'href'); const isResourceUrl = Resource.isResourceUrl(href); if (isResourceUrl && !this.supportsResourceLinks_) { return ')</span>'; } else { return '</a>'; } } renderTokens_(tokens, options) { let output = []; let previousToken = null; let anchorAttrs = []; for (let i = 0; i < tokens.length; i++) { const t = tokens[i]; const nextToken = i < tokens.length ? tokens[i+1] : null; let tag = t.tag; let openTag = null; let closeTag = null; let attrs = t.attrs ? t.attrs : []; const isCodeBlock = tag === 'code' && t.block; // if (t.map) attrs.push(['data-map', t.map.join(':')]); if (previousToken && previousToken.tag === 'li' && tag === 'p') { // Markdown-it render list items as <li><p>Text<p></li> which makes it // complicated to style and layout the HTML, so we remove this extra // <p> here and below in closeTag. openTag = null; } else if (tag && t.type.indexOf('_open') >= 0) { openTag = tag; } else if (tag && t.type.indexOf('_close') >= 0) { closeTag = tag; } else if (tag && t.type.indexOf('inline') >= 0) { openTag = tag; } else if (t.type === 'link_open') { openTag = 'a'; } else if (isCodeBlock) { openTag = 'pre'; } if (openTag) { if (openTag === 'a') { anchorAttrs.push(attrs); output.push(this.renderOpenLink_(attrs, options)); } else { const attrsHtml = this.renderAttrs_(attrs); output.push('<' + openTag + (attrsHtml ? ' ' + attrsHtml : '') + '>'); } } if (isCodeBlock) { const codeAttrs = ['code']; if (t.info) codeAttrs.push(t.info); // t.info contains the language when the token is a codeblock output.push('<code class="' + codeAttrs.join(' ') + '">'); } if (t.type === 'image') { if (t.content) attrs.push(['title', t.content]); output.push(this.renderImage_(attrs, options)); } else if (t.type === 'softbreak') { output.push('<br/>'); } else if (t.type === 'hr') { output.push('<hr/>'); } else { if (t.children) { const parsedChildren = this.renderTokens_(t.children, options); output = output.concat(parsedChildren); } else { if (t.content) { output.push(htmlentities(t.content)); } } } if (nextToken && nextToken.tag === 'li' && t.tag === 'p') { closeTag = null; } else if (t.type === 'link_close') { closeTag = 'a'; } else if (tag && t.type.indexOf('inline') >= 0) { closeTag = openTag; } else if (isCodeBlock) { closeTag = openTag; } if (isCodeBlock) output.push('</code>'); if (closeTag) { if (closeTag === 'a') { output.push(this.renderCloseLink_(anchorAttrs.pop(), options)); } else { output.push('</' + closeTag + '>'); } } previousToken = t; } return output.join(''); } render(body, style, options = null) { if (!options) options = {}; if (!options.postMessageSyntax) options.postMessageSyntax = 'postMessage'; if (!options.paddingBottom) options.paddingBottom = '0'; const cacheKey = this.makeContentKey(this.loadedResources_, body, style, options); if (this.cachedContentKey_ === cacheKey) return this.cachedContent_; const md = new MarkdownIt({ breaks: true, linkify: true, }); const env = {}; // Hack to make checkboxes clickable. Ideally, checkboxes should be parsed properly in // renderTokens_(), but for now this hack works. Marking it with HORRIBLE_HACK so // that it can be removed and replaced later on. const HORRIBLE_HACK = true; if (HORRIBLE_HACK) { let counter = -1; while (body.indexOf('- [ ]') >= 0 || body.indexOf('- [X]') >= 0) { body = body.replace(/- \[(X| )\]/, function(v, p1) { let s = p1 == ' ' ? 'NOTICK' : 'TICK'; counter++; return '- mJOPmCHECKBOXm' + s + 'm' + counter + 'm'; }); } } const tokens = md.parse(body, env); // console.info(body); // console.info(tokens); let renderedBody = this.renderTokens_(tokens, options); if (HORRIBLE_HACK) { let loopCount = 0; while (renderedBody.indexOf('mJOPm') >= 0) { renderedBody = renderedBody.replace(/mJOPmCHECKBOXm([A-Z]+)m(\d+)m/, function(v, type, index) { const js = options.postMessageSyntax + "('checkboxclick:" + type + ':' + index + "'); this.classList.contains('tick') ? this.classList.remove('tick') : this.classList.add('tick'); return false;"; return '<a href="#" onclick="' + js + '" class="checkbox ' + (type == 'NOTICK' ? '' : 'tick') + '"><span>' + '' + '</span></a>'; }); if (loopCount++ >= 9999) break; } } // https://necolas.github.io/normalize.css/ const normalizeCss = ` html{line-height:1.15;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}body{margin:0} article,aside,footer,header,nav,section{display:block}h1{font-size:2em;margin:.67em 0}hr{box-sizing:content-box;height:0;overflow:visible} pre{font-family:monospace,monospace;font-size:1em}a{background-color:transparent;-webkit-text-decoration-skip:objects} b,strong{font-weight:bolder}small{font-size:80%}img{border-style:none} `; const fontFamily = 'sans-serif'; const css = ` body { font-size: ` + style.htmlFontSize + `; color: ` + style.htmlColor + `; line-height: ` + style.htmlLineHeight + `; background-color: ` + style.htmlBackgroundColor + `; font-family: ` + fontFamily + `; padding-bottom: ` + options.paddingBottom + `; } p, h1, h2, h3, h4, h5, h6, ul, table { margin-top: 0; margin-bottom: 14px; } h1 { font-size: 1.5em; font-weight: bold; } h2 { font-size: 1.2em; font-weight: bold; } h3, h4, h5, h6 { font-size: 1em; font-weight: bold; } a { color: ` + style.htmlLinkColor + ` } ul { padding-left: 1.3em; } a.checkbox { display: inline-block; position: relative; top: .5em; text-decoration: none; width: 1.65em; /* Need to cut a bit the right border otherwise the SVG will display a black line */ height: 1.7em; margin-right: .3em; background-color: ` + style.htmlColor + `; /* Awesome Font square-o */ -webkit-mask: url("data:image/svg+xml;utf8,<svg viewBox='0 0 1792 1792' xmlns='http://www.w3.org/2000/svg'><path d='M1312 256h-832q-66 0-113 47t-47 113v832q0 66 47 113t113 47h832q66 0 113-47t47-113v-832q0-66-47-113t-113-47zm288 160v832q0 119-84.5 203.5t-203.5 84.5h-832q-119 0-203.5-84.5t-84.5-203.5v-832q0-119 84.5-203.5t203.5-84.5h832q119 0 203.5 84.5t84.5 203.5z'/></svg>"); } a.checkbox.tick { left: .1245em; /* square-o and check-square-o aren't exactly aligned so add this extra gap to align them */ /* Awesome Font check-square-o */ -webkit-mask: url("data:image/svg+xml;utf8,<svg viewBox='0 0 1792 1792' xmlns='http://www.w3.org/2000/svg'><path d='M1472 930v318q0 119-84.5 203.5t-203.5 84.5h-832q-119 0-203.5-84.5t-84.5-203.5v-832q0-119 84.5-203.5t203.5-84.5h832q63 0 117 25 15 7 18 23 3 17-9 29l-49 49q-10 10-23 10-3 0-9-2-23-6-45-6h-832q-66 0-113 47t-47 113v832q0 66 47 113t113 47h832q66 0 113-47t47-113v-254q0-13 9-22l64-64q10-10 23-10 6 0 12 3 20 8 20 29zm231-489l-814 814q-24 24-57 24t-57-24l-430-430q-24-24-24-57t24-57l110-110q24-24 57-24t57 24l263 263 647-647q24-24 57-24t57 24l110 110q24 24 24 57t-24 57z'/></svg>"); } table { border-collapse: collapse; } td, th { border: 1px solid silver; padding: .5em 1em .5em 1em; font-size: ` + style.htmlFontSize + `; color: ` + style.htmlColor + `; background-color: ` + style.htmlBackgroundColor + `; font-family: ` + fontFamily + `; } hr { border: none; border-bottom: 1px solid ` + style.htmlDividerColor + `; } img { width: auto; max-width: 100%; } `; const styleHtml = '<style>' + normalizeCss + "\n" + css + '</style>'; const output = styleHtml + renderedBody; this.cachedContent_ = output; this.cachedContentKey_ = cacheKey; return this.cachedContent_; } toggleTickAt(body, index) { let counter = -1; while (body.indexOf('- [ ]') >= 0 || body.indexOf('- [X]') >= 0) { counter++; body = body.replace(/- \[(X| )\]/, function(v, p1) { let s = p1 == ' ' ? 'NOTICK' : 'TICK'; if (index == counter) { s = s == 'NOTICK' ? 'TICK' : 'NOTICK'; } return '°°JOP°CHECKBOX°' + s + '°°'; }); } body = body.replace(/°°JOP°CHECKBOX°NOTICK°°/g, '- [ ]'); body = body.replace(/°°JOP°CHECKBOX°TICK°°/g, '- [X]'); return body; } handleCheckboxClick(msg, noteBody) { msg = msg.split(':'); let index = Number(msg[msg.length - 1]); let currentState = msg[msg.length - 2]; // Not really needed but keep it anyway return this.toggleTickAt(noteBody, index); } } module.exports = MdToHtml;
ReactNativeClient/lib/MdToHtml.js
0
https://github.com/laurent22/joplin/commit/1d7f30d441e2c0fb82bfd0750d3a4203c9636390
[ 0.005902890115976334, 0.0003104864154011011, 0.00016526324907317758, 0.0001731434604153037, 0.0008734155562706292 ]
{ "id": 3, "code_window": [ "\tif (!note.parent_id) {\n", "\t\tlet folder = await Folder.defaultFolder();\n", "\t\tif (!folder) {\n", "\t\t\t//Log.warn('Cannot save note without a notebook');\n", "\t\t\treturn;\n", "\t\t}\n", "\t\tnote.parent_id = folder.id;\n", "\t}\n", "\n", "\tlet isNew = !note.id;\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (!folder) return;\n" ], "file_path": "ReactNativeClient/lib/components/shared/note-screen-shared.js", "type": "replace", "edit_start_line_idx": 23 }
# OSX # .DS_Store # Xcode # build/ *.pbxuser !default.pbxuser *.mode1v3 !default.mode1v3 *.mode2v3 !default.mode2v3 *.perspectivev3 !default.perspectivev3 xcuserdata *.xccheckout *.moved-aside DerivedData *.hmap *.ipa *.xcuserstate project.xcworkspace # Android/IntelliJ # build/ .idea .gradle local.properties *.iml # node.js # node_modules/ npm-debug.log yarn-error.log # BUCK buck-out/ \.buckd/ *.keystore # fastlane # # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the # screenshots whenever they are needed. # For more information about the recommended setup visit: # https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Gitignore.md fastlane/report.xml fastlane/Preview.html fastlane/screenshots # This is generated: android/build* android/app/build*
ReactNativeClient/.gitignore
0
https://github.com/laurent22/joplin/commit/1d7f30d441e2c0fb82bfd0750d3a4203c9636390
[ 0.00017773175204638392, 0.00017324561486020684, 0.000169617313076742, 0.0001727643102640286, 0.0000029279985938046593 ]
{ "id": 3, "code_window": [ "\tif (!note.parent_id) {\n", "\t\tlet folder = await Folder.defaultFolder();\n", "\t\tif (!folder) {\n", "\t\t\t//Log.warn('Cannot save note without a notebook');\n", "\t\t\treturn;\n", "\t\t}\n", "\t\tnote.parent_id = folder.id;\n", "\t}\n", "\n", "\tlet isNew = !note.id;\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (!folder) return;\n" ], "file_path": "ReactNativeClient/lib/components/shared/note-screen-shared.js", "type": "replace", "edit_start_line_idx": 23 }
const React = require('react'); const Component = React.Component; const { ListView, View, Text, Button, StyleSheet } = require('react-native'); const { connect } = require('react-redux'); const { Log } = require('lib/log.js'); const { reg } = require('lib/registry.js'); const { ScreenHeader } = require('lib/components/screen-header.js'); const { time } = require('lib/time-utils'); const { themeStyle } = require('lib/components/global-style.js'); const { Logger } = require('lib/logger.js'); const { BaseScreenComponent } = require('lib/components/base-screen.js'); const { _ } = require('lib/locale.js'); class LogScreenComponent extends BaseScreenComponent { static navigationOptions(options) { return { header: null }; } constructor() { super(); const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => { return r1 !== r2; } }); this.state = { dataSource: ds, }; this.styles_ = {}; } styles() { const theme = themeStyle(this.props.theme); if (this.styles_[this.props.theme]) return this.styles_[this.props.theme]; this.styles_ = {}; let styles = { row: { flexDirection: 'row', paddingLeft: 1, paddingRight: 1, paddingTop:0, paddingBottom:0, }, rowText: { fontFamily: 'monospace', fontSize: 10, color: theme.color, }, }; styles.rowTextError = Object.assign({}, styles.rowText); styles.rowTextError.color = theme.colorError; styles.rowTextWarn = Object.assign({}, styles.rowText); styles.rowTextWarn.color = theme.colorWarn; this.styles_[this.props.theme] = StyleSheet.create(styles); return this.styles_[this.props.theme]; } componentWillMount() { this.resfreshLogEntries(); } resfreshLogEntries() { reg.logger().lastEntries(1000).then((entries) => { const newDataSource = this.state.dataSource.cloneWithRows(entries); this.setState({ dataSource: newDataSource }); }); } render() { let renderRow = (item) => { let textStyle = this.styles().rowText; if (item.level == Logger.LEVEL_WARN) textStyle = this.styles().rowTextWarn; if (item.level == Logger.LEVEL_ERROR) textStyle = this.styles().rowTextError; return ( <View style={this.styles().row}> <Text style={textStyle}>{time.formatMsToLocal(item.timestamp, 'MM-DDTHH:mm:ss') + ': ' + item.message}</Text> </View> ); } // `enableEmptySections` is to fix this warning: https://github.com/FaridSafi/react-native-gifted-listview/issues/39 return ( <View style={this.rootStyle(this.props.theme).root}> <ScreenHeader title={_('Log')}/> <ListView dataSource={this.state.dataSource} renderRow={renderRow} enableEmptySections={true} /> <Button title={_("Refresh")} onPress={() => { this.resfreshLogEntries(); }}/> </View> ); } } const LogScreen = connect( (state) => { return { theme: state.settings.theme, }; } )(LogScreenComponent) module.exports = { LogScreen };
ReactNativeClient/lib/components/screens/log.js
0
https://github.com/laurent22/joplin/commit/1d7f30d441e2c0fb82bfd0750d3a4203c9636390
[ 0.00017747889796737581, 0.00017259539163205773, 0.0001660117122810334, 0.00017426328849978745, 0.000003924015800294001 ]
{ "id": 4, "code_window": [ "\tif (isNew && !note.title) {\n", "\t\tnote.title = Note.defaultTitle(note);\n", "\t\ttitleWasAutoAssigned = true;\n", "\t}\n", "\n", "\t// Save only the properties that have changed\n", "\t// let diff = null;\n", "\t// if (!isNew) {\n", "\t// \tdiff = BaseModel.diffObjects(comp.state.lastSavedNote, note);\n", "\t// \tdiff.type_ = note.type_;\n", "\t// \tdiff.id = note.id;\n", "\t// } else {\n", "\t// \tdiff = Object.assign({}, note);\n", "\t// }\n", "\n", "\t// const savedNote = await Note.save(diff);\n", "\n", "\tlet options = {};\n", "\tif (!isNew) {\n", "\t\toptions.fields = BaseModel.diffObjectsFields(comp.state.lastSavedNote, note);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "ReactNativeClient/lib/components/shared/note-screen-shared.js", "type": "replace", "edit_start_line_idx": 38 }
const { reg } = require('lib/registry.js'); const Folder = require('lib/models/Folder.js'); const BaseModel = require('lib/BaseModel.js'); const Note = require('lib/models/Note.js'); const shared = {}; shared.noteExists = async function(noteId) { const existingNote = await Note.load(noteId); return !!existingNote; } shared.saveNoteButton_press = async function(comp) { let note = Object.assign({}, comp.state.note); // Note has been deleted while user was modifying it. In that case, we // just save a new note by clearing the note ID. if (note.id && !(await shared.noteExists(note.id))) delete note.id; // reg.logger().info('Saving note: ', note); if (!note.parent_id) { let folder = await Folder.defaultFolder(); if (!folder) { //Log.warn('Cannot save note without a notebook'); return; } note.parent_id = folder.id; } let isNew = !note.id; let titleWasAutoAssigned = false; if (isNew && !note.title) { note.title = Note.defaultTitle(note); titleWasAutoAssigned = true; } // Save only the properties that have changed // let diff = null; // if (!isNew) { // diff = BaseModel.diffObjects(comp.state.lastSavedNote, note); // diff.type_ = note.type_; // diff.id = note.id; // } else { // diff = Object.assign({}, note); // } // const savedNote = await Note.save(diff); let options = {}; if (!isNew) { options.fields = BaseModel.diffObjectsFields(comp.state.lastSavedNote, note); } const savedNote = ('fields' in options) && !options.fields.length ? Object.assign({}, note) : await Note.save(note, { userSideValidation: true }); const stateNote = comp.state.note; // Re-assign any property that might have changed during saving (updated_time, etc.) note = Object.assign(note, savedNote); if (stateNote) { // But we preserve the current title and body because // the user might have changed them between the time // saveNoteButton_press was called and the note was // saved (it's done asynchronously). // // If the title was auto-assigned above, we don't restore // it from the state because it will be empty there. if (!titleWasAutoAssigned) note.title = stateNote.title; note.body = stateNote.body; } comp.setState({ lastSavedNote: Object.assign({}, note), note: note, }); if (isNew) Note.updateGeolocation(note.id); comp.refreshNoteMetadata(); } shared.saveOneProperty = async function(comp, name, value) { let note = Object.assign({}, comp.state.note); // Note has been deleted while user was modifying it. In that, we // just save a new note by clearing the note ID. if (note.id && !(await shared.noteExists(note.id))) delete note.id; // reg.logger().info('Saving note property: ', note.id, name, value); if (note.id) { let toSave = { id: note.id }; toSave[name] = value; toSave = await Note.save(toSave); note[name] = toSave[name]; comp.setState({ lastSavedNote: Object.assign({}, note), note: note, }); } else { note[name] = value; comp.setState({ note: note }); } } shared.noteComponent_change = function(comp, propName, propValue) { let note = Object.assign({}, comp.state.note); note[propName] = propValue; comp.setState({ note: note }); } shared.refreshNoteMetadata = async function(comp, force = null) { if (force !== true && !comp.state.showNoteMetadata) return; let noteMetadata = await Note.serializeAllProps(comp.state.note); comp.setState({ noteMetadata: noteMetadata }); } shared.isModified = function(comp) { if (!comp.state.note || !comp.state.lastSavedNote) return false; let diff = BaseModel.diffObjects(comp.state.note, comp.state.lastSavedNote); delete diff.type_; return !!Object.getOwnPropertyNames(diff).length; } shared.initState = async function(comp) { let note = null; let mode = 'view'; if (!comp.props.noteId) { note = comp.props.itemType == 'todo' ? Note.newTodo(comp.props.folderId) : Note.new(comp.props.folderId); mode = 'edit'; } else { note = await Note.load(comp.props.noteId); } const folder = Folder.byId(comp.props.folders, note.parent_id); comp.setState({ lastSavedNote: Object.assign({}, note), note: note, mode: mode, folder: folder, isLoading: false, }); comp.lastLoadedNoteId_ = note ? note.id : null; } shared.showMetadata_onPress = function(comp) { comp.setState({ showNoteMetadata: !comp.state.showNoteMetadata }); comp.refreshNoteMetadata(true); } shared.toggleIsTodo_onPress = function(comp) { let newNote = Note.toggleIsTodo(comp.state.note); let newState = { note: newNote }; comp.setState(newState); } module.exports = shared;
ReactNativeClient/lib/components/shared/note-screen-shared.js
1
https://github.com/laurent22/joplin/commit/1d7f30d441e2c0fb82bfd0750d3a4203c9636390
[ 0.9981446266174316, 0.17907926440238953, 0.0001689597120275721, 0.004321781452745199, 0.3784090578556061 ]
{ "id": 4, "code_window": [ "\tif (isNew && !note.title) {\n", "\t\tnote.title = Note.defaultTitle(note);\n", "\t\ttitleWasAutoAssigned = true;\n", "\t}\n", "\n", "\t// Save only the properties that have changed\n", "\t// let diff = null;\n", "\t// if (!isNew) {\n", "\t// \tdiff = BaseModel.diffObjects(comp.state.lastSavedNote, note);\n", "\t// \tdiff.type_ = note.type_;\n", "\t// \tdiff.id = note.id;\n", "\t// } else {\n", "\t// \tdiff = Object.assign({}, note);\n", "\t// }\n", "\n", "\t// const savedNote = await Note.save(diff);\n", "\n", "\tlet options = {};\n", "\tif (!isNew) {\n", "\t\toptions.fields = BaseModel.diffObjectsFields(comp.state.lastSavedNote, note);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "ReactNativeClient/lib/components/shared/note-screen-shared.js", "type": "replace", "edit_start_line_idx": 38 }
# OSX # .DS_Store # Xcode # build/ *.pbxuser !default.pbxuser *.mode1v3 !default.mode1v3 *.mode2v3 !default.mode2v3 *.perspectivev3 !default.perspectivev3 xcuserdata *.xccheckout *.moved-aside DerivedData *.hmap *.ipa *.xcuserstate project.xcworkspace # Android/IntelliJ # build/ .idea .gradle local.properties *.iml # node.js # node_modules/ npm-debug.log yarn-error.log # BUCK buck-out/ \.buckd/ *.keystore # fastlane # # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the # screenshots whenever they are needed. # For more information about the recommended setup visit: # https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Gitignore.md fastlane/report.xml fastlane/Preview.html fastlane/screenshots # This is generated: android/build* android/app/build*
ReactNativeClient/.gitignore
0
https://github.com/laurent22/joplin/commit/1d7f30d441e2c0fb82bfd0750d3a4203c9636390
[ 0.00019479027832858264, 0.00017215468687936664, 0.00016483094077557325, 0.00016893788415472955, 0.000010331432349630632 ]