Java Code Examples for com.intellij.lang.javascript.psi.JSFile

The following examples show how to use com.intellij.lang.javascript.psi.JSFile. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: intellij   Source File: BlazeJavascriptTestLocator.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
private static List<Location> findClosureTestCase(
    Project project, File file, @Nullable String testName) {
  VirtualFile virtualFile = VfsUtils.resolveVirtualFile(file, /* refreshIfNeeded= */ false);
  if (virtualFile == null) {
    return ImmutableList.of();
  }
  PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
  if (!(psiFile instanceof JSFile)) {
    return ImmutableList.of();
  }
  if (testName != null) {
    for (JSFunction function : PsiTreeUtil.findChildrenOfType(psiFile, JSFunction.class)) {
      if (Objects.equals(function.getName(), testName)) {
        return ImmutableList.of(new PsiLocation<>(function));
      }
    }
  }
  return ImmutableList.of(new PsiLocation<>(psiFile));
}
 
Example 2
Source Project: intellij   Source File: BlazeJavascriptTestEventsHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public String getTestFilter(Project project, List<Location<?>> testLocations) {
  WorkspaceRoot root = WorkspaceRoot.fromProject(project);
  String rootName = root.directory().getName();
  String filter =
      testLocations.stream()
          .map(Location::getPsiElement)
          .map(PsiElement::getContainingFile)
          .filter(JSFile.class::isInstance)
          .map(PsiFile::getVirtualFile)
          .map(root::workspacePathFor)
          .map(WorkspacePath::relativePath)
          .map(FileUtil::getNameWithoutExtension)
          .distinct()
          .map(name -> '^' + rootName + '/' + name + '$')
          .reduce((a, b) -> a + "|" + b)
          .orElse(null);
  return filter != null
      ? String.format(
          "%s=%s", BlazeFlags.TEST_FILTER, BlazeParametersListUtil.encodeParam(filter))
      : null;
}
 
Example 3
private static Icon getClosureTestIcon(
    Project project, Collection<Label> labels, JSFile file, JSFunction function) {
  WorkspaceRoot root = WorkspaceRoot.fromProject(project);
  WorkspacePath path = root.workspacePathFor(file.getVirtualFile());
  String relativePath = root.directory().getName() + '/' + path.relativePath();
  if (relativePath.endsWith(".js")) {
    relativePath = relativePath.substring(0, relativePath.lastIndexOf(".js"));
  }
  String urlSuffix =
      relativePath
          + SmRunnerUtils.TEST_NAME_PARTS_SPLITTER
          + function.getName()
          + SmRunnerUtils.TEST_NAME_PARTS_SPLITTER
          + relativePath; // redundant class name
  return labels.stream()
      .map(
          label ->
              SmRunnerUtils.GENERIC_TEST_PROTOCOL
                  + URLUtil.SCHEME_SEPARATOR
                  + label
                  + SmRunnerUtils.TEST_NAME_PARTS_SPLITTER
                  + urlSuffix)
      .map(url -> getTestStateIcon(url, project, /* isClass = */ false))
      .max(Comparator.comparingInt(iconPriorities::get))
      .orElse(TestState.Run);
}
 
Example 4
private static ImmutableList<JSFile> jsFilesFromDtsSymbol(
    ExecutionRootPathResolver pathResolver,
    LocalFileSystem lfs,
    PsiManager psiManager,
    PsiElement dtsElement) {
  while (dtsElement != null && !(dtsElement instanceof PsiFile)) {
    PsiElement comment =
        PsiTreeUtil.findSiblingBackward(dtsElement, JSTokenTypes.END_OF_LINE_COMMENT, null);
    if (comment != null) {
      Matcher matcher = SYMBOL_GENERATED_FROM_JS_COMMENT.matcher(comment.getText());
      if (matcher.find()) {
        JSFile file = pathToJsFile(pathResolver, lfs, psiManager, matcher.group(1));
        return file != null ? ImmutableList.of(file) : ImmutableList.of();
      }
    }
    dtsElement = dtsElement.getParent();
  }
  return ImmutableList.of();
}
 
