Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
help-beta: Convert tabs syntax to equivalent MDX syntax.
Shubham Padia5bbb7ebd1a3e
diff --git a/tools/convert-help-center-docs-to-mdx b/tools/convert-help-center-docs-to-mdxindex 523970c7b65..8dbe77f88ee 100755--- a/tools/convert-help-center-docs-to-mdx+++ b/tools/convert-help-center-docs-to-mdx@@ -21,6 +21,8 @@ setup_path()os.environ["DJANGO_SETTINGS_MODULE"] = "zproject.settings"django.setup()+from zerver.lib.markdown.tabbed_sections import generate_content_blocks, parse_tabs+INDENT_SPACES = " "@@ -148,6 +150,66 @@ def replace_icons(markdown_string: str, import_statement_set: set[str]) -> str:return result+def convert_tab_syntax(markdown_string: str, import_statement_set: set[str]) -> str:+ """+ Convert our custom tab syntax to relevant MDX equivalent.+ This function is inspired from `tabbed_section.py`'s run method.+ """+ TABBED_SECTION_TEMPLATE = """<Tabs>+{blocks}+</Tabs>"""++ TAB_ITEM_TEMPLATE = """<TabItem label="{tab_label}">+{content}+</TabItem>"""++ def indent_content_inside_blocks(content_block: str) -> str:+ """+ The original function `generate_content_blocks` does no+ indenting, and we need the content in between our TabItems+ to be indented. This is bit of string manipulation, but it+ is a better alternative compared to duplicating the original+ function here just to indent.+ """+ content_block_lines = content_block.splitlines()+ result_lines = []+ for line in content_block_lines:+ if line.startswith(("<TabItem", "</TabItem>")):+ result_lines.append(line)+ else:+ result_lines.append(INDENT_SPACES + line)++ return "\n".join(result_lines)++ lines = markdown_string.splitlines()+ tab_section = parse_tabs(lines)+ while tab_section:+ if "tabs" in tab_section:+ content_blocks = generate_content_blocks(tab_section, lines, TAB_ITEM_TEMPLATE)+ content_blocks = indent_content_inside_blocks(content_blocks)+ content_blocks = indent(content_blocks, INDENT_SPACES)+ tabs_mdx = TABBED_SECTION_TEMPLATE.format(blocks=content_blocks)+ import_statement_set.add(+ "import { Tabs, TabItem } from '@astrojs/starlight/components'"+ )+ else:+ # This is the case where we don't have any tabs but we were+ # using the `start_tabs` and `end_tabs` syntax to create+ # a border around the instructions. We just put the content+ # as is in this case since we don't want to add that border+ # anymore.+ tabs_mdx = ("\n").join(+ lines[(tab_section["start_tabs_index"] + 1) : (tab_section["end_tabs_index"])]+ )++ start = tab_section["start_tabs_index"]+ end = tab_section["end_tabs_index"] + 1+ lines = [*lines[:start], tabs_mdx, *lines[end:]]+ tab_section = parse_tabs(lines)++ return "\n".join(lines)++def detab(text: str) -> tuple[str, str]:"""Remove a tab from the front of each line of the given text.@@ -297,12 +359,13 @@ def convert_help_center_file_to_mdx(import_statement_set: set[str] = set()result = fix_file_imports(result, import_statement_set, "./include")+ result = convert_admonitions_to_asides(result, import_statement_set, "../../components")+ result = convert_tab_syntax(result, import_statement_set)result = escape_curly_braces(result)result = fix_relative_path(result)result = replace_emoticon_translation_table(result, import_statement_set)result = replace_image_path(result, "../../../../static/images/help")result = replace_icons(result, import_statement_set)- result = convert_admonitions_to_asides(result, import_statement_set, "../../components")result = insert_imports(result, import_statement_set, 2)result = insert_frontmatter(result)return result@@ -328,11 +391,12 @@ def convert_include_file_to_mdx(import_statement_set: set[str] = set()result = fix_file_imports(result, import_statement_set, ".")+ result = convert_admonitions_to_asides(result, import_statement_set, "../../../components")+ result = convert_tab_syntax(result, import_statement_set)result = escape_curly_braces(result)result = fix_relative_path(result)result = replace_image_path(result, "../../../../../static/images/help")result = replace_icons(result, import_statement_set)- result = convert_admonitions_to_asides(result, import_statement_set, "../../../components")result = insert_imports(result, import_statement_set, 1)return resultdiff --git a/zerver/lib/markdown/tabbed_sections.py b/zerver/lib/markdown/tabbed_sections.pyindex da8b31ebe87..823abf19cdc 100644--- a/zerver/lib/markdown/tabbed_sections.py+++ b/zerver/lib/markdown/tabbed_sections.py@@ -140,13 +140,63 @@ class TabbedSectionsGenerator(Extension):)+def parse_tabs(lines: list[str]) -> dict[str, Any] | None:+ block: dict[str, Any] = {}+ for index, line in enumerate(lines):+ start_match = START_TABBED_SECTION_REGEX.search(line)+ if start_match:+ block["start_tabs_index"] = index++ tab_content_match = TAB_CONTENT_REGEX.search(line)+ if tab_content_match:+ block.setdefault("tabs", [])+ tab = {"start": index, "tab_key": tab_content_match.group(1)}+ block["tabs"].append(tab)++ end_match = END_TABBED_SECTION_REGEX.search(line)+ if end_match:+ block["end_tabs_index"] = index+ break+ return block+++def generate_content_blocks(+ tab_section: dict[str, Any], lines: list[str], tab_content_template: str+) -> str:+ tab_content_blocks = []+ for index, tab in enumerate(tab_section["tabs"]):+ start_index = tab["start"] + 1+ try:+ # If there are more tabs, we can use the starting index+ # of the next tab as the ending index of the previous one+ end_index = tab_section["tabs"][index + 1]["start"]+ except IndexError:+ # Otherwise, just use the end of the entire section+ end_index = tab_section["end_tabs_index"]++ content = "\n".join(lines[start_index:end_index]).strip()+ tab_content_block = tab_content_template.format(+ data_tab_key=tab["tab_key"],+ # This attribute is not used directly in this file here,+ # we need this for the current conversion script in for+ # help-beta where this function is being imported.+ tab_label=TAB_SECTION_LABELS[tab["tab_key"]],+ # Wrapping the content in two newlines is necessary here.+ # If we don't do this, the inner Markdown does not get+ # rendered properly.+ content=f"\n{content}\n",+ )+ tab_content_blocks.append(tab_content_block)+ return "\n".join(tab_content_blocks)++class TabbedSectionsPreprocessor(Preprocessor):def __init__(self, md: markdown.Markdown, config: Mapping[str, Any]) -> None:super().__init__(md)@overridedef run(self, lines: list[str]) -> list[str]:- tab_section = self.parse_tabs(lines)+ tab_section = parse_tabs(lines)while tab_section:if "tabs" in tab_section:tab_class = "has-tabs"@@ -159,7 +209,7 @@ class TabbedSectionsPreprocessor(Preprocessor):}]nav_bar = self.generate_nav_bar(tab_section)- content_blocks = self.generate_content_blocks(tab_section, lines)+ content_blocks = generate_content_blocks(tab_section, lines, DIV_TAB_CONTENT_TEMPLATE)rendered_tabs = TABBED_SECTION_TEMPLATE.format(tab_class=tab_class, nav_bar=nav_bar, blocks=content_blocks)@@ -167,32 +217,9 @@ class TabbedSectionsPreprocessor(Preprocessor):start = tab_section["start_tabs_index"]end = tab_section["end_tabs_index"] + 1lines = [*lines[:start], rendered_tabs, *lines[end:]]- tab_section = self.parse_tabs(lines)+ tab_section = parse_tabs(lines)return lines- def generate_content_blocks(self, tab_section: dict[str, Any], lines: list[str]) -> str:- tab_content_blocks = []- for index, tab in enumerate(tab_section["tabs"]):- start_index = tab["start"] + 1- try:- # If there are more tabs, we can use the starting index- # of the next tab as the ending index of the previous one- end_index = tab_section["tabs"][index + 1]["start"]- except IndexError:- # Otherwise, just use the end of the entire section- end_index = tab_section["end_tabs_index"]-- content = "\n".join(lines[start_index:end_index]).strip()- tab_content_block = DIV_TAB_CONTENT_TEMPLATE.format(- data_tab_key=tab["tab_key"],- # Wrapping the content in two newlines is necessary here.- # If we don't do this, the inner Markdown does not get- # rendered properly.- content=f"\n{content}\n",- )- tab_content_blocks.append(tab_content_block)- return "\n".join(tab_content_blocks)-def generate_nav_bar(self, tab_section: dict[str, Any]) -> str:li_elements = []for tab in tab_section["tabs"]:@@ -208,25 +235,6 @@ class TabbedSectionsPreprocessor(Preprocessor):return NAV_BAR_TEMPLATE.format(tabs="\n".join(li_elements))- def parse_tabs(self, lines: list[str]) -> dict[str, Any] | None:- block: dict[str, Any] = {}- for index, line in enumerate(lines):- start_match = START_TABBED_SECTION_REGEX.search(line)- if start_match:- block["start_tabs_index"] = index-- tab_content_match = TAB_CONTENT_REGEX.search(line)- if tab_content_match:- block.setdefault("tabs", [])- tab = {"start": index, "tab_key": tab_content_match.group(1)}- block["tabs"].append(tab)-- end_match = END_TABBED_SECTION_REGEX.search(line)- if end_match:- block["end_tabs_index"] = index- break- return block-def makeExtension(*args: Any, **kwargs: str) -> TabbedSectionsGenerator:return TabbedSectionsGenerator(**kwargs)