summaryrefslogtreecommitdiff
path: root/tools/language-server/src/plugins/css/features/getIdClassCompletion.ts
blob: 45acb5ad63f50eddee89892e9baca0e17563fff2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { CompletionItem, CompletionItemKind, CompletionList } from 'vscode-languageserver';
import { AttributeContext } from '../../../core/documents/parseHtml';
import { CSSDocument } from '../CSSDocument';

export function getIdClassCompletion(cssDoc: CSSDocument, attributeContext: AttributeContext): CompletionList | null {
  const collectingType = getCollectingType(attributeContext);

  if (!collectingType) {
    return null;
  }
  const items = collectSelectors(cssDoc.stylesheet as CSSNode, collectingType);

  console.log('getIdClassCompletion items', items.length);
  return CompletionList.create(items);
}

function getCollectingType(attributeContext: AttributeContext): number | undefined {
  if (attributeContext.inValue) {
    if (attributeContext.name === 'class') {
      return NodeType.ClassSelector;
    }
    if (attributeContext.name === 'id') {
      return NodeType.IdentifierSelector;
    }
  } else if (attributeContext.name.startsWith('class:')) {
    return NodeType.ClassSelector;
  }
}

/**
 * incomplete see
 * https://github.com/microsoft/vscode-css-languageservice/blob/master/src/parser/cssNodes.ts#L14
 * The enum is not exported. we have to update this whenever it changes
 */
export enum NodeType {
  ClassSelector = 14,
  IdentifierSelector = 15,
}

export type CSSNode = {
  type: number;
  children: CSSNode[] | undefined;
  getText(): string;
};

export function collectSelectors(stylesheet: CSSNode, type: number) {
  const result: CSSNode[] = [];
  walk(stylesheet, (node) => {
    if (node.type === type) {
      result.push(node);
    }
  });

  return result.map(
    (node): CompletionItem => ({
      label: node.getText().substring(1),
      kind: CompletionItemKind.Keyword,
    })
  );
}

function walk(node: CSSNode, callback: (node: CSSNode) => void) {
  callback(node);
  if (node.children) {
    node.children.forEach((node) => walk(node, callback));
  }
}