Example 5
private static ImmutableList<JSLiteralExpression> getModuleDeclarations(
    ImmutableList<JSFile> jsFiles) {
  return findChildrenOfType(jsFiles, JSCallExpression.class).stream()
      .filter(
          call -> {
            JSExpression method = call.getMethodExpression();
            return method != null
                && (Objects.equals(method.getText(), "goog.provide")
                    || Objects.equals(method.getText(), "goog.module"));
          })
      .map(JSCallExpression::getArguments)
      .filter(a -> a.length == 1)
      .map(a -> a[0])
      .filter(JSLiteralExpression.class::isInstance)
      .map(JSLiteralExpression.class::cast)
      .filter(JSLiteralExpression::isQuotedLiteral)
      .collect(toImmutableList());
}
 
Example 6
public static String getEnvironment(PsiFile file) {
    if (file instanceof JSFile) {
        // for JS Files we have to check the kind of environment being used
        final Ref<String> envRef = new Ref<>();
        file.accept(new PsiRecursiveElementVisitor() {
            @Override
            public void visitElement(PsiElement element) {
                if (!isJSGraphQLLanguageInjectionTarget(element, envRef)) {
                    // no match yet, so keep visiting
                    super.visitElement(element);
                }
            }
        });
        final String environment = envRef.get();
        if (environment != null) {
            return environment;
        }
    } else if (file instanceof GraphQLFile) {
        final Ref<String> tag = new Ref<>();
        if (file.getContext() != null && isJSGraphQLLanguageInjectionTarget(file.getContext(), tag)) {
            return tag.get();
        }
    }
    // fallback is traditional GraphQL
    return GRAPHQL_ENVIRONMENT;
}
 
Example 7
@NotNull
@Override
public FormattingModel createModel(PsiElement element, CodeStyleSettings settings) {
    if(element instanceof JSFile || element.getContainingFile() instanceof JSFile) {
        final JSFile file = (JSFile)(element instanceof JSFile ? element : element.getContainingFile());
        file.putUserData(WANT_DEFAULT_FORMATTER_KEY, true);
        try {
            final FormattingModelBuilder formattingModelBuilder = LanguageFormatting.INSTANCE.forContext(file.getLanguage(), element);
            if (formattingModelBuilder != null) {
                final FormattingModel model = formattingModelBuilder.createModel(element, settings);
                final Block rootBlock = model.getRootBlock();
                return new DelegatingFormattingModel(model, new GraphQLBlockWrapper(rootBlock, null, element.getNode(), rootBlock.getWrap(), rootBlock.getAlignment(), createSpaceBuilder(settings, element), settings));
            }
        } finally {
            file.putUserData(WANT_DEFAULT_FORMATTER_KEY, null);
        }
    }
    throw new IllegalArgumentException("Unsupported element '" + element + "'. It must be an element in a JSFile with its own default formatter to support injected GraphQL formatting");
}
 
Example 8
@Override
public boolean isEngagedToFormat(PsiElement context) {
    if(context instanceof JSFile) {
        if(Boolean.TRUE.equals(context.getUserData(WANT_DEFAULT_FORMATTER_KEY))) {
            // we're looking up the default formatter at the moment
            return false;
        }
        Collection<JSStringTemplateExpression> templateExpressions = PsiTreeUtil.findChildrenOfType(context, JSStringTemplateExpression.class);
        for (JSStringTemplateExpression templateExpression : templateExpressions) {
            if(GraphQLLanguageInjectionUtil.isJSGraphQLLanguageInjectionTarget(templateExpression)) {
                return true;
            }
        }
    }
    return false;
}
 
