更改所选元素时不显示折叠

问题描述 投票:0回答:1

之前我问过如何从选择中大肆制作过滤器。这就是问题本身:

根据服务器端口更改路由列表(swagger)

在求解过程中,我确保过滤器有效:

enter image description here

但是我无意中发现了一个错误,如果我折叠并选择另一个元素,它不会显示:
enter image description here

也许我在某个地方错过了它,但我找不到它:

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Swagger UI Example</title>
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/5.10.3/swagger-ui.css" crossorigin="anonymous" referrerpolicy="no-referrer" />
      <style>
        body { background-color: #ffffff; font-family: Arial, sans-serif; }
      </style>
    </head>
    <body>
    <div id="swagger-ui"></div>
    <!-- Validator badge -->
    <img src="https://img.shields.io/badge/OpenAPI-Validator-green" alt="OpenAPI Validator Badge">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/5.10.3/swagger-ui-bundle.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/5.10.3/swagger-ui-standalone-preset.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script>
      // Example JSON data
      const openApiJson = {
      "openapi": "3.1.0",
      "info": {
        "title": "blue_traktor_api",
        "description": "This API handles various functionalities for USEPI, Icons, Dashboard, Settings, Patterns, Devices, Widgets, and more.",
        "version": "0.1.0",
        "contact": {
          "name": "API Support",
          "url": "",
          "email": ""
        }
      },
      "servers": [
        {
          "url": "http://localhost:8000",
          "description": "TCP server for main operations"
        },
        {
          "url": "ws://localhost:8080",
          "description": "WebSocket server for updated parameters"
        }
      ],
      "paths": {
        "/api/usepi/patterns/create": {
          "post": {
            "tags": [
              "patterns"
            ],
            "summary": "http://localhost:8000",
            "operationId": "createPattern",
            "requestBody": {
              "required": true,
              "content": {
                "application/json": {
                  "schema": {
                    "$ref": "#/components/schemas/RequestStructure_PatternRequest"
                  },
                  "examples": {
                    "PatternExample": {
                      "summary": "An example of a PatternRequest",
                      "value": {
                        "data": {
                          "id": null,
                          "title": "test",
                          "description": "test desc",
                          "icon": "http://localhost:8000/api/icons/Cтатическое оборудование/Статическое оборудование.svg",
                          "createDate": null,
                          "updateDate": null,
                          "favourite": false,
                          "data": {
                            "ID": {},
                            "QR-Code": {},
                            "Position": {},
                            "DeviceParams": {}
                          }
                        }
                      }
                    }
                  }
                }
              }
            },
            "responses": {
              "200": {
                "description": "Pattern created.",
                "content": {
                  "application/json": {
                    "schema": {
                      "$ref": "#/components/schemas/GoodResponse_Id"
                    }
                  }
                }
              },
              "500": {
                "description": "Internal Server Error",
                "content": {
                  "application/json": {
                    "schema": {
                      "$ref": "#/components/schemas/ErrorResponse"
                    }
                  }
                }
              }
            }
          }
        },
        "/api/widgets/get": {
          "post": {
            "tags": [
              "widgets"
            ],
            "summary": "ws://localhost:8080",
            "operationId": "getWidget",
            "servers": [
              {
                "url": "ws://localhost:8080"
              }
            ],
            "requestBody": {
              "required": true,
              "content": {
                "application/json": {
                  "schema": {
                    "$ref": "#/components/schemas/RequestStructure_Id"
                  }
                }
              }
            },
            "responses": {
              "200": {
                "description": "Widget details.",
                "content": {
                  "application/json": {
                    "schema": {
                      "$ref": "#/components/schemas/GoodResponse_GetWidgetResponse"
                    }
                  }
                }
              },
              "500": {
                "description": "Internal Server Error",
                "content": {
                  "application/json": {
                    "schema": {
                      "$ref": "#/components/schemas/ErrorResponse"
                    }
                  }
                }
              }
            }
          }
        },
        "components": {
          "schemas": {
            "PatternRequest": {
              "type": "object",
              "properties": {
                "id": {
                  "type": "string",
                  "nullable": true
                },
                "title": {
                  "type": "string",
                  "nullable": true
                },
                "description": {
                  "type": "string",
                  "nullable": true
                },
                "icon": {
                  "type": "string",
                  "nullable": true
                },
                "data": {
                  "type": "object",
                  "nullable": true
                },
                "favourite": {
                  "type": "boolean",
                  "nullable": true
                }
              }
            },
            "RequestStructure_PatternRequest": {
              "type": "object",
              "properties": {
                "data": {
                  "$ref": "#/components/schemas/PatternRequest"
                }
              }
            },
            "GoodResponse_Id": {
              "type": "object",
              "properties": {
                "statusCode": {
                  "type": "integer",
                  "format": "int32",
                  "enum": [
                    200
                  ]
                },
                "data": {
                  "$ref": "#/components/schemas/Id"
                }
              }
            },
            "Id": {
              "type": "object",
              "properties": {
                "id": {
                  "type": "string",
                  "nullable": true
                }
              }
            },
            "ErrorResponse": {
              "type": "object",
              "properties": {
                "statusCode": {
                  "type": "integer",
                  "format": "int32",
                  "enum": [
                    500
                  ]
                }
              }
            },
            "RequestStructure_Id": {
              "type": "object",
              "properties": {
                "data": {
                  "$ref": "#/components/schemas/Id"
                }
              }
            },
            "GoodResponse_GetWidgetResponse": {
              "type": "object",
              "properties": {
                "statusCode": {
                  "type": "integer",
                  "format": "int32",
                  "enum": [
                    200
                  ]
                },
                "data": {
                  "$ref": "#/components/schemas/GetWidgetResponse"
                }
              }
            },
            "GetWidgetResponse": {
              "type": "object",
              "properties": {
                "id": {
                  "type": "string"
                },
                "title": {
                  "type": "object"
                },
                "folderId": {
                  "type": "string",
                  "nullable": true
                },
                "icon": {
                  "type": "string",
                  "nullable": true
                },
                "data": {
                  "type": "object"
                },
                "type": {
                  "type": "string"
                }
              }
            }
          }
        }
      }
    };

      window.onload = function() {
        // Initialize Swagger UI with the JSON data
        const ui = SwaggerUIBundle({
          spec: openApiJson, // Using the JSON data
          dom_id: '#swagger-ui',
          deepLinking: true,
          presets: [
            SwaggerUIBundle.presets.apis,
            SwaggerUIStandalonePreset
          ],
          plugins: [
            SwaggerUIBundle.plugins.DownloadUrl
          ],
          layout: "StandaloneLayout"
        });
        window.ui = ui;

        // Function to filter elements based on selected value in dropdown
        function filterElements() {
          const selectElement = document.querySelector("#swagger-ui select");
          if (selectElement) {
            const selectedValue = selectElement.options[selectElement.selectedIndex].textContent.split(' - ')[0];
            const parentCatalogs = document.querySelectorAll("#swagger-ui .opblock-tag-section");

            parentCatalogs.forEach(parent => {
              let childVisible = false;
              const childElements = parent.querySelectorAll("[id^='operations-']:not([id^='operations-tag'])");
              childElements.forEach(childElement => {
                const summaryControl = childElement.querySelector(".opblock-summary-control > div > div");
                if (summaryControl) {
                  const summaryText = summaryControl.textContent.trim();
                  if (summaryText === selectedValue) {
                    childElement.style.display = ''; // Show element if it matches selected value
                    childVisible = true;
                  } else {
                    childElement.style.display = 'none'; // Hide element if it does not match
                  }
                }
              });

              // Hide parent element if no child elements are visible
              parent.style.display = childVisible ? '' : 'none';
            });
          }
        }

        // Event listener to detect changes in the dropdown and filter elements
        document.addEventListener('change', function(event) {
          const selectElement = document.querySelector("#swagger-ui select");
          if (event.target === selectElement) {
            filterElements();
          }
        });

        // MutationObserver to detect when the dropdown is added to the DOM and filter elements
        const observer = new MutationObserver(() => {
          const selectElement = document.querySelector("#swagger-ui select");
          if (selectElement) {
            filterElements();
            observer.disconnect(); // Stop observing once the dropdown is found and filtered
          }
        });

        // Start observing the DOM for changes
        observer.observe(document.querySelector('#swagger-ui'), { childList: true, subtree: true });
      };
    </script>
    </body>
    </html>

javascript swagger
1个回答
0
投票

问题在于,当单击压套中的父元素时,div 块的类发生了变化,需要单击按钮才能展开。并在每次更改所选项目时执行此操作。

但是,在代码片段中,由于某种原因第一次尝试公开该元素时不会起作用,但如果存在完整的链接而不是 url,则该规则将毫无问题地起作用。

感谢所有参与、帮助和感兴趣的人!

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Swagger UI</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/5.10.3/swagger-ui.css" crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/5.10.3/swagger-ui-bundle.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/5.10.3/swagger-ui-standalone-preset.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
  window.onload = function() {

    // Define the Swagger specification directly in the JavaScript code
    const swaggerSpec = {
      "openapi": "3.1.0",
      "info": {
        "title": "blue_traktor_api",
        "description": "This API handles various functionalities for USEPI, Icons, Dashboard, Settings, Patterns, Devices, Widgets, and more.",
        "version": "0.1.0",
        "contact": {
          "name": "API Support",
          "url": "",
          "email": ""
        }
      },
      "servers": [
        {
          "url": "http://localhost:8000",
          "description": "TCP server for main operations"
        },
        {
          "url": "ws://localhost:8080",
          "description": "WebSocket server for updated parameters"
        }
      ],
      "paths": {
        "/api/usepi/patterns/create": {
          "post": {
            "tags": ["patterns"],
            "summary": "http://localhost:8000",
            "operationId": "createPattern",
            "requestBody": {
              "required": true,
              "content": {
                "application/json": {
                  "schema": {
                    "$ref": "#/components/schemas/RequestStructure_PatternRequest"
                  },
                  "examples": {
                    "PatternExample": {
                      "summary": "An example of a PatternRequest",
                      "value": {
                        "data": {
                          "id": null,
                          "title": "test",
                          "description": "test desc",
                          "icon": "http://localhost:8000/api/icons/Cтатическое оборудование/Статическое оборудование.svg",
                          "createDate": null,
                          "updateDate": null,
                          "favourite": false,
                          "data": {
                            "ID": {},
                            "QR-Code": {},
                            "Position": {},
                            "DeviceParams": {}
                          }
                        }
                      }
                    }
                  }
                }
              }
            },
            "responses": {
              "200": {
                "description": "Pattern created.",
                "content": {
                  "application/json": {
                    "schema": {
                      "$ref": "#/components/schemas/GoodResponse_Id"
                    }
                  }
                }
              },
              "500": {
                "description": "Internal Server Error",
                "content": {
                  "application/json": {
                    "schema": {
                      "$ref": "#/components/schemas/ErrorResponse"
                    }
                  }
                }
              }
            }
          }
        },
        "/api/widgets/get": {
          "post": {
            "tags": ["widgets"],
            "summary": "ws://localhost:8080",
            "operationId": "getWidget",
            "servers": [
              {
                "url": "ws://localhost:8080"
              }
            ],
            "requestBody": {
              "required": true,
              "content": {
                "application/json": {
                  "schema": {
                    "$ref": "#/components/schemas/RequestStructure_Id"
                  }
                }
              }
            },
            "responses": {
              "200": {
                "description": "Widget details.",
                "content": {
                  "application/json": {
                    "schema": {
                      "$ref": "#/components/schemas/GoodResponse_GetWidgetResponse"
                    }
                  }
                }
              },
              "500": {
                "description": "Internal Server Error",
                "content": {
                  "application/json": {
                    "schema": {
                      "$ref": "#/components/schemas/ErrorResponse"
                    }
                  }
                }
              }
            }
          }
        }
      },
      "components": {
        "schemas": {
          "PatternRequest": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string",
                "nullable": true
              },
              "title": {
                "type": "string",
                "nullable": true
              },
              "description": {
                "type": "string",
                "nullable": true
              },
              "icon": {
                "type": "string",
                "nullable": true
              },
              "data": {
                "type": "object",
                "nullable": true
              },
              "favourite": {
                "type": "boolean",
                "nullable": true
              }
            }
          },
          "RequestStructure_PatternRequest": {
            "type": "object",
            "properties": {
              "data": {
                "$ref": "#/components/schemas/PatternRequest"
              }
            }
          },
          "GoodResponse_Id": {
            "type": "object",
            "properties": {
              "statusCode": {
                "type": "integer",
                "format": "int32",
                "enum": [200]
              },
              "data": {
                "$ref": "#/components/schemas/Id"
              }
            }
          },
          "Id": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string",
                "nullable": true
              }
            }
          },
          "ErrorResponse": {
            "type": "object",
            "properties": {
              "statusCode": {
                "type": "integer",
                "format": "int32",
                "enum": [500]
              }
            }
          },
          "RequestStructure_Id": {
            "type": "object",
            "properties": {
              "data": {
                "$ref": "#/components/schemas/Id"
              }
            }
          },
          "GoodResponse_GetWidgetResponse": {
            "type": "object",
            "properties": {
              "statusCode": {
                "type": "integer",
                "format": "int32",
                "enum": [200]
              },
              "data": {
                "$ref": "#/components/schemas/GetWidgetResponse"
              }
            }
          },
          "GetWidgetResponse": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string"
              },
              "title": {
                "type": "object"
              },
              "folderId": {
                "type": "string",
                "nullable": true
              },
              "icon": {
                "type": "string",
                "nullable": true
              },
              "data": {
                "type": "object"
              },
              "type": {
                "type": "string"
              }
            }
          }
        }
      }
    };

    // Initialize Swagger UI with the provided specification
    const ui = SwaggerUIBundle({
      spec: swaggerSpec,
      dom_id: '#swagger-ui',
      deepLinking: true,
      presets: [
        SwaggerUIBundle.presets.apis,
        SwaggerUIStandalonePreset
      ],
      plugins: [
        SwaggerUIBundle.plugins.DownloadUrl
      ],
      layout: "StandaloneLayout"
    });

    window.ui = ui;

    let isFiltering = false;

    // Function to expand hidden elements
    function expandHiddenElements() {
      // Select all parent elements with the class 'opblock-tag-section'
      const parentElements = document.querySelectorAll('.opblock-tag-section');

      parentElements.forEach(parent => {
        // Find the header of the parent element
        const header = parent.querySelector('h3.opblock-tag');
        const isExpanded = header.getAttribute('data-is-open') === 'true';

        // If the element is hidden, expand it
        if (!isExpanded) {
          const expandButton = header.querySelector('button.expand-operation');
          if (expandButton) {
            expandButton.click();
            console.log(`Expanding parent element: ${header.textContent}`);
          } else {
            console.log(`Expand button not found for parent element: ${header.textContent}`);
          }
        }
      });
    }

    // Function to filter elements based on the selected value in the dropdown
    function filterElements() {
      const selectElement = document.querySelector('#swagger-ui>section>div.swagger-ui>div:nth-child(2)>div.scheme-container>section>div>div>div>label>select');
      if (selectElement) {
        // Get the selected value from the dropdown
        const selectedValue = selectElement.options[selectElement.selectedIndex].textContent.split(' - ')[0];
        console.log("Selected value from dropdown:", selectedValue);

        // Find all parent catalogs
        const parentCatalogs = document.querySelectorAll('#swagger-ui>section>div.swagger-ui>div:nth-child(2)>div:nth-child(4)>section>div>span> div > h3');
        console.log("Parent catalogs found:", parentCatalogs.length);

        parentCatalogs.forEach(parent => {
          // Find the parent element
          const parentElement = parent.closest('div.opblock-tag-section');
          if (parentElement) {
            let childVisible = false;
            // Find all child elements that are not tagged with 'operations-tag'
            const childElements = parentElement.querySelectorAll("[id^='operations-']:not([id^='operations-tag'])");
            childElements.forEach(childElement => {
              const summaryControl = childElement.querySelector('button.opblock-summary-control > div > div');
              if (summaryControl) {
                const summaryText = summaryControl.textContent.trim();
                // Display or hide child elements based on the selected value
                if (summaryText === selectedValue) {
                  childElement.style.display = '';
                  childVisible = true;
                  console.log(`---/Child Element ID: ${childElement.id} = ${summaryText}`);
                } else {
                  childElement.style.display = 'none';
                  console.log(`Hiding element with Child Element ID: ${childElement.id} as it does not match the selected value`);
                }
              } else {
                console.log(`Summary control not found for child element: ${childElement.id}`);
              }

              // Hide the description elements
              const elementsToRemove = childElement.querySelectorAll('.opblock-summary-description');
              elementsToRemove.forEach(element => {
                element.style.display = "none";
              });

              // Additional logic for elements with the class 'no-margin'
              if (childElement.querySelectorAll('.no-margin').length > 0) {
                const opblock = childElement;

                setTimeout(() => {
                  const elementToClear = opblock.querySelectorAll('.opblock-summary-path');
                  elementToClear.forEach(el => {
                    const dataPath = el.getAttribute('data-path').split('/').at(-1);
                    try { opblock.querySelectorAll('.opblock-description-wrapper')[0].style.display = "none"; } catch {}
                    if (dataPath !== 'list' && dataPath !== 'icons' && dataPath !== '{path}') {
                      opblock.querySelectorAll('.opblock-section-header')[0].style.display = "none";
                    }
                  });
                }, 30);
              }
            });

            // Hide or show parent elements based on the visibility of child elements
            if (isFiltering) {
              if (!childVisible) {
                parentElement.style.display = 'none';
                console.log(`Hiding parent element as all child elements are hidden: ${parent.textContent}`);
              } else {
                parentElement.style.display = '';
              }
            }
          } else {
            console.log("Parent element not found for:", parent.textContent);
          }
        });
      } else {
        console.log("Select element not found.");
      }
    }

    // Event listener for changes in the dropdown selection
    document.addEventListener('change', function(event) {
      const selectElement = document.querySelector('#swagger-ui > section > div.swagger-ui > div:nth-child(2) > div.scheme-container > section > div > div > div > label > select');
      if (event.target === selectElement) {
        isFiltering = true;
        expandHiddenElements(); // Expand hidden elements before filtering
        filterElements();
        isFiltering = false;
      }
    });

    // Event listener for clicks to trigger filtering
    document.addEventListener('click', () => {
      filterElements();
    });

    // MutationObserver to monitor changes in the DOM and apply filtering
    const observer = new MutationObserver(() => {
      const selectElement = document.querySelector('#swagger-ui > section > div.swagger-ui > div:nth-child(2) > div.scheme-container > section > div > div > div > label > select');
      if (selectElement) {
        isFiltering = true;
        expandHiddenElements(); // Expand hidden elements before filtering
        filterElements();
        isFiltering = false;
        observer.disconnect();
      }
    });

    observer.observe(document.querySelector('#swagger-ui'), { childList: true, subtree: true });

    // Apply filtering on the initial load
    isFiltering = true;
    expandHiddenElements();
    filterElements();
    isFiltering = false;
  };
</script>
</body>
</html>

© www.soinside.com 2019 - 2024. All rights reserved.