Skip to content

[WIP] Add css class name completions #90

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions djlsp/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ class WorkspaceIndex:
libraries: dict[str, Library] = field(default_factory=dict)
templates: dict[str, Template] = field(default_factory=dict)
global_template_context: dict[str, Variable] = field(default_factory=dict)
css_class_names: list = field(default_factory=list)

def update(self, django_data: dict):
self.file_watcher_globs = django_data.get(
Expand Down Expand Up @@ -121,3 +122,4 @@ def update(self, django_data: dict):
)
for name, type_ in django_data.get("global_template_context", {}).items()
}
self.css_class_names = django_data.get("css_class_names", [])
34 changes: 33 additions & 1 deletion djlsp/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,8 @@ def completions(self, line, character):
),
)
)
return []
# Check CSS
return self.get_css_class_name_completions(line, character)

def get_load_completions(self, match: Match, **kwargs):
prefix = match.group(1).split(" ")[-1]
Expand Down Expand Up @@ -558,6 +559,37 @@ def resolve_completion(item: CompletionItem):

return item

def get_css_class_name_completions(self, line, character):
# Flatten text to one line and remove Django template
one_line_html = "".join(self.document.lines)
one_line_html = re.sub(
r"\{\%.*?\%\}", lambda m: " " * len(m.group(0)), one_line_html
)
one_line_html = re.sub(
r"\{\{.*?\}\}", lambda m: " " * len(m.group(0)), one_line_html
)

abs_position = sum(len(self.document.lines[i]) for i in range(line)) + character
class_attr_pattern = re.compile(r'class=["\']([^"\']*)["\']', re.DOTALL)

for match in class_attr_pattern.finditer(one_line_html):
start_idx, end_idx = match.span(1)

if start_idx <= abs_position <= end_idx:
class_value = match.group(1)
relative_pos = abs_position - start_idx

prefix_match = re.search(r"\b[\w-]*$", class_value[:relative_pos])
prefix = prefix_match.group(0) if prefix_match else ""

return [
CompletionItem(label=class_name)
for class_name in self.workspace_index.css_class_names
if class_name.startswith(prefix)
]

return []

###################################################################################
# Hover
###################################################################################
Expand Down
20 changes: 20 additions & 0 deletions djlsp/scripts/django-collector.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@ def __init__(self, project_src_path):
self.libraries = {}
self.templates: dict[str, Template] = {}
self.global_template_context = {}
self.css_class_names = []

def collect(self):
self.file_watcher_globs = self.get_file_watcher_globs()
Expand All @@ -204,6 +205,7 @@ def collect(self):
self.urls = self.get_urls()
self.libraries = self.get_libraries()
self.global_template_context = self.get_global_template_context()
self.css_class_names = self.get_css_class_names()

# Third party collectors
self.collect_for_wagtail()
Expand All @@ -217,6 +219,7 @@ def to_json(self):
"libraries": self.libraries,
"templates": self.templates,
"global_template_context": self.global_template_context,
"css_class_names": self.css_class_names,
},
indent=4,
)
Expand Down Expand Up @@ -573,6 +576,23 @@ def collect_for_wagtail(self):
model.context_object_name
] = (model.__module__ + "." + model.__name__)

# CSS class names
# ---------------------------------------------------------------------------------
def get_css_class_names(self):
class_pattern = re.compile(r"\.(?!\d)([a-zA-Z0-9_-]+)")
class_names = set()

for finder in get_finders():
for path, file_storage in finder.list(None):
if path.endswith(".css") and not path.startswith("admin"):
try:
with file_storage.open(path, "r") as f:
content = f.read()
class_names.update(class_pattern.findall(content))
except Exception as e:
logger.error(f"Could not parse CSS file: {e}")
return list(class_names)


#######################################################################################
# CLI
Expand Down
3 changes: 3 additions & 0 deletions tests/django_test/test-static-folder/website.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.blog .item {
color: red;
}