Example 9
Source Project: idea-php-shopware-plugin   Source File: SnippetUtilTest.java    License: MIT License 6 votes vote down vote up
public void testSnippetsForBackend() {
    PsiFile psiFile = myFixture.configureByFile("snippets.js");

    Collection<ShopwareSnippet> snippetsInFile = SnippetUtil.getSnippetsInFile((JSFile) psiFile);

    assertNotNull(ContainerUtil.find(snippetsInFile, snippet ->
        "backend/foobar/namespace".equals(snippet.getNamespace()) && "start_accept".equals(snippet.getName())
    ));

    assertNotNull(ContainerUtil.find(snippetsInFile, snippet ->
        "backend/foobar".equals(snippet.getNamespace()) && "start_accept".equals(snippet.getName())
    ));

    assertNotNull(ContainerUtil.find(snippetsInFile, snippet ->
        "backend/foobar/namespace".equals(snippet.getNamespace()) && "filter_feature".equals(snippet.getName())
    ));

    assertNotNull(ContainerUtil.find(snippetsInFile, snippet ->
        "foobar".equals(snippet.getNamespace()) && "filter_feature".equals(snippet.getName())
    ));
}
 
Example 10
Source Project: consulo-unity3d   Source File: UnityScriptPsiSearcher.java    License: Apache License 2.0 6 votes vote down vote up
@RequiredReadAction
@Nonnull
@Override
public Collection<? extends DotNetTypeDeclaration> findTypesImpl(@Nonnull String key, @Nonnull GlobalSearchScope searchScope)
{
	if(DumbService.isDumb(myProject))
	{
		return Collections.emptyList();
	}

	Collection<JSFile> jsFiles = UnityScriptFileByNameIndex.getInstance().get(key, myProject, searchScope);
	JSFile jsFile = ContainerUtil.getFirstItem(jsFiles);
	if(jsFile == null)
	{
		return Collections.emptyList();
	}
	return Collections.singletonList(new UnityScriptDotNetTypeDeclaration(key, jsFile));
}
 
Example 11
@Nonnull
@Override
@RequiredReadAction
public Set<PsiElement> compute(@Nonnull final Project project,
		@Nullable final IndexBasedDotNetPsiSearcher searcher,
		@Nonnull final String indexKey,
		@Nonnull final String thisQName,
		@Nonnull final GlobalSearchScope scope)
{
	Set<PsiElement> elements = new LinkedHashSet<>();
	Collection<String> keys = UnityScriptFileByNameIndex.getInstance().getAllKeys(project);
	for(String key : keys)
	{
		ProgressManager.checkCanceled();
		Collection<JSFile> jsFiles = UnityScriptFileByNameIndex.getInstance().get(key, project, scope);
		for(JSFile jsFile : jsFiles)
		{
			elements.add(new UnityScriptDotNetTypeDeclaration(key, jsFile));
		}
	}
	return elements;
}
 
Example 12
Source Project: reasonml-idea-plugin   Source File: IconProvider.java    License: MIT License 5 votes vote down vote up
private static boolean isBsJsFile(PsiFile psiFile) {
    if (psiFile instanceof JSFile) {
        JSFile jsFile = (JSFile) psiFile;
        return jsFile.getName().endsWith("." + BsConstants.BS_JS_FILE_EXTENSION);
    }
    return false;
}
 
Example 13
@NotNull
@Override
public Collection<KeyUsagePsiElement> getUsages(PsiFile psiFile) {
    if(psiFile instanceof JSFile) {
        JsEnvironmentCallsVisitor visitor = new JsEnvironmentCallsVisitor();
        psiFile.acceptChildren(visitor);

        return visitor.getCollectedItems();
    }

    return Collections.emptyList();
}
 
Example 14
Source Project: intellij   Source File: BlazeJavascriptTestLocator.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private static List<Location> findJasmineTestCase(
    Project project, TargetIdeInfo target, String suiteName, @Nullable String testName) {
  if (!searchForJasmineSources.getValue()) {
    return ImmutableList.of();
  }
  BlazeProjectData projectData =
      BlazeProjectDataManager.getInstance(project).getBlazeProjectData();
  if (projectData == null) {
    return ImmutableList.of();
  }
  PsiManager psiManager = PsiManager.getInstance(project);
  return OutputArtifactResolver.resolveAll(
          project,
          projectData.getArtifactLocationDecoder(),
          getJasmineSources(projectData, target))
      .stream()
      .map(f -> VfsUtils.resolveVirtualFile(f, /* refreshIfNeeded= */ false))
      .filter(Objects::nonNull)
      .map(psiManager::findFile)
      .filter(JSFile.class::isInstance)
      .map(JSFile.class::cast)
      .map(JasmineFileStructureBuilder.getInstance()::buildTestFileStructure)
      .map(file -> findJasmineSuiteByName(file, suiteName))
      .filter(Objects::nonNull)
      .map(testSuite -> maybeFindJasmineTestCase(testSuite, testName))
      .map(AbstractJasmineElement::getEnclosingPsiElement)
      .map(PsiLocation::new)
      .collect(ImmutableList.toImmutableList());
}
 
Example 15
private static ImmutableList<Label> getWrapperTests(JSFile file) {
  return CachedValuesManager.getCachedValue(
      file,
      () -> {
        Project project = file.getProject();
        BlazeProjectData projectData =
            BlazeProjectDataManager.getInstance(project).getBlazeProjectData();
        if (projectData == null) {
          return Result.create(
              ImmutableList.of(), BlazeSyncModificationTracker.getInstance(project));
        }
        ImmutableMultimap<TargetKey, TargetKey> rdeps = ReverseDependencyMap.get(project);
        TargetMap targetMap = projectData.getTargetMap();
        return Result.create(
            SourceToTargetFinder.findTargetsForSourceFile(
                    project,
                    VfsUtil.virtualToIoFile(file.getVirtualFile()),
                    Optional.of(RuleType.TEST))
                .stream()
                .filter(t -> t.getKind() != null)
                .filter(t -> t.getKind().getLanguageClass() == LanguageClass.JAVASCRIPT)
                .map(t -> t.label)
                .map(TargetKey::forPlainTarget)
                .map(rdeps::get)
                .filter(Objects::nonNull)
                .flatMap(Collection::stream)
                .filter(
                    key -> {
                      TargetIdeInfo target = targetMap.get(key);
                      return target != null && target.getKind().isWebTest();
                    })
                .map(TargetKey::getLabel)
                .collect(ImmutableList.toImmutableList()),
            BlazeSyncModificationTracker.getInstance(project));
      });
}
 
Example 16
Source Project: intellij   Source File: JavascriptTestTargetHeuristic.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean matchesSource(
    Project project,
    TargetInfo target,
    @Nullable PsiFile sourcePsiFile,
    File sourceFile,
    @Nullable TestSize testSize) {
  Kind kind = target.getKind();
  return sourcePsiFile instanceof JSFile
      && kind != null
      && kind.getLanguageClass() == LanguageClass.JAVASCRIPT
      && kind.getRuleType() == RuleType.TEST;
}
 
Example 17
Source Project: intellij   Source File: JavascriptTestContextProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public RunConfigurationContext getTestContext(ConfigurationContext context) {
  JSFile file =
      Optional.of(context)
          .map(ConfigurationContext::getPsiLocation)
          .map(PsiElement::getContainingFile)
          .filter(JSFile.class::isInstance)
          .map(JSFile.class::cast)
          .orElse(null);
  if (file == null) {
    return null;
  }
  ListenableFuture<TargetInfo> targetFuture =
      TestTargetHeuristic.targetFutureForPsiElement(file, null);
  if (targetFuture == null) {
    return null;
  }
  targetFuture =
      Futures.transform(
          targetFuture,
          (target) ->
              target != null && ReadAction.compute(() -> isTestFile(file)) ? target : null,
          ApplicationManager.getApplication().isUnitTestMode()
              ? MoreExecutors.directExecutor()
              : PooledThreadExecutor.INSTANCE);
  return TestContext.builder(file, ExecutorType.DEBUG_UNSUPPORTED_TYPES)
      .setTarget(targetFuture)
      .setTestFilter(getTestFilter(file))
      .setDescription(file.getName())
      .build();
}
 
Example 18
Source Project: intellij   Source File: JavascriptTestContextProvider.java    License: Apache License 2.0 5 votes vote down vote up
/** jsunit_test can just be top level functions with a test prefix. */
private static boolean hasTopLevelTests(JSFile file) {
  return Arrays.stream(file.getChildren())
      .filter(JSFunction.class::isInstance)
      .map(JSFunction.class::cast)
      .map(JSFunction::getName)
      .filter(Objects::nonNull)
      .anyMatch(name -> name.startsWith("test"));
}
 
Example 19
Source Project: intellij   Source File: JavascriptTestContextProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * A closure test suite will contain
 *
 * <pre>goog.require('goog.testing.testSuite')</pre>
 *
 * and call the imported symbol as a top level statement.
 */
private static boolean isClosureTestSuite(JSFile file) {
  PsiElement testSuite = null;
  for (PsiElement element : file.getChildren()) {
    if (testSuite == null) {
      testSuite = findTestSuiteReference(element);
    } else {
      if (isTestSuiteCalled(testSuite, element)) {
        return true;
      }
    }
  }
  return false;
}
 
Example 20
private static ImmutableList<PsiElement> resolveToJs(
    ExecutionRootPathResolver pathResolver,
    LocalFileSystem lfs,
    PsiManager psiManager,
    boolean isConstructor,
    PsiElement dtsElement) {
  dtsElement = PsiTreeUtil.getParentOfType(dtsElement, JSQualifiedNamedElement.class, false);
  if (dtsElement == null) {
    return ImmutableList.of();
  }
  if (!TypeScriptUtil.isDefinitionFile(dtsElement.getContainingFile())) {
    return ImmutableList.of();
  }
  String qualifiedName = getDtsQualifiedName((JSQualifiedNamedElement) dtsElement);
  if (qualifiedName == null) {
    return ImmutableList.of();
  }
  ImmutableList<JSFile> jsFiles = jsFilesFromDtsSymbol(pathResolver, lfs, psiManager, dtsElement);
  if (jsFiles.isEmpty()) {
    return ImmutableList.of();
  }
  if (dtsElement instanceof TypeScriptModule) {
    String moduleName = getModuleName(qualifiedName);
    return isConstructor
        ? findChildrenOfType(jsFiles, JSFunction.class).stream()
            .filter(e -> isConstructorWithName(e, moduleName))
            .collect(toImmutableList())
        : getModuleDeclarations(jsFiles).stream()
            .filter(a -> Objects.equals(a.getStringValue(), moduleName))
            .collect(toImmutableList());
  }
  return getResolveCandidates(dtsElement, jsFiles).stream()
      .filter(e -> Objects.equals(getJsQualifiedName(e), qualifiedName))
      .collect(toImmutableList());
}
 
Example 21
private static ImmutableList<? extends JSQualifiedNamedElement> getResolveCandidates(
    PsiElement dtsElement, ImmutableList<JSFile> jsFiles) {
  if (dtsElement instanceof TypeScriptClass) {
    return Stream.concat(
            findChildrenOfType(jsFiles, JSClass.class).stream(),
            // Apparently you can declare a JS class with just a constructor function and
            // attach some properties to it.
            findChildrenOfType(jsFiles, JSFunction.class).stream())
        .collect(toImmutableList());
  } else if (dtsElement instanceof TypeScriptFunction) {
    TypeScriptFunction dtsFunction = (TypeScriptFunction) dtsElement;
    return findChildrenOfType(jsFiles, JSFunction.class).stream()
        .filter(f -> staticModifierEquals(f, dtsFunction))
        .collect(toImmutableList());
  } else if (dtsElement instanceof TypeScriptEnum) {
    return findChildrenOfType(jsFiles, JSObjectLiteralExpression.class).stream()
        .map(PsiElement::getParent)
        .filter(JSAssignmentExpression.class::isInstance)
        .map(PsiElement::getFirstChild)
        .filter(JSDefinitionExpression.class::isInstance)
        .map(JSDefinitionExpression.class::cast)
        .collect(toImmutableList());
  } else if (dtsElement instanceof TypeScriptEnumField) {
    return findChildrenOfType(jsFiles, JSProperty.class);
  }
  return ImmutableList.of();
}
 
Example 22
@Nullable
private static JSFile pathToJsFile(
    ExecutionRootPathResolver pathResolver,
    LocalFileSystem lfs,
    PsiManager psiManager,
    String path) {
  return Optional.of(path)
      .map(ExecutionRootPath::new)
      .map(pathResolver::resolveExecutionRootPath)
      .map(lfs::findFileByIoFile)
      .map(psiManager::findFile)
      .filter(JSFile.class::isInstance)
      .map(JSFile.class::cast)
      .orElse(null);
}
 
Example 23
/**
 * Usually, we can just compare {@link JSQualifiedNamedElement#getQualifiedName()}, but in
 * goog.module()s, the name "exports" replaces the actual exported symbol. E.g.,
 *
 * <pre>
 * goog.module('Foo');
 * exports.bar = goog.defineClass(null, { foo: function() {}});
 * </pre>
 *
 * creates a function with the qualified name of Foo.bar.foo.
 */
@Nullable
private static String getJsQualifiedName(JSQualifiedNamedElement jsElement) {
  String exportedName =
      Optional.ofNullable(
              PsiTreeUtil.getTopmostParentOfType(jsElement, JSAssignmentExpression.class))
          .map(JSAssignmentExpression::getDefinitionExpression)
          .map(JSQualifiedNamedElement::getQualifiedName)
          .filter(name -> name.equals("exports") || name.startsWith("exports."))
          .orElse(null);
  String qualifiedName = jsElement.getQualifiedName();
  if (qualifiedName == null || exportedName == null) {
    return qualifiedName;
  }
  String moduleName =
      Stream.of(jsElement)
          .map(PsiElement::getContainingFile)
          .map(JSFile.class::cast)
          .map(ImmutableList::of)
          // should be only one goog.module()
          .map(BlazeTypescriptGotoDeclarationHandler::getModuleDeclarations)
          .flatMap(Collection::stream)
          .findFirst()
          .map(JSLiteralExpression::getStringValue)
          .orElse(null);
  // if exports is already part of the element's qualified name, then the exported name is already
  // included, otherwise we have to include the exported name
  return qualifiedName.startsWith("exports")
      ? moduleName + qualifiedName.substring("exports".length())
      : moduleName + exportedName.substring("exports".length()) + '.' + qualifiedName;
}
 
Example 24
private static <T extends PsiElement> ImmutableList<T> findChildrenOfType(
    ImmutableList<JSFile> jsFiles, Class<? extends T> aClass) {
  return jsFiles.stream()
      .map(f -> PsiTreeUtil.findChildrenOfType(f, aClass))
      .flatMap(Collection::stream)
      .collect(toImmutableList());
}
 
Example 25
Source Project: idea-php-shopware-plugin   Source File: SnippetUtil.java    License: MIT License 5 votes vote down vote up
/**
 * This call should only used inside index process
 */
@NotNull
public static Collection<ShopwareSnippet> getSnippetsInFile(@NotNull JSFile file) {
    Collection<ShopwareSnippet> snippets = new ArrayList<>();
    visitSnippets(file, snippets::add);
    return snippets;
}
 
Example 26
@RequiredReadAction
@Nullable
@Override
public LineMarkerInfo getLineMarkerInfo(@Nonnull PsiElement element)
{
	if(element.getNode().getElementType() == JSTokenTypes.IDENTIFIER && element.getParent() instanceof JSReferenceExpression && element.getParent().getParent() instanceof JSFunction)
	{
		UnityFunctionManager functionManager = UnityFunctionManager.getInstance();
		Map<String, UnityFunctionManager.FunctionInfo> map = functionManager.getFunctionsByType().get(Unity3dTypes.UnityEngine.MonoBehaviour);
		if(map == null)
		{
			return null;
		}
		UnityFunctionManager.FunctionInfo functionInfo = map.get(element.getText());
		if(functionInfo == null)
		{
			return null;
		}
		Unity3dModuleExtension extension = ModuleUtilCore.getExtension(element, Unity3dModuleExtension.class);
		if(extension == null)
		{
			return null;
		}
		JSFunction jsFunction = (JSFunction) element.getParent().getParent();
		if(jsFunction.getParent() instanceof JSFile)
		{
			if(!isEqualParameters(functionInfo.getParameters(), jsFunction))
			{
				return null;
			}

			return new LineMarkerInfo<>(element, element.getTextRange(), Unity3dIcons.EventMethod, Pass.LINE_MARKERS, new ConstantFunction<>(functionInfo.getDescription()), null,
					GutterIconRenderer.Alignment.LEFT);
		}
	}
	return null;
}
 
Example 27
@RequiredReadAction
@Nonnull
private Collection<AbstractTreeNode> doModify(Collection<AbstractTreeNode> children, ViewSettings settings)
{
	Unity3dRootModuleExtension rootModuleExtension = Unity3dModuleExtensionUtil.getRootModuleExtension(myProject);
	if(rootModuleExtension == null)
	{
		return children;
	}

	List<AbstractTreeNode> nodes = new ArrayList<>(children.size());
	for(AbstractTreeNode child : children)
	{
		ProgressManager.checkCanceled();

		Object value = child.getValue();
		if(value instanceof JSFile && ((JSFile) value).getFileType() == JavaScriptFileType.INSTANCE)
		{
			Module moduleForPsiElement = ModuleUtilCore.findModuleForPsiElement((PsiElement) value);
			if(moduleForPsiElement != null)
			{
				nodes.add(new UnityScriptFileNode(myProject, (PsiFile) value, settings));
				continue;
			}
		}
		nodes.add(child);
	}
	return nodes;
}
 
Example 28
@RequiredReadAction
public UnityScriptDotNetTypeDeclaration(@Nonnull String nameWithoutExtension, @Nonnull JSFile file)
{
	super(file.getManager(), file.getLanguage());
	myNameWithoutExtension = nameWithoutExtension;
	myFile = file;
}
 
Example 29
@Nullable
@Override
public Info getInfo(PsiElement element) {
  if (!enableJavascriptRunLineMarkers.getValue()) {
    return null;
  }
  JSFile file =
      Optional.of(element)
          .filter(PsiElement::isValid)
          .filter(LeafPsiElement.class::isInstance)
          .map(LeafPsiElement.class::cast)
          .filter(e -> e.getElementType().equals(JSTokenTypes.IDENTIFIER))
          .map(PsiElement::getContainingFile)
          .filter(JSFile.class::isInstance)
          .map(JSFile.class::cast)
          .orElse(null);
  if (file == null) {
    return null;
  }
  Collection<Label> labels = getWrapperTests(file);
  if (labels.isEmpty()) {
    return null;
  }
  JsTestElementPath jasmineTestElement =
      CachedValuesManager.getCachedValue(
              file,
              () ->
                  Result.create(
                      JasmineFileStructureBuilder.getInstance().buildTestFileStructure(file),
                      file))
          .findTestElementPath(element);
  if (jasmineTestElement != null) {
    return new Info(
        getJasmineTestIcon(file.getProject(), labels, jasmineTestElement),
        null,
        ExecutorAction.getActions());
  }
  PsiElement parent = element.getParent();
  if (parent instanceof JSFunction && element.getText().startsWith("test")) {
    return new Info(
        getClosureTestIcon(file.getProject(), labels, file, (JSFunction) parent),
        null,
        ExecutorAction.getActions());
  }
  return null;
}
 
Example 30
Source Project: intellij   Source File: JavascriptTestContextProvider.java    License: Apache License 2.0 4 votes vote down vote up
private static boolean isTestFile(JSFile file) {
  return file.isTestFile() || hasTopLevelTests(file) || isClosureTestSuite(file);
}