diff --git a/.github/ISSUE_TEMPLATE/02-bug_report.yaml b/.github/ISSUE_TEMPLATE/02-bug_report.yaml index 01c59e475..5ac3a35d7 100644 --- a/.github/ISSUE_TEMPLATE/02-bug_report.yaml +++ b/.github/ISSUE_TEMPLATE/02-bug_report.yaml @@ -35,9 +35,9 @@ body: label: Python Version description: What version of Python are you currently running? options: - - "3.10" - - "3.11" - "3.12" + - "3.13" + - "3.14" validations: required: true - type: textarea diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 85070d98e..2fbc48d5a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,7 +31,7 @@ jobs: NETBOX_CONFIGURATION: netbox.configuration_testing strategy: matrix: - python-version: ['3.10', '3.11', '3.12'] + python-version: ['3.12', '3.13', '3.14'] node-version: ['20.x'] services: redis: diff --git a/contrib/openapi.json b/contrib/openapi.json index 8d940732f..44ce31fa0 100644 --- a/contrib/openapi.json +++ b/contrib/openapi.json @@ -2,12 +2,42 @@ "openapi": "3.0.3", "info": { "title": "NetBox REST API", - "version": "4.4.10", + "version": "4.5.0", "license": { "name": "Apache v2 License" } }, "paths": { + "/api/authentication-check/": { + "get": { + "operationId": "authentication_check_retrieve", + "description": "Return the user making the request, if authenticated successfully.", + "tags": [ + "authentication-check" + ], + "security": [ + { + "cookieAuth": [] + }, + { + "tokenAuth": [] + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": {} + } + } + }, + "description": "" + } + } + } + }, "/api/circuits/circuit-group-assignments/": { "get": { "operationId": "circuits_circuit_group_assignments_list", @@ -516,6 +546,150 @@ }, "description": "* `primary` - Primary\n* `secondary` - Secondary\n* `tertiary` - Tertiary\n* `inactive` - Inactive" }, + { + "in": "query", + "name": "priority__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "priority__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "priority__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "priority__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "priority__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "priority__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "priority__n", + "schema": { + "type": "string", + "x-spec-enum-id": "0548fc537440bf9d", + "nullable": true, + "enum": [ + "inactive", + "null", + "primary", + "secondary", + "tertiary" + ] + }, + "description": "* `primary` - Primary\n* `secondary` - Secondary\n* `tertiary` - Tertiary\n* `inactive` - Inactive" + }, + { + "in": "query", + "name": "priority__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "priority__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "priority__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "priority__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "priority__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "provider", @@ -1654,6 +1828,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -2383,6 +2611,91 @@ "operationId": "circuits_circuit_terminations_list", "description": "Get a list of circuit termination objects.", "parameters": [ + { + "in": "query", + "name": "cable_connector", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "cable_connector__gt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__gte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__lt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__lte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "cable_end", @@ -2398,6 +2711,148 @@ }, "description": "* `A` - A\n* `B` - B" }, + { + "in": "query", + "name": "cable_end__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "cable_end__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__n", + "schema": { + "type": "string", + "x-spec-enum-id": "1db84f9b93b261c8", + "nullable": true, + "enum": [ + "A", + "B", + "null" + ] + }, + "description": "* `A` - A\n* `B` - B" + }, + { + "in": "query", + "name": "cable_end__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "cable_id", @@ -3515,6 +3970,148 @@ }, "description": "* `A` - A\n* `Z` - Z" }, + { + "in": "query", + "name": "term_side__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "term_side__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "term_side__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "term_side__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "term_side__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "term_side__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "term_side__n", + "schema": { + "type": "string", + "x-spec-enum-id": "95b8fcc737f355d0", + "title": "Termination side", + "enum": [ + "A", + "Z", + "null" + ] + }, + "description": "* `A` - A\n* `Z` - Z" + }, + { + "in": "query", + "name": "term_side__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "term_side__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "term_side__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "term_side__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "term_side__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "termination_id", @@ -5073,6 +5670,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -6364,6 +7015,150 @@ }, "description": "* `km` - Kilometers\n* `m` - Meters\n* `mi` - Miles\n* `ft` - Feet" }, + { + "in": "query", + "name": "distance_unit__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "distance_unit__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "distance_unit__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "distance_unit__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "distance_unit__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "distance_unit__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "distance_unit__n", + "schema": { + "type": "string", + "x-spec-enum-id": "b1169a409430c02e", + "nullable": true, + "enum": [ + "ft", + "km", + "m", + "mi", + "null" + ] + }, + "description": "* `km` - Kilometers\n* `m` - Meters\n* `mi` - Miles\n* `ft` - Feet" + }, + { + "in": "query", + "name": "distance_unit__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "distance_unit__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "distance_unit__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "distance_unit__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "distance_unit__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "id", @@ -6686,6 +7481,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "provider", @@ -8737,6 +9586,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "provider", @@ -9877,6 +10780,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "provider", @@ -11296,6 +12253,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -14156,6 +15167,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -15395,6 +16460,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "provider", @@ -18283,6 +19402,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -20283,6 +21456,148 @@ }, "description": "* `create` - Created\n* `update` - Updated\n* `delete` - Deleted" }, + { + "in": "query", + "name": "action__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "action__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "action__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "action__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "action__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "action__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "action__n", + "schema": { + "type": "string", + "x-spec-enum-id": "36ce3d432464454d", + "enum": [ + "create", + "delete", + "null", + "update" + ] + }, + "description": "* `create` - Created\n* `update` - Updated\n* `delete` - Deleted" + }, + { + "in": "query", + "name": "action__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "action__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "action__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "action__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "action__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "changed_object_id", @@ -21612,6 +22927,148 @@ }, "description": "* `A` - A\n* `B` - B" }, + { + "in": "query", + "name": "cable_end__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "cable_end__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__n", + "schema": { + "type": "string", + "x-spec-enum-id": "1db84f9b93b261c8", + "title": "End", + "enum": [ + "A", + "B", + "null" + ] + }, + "description": "* `A` - A\n* `B` - B" + }, + { + "in": "query", + "name": "cable_end__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "created", @@ -22053,211 +23510,6 @@ "description": "" } } - }, - "post": { - "operationId": "dcim_cable_terminations_create", - "description": "Post a list of cable termination objects.", - "tags": [ - "dcim" - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "oneOf": [ - { - "$ref": "#/components/schemas/CableTerminationRequest" - }, - { - "type": "array", - "items": { - "$ref": "#/components/schemas/CableTerminationRequest" - } - } - ] - } - }, - "multipart/form-data": { - "schema": { - "oneOf": [ - { - "$ref": "#/components/schemas/CableTerminationRequest" - }, - { - "type": "array", - "items": { - "$ref": "#/components/schemas/CableTerminationRequest" - } - } - ] - } - } - }, - "required": true - }, - "security": [ - { - "cookieAuth": [] - }, - { - "tokenAuth": [] - } - ], - "responses": { - "201": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CableTermination" - } - } - }, - "description": "" - } - } - }, - "put": { - "operationId": "dcim_cable_terminations_bulk_update", - "description": "Put a list of cable termination objects.", - "tags": [ - "dcim" - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/CableTerminationRequest" - } - } - }, - "multipart/form-data": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/CableTerminationRequest" - } - } - } - }, - "required": true - }, - "security": [ - { - "cookieAuth": [] - }, - { - "tokenAuth": [] - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/CableTermination" - } - } - } - }, - "description": "" - } - } - }, - "patch": { - "operationId": "dcim_cable_terminations_bulk_partial_update", - "description": "Patch a list of cable termination objects.", - "tags": [ - "dcim" - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/CableTerminationRequest" - } - } - }, - "multipart/form-data": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/CableTerminationRequest" - } - } - } - }, - "required": true - }, - "security": [ - { - "cookieAuth": [] - }, - { - "tokenAuth": [] - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/CableTermination" - } - } - } - }, - "description": "" - } - } - }, - "delete": { - "operationId": "dcim_cable_terminations_bulk_destroy", - "description": "Delete a list of cable termination objects.", - "tags": [ - "dcim" - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/CableTerminationRequest" - } - } - }, - "multipart/form-data": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/CableTerminationRequest" - } - } - } - }, - "required": true - }, - "security": [ - { - "cookieAuth": [] - }, - { - "tokenAuth": [] - } - ], - "responses": { - "204": { - "description": "No response body" - } - } } }, "/api/dcim/cable-terminations/{id}/": { @@ -22298,142 +23550,6 @@ "description": "" } } - }, - "put": { - "operationId": "dcim_cable_terminations_update", - "description": "Put a cable termination object.", - "parameters": [ - { - "in": "path", - "name": "id", - "schema": { - "type": "integer" - }, - "description": "A unique integer value identifying this cable termination.", - "required": true - } - ], - "tags": [ - "dcim" - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CableTerminationRequest" - } - }, - "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/CableTerminationRequest" - } - } - }, - "required": true - }, - "security": [ - { - "cookieAuth": [] - }, - { - "tokenAuth": [] - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CableTermination" - } - } - }, - "description": "" - } - } - }, - "patch": { - "operationId": "dcim_cable_terminations_partial_update", - "description": "Patch a cable termination object.", - "parameters": [ - { - "in": "path", - "name": "id", - "schema": { - "type": "integer" - }, - "description": "A unique integer value identifying this cable termination.", - "required": true - } - ], - "tags": [ - "dcim" - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PatchedCableTerminationRequest" - } - }, - "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/PatchedCableTerminationRequest" - } - } - } - }, - "security": [ - { - "cookieAuth": [] - }, - { - "tokenAuth": [] - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CableTermination" - } - } - }, - "description": "" - } - } - }, - "delete": { - "operationId": "dcim_cable_terminations_destroy", - "description": "Delete a cable termination object.", - "parameters": [ - { - "in": "path", - "name": "id", - "schema": { - "type": "integer" - }, - "description": "A unique integer value identifying this cable termination.", - "required": true - } - ], - "tags": [ - "dcim" - ], - "security": [ - { - "cookieAuth": [] - }, - { - "tokenAuth": [] - } - ], - "responses": { - "204": { - "description": "No response body" - } - } } }, "/api/dcim/cables/": { @@ -23363,6 +24479,152 @@ }, "description": "* `km` - Kilometers\n* `m` - Meters\n* `cm` - Centimeters\n* `mi` - Miles\n* `ft` - Feet\n* `in` - Inches" }, + { + "in": "query", + "name": "length_unit__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "length_unit__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "length_unit__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "length_unit__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "length_unit__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "length_unit__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "length_unit__n", + "schema": { + "type": "string", + "x-spec-enum-id": "6e7645525ba02462", + "nullable": true, + "enum": [ + "cm", + "ft", + "in", + "km", + "m", + "mi", + "null" + ] + }, + "description": "* `km` - Kilometers\n* `m` - Meters\n* `cm` - Centimeters\n* `mi` - Miles\n* `ft` - Feet\n* `in` - Inches" + }, + { + "in": "query", + "name": "length_unit__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "length_unit__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "length_unit__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "length_unit__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "length_unit__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "name": "limit", "required": false, @@ -23423,6 +24685,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "powerfeed_id", @@ -23462,6 +24778,169 @@ "explode": true, "style": "form" }, + { + "in": "query", + "name": "profile", + "schema": { + "type": "array", + "items": { + "type": "string", + "x-spec-enum-id": "5e0f85310f0184ea" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "profile__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "profile__ic", + "schema": { + "type": "array", + "items": { + "type": "string", + "x-spec-enum-id": "5e0f85310f0184ea" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "profile__ie", + "schema": { + "type": "array", + "items": { + "type": "string", + "x-spec-enum-id": "5e0f85310f0184ea" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "profile__iew", + "schema": { + "type": "array", + "items": { + "type": "string", + "x-spec-enum-id": "5e0f85310f0184ea" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "profile__iregex", + "schema": { + "type": "array", + "items": { + "type": "string", + "x-spec-enum-id": "5e0f85310f0184ea" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "profile__isw", + "schema": { + "type": "array", + "items": { + "type": "string", + "x-spec-enum-id": "5e0f85310f0184ea" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "profile__n", + "schema": { + "type": "array", + "items": { + "type": "string", + "x-spec-enum-id": "5e0f85310f0184ea" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "profile__nic", + "schema": { + "type": "array", + "items": { + "type": "string", + "x-spec-enum-id": "5e0f85310f0184ea" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "profile__nie", + "schema": { + "type": "array", + "items": { + "type": "string", + "x-spec-enum-id": "5e0f85310f0184ea" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "profile__niew", + "schema": { + "type": "array", + "items": { + "type": "string", + "x-spec-enum-id": "5e0f85310f0184ea" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "profile__nisw", + "schema": { + "type": "array", + "items": { + "type": "string", + "x-spec-enum-id": "5e0f85310f0184ea" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "profile__regex", + "schema": { + "type": "array", + "items": { + "type": "string", + "x-spec-enum-id": "5e0f85310f0184ea" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -25396,6 +26875,149 @@ }, "description": "* `Serial` - [('de-9', 'DE-9'), ('db-25', 'DB-25'), ('rj-11', 'RJ-11'), ('rj-12', 'RJ-12'), ('rj-45', 'RJ-45'), ('mini-din-8', 'Mini-DIN 8')]\n* `USB` - [('usb-a', 'USB Type A'), ('usb-b', 'USB Type B'), ('usb-c', 'USB Type C'), ('usb-mini-a', 'USB Mini A'), ('usb-mini-b', 'USB Mini B'), ('usb-micro-a', 'USB Micro A'), ('usb-micro-b', 'USB Micro B'), ('usb-micro-ab', 'USB Micro AB')]\n* `Other` - [('other', 'Other')]" }, + { + "in": "query", + "name": "type__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "type__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__n", + "schema": { + "type": "string", + "x-spec-enum-id": "7b8d0e83a4bb5178", + "nullable": true, + "enum": [ + "Other", + "Serial", + "USB", + "null" + ] + }, + "description": "* `Serial` - [('de-9', 'DE-9'), ('db-25', 'DB-25'), ('rj-11', 'RJ-11'), ('rj-12', 'RJ-12'), ('rj-45', 'RJ-45'), ('mini-din-8', 'Mini-DIN 8')]\n* `USB` - [('usb-a', 'USB Type A'), ('usb-b', 'USB Type B'), ('usb-c', 'USB Type C'), ('usb-mini-a', 'USB Mini A'), ('usb-mini-b', 'USB Mini B'), ('usb-micro-a', 'USB Micro A'), ('usb-micro-b', 'USB Micro B'), ('usb-micro-ab', 'USB Micro AB')]\n* `Other` - [('other', 'Other')]" + }, + { + "in": "query", + "name": "type__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "updated_by_request", @@ -25816,6 +27438,91 @@ "operationId": "dcim_console_ports_list", "description": "Get a list of console port objects.", "parameters": [ + { + "in": "query", + "name": "cable_connector", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "cable_connector__gt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__gte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__lt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__lte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "cable_end", @@ -25831,6 +27538,148 @@ }, "description": "* `A` - A\n* `B` - B" }, + { + "in": "query", + "name": "cable_end__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "cable_end__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__n", + "schema": { + "type": "string", + "x-spec-enum-id": "1db84f9b93b261c8", + "nullable": true, + "enum": [ + "A", + "B", + "null" + ] + }, + "description": "* `A` - A\n* `B` - B" + }, + { + "in": "query", + "name": "cable_end__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "cable_id", @@ -27049,6 +28898,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -27278,6 +29181,157 @@ }, "description": "Port speed in bits per second\n\n* `1200` - 1200 bps\n* `2400` - 2400 bps\n* `4800` - 4800 bps\n* `9600` - 9600 bps\n* `19200` - 19.2 kbps\n* `38400` - 38.4 kbps\n* `57600` - 57.6 kbps\n* `115200` - 115.2 kbps" }, + { + "in": "query", + "name": "speed__ic", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "speed__ie", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "speed__iew", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "speed__iregex", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "speed__isw", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "speed__n", + "schema": { + "type": "integer", + "x-spec-enum-id": "ab6d9635c131a378", + "nullable": true, + "enum": [ + 115200, + 1200, + 19200, + 2400, + 38400, + 4800, + 57600, + 9600, + "null" + ] + }, + "description": "Port speed in bits per second\n\n* `1200` - 1200 bps\n* `2400` - 2400 bps\n* `4800` - 4800 bps\n* `9600` - 9600 bps\n* `19200` - 19.2 kbps\n* `38400` - 38.4 kbps\n* `57600` - 57.6 kbps\n* `115200` - 115.2 kbps" + }, + { + "in": "query", + "name": "speed__nic", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "speed__nie", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "speed__niew", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "speed__nisw", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "speed__regex", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "tag", @@ -28920,6 +30974,149 @@ }, "description": "* `Serial` - [('de-9', 'DE-9'), ('db-25', 'DB-25'), ('rj-11', 'RJ-11'), ('rj-12', 'RJ-12'), ('rj-45', 'RJ-45'), ('mini-din-8', 'Mini-DIN 8')]\n* `USB` - [('usb-a', 'USB Type A'), ('usb-b', 'USB Type B'), ('usb-c', 'USB Type C'), ('usb-mini-a', 'USB Mini A'), ('usb-mini-b', 'USB Mini B'), ('usb-micro-a', 'USB Micro A'), ('usb-micro-b', 'USB Micro B'), ('usb-micro-ab', 'USB Micro AB')]\n* `Other` - [('other', 'Other')]" }, + { + "in": "query", + "name": "type__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "type__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__n", + "schema": { + "type": "string", + "x-spec-enum-id": "7b8d0e83a4bb5178", + "nullable": true, + "enum": [ + "Other", + "Serial", + "USB", + "null" + ] + }, + "description": "* `Serial` - [('de-9', 'DE-9'), ('db-25', 'DB-25'), ('rj-11', 'RJ-11'), ('rj-12', 'RJ-12'), ('rj-45', 'RJ-45'), ('mini-din-8', 'Mini-DIN 8')]\n* `USB` - [('usb-a', 'USB Type A'), ('usb-b', 'USB Type B'), ('usb-c', 'USB Type C'), ('usb-mini-a', 'USB Mini A'), ('usb-mini-b', 'USB Mini B'), ('usb-micro-a', 'USB Micro A'), ('usb-micro-b', 'USB Micro B'), ('usb-micro-ab', 'USB Micro AB')]\n* `Other` - [('other', 'Other')]" + }, + { + "in": "query", + "name": "type__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "updated_by_request", @@ -29340,6 +31537,91 @@ "operationId": "dcim_console_server_ports_list", "description": "Get a list of console server port objects.", "parameters": [ + { + "in": "query", + "name": "cable_connector", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "cable_connector__gt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__gte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__lt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__lte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "cable_end", @@ -29355,6 +31637,148 @@ }, "description": "* `A` - A\n* `B` - B" }, + { + "in": "query", + "name": "cable_end__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "cable_end__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__n", + "schema": { + "type": "string", + "x-spec-enum-id": "1db84f9b93b261c8", + "nullable": true, + "enum": [ + "A", + "B", + "null" + ] + }, + "description": "* `A` - A\n* `B` - B" + }, + { + "in": "query", + "name": "cable_end__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "cable_id", @@ -30573,6 +32997,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -30802,6 +33280,157 @@ }, "description": "Port speed in bits per second\n\n* `1200` - 1200 bps\n* `2400` - 2400 bps\n* `4800` - 4800 bps\n* `9600` - 9600 bps\n* `19200` - 19.2 kbps\n* `38400` - 38.4 kbps\n* `57600` - 57.6 kbps\n* `115200` - 115.2 kbps" }, + { + "in": "query", + "name": "speed__ic", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "speed__ie", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "speed__iew", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "speed__iregex", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "speed__isw", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "speed__n", + "schema": { + "type": "integer", + "x-spec-enum-id": "ab6d9635c131a378", + "nullable": true, + "enum": [ + 115200, + 1200, + 19200, + 2400, + 38400, + 4800, + 57600, + 9600, + "null" + ] + }, + "description": "Port speed in bits per second\n\n* `1200` - 1200 bps\n* `2400` - 2400 bps\n* `4800` - 4800 bps\n* `9600` - 9600 bps\n* `19200` - 19.2 kbps\n* `38400` - 38.4 kbps\n* `57600` - 57.6 kbps\n* `115200` - 115.2 kbps" + }, + { + "in": "query", + "name": "speed__nic", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "speed__nie", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "speed__niew", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "speed__nisw", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "speed__regex", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "tag", @@ -34006,6 +36635,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -35625,6 +38308,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "parent", @@ -36336,6 +39073,156 @@ }, "description": "* `front-to-rear` - Front to rear\n* `rear-to-front` - Rear to front\n* `left-to-right` - Left to right\n* `right-to-left` - Right to left\n* `side-to-rear` - Side to rear\n* `rear-to-side` - Rear to side\n* `bottom-to-top` - Bottom to top\n* `top-to-bottom` - Top to bottom\n* `passive` - Passive\n* `mixed` - Mixed" }, + { + "in": "query", + "name": "airflow__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "airflow__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__n", + "schema": { + "type": "string", + "x-spec-enum-id": "11cb3d363b41ba9e", + "nullable": true, + "enum": [ + "bottom-to-top", + "front-to-rear", + "left-to-right", + "mixed", + "null", + "passive", + "rear-to-front", + "rear-to-side", + "right-to-left", + "side-to-rear", + "top-to-bottom" + ] + }, + "description": "* `front-to-rear` - Front to rear\n* `rear-to-front` - Rear to front\n* `left-to-right` - Left to right\n* `right-to-left` - Right to left\n* `side-to-rear` - Side to rear\n* `rear-to-side` - Rear to side\n* `bottom-to-top` - Bottom to top\n* `top-to-bottom` - Top to bottom\n* `passive` - Passive\n* `mixed` - Mixed" + }, + { + "in": "query", + "name": "airflow__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "console_port_template_count", @@ -36913,6 +39800,91 @@ }, "description": "Has device bays" }, + { + "in": "query", + "name": "device_count", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "device_count__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "device_count__gt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "device_count__gte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "device_count__lt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "device_count__lte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "device_count__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "exclude_from_utilization", @@ -37721,6 +40693,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "part_number", @@ -38326,6 +41352,149 @@ }, "description": "Parent devices house child devices in device bays. Leave blank if this device type is neither a parent nor a child.\n\n* `parent` - Parent\n* `child` - Child" }, + { + "in": "query", + "name": "subdevice_role__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "subdevice_role__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "subdevice_role__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "subdevice_role__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "subdevice_role__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "subdevice_role__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "subdevice_role__n", + "schema": { + "type": "string", + "x-spec-enum-id": "65a61d5e1deb4a24", + "nullable": true, + "title": "Parent/child status", + "enum": [ + "child", + "null", + "parent" + ] + }, + "description": "Parent devices house child devices in device bays. Leave blank if this device type is neither a parent nor a child.\n\n* `parent` - Parent\n* `child` - Child" + }, + { + "in": "query", + "name": "subdevice_role__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "subdevice_role__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "subdevice_role__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "subdevice_role__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "subdevice_role__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "tag", @@ -38568,6 +41737,150 @@ ] }, "description": "* `kg` - Kilograms\n* `g` - Grams\n* `lb` - Pounds\n* `oz` - Ounces" + }, + { + "in": "query", + "name": "weight_unit__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "weight_unit__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__n", + "schema": { + "type": "string", + "x-spec-enum-id": "2235ce3f404afbc0", + "nullable": true, + "enum": [ + "g", + "kg", + "lb", + "null", + "oz" + ] + }, + "description": "* `kg` - Kilograms\n* `g` - Grams\n* `lb` - Pounds\n* `oz` - Ounces" + }, + { + "in": "query", + "name": "weight_unit__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" } ], "tags": [ @@ -39004,6 +42317,156 @@ }, "description": "* `front-to-rear` - Front to rear\n* `rear-to-front` - Rear to front\n* `left-to-right` - Left to right\n* `right-to-left` - Right to left\n* `side-to-rear` - Side to rear\n* `rear-to-side` - Rear to side\n* `bottom-to-top` - Bottom to top\n* `top-to-bottom` - Top to bottom\n* `passive` - Passive\n* `mixed` - Mixed" }, + { + "in": "query", + "name": "airflow__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "airflow__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__n", + "schema": { + "type": "string", + "x-spec-enum-id": "11cb3d363b41ba9e", + "nullable": true, + "enum": [ + "bottom-to-top", + "front-to-rear", + "left-to-right", + "mixed", + "null", + "passive", + "rear-to-front", + "rear-to-side", + "right-to-left", + "side-to-rear", + "top-to-bottom" + ] + }, + "description": "* `front-to-rear` - Front to rear\n* `rear-to-front` - Rear to front\n* `left-to-right` - Left to right\n* `right-to-left` - Right to left\n* `side-to-rear` - Side to rear\n* `rear-to-side` - Rear to side\n* `bottom-to-top` - Bottom to top\n* `top-to-bottom` - Top to bottom\n* `passive` - Passive\n* `mixed` - Mixed" + }, + { + "in": "query", + "name": "airflow__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "asset_tag", @@ -39936,6 +43399,149 @@ }, "description": "* `front` - Front\n* `rear` - Rear" }, + { + "in": "query", + "name": "face__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "face__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "face__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "face__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "face__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "face__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "face__n", + "schema": { + "type": "string", + "x-spec-enum-id": "d2fb9b3f75158b83", + "nullable": true, + "title": "Rack face", + "enum": [ + "front", + "null", + "rear" + ] + }, + "description": "* `front` - Front\n* `rear` - Rear" + }, + { + "in": "query", + "name": "face__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "face__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "face__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "face__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "face__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "front_port_count", @@ -41160,6 +44766,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "parent_bay_id", @@ -44087,6 +47747,91 @@ "type": "string" } }, + { + "in": "query", + "name": "positions", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "positions__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "positions__gt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "positions__gte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "positions__lt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "positions__lte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "positions__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -44101,9 +47846,10 @@ "schema": { "type": "array", "items": { - "type": "integer" + "type": "string" } }, + "description": "Rear port (ID)", "explode": true, "style": "form" }, @@ -44113,94 +47859,10 @@ "schema": { "type": "array", "items": { - "type": "integer" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "rear_port_position", - "schema": { - "type": "array", - "items": { - "type": "integer", - "format": "int32" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "rear_port_position__empty", - "schema": { - "type": "boolean" - } - }, - { - "in": "query", - "name": "rear_port_position__gt", - "schema": { - "type": "array", - "items": { - "type": "integer", - "format": "int32" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "rear_port_position__gte", - "schema": { - "type": "array", - "items": { - "type": "integer", - "format": "int32" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "rear_port_position__lt", - "schema": { - "type": "array", - "items": { - "type": "integer", - "format": "int32" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "rear_port_position__lte", - "schema": { - "type": "array", - "items": { - "type": "integer", - "format": "int32" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "rear_port_position__n", - "schema": { - "type": "array", - "items": { - "type": "integer", - "format": "int32" + "type": "string" } }, + "description": "Rear port (ID)", "explode": true, "style": "form" }, @@ -44787,6 +48449,91 @@ "operationId": "dcim_front_ports_list", "description": "Get a list of front port objects.", "parameters": [ + { + "in": "query", + "name": "cable_connector", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "cable_connector__gt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__gte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__lt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__lte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "cable_end", @@ -44802,6 +48549,148 @@ }, "description": "* `A` - A\n* `B` - B" }, + { + "in": "query", + "name": "cable_end__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "cable_end__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__n", + "schema": { + "type": "string", + "x-spec-enum-id": "1db84f9b93b261c8", + "nullable": true, + "enum": [ + "A", + "B", + "null" + ] + }, + "description": "* `A` - A\n* `B` - B" + }, + { + "in": "query", + "name": "cable_end__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "cable_id", @@ -46164,6 +50053,145 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "positions", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "positions__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "positions__gt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "positions__gte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "positions__lt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "positions__lte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "positions__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -46230,9 +50258,10 @@ "schema": { "type": "array", "items": { - "type": "integer" + "type": "string" } }, + "description": "Rear port (ID)", "explode": true, "style": "form" }, @@ -46242,94 +50271,10 @@ "schema": { "type": "array", "items": { - "type": "integer" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "rear_port_position", - "schema": { - "type": "array", - "items": { - "type": "integer", - "format": "int32" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "rear_port_position__empty", - "schema": { - "type": "boolean" - } - }, - { - "in": "query", - "name": "rear_port_position__gt", - "schema": { - "type": "array", - "items": { - "type": "integer", - "format": "int32" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "rear_port_position__gte", - "schema": { - "type": "array", - "items": { - "type": "integer", - "format": "int32" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "rear_port_position__lt", - "schema": { - "type": "array", - "items": { - "type": "integer", - "format": "int32" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "rear_port_position__lte", - "schema": { - "type": "array", - "items": { - "type": "integer", - "format": "int32" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "rear_port_position__n", - "schema": { - "type": "array", - "items": { - "type": "integer", - "format": "int32" + "type": "string" } }, + "description": "Rear port (ID)", "explode": true, "style": "form" }, @@ -49267,6 +53212,91 @@ "explode": true, "style": "form" }, + { + "in": "query", + "name": "cable_connector", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "cable_connector__gt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__gte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__lt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__lte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "cable_end", @@ -49282,6 +53312,148 @@ }, "description": "* `A` - A\n* `B` - B" }, + { + "in": "query", + "name": "cable_end__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "cable_end__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__n", + "schema": { + "type": "string", + "x-spec-enum-id": "1db84f9b93b261c8", + "nullable": true, + "enum": [ + "A", + "B", + "null" + ] + }, + "description": "* `A` - A\n* `B` - B" + }, + { + "in": "query", + "name": "cable_end__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "cable_id", @@ -51192,6 +55364,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "parent_id", @@ -54584,6 +58810,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -58271,6 +62551,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "parent_id", @@ -60485,6 +64819,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "parent", @@ -62368,6 +66756,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "primary", @@ -63617,6 +68059,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -66830,6 +71326,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "parent_id", @@ -68401,6 +72951,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -68896,6 +73500,152 @@ }, "description": "* `front-to-rear` - Front to rear\n* `rear-to-front` - Rear to front\n* `left-to-right` - Left to right\n* `right-to-left` - Right to left\n* `side-to-rear` - Side to rear\n* `passive` - Passive" }, + { + "in": "query", + "name": "airflow__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "airflow__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__n", + "schema": { + "type": "string", + "x-spec-enum-id": "5ad4e700c656b09d", + "nullable": true, + "enum": [ + "front-to-rear", + "left-to-right", + "null", + "passive", + "rear-to-front", + "right-to-left", + "side-to-rear" + ] + }, + "description": "* `front-to-rear` - Front to rear\n* `rear-to-front` - Rear to front\n* `left-to-right` - Left to right\n* `right-to-left` - Right to left\n* `side-to-rear` - Side to rear\n* `passive` - Passive" + }, + { + "in": "query", + "name": "airflow__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "console_ports", @@ -69566,6 +74316,91 @@ "format": "uuid" } }, + { + "in": "query", + "name": "module_count", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "module_count__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "module_count__gt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "module_count__gte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "module_count__lt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "module_count__lte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "module_count__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, { "name": "offset", "required": false, @@ -69584,6 +74419,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "part_number", @@ -69978,6 +74867,150 @@ ] }, "description": "* `kg` - Kilograms\n* `g` - Grams\n* `lb` - Pounds\n* `oz` - Ounces" + }, + { + "in": "query", + "name": "weight_unit__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "weight_unit__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__n", + "schema": { + "type": "string", + "x-spec-enum-id": "2235ce3f404afbc0", + "nullable": true, + "enum": [ + "g", + "kg", + "lb", + "null", + "oz" + ] + }, + "description": "* `kg` - Kilograms\n* `g` - Grams\n* `lb` - Pounds\n* `oz` - Ounces" + }, + { + "in": "query", + "name": "weight_unit__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" } ], "tags": [ @@ -71235,6 +76268,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -72972,6 +78059,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "parent", @@ -73823,6 +78964,91 @@ "explode": true, "style": "form" }, + { + "in": "query", + "name": "cable_connector", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "cable_connector__gt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__gte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__lt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__lte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "cable_end", @@ -73838,6 +79064,148 @@ }, "description": "* `A` - A\n* `B` - B" }, + { + "in": "query", + "name": "cable_end__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "cable_end__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__n", + "schema": { + "type": "string", + "x-spec-enum-id": "1db84f9b93b261c8", + "nullable": true, + "enum": [ + "A", + "B", + "null" + ] + }, + "description": "* `A` - A\n* `B` - B" + }, + { + "in": "query", + "name": "cable_end__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "cable_id", @@ -74591,6 +79959,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "phase", @@ -74605,6 +80027,147 @@ }, "description": "* `single-phase` - Single phase\n* `three-phase` - Three-phase" }, + { + "in": "query", + "name": "phase__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "phase__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "phase__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "phase__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "phase__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "phase__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "phase__n", + "schema": { + "type": "string", + "x-spec-enum-id": "994bc0696f4df57f", + "enum": [ + "null", + "single-phase", + "three-phase" + ] + }, + "description": "* `single-phase` - Single phase\n* `three-phase` - Three-phase" + }, + { + "in": "query", + "name": "phase__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "phase__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "phase__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "phase__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "phase__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "power_panel_id", @@ -74990,6 +80553,147 @@ }, "description": "* `ac` - AC\n* `dc` - DC" }, + { + "in": "query", + "name": "supply__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "supply__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "supply__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "supply__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "supply__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "supply__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "supply__n", + "schema": { + "type": "string", + "x-spec-enum-id": "1b6d99616ca6412b", + "enum": [ + "ac", + "dc", + "null" + ] + }, + "description": "* `ac` - AC\n* `dc` - DC" + }, + { + "in": "query", + "name": "supply__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "supply__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "supply__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "supply__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "supply__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "tag", @@ -75154,6 +80858,147 @@ }, "description": "* `primary` - Primary\n* `redundant` - Redundant" }, + { + "in": "query", + "name": "type__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "type__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__n", + "schema": { + "type": "string", + "x-spec-enum-id": "093a164236819eb8", + "enum": [ + "null", + "primary", + "redundant" + ] + }, + "description": "* `primary` - Primary\n* `redundant` - Redundant" + }, + { + "in": "query", + "name": "type__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "updated_by_request", @@ -75699,6 +81544,157 @@ "operationId": "dcim_power_outlet_templates_list", "description": "Get a list of power outlet template objects.", "parameters": [ + { + "in": "query", + "name": "color", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "color__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "color__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "color__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "color__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "color__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "color__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "color__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "color__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "color__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "color__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "color__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "color__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "created", @@ -76766,6 +82762,158 @@ }, "description": "* `IEC 60320` - [('iec-60320-c5', 'C5'), ('iec-60320-c7', 'C7'), ('iec-60320-c13', 'C13'), ('iec-60320-c15', 'C15'), ('iec-60320-c17', 'C17'), ('iec-60320-c19', 'C19'), ('iec-60320-c21', 'C21')]\n* `IEC 60309` - [('iec-60309-p-n-e-4h', 'P+N+E 4H'), ('iec-60309-p-n-e-6h', 'P+N+E 6H'), ('iec-60309-p-n-e-9h', 'P+N+E 9H'), ('iec-60309-2p-e-4h', '2P+E 4H'), ('iec-60309-2p-e-6h', '2P+E 6H'), ('iec-60309-2p-e-9h', '2P+E 9H'), ('iec-60309-3p-e-4h', '3P+E 4H'), ('iec-60309-3p-e-6h', '3P+E 6H'), ('iec-60309-3p-e-9h', '3P+E 9H'), ('iec-60309-3p-n-e-4h', '3P+N+E 4H'), ('iec-60309-3p-n-e-6h', '3P+N+E 6H'), ('iec-60309-3p-n-e-9h', '3P+N+E 9H')]\n* `IEC 60906-1` - [('iec-60906-1', 'IEC 60906-1'), ('nbr-14136-10a', '2P+T 10A (NBR 14136)'), ('nbr-14136-20a', '2P+T 20A (NBR 14136)')]\n* `NEMA (Non-locking)` - [('nema-1-15r', 'NEMA 1-15R'), ('nema-5-15r', 'NEMA 5-15R'), ('nema-5-20r', 'NEMA 5-20R'), ('nema-5-30r', 'NEMA 5-30R'), ('nema-5-50r', 'NEMA 5-50R'), ('nema-6-15r', 'NEMA 6-15R'), ('nema-6-20r', 'NEMA 6-20R'), ('nema-6-30r', 'NEMA 6-30R'), ('nema-6-50r', 'NEMA 6-50R'), ('nema-10-30r', 'NEMA 10-30R'), ('nema-10-50r', 'NEMA 10-50R'), ('nema-14-20r', 'NEMA 14-20R'), ('nema-14-30r', 'NEMA 14-30R'), ('nema-14-50r', 'NEMA 14-50R'), ('nema-14-60r', 'NEMA 14-60R'), ('nema-15-15r', 'NEMA 15-15R'), ('nema-15-20r', 'NEMA 15-20R'), ('nema-15-30r', 'NEMA 15-30R'), ('nema-15-50r', 'NEMA 15-50R'), ('nema-15-60r', 'NEMA 15-60R')]\n* `NEMA (Locking)` - [('nema-l1-15r', 'NEMA L1-15R'), ('nema-l5-15r', 'NEMA L5-15R'), ('nema-l5-20r', 'NEMA L5-20R'), ('nema-l5-30r', 'NEMA L5-30R'), ('nema-l5-50r', 'NEMA L5-50R'), ('nema-l6-15r', 'NEMA L6-15R'), ('nema-l6-20r', 'NEMA L6-20R'), ('nema-l6-30r', 'NEMA L6-30R'), ('nema-l6-50r', 'NEMA L6-50R'), ('nema-l10-30r', 'NEMA L10-30R'), ('nema-l14-20r', 'NEMA L14-20R'), ('nema-l14-30r', 'NEMA L14-30R'), ('nema-l14-50r', 'NEMA L14-50R'), ('nema-l14-60r', 'NEMA L14-60R'), ('nema-l15-20r', 'NEMA L15-20R'), ('nema-l15-30r', 'NEMA L15-30R'), ('nema-l15-50r', 'NEMA L15-50R'), ('nema-l15-60r', 'NEMA L15-60R'), ('nema-l21-20r', 'NEMA L21-20R'), ('nema-l21-30r', 'NEMA L21-30R'), ('nema-l22-20r', 'NEMA L22-20R'), ('nema-l22-30r', 'NEMA L22-30R')]\n* `California Style` - [('CS6360C', 'CS6360C'), ('CS6364C', 'CS6364C'), ('CS8164C', 'CS8164C'), ('CS8264C', 'CS8264C'), ('CS8364C', 'CS8364C'), ('CS8464C', 'CS8464C')]\n* `ITA/International` - [('ita-e', 'ITA Type E (CEE 7/5)'), ('ita-f', 'ITA Type F (CEE 7/3)'), ('ita-g', 'ITA Type G (BS 1363)'), ('ita-h', 'ITA Type H'), ('ita-i', 'ITA Type I'), ('ita-j', 'ITA Type J'), ('ita-k', 'ITA Type K'), ('ita-l', 'ITA Type L (CEI 23-50)'), ('ita-m', 'ITA Type M (BS 546)'), ('ita-n', 'ITA Type N'), ('ita-o', 'ITA Type O'), ('ita-multistandard', 'ITA Multistandard')]\n* `USB` - [('usb-a', 'USB Type A'), ('usb-micro-b', 'USB Micro B'), ('usb-c', 'USB Type C')]\n* `Molex` - [('molex-micro-fit-1x2', 'Molex Micro-Fit 1x2'), ('molex-micro-fit-2x2', 'Molex Micro-Fit 2x2'), ('molex-micro-fit-2x3', 'Molex Micro-Fit 2x3'), ('molex-micro-fit-2x4', 'Molex Micro-Fit 2x4')]\n* `DC` - [('dc-terminal', 'DC Terminal')]\n* `Proprietary` - [('eaton-c39', 'Eaton C39'), ('hdot-cx', 'HDOT Cx'), ('saf-d-grid', 'Saf-D-Grid'), ('neutrik-powercon-20a', 'Neutrik powerCON (20A)'), ('neutrik-powercon-32a', 'Neutrik powerCON (32A)'), ('neutrik-powercon-true1', 'Neutrik powerCON TRUE1'), ('neutrik-powercon-true1-top', 'Neutrik powerCON TRUE1 TOP'), ('ubiquiti-smartpower', 'Ubiquiti SmartPower')]\n* `Other` - [('hardwired', 'Hardwired'), ('other', 'Other')]" }, + { + "in": "query", + "name": "type__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "type__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__n", + "schema": { + "type": "string", + "x-spec-enum-id": "db3e4eb2b93615f8", + "nullable": true, + "enum": [ + "California Style", + "DC", + "IEC 60309", + "IEC 60320", + "IEC 60906-1", + "ITA/International", + "Molex", + "NEMA (Locking)", + "NEMA (Non-locking)", + "Other", + "Proprietary", + "USB", + "null" + ] + }, + "description": "* `IEC 60320` - [('iec-60320-c5', 'C5'), ('iec-60320-c7', 'C7'), ('iec-60320-c13', 'C13'), ('iec-60320-c15', 'C15'), ('iec-60320-c17', 'C17'), ('iec-60320-c19', 'C19'), ('iec-60320-c21', 'C21')]\n* `IEC 60309` - [('iec-60309-p-n-e-4h', 'P+N+E 4H'), ('iec-60309-p-n-e-6h', 'P+N+E 6H'), ('iec-60309-p-n-e-9h', 'P+N+E 9H'), ('iec-60309-2p-e-4h', '2P+E 4H'), ('iec-60309-2p-e-6h', '2P+E 6H'), ('iec-60309-2p-e-9h', '2P+E 9H'), ('iec-60309-3p-e-4h', '3P+E 4H'), ('iec-60309-3p-e-6h', '3P+E 6H'), ('iec-60309-3p-e-9h', '3P+E 9H'), ('iec-60309-3p-n-e-4h', '3P+N+E 4H'), ('iec-60309-3p-n-e-6h', '3P+N+E 6H'), ('iec-60309-3p-n-e-9h', '3P+N+E 9H')]\n* `IEC 60906-1` - [('iec-60906-1', 'IEC 60906-1'), ('nbr-14136-10a', '2P+T 10A (NBR 14136)'), ('nbr-14136-20a', '2P+T 20A (NBR 14136)')]\n* `NEMA (Non-locking)` - [('nema-1-15r', 'NEMA 1-15R'), ('nema-5-15r', 'NEMA 5-15R'), ('nema-5-20r', 'NEMA 5-20R'), ('nema-5-30r', 'NEMA 5-30R'), ('nema-5-50r', 'NEMA 5-50R'), ('nema-6-15r', 'NEMA 6-15R'), ('nema-6-20r', 'NEMA 6-20R'), ('nema-6-30r', 'NEMA 6-30R'), ('nema-6-50r', 'NEMA 6-50R'), ('nema-10-30r', 'NEMA 10-30R'), ('nema-10-50r', 'NEMA 10-50R'), ('nema-14-20r', 'NEMA 14-20R'), ('nema-14-30r', 'NEMA 14-30R'), ('nema-14-50r', 'NEMA 14-50R'), ('nema-14-60r', 'NEMA 14-60R'), ('nema-15-15r', 'NEMA 15-15R'), ('nema-15-20r', 'NEMA 15-20R'), ('nema-15-30r', 'NEMA 15-30R'), ('nema-15-50r', 'NEMA 15-50R'), ('nema-15-60r', 'NEMA 15-60R')]\n* `NEMA (Locking)` - [('nema-l1-15r', 'NEMA L1-15R'), ('nema-l5-15r', 'NEMA L5-15R'), ('nema-l5-20r', 'NEMA L5-20R'), ('nema-l5-30r', 'NEMA L5-30R'), ('nema-l5-50r', 'NEMA L5-50R'), ('nema-l6-15r', 'NEMA L6-15R'), ('nema-l6-20r', 'NEMA L6-20R'), ('nema-l6-30r', 'NEMA L6-30R'), ('nema-l6-50r', 'NEMA L6-50R'), ('nema-l10-30r', 'NEMA L10-30R'), ('nema-l14-20r', 'NEMA L14-20R'), ('nema-l14-30r', 'NEMA L14-30R'), ('nema-l14-50r', 'NEMA L14-50R'), ('nema-l14-60r', 'NEMA L14-60R'), ('nema-l15-20r', 'NEMA L15-20R'), ('nema-l15-30r', 'NEMA L15-30R'), ('nema-l15-50r', 'NEMA L15-50R'), ('nema-l15-60r', 'NEMA L15-60R'), ('nema-l21-20r', 'NEMA L21-20R'), ('nema-l21-30r', 'NEMA L21-30R'), ('nema-l22-20r', 'NEMA L22-20R'), ('nema-l22-30r', 'NEMA L22-30R')]\n* `California Style` - [('CS6360C', 'CS6360C'), ('CS6364C', 'CS6364C'), ('CS8164C', 'CS8164C'), ('CS8264C', 'CS8264C'), ('CS8364C', 'CS8364C'), ('CS8464C', 'CS8464C')]\n* `ITA/International` - [('ita-e', 'ITA Type E (CEE 7/5)'), ('ita-f', 'ITA Type F (CEE 7/3)'), ('ita-g', 'ITA Type G (BS 1363)'), ('ita-h', 'ITA Type H'), ('ita-i', 'ITA Type I'), ('ita-j', 'ITA Type J'), ('ita-k', 'ITA Type K'), ('ita-l', 'ITA Type L (CEI 23-50)'), ('ita-m', 'ITA Type M (BS 546)'), ('ita-n', 'ITA Type N'), ('ita-o', 'ITA Type O'), ('ita-multistandard', 'ITA Multistandard')]\n* `USB` - [('usb-a', 'USB Type A'), ('usb-micro-b', 'USB Micro B'), ('usb-c', 'USB Type C')]\n* `Molex` - [('molex-micro-fit-1x2', 'Molex Micro-Fit 1x2'), ('molex-micro-fit-2x2', 'Molex Micro-Fit 2x2'), ('molex-micro-fit-2x3', 'Molex Micro-Fit 2x3'), ('molex-micro-fit-2x4', 'Molex Micro-Fit 2x4')]\n* `DC` - [('dc-terminal', 'DC Terminal')]\n* `Proprietary` - [('eaton-c39', 'Eaton C39'), ('hdot-cx', 'HDOT Cx'), ('saf-d-grid', 'Saf-D-Grid'), ('neutrik-powercon-20a', 'Neutrik powerCON (20A)'), ('neutrik-powercon-32a', 'Neutrik powerCON (32A)'), ('neutrik-powercon-true1', 'Neutrik powerCON TRUE1'), ('neutrik-powercon-true1-top', 'Neutrik powerCON TRUE1 TOP'), ('ubiquiti-smartpower', 'Ubiquiti SmartPower')]\n* `Other` - [('hardwired', 'Hardwired'), ('other', 'Other')]" + }, + { + "in": "query", + "name": "type__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "updated_by_request", @@ -77186,6 +83334,91 @@ "operationId": "dcim_power_outlets_list", "description": "Get a list of power outlet objects.", "parameters": [ + { + "in": "query", + "name": "cable_connector", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "cable_connector__gt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__gte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__lt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__lte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "cable_end", @@ -77201,6 +83434,148 @@ }, "description": "* `A` - A\n* `B` - B" }, + { + "in": "query", + "name": "cable_end__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "cable_end__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__n", + "schema": { + "type": "string", + "x-spec-enum-id": "1db84f9b93b261c8", + "nullable": true, + "enum": [ + "A", + "B", + "null" + ] + }, + "description": "* `A` - A\n* `B` - B" + }, + { + "in": "query", + "name": "cable_end__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "cable_id", @@ -78757,6 +85132,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "power_port_id", @@ -80667,6 +87096,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -82313,6 +88796,158 @@ }, "description": "* `IEC 60320` - [('iec-60320-c6', 'C6'), ('iec-60320-c8', 'C8'), ('iec-60320-c14', 'C14'), ('iec-60320-c16', 'C16'), ('iec-60320-c18', 'C18'), ('iec-60320-c20', 'C20'), ('iec-60320-c22', 'C22')]\n* `IEC 60309` - [('iec-60309-p-n-e-4h', 'P+N+E 4H'), ('iec-60309-p-n-e-6h', 'P+N+E 6H'), ('iec-60309-p-n-e-9h', 'P+N+E 9H'), ('iec-60309-2p-e-4h', '2P+E 4H'), ('iec-60309-2p-e-6h', '2P+E 6H'), ('iec-60309-2p-e-9h', '2P+E 9H'), ('iec-60309-3p-e-4h', '3P+E 4H'), ('iec-60309-3p-e-6h', '3P+E 6H'), ('iec-60309-3p-e-9h', '3P+E 9H'), ('iec-60309-3p-n-e-4h', '3P+N+E 4H'), ('iec-60309-3p-n-e-6h', '3P+N+E 6H'), ('iec-60309-3p-n-e-9h', '3P+N+E 9H')]\n* `IEC 60906-1` - [('iec-60906-1', 'IEC 60906-1'), ('nbr-14136-10a', '2P+T 10A (NBR 14136)'), ('nbr-14136-20a', '2P+T 20A (NBR 14136)')]\n* `NEMA (Non-locking)` - [('nema-1-15p', 'NEMA 1-15P'), ('nema-5-15p', 'NEMA 5-15P'), ('nema-5-20p', 'NEMA 5-20P'), ('nema-5-30p', 'NEMA 5-30P'), ('nema-5-50p', 'NEMA 5-50P'), ('nema-6-15p', 'NEMA 6-15P'), ('nema-6-20p', 'NEMA 6-20P'), ('nema-6-30p', 'NEMA 6-30P'), ('nema-6-50p', 'NEMA 6-50P'), ('nema-10-30p', 'NEMA 10-30P'), ('nema-10-50p', 'NEMA 10-50P'), ('nema-14-20p', 'NEMA 14-20P'), ('nema-14-30p', 'NEMA 14-30P'), ('nema-14-50p', 'NEMA 14-50P'), ('nema-14-60p', 'NEMA 14-60P'), ('nema-15-15p', 'NEMA 15-15P'), ('nema-15-20p', 'NEMA 15-20P'), ('nema-15-30p', 'NEMA 15-30P'), ('nema-15-50p', 'NEMA 15-50P'), ('nema-15-60p', 'NEMA 15-60P')]\n* `NEMA (Locking)` - [('nema-l1-15p', 'NEMA L1-15P'), ('nema-l5-15p', 'NEMA L5-15P'), ('nema-l5-20p', 'NEMA L5-20P'), ('nema-l5-30p', 'NEMA L5-30P'), ('nema-l5-50p', 'NEMA L5-50P'), ('nema-l6-15p', 'NEMA L6-15P'), ('nema-l6-20p', 'NEMA L6-20P'), ('nema-l6-30p', 'NEMA L6-30P'), ('nema-l6-50p', 'NEMA L6-50P'), ('nema-l10-30p', 'NEMA L10-30P'), ('nema-l14-20p', 'NEMA L14-20P'), ('nema-l14-30p', 'NEMA L14-30P'), ('nema-l14-50p', 'NEMA L14-50P'), ('nema-l14-60p', 'NEMA L14-60P'), ('nema-l15-20p', 'NEMA L15-20P'), ('nema-l15-30p', 'NEMA L15-30P'), ('nema-l15-50p', 'NEMA L15-50P'), ('nema-l15-60p', 'NEMA L15-60P'), ('nema-l21-20p', 'NEMA L21-20P'), ('nema-l21-30p', 'NEMA L21-30P'), ('nema-l22-20p', 'NEMA L22-20P'), ('nema-l22-30p', 'NEMA L22-30P')]\n* `California Style` - [('cs6361c', 'CS6361C'), ('cs6365c', 'CS6365C'), ('cs8165c', 'CS8165C'), ('cs8265c', 'CS8265C'), ('cs8365c', 'CS8365C'), ('cs8465c', 'CS8465C')]\n* `International/ITA` - [('ita-c', 'ITA Type C (CEE 7/16)'), ('ita-e', 'ITA Type E (CEE 7/6)'), ('ita-f', 'ITA Type F (CEE 7/4)'), ('ita-ef', 'ITA Type E/F (CEE 7/7)'), ('ita-g', 'ITA Type G (BS 1363)'), ('ita-h', 'ITA Type H'), ('ita-i', 'ITA Type I'), ('ita-j', 'ITA Type J'), ('ita-k', 'ITA Type K'), ('ita-l', 'ITA Type L (CEI 23-50)'), ('ita-m', 'ITA Type M (BS 546)'), ('ita-n', 'ITA Type N'), ('ita-o', 'ITA Type O')]\n* `USB` - [('usb-a', 'USB Type A'), ('usb-b', 'USB Type B'), ('usb-c', 'USB Type C'), ('usb-mini-a', 'USB Mini A'), ('usb-mini-b', 'USB Mini B'), ('usb-micro-a', 'USB Micro A'), ('usb-micro-b', 'USB Micro B'), ('usb-micro-ab', 'USB Micro AB'), ('usb-3-b', 'USB 3.0 Type B'), ('usb-3-micro-b', 'USB 3.0 Micro B')]\n* `Molex` - [('molex-micro-fit-1x2', 'Molex Micro-Fit 1x2'), ('molex-micro-fit-2x2', 'Molex Micro-Fit 2x2'), ('molex-micro-fit-2x3', 'Molex Micro-Fit 2x3'), ('molex-micro-fit-2x4', 'Molex Micro-Fit 2x4')]\n* `DC` - [('dc-terminal', 'DC Terminal')]\n* `Proprietary` - [('saf-d-grid', 'Saf-D-Grid'), ('neutrik-powercon-20', 'Neutrik powerCON (20A)'), ('neutrik-powercon-32', 'Neutrik powerCON (32A)'), ('neutrik-powercon-true1', 'Neutrik powerCON TRUE1'), ('neutrik-powercon-true1-top', 'Neutrik powerCON TRUE1 TOP'), ('ubiquiti-smartpower', 'Ubiquiti SmartPower')]\n* `Other` - [('hardwired', 'Hardwired'), ('other', 'Other')]" }, + { + "in": "query", + "name": "type__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "type__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__n", + "schema": { + "type": "string", + "x-spec-enum-id": "aadcbe6ca854c1ed", + "nullable": true, + "enum": [ + "California Style", + "DC", + "IEC 60309", + "IEC 60320", + "IEC 60906-1", + "International/ITA", + "Molex", + "NEMA (Locking)", + "NEMA (Non-locking)", + "Other", + "Proprietary", + "USB", + "null" + ] + }, + "description": "* `IEC 60320` - [('iec-60320-c6', 'C6'), ('iec-60320-c8', 'C8'), ('iec-60320-c14', 'C14'), ('iec-60320-c16', 'C16'), ('iec-60320-c18', 'C18'), ('iec-60320-c20', 'C20'), ('iec-60320-c22', 'C22')]\n* `IEC 60309` - [('iec-60309-p-n-e-4h', 'P+N+E 4H'), ('iec-60309-p-n-e-6h', 'P+N+E 6H'), ('iec-60309-p-n-e-9h', 'P+N+E 9H'), ('iec-60309-2p-e-4h', '2P+E 4H'), ('iec-60309-2p-e-6h', '2P+E 6H'), ('iec-60309-2p-e-9h', '2P+E 9H'), ('iec-60309-3p-e-4h', '3P+E 4H'), ('iec-60309-3p-e-6h', '3P+E 6H'), ('iec-60309-3p-e-9h', '3P+E 9H'), ('iec-60309-3p-n-e-4h', '3P+N+E 4H'), ('iec-60309-3p-n-e-6h', '3P+N+E 6H'), ('iec-60309-3p-n-e-9h', '3P+N+E 9H')]\n* `IEC 60906-1` - [('iec-60906-1', 'IEC 60906-1'), ('nbr-14136-10a', '2P+T 10A (NBR 14136)'), ('nbr-14136-20a', '2P+T 20A (NBR 14136)')]\n* `NEMA (Non-locking)` - [('nema-1-15p', 'NEMA 1-15P'), ('nema-5-15p', 'NEMA 5-15P'), ('nema-5-20p', 'NEMA 5-20P'), ('nema-5-30p', 'NEMA 5-30P'), ('nema-5-50p', 'NEMA 5-50P'), ('nema-6-15p', 'NEMA 6-15P'), ('nema-6-20p', 'NEMA 6-20P'), ('nema-6-30p', 'NEMA 6-30P'), ('nema-6-50p', 'NEMA 6-50P'), ('nema-10-30p', 'NEMA 10-30P'), ('nema-10-50p', 'NEMA 10-50P'), ('nema-14-20p', 'NEMA 14-20P'), ('nema-14-30p', 'NEMA 14-30P'), ('nema-14-50p', 'NEMA 14-50P'), ('nema-14-60p', 'NEMA 14-60P'), ('nema-15-15p', 'NEMA 15-15P'), ('nema-15-20p', 'NEMA 15-20P'), ('nema-15-30p', 'NEMA 15-30P'), ('nema-15-50p', 'NEMA 15-50P'), ('nema-15-60p', 'NEMA 15-60P')]\n* `NEMA (Locking)` - [('nema-l1-15p', 'NEMA L1-15P'), ('nema-l5-15p', 'NEMA L5-15P'), ('nema-l5-20p', 'NEMA L5-20P'), ('nema-l5-30p', 'NEMA L5-30P'), ('nema-l5-50p', 'NEMA L5-50P'), ('nema-l6-15p', 'NEMA L6-15P'), ('nema-l6-20p', 'NEMA L6-20P'), ('nema-l6-30p', 'NEMA L6-30P'), ('nema-l6-50p', 'NEMA L6-50P'), ('nema-l10-30p', 'NEMA L10-30P'), ('nema-l14-20p', 'NEMA L14-20P'), ('nema-l14-30p', 'NEMA L14-30P'), ('nema-l14-50p', 'NEMA L14-50P'), ('nema-l14-60p', 'NEMA L14-60P'), ('nema-l15-20p', 'NEMA L15-20P'), ('nema-l15-30p', 'NEMA L15-30P'), ('nema-l15-50p', 'NEMA L15-50P'), ('nema-l15-60p', 'NEMA L15-60P'), ('nema-l21-20p', 'NEMA L21-20P'), ('nema-l21-30p', 'NEMA L21-30P'), ('nema-l22-20p', 'NEMA L22-20P'), ('nema-l22-30p', 'NEMA L22-30P')]\n* `California Style` - [('cs6361c', 'CS6361C'), ('cs6365c', 'CS6365C'), ('cs8165c', 'CS8165C'), ('cs8265c', 'CS8265C'), ('cs8365c', 'CS8365C'), ('cs8465c', 'CS8465C')]\n* `International/ITA` - [('ita-c', 'ITA Type C (CEE 7/16)'), ('ita-e', 'ITA Type E (CEE 7/6)'), ('ita-f', 'ITA Type F (CEE 7/4)'), ('ita-ef', 'ITA Type E/F (CEE 7/7)'), ('ita-g', 'ITA Type G (BS 1363)'), ('ita-h', 'ITA Type H'), ('ita-i', 'ITA Type I'), ('ita-j', 'ITA Type J'), ('ita-k', 'ITA Type K'), ('ita-l', 'ITA Type L (CEI 23-50)'), ('ita-m', 'ITA Type M (BS 546)'), ('ita-n', 'ITA Type N'), ('ita-o', 'ITA Type O')]\n* `USB` - [('usb-a', 'USB Type A'), ('usb-b', 'USB Type B'), ('usb-c', 'USB Type C'), ('usb-mini-a', 'USB Mini A'), ('usb-mini-b', 'USB Mini B'), ('usb-micro-a', 'USB Micro A'), ('usb-micro-b', 'USB Micro B'), ('usb-micro-ab', 'USB Micro AB'), ('usb-3-b', 'USB 3.0 Type B'), ('usb-3-micro-b', 'USB 3.0 Micro B')]\n* `Molex` - [('molex-micro-fit-1x2', 'Molex Micro-Fit 1x2'), ('molex-micro-fit-2x2', 'Molex Micro-Fit 2x2'), ('molex-micro-fit-2x3', 'Molex Micro-Fit 2x3'), ('molex-micro-fit-2x4', 'Molex Micro-Fit 2x4')]\n* `DC` - [('dc-terminal', 'DC Terminal')]\n* `Proprietary` - [('saf-d-grid', 'Saf-D-Grid'), ('neutrik-powercon-20', 'Neutrik powerCON (20A)'), ('neutrik-powercon-32', 'Neutrik powerCON (32A)'), ('neutrik-powercon-true1', 'Neutrik powerCON TRUE1'), ('neutrik-powercon-true1-top', 'Neutrik powerCON TRUE1 TOP'), ('ubiquiti-smartpower', 'Ubiquiti SmartPower')]\n* `Other` - [('hardwired', 'Hardwired'), ('other', 'Other')]" + }, + { + "in": "query", + "name": "type__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "type__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "updated_by_request", @@ -82818,6 +89453,91 @@ "explode": true, "style": "form" }, + { + "in": "query", + "name": "cable_connector", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "cable_connector__gt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__gte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__lt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__lte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "cable_end", @@ -82833,6 +89553,148 @@ }, "description": "* `A` - A\n* `B` - B" }, + { + "in": "query", + "name": "cable_end__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "cable_end__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__n", + "schema": { + "type": "string", + "x-spec-enum-id": "1db84f9b93b261c8", + "nullable": true, + "enum": [ + "A", + "B", + "null" + ] + }, + "description": "* `A` - A\n* `B` - B" + }, + { + "in": "query", + "name": "cable_end__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "cable_id", @@ -84136,6 +90998,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -85652,6 +92568,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -87431,6 +94401,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -89247,6 +96271,148 @@ }, "description": "* `mm` - Millimeters\n* `in` - Inches" }, + { + "in": "query", + "name": "outer_unit__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "outer_unit__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "outer_unit__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "outer_unit__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "outer_unit__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "outer_unit__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "outer_unit__n", + "schema": { + "type": "string", + "x-spec-enum-id": "3d701848b66312c3", + "nullable": true, + "enum": [ + "in", + "mm", + "null" + ] + }, + "description": "* `mm` - Millimeters\n* `in` - Inches" + }, + { + "in": "query", + "name": "outer_unit__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "outer_unit__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "outer_unit__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "outer_unit__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "outer_unit__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "outer_width", @@ -89332,6 +96498,60 @@ "explode": true, "style": "form" }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -89340,6 +96560,91 @@ }, "description": "Search" }, + { + "in": "query", + "name": "rack_count", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "rack_count__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "rack_count__gt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "rack_count__gte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "rack_count__lt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "rack_count__lte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "rack_count__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "slug", @@ -89819,6 +97124,150 @@ }, "description": "* `kg` - Kilograms\n* `g` - Grams\n* `lb` - Pounds\n* `oz` - Ounces" }, + { + "in": "query", + "name": "weight_unit__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "weight_unit__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__n", + "schema": { + "type": "string", + "x-spec-enum-id": "2235ce3f404afbc0", + "nullable": true, + "enum": [ + "g", + "kg", + "lb", + "null", + "oz" + ] + }, + "description": "* `kg` - Kilograms\n* `g` - Grams\n* `lb` - Pounds\n* `oz` - Ounces" + }, + { + "in": "query", + "name": "weight_unit__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "width", @@ -90414,6 +97863,148 @@ }, "description": "* `front-to-rear` - Front to rear\n* `rear-to-front` - Rear to front" }, + { + "in": "query", + "name": "airflow__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "airflow__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__n", + "schema": { + "type": "string", + "x-spec-enum-id": "a784734d07ef1b3c", + "nullable": true, + "enum": [ + "front-to-rear", + "null", + "rear-to-front" + ] + }, + "description": "* `front-to-rear` - Front to rear\n* `rear-to-front` - Rear to front" + }, + { + "in": "query", + "name": "airflow__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "airflow__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "asset_tag", @@ -92041,6 +99632,148 @@ }, "description": "* `mm` - Millimeters\n* `in` - Inches" }, + { + "in": "query", + "name": "outer_unit__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "outer_unit__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "outer_unit__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "outer_unit__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "outer_unit__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "outer_unit__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "outer_unit__n", + "schema": { + "type": "string", + "x-spec-enum-id": "3d701848b66312c3", + "nullable": true, + "enum": [ + "in", + "mm", + "null" + ] + }, + "description": "* `mm` - Millimeters\n* `in` - Inches" + }, + { + "in": "query", + "name": "outer_unit__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "outer_unit__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "outer_unit__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "outer_unit__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "outer_unit__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "outer_width", @@ -92126,6 +99859,60 @@ "explode": true, "style": "form" }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -93134,6 +100921,150 @@ }, "description": "* `kg` - Kilograms\n* `g` - Grams\n* `lb` - Pounds\n* `oz` - Ounces" }, + { + "in": "query", + "name": "weight_unit__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "weight_unit__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__n", + "schema": { + "type": "string", + "x-spec-enum-id": "2235ce3f404afbc0", + "nullable": true, + "enum": [ + "g", + "kg", + "lb", + "null", + "oz" + ] + }, + "description": "* `kg` - Kilograms\n* `g` - Grams\n* `lb` - Pounds\n* `oz` - Ounces" + }, + { + "in": "query", + "name": "weight_unit__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "weight_unit__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "width", @@ -94292,6 +102223,32 @@ "explode": true, "style": "form" }, + { + "in": "query", + "name": "front_port_id", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Front port (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "front_port_id__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Front port (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "id", @@ -95509,6 +103466,91 @@ "operationId": "dcim_rear_ports_list", "description": "Get a list of rear port objects.", "parameters": [ + { + "in": "query", + "name": "cable_connector", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "cable_connector__gt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__gte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__lt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__lte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_connector__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "cable_end", @@ -95524,6 +103566,148 @@ }, "description": "* `A` - A\n* `B` - B" }, + { + "in": "query", + "name": "cable_end__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "cable_end__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__n", + "schema": { + "type": "string", + "x-spec-enum-id": "1db84f9b93b261c8", + "nullable": true, + "enum": [ + "A", + "B", + "null" + ] + }, + "description": "* `A` - A\n* `B` - B" + }, + { + "in": "query", + "name": "cable_end__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "cable_end__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "cable_id", @@ -96279,6 +104463,32 @@ "explode": true, "style": "form" }, + { + "in": "query", + "name": "front_port_id", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Front port (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "front_port_id__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Front port (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "id", @@ -96886,6 +105096,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "positions", @@ -98690,6 +106954,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "parent", @@ -100107,6 +108425,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "parent", @@ -101897,6 +110269,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -103883,6 +112309,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -105342,6 +113822,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "primary_ip4", @@ -107721,6 +116255,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -109279,6 +117867,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "platform", @@ -111485,6 +120127,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -112103,6 +120799,149 @@ }, "description": "Base set of predefined choices (optional)\n\n* `IATA` - IATA (Airport codes)\n* `ISO_3166` - ISO 3166 (Country codes)\n* `UN_LOCODE` - UN/LOCODE (Location codes)" }, + { + "in": "query", + "name": "base_choices__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "base_choices__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "base_choices__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "base_choices__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "base_choices__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "base_choices__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "base_choices__n", + "schema": { + "type": "string", + "x-spec-enum-id": "cf0efb5195f85007", + "nullable": true, + "enum": [ + "IATA", + "ISO_3166", + "UN_LOCODE", + "null" + ] + }, + "description": "Base set of predefined choices (optional)\n\n* `IATA` - IATA (Airport codes)\n* `ISO_3166` - ISO 3166 (Country codes)\n* `UN_LOCODE` - UN/LOCODE (Location codes)" + }, + { + "in": "query", + "name": "base_choices__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "base_choices__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "base_choices__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "base_choices__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "base_choices__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "choice", @@ -112734,6 +121573,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -113517,6 +122410,148 @@ }, "description": "Loose matches any instance of a given string; exact matches the entire field.\n\n* `disabled` - Disabled\n* `loose` - Loose\n* `exact` - Exact" }, + { + "in": "query", + "name": "filter_logic__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "filter_logic__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "filter_logic__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "filter_logic__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "filter_logic__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "filter_logic__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "filter_logic__n", + "schema": { + "type": "string", + "x-spec-enum-id": "d168820c798ae45a", + "enum": [ + "disabled", + "exact", + "loose", + "null" + ] + }, + "description": "Loose matches any instance of a given string; exact matches the entire field.\n\n* `disabled` - Disabled\n* `loose` - Loose\n* `exact` - Exact" + }, + { + "in": "query", + "name": "filter_logic__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "filter_logic__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "filter_logic__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "filter_logic__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "filter_logic__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "group_name", @@ -114296,6 +123331,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -114624,6 +123713,148 @@ }, "description": "Specifies whether the custom field value can be edited in the UI\n\n* `yes` - Yes\n* `no` - No\n* `hidden` - Hidden" }, + { + "in": "query", + "name": "ui_editable__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "ui_editable__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "ui_editable__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "ui_editable__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "ui_editable__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "ui_editable__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "ui_editable__n", + "schema": { + "type": "string", + "x-spec-enum-id": "336f52760e62022f", + "enum": [ + "hidden", + "no", + "null", + "yes" + ] + }, + "description": "Specifies whether the custom field value can be edited in the UI\n\n* `yes` - Yes\n* `no` - No\n* `hidden` - Hidden" + }, + { + "in": "query", + "name": "ui_editable__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "ui_editable__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "ui_editable__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "ui_editable__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "ui_editable__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "ui_visible", @@ -114639,6 +123870,148 @@ }, "description": "Specifies whether the custom field is displayed in the UI\n\n* `always` - Always\n* `if-set` - If set\n* `hidden` - Hidden" }, + { + "in": "query", + "name": "ui_visible__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "ui_visible__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "ui_visible__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "ui_visible__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "ui_visible__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "ui_visible__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "ui_visible__n", + "schema": { + "type": "string", + "x-spec-enum-id": "f32800c399b927b6", + "enum": [ + "always", + "hidden", + "if-set", + "null" + ] + }, + "description": "Specifies whether the custom field is displayed in the UI\n\n* `always` - Always\n* `if-set` - If set\n* `hidden` - Hidden" + }, + { + "in": "query", + "name": "ui_visible__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "ui_visible__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "ui_visible__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "ui_visible__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "ui_visible__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "unique", @@ -115499,6 +124872,160 @@ }, "description": "The class of the first link in a group will be used for the dropdown button\n\n* `default` - Default\n* `blue` - Blue\n* `indigo` - Indigo\n* `purple` - Purple\n* `pink` - Pink\n* `red` - Red\n* `orange` - Orange\n* `yellow` - Yellow\n* `green` - Green\n* `teal` - Teal\n* `cyan` - Cyan\n* `gray` - Gray\n* `black` - Black\n* `white` - White\n* `ghost-dark` - Link" }, + { + "in": "query", + "name": "button_class__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "button_class__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "button_class__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "button_class__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "button_class__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "button_class__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "button_class__n", + "schema": { + "type": "string", + "x-spec-enum-id": "5e54b3bd086685ce", + "enum": [ + "black", + "blue", + "cyan", + "default", + "ghost-dark", + "gray", + "green", + "indigo", + "null", + "orange", + "pink", + "purple", + "red", + "teal", + "white", + "yellow" + ] + }, + "description": "The class of the first link in a group will be used for the dropdown button\n\n* `default` - Default\n* `blue` - Blue\n* `indigo` - Indigo\n* `purple` - Purple\n* `pink` - Pink\n* `red` - Red\n* `orange` - Orange\n* `yellow` - Yellow\n* `green` - Green\n* `teal` - Teal\n* `cyan` - Cyan\n* `gray` - Gray\n* `black` - Black\n* `white` - White\n* `ghost-dark` - Link" + }, + { + "in": "query", + "name": "button_class__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "button_class__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "button_class__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "button_class__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "button_class__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "created", @@ -116401,6 +125928,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -118052,6 +127633,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -119856,6 +129491,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -123586,513 +133275,6 @@ } } }, - "/api/extras/object-types/": { - "get": { - "operationId": "extras_object_types_list", - "description": "Read-only list of ObjectTypes.", - "parameters": [ - { - "in": "query", - "name": "app_label", - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "app_label__empty", - "schema": { - "type": "boolean" - } - }, - { - "in": "query", - "name": "app_label__ic", - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "app_label__ie", - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "app_label__iew", - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "app_label__iregex", - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "app_label__isw", - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "app_label__n", - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "app_label__nic", - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "app_label__nie", - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "app_label__niew", - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "app_label__nisw", - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "app_label__regex", - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "features", - "schema": { - "type": "string" - } - }, - { - "in": "query", - "name": "id", - "schema": { - "type": "array", - "items": { - "type": "integer", - "format": "int32" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "id__empty", - "schema": { - "type": "boolean" - } - }, - { - "in": "query", - "name": "id__gt", - "schema": { - "type": "array", - "items": { - "type": "integer", - "format": "int32" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "id__gte", - "schema": { - "type": "array", - "items": { - "type": "integer", - "format": "int32" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "id__lt", - "schema": { - "type": "array", - "items": { - "type": "integer", - "format": "int32" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "id__lte", - "schema": { - "type": "array", - "items": { - "type": "integer", - "format": "int32" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "id__n", - "schema": { - "type": "array", - "items": { - "type": "integer", - "format": "int32" - } - }, - "explode": true, - "style": "form" - }, - { - "name": "limit", - "required": false, - "in": "query", - "description": "Number of results to return per page.", - "schema": { - "type": "integer" - } - }, - { - "in": "query", - "name": "model", - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "model__empty", - "schema": { - "type": "boolean" - } - }, - { - "in": "query", - "name": "model__ic", - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "model__ie", - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "model__iew", - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "model__iregex", - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "model__isw", - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "model__n", - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "model__nic", - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "model__nie", - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "model__niew", - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "model__nisw", - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "model__regex", - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "explode": true, - "style": "form" - }, - { - "name": "offset", - "required": false, - "in": "query", - "description": "The initial index from which to return the results.", - "schema": { - "type": "integer" - } - }, - { - "name": "ordering", - "required": false, - "in": "query", - "description": "Which field to use when ordering the results.", - "schema": { - "type": "string" - } - }, - { - "in": "query", - "name": "public", - "schema": { - "type": "boolean" - } - }, - { - "in": "query", - "name": "q", - "schema": { - "type": "string" - }, - "description": "Search" - } - ], - "tags": [ - "extras" - ], - "security": [ - { - "cookieAuth": [] - }, - { - "tokenAuth": [] - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PaginatedObjectTypeList" - } - } - }, - "description": "" - } - } - } - }, - "/api/extras/object-types/{id}/": { - "get": { - "operationId": "extras_object_types_retrieve", - "description": "Read-only list of ObjectTypes.", - "parameters": [ - { - "in": "path", - "name": "id", - "schema": { - "type": "integer" - }, - "description": "A unique integer value identifying this object type.", - "required": true - } - ], - "tags": [ - "extras" - ], - "security": [ - { - "cookieAuth": [] - }, - { - "tokenAuth": [] - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ObjectType" - } - } - }, - "description": "" - } - } - } - }, "/api/extras/saved-filters/": { "get": { "operationId": "extras_saved_filters_list", @@ -124825,6 +134007,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -129110,6 +138346,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -130851,6 +140141,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "payload_url", @@ -132126,6 +141470,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "prefix", @@ -133461,6 +142859,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -134976,6 +144428,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "provider", @@ -137783,6 +147289,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "protocol", @@ -139412,6 +148972,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "parent", @@ -141113,6 +150727,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "parent", @@ -143009,6 +152677,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "prefix", @@ -145120,6 +154842,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -146359,6 +156135,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -147891,6 +157721,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -149081,6 +158965,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "port", @@ -149145,6 +159083,148 @@ }, "description": "* `tcp` - TCP\n* `udp` - UDP\n* `sctp` - SCTP" }, + { + "in": "query", + "name": "protocol__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "protocol__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "protocol__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "protocol__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "protocol__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "protocol__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "protocol__n", + "schema": { + "type": "string", + "x-spec-enum-id": "e4b15bec749a2a32", + "enum": [ + "null", + "sctp", + "tcp", + "udp" + ] + }, + "description": "* `tcp` - TCP\n* `udp` - UDP\n* `sctp` - SCTP" + }, + { + "in": "query", + "name": "protocol__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "protocol__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "protocol__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "protocol__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "protocol__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -150411,6 +160491,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "parent_object_id", @@ -150574,6 +160708,148 @@ }, "description": "* `tcp` - TCP\n* `udp` - UDP\n* `sctp` - SCTP" }, + { + "in": "query", + "name": "protocol__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "protocol__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "protocol__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "protocol__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "protocol__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "protocol__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "protocol__n", + "schema": { + "type": "string", + "x-spec-enum-id": "e4b15bec749a2a32", + "enum": [ + "null", + "sctp", + "tcp", + "udp" + ] + }, + "description": "* `tcp` - TCP\n* `udp` - UDP\n* `sctp` - SCTP" + }, + { + "in": "query", + "name": "protocol__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "protocol__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "protocol__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "protocol__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "protocol__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -151715,6 +161991,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -153286,6 +163616,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -155667,6 +166051,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -157757,6 +168195,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -161553,6 +172045,150 @@ }, "description": "* `primary` - Primary\n* `secondary` - Secondary\n* `tertiary` - Tertiary\n* `inactive` - Inactive" }, + { + "in": "query", + "name": "priority__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "priority__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "priority__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "priority__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "priority__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "priority__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "priority__n", + "schema": { + "type": "string", + "x-spec-enum-id": "0548fc537440bf9d", + "nullable": true, + "enum": [ + "inactive", + "null", + "primary", + "secondary", + "tertiary" + ] + }, + "description": "* `primary` - Primary\n* `secondary` - Secondary\n* `tertiary` - Tertiary\n* `inactive` - Inactive" + }, + { + "in": "query", + "name": "priority__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "priority__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "priority__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "priority__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "priority__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -162767,6 +173403,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "parent", @@ -164060,6 +174750,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -165800,6 +176544,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "phone", @@ -167238,6 +178036,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "parent", @@ -168655,6 +179507,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -169752,6 +180658,58 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer" + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer" + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "permission_id", @@ -170219,6 +181177,1832 @@ } } }, + "/api/users/owner-groups/": { + "get": { + "operationId": "users_owner_groups_list", + "description": "Get a list of owner group objects.", + "parameters": [ + { + "in": "query", + "name": "description", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "description__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "description__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "description__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "description__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "description__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "description__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "description__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "description__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "description__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "description__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "description__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "description__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "id__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "id__gt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "id__gte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "id__lt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "id__lte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "name": "limit", + "required": false, + "in": "query", + "description": "Number of results to return per page.", + "schema": { + "type": "integer" + } + }, + { + "in": "query", + "name": "name", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "name__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "name__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "name__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "name__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "name__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "name__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "name__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "name__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "name__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "name__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "name__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "name__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "name": "offset", + "required": false, + "in": "query", + "description": "The initial index from which to return the results.", + "schema": { + "type": "integer" + } + }, + { + "name": "ordering", + "required": false, + "in": "query", + "description": "Which field to use when ordering the results.", + "schema": { + "type": "string" + } + }, + { + "in": "query", + "name": "q", + "schema": { + "type": "string" + }, + "description": "Search" + } + ], + "tags": [ + "users" + ], + "security": [ + { + "cookieAuth": [] + }, + { + "tokenAuth": [] + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaginatedOwnerGroupList" + } + } + }, + "description": "" + } + } + }, + "post": { + "operationId": "users_owner_groups_create", + "description": "Post a list of owner group objects.", + "tags": [ + "users" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/OwnerGroupRequest" + }, + { + "type": "array", + "items": { + "$ref": "#/components/schemas/OwnerGroupRequest" + } + } + ] + } + }, + "multipart/form-data": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/OwnerGroupRequest" + }, + { + "type": "array", + "items": { + "$ref": "#/components/schemas/OwnerGroupRequest" + } + } + ] + } + } + }, + "required": true + }, + "security": [ + { + "cookieAuth": [] + }, + { + "tokenAuth": [] + } + ], + "responses": { + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OwnerGroup" + } + } + }, + "description": "" + } + } + }, + "put": { + "operationId": "users_owner_groups_bulk_update", + "description": "Put a list of owner group objects.", + "tags": [ + "users" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OwnerGroupRequest" + } + } + }, + "multipart/form-data": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OwnerGroupRequest" + } + } + } + }, + "required": true + }, + "security": [ + { + "cookieAuth": [] + }, + { + "tokenAuth": [] + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OwnerGroup" + } + } + } + }, + "description": "" + } + } + }, + "patch": { + "operationId": "users_owner_groups_bulk_partial_update", + "description": "Patch a list of owner group objects.", + "tags": [ + "users" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OwnerGroupRequest" + } + } + }, + "multipart/form-data": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OwnerGroupRequest" + } + } + } + }, + "required": true + }, + "security": [ + { + "cookieAuth": [] + }, + { + "tokenAuth": [] + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OwnerGroup" + } + } + } + }, + "description": "" + } + } + }, + "delete": { + "operationId": "users_owner_groups_bulk_destroy", + "description": "Delete a list of owner group objects.", + "tags": [ + "users" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OwnerGroupRequest" + } + } + }, + "multipart/form-data": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OwnerGroupRequest" + } + } + } + }, + "required": true + }, + "security": [ + { + "cookieAuth": [] + }, + { + "tokenAuth": [] + } + ], + "responses": { + "204": { + "description": "No response body" + } + } + } + }, + "/api/users/owner-groups/{id}/": { + "get": { + "operationId": "users_owner_groups_retrieve", + "description": "Get a owner group object.", + "parameters": [ + { + "in": "path", + "name": "id", + "schema": { + "type": "integer" + }, + "description": "A unique integer value identifying this owner group.", + "required": true + } + ], + "tags": [ + "users" + ], + "security": [ + { + "cookieAuth": [] + }, + { + "tokenAuth": [] + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OwnerGroup" + } + } + }, + "description": "" + } + } + }, + "put": { + "operationId": "users_owner_groups_update", + "description": "Put a owner group object.", + "parameters": [ + { + "in": "path", + "name": "id", + "schema": { + "type": "integer" + }, + "description": "A unique integer value identifying this owner group.", + "required": true + } + ], + "tags": [ + "users" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OwnerGroupRequest" + } + }, + "multipart/form-data": { + "schema": { + "$ref": "#/components/schemas/OwnerGroupRequest" + } + } + }, + "required": true + }, + "security": [ + { + "cookieAuth": [] + }, + { + "tokenAuth": [] + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OwnerGroup" + } + } + }, + "description": "" + } + } + }, + "patch": { + "operationId": "users_owner_groups_partial_update", + "description": "Patch a owner group object.", + "parameters": [ + { + "in": "path", + "name": "id", + "schema": { + "type": "integer" + }, + "description": "A unique integer value identifying this owner group.", + "required": true + } + ], + "tags": [ + "users" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PatchedOwnerGroupRequest" + } + }, + "multipart/form-data": { + "schema": { + "$ref": "#/components/schemas/PatchedOwnerGroupRequest" + } + } + } + }, + "security": [ + { + "cookieAuth": [] + }, + { + "tokenAuth": [] + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OwnerGroup" + } + } + }, + "description": "" + } + } + }, + "delete": { + "operationId": "users_owner_groups_destroy", + "description": "Delete a owner group object.", + "parameters": [ + { + "in": "path", + "name": "id", + "schema": { + "type": "integer" + }, + "description": "A unique integer value identifying this owner group.", + "required": true + } + ], + "tags": [ + "users" + ], + "security": [ + { + "cookieAuth": [] + }, + { + "tokenAuth": [] + } + ], + "responses": { + "204": { + "description": "No response body" + } + } + } + }, + "/api/users/owners/": { + "get": { + "operationId": "users_owners_list", + "description": "Get a list of owner objects.", + "parameters": [ + { + "in": "query", + "name": "description", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "description__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "description__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "description__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "description__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "description__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "description__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "description__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "description__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "description__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "description__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "description__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "description__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "group", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Group (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "group__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Group (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "group_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Group (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "group_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Group (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "id__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "id__gt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "id__gte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "id__lt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "id__lte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "name": "limit", + "required": false, + "in": "query", + "description": "Number of results to return per page.", + "schema": { + "type": "integer" + } + }, + { + "in": "query", + "name": "name", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "name__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "name__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "name__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "name__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "name__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "name__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "name__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "name__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "name__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "name__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "name__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "name__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "name": "offset", + "required": false, + "in": "query", + "description": "The initial index from which to return the results.", + "schema": { + "type": "integer" + } + }, + { + "name": "ordering", + "required": false, + "in": "query", + "description": "Which field to use when ordering the results.", + "schema": { + "type": "string" + } + }, + { + "in": "query", + "name": "q", + "schema": { + "type": "string" + }, + "description": "Search" + }, + { + "in": "query", + "name": "user", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "User (username)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "user__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "User (username)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "user_group", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "User group (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "user_group__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "User group (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "user_group_id", + "schema": { + "type": "array", + "items": { + "type": "integer" + } + }, + "description": "User group (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "user_group_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer" + } + }, + "description": "User group (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "user_id", + "schema": { + "type": "array", + "items": { + "type": "integer" + } + }, + "description": "User (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "user_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer" + } + }, + "description": "User (ID)", + "explode": true, + "style": "form" + } + ], + "tags": [ + "users" + ], + "security": [ + { + "cookieAuth": [] + }, + { + "tokenAuth": [] + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaginatedOwnerList" + } + } + }, + "description": "" + } + } + }, + "post": { + "operationId": "users_owners_create", + "description": "Post a list of owner objects.", + "tags": [ + "users" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/OwnerRequest" + }, + { + "type": "array", + "items": { + "$ref": "#/components/schemas/OwnerRequest" + } + } + ] + } + }, + "multipart/form-data": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/OwnerRequest" + }, + { + "type": "array", + "items": { + "$ref": "#/components/schemas/OwnerRequest" + } + } + ] + } + } + }, + "required": true + }, + "security": [ + { + "cookieAuth": [] + }, + { + "tokenAuth": [] + } + ], + "responses": { + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Owner" + } + } + }, + "description": "" + } + } + }, + "put": { + "operationId": "users_owners_bulk_update", + "description": "Put a list of owner objects.", + "tags": [ + "users" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OwnerRequest" + } + } + }, + "multipart/form-data": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OwnerRequest" + } + } + } + }, + "required": true + }, + "security": [ + { + "cookieAuth": [] + }, + { + "tokenAuth": [] + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Owner" + } + } + } + }, + "description": "" + } + } + }, + "patch": { + "operationId": "users_owners_bulk_partial_update", + "description": "Patch a list of owner objects.", + "tags": [ + "users" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OwnerRequest" + } + } + }, + "multipart/form-data": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OwnerRequest" + } + } + } + }, + "required": true + }, + "security": [ + { + "cookieAuth": [] + }, + { + "tokenAuth": [] + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Owner" + } + } + } + }, + "description": "" + } + } + }, + "delete": { + "operationId": "users_owners_bulk_destroy", + "description": "Delete a list of owner objects.", + "tags": [ + "users" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OwnerRequest" + } + } + }, + "multipart/form-data": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OwnerRequest" + } + } + } + }, + "required": true + }, + "security": [ + { + "cookieAuth": [] + }, + { + "tokenAuth": [] + } + ], + "responses": { + "204": { + "description": "No response body" + } + } + } + }, + "/api/users/owners/{id}/": { + "get": { + "operationId": "users_owners_retrieve", + "description": "Get a owner object.", + "parameters": [ + { + "in": "path", + "name": "id", + "schema": { + "type": "integer" + }, + "description": "A unique integer value identifying this owner.", + "required": true + } + ], + "tags": [ + "users" + ], + "security": [ + { + "cookieAuth": [] + }, + { + "tokenAuth": [] + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Owner" + } + } + }, + "description": "" + } + } + }, + "put": { + "operationId": "users_owners_update", + "description": "Put a owner object.", + "parameters": [ + { + "in": "path", + "name": "id", + "schema": { + "type": "integer" + }, + "description": "A unique integer value identifying this owner.", + "required": true + } + ], + "tags": [ + "users" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OwnerRequest" + } + }, + "multipart/form-data": { + "schema": { + "$ref": "#/components/schemas/OwnerRequest" + } + } + }, + "required": true + }, + "security": [ + { + "cookieAuth": [] + }, + { + "tokenAuth": [] + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Owner" + } + } + }, + "description": "" + } + } + }, + "patch": { + "operationId": "users_owners_partial_update", + "description": "Patch a owner object.", + "parameters": [ + { + "in": "path", + "name": "id", + "schema": { + "type": "integer" + }, + "description": "A unique integer value identifying this owner.", + "required": true + } + ], + "tags": [ + "users" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PatchedOwnerRequest" + } + }, + "multipart/form-data": { + "schema": { + "$ref": "#/components/schemas/PatchedOwnerRequest" + } + } + } + }, + "security": [ + { + "cookieAuth": [] + }, + { + "tokenAuth": [] + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Owner" + } + } + }, + "description": "" + } + } + }, + "delete": { + "operationId": "users_owners_destroy", + "description": "Delete a owner object.", + "parameters": [ + { + "in": "path", + "name": "id", + "schema": { + "type": "integer" + }, + "description": "A unique integer value identifying this owner.", + "required": true + } + ], + "tags": [ + "users" + ], + "security": [ + { + "cookieAuth": [] + }, + { + "tokenAuth": [] + } + ], + "responses": { + "204": { + "description": "No response body" + } + } + } + }, "/api/users/permissions/": { "get": { "operationId": "users_permissions_list", @@ -171504,6 +184288,13 @@ "explode": true, "style": "form" }, + { + "in": "query", + "name": "enabled", + "schema": { + "type": "boolean" + } + }, { "in": "query", "name": "expires", @@ -171768,86 +184559,25 @@ "in": "query", "name": "last_used", "schema": { - "type": "array", - "items": { - "type": "string", - "format": "date-time" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "last_used__empty", - "schema": { - "type": "boolean" + "type": "string", + "format": "date-time" } }, - { - "in": "query", - "name": "last_used__gt", - "schema": { - "type": "array", - "items": { - "type": "string", - "format": "date-time" - } - }, - "explode": true, - "style": "form" - }, { "in": "query", "name": "last_used__gte", "schema": { - "type": "array", - "items": { - "type": "string", - "format": "date-time" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "last_used__lt", - "schema": { - "type": "array", - "items": { - "type": "string", - "format": "date-time" - } - }, - "explode": true, - "style": "form" + "type": "string", + "format": "date-time" + } }, { "in": "query", "name": "last_used__lte", "schema": { - "type": "array", - "items": { - "type": "string", - "format": "date-time" - } - }, - "explode": true, - "style": "form" - }, - { - "in": "query", - "name": "last_used__n", - "schema": { - "type": "array", - "items": { - "type": "string", - "format": "date-time" - } - }, - "explode": true, - "style": "form" + "type": "string", + "format": "date-time" + } }, { "name": "limit", @@ -171876,6 +184606,91 @@ "type": "string" } }, + { + "in": "query", + "name": "pepper_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "pepper_id__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "pepper_id__gt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "pepper_id__gte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "pepper_id__lt", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "pepper_id__lte", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "pepper_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -171936,6 +184751,164 @@ "explode": true, "style": "form" }, + { + "in": "query", + "name": "version", + "schema": { + "type": "integer", + "x-spec-enum-id": "b5df70f0bffd12cb", + "enum": [ + 1, + 2, + "null" + ] + }, + "description": "* `1` - v1\n* `2` - v2" + }, + { + "in": "query", + "name": "version__ic", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "version__ie", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "version__iew", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "version__iregex", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "version__isw", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "version__n", + "schema": { + "type": "integer", + "x-spec-enum-id": "b5df70f0bffd12cb", + "enum": [ + 1, + 2, + "null" + ] + }, + "description": "* `1` - v1\n* `2` - v2" + }, + { + "in": "query", + "name": "version__nic", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "version__nie", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "version__niew", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "version__nisw", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "version__regex", + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "write_enabled", @@ -172941,13 +185914,6 @@ "type": "boolean" } }, - { - "in": "query", - "name": "is_staff", - "schema": { - "type": "boolean" - } - }, { "in": "query", "name": "is_superuser", @@ -173244,6 +186210,58 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer" + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer" + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "permission_id", @@ -174529,6 +187547,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -175768,6 +188840,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -177185,6 +190311,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -179391,6 +192571,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "parent_id", @@ -180729,6 +193963,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -182685,6 +195973,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "platform", @@ -183194,6 +196536,169 @@ "explode": true, "style": "form" }, + { + "in": "query", + "name": "start_on_boot", + "schema": { + "type": "array", + "items": { + "type": "string", + "x-spec-enum-id": "610e33fc2fde73d6" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "start_on_boot__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "start_on_boot__ic", + "schema": { + "type": "array", + "items": { + "type": "string", + "x-spec-enum-id": "610e33fc2fde73d6" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "start_on_boot__ie", + "schema": { + "type": "array", + "items": { + "type": "string", + "x-spec-enum-id": "610e33fc2fde73d6" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "start_on_boot__iew", + "schema": { + "type": "array", + "items": { + "type": "string", + "x-spec-enum-id": "610e33fc2fde73d6" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "start_on_boot__iregex", + "schema": { + "type": "array", + "items": { + "type": "string", + "x-spec-enum-id": "610e33fc2fde73d6" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "start_on_boot__isw", + "schema": { + "type": "array", + "items": { + "type": "string", + "x-spec-enum-id": "610e33fc2fde73d6" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "start_on_boot__n", + "schema": { + "type": "array", + "items": { + "type": "string", + "x-spec-enum-id": "610e33fc2fde73d6" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "start_on_boot__nic", + "schema": { + "type": "array", + "items": { + "type": "string", + "x-spec-enum-id": "610e33fc2fde73d6" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "start_on_boot__nie", + "schema": { + "type": "array", + "items": { + "type": "string", + "x-spec-enum-id": "610e33fc2fde73d6" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "start_on_boot__niew", + "schema": { + "type": "array", + "items": { + "type": "string", + "x-spec-enum-id": "610e33fc2fde73d6" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "start_on_boot__nisw", + "schema": { + "type": "array", + "items": { + "type": "string", + "x-spec-enum-id": "610e33fc2fde73d6" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "start_on_boot__regex", + "schema": { + "type": "array", + "items": { + "type": "string", + "x-spec-enum-id": "610e33fc2fde73d6" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "status", @@ -185003,6 +198508,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "preshared_key", @@ -187052,6 +200611,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -188273,6 +201886,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "pfs_group", @@ -189808,6 +203475,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -191322,6 +205043,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -194172,6 +207947,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -195915,6 +209744,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -198731,6 +212614,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -200217,6 +214154,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "parent", @@ -202000,6 +215991,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -204042,6 +218087,150 @@ }, "description": "* `km` - Kilometers\n* `m` - Meters\n* `mi` - Miles\n* `ft` - Feet" }, + { + "in": "query", + "name": "distance_unit__empty", + "schema": { + "type": "boolean" + } + }, + { + "in": "query", + "name": "distance_unit__ic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "distance_unit__ie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "distance_unit__iew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "distance_unit__iregex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "distance_unit__isw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "distance_unit__n", + "schema": { + "type": "string", + "x-spec-enum-id": "b1169a409430c02e", + "nullable": true, + "enum": [ + "ft", + "km", + "m", + "mi", + "null" + ] + }, + "description": "* `km` - Kilometers\n* `m` - Meters\n* `mi` - Miles\n* `ft` - Feet" + }, + { + "in": "query", + "name": "distance_unit__nic", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "distance_unit__nie", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "distance_unit__niew", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "distance_unit__nisw", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "distance_unit__regex", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "explode": true, + "style": "form" + }, { "in": "query", "name": "id", @@ -204301,6 +218490,60 @@ "type": "string" } }, + { + "in": "query", + "name": "owner", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner__n", + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Owner (name)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, + { + "in": "query", + "name": "owner_id__n", + "schema": { + "type": "array", + "items": { + "type": "integer", + "nullable": true + } + }, + "description": "Owner (ID)", + "explode": true, + "style": "form" + }, { "in": "query", "name": "q", @@ -205193,7 +219436,7 @@ "schemas": { "ASN": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -205240,6 +219483,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -205274,6 +219525,12 @@ "type": "integer", "format": "int64", "readOnly": true + }, + "sites": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ASNSite" + } } }, "required": [ @@ -205290,7 +219547,7 @@ }, "ASNRange": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -205346,6 +219603,17 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -205390,7 +219658,7 @@ }, "ASNRangeRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -205445,6 +219713,25 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -205466,7 +219753,7 @@ }, "ASNRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "asn": { "type": "integer", @@ -205511,6 +219798,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -205523,15 +219826,61 @@ "custom_fields": { "type": "object", "additionalProperties": {} + }, + "sites": { + "type": "array", + "items": { + "type": "integer" + } } }, "required": [ "asn" ] }, + "ASNSite": { + "type": "object", + "description": "This serializer is meant for inclusion in ASNSerializer and is only used\nto avoid a circular import of SiteSerializer.", + "properties": { + "id": { + "type": "integer", + "readOnly": true + }, + "url": { + "type": "string", + "format": "uri", + "readOnly": true + }, + "display": { + "type": "string", + "readOnly": true + }, + "name": { + "type": "string", + "description": "Full name of the site", + "maxLength": 100 + }, + "description": { + "type": "string", + "maxLength": 200 + }, + "slug": { + "type": "string", + "maxLength": 100, + "pattern": "^[-a-zA-Z0-9_]+$" + } + }, + "required": [ + "display", + "id", + "name", + "slug", + "url" + ] + }, "Aggregate": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -205596,6 +219945,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -205636,7 +219993,7 @@ }, "AggregateRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "prefix": { "type": "string", @@ -205677,6 +220034,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -206056,8 +220429,8 @@ "format": "int64" }, "object": { - "nullable": true, - "readOnly": true + "readOnly": true, + "nullable": true }, "user": { "$ref": "#/components/schemas/BriefUser" @@ -206400,7 +220773,7 @@ }, "BriefCable": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -206432,7 +220805,7 @@ }, "BriefCableRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "label": { "type": "string", @@ -206446,7 +220819,7 @@ }, "BriefCircuit": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -206485,7 +220858,7 @@ }, "BriefCircuitGroup": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -206599,7 +220972,7 @@ }, "BriefCircuitGroupRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -206613,7 +220986,7 @@ }, "BriefCircuitRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "cid": { "type": "string", @@ -206644,7 +221017,7 @@ }, "BriefCircuitType": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -206689,7 +221062,7 @@ }, "BriefCircuitTypeRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -206714,7 +221087,7 @@ }, "BriefCluster": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -206753,7 +221126,7 @@ }, "BriefClusterGroup": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -206798,7 +221171,7 @@ }, "BriefClusterGroupRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -206823,7 +221196,7 @@ }, "BriefClusterRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -206841,7 +221214,7 @@ }, "BriefClusterType": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -206886,7 +221259,7 @@ }, "BriefClusterTypeRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -206911,7 +221284,7 @@ }, "BriefConfigContextProfile": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -206944,7 +221317,7 @@ }, "BriefConfigContextProfileRequest": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -206962,7 +221335,7 @@ }, "BriefConfigTemplate": { "type": "object", - "description": "Introduces support for Tag assignment. Adds `tags` serialization, and handles tag assignment\non create() and update().", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -206995,7 +221368,7 @@ }, "BriefConfigTemplateRequest": { "type": "object", - "description": "Introduces support for Tag assignment. Adds `tags` serialization, and handles tag assignment\non create() and update().", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "name": { "type": "string", @@ -207013,7 +221386,7 @@ }, "BriefContact": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -207046,7 +221419,7 @@ }, "BriefContactRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -207064,7 +221437,7 @@ }, "BriefContactRole": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -207103,7 +221476,7 @@ }, "BriefContactRoleRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -207128,7 +221501,7 @@ }, "BriefCustomFieldChoiceSet": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -207166,7 +221539,7 @@ }, "BriefCustomFieldChoiceSetRequest": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "name": { "type": "string", @@ -207214,7 +221587,7 @@ }, "BriefDataSource": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -207247,7 +221620,7 @@ }, "BriefDataSourceRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -207265,7 +221638,7 @@ }, "BriefDevice": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -207298,7 +221671,7 @@ }, "BriefDeviceRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -207313,7 +221686,7 @@ }, "BriefDeviceRole": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "id": { "type": "integer", @@ -207370,7 +221743,7 @@ }, "BriefDeviceRoleRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -207395,7 +221768,7 @@ }, "BriefDeviceType": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -207428,7 +221801,6 @@ }, "device_count": { "type": "integer", - "format": "int64", "readOnly": true } }, @@ -207444,7 +221816,7 @@ }, "BriefDeviceTypeRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "manufacturer": { "oneOf": [ @@ -207480,7 +221852,7 @@ }, "BriefFHRPGroup": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -207529,7 +221901,7 @@ }, "BriefFHRPGroupRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "protocol": { "enum": [ @@ -207562,7 +221934,7 @@ }, "BriefIKEPolicy": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -207595,7 +221967,7 @@ }, "BriefIKEPolicyRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -207613,7 +221985,7 @@ }, "BriefIPAddress": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -207668,7 +222040,7 @@ }, "BriefIPAddressRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "address": { "type": "string", @@ -207685,7 +222057,7 @@ }, "BriefIPSecPolicy": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -207718,7 +222090,7 @@ }, "BriefIPSecPolicyRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -207736,7 +222108,7 @@ }, "BriefIPSecProfile": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -207769,7 +222141,7 @@ }, "BriefIPSecProfileRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -207787,7 +222159,7 @@ }, "BriefInterface": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -207840,7 +222212,7 @@ }, "BriefInterfaceRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -207869,7 +222241,7 @@ }, "BriefInventoryItemRole": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -207914,7 +222286,7 @@ }, "BriefInventoryItemRoleRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -208013,7 +222385,7 @@ }, "BriefL2VPN": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -208104,7 +222476,7 @@ }, "BriefL2VPNRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "identifier": { "type": "integer", @@ -208204,7 +222576,7 @@ }, "BriefLocation": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "id": { "type": "integer", @@ -208255,7 +222627,7 @@ }, "BriefLocationRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -208280,7 +222652,7 @@ }, "BriefMACAddress": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -208312,7 +222684,7 @@ }, "BriefMACAddressRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "mac_address": { "type": "string", @@ -208329,7 +222701,7 @@ }, "BriefManufacturer": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -208368,7 +222740,7 @@ }, "BriefManufacturerRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -208393,7 +222765,7 @@ }, "BriefModule": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -208425,7 +222797,7 @@ }, "BriefModuleRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "device": { "oneOf": [ @@ -208448,7 +222820,7 @@ }, "BriefModuleType": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -208481,6 +222853,10 @@ "description": { "type": "string", "maxLength": 200 + }, + "module_count": { + "type": "integer", + "readOnly": true } }, "required": [ @@ -208488,12 +222864,13 @@ "id", "manufacturer", "model", + "module_count", "url" ] }, "BriefModuleTypeProfile": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -208526,7 +222903,7 @@ }, "BriefModuleTypeProfileRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -208544,7 +222921,7 @@ }, "BriefModuleTypeRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "profile": { "oneOf": [ @@ -208587,9 +222964,111 @@ "model" ] }, + "BriefOwner": { + "type": "object", + "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "properties": { + "id": { + "type": "integer", + "readOnly": true + }, + "url": { + "type": "string", + "format": "uri", + "readOnly": true + }, + "display": { + "type": "string", + "readOnly": true + }, + "name": { + "type": "string", + "maxLength": 100 + }, + "description": { + "type": "string", + "maxLength": 200 + } + }, + "required": [ + "display", + "id", + "name", + "url" + ] + }, + "BriefOwnerGroup": { + "type": "object", + "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "properties": { + "id": { + "type": "integer", + "readOnly": true + }, + "url": { + "type": "string", + "format": "uri", + "readOnly": true + }, + "display": { + "type": "string", + "readOnly": true + }, + "name": { + "type": "string", + "maxLength": 100 + }, + "description": { + "type": "string", + "maxLength": 200 + } + }, + "required": [ + "display", + "id", + "name", + "url" + ] + }, + "BriefOwnerGroupRequest": { + "type": "object", + "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "description": { + "type": "string", + "maxLength": 200 + } + }, + "required": [ + "name" + ] + }, + "BriefOwnerRequest": { + "type": "object", + "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "description": { + "type": "string", + "maxLength": 200 + } + }, + "required": [ + "name" + ] + }, "BriefPlatform": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "id": { "type": "integer", @@ -208646,7 +223125,7 @@ }, "BriefPlatformRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -208671,7 +223150,7 @@ }, "BriefPowerPanel": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -208710,7 +223189,7 @@ }, "BriefPowerPanelRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -208728,7 +223207,7 @@ }, "BriefPowerPort": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -208781,7 +223260,7 @@ }, "BriefPowerPortRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -208863,7 +223342,7 @@ }, "BriefProvider": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -208909,7 +223388,7 @@ }, "BriefProviderAccount": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -208948,7 +223427,7 @@ }, "BriefProviderAccountRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -208972,7 +223451,7 @@ }, "BriefProviderNetwork": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -209005,7 +223484,7 @@ }, "BriefProviderNetworkRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -209023,7 +223502,7 @@ }, "BriefProviderRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -209049,7 +223528,7 @@ }, "BriefRIR": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -209094,7 +223573,7 @@ }, "BriefRIRRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -209119,7 +223598,7 @@ }, "BriefRack": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -209158,7 +223637,7 @@ }, "BriefRackRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -209176,7 +223655,7 @@ }, "BriefRackRole": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -209221,7 +223700,7 @@ }, "BriefRackRoleRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -209246,7 +223725,7 @@ }, "BriefRackType": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -209276,6 +223755,10 @@ "description": { "type": "string", "maxLength": 200 + }, + "rack_count": { + "type": "integer", + "readOnly": true } }, "required": [ @@ -209283,13 +223766,14 @@ "id", "manufacturer", "model", + "rack_count", "slug", "url" ] }, "BriefRackTypeRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "manufacturer": { "oneOf": [ @@ -209323,62 +223807,9 @@ "slug" ] }, - "BriefRearPortTemplate": { - "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", - "properties": { - "id": { - "type": "integer", - "readOnly": true - }, - "url": { - "type": "string", - "format": "uri", - "readOnly": true - }, - "display": { - "type": "string", - "readOnly": true - }, - "name": { - "type": "string", - "description": "{module} is accepted as a substitution for the module bay position when attached to a module type.", - "maxLength": 64 - }, - "description": { - "type": "string", - "maxLength": 200 - } - }, - "required": [ - "display", - "id", - "name", - "url" - ] - }, - "BriefRearPortTemplateRequest": { - "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", - "properties": { - "name": { - "type": "string", - "minLength": 1, - "description": "{module} is accepted as a substitution for the module bay position when attached to a module type.", - "maxLength": 64 - }, - "description": { - "type": "string", - "maxLength": 200 - } - }, - "required": [ - "name" - ] - }, "BriefRegion": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "id": { "type": "integer", @@ -209429,7 +223860,7 @@ }, "BriefRegionRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -209454,7 +223885,7 @@ }, "BriefRole": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -209505,7 +223936,7 @@ }, "BriefRoleRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -209530,7 +223961,7 @@ }, "BriefSite": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -209570,7 +224001,7 @@ }, "BriefSiteGroup": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "id": { "type": "integer", @@ -209621,7 +224052,7 @@ }, "BriefSiteGroupRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -209646,7 +224077,7 @@ }, "BriefSiteRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -209672,7 +224103,7 @@ }, "BriefTag": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -209716,7 +224147,7 @@ }, "BriefTenant": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -209755,7 +224186,7 @@ }, "BriefTenantGroup": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "id": { "type": "integer", @@ -209806,7 +224237,7 @@ }, "BriefTenantGroupRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -209831,7 +224262,7 @@ }, "BriefTenantRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -209856,7 +224287,7 @@ }, "BriefTunnel": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -209889,7 +224320,7 @@ }, "BriefTunnelGroup": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -209934,7 +224365,7 @@ }, "BriefTunnelGroupRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -209959,7 +224390,7 @@ }, "BriefTunnelRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -210024,7 +224455,7 @@ }, "BriefVLAN": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -210065,7 +224496,7 @@ }, "BriefVLANGroup": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -210110,7 +224541,7 @@ }, "BriefVLANGroupRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -210135,7 +224566,7 @@ }, "BriefVLANRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "vid": { "type": "integer", @@ -210161,7 +224592,7 @@ }, "BriefVLANTranslationPolicy": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -210194,7 +224625,7 @@ }, "BriefVLANTranslationPolicyRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -210212,7 +224643,7 @@ }, "BriefVRF": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -210258,7 +224689,7 @@ }, "BriefVRFRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -210283,7 +224714,7 @@ }, "BriefVirtualChassis": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -210329,7 +224760,7 @@ }, "BriefVirtualChassisRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -210355,7 +224786,7 @@ }, "BriefVirtualCircuit": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -210394,7 +224825,7 @@ }, "BriefVirtualCircuitRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "cid": { "type": "string", @@ -210425,7 +224856,7 @@ }, "BriefVirtualCircuitType": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -210470,7 +224901,7 @@ }, "BriefVirtualCircuitTypeRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -210495,7 +224926,7 @@ }, "BriefVirtualMachine": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -210528,7 +224959,7 @@ }, "BriefVirtualMachineRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -210546,7 +224977,7 @@ }, "BriefWirelessLANGroup": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "id": { "type": "integer", @@ -210597,7 +225028,7 @@ }, "BriefWirelessLANGroupRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -210622,7 +225053,7 @@ }, "Cable": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -210720,6 +225151,71 @@ } } }, + "profile": { + "type": "object", + "properties": { + "value": { + "enum": [ + "single-1c1p", + "single-1c2p", + "single-1c4p", + "single-1c6p", + "single-1c8p", + "single-1c12p", + "single-1c16p", + "trunk-2c1p", + "trunk-2c2p", + "trunk-2c4p", + "trunk-2c4p-shuffle", + "trunk-2c6p", + "trunk-2c8p", + "trunk-2c12p", + "trunk-4c1p", + "trunk-4c2p", + "trunk-4c4p", + "trunk-4c4p-shuffle", + "trunk-4c6p", + "trunk-4c8p", + "trunk-8c4p", + "breakout-1c4p-4c1p", + "breakout-1c6p-6c1p", + "breakout-2c4p-8c1p-shuffle" + ], + "type": "string", + "description": "* `single-1c1p` - 1C1P\n* `single-1c2p` - 1C2P\n* `single-1c4p` - 1C4P\n* `single-1c6p` - 1C6P\n* `single-1c8p` - 1C8P\n* `single-1c12p` - 1C12P\n* `single-1c16p` - 1C16P\n* `trunk-2c1p` - 2C1P trunk\n* `trunk-2c2p` - 2C2P trunk\n* `trunk-2c4p` - 2C4P trunk\n* `trunk-2c4p-shuffle` - 2C4P trunk (shuffle)\n* `trunk-2c6p` - 2C6P trunk\n* `trunk-2c8p` - 2C8P trunk\n* `trunk-2c12p` - 2C12P trunk\n* `trunk-4c1p` - 4C1P trunk\n* `trunk-4c2p` - 4C2P trunk\n* `trunk-4c4p` - 4C4P trunk\n* `trunk-4c4p-shuffle` - 4C4P trunk (shuffle)\n* `trunk-4c6p` - 4C6P trunk\n* `trunk-4c8p` - 4C8P trunk\n* `trunk-8c4p` - 8C4P trunk\n* `breakout-1c4p-4c1p` - 1C4P:4C1P breakout\n* `breakout-1c6p-6c1p` - 1C6P:6C1P breakout\n* `breakout-2c4p-8c1p-shuffle` - 2C4P:8C1P breakout (shuffle)", + "x-spec-enum-id": "5e0f85310f0184ea" + }, + "label": { + "type": "string", + "enum": [ + "1C1P", + "1C2P", + "1C4P", + "1C6P", + "1C8P", + "1C12P", + "1C16P", + "2C1P trunk", + "2C2P trunk", + "2C4P trunk", + "2C4P trunk (shuffle)", + "2C6P trunk", + "2C8P trunk", + "2C12P trunk", + "4C1P trunk", + "4C2P trunk", + "4C4P trunk", + "4C4P trunk (shuffle)", + "4C6P trunk", + "4C8P trunk", + "8C4P trunk", + "1C4P:4C1P breakout", + "1C6P:6C1P breakout", + "2C4P:8C1P breakout (shuffle)" + ] + } + } + }, "tenant": { "allOf": [ { @@ -210782,6 +225278,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -210819,7 +225323,7 @@ }, "CableRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "type": { "enum": [ @@ -210886,6 +225390,37 @@ "description": "* `connected` - Connected\n* `planned` - Planned\n* `decommissioning` - Decommissioning", "x-spec-enum-id": "80d251a40f3a3144" }, + "profile": { + "enum": [ + "single-1c1p", + "single-1c2p", + "single-1c4p", + "single-1c6p", + "single-1c8p", + "single-1c12p", + "single-1c16p", + "trunk-2c1p", + "trunk-2c2p", + "trunk-2c4p", + "trunk-2c4p-shuffle", + "trunk-2c6p", + "trunk-2c8p", + "trunk-2c12p", + "trunk-4c1p", + "trunk-4c2p", + "trunk-4c4p", + "trunk-4c4p-shuffle", + "trunk-4c6p", + "trunk-4c8p", + "trunk-8c4p", + "breakout-1c4p-4c1p", + "breakout-1c6p-6c1p", + "breakout-2c4p-8c1p-shuffle" + ], + "type": "string", + "description": "* `single-1c1p` - 1C1P\n* `single-1c2p` - 1C2P\n* `single-1c4p` - 1C4P\n* `single-1c6p` - 1C6P\n* `single-1c8p` - 1C8P\n* `single-1c12p` - 1C12P\n* `single-1c16p` - 1C16P\n* `trunk-2c1p` - 2C1P trunk\n* `trunk-2c2p` - 2C2P trunk\n* `trunk-2c4p` - 2C4P trunk\n* `trunk-2c4p-shuffle` - 2C4P trunk (shuffle)\n* `trunk-2c6p` - 2C6P trunk\n* `trunk-2c8p` - 2C8P trunk\n* `trunk-2c12p` - 2C12P trunk\n* `trunk-4c1p` - 4C1P trunk\n* `trunk-4c2p` - 4C2P trunk\n* `trunk-4c4p` - 4C4P trunk\n* `trunk-4c4p-shuffle` - 4C4P trunk (shuffle)\n* `trunk-4c6p` - 4C6P trunk\n* `trunk-4c8p` - 4C8P trunk\n* `trunk-8c4p` - 8C4P trunk\n* `breakout-1c4p-4c1p` - 1C4P:4C1P breakout\n* `breakout-1c6p-6c1p` - 1C6P:6C1P breakout\n* `breakout-2c4p-8c1p-shuffle` - 2C4P:8C1P breakout (shuffle)", + "x-spec-enum-id": "5e0f85310f0184ea" + }, "tenant": { "oneOf": [ { @@ -210940,6 +225475,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -210973,7 +225524,8 @@ "readOnly": true }, "cable": { - "type": "integer" + "type": "integer", + "readOnly": true }, "cable_end": { "enum": [ @@ -210983,20 +225535,35 @@ "type": "string", "description": "* `A` - A\n* `B` - B", "x-spec-enum-id": "1db84f9b93b261c8", + "readOnly": true, "title": "End" }, "termination_type": { - "type": "string" + "type": "string", + "readOnly": true }, "termination_id": { "type": "integer", - "maximum": 9223372036854775807, - "minimum": 0, - "format": "int64" + "readOnly": true }, "termination": { - "nullable": true, - "readOnly": true + "readOnly": true, + "nullable": true + }, + "connector": { + "type": "integer", + "readOnly": true, + "nullable": true + }, + "positions": { + "type": "array", + "items": { + "type": "integer", + "maximum": 1024, + "minimum": 1 + }, + "readOnly": true, + "nullable": true }, "created": { "type": "string", @@ -211014,50 +225581,18 @@ "required": [ "cable", "cable_end", + "connector", "created", "display", "id", "last_updated", + "positions", "termination", "termination_id", "termination_type", "url" ] }, - "CableTerminationRequest": { - "type": "object", - "description": "Adds support for custom fields and tags.", - "properties": { - "cable": { - "type": "integer" - }, - "cable_end": { - "enum": [ - "A", - "B" - ], - "type": "string", - "description": "* `A` - A\n* `B` - B", - "x-spec-enum-id": "1db84f9b93b261c8", - "title": "End" - }, - "termination_type": { - "type": "string" - }, - "termination_id": { - "type": "integer", - "maximum": 9223372036854775807, - "minimum": 0, - "format": "int64" - } - }, - "required": [ - "cable", - "cable_end", - "termination_id", - "termination_type" - ] - }, "ChangeDiff": { "type": "object", "description": "Adds support for custom fields and tags.", @@ -211175,7 +225710,7 @@ }, "Circuit": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -211331,6 +225866,14 @@ "readOnly": true, "nullable": true }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -211408,8 +225951,8 @@ "nullable": true }, "termination": { - "nullable": true, - "readOnly": true + "readOnly": true, + "nullable": true }, "port_speed": { "type": "integer", @@ -211488,7 +226031,7 @@ }, "CircuitGroup": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -211529,6 +226072,17 @@ ], "nullable": true }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -211604,8 +226158,8 @@ "format": "int64" }, "member": { - "nullable": true, - "readOnly": true + "readOnly": true, + "nullable": true }, "priority": { "type": "object", @@ -211715,7 +226269,7 @@ }, "CircuitGroupRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -211748,6 +226302,25 @@ ], "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -211766,7 +226339,7 @@ }, "CircuitRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "cid": { "type": "string", @@ -211887,6 +226460,22 @@ "x-spec-enum-id": "b1169a409430c02e", "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -211957,8 +226546,8 @@ "nullable": true }, "termination": { - "nullable": true, - "readOnly": true + "readOnly": true, + "nullable": true }, "port_speed": { "type": "integer", @@ -212151,7 +226740,7 @@ }, "CircuitType": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -212189,6 +226778,17 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -212231,7 +226831,7 @@ }, "CircuitTypeRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -212253,6 +226853,25 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -212271,7 +226890,7 @@ }, "Cluster": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -212350,13 +226969,21 @@ "nullable": true }, "scope": { - "nullable": true, - "readOnly": true + "readOnly": true, + "nullable": true }, "description": { "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -212429,7 +227056,7 @@ }, "ClusterGroup": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -212462,6 +227089,17 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -212504,7 +227142,7 @@ }, "ClusterGroupRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -212521,6 +227159,25 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -212539,7 +227196,7 @@ }, "ClusterRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -212612,6 +227269,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -212633,7 +227306,7 @@ }, "ClusterType": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -212666,6 +227339,17 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -212708,7 +227392,7 @@ }, "ClusterTypeRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -212725,6 +227409,25 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -212751,7 +227454,7 @@ }, "ConfigContext": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -212867,6 +227570,14 @@ "$ref": "#/components/schemas/Tenant" } }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -212926,7 +227637,7 @@ }, "ConfigContextProfile": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -212961,9 +227672,17 @@ "tags": { "type": "array", "items": { - "type": "string" + "$ref": "#/components/schemas/NestedTag" } }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -213018,7 +227737,7 @@ }, "ConfigContextProfileRequest": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -213036,10 +227755,25 @@ "tags": { "type": "array", "items": { - "type": "string", - "minLength": 1 + "$ref": "#/components/schemas/NestedTagRequest" } }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -213060,7 +227794,7 @@ }, "ConfigContextRequest": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "name": { "type": "string", @@ -213167,6 +227901,22 @@ "type": "integer" } }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -213193,7 +227943,7 @@ }, "ConfigTemplate": { "type": "object", - "description": "Introduces support for Tag assignment. Adds `tags` serialization, and handles tag assignment\non create() and update().", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -213271,6 +228021,14 @@ "nullable": true, "title": "Date synced" }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -213305,7 +228063,7 @@ }, "ConfigTemplateRequest": { "type": "object", - "description": "Introduces support for Tag assignment. Adds `tags` serialization, and handles tag assignment\non create() and update().", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "name": { "type": "string", @@ -213359,6 +228117,22 @@ "type": "boolean", "description": "Enable automatic synchronization of data when the data file is updated" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -213373,7 +228147,7 @@ }, "ConsolePort": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -213543,6 +228317,14 @@ "type": "boolean", "readOnly": true }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -213592,7 +228374,7 @@ }, "ConsolePortRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -213678,6 +228460,22 @@ "type": "boolean", "description": "Treat as if a cable is connected" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -213892,7 +228690,7 @@ }, "ConsoleServerPort": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -214062,6 +228860,14 @@ "type": "boolean", "readOnly": true }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -214111,7 +228917,7 @@ }, "ConsoleServerPortRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -214197,6 +229003,22 @@ "type": "boolean", "description": "Treat as if a cable is connected" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -214411,7 +229233,7 @@ }, "Contact": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -214467,6 +229289,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -214530,9 +229360,8 @@ "format": "int64" }, "object": { - "type": "object", - "additionalProperties": {}, - "readOnly": true + "readOnly": true, + "nullable": true }, "contact": { "$ref": "#/components/schemas/BriefContact" @@ -214676,7 +229505,7 @@ }, "ContactGroup": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "id": { "type": "integer", @@ -214744,6 +229573,14 @@ "readOnly": true, "default": 0 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -214768,7 +229605,7 @@ }, "ContactGroupRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -214803,6 +229640,22 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" } @@ -214814,7 +229667,7 @@ }, "ContactRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "groups": { "type": "array", @@ -214853,6 +229706,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -214873,7 +229742,7 @@ }, "ContactRole": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -214906,6 +229775,17 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -214942,7 +229822,7 @@ }, "ContactRoleRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -214959,6 +229839,25 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -214977,7 +229876,7 @@ }, "CustomField": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -215212,6 +230111,14 @@ ], "nullable": true }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -215243,7 +230150,7 @@ }, "CustomFieldChoiceSet": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -215311,6 +230218,14 @@ "type": "integer", "readOnly": true }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "created": { "type": "string", "format": "date-time", @@ -215338,7 +230253,7 @@ }, "CustomFieldChoiceSetRequest": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "name": { "type": "string", @@ -215371,6 +230286,22 @@ "order_alphabetically": { "type": "boolean", "description": "Choices are automatically ordered alphabetically" + }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true } }, "required": [ @@ -215380,7 +230311,7 @@ }, "CustomFieldRequest": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "object_types": { "type": "array", @@ -215540,6 +230471,22 @@ ], "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" } @@ -215552,7 +230499,7 @@ }, "CustomLink": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -215629,6 +230576,14 @@ "type": "boolean", "description": "Force link to open in a new window" }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "created": { "type": "string", "format": "date-time", @@ -215657,7 +230612,7 @@ }, "CustomLinkRequest": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "object_types": { "type": "array", @@ -215718,6 +230673,22 @@ "new_window": { "type": "boolean", "description": "Force link to open in a new window" + }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true } }, "required": [ @@ -215805,7 +230776,7 @@ }, "DataSource": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -215917,6 +230888,14 @@ "type": "string", "description": "Patterns (one per line) matching files to ignore when syncing" }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -215965,7 +230944,7 @@ }, "DataSourceRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -216019,6 +230998,22 @@ "type": "string", "description": "Patterns (one per line) matching files to ignore when syncing" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -216035,7 +231030,7 @@ }, "Device": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -216304,6 +231299,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -216408,7 +231411,7 @@ }, "DeviceBay": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -216452,6 +231455,14 @@ ], "nullable": true }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -216488,7 +231499,7 @@ }, "DeviceBayRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -216530,6 +231541,22 @@ ], "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -216640,7 +231667,7 @@ }, "DeviceRole": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "id": { "type": "integer", @@ -216730,6 +231757,14 @@ "readOnly": true, "default": 0 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -216755,7 +231790,7 @@ }, "DeviceRoleRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -216816,6 +231851,22 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" } @@ -216827,7 +231878,7 @@ }, "DeviceType": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -217004,6 +232055,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -217031,7 +232090,6 @@ }, "device_count": { "type": "integer", - "format": "int64", "readOnly": true }, "console_port_template_count": { @@ -217100,7 +232158,7 @@ }, "DeviceTypeRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "manufacturer": { "oneOf": [ @@ -217230,6 +232288,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -217252,7 +232326,7 @@ }, "DeviceWithConfigContext": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -217521,6 +232595,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -217630,7 +232712,7 @@ }, "DeviceWithConfigContextRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -217907,6 +232989,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -217949,7 +233047,7 @@ }, "EventRule": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -218043,9 +233141,8 @@ "nullable": true }, "action_object": { - "type": "object", - "additionalProperties": {}, - "readOnly": true + "readOnly": true, + "nullable": true }, "description": { "type": "string", @@ -218055,6 +233152,14 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -218091,7 +233196,7 @@ }, "EventRuleRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "object_types": { "type": "array", @@ -218162,6 +233267,22 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -218179,7 +233300,7 @@ }, "ExportTemplate": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -218264,6 +233385,14 @@ "nullable": true, "title": "Date synced" }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "created": { "type": "string", "format": "date-time", @@ -218294,7 +233423,7 @@ }, "ExportTemplateRequest": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "object_types": { "type": "array", @@ -218349,6 +233478,22 @@ "$ref": "#/components/schemas/BriefDataSourceRequest" } ] + }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true } }, "required": [ @@ -218359,7 +233504,7 @@ }, "FHRPGroup": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -218424,6 +233569,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -218499,8 +233652,8 @@ "format": "int64" }, "interface": { - "nullable": true, - "readOnly": true + "readOnly": true, + "nullable": true }, "priority": { "type": "integer", @@ -218571,7 +233724,7 @@ }, "FHRPGroupRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -218618,6 +233771,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -218639,7 +233808,7 @@ }, "FrontPort": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -218817,14 +233986,16 @@ "pattern": "^[0-9a-f]{6}$", "maxLength": 6 }, - "rear_port": { - "$ref": "#/components/schemas/FrontPortRearPort" - }, - "rear_port_position": { + "positions": { "type": "integer", "maximum": 1024, - "minimum": 1, - "description": "Mapped position on corresponding rear port" + "minimum": 1 + }, + "rear_ports": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FrontPortMapping" + } }, "description": { "type": "string", @@ -218858,6 +234029,14 @@ "readOnly": true, "nullable": true }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -218899,81 +234078,55 @@ "link_peers", "link_peers_type", "name", - "rear_port", "type", "url" ] }, - "FrontPortRearPort": { + "FrontPortMapping": { "type": "object", - "description": "NestedRearPortSerializer but with parent device omitted (since front and rear ports must belong to same device)", "properties": { - "id": { + "position": { + "type": "integer" + }, + "rear_port": { + "type": "integer" + }, + "rear_port_position": { "type": "integer", - "readOnly": true - }, - "url": { - "type": "string", - "format": "uri", - "readOnly": true - }, - "display_url": { - "type": "string", - "format": "uri", - "readOnly": true - }, - "display": { - "type": "string", - "readOnly": true - }, - "name": { - "type": "string", - "maxLength": 64 - }, - "label": { - "type": "string", - "description": "Physical label", - "maxLength": 64 - }, - "description": { - "type": "string", - "maxLength": 200 + "maximum": 1024, + "minimum": 1, + "default": 1 } }, "required": [ - "display", - "display_url", - "id", - "name", - "url" + "position", + "rear_port" ] }, - "FrontPortRearPortRequest": { + "FrontPortMappingRequest": { "type": "object", - "description": "NestedRearPortSerializer but with parent device omitted (since front and rear ports must belong to same device)", "properties": { - "name": { - "type": "string", - "minLength": 1, - "maxLength": 64 + "position": { + "type": "integer" }, - "label": { - "type": "string", - "description": "Physical label", - "maxLength": 64 + "rear_port": { + "type": "integer" }, - "description": { - "type": "string", - "maxLength": 200 + "rear_port_position": { + "type": "integer", + "maximum": 1024, + "minimum": 1, + "default": 1 } }, "required": [ - "name" + "position", + "rear_port" ] }, "FrontPortRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -219081,14 +234234,16 @@ "pattern": "^[0-9a-f]{6}$", "maxLength": 6 }, - "rear_port": { - "$ref": "#/components/schemas/FrontPortRearPortRequest" - }, - "rear_port_position": { + "positions": { "type": "integer", "maximum": 1024, - "minimum": 1, - "description": "Mapped position on corresponding rear port" + "minimum": 1 + }, + "rear_ports": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FrontPortMappingRequest" + } }, "description": { "type": "string", @@ -219098,6 +234253,22 @@ "type": "boolean", "description": "Treat as if a cable is connected" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -219112,7 +234283,6 @@ "required": [ "device", "name", - "rear_port", "type" ] }, @@ -219297,14 +234467,17 @@ "pattern": "^[0-9a-f]{6}$", "maxLength": 6 }, - "rear_port": { - "$ref": "#/components/schemas/BriefRearPortTemplate" - }, - "rear_port_position": { + "positions": { "type": "integer", "maximum": 1024, "minimum": 1 }, + "rear_ports": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FrontPortTemplateMapping" + } + }, "description": { "type": "string", "maxLength": 200 @@ -219328,11 +234501,52 @@ "id", "last_updated", "name", - "rear_port", "type", "url" ] }, + "FrontPortTemplateMapping": { + "type": "object", + "properties": { + "position": { + "type": "integer" + }, + "rear_port": { + "type": "integer" + }, + "rear_port_position": { + "type": "integer", + "maximum": 1024, + "minimum": 1, + "default": 1 + } + }, + "required": [ + "position", + "rear_port" + ] + }, + "FrontPortTemplateMappingRequest": { + "type": "object", + "properties": { + "position": { + "type": "integer" + }, + "rear_port": { + "type": "integer" + }, + "rear_port_position": { + "type": "integer", + "maximum": 1024, + "minimum": 1, + "default": 1 + } + }, + "required": [ + "position", + "rear_port" + ] + }, "FrontPortTemplateRequest": { "type": "object", "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", @@ -219450,21 +234664,17 @@ "pattern": "^[0-9a-f]{6}$", "maxLength": 6 }, - "rear_port": { - "oneOf": [ - { - "type": "integer" - }, - { - "$ref": "#/components/schemas/BriefRearPortTemplateRequest" - } - ] - }, - "rear_port_position": { + "positions": { "type": "integer", "maximum": 1024, "minimum": 1 }, + "rear_ports": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FrontPortTemplateMappingRequest" + } + }, "description": { "type": "string", "maxLength": 200 @@ -219472,7 +234682,6 @@ }, "required": [ "name", - "rear_port", "type" ] }, @@ -219589,7 +234798,7 @@ }, "IKEPolicy": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -219669,6 +234878,14 @@ "type": "string", "title": "Pre-shared key" }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -219708,7 +234925,7 @@ }, "IKEPolicyRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -219747,6 +234964,22 @@ "type": "string", "title": "Pre-shared key" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -219768,7 +235001,7 @@ }, "IKEProposal": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -219953,6 +235186,14 @@ "nullable": true, "description": "Security association lifetime (in seconds)" }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -219994,7 +235235,7 @@ }, "IKEProposalRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -220081,6 +235322,22 @@ "nullable": true, "description": "Security association lifetime (in seconds)" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -220104,7 +235361,7 @@ }, "IPAddress": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -220238,8 +235495,8 @@ "nullable": true }, "assigned_object": { - "nullable": true, - "readOnly": true + "readOnly": true, + "nullable": true }, "nat_inside": { "allOf": [ @@ -220266,6 +235523,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -220307,7 +235572,7 @@ }, "IPAddressRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "address": { "type": "string", @@ -220402,6 +235667,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -220422,7 +235703,7 @@ }, "IPRange": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -220525,6 +235806,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -220574,7 +235863,7 @@ }, "IPRangeRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "start_address": { "type": "string", @@ -220646,6 +235935,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -220675,7 +235980,7 @@ }, "IPSecPolicy": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -220774,6 +236079,14 @@ } } }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -220812,7 +236125,7 @@ }, "IPSecPolicyRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -220860,6 +236173,22 @@ "description": "* `1` - Group 1\n* `2` - Group 2\n* `5` - Group 5\n* `14` - Group 14\n* `15` - Group 15\n* `16` - Group 16\n* `17` - Group 17\n* `18` - Group 18\n* `19` - Group 19\n* `20` - Group 20\n* `21` - Group 21\n* `22` - Group 22\n* `23` - Group 23\n* `24` - Group 24\n* `25` - Group 25\n* `26` - Group 26\n* `27` - Group 27\n* `28` - Group 28\n* `29` - Group 29\n* `30` - Group 30\n* `31` - Group 31\n* `32` - Group 32\n* `33` - Group 33\n* `34` - Group 34", "x-spec-enum-id": "dbef43be795462a8" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -220880,7 +236209,7 @@ }, "IPSecProfile": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -220935,6 +236264,14 @@ "ipsec_policy": { "$ref": "#/components/schemas/BriefIPSecPolicy" }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -220976,7 +236313,7 @@ }, "IPSecProfileRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -221016,6 +236353,22 @@ } ] }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -221039,7 +236392,7 @@ }, "IPSecProposal": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -221143,6 +236496,14 @@ "title": "SA lifetime (KB)", "description": "Security association lifetime (in kilobytes)" }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -221181,7 +236542,7 @@ }, "IPSecProposalRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -221235,6 +236596,22 @@ "title": "SA lifetime (KB)", "description": "Security association lifetime (in kilobytes)" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -221280,8 +236657,8 @@ "format": "int64" }, "parent": { - "nullable": true, - "readOnly": true + "readOnly": true, + "nullable": true }, "name": { "type": "string", @@ -221388,7 +236765,7 @@ }, "Interface": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -222620,6 +237997,14 @@ "type": "boolean", "readOnly": true }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -222685,7 +238070,7 @@ }, "InterfaceRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -223386,6 +238771,22 @@ ], "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -224330,7 +239731,7 @@ }, "InventoryItem": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -224447,8 +239848,16 @@ "nullable": true }, "component": { - "nullable": true, - "readOnly": true + "readOnly": true, + "nullable": true + }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true }, "tags": { "type": "array", @@ -224493,7 +239902,7 @@ }, "InventoryItemRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -224599,6 +240008,22 @@ "format": "int64", "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -224617,7 +240042,7 @@ }, "InventoryItemRole": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -224655,6 +240080,17 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -224697,7 +240133,7 @@ }, "InventoryItemRoleRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -224720,6 +240156,25 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -224807,8 +240262,8 @@ "nullable": true }, "component": { - "nullable": true, - "readOnly": true + "readOnly": true, + "nullable": true }, "created": { "type": "string", @@ -225095,8 +240550,8 @@ "format": "int64" }, "assigned_object": { - "nullable": true, - "readOnly": true + "readOnly": true, + "nullable": true }, "created": { "type": "string", @@ -225217,7 +240672,7 @@ }, "L2VPN": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -225337,6 +240792,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -225384,7 +240847,7 @@ }, "L2VPNRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "identifier": { "type": "integer", @@ -225451,6 +240914,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -225521,8 +241000,8 @@ "format": "int64" }, "assigned_object": { - "nullable": true, - "readOnly": true + "readOnly": true, + "nullable": true }, "tags": { "type": "array", @@ -225602,7 +241081,7 @@ }, "Location": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "id": { "type": "integer", @@ -225723,6 +241202,14 @@ "format": "int64", "readOnly": true }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -225750,7 +241237,7 @@ }, "LocationRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -225828,6 +241315,22 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" } @@ -225840,7 +241343,7 @@ }, "MACAddress": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -225875,13 +241378,21 @@ "nullable": true }, "assigned_object": { - "nullable": true, - "readOnly": true + "readOnly": true, + "nullable": true }, "description": { "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -225921,7 +241432,7 @@ }, "MACAddressRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "mac_address": { "type": "string", @@ -225942,6 +241453,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -225962,7 +241489,7 @@ }, "Manufacturer": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -225995,6 +241522,17 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -226022,6 +241560,11 @@ "format": "int64", "readOnly": true }, + "moduletype_count": { + "type": "integer", + "format": "int64", + "readOnly": true + }, "inventoryitem_count": { "type": "integer", "format": "int64", @@ -226041,6 +241584,7 @@ "id", "inventoryitem_count", "last_updated", + "moduletype_count", "name", "platform_count", "slug", @@ -226049,7 +241593,7 @@ }, "ManufacturerRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -226066,6 +241610,25 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -226084,7 +241647,7 @@ }, "Module": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -226157,6 +241720,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -226197,7 +241768,7 @@ }, "ModuleBay": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -226254,6 +241825,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -226290,7 +241869,7 @@ }, "ModuleBayRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -226353,6 +241932,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -226506,7 +242101,7 @@ }, "ModuleRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "device": { "oneOf": [ @@ -226559,6 +242154,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -226581,7 +242192,7 @@ }, "ModuleType": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -226697,6 +242308,14 @@ "attributes": { "nullable": true }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -226721,6 +242340,10 @@ "format": "date-time", "readOnly": true, "nullable": true + }, + "module_count": { + "type": "integer", + "readOnly": true } }, "required": [ @@ -226731,12 +242354,13 @@ "last_updated", "manufacturer", "model", + "module_count", "url" ] }, "ModuleTypeProfile": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -226767,6 +242391,14 @@ "schema": { "nullable": true }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -226805,7 +242437,7 @@ }, "ModuleTypeProfileRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -226819,6 +242451,22 @@ "schema": { "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -226839,7 +242487,7 @@ }, "ModuleTypeRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "profile": { "oneOf": [ @@ -226923,6 +242571,22 @@ "attributes": { "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -228142,8 +243806,8 @@ "format": "int64" }, "object": { - "nullable": true, - "readOnly": true + "readOnly": true, + "nullable": true }, "user": { "$ref": "#/components/schemas/BriefUser" @@ -228406,7 +244070,11 @@ "format": "int64" }, "changed_object": { - "nullable": true, + "readOnly": true, + "nullable": true + }, + "object_repr": { + "type": "string", "readOnly": true }, "message": { @@ -228431,6 +244099,7 @@ "display_url", "id", "message", + "object_repr", "postchange_data", "prechange_data", "request_id", @@ -228646,6 +244315,176 @@ "url" ] }, + "Owner": { + "type": "object", + "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "properties": { + "id": { + "type": "integer", + "readOnly": true + }, + "url": { + "type": "string", + "format": "uri", + "readOnly": true + }, + "display_url": { + "type": "string", + "format": "uri", + "readOnly": true + }, + "display": { + "type": "string", + "readOnly": true + }, + "name": { + "type": "string", + "maxLength": 100 + }, + "group": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerGroup" + } + ], + "nullable": true + }, + "description": { + "type": "string", + "maxLength": 200 + }, + "user_groups": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Group" + } + }, + "users": { + "type": "array", + "items": { + "$ref": "#/components/schemas/User" + } + } + }, + "required": [ + "display", + "display_url", + "group", + "id", + "name", + "url" + ] + }, + "OwnerGroup": { + "type": "object", + "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "properties": { + "id": { + "type": "integer", + "readOnly": true + }, + "url": { + "type": "string", + "format": "uri", + "readOnly": true + }, + "display_url": { + "type": "string", + "format": "uri", + "readOnly": true + }, + "display": { + "type": "string", + "readOnly": true + }, + "name": { + "type": "string", + "maxLength": 100 + }, + "description": { + "type": "string", + "maxLength": 200 + }, + "member_count": { + "type": "integer", + "format": "int64", + "readOnly": true + } + }, + "required": [ + "display", + "display_url", + "id", + "member_count", + "name", + "url" + ] + }, + "OwnerGroupRequest": { + "type": "object", + "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "description": { + "type": "string", + "maxLength": 200 + } + }, + "required": [ + "name" + ] + }, + "OwnerRequest": { + "type": "object", + "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "group": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerGroupRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "description": { + "type": "string", + "maxLength": 200 + }, + "user_groups": { + "type": "array", + "items": { + "type": "integer" + } + }, + "users": { + "type": "array", + "items": { + "type": "integer" + } + } + }, + "required": [ + "group", + "name" + ] + }, "PaginatedASNList": { "type": "object", "required": [ @@ -230971,6 +246810,68 @@ } } }, + "PaginatedOwnerGroupList": { + "type": "object", + "required": [ + "count", + "results" + ], + "properties": { + "count": { + "type": "integer", + "example": 123 + }, + "next": { + "type": "string", + "nullable": true, + "format": "uri", + "example": "http://api.example.org/accounts/?offset=400&limit=100" + }, + "previous": { + "type": "string", + "nullable": true, + "format": "uri", + "example": "http://api.example.org/accounts/?offset=200&limit=100" + }, + "results": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OwnerGroup" + } + } + } + }, + "PaginatedOwnerList": { + "type": "object", + "required": [ + "count", + "results" + ], + "properties": { + "count": { + "type": "integer", + "example": 123 + }, + "next": { + "type": "string", + "nullable": true, + "format": "uri", + "example": "http://api.example.org/accounts/?offset=400&limit=100" + }, + "previous": { + "type": "string", + "nullable": true, + "format": "uri", + "example": "http://api.example.org/accounts/?offset=200&limit=100" + }, + "results": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Owner" + } + } + } + }, "PaginatedPlatformList": { "type": "object", "required": [ @@ -232709,7 +248610,7 @@ }, "PatchedASNRangeRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -232764,6 +248665,25 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -232778,7 +248698,7 @@ }, "PatchedASNRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "asn": { "type": "integer", @@ -232823,6 +248743,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -232835,6 +248771,12 @@ "custom_fields": { "type": "object", "additionalProperties": {} + }, + "sites": { + "type": "array", + "items": { + "type": "integer" + } } } }, @@ -232863,37 +248805,9 @@ } } }, - "PatchedCableTerminationRequest": { - "type": "object", - "description": "Adds support for custom fields and tags.", - "properties": { - "cable": { - "type": "integer" - }, - "cable_end": { - "enum": [ - "A", - "B" - ], - "type": "string", - "description": "* `A` - A\n* `B` - B", - "x-spec-enum-id": "1db84f9b93b261c8", - "title": "End" - }, - "termination_type": { - "type": "string" - }, - "termination_id": { - "type": "integer", - "maximum": 9223372036854775807, - "minimum": 0, - "format": "int64" - } - } - }, "PatchedCircuitGroupRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -232926,6 +248840,25 @@ ], "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -233020,7 +248953,7 @@ }, "PatchedCircuitTypeRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -233042,6 +248975,25 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -233056,7 +249008,7 @@ }, "PatchedClusterGroupRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -233073,6 +249025,25 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -233087,7 +249058,7 @@ }, "PatchedClusterTypeRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -233104,6 +249075,25 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -233118,7 +249108,7 @@ }, "PatchedConfigContextProfileRequest": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -233136,10 +249126,25 @@ "tags": { "type": "array", "items": { - "type": "string", - "minLength": 1 + "$ref": "#/components/schemas/NestedTagRequest" } }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -233157,7 +249162,7 @@ }, "PatchedConfigContextRequest": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "name": { "type": "string", @@ -233264,6 +249269,22 @@ "type": "integer" } }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -233286,7 +249307,7 @@ }, "PatchedConfigTemplateRequest": { "type": "object", - "description": "Introduces support for Tag assignment. Adds `tags` serialization, and handles tag assignment\non create() and update().", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "name": { "type": "string", @@ -233340,6 +249361,22 @@ "type": "boolean", "description": "Enable automatic synchronization of data when the data file is updated" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -233350,7 +249387,7 @@ }, "PatchedContactRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "groups": { "type": "array", @@ -233389,6 +249426,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -233406,7 +249459,7 @@ }, "PatchedContactRoleRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -233423,6 +249476,25 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -233437,7 +249509,7 @@ }, "PatchedCustomLinkRequest": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "object_types": { "type": "array", @@ -233498,6 +249570,22 @@ "new_window": { "type": "boolean", "description": "Force link to open in a new window" + }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true } } }, @@ -233510,7 +249598,7 @@ }, "PatchedDeviceBayRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -233552,6 +249640,22 @@ ], "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -233597,7 +249701,7 @@ }, "PatchedExportTemplateRequest": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "object_types": { "type": "array", @@ -233652,6 +249756,22 @@ "$ref": "#/components/schemas/BriefDataSourceRequest" } ] + }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true } } }, @@ -233687,7 +249807,7 @@ }, "PatchedFHRPGroupRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -233734,6 +249854,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -233799,7 +249935,7 @@ }, "PatchedInventoryItemRoleRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -233822,6 +249958,25 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -233954,7 +250109,7 @@ }, "PatchedMACAddressRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "mac_address": { "type": "string", @@ -233975,6 +250130,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -233992,7 +250163,7 @@ }, "PatchedManufacturerRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -234009,6 +250180,25 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -234023,7 +250213,7 @@ }, "PatchedModuleBayRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -234086,6 +250276,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -234158,7 +250364,7 @@ }, "PatchedModuleTypeProfileRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -234172,6 +250378,22 @@ "schema": { "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -234313,9 +250535,67 @@ } } }, + "PatchedOwnerGroupRequest": { + "type": "object", + "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "description": { + "type": "string", + "maxLength": 200 + } + } + }, + "PatchedOwnerRequest": { + "type": "object", + "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "group": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerGroupRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "description": { + "type": "string", + "maxLength": 200 + }, + "user_groups": { + "type": "array", + "items": { + "type": "integer" + } + }, + "users": { + "type": "array", + "items": { + "type": "integer" + } + } + } + }, "PatchedPowerPanelRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "site": { "oneOf": [ @@ -234352,6 +250632,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -234369,7 +250665,7 @@ }, "PatchedProviderAccountRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "provider": { "oneOf": [ @@ -234396,6 +250692,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -234413,7 +250725,7 @@ }, "PatchedProviderNetworkRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "provider": { "oneOf": [ @@ -234438,6 +250750,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -234455,7 +250783,7 @@ }, "PatchedProviderRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -234479,6 +250807,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -234502,7 +250846,7 @@ }, "PatchedRIRRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -234524,6 +250868,25 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -234538,7 +250901,7 @@ }, "PatchedRackRoleRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -234561,6 +250924,25 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -234575,7 +250957,7 @@ }, "PatchedRoleRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -234597,6 +250979,25 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -234611,7 +251012,7 @@ }, "PatchedRouteTargetRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -234639,6 +251040,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -234656,7 +251073,7 @@ }, "PatchedSavedFilterRequest": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "object_types": { "type": "array", @@ -234694,7 +251111,23 @@ "shared": { "type": "boolean" }, - "parameters": {} + "parameters": {}, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + } } }, "PatchedScriptInputRequest": { @@ -234797,7 +251230,7 @@ }, "PatchedTagRequest": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "name": { "type": "string", @@ -234835,7 +251268,7 @@ }, "PatchedTenantRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -234868,6 +251301,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -234887,6 +251336,17 @@ "type": "object", "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", "properties": { + "version": { + "enum": [ + 1, + 2 + ], + "type": "integer", + "description": "* `1` - v1\n* `2` - v2", + "x-spec-enum-id": "b5df70f0bffd12cb", + "minimum": 0, + "maximum": 32767 + }, "user": { "oneOf": [ { @@ -234897,6 +251357,10 @@ } ] }, + "description": { + "type": "string", + "maxLength": 200 + }, "expires": { "type": "string", "format": "date-time", @@ -234907,24 +251371,30 @@ "format": "date-time", "nullable": true }, - "key": { - "type": "string", - "maxLength": 40, - "minLength": 40 + "enabled": { + "type": "boolean", + "description": "Disable to temporarily revoke this token without deleting it." }, "write_enabled": { "type": "boolean", "description": "Permit create/update/delete operations using this key" }, - "description": { + "pepper_id": { + "type": "integer", + "maximum": 32767, + "minimum": 0, + "nullable": true, + "description": "ID of the cryptographic pepper used to hash the token (v2 only)" + }, + "token": { "type": "string", - "maxLength": 200 + "minLength": 1 } } }, "PatchedTunnelGroupRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -234941,6 +251411,25 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -234984,11 +251473,6 @@ "title": "Email address", "maxLength": 254 }, - "is_staff": { - "type": "boolean", - "title": "Staff status", - "description": "Designates whether the user can log into this admin site." - }, "is_active": { "type": "boolean", "title": "Active", @@ -235019,7 +251503,7 @@ }, "PatchedVLANGroupRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -235066,6 +251550,25 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -235080,7 +251583,7 @@ }, "PatchedVLANTranslationPolicyRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -235090,6 +251593,25 @@ "description": { "type": "string", "maxLength": 200 + }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" } } }, @@ -235122,7 +251644,7 @@ }, "PatchedVRFRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -235161,6 +251683,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -235190,7 +251728,7 @@ }, "PatchedVirtualCircuitTypeRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -235212,6 +251750,25 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -235226,7 +251783,7 @@ }, "PatchedVirtualDiskRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "virtual_machine": { "oneOf": [ @@ -235253,6 +251810,22 @@ "minimum": 0, "title": "Size (MB)" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -235267,7 +251840,7 @@ }, "PatchedWebhookRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "name": { "type": "string", @@ -235330,6 +251903,22 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -235340,7 +251929,7 @@ }, "PatchedWritableAggregateRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "prefix": { "type": "string", @@ -235381,6 +251970,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -235431,7 +252036,7 @@ }, "PatchedWritableCableRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "type": { "enum": [ @@ -235498,6 +252103,38 @@ "description": "* `connected` - Connected\n* `planned` - Planned\n* `decommissioning` - Decommissioning", "x-spec-enum-id": "80d251a40f3a3144" }, + "profile": { + "enum": [ + "single-1c1p", + "single-1c2p", + "single-1c4p", + "single-1c6p", + "single-1c8p", + "single-1c12p", + "single-1c16p", + "trunk-2c1p", + "trunk-2c2p", + "trunk-2c4p", + "trunk-2c4p-shuffle", + "trunk-2c6p", + "trunk-2c8p", + "trunk-2c12p", + "trunk-4c1p", + "trunk-4c2p", + "trunk-4c4p", + "trunk-4c4p-shuffle", + "trunk-4c6p", + "trunk-4c8p", + "trunk-8c4p", + "breakout-1c4p-4c1p", + "breakout-1c6p-6c1p", + "breakout-2c4p-8c1p-shuffle", + "" + ], + "type": "string", + "description": "* `single-1c1p` - 1C1P\n* `single-1c2p` - 1C2P\n* `single-1c4p` - 1C4P\n* `single-1c6p` - 1C6P\n* `single-1c8p` - 1C8P\n* `single-1c12p` - 1C12P\n* `single-1c16p` - 1C16P\n* `trunk-2c1p` - 2C1P trunk\n* `trunk-2c2p` - 2C2P trunk\n* `trunk-2c4p` - 2C4P trunk\n* `trunk-2c4p-shuffle` - 2C4P trunk (shuffle)\n* `trunk-2c6p` - 2C6P trunk\n* `trunk-2c8p` - 2C8P trunk\n* `trunk-2c12p` - 2C12P trunk\n* `trunk-4c1p` - 4C1P trunk\n* `trunk-4c2p` - 4C2P trunk\n* `trunk-4c4p` - 4C4P trunk\n* `trunk-4c4p-shuffle` - 4C4P trunk (shuffle)\n* `trunk-4c6p` - 4C6P trunk\n* `trunk-4c8p` - 4C8P trunk\n* `trunk-8c4p` - 8C4P trunk\n* `breakout-1c4p-4c1p` - 1C4P:4C1P breakout\n* `breakout-1c6p-6c1p` - 1C6P:6C1P breakout\n* `breakout-2c4p-8c1p-shuffle` - 2C4P:8C1P breakout (shuffle)", + "x-spec-enum-id": "5e0f85310f0184ea" + }, "tenant": { "oneOf": [ { @@ -235552,6 +252189,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -235614,7 +252267,7 @@ }, "PatchedWritableCircuitRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "cid": { "type": "string", @@ -235735,6 +252388,22 @@ "x-spec-enum-id": "b1169a409430c02e", "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -235758,7 +252427,7 @@ }, "PatchedWritableClusterRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -235831,6 +252500,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -235848,7 +252533,7 @@ }, "PatchedWritableConsolePortRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -235938,6 +252623,22 @@ "type": "boolean", "description": "Treat as if a cable is connected" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -236030,7 +252731,7 @@ }, "PatchedWritableConsoleServerPortRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -236120,6 +252821,22 @@ "type": "boolean", "description": "Treat as if a cable is connected" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -236277,7 +252994,7 @@ }, "PatchedWritableContactGroupRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -236308,6 +253025,22 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" } @@ -236315,7 +253048,7 @@ }, "PatchedWritableCustomFieldChoiceSetRequest": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "name": { "type": "string", @@ -236351,12 +253084,28 @@ "order_alphabetically": { "type": "boolean", "description": "Choices are automatically ordered alphabetically" + }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true } } }, "PatchedWritableCustomFieldRequest": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "object_types": { "type": "array", @@ -236516,6 +253265,22 @@ ], "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" } @@ -236523,7 +253288,7 @@ }, "PatchedWritableDataSourceRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -236572,6 +253337,22 @@ "type": "string", "description": "Patterns (one per line) matching files to ignore when syncing" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -236583,7 +253364,7 @@ }, "PatchedWritableDeviceRoleRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -236640,6 +253421,22 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" } @@ -236647,7 +253444,7 @@ }, "PatchedWritableDeviceTypeRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "manufacturer": { "oneOf": [ @@ -236778,6 +253575,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -236795,7 +253608,7 @@ }, "PatchedWritableDeviceWithConfigContextRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -237077,6 +253890,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -237114,7 +253943,7 @@ }, "PatchedWritableEventRuleRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "object_types": { "type": "array", @@ -237185,6 +254014,22 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -237195,7 +254040,7 @@ }, "PatchedWritableFrontPortRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -237303,14 +254148,16 @@ "pattern": "^[0-9a-f]{6}$", "maxLength": 6 }, - "rear_port": { - "type": "integer" - }, - "rear_port_position": { + "positions": { "type": "integer", "maximum": 1024, - "minimum": 1, - "description": "Mapped position on corresponding rear port" + "minimum": 1 + }, + "rear_ports": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FrontPortMappingRequest" + } }, "description": { "type": "string", @@ -237320,6 +254167,22 @@ "type": "boolean", "description": "Treat as if a cable is connected" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -237449,21 +254312,17 @@ "pattern": "^[0-9a-f]{6}$", "maxLength": 6 }, - "rear_port": { - "oneOf": [ - { - "type": "integer" - }, - { - "$ref": "#/components/schemas/BriefRearPortTemplateRequest" - } - ] - }, - "rear_port_position": { + "positions": { "type": "integer", "maximum": 1024, "minimum": 1 }, + "rear_ports": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FrontPortTemplateMappingRequest" + } + }, "description": { "type": "string", "maxLength": 200 @@ -237472,7 +254331,7 @@ }, "PatchedWritableIKEPolicyRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -237516,6 +254375,22 @@ "type": "string", "title": "Pre-shared key" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -237533,7 +254408,7 @@ }, "PatchedWritableIKEProposalRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -237625,6 +254500,22 @@ "nullable": true, "description": "Security association lifetime (in seconds)" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -237642,7 +254533,7 @@ }, "PatchedWritableIPAddressRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "address": { "type": "string", @@ -237737,6 +254628,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -237754,7 +254661,7 @@ }, "PatchedWritableIPRangeRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "start_address": { "type": "string", @@ -237826,6 +254733,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -237851,7 +254774,7 @@ }, "PatchedWritableIPSecPolicyRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -237903,6 +254826,22 @@ "minimum": 0, "maximum": 32767 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -237920,7 +254859,7 @@ }, "PatchedWritableIPSecProfileRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -237960,6 +254899,22 @@ } ] }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -237977,7 +254932,7 @@ }, "PatchedWritableIPSecProposalRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -238039,6 +254994,22 @@ "title": "SA lifetime (KB)", "description": "Security association lifetime (in kilobytes)" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -238056,7 +255027,7 @@ }, "PatchedWritableInterfaceRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -238760,6 +255731,22 @@ ], "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -239095,7 +256082,7 @@ }, "PatchedWritableInventoryItemRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -239201,6 +256188,22 @@ "format": "int64", "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -239259,7 +256262,7 @@ }, "PatchedWritableL2VPNRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "identifier": { "type": "integer", @@ -239326,6 +256329,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -239359,7 +256378,7 @@ }, "PatchedWritableLocationRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -239433,6 +256452,22 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" } @@ -239440,7 +256475,7 @@ }, "PatchedWritableModuleRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "device": { "oneOf": [ @@ -239493,6 +256528,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -239510,7 +256561,7 @@ }, "PatchedWritableModuleTypeRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "profile": { "oneOf": [ @@ -239594,6 +256645,22 @@ "attributes": { "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -239611,7 +256678,7 @@ }, "PatchedWritablePlatformRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "parent": { "type": "integer", @@ -239664,6 +256731,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -239681,7 +256764,7 @@ }, "PatchedWritablePowerFeedRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "power_panel": { "oneOf": [ @@ -239792,6 +256875,22 @@ ], "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -239809,7 +256908,7 @@ }, "PatchedWritablePowerOutletRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -240009,6 +257108,22 @@ "type": "boolean", "description": "Treat as if a cable is connected" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -240178,6 +257293,11 @@ "x-spec-enum-id": "db3e4eb2b93615f8", "nullable": true }, + "color": { + "type": "string", + "pattern": "^[0-9a-f]{6}$", + "maxLength": 6 + }, "power_port": { "oneOf": [ { @@ -240215,7 +257335,7 @@ }, "PatchedWritablePowerPortRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -240391,6 +257511,22 @@ "type": "boolean", "description": "Treat as if a cable is connected" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -240588,7 +257724,7 @@ }, "PatchedWritablePrefixRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "prefix": { "type": "string", @@ -240690,6 +257826,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -240707,7 +257859,7 @@ }, "PatchedWritableRackRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -240950,6 +258102,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -240967,7 +258135,7 @@ }, "PatchedWritableRackReservationRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "rack": { "oneOf": [ @@ -241028,6 +258196,22 @@ "minLength": 1, "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -241045,7 +258229,7 @@ }, "PatchedWritableRackTypeRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "manufacturer": { "oneOf": [ @@ -241187,6 +258371,22 @@ "nullable": true, "description": "Maximum depth of a mounted device, in millimeters. For four-post racks, this is the distance between the front and rear rails." }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -241204,7 +258404,7 @@ }, "PatchedWritableRearPortRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -241315,8 +258515,13 @@ "positions": { "type": "integer", "maximum": 1024, - "minimum": 1, - "description": "Number of front ports which may be mapped" + "minimum": 1 + }, + "front_ports": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RearPortMappingRequest" + } }, "description": { "type": "string", @@ -241326,6 +258531,22 @@ "type": "boolean", "description": "Treat as if a cable is connected" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -241460,6 +258681,12 @@ "maximum": 1024, "minimum": 1 }, + "front_ports": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RearPortTemplateMappingRequest" + } + }, "description": { "type": "string", "maxLength": 200 @@ -241468,7 +258695,7 @@ }, "PatchedWritableRegionRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -241499,6 +258726,22 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" } @@ -241506,7 +258749,7 @@ }, "PatchedWritableServiceRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "parent_object_type": { "type": "string" @@ -241551,6 +258794,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -241568,7 +258827,7 @@ }, "PatchedWritableServiceTemplateRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -241598,6 +258857,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -241615,7 +258890,7 @@ }, "PatchedWritableSiteGroupRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -241646,6 +258921,22 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" } @@ -241653,7 +258944,7 @@ }, "PatchedWritableSiteRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -241767,6 +259058,22 @@ "nullable": true, "description": "GPS coordinate in decimal format (xx.yyyyyy)" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -241790,7 +259097,7 @@ }, "PatchedWritableTenantGroupRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -241821,6 +259128,22 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" } @@ -241828,7 +259151,7 @@ }, "PatchedWritableTunnelRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -241919,6 +259242,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -241998,7 +259337,7 @@ }, "PatchedWritableVLANRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "site": { "oneOf": [ @@ -242107,6 +259446,22 @@ "type": "integer", "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -242124,7 +259479,7 @@ }, "PatchedWritableVMInterfaceRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "virtual_machine": { "oneOf": [ @@ -242264,6 +259619,22 @@ ], "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -242278,7 +259649,7 @@ }, "PatchedWritableVirtualChassisRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -242297,6 +259668,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -242314,7 +259701,7 @@ }, "PatchedWritableVirtualCircuitRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "cid": { "type": "string", @@ -242392,6 +259779,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -242459,7 +259862,7 @@ }, "PatchedWritableVirtualDeviceContextRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -242544,6 +259947,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -242561,7 +259980,7 @@ }, "PatchedWritableVirtualMachineWithConfigContextRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -242582,6 +260001,16 @@ "description": "* `offline` - Offline\n* `active` - Active\n* `planned` - Planned\n* `staged` - Staged\n* `failed` - Failed\n* `decommissioning` - Decommissioning\n* `paused` - Paused", "x-spec-enum-id": "effecc3b94e0b74b" }, + "start_on_boot": { + "enum": [ + "on", + "off", + "laststate" + ], + "type": "string", + "description": "* `on` - On\n* `off` - Off\n* `laststate` - Last State", + "x-spec-enum-id": "610e33fc2fde73d6" + }, "site": { "oneOf": [ { @@ -242741,6 +260170,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -242778,7 +260223,7 @@ }, "PatchedWritableWirelessLANGroupRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -242809,6 +260254,22 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" } @@ -242816,7 +260277,7 @@ }, "PatchedWritableWirelessLANRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "ssid": { "type": "string", @@ -242928,6 +260389,22 @@ "title": "Pre-shared key", "maxLength": 64 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -242945,7 +260422,7 @@ }, "PatchedWritableWirelessLinkRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "interface_a": { "oneOf": [ @@ -243058,6 +260535,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -243075,7 +260568,7 @@ }, "Platform": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "id": { "type": "integer", @@ -243132,6 +260625,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -243189,7 +260690,7 @@ }, "PlatformRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "parent": { "allOf": [ @@ -243246,6 +260747,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -243267,7 +260784,7 @@ }, "PowerFeed": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -243461,6 +260978,14 @@ ], "nullable": true }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -243513,7 +261038,7 @@ }, "PowerFeedRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "power_panel": { "oneOf": [ @@ -243624,6 +261149,22 @@ ], "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -243645,7 +261186,7 @@ }, "PowerOutlet": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -244014,6 +261555,14 @@ "type": "boolean", "readOnly": true }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -244063,7 +261612,7 @@ }, "PowerOutletRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -244263,6 +261812,22 @@ "type": "boolean", "description": "Treat as if a cable is connected" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -244542,6 +262107,11 @@ }, "nullable": true }, + "color": { + "type": "string", + "pattern": "^[0-9a-f]{6}$", + "maxLength": 6 + }, "power_port": { "allOf": [ { @@ -244759,6 +262329,11 @@ "x-spec-enum-id": "db3e4eb2b93615f8", "nullable": true }, + "color": { + "type": "string", + "pattern": "^[0-9a-f]{6}$", + "maxLength": 6 + }, "power_port": { "oneOf": [ { @@ -244799,7 +262374,7 @@ }, "PowerPanel": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -244838,6 +262413,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -244883,7 +262466,7 @@ }, "PowerPanelRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "site": { "oneOf": [ @@ -244920,6 +262503,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -244941,7 +262540,7 @@ }, "PowerPort": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -245274,6 +262873,14 @@ "type": "boolean", "readOnly": true }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -245323,7 +262930,7 @@ }, "PowerPortRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -245499,6 +263106,22 @@ "type": "boolean", "description": "Treat as if a cable is connected" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -246018,7 +263641,7 @@ }, "Prefix": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -246080,8 +263703,8 @@ "nullable": true }, "scope": { - "nullable": true, - "readOnly": true + "readOnly": true, + "nullable": true }, "tenant": { "allOf": [ @@ -246145,6 +263768,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -246196,7 +263827,7 @@ }, "PrefixRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "prefix": { "type": "string", @@ -246298,6 +263929,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -246318,7 +263965,7 @@ }, "Provider": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -246358,6 +264005,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -246409,7 +264064,7 @@ }, "ProviderAccount": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -246446,6 +264101,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -246485,7 +264148,7 @@ }, "ProviderAccountRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "provider": { "oneOf": [ @@ -246512,6 +264175,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -246533,7 +264212,7 @@ }, "ProviderNetwork": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -246568,6 +264247,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -246607,7 +264294,7 @@ }, "ProviderNetworkRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "provider": { "oneOf": [ @@ -246632,6 +264319,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -246653,7 +264356,7 @@ }, "ProviderRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -246677,6 +264380,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -246704,7 +264423,7 @@ }, "RIR": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -246742,6 +264461,17 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -246784,7 +264514,7 @@ }, "RIRRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -246806,6 +264536,25 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -246824,7 +264573,7 @@ }, "Rack": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -247125,6 +264874,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -247176,7 +264933,7 @@ }, "RackRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -247415,6 +265172,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -247436,7 +265209,7 @@ }, "RackReservation": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -247517,6 +265290,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -247546,7 +265327,7 @@ }, "RackReservationRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "rack": { "oneOf": [ @@ -247607,6 +265388,22 @@ "minLength": 1, "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -247630,7 +265427,7 @@ }, "RackRole": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -247668,6 +265465,17 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -247710,7 +265518,7 @@ }, "RackRoleRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -247733,6 +265541,25 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -247751,7 +265578,7 @@ }, "RackType": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -247960,6 +265787,14 @@ "nullable": true, "description": "Maximum depth of a mounted device, in millimeters. For four-post racks, this is the distance between the front and rear rails." }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -247984,6 +265819,10 @@ "format": "date-time", "readOnly": true, "nullable": true + }, + "rack_count": { + "type": "integer", + "readOnly": true } }, "required": [ @@ -247994,13 +265833,14 @@ "last_updated", "manufacturer", "model", + "rack_count", "slug", "url" ] }, "RackTypeRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "manufacturer": { "oneOf": [ @@ -248143,6 +265983,22 @@ "nullable": true, "description": "Maximum depth of a mounted device, in millimeters. For four-post racks, this is the distance between the front and rear rails." }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -248230,7 +266086,7 @@ }, "RearPort": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -248411,8 +266267,13 @@ "positions": { "type": "integer", "maximum": 1024, - "minimum": 1, - "description": "Number of front ports which may be mapped" + "minimum": 1 + }, + "front_ports": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RearPortMapping" + } }, "description": { "type": "string", @@ -248446,6 +266307,14 @@ "readOnly": true, "nullable": true }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -248491,9 +266360,51 @@ "url" ] }, + "RearPortMapping": { + "type": "object", + "properties": { + "position": { + "type": "integer" + }, + "front_port": { + "type": "integer" + }, + "front_port_position": { + "type": "integer", + "maximum": 1024, + "minimum": 1, + "default": 1 + } + }, + "required": [ + "front_port", + "position" + ] + }, + "RearPortMappingRequest": { + "type": "object", + "properties": { + "position": { + "type": "integer" + }, + "front_port": { + "type": "integer" + }, + "front_port_position": { + "type": "integer", + "maximum": 1024, + "minimum": 1, + "default": 1 + } + }, + "required": [ + "front_port", + "position" + ] + }, "RearPortRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -248604,8 +266515,13 @@ "positions": { "type": "integer", "maximum": 1024, - "minimum": 1, - "description": "Number of front ports which may be mapped" + "minimum": 1 + }, + "front_ports": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RearPortMappingRequest" + } }, "description": { "type": "string", @@ -248615,6 +266531,22 @@ "type": "boolean", "description": "Treat as if a cable is connected" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -248818,6 +266750,12 @@ "maximum": 1024, "minimum": 1 }, + "front_ports": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RearPortTemplateMapping" + } + }, "description": { "type": "string", "maxLength": 200 @@ -248845,6 +266783,48 @@ "url" ] }, + "RearPortTemplateMapping": { + "type": "object", + "properties": { + "position": { + "type": "integer" + }, + "front_port": { + "type": "integer" + }, + "front_port_position": { + "type": "integer", + "maximum": 1024, + "minimum": 1, + "default": 1 + } + }, + "required": [ + "front_port", + "position" + ] + }, + "RearPortTemplateMappingRequest": { + "type": "object", + "properties": { + "position": { + "type": "integer" + }, + "front_port": { + "type": "integer" + }, + "front_port_position": { + "type": "integer", + "maximum": 1024, + "minimum": 1, + "default": 1 + } + }, + "required": [ + "front_port", + "position" + ] + }, "RearPortTemplateRequest": { "type": "object", "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", @@ -248967,6 +266947,12 @@ "maximum": 1024, "minimum": 1 }, + "front_ports": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RearPortTemplateMappingRequest" + } + }, "description": { "type": "string", "maxLength": 200 @@ -248979,7 +266965,7 @@ }, "Region": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "id": { "type": "integer", @@ -249052,6 +267038,14 @@ "format": "int64", "readOnly": true }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -249077,7 +267071,7 @@ }, "RegionRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -249112,6 +267106,22 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" } @@ -249123,7 +267133,7 @@ }, "Role": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -249161,6 +267171,17 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -249209,7 +267230,7 @@ }, "RoleRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -249231,6 +267252,25 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -249249,7 +267289,7 @@ }, "RouteTarget": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -249286,6 +267326,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -249324,7 +267372,7 @@ }, "RouteTargetRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -249352,6 +267400,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -249372,7 +267436,7 @@ }, "SavedFilter": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -249427,6 +267491,14 @@ "type": "boolean" }, "parameters": {}, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "created": { "type": "string", "format": "date-time", @@ -249455,7 +267527,7 @@ }, "SavedFilterRequest": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "object_types": { "type": "array", @@ -249493,7 +267565,23 @@ "shared": { "type": "boolean" }, - "parameters": {} + "parameters": {}, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + } }, "required": [ "name", @@ -249591,7 +267679,7 @@ }, "Service": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -249621,8 +267709,8 @@ "format": "int64" }, "parent": { - "nullable": true, - "readOnly": true + "readOnly": true, + "nullable": true }, "name": { "type": "string", @@ -249670,6 +267758,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -249712,7 +267808,7 @@ }, "ServiceRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "parent_object_type": { "type": "string" @@ -249757,6 +267853,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -249780,7 +267892,7 @@ }, "ServiceTemplate": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -249840,6 +267952,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -249879,7 +267999,7 @@ }, "ServiceTemplateRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -249909,6 +268029,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -249930,7 +268066,7 @@ }, "Site": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -250050,6 +268186,14 @@ "nullable": true, "description": "GPS coordinate in decimal format (xx.yyyyyy)" }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -250131,7 +268275,7 @@ }, "SiteGroup": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "id": { "type": "integer", @@ -250204,6 +268348,14 @@ "format": "int64", "readOnly": true }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -250229,7 +268381,7 @@ }, "SiteGroupRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -250264,6 +268416,22 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" } @@ -250275,7 +268443,7 @@ }, "SiteRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -250389,6 +268557,22 @@ "nullable": true, "description": "GPS coordinate in decimal format (xx.yyyyyy)" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -250441,8 +268625,8 @@ "format": "int64" }, "object": { - "nullable": true, - "readOnly": true + "readOnly": true, + "nullable": true }, "user": { "$ref": "#/components/schemas/BriefUser" @@ -250650,7 +268834,7 @@ }, "Tag": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -250731,7 +268915,7 @@ }, "TagRequest": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "name": { "type": "string", @@ -250820,7 +269004,7 @@ }, "Tenant": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -250861,6 +269045,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -250960,7 +269152,7 @@ }, "TenantGroup": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "id": { "type": "integer", @@ -251028,6 +269220,14 @@ "readOnly": true, "default": 0 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -251052,7 +269252,7 @@ }, "TenantGroupRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -251087,6 +269287,22 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" } @@ -251098,7 +269314,7 @@ }, "TenantRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -251131,6 +269347,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -251172,9 +269404,30 @@ "type": "string", "readOnly": true }, + "version": { + "enum": [ + 1, + 2 + ], + "type": "integer", + "description": "* `1` - v1\n* `2` - v2", + "x-spec-enum-id": "b5df70f0bffd12cb", + "minimum": 0, + "maximum": 32767 + }, + "key": { + "type": "string", + "readOnly": true, + "nullable": true, + "description": "v2 token identification key" + }, "user": { "$ref": "#/components/schemas/BriefUser" }, + "description": { + "type": "string", + "maxLength": 200 + }, "created": { "type": "string", "format": "date-time", @@ -251190,18 +269443,23 @@ "format": "date-time", "nullable": true }, - "key": { - "type": "string", - "maxLength": 40, - "minLength": 40 + "enabled": { + "type": "boolean", + "description": "Disable to temporarily revoke this token without deleting it." }, "write_enabled": { "type": "boolean", "description": "Permit create/update/delete operations using this key" }, - "description": { - "type": "string", - "maxLength": 200 + "pepper_id": { + "type": "integer", + "maximum": 32767, + "minimum": 0, + "nullable": true, + "description": "ID of the cryptographic pepper used to hash the token (v2 only)" + }, + "token": { + "type": "string" } }, "required": [ @@ -251209,6 +269467,7 @@ "display", "display_url", "id", + "key", "url", "user" ] @@ -251235,6 +269494,17 @@ "type": "string", "readOnly": true }, + "version": { + "enum": [ + 1, + 2 + ], + "type": "integer", + "description": "* `1` - v1\n* `2` - v2", + "x-spec-enum-id": "b5df70f0bffd12cb", + "minimum": 0, + "maximum": 32767 + }, "user": { "allOf": [ { @@ -251243,6 +269513,10 @@ ], "readOnly": true }, + "key": { + "type": "string", + "readOnly": true + }, "created": { "type": "string", "format": "date-time", @@ -251258,9 +269532,9 @@ "format": "date-time", "readOnly": true }, - "key": { - "type": "string", - "readOnly": true + "enabled": { + "type": "boolean", + "description": "Disable to temporarily revoke this token without deleting it." }, "write_enabled": { "type": "boolean", @@ -251269,6 +269543,9 @@ "description": { "type": "string", "maxLength": 200 + }, + "token": { + "type": "string" } }, "required": [ @@ -251286,11 +269563,26 @@ "type": "object", "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", "properties": { + "version": { + "enum": [ + 1, + 2 + ], + "type": "integer", + "description": "* `1` - v1\n* `2` - v2", + "x-spec-enum-id": "b5df70f0bffd12cb", + "minimum": 0, + "maximum": 32767 + }, "expires": { "type": "string", "format": "date-time", "nullable": true }, + "enabled": { + "type": "boolean", + "description": "Disable to temporarily revoke this token without deleting it." + }, "write_enabled": { "type": "boolean", "description": "Permit create/update/delete operations using this key" @@ -251308,6 +269600,10 @@ "type": "string", "writeOnly": true, "minLength": 1 + }, + "token": { + "type": "string", + "minLength": 1 } }, "required": [ @@ -251319,6 +269615,17 @@ "type": "object", "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", "properties": { + "version": { + "enum": [ + 1, + 2 + ], + "type": "integer", + "description": "* `1` - v1\n* `2` - v2", + "x-spec-enum-id": "b5df70f0bffd12cb", + "minimum": 0, + "maximum": 32767 + }, "user": { "oneOf": [ { @@ -251329,6 +269636,10 @@ } ] }, + "description": { + "type": "string", + "maxLength": 200 + }, "expires": { "type": "string", "format": "date-time", @@ -251339,18 +269650,24 @@ "format": "date-time", "nullable": true }, - "key": { - "type": "string", - "maxLength": 40, - "minLength": 40 + "enabled": { + "type": "boolean", + "description": "Disable to temporarily revoke this token without deleting it." }, "write_enabled": { "type": "boolean", "description": "Permit create/update/delete operations using this key" }, - "description": { + "pepper_id": { + "type": "integer", + "maximum": 32767, + "minimum": 0, + "nullable": true, + "description": "ID of the cryptographic pepper used to hash the token (v2 only)" + }, + "token": { "type": "string", - "maxLength": 200 + "minLength": 1 } }, "required": [ @@ -251359,7 +269676,7 @@ }, "Tunnel": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -251474,6 +269791,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -251520,7 +269845,7 @@ }, "TunnelGroup": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -251553,6 +269878,17 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -251595,7 +269931,7 @@ }, "TunnelGroupRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -251612,6 +269948,25 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -251630,7 +269985,7 @@ }, "TunnelRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -251721,6 +270076,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -251800,8 +270171,8 @@ "nullable": true }, "termination": { - "nullable": true, - "readOnly": true + "readOnly": true, + "nullable": true }, "outside_ip": { "allOf": [ @@ -251956,11 +270327,6 @@ "title": "Email address", "maxLength": 254 }, - "is_staff": { - "type": "boolean", - "title": "Staff status", - "description": "Designates whether the user can log into this admin site." - }, "is_active": { "type": "boolean", "title": "Active", @@ -252027,11 +270393,6 @@ "title": "Email address", "maxLength": 254 }, - "is_staff": { - "type": "boolean", - "title": "Staff status", - "description": "Designates whether the user can log into this admin site." - }, "is_active": { "type": "boolean", "title": "Active", @@ -252066,7 +270427,7 @@ }, "VLAN": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -252187,6 +270548,14 @@ ], "nullable": true }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -252242,7 +270611,7 @@ }, "VLANGroup": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -252280,8 +270649,8 @@ "nullable": true }, "scope": { - "nullable": true, - "readOnly": true + "readOnly": true, + "nullable": true }, "vid_ranges": { "type": "array", @@ -252301,6 +270670,17 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -252349,7 +270729,7 @@ }, "VLANGroupRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -252396,6 +270776,25 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -252414,7 +270813,7 @@ }, "VLANRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "site": { "oneOf": [ @@ -252525,6 +270924,22 @@ ], "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -252546,7 +270961,7 @@ }, "VLANTranslationPolicy": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -252575,6 +270990,17 @@ "$ref": "#/components/schemas/VLANTranslationRule" }, "readOnly": true + }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, + "comments": { + "type": "string" } }, "required": [ @@ -252587,7 +271013,7 @@ }, "VLANTranslationPolicyRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -252597,6 +271023,25 @@ "description": { "type": "string", "maxLength": 200 + }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" } }, "required": [ @@ -252685,7 +271130,7 @@ }, "VMInterface": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -252835,6 +271280,14 @@ "readOnly": true, "nullable": true }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -252884,7 +271337,7 @@ }, "VMInterfaceRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "virtual_machine": { "oneOf": [ @@ -253028,6 +271481,22 @@ ], "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -253046,7 +271515,7 @@ }, "VRF": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -253094,6 +271563,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -253156,7 +271633,7 @@ }, "VRFRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -253195,6 +271672,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -253227,7 +271720,7 @@ }, "VirtualChassis": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -253267,6 +271760,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -253318,7 +271819,7 @@ }, "VirtualChassisRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -253341,6 +271842,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -253361,7 +271878,7 @@ }, "VirtualCircuit": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -253442,6 +271959,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -253482,7 +272007,7 @@ }, "VirtualCircuitRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "cid": { "type": "string", @@ -253560,6 +272085,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -253725,7 +272266,7 @@ }, "VirtualCircuitType": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "id": { "type": "integer", @@ -253763,6 +272304,17 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -253805,7 +272357,7 @@ }, "VirtualCircuitTypeRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from OrganizationalModel.", "properties": { "name": { "type": "string", @@ -253827,6 +272379,25 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, + "comments": { + "type": "string" + }, "tags": { "type": "array", "items": { @@ -253845,7 +272416,7 @@ }, "VirtualDeviceContext": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -253938,6 +272509,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -253985,7 +272564,7 @@ }, "VirtualDeviceContextRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -254070,6 +272649,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -254092,7 +272687,7 @@ }, "VirtualDisk": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -254129,6 +272724,14 @@ "minimum": 0, "title": "Size (MB)" }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -254166,7 +272769,7 @@ }, "VirtualDiskRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "virtual_machine": { "oneOf": [ @@ -254193,6 +272796,22 @@ "minimum": 0, "title": "Size (MB)" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -254212,7 +272831,7 @@ }, "VirtualMachineWithConfigContext": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -254267,6 +272886,29 @@ } } }, + "start_on_boot": { + "type": "object", + "properties": { + "value": { + "enum": [ + "on", + "off", + "laststate" + ], + "type": "string", + "description": "* `on` - On\n* `off` - Off\n* `laststate` - Last State", + "x-spec-enum-id": "610e33fc2fde73d6" + }, + "label": { + "type": "string", + "enum": [ + "On", + "Off", + "Last State" + ] + } + } + }, "site": { "allOf": [ { @@ -254371,6 +273013,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -254437,7 +273087,7 @@ }, "VirtualMachineWithConfigContextRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -254458,6 +273108,16 @@ "description": "* `offline` - Offline\n* `active` - Active\n* `planned` - Planned\n* `staged` - Staged\n* `failed` - Failed\n* `decommissioning` - Decommissioning\n* `paused` - Paused", "x-spec-enum-id": "effecc3b94e0b74b" }, + "start_on_boot": { + "enum": [ + "on", + "off", + "laststate" + ], + "type": "string", + "description": "* `on` - On\n* `off` - Off\n* `laststate` - Last State", + "x-spec-enum-id": "610e33fc2fde73d6" + }, "site": { "oneOf": [ { @@ -254617,6 +273277,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -254657,7 +273333,7 @@ }, "Webhook": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "id": { "type": "integer", @@ -254735,6 +273411,14 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -254767,7 +273451,7 @@ }, "WebhookRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "name": { "type": "string", @@ -254830,6 +273514,22 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -254844,7 +273544,7 @@ }, "WirelessLAN": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -254923,8 +273623,8 @@ "nullable": true }, "scope": { - "nullable": true, - "readOnly": true + "readOnly": true, + "nullable": true }, "tenant": { "allOf": [ @@ -254989,6 +273689,14 @@ "title": "Pre-shared key", "maxLength": 64 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -255028,7 +273736,7 @@ }, "WirelessLANGroup": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "id": { "type": "integer", @@ -255096,6 +273804,14 @@ "readOnly": true, "default": 0 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -255120,7 +273836,7 @@ }, "WirelessLANGroupRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -255155,6 +273871,22 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" } @@ -255166,7 +273898,7 @@ }, "WirelessLANRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "ssid": { "type": "string", @@ -255273,6 +274005,22 @@ "title": "Pre-shared key", "maxLength": 64 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -255293,7 +274041,7 @@ }, "WirelessLink": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "id": { "type": "integer", @@ -255450,6 +274198,14 @@ "type": "string", "maxLength": 200 }, + "owner": { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwner" + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -255489,7 +274245,7 @@ }, "WirelessLinkRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "interface_a": { "oneOf": [ @@ -255596,6 +274352,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -255617,7 +274389,7 @@ }, "WritableAggregateRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "prefix": { "type": "string", @@ -255658,6 +274430,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -255715,7 +274503,7 @@ }, "WritableCableRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "type": { "enum": [ @@ -255782,6 +274570,38 @@ "description": "* `connected` - Connected\n* `planned` - Planned\n* `decommissioning` - Decommissioning", "x-spec-enum-id": "80d251a40f3a3144" }, + "profile": { + "enum": [ + "single-1c1p", + "single-1c2p", + "single-1c4p", + "single-1c6p", + "single-1c8p", + "single-1c12p", + "single-1c16p", + "trunk-2c1p", + "trunk-2c2p", + "trunk-2c4p", + "trunk-2c4p-shuffle", + "trunk-2c6p", + "trunk-2c8p", + "trunk-2c12p", + "trunk-4c1p", + "trunk-4c2p", + "trunk-4c4p", + "trunk-4c4p-shuffle", + "trunk-4c6p", + "trunk-4c8p", + "trunk-8c4p", + "breakout-1c4p-4c1p", + "breakout-1c6p-6c1p", + "breakout-2c4p-8c1p-shuffle", + "" + ], + "type": "string", + "description": "* `single-1c1p` - 1C1P\n* `single-1c2p` - 1C2P\n* `single-1c4p` - 1C4P\n* `single-1c6p` - 1C6P\n* `single-1c8p` - 1C8P\n* `single-1c12p` - 1C12P\n* `single-1c16p` - 1C16P\n* `trunk-2c1p` - 2C1P trunk\n* `trunk-2c2p` - 2C2P trunk\n* `trunk-2c4p` - 2C4P trunk\n* `trunk-2c4p-shuffle` - 2C4P trunk (shuffle)\n* `trunk-2c6p` - 2C6P trunk\n* `trunk-2c8p` - 2C8P trunk\n* `trunk-2c12p` - 2C12P trunk\n* `trunk-4c1p` - 4C1P trunk\n* `trunk-4c2p` - 4C2P trunk\n* `trunk-4c4p` - 4C4P trunk\n* `trunk-4c4p-shuffle` - 4C4P trunk (shuffle)\n* `trunk-4c6p` - 4C6P trunk\n* `trunk-4c8p` - 4C8P trunk\n* `trunk-8c4p` - 8C4P trunk\n* `breakout-1c4p-4c1p` - 1C4P:4C1P breakout\n* `breakout-1c6p-6c1p` - 1C6P:6C1P breakout\n* `breakout-2c4p-8c1p-shuffle` - 2C4P:8C1P breakout (shuffle)", + "x-spec-enum-id": "5e0f85310f0184ea" + }, "tenant": { "oneOf": [ { @@ -255836,6 +274656,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -255903,7 +274739,7 @@ }, "WritableCircuitRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "cid": { "type": "string", @@ -256024,6 +274860,22 @@ "x-spec-enum-id": "b1169a409430c02e", "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -256052,7 +274904,7 @@ }, "WritableClusterRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -256125,6 +274977,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -256146,7 +275014,7 @@ }, "WritableConsolePortRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -256236,6 +275104,22 @@ "type": "boolean", "description": "Treat as if a cable is connected" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -256335,7 +275219,7 @@ }, "WritableConsoleServerPortRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -256425,6 +275309,22 @@ "type": "boolean", "description": "Treat as if a cable is connected" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -256594,7 +275494,7 @@ }, "WritableContactGroupRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -256625,6 +275525,22 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" } @@ -256636,7 +275552,7 @@ }, "WritableCustomFieldChoiceSetRequest": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "name": { "type": "string", @@ -256672,6 +275588,22 @@ "order_alphabetically": { "type": "boolean", "description": "Choices are automatically ordered alphabetically" + }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true } }, "required": [ @@ -256681,7 +275613,7 @@ }, "WritableCustomFieldRequest": { "type": "object", - "description": "Extends the built-in ModelSerializer to enforce calling full_clean() on a copy of the associated instance during\nvalidation. (DRF does not do this by default; see https://github.com/encode/django-rest-framework/issues/3144)", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "object_types": { "type": "array", @@ -256841,6 +275773,22 @@ ], "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" } @@ -256852,7 +275800,7 @@ }, "WritableDataSourceRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -256901,6 +275849,22 @@ "type": "string", "description": "Patterns (one per line) matching files to ignore when syncing" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -256917,7 +275881,7 @@ }, "WritableDeviceRoleRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -256974,6 +275938,22 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" } @@ -256985,7 +275965,7 @@ }, "WritableDeviceTypeRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "manufacturer": { "oneOf": [ @@ -257116,6 +276096,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -257138,7 +276134,7 @@ }, "WritableDeviceWithConfigContextRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -257420,6 +276416,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -257462,7 +276474,7 @@ }, "WritableEventRuleRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "object_types": { "type": "array", @@ -257533,6 +276545,22 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -257549,7 +276577,7 @@ }, "WritableFrontPortRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -257657,14 +276685,16 @@ "pattern": "^[0-9a-f]{6}$", "maxLength": 6 }, - "rear_port": { - "type": "integer" - }, - "rear_port_position": { + "positions": { "type": "integer", "maximum": 1024, - "minimum": 1, - "description": "Mapped position on corresponding rear port" + "minimum": 1 + }, + "rear_ports": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FrontPortMappingRequest" + } }, "description": { "type": "string", @@ -257674,6 +276704,22 @@ "type": "boolean", "description": "Treat as if a cable is connected" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -257688,7 +276734,6 @@ "required": [ "device", "name", - "rear_port", "type" ] }, @@ -257809,21 +276854,17 @@ "pattern": "^[0-9a-f]{6}$", "maxLength": 6 }, - "rear_port": { - "oneOf": [ - { - "type": "integer" - }, - { - "$ref": "#/components/schemas/BriefRearPortTemplateRequest" - } - ] - }, - "rear_port_position": { + "positions": { "type": "integer", "maximum": 1024, "minimum": 1 }, + "rear_ports": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FrontPortTemplateMappingRequest" + } + }, "description": { "type": "string", "maxLength": 200 @@ -257831,13 +276872,12 @@ }, "required": [ "name", - "rear_port", "type" ] }, "WritableIKEPolicyRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -257881,6 +276921,22 @@ "type": "string", "title": "Pre-shared key" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -257901,7 +276957,7 @@ }, "WritableIKEProposalRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -257993,6 +277049,22 @@ "nullable": true, "description": "Security association lifetime (in seconds)" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -258016,7 +277088,7 @@ }, "WritableIPAddressRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "address": { "type": "string", @@ -258111,6 +277183,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -258131,7 +277219,7 @@ }, "WritableIPRangeRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "start_address": { "type": "string", @@ -258203,6 +277291,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -258232,7 +277336,7 @@ }, "WritableIPSecPolicyRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -258284,6 +277388,22 @@ "minimum": 0, "maximum": 32767 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -258304,7 +277424,7 @@ }, "WritableIPSecProfileRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -258344,6 +277464,22 @@ } ] }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -258367,7 +277503,7 @@ }, "WritableIPSecProposalRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -258429,6 +277565,22 @@ "title": "SA lifetime (KB)", "description": "Security association lifetime (in kilobytes)" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -258449,7 +277601,7 @@ }, "WritableInterfaceRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -259153,6 +278305,22 @@ ], "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -259497,7 +278665,7 @@ }, "WritableInventoryItemRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -259603,6 +278771,22 @@ "format": "int64", "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -259670,7 +278854,7 @@ }, "WritableL2VPNRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "identifier": { "type": "integer", @@ -259737,6 +278921,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -259775,7 +278975,7 @@ }, "WritableLocationRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -259849,6 +279049,22 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" } @@ -259861,7 +279077,7 @@ }, "WritableModuleRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "device": { "oneOf": [ @@ -259914,6 +279130,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -259936,7 +279168,7 @@ }, "WritableModuleTypeRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "profile": { "oneOf": [ @@ -260020,6 +279252,22 @@ "attributes": { "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -260041,7 +279289,7 @@ }, "WritablePlatformRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "parent": { "type": "integer", @@ -260094,6 +279342,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -260115,7 +279379,7 @@ }, "WritablePowerFeedRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "power_panel": { "oneOf": [ @@ -260226,6 +279490,22 @@ ], "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -260247,7 +279527,7 @@ }, "WritablePowerOutletRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -260447,6 +279727,22 @@ "type": "boolean", "description": "Treat as if a cable is connected" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -260620,6 +279916,11 @@ "x-spec-enum-id": "db3e4eb2b93615f8", "nullable": true }, + "color": { + "type": "string", + "pattern": "^[0-9a-f]{6}$", + "maxLength": 6 + }, "power_port": { "oneOf": [ { @@ -260660,7 +279961,7 @@ }, "WritablePowerPortRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -260836,6 +280137,22 @@ "type": "boolean", "description": "Treat as if a cable is connected" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -261040,7 +280357,7 @@ }, "WritablePrefixRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "prefix": { "type": "string", @@ -261142,6 +280459,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -261162,7 +280495,7 @@ }, "WritableRackRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -261405,6 +280738,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -261426,7 +280775,7 @@ }, "WritableRackReservationRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "rack": { "oneOf": [ @@ -261487,6 +280836,22 @@ "minLength": 1, "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -261510,7 +280875,7 @@ }, "WritableRackTypeRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "manufacturer": { "oneOf": [ @@ -261652,6 +281017,22 @@ "nullable": true, "description": "Maximum depth of a mounted device, in millimeters. For four-post racks, this is the distance between the front and rear rails." }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -261675,7 +281056,7 @@ }, "WritableRearPortRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "device": { "oneOf": [ @@ -261786,8 +281167,13 @@ "positions": { "type": "integer", "maximum": 1024, - "minimum": 1, - "description": "Number of front ports which may be mapped" + "minimum": 1 + }, + "front_ports": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RearPortMappingRequest" + } }, "description": { "type": "string", @@ -261797,6 +281183,22 @@ "type": "boolean", "description": "Treat as if a cable is connected" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -261936,6 +281338,12 @@ "maximum": 1024, "minimum": 1 }, + "front_ports": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RearPortTemplateMappingRequest" + } + }, "description": { "type": "string", "maxLength": 200 @@ -261948,7 +281356,7 @@ }, "WritableRegionRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -261979,6 +281387,22 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" } @@ -261990,7 +281414,7 @@ }, "WritableServiceRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "parent_object_type": { "type": "string" @@ -262035,6 +281459,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -262059,7 +281499,7 @@ }, "WritableServiceTemplateRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -262089,6 +281529,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -262111,7 +281567,7 @@ }, "WritableSiteGroupRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -262142,6 +281598,22 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" } @@ -262153,7 +281625,7 @@ }, "WritableSiteRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -262267,6 +281739,22 @@ "nullable": true, "description": "GPS coordinate in decimal format (xx.yyyyyy)" }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -262294,7 +281782,7 @@ }, "WritableTenantGroupRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -262325,6 +281813,22 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" } @@ -262336,7 +281840,7 @@ }, "WritableTunnelRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -262427,6 +281931,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -262514,7 +282034,7 @@ }, "WritableVLANRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "site": { "oneOf": [ @@ -262623,6 +282143,22 @@ "type": "integer", "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -262644,7 +282180,7 @@ }, "WritableVMInterfaceRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Adds an `owner` field for models which have a ForeignKey to users.Owner.", "properties": { "virtual_machine": { "oneOf": [ @@ -262784,6 +282320,22 @@ ], "nullable": true }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "tags": { "type": "array", "items": { @@ -262802,7 +282354,7 @@ }, "WritableVirtualChassisRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -262821,6 +282373,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -262841,7 +282409,7 @@ }, "WritableVirtualCircuitRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "cid": { "type": "string", @@ -262919,6 +282487,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -262995,7 +282579,7 @@ }, "WritableVirtualDeviceContextRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -263080,6 +282664,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -263102,7 +282702,7 @@ }, "WritableVirtualMachineWithConfigContextRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "name": { "type": "string", @@ -263123,6 +282723,16 @@ "description": "* `offline` - Offline\n* `active` - Active\n* `planned` - Planned\n* `staged` - Staged\n* `failed` - Failed\n* `decommissioning` - Decommissioning\n* `paused` - Paused", "x-spec-enum-id": "effecc3b94e0b74b" }, + "start_on_boot": { + "enum": [ + "on", + "off", + "laststate" + ], + "type": "string", + "description": "* `on` - On\n* `off` - Off\n* `laststate` - Last State", + "x-spec-enum-id": "610e33fc2fde73d6" + }, "site": { "oneOf": [ { @@ -263282,6 +282892,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -263322,7 +282948,7 @@ }, "WritableWirelessLANGroupRequest": { "type": "object", - "description": "Extends PrimaryModelSerializer to include MPTT support.", + "description": "Base serializer class for models inheriting from NestedGroupModel.", "properties": { "name": { "type": "string", @@ -263353,6 +282979,22 @@ "type": "object", "additionalProperties": {} }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" } @@ -263364,7 +283006,7 @@ }, "WritableWirelessLANRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "ssid": { "type": "string", @@ -263476,6 +283118,22 @@ "title": "Pre-shared key", "maxLength": 64 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -263496,7 +283154,7 @@ }, "WritableWirelessLinkRequest": { "type": "object", - "description": "Adds support for custom fields and tags.", + "description": "Base serializer class for models inheriting from PrimaryModel.", "properties": { "interface_a": { "oneOf": [ @@ -263609,6 +283267,22 @@ "type": "string", "maxLength": 200 }, + "owner": { + "oneOf": [ + { + "type": "integer" + }, + { + "allOf": [ + { + "$ref": "#/components/schemas/BriefOwnerRequest" + } + ], + "nullable": true + } + ], + "nullable": true + }, "comments": { "type": "string" }, @@ -263639,7 +283313,7 @@ "type": "apiKey", "in": "header", "name": "Authorization", - "description": "Token-based authentication with required prefix \"Token\"" + "description": "`Token ` (v1) or `Bearer .` (v2)" } } }, diff --git a/docs/administration/authentication/overview.md b/docs/administration/authentication/overview.md index 19c86a4c0..6b805ee92 100644 --- a/docs/administration/authentication/overview.md +++ b/docs/administration/authentication/overview.md @@ -2,7 +2,7 @@ ## Local Authentication -Local user accounts and groups can be created in NetBox under the "Authentication" section in the "Admin" menu. This section is available only to users with the "staff" permission enabled. +Local user accounts and groups can be created in NetBox under the "Authentication" section in the "Admin" menu. At a minimum, each user account must have a username and password set. User accounts may also denote a first name, last name, and email address. [Permissions](../permissions.md) may also be assigned to individual users and/or groups as needed. diff --git a/docs/configuration/graphql-api.md b/docs/configuration/graphql-api.md index 2c1a1c33b..e58bb0576 100644 --- a/docs/configuration/graphql-api.md +++ b/docs/configuration/graphql-api.md @@ -1,5 +1,15 @@ # GraphQL API Parameters +## GRAPHQL_DEFAULT_VERSION + +!!! note "This parameter was introduced in NetBox v4.5." + +Default: `1` + +Designates the default version of the GraphQL API served by `/graphql/`. To access a specific version, append the version number to the URL, e.g. `/graphql/v2/`. + +--- + ## GRAPHQL_ENABLED !!! tip "Dynamic Configuration Parameter" diff --git a/docs/configuration/remote-authentication.md b/docs/configuration/remote-authentication.md index 5d5f1ee58..2dbb689c2 100644 --- a/docs/configuration/remote-authentication.md +++ b/docs/configuration/remote-authentication.md @@ -127,19 +127,3 @@ The list of groups that promote an remote User to Superuser on Login. If group i Default: `[]` (Empty list) The list of users that get promoted to Superuser on Login. If user isn't present in list on next Login, the Role gets revoked. (Requires `REMOTE_AUTH_ENABLED` and `REMOTE_AUTH_GROUP_SYNC_ENABLED` ) - ---- - -## REMOTE_AUTH_STAFF_GROUPS - -Default: `[]` (Empty list) - -The list of groups that promote an remote User to Staff on Login. If group isn't present on next Login, the Role gets revoked. (Requires `REMOTE_AUTH_ENABLED` and `REMOTE_AUTH_GROUP_SYNC_ENABLED` ) - ---- - -## REMOTE_AUTH_STAFF_USERS - -Default: `[]` (Empty list) - -The list of users that get promoted to Staff on Login. If user isn't present in list on next Login, the Role gets revoked. (Requires `REMOTE_AUTH_ENABLED` and `REMOTE_AUTH_GROUP_SYNC_ENABLED` ) diff --git a/docs/configuration/required-parameters.md b/docs/configuration/required-parameters.md index 19222740d..cced030b1 100644 --- a/docs/configuration/required-parameters.md +++ b/docs/configuration/required-parameters.md @@ -23,6 +23,31 @@ ALLOWED_HOSTS = ['*'] --- +## API_TOKEN_PEPPERS + +!!! info "This parameter was introduced in NetBox v4.5." + +[Cryptographic peppers](https://en.wikipedia.org/wiki/Pepper_(cryptography)) are employed to generate hashes of sensitive values on the server. This parameter defines the peppers used to hash v2 API tokens in NetBox. You must define at least one pepper before creating a v2 API token. See the [API documentation](../integrations/rest-api.md#authentication) for further information about how peppers are used. + +```python +API_TOKEN_PEPPERS = { + # DO NOT USE THIS EXAMPLE PEPPER IN PRODUCTION + 1: 'kp7ht*76fiQAhUi5dHfASLlYUE_S^gI^(7J^K5M!LfoH@vl&b_', +} +``` + +!!! warning "Peppers are sensitive" + Treat pepper values as extremely sensitive. Consider populating peppers from environment variables at initialization time rather than defining them in the configuration file, if feasible. + +Peppers must be at least 50 characters in length and should comprise a random string with a diverse character set. Consider using the Python script at `$INSTALL_ROOT/netbox/generate_secret_key.py` to generate a pepper value. + +It is recommended to start with a pepper ID of `1`. Additional peppers can be introduced later as needed to begin rotating token hashes. + +!!! tip + Although NetBox will run without `API_TOKEN_PEPPERS` defined, the use of v2 API tokens will be unavailable. + +--- + ## DATABASE !!! warning "Legacy Configuration Parameter" diff --git a/docs/configuration/security.md b/docs/configuration/security.md index c8518f0ff..f7d7821f3 100644 --- a/docs/configuration/security.md +++ b/docs/configuration/security.md @@ -1,16 +1,5 @@ # Security & Authentication Parameters -## ALLOW_TOKEN_RETRIEVAL - -Default: `False` - -!!! note - The default value of this parameter changed from `True` to `False` in NetBox v4.3.0. - -If disabled, the values of API tokens will not be displayed after each token's initial creation. A user **must** record the value of a token prior to its creation, or it will be lost. Note that this affects _all_ users, regardless of assigned permissions. - ---- - ## ALLOWED_URL_SCHEMES !!! tip "Dynamic Configuration Parameter" diff --git a/docs/customization/custom-scripts.md b/docs/customization/custom-scripts.md index 15d6c81f0..3fe44ed88 100644 --- a/docs/customization/custom-scripts.md +++ b/docs/customization/custom-scripts.md @@ -131,17 +131,6 @@ self.log_info(f"Running as user {username} (IP: {ip_address})...") For a complete list of available request parameters, please see the [Django documentation](https://docs.djangoproject.com/en/stable/ref/request-response/). -## Reading Data from Files - -The Script class provides two convenience methods for reading data from files: - -* `load_yaml` -* `load_json` - -These two methods will load data in YAML or JSON format, respectively, from files within the local path (i.e. `SCRIPTS_ROOT`). - -**Note:** These convenience methods are deprecated and will be removed in NetBox v4.4. These only work if running scripts within the local path, they will not work if using a storage other than ScriptFileSystemStorage. - ## Logging The Script object provides a set of convenient functions for recording messages at different severity levels: diff --git a/docs/development/application-registry.md b/docs/development/application-registry.md index 8d36ccf96..9503f8ff0 100644 --- a/docs/development/application-registry.md +++ b/docs/development/application-registry.md @@ -20,6 +20,10 @@ A dictionary mapping data backend types to their respective classes. These are u Stores registration made using `netbox.denormalized.register()`. For each model, a list of related models and their field mappings is maintained to facilitate automatic updates. +### `filtersets` + +A dictionary mapping each model (identified by its app and label) to its filterset class, if one has been registered for it. Filtersets are registered using the `@register_filterset` decorator. + ### `model_features` A dictionary of model features (e.g. custom fields, tags, etc.) mapped to the functions used to qualify a model as supporting each feature. Model features are registered using the `register_model_feature()` function in `netbox.utils`. diff --git a/docs/development/getting-started.md b/docs/development/getting-started.md index 8add82c90..956226760 100644 --- a/docs/development/getting-started.md +++ b/docs/development/getting-started.md @@ -7,7 +7,7 @@ Getting started with NetBox development is pretty straightforward, and should fe * A Linux system or compatible environment * A PostgreSQL server, which can be installed locally [per the documentation](../installation/1-postgresql.md) * A Redis server, which can also be [installed locally](../installation/2-redis.md) -* Python 3.10 or later +* Python 3.12 or later ### 1. Fork the Repo diff --git a/docs/features/api-integration.md b/docs/features/api-integration.md index 94a39d731..28aefda92 100644 --- a/docs/features/api-integration.md +++ b/docs/features/api-integration.md @@ -8,7 +8,7 @@ NetBox's REST API, powered by the [Django REST Framework](https://www.django-res ```no-highlight curl -s -X POST \ --H "Authorization: Token $TOKEN" \ +-H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ http://netbox/api/ipam/prefixes/ \ --data '{"prefix": "192.0.2.0/24", "site": {"name": "Branch 12"}}' diff --git a/docs/features/configuration-rendering.md b/docs/features/configuration-rendering.md index 44cacc684..7cf197f54 100644 --- a/docs/features/configuration-rendering.md +++ b/docs/features/configuration-rendering.md @@ -90,3 +90,10 @@ http://netbox:8000/api/extras/config-templates/123/render/ \ "bar": 123 }' ``` + +!!! note "Permissions" + Rendering configuration templates via the REST API requires appropriate permissions for the relevant object type: + + * To render a device's configuration via `/api/dcim/devices/{id}/render-config/`, assign a permission for "DCIM > Device" with the `render_config` action. + * To render a virtual machine's configuration via `/api/virtualization/virtual-machines/{id}/render-config/`, assign a permission for "Virtualization > Virtual Machine" with the `render_config` action. + * To render a config template directly via `/api/extras/config-templates/{id}/render/`, assign a permission for "Extras > Config Template" with the `render` action. diff --git a/docs/features/resource-ownership.md b/docs/features/resource-ownership.md new file mode 100644 index 000000000..a50984f5a --- /dev/null +++ b/docs/features/resource-ownership.md @@ -0,0 +1,10 @@ +# Resource Ownership + +!!! info "This feature was introduced in NetBox v4.5." + +Most objects in NetBox can be assigned an owner. An owner is a set of users and/or groups who are responsible for the administration of associated objects. For example, you might designate the operations team at a site as the owner for all prefixes and VLANs deployed at that site. The users and groups assigned to an owner are referred to as its members. + +!!! note + Ownership of an object should not be confused with the concept of [tenancy](./tenancy.md), which indicates the dedication of an object to a specific tenant. For instance, a tenant might represent a customer served by the object, whereas an owner typically represents a set of internal users responsible for the management of the object. + +Owners can be organized into groups for easier management. diff --git a/docs/features/tenancy.md b/docs/features/tenancy.md index 470905f20..3f76ff805 100644 --- a/docs/features/tenancy.md +++ b/docs/features/tenancy.md @@ -1,6 +1,6 @@ # Tenancy -Most core objects within NetBox's data model support _tenancy_. This is the association of an object with a particular tenant to convey ownership or dependency. For example, an enterprise might represent its internal business units as tenants, whereas a managed services provider might create a tenant in NetBox to represent each of its customers. +Most core objects within NetBox's data model support _tenancy_. This is the association of an object with a particular tenant to convey assignment or dependency. For example, an enterprise might represent its internal business units as tenants, whereas a managed services provider might create a tenant in NetBox to represent each of its customers. ```mermaid flowchart TD @@ -19,20 +19,36 @@ Tenants can be grouped by any logic that your use case demands, and groups can b Typically, the tenant model is used to represent a customer or internal organization, however it can be used for whatever purpose meets your needs. -Most core objects within NetBox can be assigned to particular tenant, so this model provides a very convenient way to correlate ownership across object types. For example, each of your customers might have its own racks, devices, IP addresses, circuits and so on: These can all be easily tracked via tenant assignment. +Most core objects within NetBox can be assigned to a particular tenant, so this model provides a very convenient way to correlate resource allocation across object types. For example, each of your customers might have its own racks, devices, IP addresses, circuits and so on: These can all be easily tracked via tenant assignment. The following objects can be assigned to tenants: -* Sites +* Circuits +* Circuit groups +* Virtual circuits +* Cables +* Devices +* Virtual device contexts +* Power feeds * Racks * Rack reservations -* Devices -* VRFs +* Sites +* Locations +* ASNs +* ASN ranges +* Aggregates * Prefixes +* IP ranges * IP addresses * VLANs -* Circuits +* VLAN groups +* VRFs +* Route targets * Clusters * Virtual machines +* L2VPNs +* Tunnels +* Wireless LANs +* Wireless links -Tenant assignment is used to signify the ownership of an object in NetBox. As such, each object may only be owned by a single tenant. For example, if you have a firewall dedicated to a particular customer, you would assign it to the tenant which represents that customer. However, if the firewall serves multiple customers, it doesn't *belong* to any particular customer, so tenant assignment would not be appropriate. +Tenancy represents the dedication of an object to a specific tenant. As such, each object may only be assigned to a single tenant. For example, if you have a firewall dedicated to a particular customer, you would assign it to the tenant which represents that customer. However, if the firewall serves multiple customers, it doesn't *belong* to any particular customer, so the assignment of a tenant would not be appropriate. diff --git a/docs/features/user-preferences.md b/docs/features/user-preferences.md index 6c0a2884f..c8670bb69 100644 --- a/docs/features/user-preferences.md +++ b/docs/features/user-preferences.md @@ -34,9 +34,6 @@ Sets the default number of rows displayed on paginated tables. ### Paginator placement Controls where pagination controls are rendered relative to a table. -### HTMX navigation (experimental) -Enables partial‑page navigation for supported views. Disable this preference if unexpected behavior is observed. - ### Striped table rows Toggles alternating row backgrounds on tables. diff --git a/docs/installation/3-netbox.md b/docs/installation/3-netbox.md index acf04dc2a..fd9b21f50 100644 --- a/docs/installation/3-netbox.md +++ b/docs/installation/3-netbox.md @@ -6,8 +6,8 @@ This section of the documentation discusses installing and configuring the NetBo Begin by installing all system packages required by NetBox and its dependencies. -!!! warning "Python 3.10 or later required" - NetBox supports Python 3.10, 3.11, and 3.12. +!!! warning "Python 3.12 or later required" + NetBox supports only Python 3.12 or later. ```no-highlight sudo apt install -y python3 python3-pip python3-venv python3-dev \ @@ -15,7 +15,7 @@ build-essential libxml2-dev libxslt1-dev libffi-dev libpq-dev \ libssl-dev zlib1g-dev ``` -Before continuing, check that your installed Python version is at least 3.10: +Before continuing, check that your installed Python version is at least 3.12: ```no-highlight python3 -V @@ -120,6 +120,23 @@ If you are not yet sure what the domain name and/or IP address of the NetBox ins ALLOWED_HOSTS = ['*'] ``` +### API_TOKEN_PEPPERS + +Define at least one random cryptographic pepper, identified by a numeric ID starting at 1. This will be used to generate SHA256 checksums for API tokens. + +```python +API_TOKEN_PEPPERS = { + # DO NOT USE THIS EXAMPLE PEPPER IN PRODUCTION + 1: 'kp7ht*76fiQAhUi5dHfASLlYUE_S^gI^(7J^K5M!LfoH@vl&b_', +} +``` + +!!! tip + As with [`SECRET_KEY`](#secret_key) below, you can use the `generate_secret_key.py` script to generate a random pepper: + ```no-highlight + python3 ../generate_secret_key.py + ``` + ### DATABASES This parameter holds the PostgreSQL database configuration details. The default database must be defined; additional databases may be defined as needed e.g. by plugins. @@ -235,10 +252,10 @@ Once NetBox has been configured, we're ready to proceed with the actual installa sudo /opt/netbox/upgrade.sh ``` -Note that **Python 3.10 or later is required** for NetBox v4.0 and later releases. If the default Python installation on your server is set to a lesser version, pass the path to the supported installation as an environment variable named `PYTHON`. (Note that the environment variable must be passed _after_ the `sudo` command.) +Note that **Python 3.12 or later is required** for NetBox v4.5 and later releases. If the default Python installation on your server is set to a lesser version, pass the path to the supported installation as an environment variable named `PYTHON`. (Note that the environment variable must be passed _after_ the `sudo` command.) ```no-highlight -sudo PYTHON=/usr/bin/python3.10 /opt/netbox/upgrade.sh +sudo PYTHON=/usr/bin/python3.12 /opt/netbox/upgrade.sh ``` !!! note diff --git a/docs/installation/4a-gunicorn.md b/docs/installation/4a-gunicorn.md index 3aca4ef0e..91bbcd0e5 100644 --- a/docs/installation/4a-gunicorn.md +++ b/docs/installation/4a-gunicorn.md @@ -60,6 +60,3 @@ You should see output similar to the following: If the NetBox service fails to start, issue the command `journalctl -eu netbox` to check for log messages that may indicate the problem. Once you've verified that the WSGI workers are up and running, move on to HTTP server setup. - -!!! note - There is a bug in the current stable release of gunicorn (v21.2.0) where automatic restarts of the worker processes can result in 502 errors under heavy load. (See [gunicorn bug #3038](https://github.com/benoitc/gunicorn/issues/3038) for more detail.) Users who encounter this issue may opt to downgrade to an earlier, unaffected release of gunicorn (`pip install gunicorn==20.1.0`). Note, however, that this earlier release does not officially support Python 3.11. diff --git a/docs/installation/6-ldap.md b/docs/installation/6-ldap.md index 7de9f116d..4d27f2f01 100644 --- a/docs/installation/6-ldap.md +++ b/docs/installation/6-ldap.md @@ -121,7 +121,6 @@ AUTH_LDAP_MIRROR_GROUPS = True # Define special user types using groups. Exercise great caution when assigning superuser status. AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active": "cn=active,ou=groups,dc=example,dc=com", - "is_staff": "cn=staff,ou=groups,dc=example,dc=com", "is_superuser": "cn=superuser,ou=groups,dc=example,dc=com" } @@ -134,7 +133,6 @@ AUTH_LDAP_CACHE_TIMEOUT = 3600 ``` * `is_active` - All users must be mapped to at least this group to enable authentication. Without this, users cannot log in. -* `is_staff` - Users mapped to this group are enabled for access to the administration tools; this is the equivalent of checking the "staff status" box on a manually created user. This doesn't grant any specific permissions. * `is_superuser` - Users mapped to this group will be granted superuser status. Superusers are implicitly granted all permissions. !!! warning @@ -248,7 +246,6 @@ AUTH_LDAP_MIRROR_GROUPS = True # Define special user types using groups. Exercise great caution when assigning superuser status. AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active": "cn=active,ou=groups,dc=example,dc=com", - "is_staff": "cn=staff,ou=groups,dc=example,dc=com", "is_superuser": "cn=superuser,ou=groups,dc=example,dc=com" } diff --git a/docs/installation/index.md b/docs/installation/index.md index aefa39d17..73bf1220c 100644 --- a/docs/installation/index.md +++ b/docs/installation/index.md @@ -27,7 +27,7 @@ The following sections detail how to set up a new instance of NetBox: | Dependency | Supported Versions | |------------|--------------------| -| Python | 3.10, 3.11, 3.12 | +| Python | 3.12, 3.13, 3.14 | | PostgreSQL | 14+ | | Redis | 4.0+ | diff --git a/docs/installation/upgrading.md b/docs/installation/upgrading.md index cf0a16754..ce5282b04 100644 --- a/docs/installation/upgrading.md +++ b/docs/installation/upgrading.md @@ -19,7 +19,7 @@ NetBox requires the following dependencies: | Dependency | Supported Versions | |------------|--------------------| -| Python | 3.10, 3.11, 3.12 | +| Python | 3.12, 3.13, 3.14 | | PostgreSQL | 14+ | | Redis | 4.0+ | @@ -27,6 +27,7 @@ NetBox requires the following dependencies: | NetBox Version | Python min | Python max | PostgreSQL min | Redis min | Documentation | |:--------------:|:----------:|:----------:|:--------------:|:---------:|:-----------------------------------------------------------------------------------------:| +| 4.5 | 3.12 | 3.14 | 14 | 4.0 | [Link](https://github.com/netbox-community/netbox/blob/v4.5.0/docs/installation/index.md) | | 4.4 | 3.10 | 3.12 | 14 | 4.0 | [Link](https://github.com/netbox-community/netbox/blob/v4.4.0/docs/installation/index.md) | | 4.3 | 3.10 | 3.12 | 14 | 4.0 | [Link](https://github.com/netbox-community/netbox/blob/v4.3.0/docs/installation/index.md) | | 4.2 | 3.10 | 3.12 | 13 | 4.0 | [Link](https://github.com/netbox-community/netbox/blob/v4.2.0/docs/installation/index.md) | @@ -130,7 +131,7 @@ sudo ./upgrade.sh If the default version of Python is not at least 3.10, you'll need to pass the path to a supported Python version as an environment variable when calling the upgrade script. For example: ```no-highlight - sudo PYTHON=/usr/bin/python3.10 ./upgrade.sh + sudo PYTHON=/usr/bin/python3.12 ./upgrade.sh ``` !!! note diff --git a/docs/integrations/rest-api.md b/docs/integrations/rest-api.md index 47fb65494..2b97f601c 100644 --- a/docs/integrations/rest-api.md +++ b/docs/integrations/rest-api.md @@ -80,7 +80,7 @@ Likewise, the site, rack, and device objects are located under the "DCIM" applic The full hierarchy of available endpoints can be viewed by navigating to the API root in a web browser. -Each model generally has two views associated with it: a list view and a detail view. The list view is used to retrieve a list of multiple objects and to create new objects. The detail view is used to retrieve, update, or delete an single existing object. All objects are referenced by their numeric primary key (`id`). +Each model generally has two views associated with it: a list view and a detail view. The list view is used to retrieve a list of multiple objects and to create new objects. The detail view is used to retrieve, update, or delete a single existing object. All objects are referenced by their numeric primary key (`id`). * `/api/dcim/devices/` - List existing devices or create a new device * `/api/dcim/devices/123/` - Retrieve, update, or delete the device with ID 123 @@ -653,18 +653,22 @@ The NetBox REST API primarily employs token-based authentication. For convenienc ### Tokens -A token is a unique identifier mapped to a NetBox user account. Each user may have one or more tokens which he or she can use for authentication when making REST API requests. To create a token, navigate to the API tokens page under your user profile. +A token is a secret, unique identifier mapped to a NetBox user account. Each user may have one or more tokens which he or she can use for authentication when making REST API requests. To create a token, navigate to the API tokens page under your user profile. When creating a token, NetBox will automatically populate a randomly-generated token value. + +!!! note "Tokens cannot be retrieved once created" + Once a token has been created, its plaintext value cannot be retrieved. For this reason, you must take care to securely record the token locally immediately upon its creation. If a token plaintext is lost, it cannot be recovered: A new token must be created. By default, all users can create and manage their own REST API tokens under the user control panel in the UI or via the REST API. This ability can be disabled by overriding the [`DEFAULT_PERMISSIONS`](../configuration/security.md#default_permissions) configuration parameter. -Each token contains a 160-bit key represented as 40 hexadecimal characters. When creating a token, you'll typically leave the key field blank so that a random key will be automatically generated. However, NetBox allows you to specify a key in case you need to restore a previously deleted token to operation. - Additionally, a token can be set to expire at a specific time. This can be useful if an external client needs to be granted temporary access to NetBox. -!!! info "Restricting Token Retrieval" - The ability to retrieve the key value of a previously-created API token can be restricted by disabling the [`ALLOW_TOKEN_RETRIEVAL`](../configuration/security.md#allow_token_retrieval) configuration parameter. +#### v1 and v2 Tokens -### Restricting Write Operations +Beginning with NetBox v4.5, two versions of API token are supported, denoted as v1 and v2. Users are strongly encouraged to create only v2 tokens and to discontinue the use of v1 tokens. Support for v1 tokens will be removed in a future NetBox release. + +v2 API tokens offer much stronger security. The token plaintext given at creation time is hashed together with a configured [cryptographic pepper](../configuration/required-parameters.md#api_token_peppers) to generate a unique checksum. This checksum is irreversible; the token plaintext is never stored on the server and thus cannot be retrieved even with database-level access. + +#### Restricting Write Operations By default, a token can be used to perform all actions via the API that a user would be permitted to do via the web UI. Deselecting the "write enabled" option will restrict API requests made with the token to read operations (e.g. GET) only. @@ -681,10 +685,22 @@ It is possible to provision authentication tokens for other users via the REST A ### Authenticating to the API -An authentication token is attached to a request by setting the `Authorization` header to the string `Token` followed by a space and the user's token: +An authentication token is included with a request in its `Authorization` header. The format of the header value depends on the version of token in use. v2 tokens use the following form, concatenating the token's prefix (`nbt_`) and key with its plaintext value, separated by a period: ``` -$ curl -H "Authorization: Token $TOKEN" \ +Authorization: Bearer nbt_. +``` + +Legacy v1 tokens use the prefix `Token` rather than `Bearer`, and include only the token plaintext. (v1 tokens do not have a key.) + +``` +Authorization: Token +``` + +Below is an example REST API request utilizing a v2 token. + +``` +$ curl -H "Authorization: Bearer nbt_4F9DAouzURLb.zjebxBPzICiPbWz0Wtx0fTL7bCKXKGTYhNzkgC2S" \ -H "Accept: application/json; indent=4" \ https://netbox/api/dcim/sites/ { diff --git a/docs/models/dcim/cable.md b/docs/models/dcim/cable.md index 20f6c03c7..8a60d8353 100644 --- a/docs/models/dcim/cable.md +++ b/docs/models/dcim/cable.md @@ -21,6 +21,21 @@ The cable's operational status. Choices include: * Planned * Decommissioning +### Profile + +!!! note "This field was introduced in NetBox v4.5." + +The profile to which the cable conforms. The profile determines the mapping of termination between the two ends and enables logical tracing across complex connections, such as breakout cables. Supported profiles are listed below. + +* Straight (single position) +* Straight (multi-position) +* Shuffle (2x2 MPO8) +* Shuffle (4x4 MPO8) + +A single-position cable is allowed only one termination point at each end. There is no limit to the number of terminations a multi-position cable may have. Each end of a cable must have the same number of terminations, unless connected to a pass-through port or to a circuit termination. + +The assignment of a cable profile is optional. If no profile is assigned, legacy tracing behavior will be preserved. + ### Type The cable's physical medium or classification. diff --git a/docs/models/users/owner.md b/docs/models/users/owner.md new file mode 100644 index 000000000..70c9a93e7 --- /dev/null +++ b/docs/models/users/owner.md @@ -0,0 +1,23 @@ +# Owner + +An owner is a set of users and/or groups who are responsible for the administration of certain resources within NetBox. The users and groups assigned to an owner are referred to as its members. Owner assignments are useful for indicating which parties are responsible for the administration of a particular object. + +Most objects within NetBox can be assigned an owner, although this is not required. + +## Fields + +### Name + +The owner's name. + +### Group + +The [group](./ownergroup.md) to which the owner is assigned. The assignment of an owner to a group is optional. + +### User Groups + +Groups of users that are members of the owner. + +### Users + +Individual users that are members of the owner. diff --git a/docs/models/users/ownergroup.md b/docs/models/users/ownergroup.md new file mode 100644 index 000000000..61c279438 --- /dev/null +++ b/docs/models/users/ownergroup.md @@ -0,0 +1,9 @@ +# Owner Groups + +Groups are used to correlate and organize [owners](./owner.md). The assignment of an owner to a group has no bearing on the relationship of owned objects to their owners. + +## Fields + +### Name + +The name of the group. diff --git a/docs/models/virtualization/virtualmachine.md b/docs/models/virtualization/virtualmachine.md index a90b2752d..189a4ba75 100644 --- a/docs/models/virtualization/virtualmachine.md +++ b/docs/models/virtualization/virtualmachine.md @@ -21,6 +21,13 @@ The VM's operational status. !!! tip Additional statuses may be defined by setting `VirtualMachine.status` under the [`FIELD_CHOICES`](../../configuration/data-validation.md#field_choices) configuration parameter. +### Start on boot + +The start on boot setting from the hypervisor. + +!!! tip + Additional statuses may be defined by setting `VirtualMachine.start_on_boot` under the [`FIELD_CHOICES`](../../configuration/data-validation.md#field_choices) configuration parameter. + ### Site & Cluster The [site](../dcim/site.md) and/or [cluster](./cluster.md) to which the VM is assigned. diff --git a/docs/plugins/development/filtersets.md b/docs/plugins/development/filtersets.md index e829ddea5..36e6346c5 100644 --- a/docs/plugins/development/filtersets.md +++ b/docs/plugins/development/filtersets.md @@ -6,12 +6,17 @@ Filter sets define the mechanisms available for filtering or searching through a To support additional functionality standard to NetBox models, such as tag assignment and custom field support, the `NetBoxModelFilterSet` class is available for use by plugins. This should be used as the base filter set class for plugin models which inherit from `NetBoxModel`. Within this class, individual filters can be declared as directed by the `django-filters` documentation. An example is provided below. +!!! info "New in NetBox v4.5: FilterSet Registration" + NetBox v4.5 introduced the `register_filterset()` utility function. This enables plugins to register their filtersets to receive advanced functionality, such as the automatic attachment of field-specific lookup modifiers on the filter form. Registration is optional: Unregistered filtersets will continue to work as before, but will not receive the enhanced functionality. + ```python # filtersets.py import django_filters from netbox.filtersets import NetBoxModelFilterSet +from utilities.filtersets import register_filterset from .models import MyModel +@register_filterset class MyFilterSet(NetBoxModelFilterSet): status = django_filters.MultipleChoiceFilter( choices=( @@ -27,6 +32,14 @@ class MyFilterSet(NetBoxModelFilterSet): fields = ('some', 'other', 'fields') ``` +In addition to the base NetBoxModelFilterSet class, the following filterset classes are also available for subclasses of standard base models. + +| Model Class | FilterSet Class | +|-----------------------|--------------------------------------------------| +| `PrimaryModel` | `netbox.filtersets.PrimaryModelFilterSet` | +| `OrganizationalModel` | `netbox.filtersets.OrganizationalModelFilterSet` | +| `NestedGroupModel` | `netbox.filtersets.NestedGroupModelFilterSet` | + ### Declaring Filter Sets To utilize a filter set in a subclass of one of NetBox's generic views (such as `ObjectListView` or `BulkEditView`), define the `filterset` attribute on the view class: @@ -42,7 +55,7 @@ class MyModelListView(ObjectListView): filterset = MyModelFilterSet ``` -To enable a filter set on a REST API endpoint, set the `filterset_class` attribute on the API view: +To enable a filter set on a REST API endpoint, set the `filterset_class` attribute on the API view: ```python # api/views.py @@ -62,7 +75,9 @@ The `ObjectListView` has a field called Quick Search. For Quick Search to work t ```python from django.db.models import Q from netbox.filtersets import NetBoxModelFilterSet +from utilities.filtersets import register_filterset +@register_filterset class MyFilterSet(NetBoxModelFilterSet): ... def search(self, queryset, name, value): @@ -90,7 +105,9 @@ This class filters `tags` using the `slug` field. For example: ```python from django_filters import FilterSet from extras.filters import TagFilter +from utilities.filtersets import register_filterset +@register_filterset class MyModelFilterSet(FilterSet): tag = TagFilter() ``` @@ -106,7 +123,9 @@ This class filters `tags` using the `id` field. For example: ```python from django_filters import FilterSet from extras.filters import TagIDFilter +from utilities.filtersets import register_filterset +@register_filterset class MyModelFilterSet(FilterSet): tag_id = TagIDFilter() ``` diff --git a/docs/plugins/development/forms.md b/docs/plugins/development/forms.md index 209506172..afe05407e 100644 --- a/docs/plugins/development/forms.md +++ b/docs/plugins/development/forms.md @@ -2,7 +2,7 @@ ## Form Classes -NetBox provides several base form classes for use by plugins. +NetBox provides several base form classes for use by plugins. Additional form classes are also available for other standard base model classes (PrimaryModel, OrganizationalModel, and NestedGroupModel). | Form Class | Purpose | |----------------------------|--------------------------------------| @@ -19,7 +19,17 @@ This is the base form for creating and editing NetBox models. It extends Django' |-------------|---------------------------------------------------------------------------------------| | `fieldsets` | A tuple of `FieldSet` instances which control how form fields are rendered (optional) | -**Example** +#### Subclasses + +The corresponding model-specific subclasses of `NetBoxModelForm` are documented below. + +| Model Class | Form Class | +|-----------------------|---------------------------| +| `PrimaryModel` | `PrimaryModelForm` | +| `OrganizationalModel` | `OrganizationalModelForm` | +| `NestedGroupModel` | `NestedGroupModelForm` | + +#### Example ```python from django.utils.translation import gettext_lazy as _ @@ -49,9 +59,19 @@ class MyModelForm(NetBoxModelForm): ### `NetBoxModelImportForm` -This form facilitates the bulk import of new objects from CSV, JSON, or YAML data. As with model forms, you'll need to declare a `Meta` subclass specifying the associated `model` and `fields`. NetBox also provides several form fields suitable for import various types of CSV data, listed below. +This form facilitates the bulk import of new objects from CSV, JSON, or YAML data. As with model forms, you'll need to declare a `Meta` subclass specifying the associated `model` and `fields`. NetBox also provides several form fields suitable for importing various types of CSV data, listed [below](#csv-import-fields). -**Example** +#### Subclasses + +The corresponding model-specific subclasses of `NetBoxModelImportForm` are documented below. + +| Model Class | Form Class | +|-----------------------|---------------------------------| +| `PrimaryModel` | `PrimaryModelImportForm` | +| `OrganizationalModel` | `OrganizationalModelImportForm` | +| `NestedGroupModel` | `NestedGroupModelImportForm` | + +#### Example ```python from django.utils.translation import gettext_lazy as _ @@ -83,7 +103,17 @@ This form facilitates editing multiple objects in bulk. Unlike a model form, thi | `fieldsets` | A tuple of `FieldSet` instances which control how form fields are rendered (optional) | | `nullable_fields` | A tuple of fields which can be nullified (set to empty) using the bulk edit form (optional) | -**Example** +#### Subclasses + +The corresponding model-specific subclasses of `NetBoxModelBulkEditForm` are documented below. + +| Model Class | Form Class | +|-----------------------|-----------------------------------| +| `PrimaryModel` | `PrimaryModelBulkEditForm` | +| `OrganizationalModel` | `OrganizationalModelBulkEditForm` | +| `NestedGroupModel` | `NestedGroupModelBulkEditForm` | + +#### Example ```python from django import forms @@ -125,7 +155,17 @@ This form class is used to render a form expressly for filtering a list of objec | `model` | The model of object being edited | | `fieldsets` | A tuple of `FieldSet` instances which control how form fields are rendered (optional) | -**Example** +#### Subclasses + +The corresponding model-specific subclasses of `NetBoxModelFilterSetForm` are documented below. + +| Model Class | Form Class | +|-----------------------|------------------------------------| +| `PrimaryModel` | `PrimaryModelFilterSetForm` | +| `OrganizationalModel` | `OrganizationalModelFilterSetForm` | +| `NestedGroupModel` | `NestedGroupModelFilterSetForm` | + +#### Example ```python from dcim.models import Site diff --git a/docs/plugins/development/graphql-api.md b/docs/plugins/development/graphql-api.md index 603b0cead..b7691cc70 100644 --- a/docs/plugins/development/graphql-api.md +++ b/docs/plugins/development/graphql-api.md @@ -46,3 +46,19 @@ NetBox provides two object type classes for use by plugins. ::: netbox.graphql.types.NetBoxObjectType options: members: false + +## GraphQL Filters + +NetBox provides a base filter class for use by plugins which employ subclasseses of `NetBoxModel`. + +::: netbox.graphql.filters.NetBoxModelFilter + options: + members: false + +Additionally, the following filter classes are available for subclasses of standard base models. + +| Model Class | FilterSet Class | +|-----------------------|----------------------------------------------------| +| `PrimaryModel` | `netbox.graphql.filters.PrimaryModelFilter` | +| `OrganizationalModel` | `netbox.graphql.filters.OrganizationalModelFilter` | +| `NestedGroupModel` | `netbox.graphql.filters.NestedGroupModelFilter` | diff --git a/docs/plugins/development/index.md b/docs/plugins/development/index.md index 78b1460c7..25f8b68df 100644 --- a/docs/plugins/development/index.md +++ b/docs/plugins/development/index.md @@ -173,12 +173,12 @@ classifiers=[ 'Intended Audience :: Developers', 'Natural Language :: English', "Programming Language :: Python :: 3 :: Only", - 'Programming Language :: Python :: 3.10', - 'Programming Language :: Python :: 3.11', 'Programming Language :: Python :: 3.12', + 'Programming Language :: Python :: 3.13', + 'Programming Language :: Python :: 3.14', ] -requires-python = ">=3.10.0" +requires-python = ">=3.12.0" ``` Many of these are self-explanatory, but for more information, see the [pyproject.toml documentation](https://packaging.python.org/en/latest/specifications/pyproject-toml/). @@ -208,7 +208,7 @@ python3 -m venv ~/.virtualenvs/my_plugin You can make NetBox available within this environment by creating a path file pointing to its location. This will add NetBox to the Python path upon activation. (Be sure to adjust the command below to specify your actual virtual environment path, Python version, and NetBox installation.) ```shell -echo /opt/netbox/netbox > $VENV/lib/python3.10/site-packages/netbox.pth +echo /opt/netbox/netbox > $VENV/lib/python3.12/site-packages/netbox.pth ``` ## Development Installation diff --git a/docs/plugins/development/migration-v4.md b/docs/plugins/development/migration-v4.md index bf7e720ac..ee84950d2 100644 --- a/docs/plugins/development/migration-v4.md +++ b/docs/plugins/development/migration-v4.md @@ -325,14 +325,14 @@ class CircuitTypeType(OrganizationalObjectType): ### Change filters.py -Strawberry currently doesn't directly support django-filter, so an explicit filters.py file will need to be created. NetBox includes a new `autotype_decorator` used to automatically wrap FilterSets to reduce the required code to a minimum. +Filter classes should inherit from `netbox.graphql.filters.BaseModelFilter`. ```python title="New" import strawberry import strawberry_django from circuits import filtersets, models -from netbox.graphql.filter_mixins import autotype_decorator, BaseFilterMixin +from netbox.graphql.filters import BaseModelFilter __all__ = ( 'CircuitFilter', @@ -340,8 +340,7 @@ __all__ = ( @strawberry_django.filter(models.Circuit, lookups=True) -@autotype_decorator(filtersets.CircuitFilterSet) -class CircuitFilter(BaseFilterMixin): +class CircuitFilter(BaseModelFilter): pass ``` diff --git a/docs/plugins/development/models.md b/docs/plugins/development/models.md index eb12204ff..9a8256d6d 100644 --- a/docs/plugins/development/models.md +++ b/docs/plugins/development/models.md @@ -67,6 +67,46 @@ class MyModel(ExportTemplatesMixin, TagsMixin, models.Model): ... ``` +### Additional Models + +In addition to the base NetBoxModel class, the following additional classes are provided for convenience. + +!!! info "These model classes were added to the plugins API in NetBox v4.5." + +#### PrimaryModel + +PrimaryModel is the go-to class for most object types. It extends NetBoxModel with `description` and `comments` fields, and it introduces support for ownership assignment. + +| Field | Required | Unique | Description | +|---------------|----------|--------|---------------------------------------------| +| `owner` | No | No | The object's owner | +| `description` | No | No | A human-friendly description for the object | +| `comments` | No | No | General comments | + +#### OrganizationalModel + +OrganizationalModel is used by object types whose function is primarily the organization of other objects. + +| Field | Required | Unique | Description | +|---------------|----------|--------|---------------------------------------------| +| `name` | Yes | Yes | The name of the object | +| `slug` | Yes | Yes | A unique URL-friendly identifier | +| `owner` | No | No | The object's owner | +| `description` | No | No | A human-friendly description for the object | + +#### NestedGroupModel + +NestedGroupModel is used for objects which arrange into a recursive hierarchy (like regions and locations) via its self-referential `parent` foreign key. + +| Field | Required | Unique | Description | +|---------------|----------|--------|-----------------------------------------------------------------| +| `name` | Yes | Yes | The name of the object | +| `slug` | Yes | Yes | A unique URL-friendly identifier | +| `parent` | No | No | The object (of the same type) under which this object is nested | +| `owner` | No | No | The object's owner | +| `description` | No | No | A human-friendly description for the object | +| `comments` | No | No | General comments | + ## Database Migrations Once you have completed defining the model(s) for your plugin, you'll need to create the database schema migrations. A migration file is essentially a set of instructions for manipulating the PostgreSQL database to support your new model, or to alter existing models. Creating migrations can usually be done automatically using Django's `makemigrations` management command. (Ensure that your plugin has been installed and enabled first, otherwise it won't be found.) diff --git a/docs/plugins/development/navigation.md b/docs/plugins/development/navigation.md index b5e2694b4..bb855bcea 100644 --- a/docs/plugins/development/navigation.md +++ b/docs/plugins/development/navigation.md @@ -64,14 +64,17 @@ item1 = PluginMenuItem( A `PluginMenuItem` has the following attributes: -| Attribute | Required | Description | -|-----------------|----------|----------------------------------------------------------------------------------------------------------| -| `link` | Yes | Name of the URL path to which this menu item links | -| `link_text` | Yes | The text presented to the user | -| `permissions` | - | A list of permissions required to display this link | -| `auth_required` | - | Display only for authenticated users | -| `staff_only` | - | Display only for users who have `is_staff` set to true (any specified permissions will also be required) | -| `buttons` | - | An iterable of PluginMenuButton instances to include | +| Attribute | Required | Description | +|-----------------|----------|------------------------------------------------------| +| `link` | Yes | Name of the URL path to which this menu item links | +| `link_text` | Yes | The text presented to the user | +| `permissions` | - | A list of permissions required to display this link | +| `auth_required` | - | Display only for authenticated users | +| `staff_only` | - | Display only for superusers | +| `buttons` | - | An iterable of PluginMenuButton instances to include | + +!!! note "Changed in NetBox v4.5" + In releases prior to NetBox v4.5, `staff_only` restricted display of a menu item to only users with `is_staff` set to True. In NetBox v4.5, the `is_staff` flag was removed from the user model. Menu items with `staff_only` set to True are now displayed only for superusers. ## Menu Buttons diff --git a/docs/plugins/development/rest-api.md b/docs/plugins/development/rest-api.md index 8cb5b3713..875289d94 100644 --- a/docs/plugins/development/rest-api.md +++ b/docs/plugins/development/rest-api.md @@ -27,6 +27,14 @@ Serializers are responsible for converting Python objects to JSON data suitable The default nested representation of an object is defined by the `brief_fields` attributes under the serializer's `Meta` class. (Older versions of NetBox required the definition of a separate nested serializer.) +In addition to the base NetBoxModelSerializer class, the following serializer classes are also available for subclasses of standard base models. + +| Model Class | Serializer Class | +|-----------------------|--------------------------------------------------------| +| `PrimaryModel` | `netbox.api.serializers.PrimaryModelSerializer` | +| `OrganizationalModel` | `netbox.api.serializers.OrganizationalModelSerializer` | +| `NestedGroupModel` | `netbox.api.serializers.NestedGroupModelSerializer` | + #### Example To create a serializer for a plugin model, subclass `NetBoxModelSerializer` in `api/serializers.py`. Specify the model class and the fields to include within the serializer's `Meta` class. diff --git a/docs/plugins/development/tables.md b/docs/plugins/development/tables.md index ea36b204d..15dceed07 100644 --- a/docs/plugins/development/tables.md +++ b/docs/plugins/development/tables.md @@ -36,6 +36,14 @@ class MyModelTable(NetBoxTable): default_columns = ('pk', 'name', ...) ``` +In addition to the base NetBoxTable class, the following table classes are also available for subclasses of standard base models. + +| Model Class | Table Class | +|-----------------------|------------------------------------------| +| `PrimaryModel` | `netbox.tables.PrimaryModelTable` | +| `OrganizationalModel` | `netbox.tables.OrganizationalModelTable` | +| `NestedGroupModel` | `netbox.tables.NestedGroupModelTable` | + ### Table Configuration The NetBoxTable class features dynamic configuration to allow users to change their column display and ordering preferences. To configure a table for a specific request, simply call its `configure()` method and pass the current HTTPRequest object. For example: diff --git a/docs/plugins/development/ui-components.md b/docs/plugins/development/ui-components.md new file mode 100644 index 000000000..a8fe2eff0 --- /dev/null +++ b/docs/plugins/development/ui-components.md @@ -0,0 +1,148 @@ +# UI Components + +!!! note "New in NetBox v4.5" + All UI components described here were introduced in NetBox v4.5. Be sure to set the minimum NetBox version to 4.5.0 for your plugin before incorporating any of these resources. + +!!! danger "Beta Feature" + UI components are considered a beta feature, and are still under active development. Please be aware that the API for resources on this page is subject to change in future releases. + +To simply the process of designing your plugin's user interface, and to encourage a consistent look and feel throughout the entire application, NetBox provides a set of components that enable programmatic UI design. These make it possible to declare complex page layouts with little or no custom HTML. + +## Page Layout + +A layout defines the general arrangement of content on a page into rows and columns. The layout is defined under the [view](./views.md) and declares a set of rows, each of which may have one or more columns. Below is an example layout. + +``` ++-------+-------+-------+ +| Col 1 | Col 2 | Col 3 | ++-------+-------+-------+ +| Col 4 | ++-----------+-----------+ +| Col 5 | Col 6 | ++-----------+-----------+ +``` + +The above layout can be achieved with the following declaration under a view: + +```python +from netbox.ui import layout +from netbox.views import generic + +class MyView(generic.ObjectView): + layout = layout.Layout( + layout.Row( + layout.Column(), + layout.Column(), + layout.Column(), + ), + layout.Row( + layout.Column(), + ), + layout.Row( + layout.Column(), + layout.Column(), + ), + ) +``` + +!!! note + Currently, layouts are supported only for subclasses of [`generic.ObjectView`](./views.md#netbox.views.generic.ObjectView). + +::: netbox.ui.layout.Layout + +::: netbox.ui.layout.SimpleLayout + +::: netbox.ui.layout.Row + +::: netbox.ui.layout.Column + +## Panels + +Within each column, related blocks of content are arranged into panels. Each panel has a title and may have a set of associated actions, but the content within is otherwise arbitrary. + +Plugins can define their own panels by inheriting from the base class `netbox.ui.panels.Panel`. Override the `get_context()` method to pass additional context to your custom panel template. An example is provided below. + +```python +from django.utils.translation import gettext_lazy as _ +from netbox.ui.panels import Panel + +class RecentChangesPanel(Panel): + template_name = 'my_plugin/panels/recent_changes.html' + title = _('Recent Changes') + + def get_context(self, context): + return { + **super().get_context(context), + 'changes': get_changes()[:10], + } +``` + +NetBox also includes a set of panels suite for specific uses, such as display object details or embedding a table of related objects. These are listed below. + +::: netbox.ui.panels.Panel + +::: netbox.ui.panels.ObjectPanel + +::: netbox.ui.panels.ObjectAttributesPanel + +#### Object Attributes + +The following classes are available to represent object attributes within an ObjectAttributesPanel. Additionally, plugins can subclass `netbox.ui.attrs.ObjectAttribute` to create custom classes. + +| Class | Description | +|--------------------------------------|--------------------------------------------------| +| `netbox.ui.attrs.AddressAttr` | A physical or mailing address. | +| `netbox.ui.attrs.BooleanAttr` | A boolean value | +| `netbox.ui.attrs.ColorAttr` | A color expressed in RGB | +| `netbox.ui.attrs.ChoiceAttr` | A selection from a set of choices | +| `netbox.ui.attrs.GPSCoordinatesAttr` | GPS coordinates (latitude and longitude) | +| `netbox.ui.attrs.ImageAttr` | An attached image (displays the image) | +| `netbox.ui.attrs.NestedObjectAttr` | A related nested object | +| `netbox.ui.attrs.NumericAttr` | An integer or float value | +| `netbox.ui.attrs.RelatedObjectAttr` | A related object | +| `netbox.ui.attrs.TemplatedAttr` | Renders an attribute using a custom template | +| `netbox.ui.attrs.TextAttr` | A string (text) value | +| `netbox.ui.attrs.TimezoneAttr` | A timezone with annotated offset | +| `netbox.ui.attrs.UtilizationAttr` | A numeric value expressed as a utilization graph | + +::: netbox.ui.panels.OrganizationalObjectPanel + +::: netbox.ui.panels.NestedGroupObjectPanel + +::: netbox.ui.panels.CommentsPanel + +::: netbox.ui.panels.JSONPanel + +::: netbox.ui.panels.RelatedObjectsPanel + +::: netbox.ui.panels.ObjectsTablePanel + +::: netbox.ui.panels.TemplatePanel + +::: netbox.ui.panels.PluginContentPanel + +## Panel Actions + +Each panel may have actions associated with it. These render as links or buttons within the panel header, opposite the panel's title. For example, a common use case is to include an "Add" action on a panel which displays a list of objects. Below is an example of this. + +```python +from django.utils.translation import gettext_lazy as _ +from netbox.ui import actions, panels + +panels.ObjectsTablePanel( + model='dcim.Region', + title=_('Child Regions'), + filters={'parent_id': lambda ctx: ctx['object'].pk}, + actions=[ + actions.AddObject('dcim.Region', url_params={'parent': lambda ctx: ctx['object'].pk}), + ], +), +``` + +::: netbox.ui.actions.PanelAction + +::: netbox.ui.actions.LinkAction + +::: netbox.ui.actions.AddObject + +::: netbox.ui.actions.CopyContent diff --git a/docs/release-notes/index.md b/docs/release-notes/index.md index b86ac3d02..27cea90f3 100644 --- a/docs/release-notes/index.md +++ b/docs/release-notes/index.md @@ -10,6 +10,14 @@ Minor releases are published in April, August, and December of each calendar yea This page contains a history of all major and minor releases since NetBox v2.0. For more detail on a specific patch release, please see the release notes page for that specific minor release. +#### [Version 4.5](./version-4.5.md) (January 2026) + +* Lookup Modifiers in Filter Forms ([#7604](https://github.com/netbox-community/netbox/issues/7604)) +* Improved API Authentication Tokens ([#20210](https://github.com/netbox-community/netbox/issues/20210)) +* Object Ownership ([#20304](https://github.com/netbox-community/netbox/issues/20304)) +* Advanced Port Mappings ([#20564](https://github.com/netbox-community/netbox/issues/20564)) +* Cable Profiles ([#20788](https://github.com/netbox-community/netbox/issues/20788)) + #### [Version 4.4](./version-4.4.md) (September 2025) * Background Jobs for Bulk Operations ([#19589](https://github.com/netbox-community/netbox/issues/19589), [#19891](https://github.com/netbox-community/netbox/issues/19891)) diff --git a/docs/release-notes/version-4.5.md b/docs/release-notes/version-4.5.md new file mode 100644 index 000000000..2efffd47a --- /dev/null +++ b/docs/release-notes/version-4.5.md @@ -0,0 +1,150 @@ +## v4.5.0 (FUTURE) + +### Breaking Changes + +* Python 3.10 and 3.11 are no longer supported. NetBox now requires Python 3.12, 3.13, or 3.14. +* GraphQL API queries which filter by object IDs or enums must now specify a filter lookup similar to other fields. For example, `id: 123` becomes `id: {exact: 123 }`. +* Rendering a device or virtual machine configuration is now restricted to users with the `render_config` permission for the applicable object type. +* Retrieval of API token plaintexts is no longer supported. The `ALLOW_TOKEN_RETRIEVAL` config parameter has been removed. +* API tokens can no longer be reassigned from one user to another. +* A config context assigned to a platform will now also apply to any children of that platform. (Although this is typically desired behavior, it may introduce unanticipated changes for existing deployments.) +* The `/api/dcim/cable-terminations/` REST API endpoint is now read-only. Cable terminations must be set on cables directly via the `/api/dcim/cables/` endpoint. +* The UI view dedicated to swapping A/Z circuit terminations has been removed. +* The experimental HTMX navigation feature has been removed. +* The obsolete boolean field `is_staff` has been removed from the `User` model. +* Removal of deprecated behavior + * The `/api/extras/object-types/` REST API endpoint has been removed. (Use `/api/core/object-types/` instead.) + * Webhooks no longer specify a `model` in payload data. (Reference `object_type` instead, which includes the parent app label.) + * The obsolete module `core.models.contenttypes` has been removed (replaced in v4.4 by `core.models.object_types`). + * The `load_yaml()` and `load_json()` utility methods have been removed from the base class for custom scripts. + +### New Features + +#### Lookup Modifiers in Filter Forms ([#7604](https://github.com/netbox-community/netbox/issues/7604)) + +Most object list filters within the UI have been extended to include optional lookup modifiers to support more complex queries. For instance, filters for numeric values now include a dropdown where a user can select "less than," "greater than," or "not" in addition to the default equivalency match. The specific modifiers available depend on the type of each filter. Plugins can register their own filtersets using the `register_filterset()` decorator to enable this new functionality. + +(Note that this feature does not introduce any new filters. Rather, it makes available in the UI filters which already exist.) + +#### Improved API Authentication Tokens ([#20210](https://github.com/netbox-community/netbox/issues/20210)) + +This release introduces a new version of API token (v2) which implements several security improvements. HMAC hashing with a cryptographic pepper is used to authenticate these tokens, obviating the need to store plaintexts. The new tokens also employ a non-sensitive key which can be shared to identify tokens without divulging their plaintexts. We've also adopted the standard "bearer" HTTP header format, as shown below. + +``` +# v1 token header +Authorization: Token + +# v2 token header +Authorization: Bearer nbt_. +``` + +Note that v2 token keys are prefixed with the fixed string `nbt_`, which can be used to aid in secret detection. + +Backward compatibility with legacy (v1) tokens is retained in this release. However, users are strongly encouraged to begin using only v2 tokens, as support for legacy tokens will be removed in NetBox v4.7. + +#### Object Ownership ([#20304](https://github.com/netbox-community/netbox/issues/20304)) + +An optional `owner` foreign key field has been added to most models. This enables the assignment of objects to a new Owner model, which represents a set of users and/or groups. Through this relationship, we can now convey ownership of objects within NetBox natively, without needing to rely on the assignment of tags or custom fields. + +(Note that ownership differs significantly in function from tenancy. Ownership determines the parties responsible for the maintenance of an object, whereas as tenancy conveys an operational dependency.) + +#### Advanced Port Mappings ([#20564](https://github.com/netbox-community/netbox/issues/20564)) + +The previous many-to-one mapping of front to rear ports has been expanded to support bidirectional mappings. The `rear_port` and `rear_port_position` fields on the FrontPort model have been replaced with an intermediary PortMapping model, which supports any number of assignments between front port/position pair and a rear port/position pair. This change unlocks the ability to model complex inline devices that swap individual fiber pairs between cables. + +#### Cable Profiles ([#20788](https://github.com/netbox-community/netbox/issues/20788)) + +Cables can now be assigned profiles which determine how they are treated for path tracing. A profile indicates the number of discrete parallel channels or lanes carried by the cable among its endpoints. For example, a 1-to-4 breakout cable has four lanes, shared at one end via a common termination and split out at the other end to four separate terminations. Profiles, when assigned, enable NetBox to more accurately trace a specific connection within a cable, rather than the cable as a whole. + +The assignment of cable profiles is optional: Cable tracing will continue to operate as before for cables with no profile assigned. + +### Enhancements + +* [#16681](https://github.com/netbox-community/netbox/issues/16681) - Introduce a `render_config` permission, which is now required to render a device or virtual machine configuration +* [#18658](https://github.com/netbox-community/netbox/issues/18658) - Add a `start_on_boot` choice field for virtual machines +* [#19095](https://github.com/netbox-community/netbox/issues/19095) - Add support for Python 3.13 and 3.14 +* [#19338](https://github.com/netbox-community/netbox/issues/19338) - Enable filter lookups for object IDs and enums in GraphQL API queries +* [#19523](https://github.com/netbox-community/netbox/issues/19523) - Cache the number of instances for device, module, and rack types, and enable filtering by these counts +* [#20417](https://github.com/netbox-community/netbox/issues/20417) - Add an optional `color` field for device type power outlets +* [#20476](https://github.com/netbox-community/netbox/issues/20476) - Once provisioned, the owner of an API token cannot be changed +* [#20492](https://github.com/netbox-community/netbox/issues/20492) - Completely disabled the means to retrieve legacy API token plaintexts (removed the `ALLOW_TOKEN_RETRIEVAL` config parameter) +* [#20639](https://github.com/netbox-community/netbox/issues/20639) - Apply config contexts to devices/VMs assigned any child platform of the parent platform +* [#20834](https://github.com/netbox-community/netbox/issues/20834) - Add an `enabled` boolean field to API tokens +* [#20917](https://github.com/netbox-community/netbox/issues/20917) - Include usage reference on API token views +* [#20925](https://github.com/netbox-community/netbox/issues/20925) - Add optional `comments` field to all subclasses of `OrganizationalModel` +* [#20929](https://github.com/netbox-community/netbox/issues/20929) - Require the `render_config` permission to view a rendered device/VM configuration in the UI +* [#20936](https://github.com/netbox-community/netbox/issues/20936) - Introduce the `/api/authentication-check/` REST API endpoint for validating authentication tokens +* [#20959](https://github.com/netbox-community/netbox/issues/20959) - Include a count of related module types for a manufacturer in the REST API + +### Plugins + +* [#13182](https://github.com/netbox-community/netbox/issues/13182) - Added `PrimaryModel`, `OrganizationalModel`, and `NestedGroupModel` to the plugins API, as well as their respective base classes for various resources + +### Other Changes + +* [#16137](https://github.com/netbox-community/netbox/issues/16137) - Remove the obsolete boolean field `is_staff` from the `User` model +* [#17571](https://github.com/netbox-community/netbox/issues/17571) - Remove the experimental HTMX navigation feature +* [#17936](https://github.com/netbox-community/netbox/issues/17936) - Introduce a dedicated `GFKSerializerField` for representing generic foreign keys in API serializers +* [#19889](https://github.com/netbox-community/netbox/issues/19889) - Drop support for Python 3.10 and 3.11 +* [#19898](https://github.com/netbox-community/netbox/issues/19898) - Remove the obsolete REST API endpoint `/api/extras/object-types/` +* [#20088](https://github.com/netbox-community/netbox/issues/20088) - Remove the non-deterministic `model` key from webhook payload data +* [#20095](https://github.com/netbox-community/netbox/issues/20095) - Remove the obsolete module `core.models.contenttypes` +* [#20096](https://github.com/netbox-community/netbox/issues/20096) - Remove the `load_yaml()` and `load_json()` utility methods from the `BaseScript` class +* [#20204](https://github.com/netbox-community/netbox/issues/20204) - Started migrating object views from custom HTML templates to declarative layouts +* [#20295](https://github.com/netbox-community/netbox/issues/20295) - Cable terminations may be modified via the REST API only by modifying the cable itself +* [#20617](https://github.com/netbox-community/netbox/issues/20617) - Introduce `BaseModel` as the global base class for models +* [#20683](https://github.com/netbox-community/netbox/issues/20683) - Remove the UI view dedicated to swapping A/Z circuit terminations +* [#20926](https://github.com/netbox-community/netbox/issues/20926) - Standardize naming of GraphQL filters + +### REST API Changes + +* Most objects now include an optional `owner` foreign key field. +* The `/api/dcim/cable-terminations` endpoint is now read-only. +* Introduced the `/api/authentication-check/` endpoint to test REST API credentials +* `circuits.CircuitGroup` + * Add optional `comments` field +* `circuits.CircuitType` + * Add optional `comments` field +* `circuits.VirtualCircuitType` + * Add optional `comments` field +* `dcim.Cable` + * Add the optional `profile` choice field +* `dcim.FrontPort` + * Removed the `rear_port` and `rear_port_position` fields + * Add the `positions` integer field + * Add the `rear_ports` list for port mappings +* `dcim.InventoryItemRole` + * Add optional `comments` field +* `dcim.Manufacturer` + * Add optional `comments` field + * Add read-only `moduletype_count` integer field +* `dcim.ModuleType` + * Add read-only `module_count` integer field +* `dcim.PowerOutletTemplate` + * Add optional `color` field +* `dcim.RackRole` + * Add optional `comments` field +* `dcim.RackType` + * Add read-only `rack_count` integer field +* `dcim.RearPort` + * Add the `front_ports` list for port mappings +* `ipam.ASNRange` + * Add optional `comments` field +* `ipam.RIR` + * Add optional `comments` field +* `ipam.Role` + * Add optional `comments` field +* `ipam.VLANGroup` + * Add optional `comments` field +* `tenancy.ContactRole` + * Add optional `comments` field +* `users.Token` + * Add `enabled` boolean field +* `virtualization.ClusterGroup` + * Add optional `comments` field +* `virtualization.ClusterType` + * Add optional `comments` field +* `virtualization.VirtualMachine` + * Add optional `start_on_boot` choice field +* `vpn.TunnelGroup` + * Add optional `comments` field diff --git a/mkdocs.yml b/mkdocs.yml index fd6d7e4f2..dc758f197 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -77,6 +77,7 @@ nav: - Wireless: 'features/wireless.md' - Virtualization: 'features/virtualization.md' - VPN Tunnels: 'features/vpn-tunnels.md' + - Resource Ownership: 'features/resource-ownership.md' - Tenancy: 'features/tenancy.md' - Contacts: 'features/contacts.md' - Search: 'features/search.md' @@ -142,6 +143,7 @@ nav: - Getting Started: 'plugins/development/index.md' - Models: 'plugins/development/models.md' - Views: 'plugins/development/views.md' + - UI Components: 'plugins/development/ui-components.md' - Navigation: 'plugins/development/navigation.md' - Templates: 'plugins/development/templates.md' - Tables: 'plugins/development/tables.md' @@ -273,6 +275,9 @@ nav: - ContactRole: 'models/tenancy/contactrole.md' - Tenant: 'models/tenancy/tenant.md' - TenantGroup: 'models/tenancy/tenantgroup.md' + - Users: + - Owner: 'models/users/owner.md' + - OwnerGroup: 'models/users/ownergroup.md' - Virtualization: - Cluster: 'models/virtualization/cluster.md' - ClusterGroup: 'models/virtualization/clustergroup.md' @@ -317,6 +322,7 @@ nav: - git Cheat Sheet: 'development/git-cheat-sheet.md' - Release Notes: - Summary: 'release-notes/index.md' + - Version 4.5: 'release-notes/version-4.5.md' - Version 4.4: 'release-notes/version-4.4.md' - Version 4.3: 'release-notes/version-4.3.md' - Version 4.2: 'release-notes/version-4.2.md' diff --git a/netbox/account/tables.py b/netbox/account/tables.py deleted file mode 100644 index bcc0a0ccd..000000000 --- a/netbox/account/tables.py +++ /dev/null @@ -1,57 +0,0 @@ -from django.utils.translation import gettext as _ - -from account.models import UserToken -from netbox.tables import NetBoxTable, columns - -__all__ = ( - 'UserTokenTable', -) - - -TOKEN = """{{ record }}""" - -ALLOWED_IPS = """{{ value|join:", " }}""" - -COPY_BUTTON = """ -{% if settings.ALLOW_TOKEN_RETRIEVAL %} - {% copy_content record.pk prefix="token_" color="success" %} -{% endif %} -""" - - -class UserTokenTable(NetBoxTable): - """ - Table for users to manager their own API tokens under account views. - """ - key = columns.TemplateColumn( - verbose_name=_('Key'), - template_code=TOKEN, - ) - write_enabled = columns.BooleanColumn( - verbose_name=_('Write Enabled') - ) - created = columns.DateTimeColumn( - timespec='minutes', - verbose_name=_('Created'), - ) - expires = columns.DateTimeColumn( - timespec='minutes', - verbose_name=_('Expires'), - ) - last_used = columns.DateTimeColumn( - verbose_name=_('Last Used'), - ) - allowed_ips = columns.TemplateColumn( - verbose_name=_('Allowed IPs'), - template_code=ALLOWED_IPS - ) - actions = columns.ActionsColumn( - actions=('edit', 'delete'), - extra_buttons=COPY_BUTTON - ) - - class Meta(NetBoxTable.Meta): - model = UserToken - fields = ( - 'pk', 'id', 'key', 'description', 'write_enabled', 'created', 'expires', 'last_used', 'allowed_ips', - ) diff --git a/netbox/account/views.py b/netbox/account/views.py index f5ef534ce..7dd423919 100644 --- a/netbox/account/views.py +++ b/netbox/account/views.py @@ -25,9 +25,12 @@ from extras.models import Bookmark from extras.tables import BookmarkTable, NotificationTable, SubscriptionTable from netbox.authentication import get_auth_backend_display, get_saml_idps from netbox.config import get_config +from netbox.ui import layout from netbox.views import generic -from users import forms, tables +from users import forms from users.models import UserConfig +from users.tables import TokenTable +from users.ui.panels import TokenExamplePanel, TokenPanel from utilities.request import safe_for_redirect from utilities.string import remove_linebreaks from utilities.views import register_model_view @@ -328,7 +331,8 @@ class UserTokenListView(LoginRequiredMixin, View): def get(self, request): tokens = UserToken.objects.filter(user=request.user) - table = tables.UserTokenTable(tokens) + table = TokenTable(tokens) + table.columns.hide('user') table.configure(request) return render(request, 'account/token_list.html', { @@ -340,14 +344,21 @@ class UserTokenListView(LoginRequiredMixin, View): @register_model_view(UserToken) class UserTokenView(LoginRequiredMixin, View): + layout = layout.SimpleLayout( + left_panels=[ + TokenPanel(), + ], + right_panels=[ + TokenExamplePanel(), + ], + ) def get(self, request, pk): token = get_object_or_404(UserToken.objects.filter(user=request.user), pk=pk) - key = token.key if settings.ALLOW_TOKEN_RETRIEVAL else None return render(request, 'account/token.html', { 'object': token, - 'key': key, + 'layout': self.layout, }) diff --git a/netbox/circuits/api/serializers_/circuits.py b/netbox/circuits/api/serializers_/circuits.py index 70b57a688..6ac4f39a3 100644 --- a/netbox/circuits/api/serializers_/circuits.py +++ b/netbox/circuits/api/serializers_/circuits.py @@ -1,5 +1,4 @@ from django.contrib.contenttypes.models import ContentType -from drf_spectacular.utils import extend_schema_field from rest_framework import serializers from circuits.choices import CircuitPriorityChoices, CircuitStatusChoices, VirtualCircuitTerminationRoleChoices @@ -11,10 +10,12 @@ from circuits.models import ( from dcim.api.serializers_.device_components import InterfaceSerializer from dcim.api.serializers_.cables import CabledObjectSerializer from netbox.api.fields import ChoiceField, ContentTypeField, RelatedObjectCountField -from netbox.api.serializers import NetBoxModelSerializer, WritableNestedSerializer +from netbox.api.gfk_fields import GFKSerializerField +from netbox.api.serializers import ( + NetBoxModelSerializer, OrganizationalModelSerializer, PrimaryModelSerializer, WritableNestedSerializer, +) from netbox.choices import DistanceUnitChoices from tenancy.api.serializers_.tenants import TenantSerializer -from utilities.api import get_serializer_for_model from .providers import ProviderAccountSerializer, ProviderNetworkSerializer, ProviderSerializer __all__ = ( @@ -29,7 +30,7 @@ __all__ = ( ) -class CircuitTypeSerializer(NetBoxModelSerializer): +class CircuitTypeSerializer(OrganizationalModelSerializer): # Related object counts circuit_count = RelatedObjectCountField('circuits') @@ -37,8 +38,8 @@ class CircuitTypeSerializer(NetBoxModelSerializer): class Meta: model = CircuitType fields = [ - 'id', 'url', 'display_url', 'display', 'name', 'slug', 'color', 'description', 'tags', 'custom_fields', - 'created', 'last_updated', 'circuit_count', + 'id', 'url', 'display_url', 'display', 'name', 'slug', 'color', 'description', 'owner', 'comments', 'tags', + 'custom_fields', 'created', 'last_updated', 'circuit_count', ] brief_fields = ('id', 'url', 'display', 'name', 'slug', 'description', 'circuit_count') @@ -53,7 +54,7 @@ class CircuitCircuitTerminationSerializer(WritableNestedSerializer): default=None ) termination_id = serializers.IntegerField(allow_null=True, required=False, default=None) - termination = serializers.SerializerMethodField(read_only=True) + termination = GFKSerializerField(read_only=True) class Meta: model = CircuitTermination @@ -62,24 +63,16 @@ class CircuitCircuitTerminationSerializer(WritableNestedSerializer): 'upstream_speed', 'xconnect_id', 'description', ] - @extend_schema_field(serializers.JSONField(allow_null=True)) - def get_termination(self, obj): - if obj.termination_id is None: - return None - serializer = get_serializer_for_model(obj.termination) - context = {'request': self.context['request']} - return serializer(obj.termination, nested=True, context=context).data - -class CircuitGroupSerializer(NetBoxModelSerializer): +class CircuitGroupSerializer(OrganizationalModelSerializer): tenant = TenantSerializer(nested=True, required=False, allow_null=True) circuit_count = RelatedObjectCountField('assignments') class Meta: model = CircuitGroup fields = [ - 'id', 'url', 'display_url', 'display', 'name', 'slug', 'description', 'tenant', - 'tags', 'custom_fields', 'created', 'last_updated', 'circuit_count' + 'id', 'url', 'display_url', 'display', 'name', 'slug', 'description', 'tenant', 'owner', 'comments', 'tags', + 'custom_fields', 'created', 'last_updated', 'circuit_count' ] brief_fields = ('id', 'url', 'display', 'name') @@ -99,7 +92,7 @@ class CircuitGroupAssignmentSerializer_(NetBoxModelSerializer): brief_fields = ('id', 'url', 'display', 'group', 'priority') -class CircuitSerializer(NetBoxModelSerializer): +class CircuitSerializer(PrimaryModelSerializer): provider = ProviderSerializer(nested=True) provider_account = ProviderAccountSerializer(nested=True, required=False, allow_null=True, default=None) status = ChoiceField(choices=CircuitStatusChoices, required=False) @@ -115,7 +108,7 @@ class CircuitSerializer(NetBoxModelSerializer): fields = [ 'id', 'url', 'display_url', 'display', 'cid', 'provider', 'provider_account', 'type', 'status', 'tenant', 'install_date', 'termination_date', 'commit_rate', 'description', 'distance', 'distance_unit', - 'termination_a', 'termination_z', 'comments', 'tags', 'custom_fields', 'created', 'last_updated', + 'termination_a', 'termination_z', 'owner', 'comments', 'tags', 'custom_fields', 'created', 'last_updated', 'assignments', ] brief_fields = ('id', 'url', 'display', 'provider', 'cid', 'description') @@ -132,7 +125,7 @@ class CircuitTerminationSerializer(NetBoxModelSerializer, CabledObjectSerializer default=None ) termination_id = serializers.IntegerField(allow_null=True, required=False, default=None) - termination = serializers.SerializerMethodField(read_only=True) + termination = GFKSerializerField(read_only=True) class Meta: model = CircuitTermination @@ -144,20 +137,12 @@ class CircuitTerminationSerializer(NetBoxModelSerializer, CabledObjectSerializer ] brief_fields = ('id', 'url', 'display', 'circuit', 'term_side', 'description', 'cable', '_occupied') - @extend_schema_field(serializers.JSONField(allow_null=True)) - def get_termination(self, obj): - if obj.termination_id is None: - return None - serializer = get_serializer_for_model(obj.termination) - context = {'request': self.context['request']} - return serializer(obj.termination, nested=True, context=context).data - class CircuitGroupAssignmentSerializer(CircuitGroupAssignmentSerializer_): member_type = ContentTypeField( queryset=ContentType.objects.filter(CIRCUIT_GROUP_ASSIGNMENT_MEMBER_MODELS) ) - member = serializers.SerializerMethodField(read_only=True) + member = GFKSerializerField(read_only=True) class Meta: model = CircuitGroupAssignment @@ -167,16 +152,8 @@ class CircuitGroupAssignmentSerializer(CircuitGroupAssignmentSerializer_): ] brief_fields = ('id', 'url', 'display', 'group', 'member_type', 'member_id', 'member', 'priority') - @extend_schema_field(serializers.JSONField(allow_null=True)) - def get_member(self, obj): - if obj.member_id is None: - return None - serializer = get_serializer_for_model(obj.member) - context = {'request': self.context['request']} - return serializer(obj.member, nested=True, context=context).data - -class VirtualCircuitTypeSerializer(NetBoxModelSerializer): +class VirtualCircuitTypeSerializer(OrganizationalModelSerializer): # Related object counts virtual_circuit_count = RelatedObjectCountField('virtual_circuits') @@ -184,13 +161,13 @@ class VirtualCircuitTypeSerializer(NetBoxModelSerializer): class Meta: model = VirtualCircuitType fields = [ - 'id', 'url', 'display_url', 'display', 'name', 'slug', 'color', 'description', 'tags', 'custom_fields', - 'created', 'last_updated', 'virtual_circuit_count', + 'id', 'url', 'display_url', 'display', 'name', 'slug', 'color', 'description', 'owner', 'comments', 'tags', + 'custom_fields', 'created', 'last_updated', 'virtual_circuit_count', ] brief_fields = ('id', 'url', 'display', 'name', 'slug', 'description', 'virtual_circuit_count') -class VirtualCircuitSerializer(NetBoxModelSerializer): +class VirtualCircuitSerializer(PrimaryModelSerializer): provider_network = ProviderNetworkSerializer(nested=True) provider_account = ProviderAccountSerializer(nested=True, required=False, allow_null=True, default=None) type = VirtualCircuitTypeSerializer(nested=True) @@ -201,7 +178,7 @@ class VirtualCircuitSerializer(NetBoxModelSerializer): model = VirtualCircuit fields = [ 'id', 'url', 'display_url', 'display', 'cid', 'provider_network', 'provider_account', 'type', 'status', - 'tenant', 'description', 'comments', 'tags', 'custom_fields', 'created', 'last_updated', + 'tenant', 'description', 'owner', 'comments', 'tags', 'custom_fields', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'provider_network', 'cid', 'description') diff --git a/netbox/circuits/api/serializers_/providers.py b/netbox/circuits/api/serializers_/providers.py index 4e3787107..875c5c7f2 100644 --- a/netbox/circuits/api/serializers_/providers.py +++ b/netbox/circuits/api/serializers_/providers.py @@ -4,7 +4,7 @@ from circuits.models import Provider, ProviderAccount, ProviderNetwork from ipam.api.serializers_.asns import ASNSerializer from ipam.models import ASN from netbox.api.fields import RelatedObjectCountField, SerializedPKRelatedField -from netbox.api.serializers import NetBoxModelSerializer +from netbox.api.serializers import PrimaryModelSerializer from .nested import NestedProviderAccountSerializer __all__ = ( @@ -14,7 +14,7 @@ __all__ = ( ) -class ProviderSerializer(NetBoxModelSerializer): +class ProviderSerializer(PrimaryModelSerializer): accounts = SerializedPKRelatedField( queryset=ProviderAccount.objects.all(), serializer=NestedProviderAccountSerializer, @@ -35,32 +35,32 @@ class ProviderSerializer(NetBoxModelSerializer): class Meta: model = Provider fields = [ - 'id', 'url', 'display_url', 'display', 'name', 'slug', 'accounts', 'description', 'comments', + 'id', 'url', 'display_url', 'display', 'name', 'slug', 'accounts', 'description', 'owner', 'comments', 'asns', 'tags', 'custom_fields', 'created', 'last_updated', 'circuit_count', ] brief_fields = ('id', 'url', 'display', 'name', 'slug', 'description', 'circuit_count') -class ProviderAccountSerializer(NetBoxModelSerializer): +class ProviderAccountSerializer(PrimaryModelSerializer): provider = ProviderSerializer(nested=True) name = serializers.CharField(allow_blank=True, max_length=100, required=False, default='') class Meta: model = ProviderAccount fields = [ - 'id', 'url', 'display_url', 'display', 'provider', 'name', 'account', 'description', 'comments', 'tags', - 'custom_fields', 'created', 'last_updated', + 'id', 'url', 'display_url', 'display', 'provider', 'name', 'account', 'description', 'owner', 'comments', + 'tags', 'custom_fields', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'name', 'account', 'description') -class ProviderNetworkSerializer(NetBoxModelSerializer): +class ProviderNetworkSerializer(PrimaryModelSerializer): provider = ProviderSerializer(nested=True) class Meta: model = ProviderNetwork fields = [ - 'id', 'url', 'display_url', 'display', 'provider', 'name', 'service_id', 'description', 'comments', 'tags', - 'custom_fields', 'created', 'last_updated', + 'id', 'url', 'display_url', 'display', 'provider', 'name', 'service_id', 'description', 'owner', 'comments', + 'tags', 'custom_fields', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'name', 'description') diff --git a/netbox/circuits/filtersets.py b/netbox/circuits/filtersets.py index e02db20e0..6c7b45164 100644 --- a/netbox/circuits/filtersets.py +++ b/netbox/circuits/filtersets.py @@ -6,11 +6,12 @@ from django.utils.translation import gettext as _ from dcim.filtersets import CabledObjectFilterSet from dcim.models import Interface, Location, Region, Site, SiteGroup from ipam.models import ASN -from netbox.filtersets import NetBoxModelFilterSet, OrganizationalModelFilterSet +from netbox.filtersets import NetBoxModelFilterSet, OrganizationalModelFilterSet, PrimaryModelFilterSet from tenancy.filtersets import ContactModelFilterSet, TenancyFilterSet from utilities.filters import ( ContentTypeFilter, MultiValueCharFilter, MultiValueNumberFilter, TreeNodeMultipleChoiceFilter, ) +from utilities.filtersets import register_filterset from .choices import * from .models import * @@ -29,7 +30,8 @@ __all__ = ( ) -class ProviderFilterSet(NetBoxModelFilterSet, ContactModelFilterSet): +@register_filterset +class ProviderFilterSet(PrimaryModelFilterSet, ContactModelFilterSet): region_id = TreeNodeMultipleChoiceFilter( queryset=Region.objects.all(), field_name='circuits__terminations___region', @@ -93,7 +95,8 @@ class ProviderFilterSet(NetBoxModelFilterSet, ContactModelFilterSet): ) -class ProviderAccountFilterSet(NetBoxModelFilterSet, ContactModelFilterSet): +@register_filterset +class ProviderAccountFilterSet(PrimaryModelFilterSet, ContactModelFilterSet): provider_id = django_filters.ModelMultipleChoiceFilter( queryset=Provider.objects.all(), label=_('Provider (ID)'), @@ -120,7 +123,8 @@ class ProviderAccountFilterSet(NetBoxModelFilterSet, ContactModelFilterSet): ).distinct() -class ProviderNetworkFilterSet(NetBoxModelFilterSet): +@register_filterset +class ProviderNetworkFilterSet(PrimaryModelFilterSet): provider_id = django_filters.ModelMultipleChoiceFilter( queryset=Provider.objects.all(), label=_('Provider (ID)'), @@ -147,6 +151,7 @@ class ProviderNetworkFilterSet(NetBoxModelFilterSet): ).distinct() +@register_filterset class CircuitTypeFilterSet(OrganizationalModelFilterSet): class Meta: @@ -154,7 +159,8 @@ class CircuitTypeFilterSet(OrganizationalModelFilterSet): fields = ('id', 'name', 'slug', 'color', 'description') -class CircuitFilterSet(NetBoxModelFilterSet, TenancyFilterSet, ContactModelFilterSet): +@register_filterset +class CircuitFilterSet(PrimaryModelFilterSet, TenancyFilterSet, ContactModelFilterSet): provider_id = django_filters.ModelMultipleChoiceFilter( queryset=Provider.objects.all(), label=_('Provider (ID)'), @@ -265,6 +271,7 @@ class CircuitFilterSet(NetBoxModelFilterSet, TenancyFilterSet, ContactModelFilte ).distinct() +@register_filterset class CircuitTerminationFilterSet(NetBoxModelFilterSet, CabledObjectFilterSet): q = django_filters.CharFilter( method='search', @@ -346,7 +353,7 @@ class CircuitTerminationFilterSet(NetBoxModelFilterSet, CabledObjectFilterSet): model = CircuitTermination fields = ( 'id', 'termination_id', 'term_side', 'port_speed', 'upstream_speed', 'xconnect_id', 'description', - 'mark_connected', 'pp_info', 'cable_end', + 'mark_connected', 'pp_info', 'cable_end', 'cable_connector', ) def search(self, queryset, name, value): @@ -360,6 +367,7 @@ class CircuitTerminationFilterSet(NetBoxModelFilterSet, CabledObjectFilterSet): ).distinct() +@register_filterset class CircuitGroupFilterSet(OrganizationalModelFilterSet, TenancyFilterSet): class Meta: @@ -367,6 +375,7 @@ class CircuitGroupFilterSet(OrganizationalModelFilterSet, TenancyFilterSet): fields = ('id', 'name', 'slug', 'description') +@register_filterset class CircuitGroupAssignmentFilterSet(NetBoxModelFilterSet): q = django_filters.CharFilter( method='search', @@ -466,6 +475,7 @@ class CircuitGroupAssignmentFilterSet(NetBoxModelFilterSet): ) +@register_filterset class VirtualCircuitTypeFilterSet(OrganizationalModelFilterSet): class Meta: @@ -473,7 +483,8 @@ class VirtualCircuitTypeFilterSet(OrganizationalModelFilterSet): fields = ('id', 'name', 'slug', 'color', 'description') -class VirtualCircuitFilterSet(NetBoxModelFilterSet, TenancyFilterSet): +@register_filterset +class VirtualCircuitFilterSet(PrimaryModelFilterSet, TenancyFilterSet): provider_id = django_filters.ModelMultipleChoiceFilter( field_name='provider_network__provider', queryset=Provider.objects.all(), @@ -529,6 +540,7 @@ class VirtualCircuitFilterSet(NetBoxModelFilterSet, TenancyFilterSet): ).distinct() +@register_filterset class VirtualCircuitTerminationFilterSet(NetBoxModelFilterSet): q = django_filters.CharFilter( method='search', diff --git a/netbox/circuits/forms/bulk_edit.py b/netbox/circuits/forms/bulk_edit.py index 8d6e8dec1..d03577ab9 100644 --- a/netbox/circuits/forms/bulk_edit.py +++ b/netbox/circuits/forms/bulk_edit.py @@ -11,11 +11,11 @@ from circuits.models import * from dcim.models import Site from ipam.models import ASN from netbox.choices import DistanceUnitChoices -from netbox.forms import NetBoxModelBulkEditForm +from netbox.forms import NetBoxModelBulkEditForm, OrganizationalModelBulkEditForm, PrimaryModelBulkEditForm from tenancy.models import Tenant from utilities.forms import add_blank_choice, get_field_value from utilities.forms.fields import ( - ColorField, CommentField, ContentTypeChoiceField, DynamicModelChoiceField, DynamicModelMultipleChoiceField, + ColorField, ContentTypeChoiceField, DynamicModelChoiceField, DynamicModelMultipleChoiceField, ) from utilities.forms.rendering import FieldSet from utilities.forms.widgets import BulkEditNullBooleanSelect, DatePicker, HTMXSelect, NumberWithOptions @@ -36,18 +36,12 @@ __all__ = ( ) -class ProviderBulkEditForm(NetBoxModelBulkEditForm): +class ProviderBulkEditForm(PrimaryModelBulkEditForm): asns = DynamicModelMultipleChoiceField( queryset=ASN.objects.all(), label=_('ASNs'), required=False ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = Provider fieldsets = ( @@ -58,18 +52,12 @@ class ProviderBulkEditForm(NetBoxModelBulkEditForm): ) -class ProviderAccountBulkEditForm(NetBoxModelBulkEditForm): +class ProviderAccountBulkEditForm(PrimaryModelBulkEditForm): provider = DynamicModelChoiceField( label=_('Provider'), queryset=Provider.objects.all(), required=False ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = ProviderAccount fieldsets = ( @@ -80,7 +68,7 @@ class ProviderAccountBulkEditForm(NetBoxModelBulkEditForm): ) -class ProviderNetworkBulkEditForm(NetBoxModelBulkEditForm): +class ProviderNetworkBulkEditForm(PrimaryModelBulkEditForm): provider = DynamicModelChoiceField( label=_('Provider'), queryset=Provider.objects.all(), @@ -91,12 +79,6 @@ class ProviderNetworkBulkEditForm(NetBoxModelBulkEditForm): required=False, label=_('Service ID') ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = ProviderNetwork fieldsets = ( @@ -107,25 +89,20 @@ class ProviderNetworkBulkEditForm(NetBoxModelBulkEditForm): ) -class CircuitTypeBulkEditForm(NetBoxModelBulkEditForm): +class CircuitTypeBulkEditForm(OrganizationalModelBulkEditForm): color = ColorField( label=_('Color'), required=False ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) model = CircuitType fieldsets = ( FieldSet('color', 'description'), ) - nullable_fields = ('color', 'description') + nullable_fields = ('color', 'description', 'comments') -class CircuitBulkEditForm(NetBoxModelBulkEditForm): +class CircuitBulkEditForm(PrimaryModelBulkEditForm): type = DynamicModelChoiceField( label=_('Type'), queryset=CircuitType.objects.all(), @@ -183,12 +160,6 @@ class CircuitBulkEditForm(NetBoxModelBulkEditForm): required=False, initial='' ) - description = forms.CharField( - label=_('Description'), - max_length=100, - required=False - ) - comments = CommentField() model = Circuit fieldsets = ( @@ -261,12 +232,7 @@ class CircuitTerminationBulkEditForm(NetBoxModelBulkEditForm): pass -class CircuitGroupBulkEditForm(NetBoxModelBulkEditForm): - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) +class CircuitGroupBulkEditForm(OrganizationalModelBulkEditForm): tenant = DynamicModelChoiceField( label=_('Tenant'), queryset=Tenant.objects.all(), @@ -275,7 +241,7 @@ class CircuitGroupBulkEditForm(NetBoxModelBulkEditForm): model = CircuitGroup nullable_fields = ( - 'description', 'tenant', + 'description', 'tenant', 'comments', ) @@ -298,25 +264,20 @@ class CircuitGroupAssignmentBulkEditForm(NetBoxModelBulkEditForm): nullable_fields = ('priority',) -class VirtualCircuitTypeBulkEditForm(NetBoxModelBulkEditForm): +class VirtualCircuitTypeBulkEditForm(OrganizationalModelBulkEditForm): color = ColorField( label=_('Color'), required=False ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) model = VirtualCircuitType fieldsets = ( FieldSet('color', 'description'), ) - nullable_fields = ('color', 'description') + nullable_fields = ('color', 'description', 'comments') -class VirtualCircuitBulkEditForm(NetBoxModelBulkEditForm): +class VirtualCircuitBulkEditForm(PrimaryModelBulkEditForm): provider_network = DynamicModelChoiceField( label=_('Provider network'), queryset=ProviderNetwork.objects.all(), @@ -343,12 +304,6 @@ class VirtualCircuitBulkEditForm(NetBoxModelBulkEditForm): queryset=Tenant.objects.all(), required=False ) - description = forms.CharField( - label=_('Description'), - max_length=100, - required=False - ) - comments = CommentField() model = VirtualCircuit fieldsets = ( diff --git a/netbox/circuits/forms/bulk_import.py b/netbox/circuits/forms/bulk_import.py index 43700d16b..dbcd1554b 100644 --- a/netbox/circuits/forms/bulk_import.py +++ b/netbox/circuits/forms/bulk_import.py @@ -7,7 +7,7 @@ from circuits.constants import * from circuits.models import * from dcim.models import Interface from netbox.choices import DistanceUnitChoices -from netbox.forms import NetBoxModelImportForm +from netbox.forms import NetBoxModelImportForm, OrganizationalModelImportForm, PrimaryModelImportForm from tenancy.models import Tenant from utilities.forms.fields import CSVChoiceField, CSVContentTypeField, CSVModelChoiceField, SlugField @@ -28,17 +28,17 @@ __all__ = ( ) -class ProviderImportForm(NetBoxModelImportForm): +class ProviderImportForm(PrimaryModelImportForm): slug = SlugField() class Meta: model = Provider fields = ( - 'name', 'slug', 'description', 'comments', 'tags', + 'name', 'slug', 'description', 'owner', 'comments', 'tags', ) -class ProviderAccountImportForm(NetBoxModelImportForm): +class ProviderAccountImportForm(PrimaryModelImportForm): provider = CSVModelChoiceField( label=_('Provider'), queryset=Provider.objects.all(), @@ -49,11 +49,11 @@ class ProviderAccountImportForm(NetBoxModelImportForm): class Meta: model = ProviderAccount fields = ( - 'provider', 'name', 'account', 'description', 'comments', 'tags', + 'provider', 'name', 'account', 'description', 'owner', 'comments', 'tags', ) -class ProviderNetworkImportForm(NetBoxModelImportForm): +class ProviderNetworkImportForm(PrimaryModelImportForm): provider = CSVModelChoiceField( label=_('Provider'), queryset=Provider.objects.all(), @@ -64,19 +64,19 @@ class ProviderNetworkImportForm(NetBoxModelImportForm): class Meta: model = ProviderNetwork fields = [ - 'provider', 'name', 'service_id', 'description', 'comments', 'tags' + 'provider', 'name', 'service_id', 'description', 'owner', 'comments', 'tags' ] -class CircuitTypeImportForm(NetBoxModelImportForm): +class CircuitTypeImportForm(OrganizationalModelImportForm): slug = SlugField() class Meta: model = CircuitType - fields = ('name', 'slug', 'color', 'description', 'tags') + fields = ('name', 'slug', 'color', 'description', 'owner', 'comments', 'tags') -class CircuitImportForm(NetBoxModelImportForm): +class CircuitImportForm(PrimaryModelImportForm): provider = CSVModelChoiceField( label=_('Provider'), queryset=Provider.objects.all(), @@ -119,7 +119,7 @@ class CircuitImportForm(NetBoxModelImportForm): model = Circuit fields = [ 'cid', 'provider', 'provider_account', 'type', 'status', 'tenant', 'install_date', 'termination_date', - 'commit_rate', 'distance', 'distance_unit', 'description', 'comments', 'tags' + 'commit_rate', 'distance', 'distance_unit', 'description', 'owner', 'comments', 'tags' ] @@ -165,7 +165,7 @@ class CircuitTerminationImportForm(NetBoxModelImportForm, BaseCircuitTermination } -class CircuitGroupImportForm(NetBoxModelImportForm): +class CircuitGroupImportForm(OrganizationalModelImportForm): tenant = CSVModelChoiceField( label=_('Tenant'), queryset=Tenant.objects.all(), @@ -176,7 +176,7 @@ class CircuitGroupImportForm(NetBoxModelImportForm): class Meta: model = CircuitGroup - fields = ('name', 'slug', 'description', 'tenant', 'tags') + fields = ('name', 'slug', 'description', 'tenant', 'owner', 'comments', 'tags') class CircuitGroupAssignmentImportForm(NetBoxModelImportForm): @@ -195,15 +195,14 @@ class CircuitGroupAssignmentImportForm(NetBoxModelImportForm): fields = ('member_type', 'member_id', 'group', 'priority') -class VirtualCircuitTypeImportForm(NetBoxModelImportForm): - slug = SlugField() +class VirtualCircuitTypeImportForm(OrganizationalModelImportForm): class Meta: model = VirtualCircuitType - fields = ('name', 'slug', 'color', 'description', 'tags') + fields = ('name', 'slug', 'color', 'description', 'owner', 'comments', 'tags') -class VirtualCircuitImportForm(NetBoxModelImportForm): +class VirtualCircuitImportForm(PrimaryModelImportForm): provider_network = CSVModelChoiceField( label=_('Provider network'), queryset=ProviderNetwork.objects.all(), @@ -239,8 +238,8 @@ class VirtualCircuitImportForm(NetBoxModelImportForm): class Meta: model = VirtualCircuit fields = [ - 'cid', 'provider_network', 'provider_account', 'type', 'status', 'tenant', 'description', 'comments', - 'tags', + 'cid', 'provider_network', 'provider_account', 'type', 'status', 'tenant', 'description', 'owner', + 'comments', 'tags', ] diff --git a/netbox/circuits/forms/filtersets.py b/netbox/circuits/forms/filtersets.py index 9b2129989..c71f5c65c 100644 --- a/netbox/circuits/forms/filtersets.py +++ b/netbox/circuits/forms/filtersets.py @@ -9,7 +9,7 @@ from circuits.models import * from dcim.models import Location, Region, Site, SiteGroup from ipam.models import ASN from netbox.choices import DistanceUnitChoices -from netbox.forms import NetBoxModelFilterSetForm +from netbox.forms import NetBoxModelFilterSetForm, OrganizationalModelFilterSetForm, PrimaryModelFilterSetForm from tenancy.forms import TenancyFilterForm, ContactModelFilterForm from utilities.forms import add_blank_choice from utilities.forms.fields import ColorField, DynamicModelMultipleChoiceField, TagFilterField @@ -31,10 +31,10 @@ __all__ = ( ) -class ProviderFilterForm(ContactModelFilterForm, NetBoxModelFilterSetForm): +class ProviderFilterForm(ContactModelFilterForm, PrimaryModelFilterSetForm): model = Provider fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('region_id', 'site_group_id', 'site_id', name=_('Location')), FieldSet('asn_id', name=_('ASN')), FieldSet('contact', 'contact_role', 'contact_group', name=_('Contacts')), @@ -66,10 +66,10 @@ class ProviderFilterForm(ContactModelFilterForm, NetBoxModelFilterSetForm): tag = TagFilterField(model) -class ProviderAccountFilterForm(ContactModelFilterForm, NetBoxModelFilterSetForm): +class ProviderAccountFilterForm(ContactModelFilterForm, PrimaryModelFilterSetForm): model = ProviderAccount fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('provider_id', 'account', name=_('Attributes')), FieldSet('contact', 'contact_role', 'contact_group', name=_('Contacts')), ) @@ -85,10 +85,10 @@ class ProviderAccountFilterForm(ContactModelFilterForm, NetBoxModelFilterSetForm tag = TagFilterField(model) -class ProviderNetworkFilterForm(NetBoxModelFilterSetForm): +class ProviderNetworkFilterForm(PrimaryModelFilterSetForm): model = ProviderNetwork fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('provider_id', 'service_id', name=_('Attributes')), ) provider_id = DynamicModelMultipleChoiceField( @@ -104,10 +104,10 @@ class ProviderNetworkFilterForm(NetBoxModelFilterSetForm): tag = TagFilterField(model) -class CircuitTypeFilterForm(NetBoxModelFilterSetForm): +class CircuitTypeFilterForm(OrganizationalModelFilterSetForm): model = CircuitType fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('color', name=_('Attributes')), ) tag = TagFilterField(model) @@ -118,10 +118,10 @@ class CircuitTypeFilterForm(NetBoxModelFilterSetForm): ) -class CircuitFilterForm(TenancyFilterForm, ContactModelFilterForm, NetBoxModelFilterSetForm): +class CircuitFilterForm(TenancyFilterForm, ContactModelFilterForm, PrimaryModelFilterSetForm): model = Circuit fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('provider_id', 'provider_account_id', 'provider_network_id', name=_('Provider')), FieldSet( 'type_id', 'status', 'install_date', 'termination_date', 'commit_rate', 'distance', 'distance_unit', @@ -271,10 +271,10 @@ class CircuitTerminationFilterForm(NetBoxModelFilterSetForm): tag = TagFilterField(model) -class CircuitGroupFilterForm(TenancyFilterForm, NetBoxModelFilterSetForm): +class CircuitGroupFilterForm(TenancyFilterForm, OrganizationalModelFilterSetForm): model = CircuitGroup fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('tenant_group_id', 'tenant_id', name=_('Tenant')), ) tag = TagFilterField(model) @@ -309,10 +309,10 @@ class CircuitGroupAssignmentFilterForm(NetBoxModelFilterSetForm): tag = TagFilterField(model) -class VirtualCircuitTypeFilterForm(NetBoxModelFilterSetForm): +class VirtualCircuitTypeFilterForm(OrganizationalModelFilterSetForm): model = VirtualCircuitType fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('color', name=_('Attributes')), ) tag = TagFilterField(model) @@ -323,10 +323,10 @@ class VirtualCircuitTypeFilterForm(NetBoxModelFilterSetForm): ) -class VirtualCircuitFilterForm(TenancyFilterForm, ContactModelFilterForm, NetBoxModelFilterSetForm): +class VirtualCircuitFilterForm(TenancyFilterForm, ContactModelFilterForm, PrimaryModelFilterSetForm): model = VirtualCircuit fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('provider_id', 'provider_account_id', 'provider_network_id', name=_('Provider')), FieldSet('type_id', 'status', name=_('Attributes')), FieldSet('tenant_group_id', 'tenant_id', name=_('Tenant')), diff --git a/netbox/circuits/forms/model_forms.py b/netbox/circuits/forms/model_forms.py index ce09862ae..906fe8952 100644 --- a/netbox/circuits/forms/model_forms.py +++ b/netbox/circuits/forms/model_forms.py @@ -10,11 +10,11 @@ from circuits.constants import * from circuits.models import * from dcim.models import Interface, Site from ipam.models import ASN -from netbox.forms import NetBoxModelForm +from netbox.forms import NetBoxModelForm, OrganizationalModelForm, PrimaryModelForm from tenancy.forms import TenancyForm from utilities.forms import get_field_value from utilities.forms.fields import ( - CommentField, ContentTypeChoiceField, DynamicModelChoiceField, DynamicModelMultipleChoiceField, SlugField, + ContentTypeChoiceField, DynamicModelChoiceField, DynamicModelMultipleChoiceField, SlugField, ) from utilities.forms.mixins import DistanceValidationMixin from utilities.forms.rendering import FieldSet, InlineFields @@ -36,14 +36,13 @@ __all__ = ( ) -class ProviderForm(NetBoxModelForm): +class ProviderForm(PrimaryModelForm): slug = SlugField() asns = DynamicModelMultipleChoiceField( queryset=ASN.objects.all(), label=_('ASNs'), required=False ) - comments = CommentField() fieldsets = ( FieldSet('name', 'slug', 'asns', 'description', 'tags'), @@ -52,34 +51,32 @@ class ProviderForm(NetBoxModelForm): class Meta: model = Provider fields = [ - 'name', 'slug', 'asns', 'description', 'comments', 'tags', + 'name', 'slug', 'asns', 'description', 'owner', 'comments', 'tags', ] -class ProviderAccountForm(NetBoxModelForm): +class ProviderAccountForm(PrimaryModelForm): provider = DynamicModelChoiceField( label=_('Provider'), queryset=Provider.objects.all(), selector=True, quick_add=True ) - comments = CommentField() class Meta: model = ProviderAccount fields = [ - 'provider', 'name', 'account', 'description', 'comments', 'tags', + 'provider', 'name', 'account', 'description', 'owner', 'comments', 'tags', ] -class ProviderNetworkForm(NetBoxModelForm): +class ProviderNetworkForm(PrimaryModelForm): provider = DynamicModelChoiceField( label=_('Provider'), queryset=Provider.objects.all(), selector=True, quick_add=True ) - comments = CommentField() fieldsets = ( FieldSet('provider', 'name', 'service_id', 'description', 'tags'), @@ -88,25 +85,23 @@ class ProviderNetworkForm(NetBoxModelForm): class Meta: model = ProviderNetwork fields = [ - 'provider', 'name', 'service_id', 'description', 'comments', 'tags', + 'provider', 'name', 'service_id', 'description', 'owner', 'comments', 'tags', ] -class CircuitTypeForm(NetBoxModelForm): - slug = SlugField() - +class CircuitTypeForm(OrganizationalModelForm): fieldsets = ( - FieldSet('name', 'slug', 'color', 'description', 'tags'), + FieldSet('name', 'slug', 'color', 'description', 'owner', 'tags'), ) class Meta: model = CircuitType fields = [ - 'name', 'slug', 'color', 'description', 'tags', + 'name', 'slug', 'color', 'description', 'comments', 'tags', ] -class CircuitForm(DistanceValidationMixin, TenancyForm, NetBoxModelForm): +class CircuitForm(DistanceValidationMixin, TenancyForm, PrimaryModelForm): provider = DynamicModelChoiceField( label=_('Provider'), queryset=Provider.objects.all(), @@ -125,7 +120,6 @@ class CircuitForm(DistanceValidationMixin, TenancyForm, NetBoxModelForm): queryset=CircuitType.objects.all(), quick_add=True ) - comments = CommentField() fieldsets = ( FieldSet( @@ -147,7 +141,7 @@ class CircuitForm(DistanceValidationMixin, TenancyForm, NetBoxModelForm): model = Circuit fields = [ 'cid', 'type', 'provider', 'provider_account', 'status', 'install_date', 'termination_date', 'commit_rate', - 'distance', 'distance_unit', 'description', 'tenant_group', 'tenant', 'comments', 'tags', + 'distance', 'distance_unit', 'description', 'tenant_group', 'tenant', 'owner', 'comments', 'tags', ] widgets = { 'install_date': DatePicker(), @@ -233,9 +227,7 @@ class CircuitTerminationForm(NetBoxModelForm): self.instance.termination = self.cleaned_data.get('termination') -class CircuitGroupForm(TenancyForm, NetBoxModelForm): - slug = SlugField() - +class CircuitGroupForm(TenancyForm, OrganizationalModelForm): fieldsets = ( FieldSet('name', 'slug', 'description', 'tags', name=_('Circuit Group')), FieldSet('tenant_group', 'tenant', name=_('Tenancy')), @@ -244,7 +236,7 @@ class CircuitGroupForm(TenancyForm, NetBoxModelForm): class Meta: model = CircuitGroup fields = [ - 'name', 'slug', 'description', 'tenant_group', 'tenant', 'tags', + 'name', 'slug', 'description', 'tenant_group', 'tenant', 'owner', 'comments', 'tags', ] @@ -307,9 +299,7 @@ class CircuitGroupAssignmentForm(NetBoxModelForm): self.instance.member = self.cleaned_data.get('member') -class VirtualCircuitTypeForm(NetBoxModelForm): - slug = SlugField() - +class VirtualCircuitTypeForm(OrganizationalModelForm): fieldsets = ( FieldSet('name', 'slug', 'color', 'description', 'tags'), ) @@ -317,11 +307,11 @@ class VirtualCircuitTypeForm(NetBoxModelForm): class Meta: model = VirtualCircuitType fields = [ - 'name', 'slug', 'color', 'description', 'tags', + 'name', 'slug', 'color', 'description', 'owner', 'comments', 'tags', ] -class VirtualCircuitForm(TenancyForm, NetBoxModelForm): +class VirtualCircuitForm(TenancyForm, PrimaryModelForm): provider_network = DynamicModelChoiceField( label=_('Provider network'), queryset=ProviderNetwork.objects.all(), @@ -336,7 +326,6 @@ class VirtualCircuitForm(TenancyForm, NetBoxModelForm): queryset=VirtualCircuitType.objects.all(), quick_add=True ) - comments = CommentField() fieldsets = ( FieldSet( @@ -350,7 +339,7 @@ class VirtualCircuitForm(TenancyForm, NetBoxModelForm): model = VirtualCircuit fields = [ 'cid', 'provider_network', 'provider_account', 'type', 'status', 'description', 'tenant_group', 'tenant', - 'comments', 'tags', + 'owner', 'comments', 'tags', ] diff --git a/netbox/circuits/graphql/filter_mixins.py b/netbox/circuits/graphql/filter_mixins.py index 3ae6fa82e..f7795f10a 100644 --- a/netbox/circuits/graphql/filter_mixins.py +++ b/netbox/circuits/graphql/filter_mixins.py @@ -3,17 +3,18 @@ from typing import Annotated, TYPE_CHECKING import strawberry import strawberry_django - -from netbox.graphql.filter_mixins import OrganizationalModelFilterMixin +from strawberry_django import BaseFilterLookup if TYPE_CHECKING: from netbox.graphql.enums import ColorEnum __all__ = ( - 'BaseCircuitTypeFilterMixin', + 'CircuitTypeFilterMixin', ) @dataclass -class BaseCircuitTypeFilterMixin(OrganizationalModelFilterMixin): - color: Annotated['ColorEnum', strawberry.lazy('netbox.graphql.enums')] | None = strawberry_django.filter_field() +class CircuitTypeFilterMixin: + color: BaseFilterLookup[Annotated['ColorEnum', strawberry.lazy('netbox.graphql.enums')]] | None = ( + strawberry_django.filter_field() + ) diff --git a/netbox/circuits/graphql/filters.py b/netbox/circuits/graphql/filters.py index d6ef2976d..160dd9c2b 100644 --- a/netbox/circuits/graphql/filters.py +++ b/netbox/circuits/graphql/filters.py @@ -4,20 +4,15 @@ from typing import Annotated, TYPE_CHECKING import strawberry import strawberry_django from strawberry.scalars import ID -from strawberry_django import FilterLookup, DateFilterLookup +from strawberry_django import BaseFilterLookup, FilterLookup, DateFilterLookup from circuits import models -from core.graphql.filter_mixins import BaseObjectTypeFilterMixin, ChangeLogFilterMixin +from circuits.graphql.filter_mixins import CircuitTypeFilterMixin from dcim.graphql.filter_mixins import CabledObjectModelFilterMixin from extras.graphql.filter_mixins import CustomFieldsFilterMixin, TagsFilterMixin -from netbox.graphql.filter_mixins import ( - DistanceFilterMixin, - ImageAttachmentFilterMixin, - OrganizationalModelFilterMixin, - PrimaryModelFilterMixin, -) +from netbox.graphql.filter_mixins import DistanceFilterMixin, ImageAttachmentFilterMixin +from netbox.graphql.filters import ChangeLoggedModelFilter, OrganizationalModelFilter, PrimaryModelFilter from tenancy.graphql.filter_mixins import ContactFilterMixin, TenancyFilterMixin -from .filter_mixins import BaseCircuitTypeFilterMixin if TYPE_CHECKING: from core.graphql.filters import ContentTypeFilter @@ -43,16 +38,17 @@ __all__ = ( @strawberry_django.filter_type(models.CircuitTermination, lookups=True) class CircuitTerminationFilter( - BaseObjectTypeFilterMixin, CustomFieldsFilterMixin, TagsFilterMixin, - ChangeLogFilterMixin, + ChangeLoggedModelFilter, CabledObjectModelFilterMixin, ): circuit: Annotated['CircuitFilter', strawberry.lazy('circuits.graphql.filters')] | None = ( strawberry_django.filter_field() ) - term_side: Annotated['CircuitTerminationSideEnum', strawberry.lazy('circuits.graphql.enums')] | None = ( + term_side: ( + BaseFilterLookup[Annotated['CircuitTerminationSideEnum', strawberry.lazy('circuits.graphql.enums')]] | None + ) = ( strawberry_django.filter_field() ) termination_type: Annotated['ContentTypeFilter', strawberry.lazy('core.graphql.filters')] | None = ( @@ -93,7 +89,7 @@ class CircuitFilter( ImageAttachmentFilterMixin, DistanceFilterMixin, TenancyFilterMixin, - PrimaryModelFilterMixin + PrimaryModelFilter ): cid: FilterLookup[str] | None = strawberry_django.filter_field() provider: Annotated['ProviderFilter', strawberry.lazy('circuits.graphql.filters')] | None = ( @@ -108,7 +104,7 @@ class CircuitFilter( strawberry_django.filter_field() ) type_id: ID | None = strawberry_django.filter_field() - status: Annotated['CircuitStatusEnum', strawberry.lazy('circuits.graphql.enums')] | None = ( + status: BaseFilterLookup[Annotated['CircuitStatusEnum', strawberry.lazy('circuits.graphql.enums')]] | None = ( strawberry_django.filter_field() ) install_date: DateFilterLookup[date] | None = strawberry_django.filter_field() @@ -122,19 +118,17 @@ class CircuitFilter( @strawberry_django.filter_type(models.CircuitType, lookups=True) -class CircuitTypeFilter(BaseCircuitTypeFilterMixin): +class CircuitTypeFilter(CircuitTypeFilterMixin, OrganizationalModelFilter): pass @strawberry_django.filter_type(models.CircuitGroup, lookups=True) -class CircuitGroupFilter(TenancyFilterMixin, OrganizationalModelFilterMixin): +class CircuitGroupFilter(TenancyFilterMixin, OrganizationalModelFilter): pass @strawberry_django.filter_type(models.CircuitGroupAssignment, lookups=True) -class CircuitGroupAssignmentFilter( - BaseObjectTypeFilterMixin, CustomFieldsFilterMixin, TagsFilterMixin, ChangeLogFilterMixin -): +class CircuitGroupAssignmentFilter(CustomFieldsFilterMixin, TagsFilterMixin, ChangeLoggedModelFilter): member_type: Annotated['ContentTypeFilter', strawberry.lazy('core.graphql.filters')] | None = ( strawberry_django.filter_field() ) @@ -143,13 +137,13 @@ class CircuitGroupAssignmentFilter( strawberry_django.filter_field() ) group_id: ID | None = strawberry_django.filter_field() - priority: Annotated['CircuitPriorityEnum', strawberry.lazy('circuits.graphql.enums')] | None = ( + priority: BaseFilterLookup[Annotated['CircuitPriorityEnum', strawberry.lazy('circuits.graphql.enums')]] | None = ( strawberry_django.filter_field() ) @strawberry_django.filter_type(models.Provider, lookups=True) -class ProviderFilter(ContactFilterMixin, PrimaryModelFilterMixin): +class ProviderFilter(ContactFilterMixin, PrimaryModelFilter): name: FilterLookup[str] | None = strawberry_django.filter_field() slug: FilterLookup[str] | None = strawberry_django.filter_field() asns: Annotated['ASNFilter', strawberry.lazy('ipam.graphql.filters')] | None = strawberry_django.filter_field() @@ -159,7 +153,7 @@ class ProviderFilter(ContactFilterMixin, PrimaryModelFilterMixin): @strawberry_django.filter_type(models.ProviderAccount, lookups=True) -class ProviderAccountFilter(ContactFilterMixin, PrimaryModelFilterMixin): +class ProviderAccountFilter(ContactFilterMixin, PrimaryModelFilter): provider: Annotated['ProviderFilter', strawberry.lazy('circuits.graphql.filters')] | None = ( strawberry_django.filter_field() ) @@ -169,7 +163,7 @@ class ProviderAccountFilter(ContactFilterMixin, PrimaryModelFilterMixin): @strawberry_django.filter_type(models.ProviderNetwork, lookups=True) -class ProviderNetworkFilter(PrimaryModelFilterMixin): +class ProviderNetworkFilter(PrimaryModelFilter): name: FilterLookup[str] | None = strawberry_django.filter_field() provider: Annotated['ProviderFilter', strawberry.lazy('circuits.graphql.filters')] | None = ( strawberry_django.filter_field() @@ -179,12 +173,12 @@ class ProviderNetworkFilter(PrimaryModelFilterMixin): @strawberry_django.filter_type(models.VirtualCircuitType, lookups=True) -class VirtualCircuitTypeFilter(BaseCircuitTypeFilterMixin): +class VirtualCircuitTypeFilter(CircuitTypeFilterMixin, OrganizationalModelFilter): pass @strawberry_django.filter_type(models.VirtualCircuit, lookups=True) -class VirtualCircuitFilter(TenancyFilterMixin, PrimaryModelFilterMixin): +class VirtualCircuitFilter(TenancyFilterMixin, PrimaryModelFilter): cid: FilterLookup[str] | None = strawberry_django.filter_field() provider_network: Annotated['ProviderNetworkFilter', strawberry.lazy('circuits.graphql.filters')] | None = ( strawberry_django.filter_field() @@ -198,7 +192,7 @@ class VirtualCircuitFilter(TenancyFilterMixin, PrimaryModelFilterMixin): strawberry_django.filter_field() ) type_id: ID | None = strawberry_django.filter_field() - status: Annotated['CircuitStatusEnum', strawberry.lazy('circuits.graphql.enums')] | None = ( + status: BaseFilterLookup[Annotated['CircuitStatusEnum', strawberry.lazy('circuits.graphql.enums')]] | None = ( strawberry_django.filter_field() ) group_assignments: Annotated['CircuitGroupAssignmentFilter', strawberry.lazy('circuits.graphql.filters')] | None = ( @@ -207,14 +201,16 @@ class VirtualCircuitFilter(TenancyFilterMixin, PrimaryModelFilterMixin): @strawberry_django.filter_type(models.VirtualCircuitTermination, lookups=True) -class VirtualCircuitTerminationFilter( - BaseObjectTypeFilterMixin, CustomFieldsFilterMixin, TagsFilterMixin, ChangeLogFilterMixin -): +class VirtualCircuitTerminationFilter(CustomFieldsFilterMixin, TagsFilterMixin, ChangeLoggedModelFilter): virtual_circuit: Annotated['VirtualCircuitFilter', strawberry.lazy('circuits.graphql.filters')] | None = ( strawberry_django.filter_field() ) virtual_circuit_id: ID | None = strawberry_django.filter_field() - role: Annotated['VirtualCircuitTerminationRoleEnum', strawberry.lazy('circuits.graphql.enums')] | None = ( + role: ( + BaseFilterLookup[ + Annotated['VirtualCircuitTerminationRoleEnum', strawberry.lazy('circuits.graphql.enums')] + ] | None + ) = ( strawberry_django.filter_field() ) interface: Annotated['InterfaceFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( diff --git a/netbox/circuits/graphql/types.py b/netbox/circuits/graphql/types.py index 89d2a33b6..8592e929d 100644 --- a/netbox/circuits/graphql/types.py +++ b/netbox/circuits/graphql/types.py @@ -6,7 +6,7 @@ import strawberry_django from circuits import models from dcim.graphql.mixins import CabledObjectMixin from extras.graphql.mixins import ContactsMixin, CustomFieldsMixin, TagsMixin -from netbox.graphql.types import BaseObjectType, NetBoxObjectType, ObjectType, OrganizationalObjectType +from netbox.graphql.types import BaseObjectType, ObjectType, OrganizationalObjectType, PrimaryObjectType from tenancy.graphql.types import TenantType from .filters import * @@ -35,8 +35,7 @@ __all__ = ( filters=ProviderFilter, pagination=True ) -class ProviderType(NetBoxObjectType, ContactsMixin): - +class ProviderType(ContactsMixin, PrimaryObjectType): networks: List[Annotated["ProviderNetworkType", strawberry.lazy('circuits.graphql.types')]] circuits: List[Annotated["CircuitType", strawberry.lazy('circuits.graphql.types')]] asns: List[Annotated["ASNType", strawberry.lazy('ipam.graphql.types')]] @@ -49,9 +48,8 @@ class ProviderType(NetBoxObjectType, ContactsMixin): filters=ProviderAccountFilter, pagination=True ) -class ProviderAccountType(ContactsMixin, NetBoxObjectType): +class ProviderAccountType(ContactsMixin, PrimaryObjectType): provider: Annotated["ProviderType", strawberry.lazy('circuits.graphql.types')] - circuits: List[Annotated["CircuitType", strawberry.lazy('circuits.graphql.types')]] @@ -61,9 +59,8 @@ class ProviderAccountType(ContactsMixin, NetBoxObjectType): filters=ProviderNetworkFilter, pagination=True ) -class ProviderNetworkType(NetBoxObjectType): +class ProviderNetworkType(PrimaryObjectType): provider: Annotated["ProviderType", strawberry.lazy('circuits.graphql.types')] - circuit_terminations: List[Annotated["CircuitTerminationType", strawberry.lazy('circuits.graphql.types')]] @@ -105,14 +102,13 @@ class CircuitTypeType(OrganizationalObjectType): filters=CircuitFilter, pagination=True ) -class CircuitType(NetBoxObjectType, ContactsMixin): +class CircuitType(PrimaryObjectType, ContactsMixin): provider: ProviderType provider_account: ProviderAccountType | None termination_a: CircuitTerminationType | None termination_z: CircuitTerminationType | None type: CircuitTypeType tenant: TenantType | None - terminations: List[CircuitTerminationType] @@ -178,12 +174,11 @@ class VirtualCircuitTerminationType(CustomFieldsMixin, TagsMixin, ObjectType): filters=VirtualCircuitFilter, pagination=True ) -class VirtualCircuitType(NetBoxObjectType): +class VirtualCircuitType(PrimaryObjectType): provider_network: ProviderNetworkType = strawberry_django.field(select_related=["provider_network"]) provider_account: ProviderAccountType | None type: Annotated["VirtualCircuitTypeType", strawberry.lazy('circuits.graphql.types')] = strawberry_django.field( select_related=["type"] ) tenant: TenantType | None - terminations: List[VirtualCircuitTerminationType] diff --git a/netbox/circuits/migrations/0053_owner.py b/netbox/circuits/migrations/0053_owner.py new file mode 100644 index 000000000..04056bfce --- /dev/null +++ b/netbox/circuits/migrations/0053_owner.py @@ -0,0 +1,68 @@ +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ('circuits', '0052_extend_circuit_abs_distance_upper_limit'), + ('users', '0015_owner'), + ] + + operations = [ + migrations.AddField( + model_name='circuit', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='circuitgroup', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='circuittype', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='provider', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='provideraccount', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='providernetwork', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='virtualcircuit', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='virtualcircuittype', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + ] diff --git a/netbox/circuits/migrations/0054_cable_connector_positions.py b/netbox/circuits/migrations/0054_cable_connector_positions.py new file mode 100644 index 000000000..12e0e2fbf --- /dev/null +++ b/netbox/circuits/migrations/0054_cable_connector_positions.py @@ -0,0 +1,39 @@ +import django.contrib.postgres.fields +import django.core.validators +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ('circuits', '0053_owner'), + ] + + operations = [ + migrations.AddField( + model_name='circuittermination', + name='cable_connector', + field=models.PositiveSmallIntegerField( + blank=True, + null=True, + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(256) + ], + ), + ), + migrations.AddField( + model_name='circuittermination', + name='cable_positions', + field=django.contrib.postgres.fields.ArrayField( + base_field=models.PositiveSmallIntegerField( + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(1024), + ] + ), + blank=True, + null=True, + size=None, + ), + ), + ] diff --git a/netbox/circuits/migrations/0055_add_comments_to_organizationalmodel.py b/netbox/circuits/migrations/0055_add_comments_to_organizationalmodel.py new file mode 100644 index 000000000..83574b03b --- /dev/null +++ b/netbox/circuits/migrations/0055_add_comments_to_organizationalmodel.py @@ -0,0 +1,28 @@ +# Generated by Django 5.2.8 on 2025-12-08 17:38 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('circuits', '0054_cable_connector_positions'), + ] + + operations = [ + migrations.AddField( + model_name='circuitgroup', + name='comments', + field=models.TextField(blank=True), + ), + migrations.AddField( + model_name='circuittype', + name='comments', + field=models.TextField(blank=True), + ), + migrations.AddField( + model_name='virtualcircuittype', + name='comments', + field=models.TextField(blank=True), + ), + ] diff --git a/netbox/circuits/migrations/0056_gfk_indexes.py b/netbox/circuits/migrations/0056_gfk_indexes.py new file mode 100644 index 000000000..7652139df --- /dev/null +++ b/netbox/circuits/migrations/0056_gfk_indexes.py @@ -0,0 +1,17 @@ +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ('circuits', '0055_add_comments_to_organizationalmodel'), + ('contenttypes', '0002_remove_content_type_name'), + ('dcim', '0224_add_comments_to_organizationalmodel'), + ('extras', '0134_owner'), + ] + + operations = [ + migrations.AddIndex( + model_name='circuittermination', + index=models.Index(fields=['termination_type', 'termination_id'], name='circuits_ci_termina_505dda_idx'), + ), + ] diff --git a/netbox/circuits/models/circuits.py b/netbox/circuits/models/circuits.py index 643aac3bd..7e8ac4509 100644 --- a/netbox/circuits/models/circuits.py +++ b/netbox/circuits/models/circuits.py @@ -335,6 +335,9 @@ class CircuitTermination( name='%(app_label)s_%(class)s_unique_circuit_term_side' ), ) + indexes = ( + models.Index(fields=('termination_type', 'termination_id')), + ) verbose_name = _('circuit termination') verbose_name_plural = _('circuit terminations') diff --git a/netbox/circuits/search.py b/netbox/circuits/search.py index f7654e328..6c25d3a9c 100644 --- a/netbox/circuits/search.py +++ b/netbox/circuits/search.py @@ -20,6 +20,7 @@ class CircuitGroupIndex(SearchIndex): ('name', 100), ('slug', 110), ('description', 500), + ('comments', 5000), ) display_attrs = ('description',) @@ -44,6 +45,7 @@ class CircuitTypeIndex(SearchIndex): ('name', 100), ('slug', 110), ('description', 500), + ('comments', 5000), ) display_attrs = ('description',) @@ -109,5 +111,6 @@ class VirtualCircuitTypeIndex(SearchIndex): ('name', 100), ('slug', 110), ('description', 500), + ('comments', 5000), ) display_attrs = ('description',) diff --git a/netbox/circuits/tables/circuits.py b/netbox/circuits/tables/circuits.py index 901893a77..ae4e2c8bd 100644 --- a/netbox/circuits/tables/circuits.py +++ b/netbox/circuits/tables/circuits.py @@ -1,11 +1,9 @@ -from django.utils.translation import gettext_lazy as _ import django_tables2 as tables +from django.utils.translation import gettext_lazy as _ from circuits.models import * +from netbox.tables import NetBoxTable, OrganizationalModelTable, PrimaryModelTable, columns from tenancy.tables import ContactsColumnMixin, TenancyColumnsMixin - -from netbox.tables import NetBoxTable, columns - from .columns import CommitRateColumn __all__ = ( @@ -24,7 +22,7 @@ CIRCUITTERMINATION_LINK = """ """ -class CircuitTypeTable(NetBoxTable): +class CircuitTypeTable(OrganizationalModelTable): name = tables.Column( linkify=True, verbose_name=_('Name'), @@ -39,16 +37,16 @@ class CircuitTypeTable(NetBoxTable): verbose_name=_('Circuits') ) - class Meta(NetBoxTable.Meta): + class Meta(OrganizationalModelTable.Meta): model = CircuitType fields = ( - 'pk', 'id', 'name', 'circuit_count', 'color', 'description', 'slug', 'tags', 'created', 'last_updated', - 'actions', + 'pk', 'id', 'name', 'circuit_count', 'color', 'description', 'slug', 'comments', 'tags', 'created', + 'last_updated', 'actions', ) default_columns = ('pk', 'name', 'circuit_count', 'color', 'description') -class CircuitTable(TenancyColumnsMixin, ContactsColumnMixin, NetBoxTable): +class CircuitTable(TenancyColumnsMixin, ContactsColumnMixin, PrimaryModelTable): cid = tables.Column( linkify=True, verbose_name=_('Circuit ID') @@ -79,9 +77,6 @@ class CircuitTable(TenancyColumnsMixin, ContactsColumnMixin, NetBoxTable): verbose_name=_('Commit Rate') ) distance = columns.DistanceColumn() - comments = columns.MarkdownColumn( - verbose_name=_('Comments') - ) tags = columns.TagColumn( url_name='circuits:circuit_list' ) @@ -90,7 +85,7 @@ class CircuitTable(TenancyColumnsMixin, ContactsColumnMixin, NetBoxTable): linkify_item=True ) - class Meta(NetBoxTable.Meta): + class Meta(PrimaryModelTable.Meta): model = Circuit fields = ( 'pk', 'id', 'cid', 'provider', 'provider_account', 'type', 'status', 'tenant', 'tenant_group', @@ -163,7 +158,7 @@ class CircuitTerminationTable(NetBoxTable): ) -class CircuitGroupTable(NetBoxTable): +class CircuitGroupTable(OrganizationalModelTable): name = tables.Column( verbose_name=_('Name'), linkify=True @@ -177,10 +172,10 @@ class CircuitGroupTable(NetBoxTable): url_name='circuits:circuitgroup_list' ) - class Meta(NetBoxTable.Meta): + class Meta(OrganizationalModelTable.Meta): model = CircuitGroup fields = ( - 'pk', 'name', 'description', 'circuit_group_assignment_count', 'tags', + 'pk', 'name', 'description', 'circuit_group_assignment_count', 'comments', 'tags', 'created', 'last_updated', 'actions', ) default_columns = ('pk', 'name', 'description', 'circuit_group_assignment_count') diff --git a/netbox/circuits/tables/providers.py b/netbox/circuits/tables/providers.py index 54a5c2cc9..4fbdff8c7 100644 --- a/netbox/circuits/tables/providers.py +++ b/netbox/circuits/tables/providers.py @@ -1,10 +1,10 @@ import django_tables2 as tables from django.utils.translation import gettext_lazy as _ -from circuits.models import * from django_tables2.utils import Accessor -from tenancy.tables import ContactsColumnMixin -from netbox.tables import NetBoxTable, columns +from circuits.models import * +from netbox.tables import PrimaryModelTable, columns +from tenancy.tables import ContactsColumnMixin __all__ = ( 'ProviderTable', @@ -13,7 +13,7 @@ __all__ = ( ) -class ProviderTable(ContactsColumnMixin, NetBoxTable): +class ProviderTable(ContactsColumnMixin, PrimaryModelTable): name = tables.Column( verbose_name=_('Name'), linkify=True @@ -42,14 +42,11 @@ class ProviderTable(ContactsColumnMixin, NetBoxTable): url_params={'provider_id': 'pk'}, verbose_name=_('Circuits') ) - comments = columns.MarkdownColumn( - verbose_name=_('Comments'), - ) tags = columns.TagColumn( url_name='circuits:provider_list' ) - class Meta(NetBoxTable.Meta): + class Meta(PrimaryModelTable.Meta): model = Provider fields = ( 'pk', 'id', 'name', 'accounts', 'account_count', 'asns', 'asn_count', 'circuit_count', 'description', @@ -58,7 +55,7 @@ class ProviderTable(ContactsColumnMixin, NetBoxTable): default_columns = ('pk', 'name', 'account_count', 'circuit_count') -class ProviderAccountTable(ContactsColumnMixin, NetBoxTable): +class ProviderAccountTable(ContactsColumnMixin, PrimaryModelTable): account = tables.Column( linkify=True, verbose_name=_('Account'), @@ -76,14 +73,11 @@ class ProviderAccountTable(ContactsColumnMixin, NetBoxTable): url_params={'provider_account_id': 'pk'}, verbose_name=_('Circuits') ) - comments = columns.MarkdownColumn( - verbose_name=_('Comments'), - ) tags = columns.TagColumn( url_name='circuits:provideraccount_list' ) - class Meta(NetBoxTable.Meta): + class Meta(PrimaryModelTable.Meta): model = ProviderAccount fields = ( 'pk', 'id', 'account', 'name', 'provider', 'circuit_count', 'comments', 'contacts', 'tags', 'created', @@ -92,7 +86,7 @@ class ProviderAccountTable(ContactsColumnMixin, NetBoxTable): default_columns = ('pk', 'account', 'name', 'provider', 'circuit_count') -class ProviderNetworkTable(NetBoxTable): +class ProviderNetworkTable(PrimaryModelTable): name = tables.Column( verbose_name=_('Name'), linkify=True @@ -101,14 +95,11 @@ class ProviderNetworkTable(NetBoxTable): verbose_name=_('Provider'), linkify=True ) - comments = columns.MarkdownColumn( - verbose_name=_('Comments'), - ) tags = columns.TagColumn( url_name='circuits:providernetwork_list' ) - class Meta(NetBoxTable.Meta): + class Meta(PrimaryModelTable.Meta): model = ProviderNetwork fields = ( 'pk', 'id', 'name', 'provider', 'service_id', 'description', 'comments', 'created', 'last_updated', 'tags', diff --git a/netbox/circuits/tables/virtual_circuits.py b/netbox/circuits/tables/virtual_circuits.py index ea3b6dc13..c55dfd178 100644 --- a/netbox/circuits/tables/virtual_circuits.py +++ b/netbox/circuits/tables/virtual_circuits.py @@ -2,7 +2,7 @@ import django_tables2 as tables from django.utils.translation import gettext_lazy as _ from circuits.models import * -from netbox.tables import NetBoxTable, columns +from netbox.tables import NetBoxTable, OrganizationalModelTable, PrimaryModelTable, columns from tenancy.tables import ContactsColumnMixin, TenancyColumnsMixin __all__ = ( @@ -12,7 +12,7 @@ __all__ = ( ) -class VirtualCircuitTypeTable(NetBoxTable): +class VirtualCircuitTypeTable(OrganizationalModelTable): name = tables.Column( linkify=True, verbose_name=_('Name'), @@ -27,7 +27,7 @@ class VirtualCircuitTypeTable(NetBoxTable): verbose_name=_('Circuits') ) - class Meta(NetBoxTable.Meta): + class Meta(OrganizationalModelTable.Meta): model = VirtualCircuitType fields = ( 'pk', 'id', 'name', 'virtual_circuit_count', 'color', 'description', 'slug', 'tags', 'created', @@ -36,7 +36,7 @@ class VirtualCircuitTypeTable(NetBoxTable): default_columns = ('pk', 'name', 'virtual_circuit_count', 'color', 'description') -class VirtualCircuitTable(TenancyColumnsMixin, ContactsColumnMixin, NetBoxTable): +class VirtualCircuitTable(TenancyColumnsMixin, ContactsColumnMixin, PrimaryModelTable): cid = tables.Column( linkify=True, verbose_name=_('Circuit ID') @@ -63,14 +63,11 @@ class VirtualCircuitTable(TenancyColumnsMixin, ContactsColumnMixin, NetBoxTable) url_params={'virtual_circuit_id': 'pk'}, verbose_name=_('Terminations') ) - comments = columns.MarkdownColumn( - verbose_name=_('Comments') - ) tags = columns.TagColumn( url_name='circuits:virtualcircuit_list' ) - class Meta(NetBoxTable.Meta): + class Meta(PrimaryModelTable.Meta): model = VirtualCircuit fields = ( 'pk', 'id', 'cid', 'provider', 'provider_account', 'provider_network', 'type', 'status', 'tenant', diff --git a/netbox/circuits/tests/test_filtersets.py b/netbox/circuits/tests/test_filtersets.py index 91077ee64..6b6a93608 100644 --- a/netbox/circuits/tests/test_filtersets.py +++ b/netbox/circuits/tests/test_filtersets.py @@ -433,7 +433,7 @@ class CircuitTestCase(TestCase, ChangeLoggedFilterSetTests): class CircuitTerminationTestCase(TestCase, ChangeLoggedFilterSetTests): queryset = CircuitTermination.objects.all() filterset = CircuitTerminationFilterSet - ignore_fields = ('cable',) + ignore_fields = ('cable', 'cable_positions') @classmethod def setUpTestData(cls): diff --git a/netbox/circuits/urls.py b/netbox/circuits/urls.py index 594570638..c5f232852 100644 --- a/netbox/circuits/urls.py +++ b/netbox/circuits/urls.py @@ -18,11 +18,6 @@ urlpatterns = [ path('circuit-types//', include(get_model_urls('circuits', 'circuittype'))), path('circuits/', include(get_model_urls('circuits', 'circuit', detail=False))), - path( - 'circuits//terminations/swap/', - views.CircuitSwapTerminations.as_view(), - name='circuit_terminations_swap' - ), path('circuits//', include(get_model_urls('circuits', 'circuit'))), path('circuit-terminations/', include(get_model_urls('circuits', 'circuittermination', detail=False))), diff --git a/netbox/circuits/views.py b/netbox/circuits/views.py index eead0751f..a3266f460 100644 --- a/netbox/circuits/views.py +++ b/netbox/circuits/views.py @@ -1,13 +1,8 @@ -from django.contrib import messages -from django.db import router, transaction -from django.shortcuts import get_object_or_404, redirect, render -from django.utils.translation import gettext_lazy as _ from dcim.views import PathTraceView from ipam.models import ASN from netbox.object_actions import AddObject, BulkDelete, BulkEdit, BulkExport, BulkImport from netbox.views import generic -from utilities.forms import ConfirmationForm from utilities.query import count_related from utilities.views import GetRelatedModelsMixin, register_model_view from . import filtersets, forms, tables @@ -378,82 +373,6 @@ class CircuitBulkDeleteView(generic.BulkDeleteView): table = tables.CircuitTable -class CircuitSwapTerminations(generic.ObjectEditView): - """ - Swap the A and Z terminations of a circuit. - """ - queryset = Circuit.objects.all() - - def get(self, request, pk): - circuit = get_object_or_404(self.queryset, pk=pk) - form = ConfirmationForm() - - # Circuit must have at least one termination to swap - if not circuit.termination_a and not circuit.termination_z: - messages.error(request, _( - "No terminations have been defined for circuit {circuit}." - ).format(circuit=circuit)) - return redirect('circuits:circuit', pk=circuit.pk) - - return render(request, 'circuits/circuit_terminations_swap.html', { - 'circuit': circuit, - 'termination_a': circuit.termination_a, - 'termination_z': circuit.termination_z, - 'form': form, - 'panel_class': 'light', - 'button_class': 'primary', - 'return_url': circuit.get_absolute_url(), - }) - - def post(self, request, pk): - circuit = get_object_or_404(self.queryset, pk=pk) - form = ConfirmationForm(request.POST) - - if form.is_valid(): - - termination_a = CircuitTermination.objects.filter(pk=circuit.termination_a_id).first() - termination_z = CircuitTermination.objects.filter(pk=circuit.termination_z_id).first() - - if termination_a and termination_z: - # Use a placeholder to avoid an IntegrityError on the (circuit, term_side) unique constraint - with transaction.atomic(using=router.db_for_write(CircuitTermination)): - termination_a.term_side = '_' - termination_a.save() - termination_z.term_side = 'A' - termination_z.save() - termination_a.term_side = 'Z' - termination_a.save() - circuit.refresh_from_db() - circuit.termination_a = termination_z - circuit.termination_z = termination_a - circuit.save() - elif termination_a: - termination_a.term_side = 'Z' - termination_a.save() - circuit.refresh_from_db() - circuit.termination_a = None - circuit.save() - else: - termination_z.term_side = 'A' - termination_z.save() - circuit.refresh_from_db() - circuit.termination_z = None - circuit.save() - - messages.success(request, _("Swapped terminations for circuit {circuit}.").format(circuit=circuit)) - return redirect('circuits:circuit', pk=circuit.pk) - - return render(request, 'circuits/circuit_terminations_swap.html', { - 'circuit': circuit, - 'termination_a': circuit.termination_a, - 'termination_z': circuit.termination_z, - 'form': form, - 'panel_class': 'default', - 'button_class': 'primary', - 'return_url': circuit.get_absolute_url(), - }) - - # # Circuit terminations # diff --git a/netbox/core/api/serializers_/change_logging.py b/netbox/core/api/serializers_/change_logging.py index 575a849d5..4431b6298 100644 --- a/netbox/core/api/serializers_/change_logging.py +++ b/netbox/core/api/serializers_/change_logging.py @@ -1,13 +1,11 @@ -from drf_spectacular.utils import extend_schema_field from rest_framework import serializers from core.choices import * from core.models import ObjectChange -from netbox.api.exceptions import SerializerNotFound from netbox.api.fields import ChoiceField, ContentTypeField +from netbox.api.gfk_fields import GFKSerializerField from netbox.api.serializers import BaseModelSerializer from users.api.serializers_.users import UserSerializer -from utilities.api import get_serializer_for_model __all__ = ( 'ObjectChangeSerializer', @@ -26,7 +24,10 @@ class ObjectChangeSerializer(BaseModelSerializer): changed_object_type = ContentTypeField( read_only=True ) - changed_object = serializers.SerializerMethodField( + changed_object = GFKSerializerField( + read_only=True + ) + object_repr = serializers.CharField( read_only=True ) prechange_data = serializers.JSONField( @@ -44,22 +45,6 @@ class ObjectChangeSerializer(BaseModelSerializer): model = ObjectChange fields = [ 'id', 'url', 'display_url', 'display', 'time', 'user', 'user_name', 'request_id', 'action', - 'changed_object_type', 'changed_object_id', 'changed_object', 'message', 'prechange_data', - 'postchange_data', + 'changed_object_type', 'changed_object_id', 'changed_object', 'object_repr', 'message', + 'prechange_data', 'postchange_data', ] - - @extend_schema_field(serializers.JSONField(allow_null=True)) - def get_changed_object(self, obj): - """ - Serialize a nested representation of the changed object. - """ - if obj.changed_object is None: - return None - - try: - serializer = get_serializer_for_model(obj.changed_object) - except SerializerNotFound: - return obj.object_repr - data = serializer(obj.changed_object, nested=True, context={'request': self.context['request']}).data - - return data diff --git a/netbox/core/api/serializers_/data.py b/netbox/core/api/serializers_/data.py index 3f2ddb2a0..3130b7472 100644 --- a/netbox/core/api/serializers_/data.py +++ b/netbox/core/api/serializers_/data.py @@ -1,7 +1,7 @@ from core.choices import * from core.models import DataFile, DataSource from netbox.api.fields import ChoiceField, RelatedObjectCountField -from netbox.api.serializers import NetBoxModelSerializer +from netbox.api.serializers import NetBoxModelSerializer, PrimaryModelSerializer from netbox.utils import get_data_backend_choices __all__ = ( @@ -10,7 +10,7 @@ __all__ = ( ) -class DataSourceSerializer(NetBoxModelSerializer): +class DataSourceSerializer(PrimaryModelSerializer): type = ChoiceField( choices=get_data_backend_choices() ) @@ -26,8 +26,8 @@ class DataSourceSerializer(NetBoxModelSerializer): model = DataSource fields = [ 'id', 'url', 'display_url', 'display', 'name', 'type', 'source_url', 'enabled', 'status', 'description', - 'sync_interval', 'parameters', 'ignore_rules', 'comments', 'custom_fields', 'created', 'last_updated', - 'last_synced', 'file_count', + 'sync_interval', 'parameters', 'ignore_rules', 'owner', 'comments', 'custom_fields', 'created', + 'last_updated', 'last_synced', 'file_count', ] brief_fields = ('id', 'url', 'display', 'name', 'description') diff --git a/netbox/core/api/views.py b/netbox/core/api/views.py index 3d3462b7b..e4b6ea171 100644 --- a/netbox/core/api/views.py +++ b/netbox/core/api/views.py @@ -9,7 +9,6 @@ from drf_spectacular.utils import OpenApiParameter, extend_schema from rest_framework import viewsets from rest_framework.decorators import action from rest_framework.exceptions import PermissionDenied -from rest_framework.permissions import IsAdminUser from rest_framework.response import Response from rest_framework.routers import APIRootView from rest_framework.viewsets import ReadOnlyModelViewSet @@ -24,7 +23,7 @@ from netbox.api.authentication import IsAuthenticatedOrLoginNotRequired from netbox.api.metadata import ContentTypeMetadata from netbox.api.pagination import LimitOffsetListPagination from netbox.api.viewsets import NetBoxModelViewSet, NetBoxReadOnlyModelViewSet - +from utilities.api import IsSuperuser from . import serializers @@ -100,7 +99,7 @@ class BaseRQViewSet(viewsets.ViewSet): """ Base class for RQ view sets. Provides a list() method. Subclasses must implement get_data(). """ - permission_classes = [IsAdminUser] + permission_classes = [IsSuperuser] serializer_class = None def get_data(self): diff --git a/netbox/core/filtersets.py b/netbox/core/filtersets.py index 2454e0b86..a531c051e 100644 --- a/netbox/core/filtersets.py +++ b/netbox/core/filtersets.py @@ -3,10 +3,11 @@ from django.contrib.contenttypes.models import ContentType from django.db.models import Q from django.utils.translation import gettext as _ -from netbox.filtersets import BaseFilterSet, ChangeLoggedModelFilterSet, NetBoxModelFilterSet +from netbox.filtersets import BaseFilterSet, ChangeLoggedModelFilterSet, PrimaryModelFilterSet from netbox.utils import get_data_backend_choices from users.models import User from utilities.filters import ContentTypeFilter +from utilities.filtersets import register_filterset from .choices import * from .models import * @@ -20,7 +21,8 @@ __all__ = ( ) -class DataSourceFilterSet(NetBoxModelFilterSet): +@register_filterset +class DataSourceFilterSet(PrimaryModelFilterSet): type = django_filters.MultipleChoiceFilter( choices=get_data_backend_choices, null_value=None @@ -48,6 +50,7 @@ class DataSourceFilterSet(NetBoxModelFilterSet): ) +@register_filterset class DataFileFilterSet(ChangeLoggedModelFilterSet): q = django_filters.CharFilter( method='search' @@ -75,6 +78,7 @@ class DataFileFilterSet(ChangeLoggedModelFilterSet): ) +@register_filterset class JobFilterSet(BaseFilterSet): q = django_filters.CharFilter( method='search', @@ -139,6 +143,7 @@ class JobFilterSet(BaseFilterSet): ) +@register_filterset class ObjectTypeFilterSet(BaseFilterSet): q = django_filters.CharFilter( method='search', @@ -164,6 +169,7 @@ class ObjectTypeFilterSet(BaseFilterSet): return queryset.filter(features__icontains=value) +@register_filterset class ObjectChangeFilterSet(BaseFilterSet): q = django_filters.CharFilter( method='search', @@ -203,6 +209,7 @@ class ObjectChangeFilterSet(BaseFilterSet): ) +@register_filterset class ConfigRevisionFilterSet(BaseFilterSet): q = django_filters.CharFilter( method='search', diff --git a/netbox/core/forms/bulk_edit.py b/netbox/core/forms/bulk_edit.py index 73618826d..3111ac268 100644 --- a/netbox/core/forms/bulk_edit.py +++ b/netbox/core/forms/bulk_edit.py @@ -3,9 +3,8 @@ from django.utils.translation import gettext_lazy as _ from core.choices import JobIntervalChoices from core.models import * -from netbox.forms import NetBoxModelBulkEditForm +from netbox.forms import PrimaryModelBulkEditForm from netbox.utils import get_data_backend_choices -from utilities.forms.fields import CommentField from utilities.forms.rendering import FieldSet from utilities.forms.widgets import BulkEditNullBooleanSelect @@ -14,7 +13,7 @@ __all__ = ( ) -class DataSourceBulkEditForm(NetBoxModelBulkEditForm): +class DataSourceBulkEditForm(PrimaryModelBulkEditForm): type = forms.ChoiceField( label=_('Type'), choices=get_data_backend_choices, @@ -25,17 +24,11 @@ class DataSourceBulkEditForm(NetBoxModelBulkEditForm): widget=BulkEditNullBooleanSelect(), label=_('Enabled') ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) sync_interval = forms.ChoiceField( choices=JobIntervalChoices, required=False, label=_('Sync interval') ) - comments = CommentField() parameters = forms.JSONField( label=_('Parameters'), required=False diff --git a/netbox/core/forms/bulk_import.py b/netbox/core/forms/bulk_import.py index a5791c945..b04e705e3 100644 --- a/netbox/core/forms/bulk_import.py +++ b/netbox/core/forms/bulk_import.py @@ -1,16 +1,16 @@ from core.models import * -from netbox.forms import NetBoxModelImportForm +from netbox.forms import PrimaryModelImportForm __all__ = ( 'DataSourceImportForm', ) -class DataSourceImportForm(NetBoxModelImportForm): +class DataSourceImportForm(PrimaryModelImportForm): class Meta: model = DataSource fields = ( 'name', 'type', 'source_url', 'enabled', 'description', 'sync_interval', 'parameters', 'ignore_rules', - 'comments', + 'owner', 'comments', ) diff --git a/netbox/core/forms/filtersets.py b/netbox/core/forms/filtersets.py index f9310a70c..69e6a4fbb 100644 --- a/netbox/core/forms/filtersets.py +++ b/netbox/core/forms/filtersets.py @@ -3,13 +3,13 @@ from django.utils.translation import gettext_lazy as _ from core.choices import * from core.models import * -from netbox.forms import NetBoxModelFilterSetForm +from netbox.forms import NetBoxModelFilterSetForm, PrimaryModelFilterSetForm from netbox.forms.mixins import SavedFiltersMixin from netbox.utils import get_data_backend_choices from users.models import User from utilities.forms import BOOLEAN_WITH_BLANK_CHOICES, FilterForm, add_blank_choice from utilities.forms.fields import ( - ContentTypeChoiceField, ContentTypeMultipleChoiceField, DynamicModelMultipleChoiceField, + ContentTypeChoiceField, ContentTypeMultipleChoiceField, DynamicModelMultipleChoiceField, TagFilterField, ) from utilities.forms.rendering import FieldSet from utilities.forms.widgets import DateTimePicker @@ -23,10 +23,10 @@ __all__ = ( ) -class DataSourceFilterForm(NetBoxModelFilterSetForm): +class DataSourceFilterForm(PrimaryModelFilterSetForm): model = DataSource fieldsets = ( - FieldSet('q', 'filter_id'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('type', 'status', 'enabled', 'sync_interval', name=_('Data Source')), ) type = forms.MultipleChoiceField( @@ -51,6 +51,7 @@ class DataSourceFilterForm(NetBoxModelFilterSetForm): choices=JobIntervalChoices, required=False ) + tag = TagFilterField(model) class DataFileFilterForm(NetBoxModelFilterSetForm): diff --git a/netbox/core/forms/model_forms.py b/netbox/core/forms/model_forms.py index 52c68fd79..3b699b0d0 100644 --- a/netbox/core/forms/model_forms.py +++ b/netbox/core/forms/model_forms.py @@ -9,11 +9,11 @@ from django.utils.translation import gettext_lazy as _ from core.forms.mixins import SyncedDataMixin from core.models import * from netbox.config import get_config, PARAMS -from netbox.forms import NetBoxModelForm +from netbox.forms import NetBoxModelForm, PrimaryModelForm from netbox.registry import registry from netbox.utils import get_data_backend_choices from utilities.forms import get_field_value -from utilities.forms.fields import CommentField, JSONField +from utilities.forms.fields import JSONField from utilities.forms.rendering import FieldSet from utilities.forms.widgets import HTMXSelect @@ -26,17 +26,17 @@ __all__ = ( EMPTY_VALUES = ('', None, [], ()) -class DataSourceForm(NetBoxModelForm): +class DataSourceForm(PrimaryModelForm): type = forms.ChoiceField( choices=get_data_backend_choices, widget=HTMXSelect() ) - comments = CommentField() class Meta: model = DataSource fields = [ - 'name', 'type', 'source_url', 'enabled', 'description', 'sync_interval', 'ignore_rules', 'comments', 'tags', + 'name', 'type', 'source_url', 'enabled', 'description', 'sync_interval', 'ignore_rules', 'owner', + 'comments', 'tags', ] widgets = { 'ignore_rules': forms.Textarea( diff --git a/netbox/core/graphql/enums.py b/netbox/core/graphql/enums.py new file mode 100644 index 000000000..863382258 --- /dev/null +++ b/netbox/core/graphql/enums.py @@ -0,0 +1,11 @@ +import strawberry + +from core.choices import * + +__all__ = ( + 'DataSourceStatusEnum', + 'ObjectChangeActionEnum', +) + +DataSourceStatusEnum = strawberry.enum(DataSourceStatusChoices.as_enum(prefix='status')) +ObjectChangeActionEnum = strawberry.enum(ObjectChangeActionChoices.as_enum(prefix='action')) diff --git a/netbox/core/graphql/filter_mixins.py b/netbox/core/graphql/filter_mixins.py index 670ec2ebb..7383f6c4e 100644 --- a/netbox/core/graphql/filter_mixins.py +++ b/netbox/core/graphql/filter_mixins.py @@ -4,31 +4,19 @@ from typing import Annotated, TYPE_CHECKING import strawberry import strawberry_django -from strawberry import ID from strawberry_django import DatetimeFilterLookup if TYPE_CHECKING: from .filters import * __all__ = ( - 'BaseFilterMixin', - 'BaseObjectTypeFilterMixin', - 'ChangeLogFilterMixin', + 'ChangeLoggingMixin', ) -# @strawberry.input -class BaseFilterMixin: ... - - @dataclass -class BaseObjectTypeFilterMixin(BaseFilterMixin): - id: ID | None = strawberry.UNSET - - -@dataclass -class ChangeLogFilterMixin(BaseFilterMixin): - id: ID | None = strawberry.UNSET +class ChangeLoggingMixin: + # TODO: "changelog" is not a valid field name; needs to be updated for ObjectChange changelog: Annotated['ObjectChangeFilter', strawberry.lazy('core.graphql.filters')] | None = ( strawberry_django.filter_field() ) diff --git a/netbox/core/graphql/filters.py b/netbox/core/graphql/filters.py index 76ace2362..2e78b878b 100644 --- a/netbox/core/graphql/filters.py +++ b/netbox/core/graphql/filters.py @@ -5,11 +5,11 @@ import strawberry import strawberry_django from django.contrib.contenttypes.models import ContentType as DjangoContentType from strawberry.scalars import ID -from strawberry_django import DatetimeFilterLookup, FilterLookup +from strawberry_django import BaseFilterLookup, DatetimeFilterLookup, FilterLookup from core import models -from core.graphql.filter_mixins import BaseFilterMixin -from netbox.graphql.filter_mixins import PrimaryModelFilterMixin +from netbox.graphql.filters import BaseModelFilter, PrimaryModelFilter +from .enums import * if TYPE_CHECKING: from netbox.graphql.filter_lookups import IntegerLookup, JSONFilter @@ -24,8 +24,7 @@ __all__ = ( @strawberry_django.filter_type(models.DataFile, lookups=True) -class DataFileFilter(BaseFilterMixin): - id: ID | None = strawberry_django.filter_field() +class DataFileFilter(BaseModelFilter): created: DatetimeFilterLookup[datetime] | None = strawberry_django.filter_field() last_updated: DatetimeFilterLookup[datetime] | None = strawberry_django.filter_field() source: Annotated['DataSourceFilter', strawberry.lazy('core.graphql.filters')] | None = ( @@ -40,11 +39,13 @@ class DataFileFilter(BaseFilterMixin): @strawberry_django.filter_type(models.DataSource, lookups=True) -class DataSourceFilter(PrimaryModelFilterMixin): +class DataSourceFilter(PrimaryModelFilter): name: FilterLookup[str] | None = strawberry_django.filter_field() type: FilterLookup[str] | None = strawberry_django.filter_field() source_url: FilterLookup[str] | None = strawberry_django.filter_field() - status: FilterLookup[str] | None = strawberry_django.filter_field() + status: ( + BaseFilterLookup[Annotated['DataSourceStatusEnum', strawberry.lazy('core.graphql.enums')]] | None + ) = strawberry_django.filter_field() enabled: FilterLookup[bool] | None = strawberry_django.filter_field() ignore_rules: FilterLookup[str] | None = strawberry_django.filter_field() parameters: Annotated['JSONFilter', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( @@ -57,13 +58,14 @@ class DataSourceFilter(PrimaryModelFilterMixin): @strawberry_django.filter_type(models.ObjectChange, lookups=True) -class ObjectChangeFilter(BaseFilterMixin): - id: ID | None = strawberry_django.filter_field() +class ObjectChangeFilter(BaseModelFilter): time: DatetimeFilterLookup[datetime] | None = strawberry_django.filter_field() user: Annotated['UserFilter', strawberry.lazy('users.graphql.filters')] | None = strawberry_django.filter_field() user_name: FilterLookup[str] | None = strawberry_django.filter_field() request_id: FilterLookup[str] | None = strawberry_django.filter_field() - action: FilterLookup[str] | None = strawberry_django.filter_field() + action: ( + BaseFilterLookup[Annotated['ObjectChangeActionEnum', strawberry.lazy('core.graphql.enums')]] | None + ) = strawberry_django.filter_field() changed_object_type: Annotated['ContentTypeFilter', strawberry.lazy('core.graphql.filters')] | None = ( strawberry_django.filter_field() ) @@ -83,7 +85,6 @@ class ObjectChangeFilter(BaseFilterMixin): @strawberry_django.filter_type(DjangoContentType, lookups=True) -class ContentTypeFilter(BaseFilterMixin): - id: ID | None = strawberry_django.filter_field() +class ContentTypeFilter(BaseModelFilter): app_label: FilterLookup[str] | None = strawberry_django.filter_field() model: FilterLookup[str] | None = strawberry_django.filter_field() diff --git a/netbox/core/graphql/types.py b/netbox/core/graphql/types.py index ffaa24411..12407b5c7 100644 --- a/netbox/core/graphql/types.py +++ b/netbox/core/graphql/types.py @@ -5,7 +5,7 @@ import strawberry_django from django.contrib.contenttypes.models import ContentType as DjangoContentType from core import models -from netbox.graphql.types import BaseObjectType, NetBoxObjectType +from netbox.graphql.types import BaseObjectType, PrimaryObjectType from .filters import * __all__ = ( @@ -32,8 +32,7 @@ class DataFileType(BaseObjectType): filters=DataSourceFilter, pagination=True ) -class DataSourceType(NetBoxObjectType): - +class DataSourceType(PrimaryObjectType): datafiles: List[Annotated["DataFileType", strawberry.lazy('core.graphql.types')]] diff --git a/netbox/core/migrations/0020_owner.py b/netbox/core/migrations/0020_owner.py new file mode 100644 index 000000000..f9cdb15b0 --- /dev/null +++ b/netbox/core/migrations/0020_owner.py @@ -0,0 +1,19 @@ +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ('core', '0019_configrevision_active'), + ('users', '0015_owner'), + ] + + operations = [ + migrations.AddField( + model_name='datasource', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + ] diff --git a/netbox/core/models/contenttypes.py b/netbox/core/models/contenttypes.py deleted file mode 100644 index 3d5c5e8b2..000000000 --- a/netbox/core/models/contenttypes.py +++ /dev/null @@ -1,3 +0,0 @@ -# TODO: Remove this module in NetBox v4.5 -# Provided for backward compatibility -from .object_types import * diff --git a/netbox/core/tables/data.py b/netbox/core/tables/data.py index 226a48081..db688b22a 100644 --- a/netbox/core/tables/data.py +++ b/netbox/core/tables/data.py @@ -2,7 +2,7 @@ from django.utils.translation import gettext_lazy as _ import django_tables2 as tables from core.models import * -from netbox.tables import NetBoxTable, columns +from netbox.tables import NetBoxTable, PrimaryModelTable, columns from .columns import BackendTypeColumn from .template_code import DATA_SOURCE_SYNC_BUTTON @@ -12,7 +12,7 @@ __all__ = ( ) -class DataSourceTable(NetBoxTable): +class DataSourceTable(PrimaryModelTable): name = tables.Column( verbose_name=_('Name'), linkify=True, @@ -42,7 +42,7 @@ class DataSourceTable(NetBoxTable): extra_buttons=DATA_SOURCE_SYNC_BUTTON, ) - class Meta(NetBoxTable.Meta): + class Meta(PrimaryModelTable.Meta): model = DataSource fields = ( 'pk', 'id', 'name', 'type', 'status', 'enabled', 'source_url', 'description', 'sync_interval', 'comments', diff --git a/netbox/core/tests/test_api.py b/netbox/core/tests/test_api.py index 4a285bdb4..a1dcf04d5 100644 --- a/netbox/core/tests/test_api.py +++ b/netbox/core/tests/test_api.py @@ -8,6 +8,7 @@ from rq.job import Job as RQ_Job, JobStatus from rq.registry import FailedJobRegistry, StartedJobRegistry from rest_framework import status +from users.constants import TOKEN_PREFIX from users.models import Token, User from utilities.testing import APITestCase, APIViewTestCases, TestCase from utilities.testing.utils import disable_logging @@ -107,14 +108,14 @@ class ObjectTypeTest(APITestCase): def test_list_objects(self): object_type_count = ObjectType.objects.count() - response = self.client.get(reverse('extras-api:objecttype-list'), **self.header) + response = self.client.get(reverse('core-api:objecttype-list'), **self.header) self.assertHttpStatus(response, status.HTTP_200_OK) self.assertEqual(response.data['count'], object_type_count) def test_get_object(self): object_type = ObjectType.objects.first() - url = reverse('extras-api:objecttype-detail', kwargs={'pk': object_type.pk}) + url = reverse('core-api:objecttype-detail', kwargs={'pk': object_type.pk}) self.assertHttpStatus(self.client.get(url, **self.header), status.HTTP_200_OK) @@ -134,12 +135,9 @@ class BackgroundTaskTestCase(TestCase): Create a user and token for API calls. """ # Create the test user and assign permissions - self.user = User.objects.create_user(username='testuser') - self.user.is_staff = True - self.user.is_active = True - self.user.save() + self.user = User.objects.create_user(username='testuser', is_active=True) self.token = Token.objects.create(user=self.user) - self.header = {'HTTP_AUTHORIZATION': f'Token {self.token.key}'} + self.header = {'HTTP_AUTHORIZATION': f'Bearer {TOKEN_PREFIX}{self.token.key}.{self.token.token}'} # Clear all queues prior to running each test get_queue('default').connection.flushall() @@ -150,13 +148,11 @@ class BackgroundTaskTestCase(TestCase): url = reverse('core-api:rqqueue-list') # Attempt to load view without permission - self.user.is_staff = False - self.user.save() response = self.client.get(url, **self.header) self.assertEqual(response.status_code, 403) # Load view with permission - self.user.is_staff = True + self.user.is_superuser = True self.user.save() response = self.client.get(url, **self.header) self.assertEqual(response.status_code, 200) @@ -165,7 +161,16 @@ class BackgroundTaskTestCase(TestCase): self.assertIn('low', str(response.content)) def test_background_queue(self): - response = self.client.get(reverse('core-api:rqqueue-detail', args=['default']), **self.header) + url = reverse('core-api:rqqueue-detail', args=['default']) + + # Attempt to load view without permission + response = self.client.get(url, **self.header) + self.assertEqual(response.status_code, 403) + + # Load view with permission + self.user.is_superuser = True + self.user.save() + response = self.client.get(url, **self.header) self.assertEqual(response.status_code, 200) self.assertIn('default', str(response.content)) self.assertIn('oldest_job_timestamp', str(response.content)) @@ -174,8 +179,16 @@ class BackgroundTaskTestCase(TestCase): def test_background_task_list(self): queue = get_queue('default') queue.enqueue(self.dummy_job_default) + url = reverse('core-api:rqtask-list') - response = self.client.get(reverse('core-api:rqtask-list'), **self.header) + # Attempt to load view without permission + response = self.client.get(url, **self.header) + self.assertEqual(response.status_code, 403) + + # Load view with permission + self.user.is_superuser = True + self.user.save() + response = self.client.get(url, **self.header) self.assertEqual(response.status_code, 200) self.assertIn('origin', str(response.content)) self.assertIn('core.tests.test_api.BackgroundTaskTestCase.dummy_job_default()', str(response.content)) @@ -183,8 +196,16 @@ class BackgroundTaskTestCase(TestCase): def test_background_task(self): queue = get_queue('default') job = queue.enqueue(self.dummy_job_default) + url = reverse('core-api:rqtask-detail', args=[job.id]) - response = self.client.get(reverse('core-api:rqtask-detail', args=[job.id]), **self.header) + # Attempt to load view without permission + response = self.client.get(url, **self.header) + self.assertEqual(response.status_code, 403) + + # Load view with permission + self.user.is_superuser = True + self.user.save() + response = self.client.get(url, **self.header) self.assertEqual(response.status_code, 200) self.assertIn(str(job.id), str(response.content)) self.assertIn('origin', str(response.content)) @@ -194,45 +215,65 @@ class BackgroundTaskTestCase(TestCase): def test_background_task_delete(self): queue = get_queue('default') job = queue.enqueue(self.dummy_job_default) + url = reverse('core-api:rqtask-delete', args=[job.id]) - response = self.client.post(reverse('core-api:rqtask-delete', args=[job.id]), **self.header) + # Attempt to load view without permission + response = self.client.get(url, **self.header) + self.assertEqual(response.status_code, 403) + + # Load view with permission + self.user.is_superuser = True + self.user.save() + response = self.client.post(url, **self.header) self.assertEqual(response.status_code, 200) self.assertFalse(RQ_Job.exists(job.id, connection=queue.connection)) queue = get_queue('default') self.assertNotIn(job.id, queue.job_ids) def test_background_task_requeue(self): - queue = get_queue('default') - # Enqueue & run a job that will fail + queue = get_queue('default') job = queue.enqueue(self.dummy_job_failing) worker = get_worker('default') with disable_logging(): worker.work(burst=True) self.assertTrue(job.is_failed) + url = reverse('core-api:rqtask-requeue', args=[job.id]) + + # Attempt to requeue the job without permission + response = self.client.post(url, **self.header) + self.assertEqual(response.status_code, 403) # Re-enqueue the failed job and check that its status has been reset - response = self.client.post(reverse('core-api:rqtask-requeue', args=[job.id]), **self.header) + self.user.is_superuser = True + self.user.save() + response = self.client.post(url, **self.header) self.assertEqual(response.status_code, 200) job = RQ_Job.fetch(job.id, queue.connection) self.assertFalse(job.is_failed) def test_background_task_enqueue(self): - queue = get_queue('default') - # Enqueue some jobs that each depends on its predecessor + queue = get_queue('default') job = previous_job = None for _ in range(0, 3): job = queue.enqueue(self.dummy_job_default, depends_on=previous_job) previous_job = job + url = reverse('core-api:rqtask-enqueue', args=[job.id]) # Check that the last job to be enqueued has a status of deferred self.assertIsNotNone(job) self.assertEqual(job.get_status(), JobStatus.DEFERRED) self.assertIsNone(job.enqueued_at) + # Attempt to force-enqueue the job without permission + response = self.client.post(url, **self.header) + self.assertEqual(response.status_code, 403) + # Force-enqueue the deferred job - response = self.client.post(reverse('core-api:rqtask-enqueue', args=[job.id]), **self.header) + self.user.is_superuser = True + self.user.save() + response = self.client.post(url, **self.header) self.assertEqual(response.status_code, 200) # Check that job's status is updated correctly @@ -242,19 +283,27 @@ class BackgroundTaskTestCase(TestCase): def test_background_task_stop(self): queue = get_queue('default') - worker = get_worker('default') job = queue.enqueue(self.dummy_job_default) worker.prepare_job_execution(job) - + url = reverse('core-api:rqtask-stop', args=[job.id]) self.assertEqual(job.get_status(), JobStatus.STARTED) - response = self.client.post(reverse('core-api:rqtask-stop', args=[job.id]), **self.header) + + # Attempt to stop the task without permission + response = self.client.post(url, **self.header) + self.assertEqual(response.status_code, 403) + + # Stop the task + self.user.is_superuser = True + self.user.save() + response = self.client.post(url, **self.header) self.assertEqual(response.status_code, 200) with disable_logging(): worker.monitor_work_horse(job, queue) # Sets the job as Failed and removes from Started started_job_registry = StartedJobRegistry(queue.name, connection=queue.connection) self.assertEqual(len(started_job_registry), 0) + # Verify that the task was cancelled canceled_job_registry = FailedJobRegistry(queue.name, connection=queue.connection) self.assertEqual(len(canceled_job_registry), 1) self.assertIn(job.id, canceled_job_registry) @@ -262,19 +311,34 @@ class BackgroundTaskTestCase(TestCase): def test_worker_list(self): worker1 = get_worker('default', name=uuid.uuid4().hex) worker1.register_birth() - worker2 = get_worker('high') worker2.register_birth() + url = reverse('core-api:rqworker-list') - response = self.client.get(reverse('core-api:rqworker-list'), **self.header) + # Attempt to fetch the worker list without permission + response = self.client.get(url, **self.header) + self.assertEqual(response.status_code, 403) + + # Fetch the worker list + self.user.is_superuser = True + self.user.save() + response = self.client.get(url, **self.header) self.assertEqual(response.status_code, 200) self.assertIn(str(worker1.name), str(response.content)) def test_worker(self): worker1 = get_worker('default', name=uuid.uuid4().hex) worker1.register_birth() + url = reverse('core-api:rqworker-detail', args=[worker1.name]) - response = self.client.get(reverse('core-api:rqworker-detail', args=[worker1.name]), **self.header) + # Attempt to fetch a worker without permission + response = self.client.get(url, **self.header) + self.assertEqual(response.status_code, 403) + + # Fetch the worker + self.user.is_superuser = True + self.user.save() + response = self.client.get(url, **self.header) self.assertEqual(response.status_code, 200) self.assertIn(str(worker1.name), str(response.content)) self.assertIn('birth_date', str(response.content)) diff --git a/netbox/core/tests/test_views.py b/netbox/core/tests/test_views.py index 1001243eb..2f0ef59e6 100644 --- a/netbox/core/tests/test_views.py +++ b/netbox/core/tests/test_views.py @@ -158,7 +158,7 @@ class BackgroundTaskTestCase(TestCase): def setUp(self): super().setUp() - self.user.is_staff = True + self.user.is_superuser = True self.user.is_active = True self.user.save() @@ -171,13 +171,13 @@ class BackgroundTaskTestCase(TestCase): url = reverse('core:background_queue_list') # Attempt to load view without permission - self.user.is_staff = False + self.user.is_superuser = False self.user.save() response = self.client.get(url) self.assertEqual(response.status_code, 403) # Load view with permission - self.user.is_staff = True + self.user.is_superuser = True self.user.save() response = self.client.get(url) self.assertEqual(response.status_code, 200) @@ -356,7 +356,7 @@ class SystemTestCase(TestCase): def setUp(self): super().setUp() - self.user.is_staff = True + self.user.is_superuser = True self.user.save() def test_system_view_default(self): diff --git a/netbox/core/views.py b/netbox/core/views.py index b96392a9b..c3e26ae3d 100644 --- a/netbox/core/views.py +++ b/netbox/core/views.py @@ -373,7 +373,7 @@ class ConfigRevisionRestoreView(ContentTypePermissionRequiredMixin, View): class BaseRQView(UserPassesTestMixin, View): def test_func(self): - return self.request.user.is_staff + return self.request.user.is_superuser class BackgroundQueueListView(TableMixin, BaseRQView): @@ -556,7 +556,7 @@ class WorkerView(BaseRQView): class SystemView(UserPassesTestMixin, View): def test_func(self): - return self.request.user.is_staff + return self.request.user.is_superuser def get(self, request): @@ -639,7 +639,7 @@ class BasePluginView(UserPassesTestMixin, View): CACHE_KEY_CATALOG_ERROR = 'plugins-catalog-error' def test_func(self): - return self.request.user.is_staff + return self.request.user.is_superuser def get_cached_plugins(self, request): catalog_plugins = {} diff --git a/netbox/dcim/api/serializers_/base.py b/netbox/dcim/api/serializers_/base.py index 1dca773b2..3b9142f1d 100644 --- a/netbox/dcim/api/serializers_/base.py +++ b/netbox/dcim/api/serializers_/base.py @@ -2,10 +2,12 @@ from drf_spectacular.types import OpenApiTypes from drf_spectacular.utils import extend_schema_field from rest_framework import serializers +from dcim.models import FrontPort, FrontPortTemplate, PortMapping, PortTemplateMapping, RearPort, RearPortTemplate from utilities.api import get_serializer_for_model __all__ = ( 'ConnectedEndpointsSerializer', + 'PortSerializer', ) @@ -35,3 +37,53 @@ class ConnectedEndpointsSerializer(serializers.ModelSerializer): @extend_schema_field(serializers.BooleanField) def get_connected_endpoints_reachable(self, obj): return obj._path and obj._path.is_complete and obj._path.is_active + + +class PortSerializer(serializers.ModelSerializer): + """ + Base serializer for front & rear port and port templates. + """ + @property + def _mapper(self): + """ + Return the model and ForeignKey field name used to track port mappings for this model. + """ + if self.Meta.model is FrontPort: + return PortMapping, 'front_port' + if self.Meta.model is RearPort: + return PortMapping, 'rear_port' + if self.Meta.model is FrontPortTemplate: + return PortTemplateMapping, 'front_port' + if self.Meta.model is RearPortTemplate: + return PortTemplateMapping, 'rear_port' + raise ValueError(f"Could not determine mapping details for {self.__class__}") + + def create(self, validated_data): + mappings = validated_data.pop('mappings', []) + instance = super().create(validated_data) + + # Create port mappings + mapping_model, fk_name = self._mapper + for attrs in mappings: + mapping_model.objects.create(**{ + fk_name: instance, + **attrs, + }) + + return instance + + def update(self, instance, validated_data): + mappings = validated_data.pop('mappings', None) + instance = super().update(instance, validated_data) + + if mappings is not None: + # Update port mappings + mapping_model, fk_name = self._mapper + mapping_model.objects.filter(**{fk_name: instance}).delete() + for attrs in mappings: + mapping_model.objects.create(**{ + fk_name: instance, + **attrs, + }) + + return instance diff --git a/netbox/dcim/api/serializers_/cables.py b/netbox/dcim/api/serializers_/cables.py index 397e5cd16..0ed0cf851 100644 --- a/netbox/dcim/api/serializers_/cables.py +++ b/netbox/dcim/api/serializers_/cables.py @@ -1,13 +1,14 @@ -from django.contrib.contenttypes.models import ContentType from drf_spectacular.types import OpenApiTypes from drf_spectacular.utils import extend_schema_field from rest_framework import serializers from dcim.choices import * -from dcim.constants import * from dcim.models import Cable, CablePath, CableTermination from netbox.api.fields import ChoiceField, ContentTypeField -from netbox.api.serializers import BaseModelSerializer, GenericObjectSerializer, NetBoxModelSerializer +from netbox.api.gfk_fields import GFKSerializerField +from netbox.api.serializers import ( + BaseModelSerializer, GenericObjectSerializer, NetBoxModelSerializer, PrimaryModelSerializer, +) from tenancy.api.serializers_.tenants import TenantSerializer from utilities.api import get_serializer_for_model @@ -20,19 +21,20 @@ __all__ = ( ) -class CableSerializer(NetBoxModelSerializer): +class CableSerializer(PrimaryModelSerializer): a_terminations = GenericObjectSerializer(many=True, required=False) b_terminations = GenericObjectSerializer(many=True, required=False) status = ChoiceField(choices=LinkStatusChoices, required=False) + profile = ChoiceField(choices=CableProfileChoices, required=False) tenant = TenantSerializer(nested=True, required=False, allow_null=True) length_unit = ChoiceField(choices=CableLengthUnitChoices, allow_blank=True, required=False, allow_null=True) class Meta: model = Cable fields = [ - 'id', 'url', 'display_url', 'display', 'type', 'a_terminations', 'b_terminations', 'status', 'tenant', - 'label', 'color', 'length', 'length_unit', 'description', 'comments', 'tags', 'custom_fields', 'created', - 'last_updated', + 'id', 'url', 'display_url', 'display', 'type', 'a_terminations', 'b_terminations', 'status', 'profile', + 'tenant', 'label', 'color', 'length', 'length_unit', 'description', 'owner', 'comments', 'tags', + 'custom_fields', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'label', 'description') @@ -51,22 +53,21 @@ class TracedCableSerializer(BaseModelSerializer): class CableTerminationSerializer(NetBoxModelSerializer): termination_type = ContentTypeField( - queryset=ContentType.objects.filter(CABLE_TERMINATION_MODELS) + read_only=True, ) - termination = serializers.SerializerMethodField(read_only=True) + termination = GFKSerializerField(read_only=True) class Meta: model = CableTermination fields = [ 'id', 'url', 'display', 'cable', 'cable_end', 'termination_type', 'termination_id', - 'termination', 'created', 'last_updated', + 'termination', 'connector', 'positions', 'created', 'last_updated', ] - - @extend_schema_field(serializers.JSONField(allow_null=True)) - def get_termination(self, obj): - serializer = get_serializer_for_model(obj.termination) - context = {'request': self.context['request']} - return serializer(obj.termination, nested=True, context=context).data + read_only_fields = fields + brief_fields = ( + 'id', 'url', 'display', 'cable', 'cable_end', 'connector', 'positions', 'termination_type', + 'termination_id', + ) class CablePathSerializer(serializers.ModelSerializer): diff --git a/netbox/dcim/api/serializers_/device_components.py b/netbox/dcim/api/serializers_/device_components.py index f4b14cda7..e56471dd5 100644 --- a/netbox/dcim/api/serializers_/device_components.py +++ b/netbox/dcim/api/serializers_/device_components.py @@ -1,26 +1,26 @@ from django.contrib.contenttypes.models import ContentType from django.utils.translation import gettext as _ -from drf_spectacular.utils import extend_schema_field from rest_framework import serializers from dcim.choices import * from dcim.constants import * from dcim.models import ( - ConsolePort, ConsoleServerPort, DeviceBay, FrontPort, Interface, InventoryItem, ModuleBay, PowerOutlet, PowerPort, - RearPort, VirtualDeviceContext, + ConsolePort, ConsoleServerPort, DeviceBay, FrontPort, Interface, InventoryItem, ModuleBay, PortMapping, + PowerOutlet, PowerPort, RearPort, VirtualDeviceContext, ) from ipam.api.serializers_.vlans import VLANSerializer, VLANTranslationPolicySerializer from ipam.api.serializers_.vrfs import VRFSerializer from ipam.models import VLAN from netbox.api.fields import ChoiceField, ContentTypeField, SerializedPKRelatedField -from netbox.api.serializers import NetBoxModelSerializer, WritableNestedSerializer -from utilities.api import get_serializer_for_model +from netbox.api.gfk_fields import GFKSerializerField +from netbox.api.serializers import NetBoxModelSerializer +from users.api.serializers_.mixins import OwnerMixin from vpn.api.serializers_.l2vpn import L2VPNTerminationSerializer from wireless.api.serializers_.nested import NestedWirelessLinkSerializer from wireless.api.serializers_.wirelesslans import WirelessLANSerializer from wireless.choices import * from wireless.models import WirelessLAN -from .base import ConnectedEndpointsSerializer +from .base import ConnectedEndpointsSerializer, PortSerializer from .cables import CabledObjectSerializer from .devices import DeviceSerializer, MACAddressSerializer, ModuleSerializer, VirtualDeviceContextSerializer from .manufacturers import ManufacturerSerializer @@ -41,7 +41,12 @@ __all__ = ( ) -class ConsoleServerPortSerializer(NetBoxModelSerializer, CabledObjectSerializer, ConnectedEndpointsSerializer): +class ConsoleServerPortSerializer( + OwnerMixin, + NetBoxModelSerializer, + CabledObjectSerializer, + ConnectedEndpointsSerializer +): device = DeviceSerializer(nested=True) module = ModuleSerializer( nested=True, @@ -65,13 +70,18 @@ class ConsoleServerPortSerializer(NetBoxModelSerializer, CabledObjectSerializer, fields = [ 'id', 'url', 'display_url', 'display', 'device', 'module', 'name', 'label', 'type', 'speed', 'description', 'mark_connected', 'cable', 'cable_end', 'link_peers', 'link_peers_type', 'connected_endpoints', - 'connected_endpoints_type', 'connected_endpoints_reachable', 'tags', 'custom_fields', 'created', + 'connected_endpoints_type', 'connected_endpoints_reachable', 'owner', 'tags', 'custom_fields', 'created', 'last_updated', '_occupied', ] brief_fields = ('id', 'url', 'display', 'device', 'name', 'description', 'cable', '_occupied') -class ConsolePortSerializer(NetBoxModelSerializer, CabledObjectSerializer, ConnectedEndpointsSerializer): +class ConsolePortSerializer( + OwnerMixin, + NetBoxModelSerializer, + CabledObjectSerializer, + ConnectedEndpointsSerializer +): device = DeviceSerializer(nested=True) module = ModuleSerializer( nested=True, @@ -95,13 +105,18 @@ class ConsolePortSerializer(NetBoxModelSerializer, CabledObjectSerializer, Conne fields = [ 'id', 'url', 'display_url', 'display', 'device', 'module', 'name', 'label', 'type', 'speed', 'description', 'mark_connected', 'cable', 'cable_end', 'link_peers', 'link_peers_type', 'connected_endpoints', - 'connected_endpoints_type', 'connected_endpoints_reachable', 'tags', 'custom_fields', 'created', + 'connected_endpoints_type', 'connected_endpoints_reachable', 'owner', 'tags', 'custom_fields', 'created', 'last_updated', '_occupied', ] brief_fields = ('id', 'url', 'display', 'device', 'name', 'description', 'cable', '_occupied') -class PowerPortSerializer(NetBoxModelSerializer, CabledObjectSerializer, ConnectedEndpointsSerializer): +class PowerPortSerializer( + OwnerMixin, + NetBoxModelSerializer, + CabledObjectSerializer, + ConnectedEndpointsSerializer +): device = DeviceSerializer(nested=True) module = ModuleSerializer( nested=True, @@ -121,13 +136,18 @@ class PowerPortSerializer(NetBoxModelSerializer, CabledObjectSerializer, Connect fields = [ 'id', 'url', 'display_url', 'display', 'device', 'module', 'name', 'label', 'type', 'maximum_draw', 'allocated_draw', 'description', 'mark_connected', 'cable', 'cable_end', 'link_peers', 'link_peers_type', - 'connected_endpoints', 'connected_endpoints_type', 'connected_endpoints_reachable', 'tags', 'custom_fields', - 'created', 'last_updated', '_occupied', + 'connected_endpoints', 'connected_endpoints_type', 'connected_endpoints_reachable', 'owner', 'tags', + 'custom_fields', 'created', 'last_updated', '_occupied', ] brief_fields = ('id', 'url', 'display', 'device', 'name', 'description', 'cable', '_occupied') -class PowerOutletSerializer(NetBoxModelSerializer, CabledObjectSerializer, ConnectedEndpointsSerializer): +class PowerOutletSerializer( + OwnerMixin, + NetBoxModelSerializer, + CabledObjectSerializer, + ConnectedEndpointsSerializer +): device = DeviceSerializer(nested=True) module = ModuleSerializer( nested=True, @@ -160,12 +180,17 @@ class PowerOutletSerializer(NetBoxModelSerializer, CabledObjectSerializer, Conne 'id', 'url', 'display_url', 'display', 'device', 'module', 'name', 'label', 'type', 'status', 'color', 'power_port', 'feed_leg', 'description', 'mark_connected', 'cable', 'cable_end', 'link_peers', 'link_peers_type', 'connected_endpoints', 'connected_endpoints_type', 'connected_endpoints_reachable', - 'tags', 'custom_fields', 'created', 'last_updated', '_occupied', + 'owner', 'tags', 'custom_fields', 'created', 'last_updated', '_occupied', ] brief_fields = ('id', 'url', 'display', 'device', 'name', 'description', 'cable', '_occupied') -class InterfaceSerializer(NetBoxModelSerializer, CabledObjectSerializer, ConnectedEndpointsSerializer): +class InterfaceSerializer( + OwnerMixin, + NetBoxModelSerializer, + CabledObjectSerializer, + ConnectedEndpointsSerializer +): device = DeviceSerializer(nested=True) vdcs = SerializedPKRelatedField( queryset=VirtualDeviceContext.objects.all(), @@ -228,8 +253,8 @@ class InterfaceSerializer(NetBoxModelSerializer, CabledObjectSerializer, Connect 'poe_mode', 'poe_type', 'rf_channel_frequency', 'rf_channel_width', 'tx_power', 'untagged_vlan', 'tagged_vlans', 'qinq_svlan', 'vlan_translation_policy', 'mark_connected', 'cable', 'cable_end', 'wireless_link', 'link_peers', 'link_peers_type', 'wireless_lans', 'vrf', 'l2vpn_termination', - 'connected_endpoints', 'connected_endpoints_type', 'connected_endpoints_reachable', 'tags', 'custom_fields', - 'created', 'last_updated', 'count_ipaddresses', 'count_fhrp_groups', '_occupied', + 'connected_endpoints', 'connected_endpoints_type', 'connected_endpoints_reachable', 'owner', 'tags', + 'custom_fields', 'created', 'last_updated', 'count_ipaddresses', 'count_fhrp_groups', '_occupied', ] brief_fields = ('id', 'url', 'display', 'device', 'name', 'description', 'cable', '_occupied') @@ -296,7 +321,20 @@ class InterfaceSerializer(NetBoxModelSerializer, CabledObjectSerializer, Connect return super().validate(data) -class RearPortSerializer(NetBoxModelSerializer, CabledObjectSerializer): +class RearPortMappingSerializer(serializers.ModelSerializer): + position = serializers.IntegerField( + source='rear_port_position' + ) + front_port = serializers.PrimaryKeyRelatedField( + queryset=FrontPort.objects.all(), + ) + + class Meta: + model = PortMapping + fields = ('position', 'front_port', 'front_port_position') + + +class RearPortSerializer(OwnerMixin, NetBoxModelSerializer, CabledObjectSerializer, PortSerializer): device = DeviceSerializer(nested=True) module = ModuleSerializer( nested=True, @@ -305,28 +343,36 @@ class RearPortSerializer(NetBoxModelSerializer, CabledObjectSerializer): allow_null=True ) type = ChoiceField(choices=PortTypeChoices) + front_ports = RearPortMappingSerializer( + source='mappings', + many=True, + required=False, + ) class Meta: model = RearPort fields = [ 'id', 'url', 'display_url', 'display', 'device', 'module', 'name', 'label', 'type', 'color', 'positions', - 'description', 'mark_connected', 'cable', 'cable_end', 'link_peers', 'link_peers_type', 'tags', - 'custom_fields', 'created', 'last_updated', '_occupied', + 'front_ports', 'description', 'mark_connected', 'cable', 'cable_end', 'link_peers', 'link_peers_type', + 'owner', 'tags', 'custom_fields', 'created', 'last_updated', '_occupied', ] brief_fields = ('id', 'url', 'display', 'device', 'name', 'description', 'cable', '_occupied') -class FrontPortRearPortSerializer(WritableNestedSerializer): - """ - NestedRearPortSerializer but with parent device omitted (since front and rear ports must belong to same device) - """ +class FrontPortMappingSerializer(serializers.ModelSerializer): + position = serializers.IntegerField( + source='front_port_position' + ) + rear_port = serializers.PrimaryKeyRelatedField( + queryset=RearPort.objects.all(), + ) class Meta: - model = RearPort - fields = ['id', 'url', 'display_url', 'display', 'name', 'label', 'description'] + model = PortMapping + fields = ('position', 'rear_port', 'rear_port_position') -class FrontPortSerializer(NetBoxModelSerializer, CabledObjectSerializer): +class FrontPortSerializer(OwnerMixin, NetBoxModelSerializer, CabledObjectSerializer, PortSerializer): device = DeviceSerializer(nested=True) module = ModuleSerializer( nested=True, @@ -335,19 +381,23 @@ class FrontPortSerializer(NetBoxModelSerializer, CabledObjectSerializer): allow_null=True ) type = ChoiceField(choices=PortTypeChoices) - rear_port = FrontPortRearPortSerializer() + rear_ports = FrontPortMappingSerializer( + source='mappings', + many=True, + required=False, + ) class Meta: model = FrontPort fields = [ - 'id', 'url', 'display_url', 'display', 'device', 'module', 'name', 'label', 'type', 'color', 'rear_port', - 'rear_port_position', 'description', 'mark_connected', 'cable', 'cable_end', 'link_peers', - 'link_peers_type', 'tags', 'custom_fields', 'created', 'last_updated', '_occupied', + 'id', 'url', 'display_url', 'display', 'device', 'module', 'name', 'label', 'type', 'color', 'positions', + 'rear_ports', 'description', 'mark_connected', 'cable', 'cable_end', 'link_peers', 'link_peers_type', + 'owner', 'tags', 'custom_fields', 'created', 'last_updated', '_occupied', ] brief_fields = ('id', 'url', 'display', 'device', 'name', 'description', 'cable', '_occupied') -class ModuleBaySerializer(NetBoxModelSerializer): +class ModuleBaySerializer(OwnerMixin, NetBoxModelSerializer): device = DeviceSerializer(nested=True) module = ModuleSerializer( nested=True, @@ -367,12 +417,12 @@ class ModuleBaySerializer(NetBoxModelSerializer): model = ModuleBay fields = [ 'id', 'url', 'display_url', 'display', 'device', 'module', 'name', 'installed_module', 'label', 'position', - 'description', 'tags', 'custom_fields', 'created', 'last_updated', + 'description', 'owner', 'tags', 'custom_fields', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'installed_module', 'name', 'description') -class DeviceBaySerializer(NetBoxModelSerializer): +class DeviceBaySerializer(OwnerMixin, NetBoxModelSerializer): device = DeviceSerializer(nested=True) installed_device = DeviceSerializer(nested=True, required=False, allow_null=True) @@ -380,12 +430,12 @@ class DeviceBaySerializer(NetBoxModelSerializer): model = DeviceBay fields = [ 'id', 'url', 'display_url', 'display', 'device', 'name', 'label', 'description', 'installed_device', - 'tags', 'custom_fields', 'created', 'last_updated', + 'owner', 'tags', 'custom_fields', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'device', 'name', 'description') -class InventoryItemSerializer(NetBoxModelSerializer): +class InventoryItemSerializer(OwnerMixin, NetBoxModelSerializer): device = DeviceSerializer(nested=True) parent = serializers.PrimaryKeyRelatedField(queryset=InventoryItem.objects.all(), allow_null=True, default=None) role = InventoryItemRoleSerializer(nested=True, required=False, allow_null=True) @@ -395,7 +445,7 @@ class InventoryItemSerializer(NetBoxModelSerializer): required=False, allow_null=True ) - component = serializers.SerializerMethodField(read_only=True, allow_null=True) + component = GFKSerializerField(read_only=True) _depth = serializers.IntegerField(source='level', read_only=True) status = ChoiceField(choices=InventoryItemStatusChoices, required=False) @@ -404,14 +454,6 @@ class InventoryItemSerializer(NetBoxModelSerializer): fields = [ 'id', 'url', 'display_url', 'display', 'device', 'parent', 'name', 'label', 'status', 'role', 'manufacturer', 'part_id', 'serial', 'asset_tag', 'discovered', 'description', 'component_type', - 'component_id', 'component', 'tags', 'custom_fields', 'created', 'last_updated', '_depth', + 'component_id', 'component', 'owner', 'tags', 'custom_fields', 'created', 'last_updated', '_depth', ] brief_fields = ('id', 'url', 'display', 'device', 'name', 'description', '_depth') - - @extend_schema_field(serializers.JSONField(allow_null=True)) - def get_component(self, obj): - if obj.component is None: - return None - serializer = get_serializer_for_model(obj.component) - context = {'request': self.context['request']} - return serializer(obj.component, nested=True, context=context).data diff --git a/netbox/dcim/api/serializers_/devices.py b/netbox/dcim/api/serializers_/devices.py index c1e9c5f51..6346a3b43 100644 --- a/netbox/dcim/api/serializers_/devices.py +++ b/netbox/dcim/api/serializers_/devices.py @@ -11,15 +11,15 @@ from dcim.models import Device, DeviceBay, MACAddress, Module, VirtualDeviceCont from extras.api.serializers_.configtemplates import ConfigTemplateSerializer from ipam.api.serializers_.ip import IPAddressSerializer from netbox.api.fields import ChoiceField, ContentTypeField, RelatedObjectCountField -from netbox.api.serializers import NetBoxModelSerializer +from netbox.api.gfk_fields import GFKSerializerField +from netbox.api.serializers import PrimaryModelSerializer from tenancy.api.serializers_.tenants import TenantSerializer -from utilities.api import get_serializer_for_model from virtualization.api.serializers_.clusters import ClusterSerializer from .devicetypes import * +from .nested import NestedDeviceBaySerializer, NestedDeviceSerializer, NestedModuleBaySerializer from .platforms import PlatformSerializer from .racks import RackSerializer from .roles import DeviceRoleSerializer -from .nested import NestedDeviceBaySerializer, NestedDeviceSerializer, NestedModuleBaySerializer from .sites import LocationSerializer, SiteSerializer from .virtualchassis import VirtualChassisSerializer @@ -32,7 +32,7 @@ __all__ = ( ) -class DeviceSerializer(NetBoxModelSerializer): +class DeviceSerializer(PrimaryModelSerializer): device_type = DeviceTypeSerializer(nested=True) role = DeviceRoleSerializer(nested=True) tenant = TenantSerializer( @@ -84,8 +84,8 @@ class DeviceSerializer(NetBoxModelSerializer): 'id', 'url', 'display_url', 'display', 'name', 'device_type', 'role', 'tenant', 'platform', 'serial', 'asset_tag', 'site', 'location', 'rack', 'position', 'face', 'latitude', 'longitude', 'parent_device', 'status', 'airflow', 'primary_ip', 'primary_ip4', 'primary_ip6', 'oob_ip', 'cluster', 'virtual_chassis', - 'vc_position', 'vc_priority', 'description', 'comments', 'config_template', 'local_context_data', 'tags', - 'custom_fields', 'created', 'last_updated', 'console_port_count', 'console_server_port_count', + 'vc_position', 'vc_priority', 'description', 'owner', 'comments', 'config_template', 'local_context_data', + 'tags', 'custom_fields', 'created', 'last_updated', 'console_port_count', 'console_server_port_count', 'power_port_count', 'power_outlet_count', 'interface_count', 'front_port_count', 'rear_port_count', 'device_bay_count', 'module_bay_count', 'inventory_item_count', ] @@ -111,7 +111,7 @@ class DeviceWithConfigContextSerializer(DeviceSerializer): 'id', 'url', 'display_url', 'display', 'name', 'device_type', 'role', 'tenant', 'platform', 'serial', 'asset_tag', 'site', 'location', 'rack', 'position', 'face', 'latitude', 'longitude', 'parent_device', 'status', 'airflow', 'primary_ip', 'primary_ip4', 'primary_ip6', 'oob_ip', 'cluster', 'virtual_chassis', - 'vc_position', 'vc_priority', 'description', 'comments', 'config_template', 'config_context', + 'vc_position', 'vc_priority', 'description', 'owner', 'comments', 'config_template', 'config_context', 'local_context_data', 'tags', 'custom_fields', 'created', 'last_updated', 'console_port_count', 'console_server_port_count', 'power_port_count', 'power_outlet_count', 'interface_count', 'front_port_count', 'rear_port_count', 'device_bay_count', 'module_bay_count', 'inventory_item_count', @@ -122,7 +122,7 @@ class DeviceWithConfigContextSerializer(DeviceSerializer): return obj.get_config_context() -class VirtualDeviceContextSerializer(NetBoxModelSerializer): +class VirtualDeviceContextSerializer(PrimaryModelSerializer): device = DeviceSerializer(nested=True) identifier = serializers.IntegerField(allow_null=True, max_value=32767, min_value=0, required=False, default=None) tenant = TenantSerializer(nested=True, required=False, allow_null=True, default=None) @@ -138,13 +138,13 @@ class VirtualDeviceContextSerializer(NetBoxModelSerializer): model = VirtualDeviceContext fields = [ 'id', 'url', 'display_url', 'display', 'name', 'device', 'identifier', 'tenant', 'primary_ip', - 'primary_ip4', 'primary_ip6', 'status', 'description', 'comments', 'tags', 'custom_fields', + 'primary_ip4', 'primary_ip6', 'status', 'description', 'owner', 'comments', 'tags', 'custom_fields', 'created', 'last_updated', 'interface_count', ] brief_fields = ('id', 'url', 'display', 'name', 'identifier', 'device', 'description') -class ModuleSerializer(NetBoxModelSerializer): +class ModuleSerializer(PrimaryModelSerializer): device = DeviceSerializer(nested=True) module_bay = NestedModuleBaySerializer() module_type = ModuleTypeSerializer(nested=True) @@ -154,31 +154,23 @@ class ModuleSerializer(NetBoxModelSerializer): model = Module fields = [ 'id', 'url', 'display_url', 'display', 'device', 'module_bay', 'module_type', 'status', 'serial', - 'asset_tag', 'description', 'comments', 'tags', 'custom_fields', 'created', 'last_updated', + 'asset_tag', 'description', 'owner', 'comments', 'tags', 'custom_fields', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'device', 'module_bay', 'module_type', 'description') -class MACAddressSerializer(NetBoxModelSerializer): +class MACAddressSerializer(PrimaryModelSerializer): assigned_object_type = ContentTypeField( queryset=ContentType.objects.filter(MACADDRESS_ASSIGNMENT_MODELS), required=False, allow_null=True ) - assigned_object = serializers.SerializerMethodField(read_only=True) + assigned_object = GFKSerializerField(read_only=True) class Meta: model = MACAddress fields = [ 'id', 'url', 'display_url', 'display', 'mac_address', 'assigned_object_type', 'assigned_object_id', - 'assigned_object', 'description', 'comments', 'tags', 'custom_fields', 'created', 'last_updated', + 'assigned_object', 'description', 'owner', 'comments', 'tags', 'custom_fields', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'mac_address', 'description') - - @extend_schema_field(serializers.JSONField(allow_null=True)) - def get_assigned_object(self, obj): - if obj.assigned_object is None: - return None - serializer = get_serializer_for_model(obj.assigned_object) - context = {'request': self.context['request']} - return serializer(obj.assigned_object, nested=True, context=context).data diff --git a/netbox/dcim/api/serializers_/devicetype_components.py b/netbox/dcim/api/serializers_/devicetype_components.py index 8d4403d2d..9a9b5d470 100644 --- a/netbox/dcim/api/serializers_/devicetype_components.py +++ b/netbox/dcim/api/serializers_/devicetype_components.py @@ -1,17 +1,18 @@ from django.contrib.contenttypes.models import ContentType -from drf_spectacular.utils import extend_schema_field from rest_framework import serializers from dcim.choices import * from dcim.constants import * from dcim.models import ( ConsolePortTemplate, ConsoleServerPortTemplate, DeviceBayTemplate, FrontPortTemplate, InterfaceTemplate, - InventoryItemTemplate, ModuleBayTemplate, PowerOutletTemplate, PowerPortTemplate, RearPortTemplate, + InventoryItemTemplate, ModuleBayTemplate, PortTemplateMapping, PowerOutletTemplate, PowerPortTemplate, + RearPortTemplate, ) from netbox.api.fields import ChoiceField, ContentTypeField +from netbox.api.gfk_fields import GFKSerializerField from netbox.api.serializers import ChangeLogMessageSerializer, ValidatedModelSerializer -from utilities.api import get_serializer_for_model from wireless.choices import * +from .base import PortSerializer from .devicetypes import DeviceTypeSerializer, ModuleTypeSerializer from .manufacturers import ManufacturerSerializer from .nested import NestedInterfaceTemplateSerializer @@ -155,7 +156,7 @@ class PowerOutletTemplateSerializer(ComponentTemplateSerializer): model = PowerOutletTemplate fields = [ 'id', 'url', 'display', 'device_type', 'module_type', 'name', 'label', 'type', - 'power_port', 'feed_leg', 'description', 'created', 'last_updated', + 'color', 'power_port', 'feed_leg', 'description', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'name', 'description') @@ -206,7 +207,20 @@ class InterfaceTemplateSerializer(ComponentTemplateSerializer): brief_fields = ('id', 'url', 'display', 'name', 'description') -class RearPortTemplateSerializer(ComponentTemplateSerializer): +class RearPortTemplateMappingSerializer(serializers.ModelSerializer): + position = serializers.IntegerField( + source='rear_port_position' + ) + front_port = serializers.PrimaryKeyRelatedField( + queryset=FrontPortTemplate.objects.all(), + ) + + class Meta: + model = PortTemplateMapping + fields = ('position', 'front_port', 'front_port_position') + + +class RearPortTemplateSerializer(ComponentTemplateSerializer, PortSerializer): device_type = DeviceTypeSerializer( required=False, nested=True, @@ -220,17 +234,35 @@ class RearPortTemplateSerializer(ComponentTemplateSerializer): default=None ) type = ChoiceField(choices=PortTypeChoices) + front_ports = RearPortTemplateMappingSerializer( + source='mappings', + many=True, + required=False, + ) class Meta: model = RearPortTemplate fields = [ - 'id', 'url', 'display', 'device_type', 'module_type', 'name', 'label', 'type', 'color', - 'positions', 'description', 'created', 'last_updated', + 'id', 'url', 'display', 'device_type', 'module_type', 'name', 'label', 'type', 'color', 'positions', + 'front_ports', 'description', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'name', 'description') -class FrontPortTemplateSerializer(ComponentTemplateSerializer): +class FrontPortTemplateMappingSerializer(serializers.ModelSerializer): + position = serializers.IntegerField( + source='front_port_position' + ) + rear_port = serializers.PrimaryKeyRelatedField( + queryset=RearPortTemplate.objects.all(), + ) + + class Meta: + model = PortTemplateMapping + fields = ('position', 'rear_port', 'rear_port_position') + + +class FrontPortTemplateSerializer(ComponentTemplateSerializer, PortSerializer): device_type = DeviceTypeSerializer( nested=True, required=False, @@ -244,13 +276,17 @@ class FrontPortTemplateSerializer(ComponentTemplateSerializer): default=None ) type = ChoiceField(choices=PortTypeChoices) - rear_port = RearPortTemplateSerializer(nested=True) + rear_ports = FrontPortTemplateMappingSerializer( + source='mappings', + many=True, + required=False, + ) class Meta: model = FrontPortTemplate fields = [ - 'id', 'url', 'display', 'device_type', 'module_type', 'name', 'label', 'type', 'color', - 'rear_port', 'rear_port_position', 'description', 'created', 'last_updated', + 'id', 'url', 'display', 'device_type', 'module_type', 'name', 'label', 'type', 'color', 'positions', + 'rear_ports', 'description', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'name', 'description') @@ -313,7 +349,7 @@ class InventoryItemTemplateSerializer(ComponentTemplateSerializer): required=False, allow_null=True ) - component = serializers.SerializerMethodField(read_only=True, allow_null=True) + component = GFKSerializerField(read_only=True) _depth = serializers.IntegerField(source='level', read_only=True) class Meta: @@ -324,11 +360,3 @@ class InventoryItemTemplateSerializer(ComponentTemplateSerializer): '_depth', ] brief_fields = ('id', 'url', 'display', 'name', 'description', '_depth') - - @extend_schema_field(serializers.JSONField(allow_null=True)) - def get_component(self, obj): - if obj.component is None: - return None - serializer = get_serializer_for_model(obj.component) - context = {'request': self.context['request']} - return serializer(obj.component, nested=True, context=context).data diff --git a/netbox/dcim/api/serializers_/devicetypes.py b/netbox/dcim/api/serializers_/devicetypes.py index 61e3833ec..797d31d87 100644 --- a/netbox/dcim/api/serializers_/devicetypes.py +++ b/netbox/dcim/api/serializers_/devicetypes.py @@ -5,8 +5,8 @@ from rest_framework import serializers from dcim.choices import * from dcim.models import DeviceType, ModuleType, ModuleTypeProfile -from netbox.api.fields import AttributesField, ChoiceField, RelatedObjectCountField -from netbox.api.serializers import NetBoxModelSerializer +from netbox.api.fields import AttributesField, ChoiceField +from netbox.api.serializers import PrimaryModelSerializer from netbox.choices import * from .manufacturers import ManufacturerSerializer from .platforms import PlatformSerializer @@ -18,7 +18,7 @@ __all__ = ( ) -class DeviceTypeSerializer(NetBoxModelSerializer): +class DeviceTypeSerializer(PrimaryModelSerializer): manufacturer = ManufacturerSerializer(nested=True) default_platform = PlatformSerializer(nested=True, required=False, allow_null=True) u_height = serializers.DecimalField( @@ -45,16 +45,14 @@ class DeviceTypeSerializer(NetBoxModelSerializer): device_bay_template_count = serializers.IntegerField(read_only=True) module_bay_template_count = serializers.IntegerField(read_only=True) inventory_item_template_count = serializers.IntegerField(read_only=True) - - # Related object counts - device_count = RelatedObjectCountField('instances') + device_count = serializers.IntegerField(read_only=True) class Meta: model = DeviceType fields = [ 'id', 'url', 'display_url', 'display', 'manufacturer', 'default_platform', 'model', 'slug', 'part_number', 'u_height', 'exclude_from_utilization', 'is_full_depth', 'subdevice_role', 'airflow', 'weight', - 'weight_unit', 'front_image', 'rear_image', 'description', 'comments', 'tags', 'custom_fields', + 'weight_unit', 'front_image', 'rear_image', 'description', 'owner', 'comments', 'tags', 'custom_fields', 'created', 'last_updated', 'device_count', 'console_port_template_count', 'console_server_port_template_count', 'power_port_template_count', 'power_outlet_template_count', 'interface_template_count', 'front_port_template_count', 'rear_port_template_count', @@ -63,18 +61,18 @@ class DeviceTypeSerializer(NetBoxModelSerializer): brief_fields = ('id', 'url', 'display', 'manufacturer', 'model', 'slug', 'description', 'device_count') -class ModuleTypeProfileSerializer(NetBoxModelSerializer): +class ModuleTypeProfileSerializer(PrimaryModelSerializer): class Meta: model = ModuleTypeProfile fields = [ - 'id', 'url', 'display_url', 'display', 'name', 'description', 'schema', 'comments', 'tags', 'custom_fields', - 'created', 'last_updated', + 'id', 'url', 'display_url', 'display', 'name', 'description', 'schema', 'owner', 'comments', 'tags', + 'custom_fields', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'name', 'description') -class ModuleTypeSerializer(NetBoxModelSerializer): +class ModuleTypeSerializer(PrimaryModelSerializer): profile = ModuleTypeProfileSerializer( nested=True, required=False, @@ -100,12 +98,13 @@ class ModuleTypeSerializer(NetBoxModelSerializer): required=False, allow_null=True ) + module_count = serializers.IntegerField(read_only=True) class Meta: model = ModuleType fields = [ 'id', 'url', 'display_url', 'display', 'profile', 'manufacturer', 'model', 'part_number', 'airflow', - 'weight', 'weight_unit', 'description', 'attributes', 'comments', 'tags', 'custom_fields', 'created', - 'last_updated', + 'weight', 'weight_unit', 'description', 'attributes', 'owner', 'comments', 'tags', 'custom_fields', + 'created', 'last_updated', 'module_count', ] - brief_fields = ('id', 'url', 'display', 'profile', 'manufacturer', 'model', 'description') + brief_fields = ('id', 'url', 'display', 'profile', 'manufacturer', 'model', 'description', 'module_count') diff --git a/netbox/dcim/api/serializers_/manufacturers.py b/netbox/dcim/api/serializers_/manufacturers.py index bd064f411..42944be46 100644 --- a/netbox/dcim/api/serializers_/manufacturers.py +++ b/netbox/dcim/api/serializers_/manufacturers.py @@ -1,23 +1,25 @@ from dcim.models import Manufacturer from netbox.api.fields import RelatedObjectCountField -from netbox.api.serializers import NetBoxModelSerializer +from netbox.api.serializers import OrganizationalModelSerializer __all__ = ( 'ManufacturerSerializer', ) -class ManufacturerSerializer(NetBoxModelSerializer): +class ManufacturerSerializer(OrganizationalModelSerializer): # Related object counts devicetype_count = RelatedObjectCountField('device_types') + moduletype_count = RelatedObjectCountField('module_types') inventoryitem_count = RelatedObjectCountField('inventory_items') platform_count = RelatedObjectCountField('platforms') class Meta: model = Manufacturer fields = [ - 'id', 'url', 'display_url', 'display', 'name', 'slug', 'description', 'tags', 'custom_fields', - 'created', 'last_updated', 'devicetype_count', 'inventoryitem_count', 'platform_count', + 'id', 'url', 'display_url', 'display', 'name', 'slug', 'description', 'owner', 'comments', 'tags', + 'custom_fields', 'created', 'last_updated', 'devicetype_count', 'moduletype_count', 'inventoryitem_count', + 'platform_count', ] brief_fields = ('id', 'url', 'display', 'name', 'slug', 'description') diff --git a/netbox/dcim/api/serializers_/platforms.py b/netbox/dcim/api/serializers_/platforms.py index 08f8a64a8..c86bd9773 100644 --- a/netbox/dcim/api/serializers_/platforms.py +++ b/netbox/dcim/api/serializers_/platforms.py @@ -24,7 +24,7 @@ class PlatformSerializer(NestedGroupModelSerializer): model = Platform fields = [ 'id', 'url', 'display_url', 'display', 'parent', 'name', 'slug', 'manufacturer', 'config_template', - 'description', 'comments', 'tags', 'custom_fields', 'created', 'last_updated', 'device_count', + 'description', 'owner', 'comments', 'tags', 'custom_fields', 'created', 'last_updated', 'device_count', 'virtualmachine_count', '_depth', ] brief_fields = ( diff --git a/netbox/dcim/api/serializers_/power.py b/netbox/dcim/api/serializers_/power.py index 4c2cf54fb..a9f83cdbe 100644 --- a/netbox/dcim/api/serializers_/power.py +++ b/netbox/dcim/api/serializers_/power.py @@ -1,7 +1,7 @@ from dcim.choices import * from dcim.models import PowerFeed, PowerPanel from netbox.api.fields import ChoiceField, RelatedObjectCountField -from netbox.api.serializers import NetBoxModelSerializer +from netbox.api.serializers import PrimaryModelSerializer from tenancy.api.serializers_.tenants import TenantSerializer from .base import ConnectedEndpointsSerializer from .cables import CabledObjectSerializer @@ -14,7 +14,7 @@ __all__ = ( ) -class PowerPanelSerializer(NetBoxModelSerializer): +class PowerPanelSerializer(PrimaryModelSerializer): site = SiteSerializer(nested=True) location = LocationSerializer( nested=True, @@ -29,13 +29,13 @@ class PowerPanelSerializer(NetBoxModelSerializer): class Meta: model = PowerPanel fields = [ - 'id', 'url', 'display_url', 'display', 'site', 'location', 'name', 'description', 'comments', 'tags', - 'custom_fields', 'powerfeed_count', 'created', 'last_updated', + 'id', 'url', 'display_url', 'display', 'site', 'location', 'name', 'description', 'owner', 'comments', + 'tags', 'custom_fields', 'powerfeed_count', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'name', 'description', 'powerfeed_count') -class PowerFeedSerializer(NetBoxModelSerializer, CabledObjectSerializer, ConnectedEndpointsSerializer): +class PowerFeedSerializer(PrimaryModelSerializer, CabledObjectSerializer, ConnectedEndpointsSerializer): power_panel = PowerPanelSerializer(nested=True) rack = RackSerializer( nested=True, @@ -71,6 +71,7 @@ class PowerFeedSerializer(NetBoxModelSerializer, CabledObjectSerializer, Connect 'id', 'url', 'display_url', 'display', 'power_panel', 'rack', 'name', 'status', 'type', 'supply', 'phase', 'voltage', 'amperage', 'max_utilization', 'mark_connected', 'cable', 'cable_end', 'link_peers', 'link_peers_type', 'connected_endpoints', 'connected_endpoints_type', 'connected_endpoints_reachable', - 'description', 'tenant', 'comments', 'tags', 'custom_fields', 'created', 'last_updated', '_occupied', + 'description', 'tenant', 'owner', 'comments', 'tags', 'custom_fields', 'created', 'last_updated', + '_occupied', ] brief_fields = ('id', 'url', 'display', 'name', 'description', 'cable', '_occupied') diff --git a/netbox/dcim/api/serializers_/racks.py b/netbox/dcim/api/serializers_/racks.py index 9c2c739fe..e6f15ccfc 100644 --- a/netbox/dcim/api/serializers_/racks.py +++ b/netbox/dcim/api/serializers_/racks.py @@ -5,7 +5,7 @@ from dcim.choices import * from dcim.constants import * from dcim.models import Rack, RackReservation, RackRole, RackType from netbox.api.fields import ChoiceField, RelatedObjectCountField -from netbox.api.serializers import NetBoxModelSerializer +from netbox.api.serializers import OrganizationalModelSerializer, PrimaryModelSerializer from netbox.choices import * from netbox.config import ConfigItem from tenancy.api.serializers_.tenants import TenantSerializer @@ -22,7 +22,7 @@ __all__ = ( ) -class RackRoleSerializer(NetBoxModelSerializer): +class RackRoleSerializer(OrganizationalModelSerializer): # Related object counts rack_count = RelatedObjectCountField('racks') @@ -30,13 +30,13 @@ class RackRoleSerializer(NetBoxModelSerializer): class Meta: model = RackRole fields = [ - 'id', 'url', 'display_url', 'display', 'name', 'slug', 'color', 'description', 'tags', 'custom_fields', - 'created', 'last_updated', 'rack_count', + 'id', 'url', 'display_url', 'display', 'name', 'slug', 'color', 'description', 'owner', 'comments', 'tags', + 'custom_fields', 'created', 'last_updated', 'rack_count', ] brief_fields = ('id', 'url', 'display', 'name', 'slug', 'description', 'rack_count') -class RackBaseSerializer(NetBoxModelSerializer): +class RackBaseSerializer(PrimaryModelSerializer): form_factor = ChoiceField( choices=RackFormFactorChoices, allow_blank=True, @@ -62,19 +62,18 @@ class RackBaseSerializer(NetBoxModelSerializer): class RackTypeSerializer(RackBaseSerializer): - manufacturer = ManufacturerSerializer( - nested=True - ) + manufacturer = ManufacturerSerializer(nested=True) + rack_count = serializers.IntegerField(read_only=True) class Meta: model = RackType fields = [ 'id', 'url', 'display_url', 'display', 'manufacturer', 'model', 'slug', 'description', 'form_factor', 'width', 'u_height', 'starting_unit', 'desc_units', 'outer_width', 'outer_height', 'outer_depth', - 'outer_unit', 'weight', 'max_weight', 'weight_unit', 'mounting_depth', 'description', 'comments', 'tags', - 'custom_fields', 'created', 'last_updated', + 'outer_unit', 'weight', 'max_weight', 'weight_unit', 'mounting_depth', 'description', 'owner', 'comments', + 'tags', 'custom_fields', 'created', 'last_updated', 'rack_count', ] - brief_fields = ('id', 'url', 'display', 'manufacturer', 'model', 'slug', 'description') + brief_fields = ('id', 'url', 'display', 'manufacturer', 'model', 'slug', 'description', 'rack_count') class RackSerializer(RackBaseSerializer): @@ -130,13 +129,13 @@ class RackSerializer(RackBaseSerializer): 'id', 'url', 'display_url', 'display', 'name', 'facility_id', 'site', 'location', 'tenant', 'status', 'role', 'serial', 'asset_tag', 'rack_type', 'form_factor', 'width', 'u_height', 'starting_unit', 'weight', 'max_weight', 'weight_unit', 'desc_units', 'outer_width', 'outer_height', 'outer_depth', 'outer_unit', - 'mounting_depth', 'airflow', 'description', 'comments', 'tags', 'custom_fields', - 'created', 'last_updated', 'device_count', 'powerfeed_count', + 'mounting_depth', 'airflow', 'description', 'owner', 'comments', 'tags', 'custom_fields', 'created', + 'last_updated', 'device_count', 'powerfeed_count', ] brief_fields = ('id', 'url', 'display', 'name', 'description', 'device_count') -class RackReservationSerializer(NetBoxModelSerializer): +class RackReservationSerializer(PrimaryModelSerializer): rack = RackSerializer( nested=True, ) @@ -157,7 +156,7 @@ class RackReservationSerializer(NetBoxModelSerializer): model = RackReservation fields = [ 'id', 'url', 'display_url', 'display', 'rack', 'units', 'status', 'created', 'last_updated', 'user', - 'tenant', 'description', 'comments', 'tags', 'custom_fields', + 'tenant', 'description', 'owner', 'comments', 'tags', 'custom_fields', ] brief_fields = ('id', 'url', 'display', 'status', 'user', 'description', 'units') diff --git a/netbox/dcim/api/serializers_/roles.py b/netbox/dcim/api/serializers_/roles.py index 0f83655a6..a1c1d2be9 100644 --- a/netbox/dcim/api/serializers_/roles.py +++ b/netbox/dcim/api/serializers_/roles.py @@ -3,7 +3,7 @@ from rest_framework import serializers from dcim.models import DeviceRole, InventoryItemRole from extras.api.serializers_.configtemplates import ConfigTemplateSerializer from netbox.api.fields import RelatedObjectCountField -from netbox.api.serializers import NestedGroupModelSerializer, NetBoxModelSerializer +from netbox.api.serializers import NestedGroupModelSerializer, OrganizationalModelSerializer from .nested import NestedDeviceRoleSerializer __all__ = ( @@ -23,14 +23,14 @@ class DeviceRoleSerializer(NestedGroupModelSerializer): fields = [ 'id', 'url', 'display_url', 'display', 'name', 'slug', 'color', 'vm_role', 'config_template', 'parent', 'description', 'tags', 'custom_fields', 'created', 'last_updated', 'device_count', 'virtualmachine_count', - 'comments', '_depth', + 'owner', 'comments', '_depth', ] brief_fields = ( 'id', 'url', 'display', 'name', 'slug', 'description', 'device_count', 'virtualmachine_count', '_depth' ) -class InventoryItemRoleSerializer(NetBoxModelSerializer): +class InventoryItemRoleSerializer(OrganizationalModelSerializer): # Related object counts inventoryitem_count = RelatedObjectCountField('inventory_items') @@ -38,7 +38,7 @@ class InventoryItemRoleSerializer(NetBoxModelSerializer): class Meta: model = InventoryItemRole fields = [ - 'id', 'url', 'display_url', 'display', 'name', 'slug', 'color', 'description', 'tags', 'custom_fields', - 'created', 'last_updated', 'inventoryitem_count', + 'id', 'url', 'display_url', 'display', 'name', 'slug', 'color', 'description', 'owner', 'comments', 'tags', + 'custom_fields', 'created', 'last_updated', 'inventoryitem_count', ] brief_fields = ('id', 'url', 'display', 'name', 'slug', 'description', 'inventoryitem_count') diff --git a/netbox/dcim/api/serializers_/sites.py b/netbox/dcim/api/serializers_/sites.py index 90f7b5d35..d0f632945 100644 --- a/netbox/dcim/api/serializers_/sites.py +++ b/netbox/dcim/api/serializers_/sites.py @@ -6,7 +6,7 @@ from dcim.models import Location, Region, Site, SiteGroup from ipam.api.serializers_.asns import ASNSerializer from ipam.models import ASN from netbox.api.fields import ChoiceField, RelatedObjectCountField, SerializedPKRelatedField -from netbox.api.serializers import NestedGroupModelSerializer, NetBoxModelSerializer +from netbox.api.serializers import NestedGroupModelSerializer, PrimaryModelSerializer from tenancy.api.serializers_.tenants import TenantSerializer from .nested import NestedLocationSerializer, NestedRegionSerializer, NestedSiteGroupSerializer @@ -27,7 +27,7 @@ class RegionSerializer(NestedGroupModelSerializer): model = Region fields = [ 'id', 'url', 'display_url', 'display', 'name', 'slug', 'parent', 'description', 'tags', 'custom_fields', - 'created', 'last_updated', 'site_count', 'prefix_count', 'comments', '_depth', + 'created', 'last_updated', 'site_count', 'prefix_count', 'owner', 'comments', '_depth', ] brief_fields = ('id', 'url', 'display', 'name', 'slug', 'description', 'site_count', '_depth') @@ -41,12 +41,12 @@ class SiteGroupSerializer(NestedGroupModelSerializer): model = SiteGroup fields = [ 'id', 'url', 'display_url', 'display', 'name', 'slug', 'parent', 'description', 'tags', 'custom_fields', - 'created', 'last_updated', 'site_count', 'prefix_count', 'comments', '_depth', + 'created', 'last_updated', 'site_count', 'prefix_count', 'owner', 'comments', '_depth', ] brief_fields = ('id', 'url', 'display', 'name', 'slug', 'description', 'site_count', '_depth') -class SiteSerializer(NetBoxModelSerializer): +class SiteSerializer(PrimaryModelSerializer): status = ChoiceField(choices=SiteStatusChoices, required=False) region = RegionSerializer(nested=True, required=False, allow_null=True) group = SiteGroupSerializer(nested=True, required=False, allow_null=True) @@ -72,7 +72,7 @@ class SiteSerializer(NetBoxModelSerializer): model = Site fields = [ 'id', 'url', 'display_url', 'display', 'name', 'slug', 'status', 'region', 'group', 'tenant', 'facility', - 'time_zone', 'description', 'physical_address', 'shipping_address', 'latitude', 'longitude', + 'time_zone', 'description', 'physical_address', 'shipping_address', 'latitude', 'longitude', 'owner', 'comments', 'asns', 'tags', 'custom_fields', 'created', 'last_updated', 'circuit_count', 'device_count', 'prefix_count', 'rack_count', 'virtualmachine_count', 'vlan_count', ] @@ -93,6 +93,6 @@ class LocationSerializer(NestedGroupModelSerializer): fields = [ 'id', 'url', 'display_url', 'display', 'name', 'slug', 'site', 'parent', 'status', 'tenant', 'facility', 'description', 'tags', 'custom_fields', 'created', 'last_updated', 'rack_count', 'device_count', - 'prefix_count', 'comments', '_depth', + 'prefix_count', 'owner', 'comments', '_depth', ] brief_fields = ('id', 'url', 'display', 'name', 'slug', 'description', 'rack_count', '_depth') diff --git a/netbox/dcim/api/serializers_/virtualchassis.py b/netbox/dcim/api/serializers_/virtualchassis.py index a93d2833f..5e2ac7bec 100644 --- a/netbox/dcim/api/serializers_/virtualchassis.py +++ b/netbox/dcim/api/serializers_/virtualchassis.py @@ -1,7 +1,7 @@ from rest_framework import serializers from dcim.models import VirtualChassis -from netbox.api.serializers import NetBoxModelSerializer +from netbox.api.serializers import PrimaryModelSerializer from .nested import NestedDeviceSerializer __all__ = ( @@ -9,7 +9,7 @@ __all__ = ( ) -class VirtualChassisSerializer(NetBoxModelSerializer): +class VirtualChassisSerializer(PrimaryModelSerializer): master = NestedDeviceSerializer(required=False, allow_null=True, default=None) members = NestedDeviceSerializer(many=True, read_only=True) @@ -19,7 +19,7 @@ class VirtualChassisSerializer(NetBoxModelSerializer): class Meta: model = VirtualChassis fields = [ - 'id', 'url', 'display_url', 'display', 'name', 'domain', 'master', 'description', 'comments', 'tags', - 'custom_fields', 'created', 'last_updated', 'member_count', 'members', + 'id', 'url', 'display_url', 'display', 'name', 'domain', 'master', 'description', 'owner', 'comments', + 'tags', 'custom_fields', 'created', 'last_updated', 'member_count', 'members', ] brief_fields = ('id', 'url', 'display', 'name', 'master', 'description', 'member_count') diff --git a/netbox/dcim/api/views.py b/netbox/dcim/api/views.py index ffc0ca4d6..9ecaaa76a 100644 --- a/netbox/dcim/api/views.py +++ b/netbox/dcim/api/views.py @@ -16,7 +16,7 @@ from extras.api.mixins import ConfigContextQuerySetMixin, RenderConfigMixin from netbox.api.authentication import IsAuthenticatedOrLoginNotRequired from netbox.api.metadata import ContentTypeMetadata from netbox.api.pagination import StripCountAnnotationsPaginator -from netbox.api.viewsets import NetBoxModelViewSet, MPTTLockedMixin +from netbox.api.viewsets import NetBoxModelViewSet, MPTTLockedMixin, NetBoxReadOnlyModelViewSet from netbox.api.viewsets.mixins import SequentialBulkCreatesMixin from utilities.api import get_serializer_for_model from utilities.query_functions import CollateAsChar @@ -563,7 +563,7 @@ class CableViewSet(NetBoxModelViewSet): filterset_class = filtersets.CableFilterSet -class CableTerminationViewSet(NetBoxModelViewSet): +class CableTerminationViewSet(NetBoxReadOnlyModelViewSet): metadata_class = ContentTypeMetadata queryset = CableTermination.objects.all() serializer_class = serializers.CableTerminationSerializer diff --git a/netbox/dcim/apps.py b/netbox/dcim/apps.py index 9653d3b93..67ff17489 100644 --- a/netbox/dcim/apps.py +++ b/netbox/dcim/apps.py @@ -11,7 +11,7 @@ class DCIMConfig(AppConfig): from netbox.models.features import register_models from utilities.counters import connect_counters from . import signals, search # noqa: F401 - from .models import CableTermination, Device, DeviceType, VirtualChassis + from .models import CableTermination, Device, DeviceType, ModuleType, RackType, VirtualChassis # Register models register_models(*self.get_models()) @@ -31,4 +31,4 @@ class DCIMConfig(AppConfig): }) # Register counters - connect_counters(Device, DeviceType, VirtualChassis) + connect_counters(Device, DeviceType, ModuleType, RackType, VirtualChassis) diff --git a/netbox/dcim/cable_profiles.py b/netbox/dcim/cable_profiles.py new file mode 100644 index 000000000..8d5e787a3 --- /dev/null +++ b/netbox/dcim/cable_profiles.py @@ -0,0 +1,390 @@ +from django.core.exceptions import ValidationError +from django.utils.translation import gettext_lazy as _ + +from dcim.choices import CableEndChoices +from dcim.models import CableTermination + + +class BaseCableProfile: + """Base class for representing a cable profile.""" + + # Mappings of connectors to the number of positions presented by each, at either end of the cable. For example, a + # 12-strand MPO fiber cable would have one connector at either end with six positions (six bidirectional fiber + # pairs). + a_connectors = {} + b_connectors = {} + + # Defined a mapping of A/B connector & position pairings. If not defined, all positions are presumed to be + # symmetrical (i.e. 1:1 on side A maps to 1:1 on side B). If defined, it must be constructed as a dictionary of + # two-item tuples, e.g. {(1, 1): (1, 1)}. + _mapping = None + + def clean(self, cable): + # Enforce maximum terminations limits + a_terminations_count = len(cable.a_terminations) + b_terminations_count = len(cable.b_terminations) + max_a_terminations = len(self.a_connectors) + max_b_terminations = len(self.b_connectors) + if a_terminations_count > max_a_terminations: + raise ValidationError({ + 'a_terminations': _( + 'A side of cable has {count} terminations but only {max} are permitted for profile {profile}' + ).format( + count=a_terminations_count, + profile=cable.get_profile_display(), + max=max_a_terminations, + ) + }) + if b_terminations_count > max_b_terminations: + raise ValidationError({ + 'b_terminations': _( + 'B side of cable has {count} terminations but only {max} are permitted for profile {profile}' + ).format( + count=b_terminations_count, + profile=cable.get_profile_display(), + max=max_b_terminations, + ) + }) + + def get_mapped_position(self, side, connector, position): + """ + Return the mapped far-end connector & position for a given cable end the local connector & position. + """ + # By default, assume all positions are symmetrical. + if self._mapping: + return self._mapping.get((connector, position)) + return connector, position + + def get_peer_termination(self, termination, position): + """ + Given a terminating object, return the peer terminating object (if any) on the opposite end of the cable. + """ + try: + connector, position = self.get_mapped_position( + termination.cable_end, + termination.cable_connector, + position + ) + except TypeError: + raise ValueError( + f"Could not map connector {termination.cable_connector} position {position} on side " + f"{termination.cable_end}" + ) + try: + ct = CableTermination.objects.get( + cable=termination.cable, + cable_end=termination.opposite_cable_end, + connector=connector, + positions__contains=[position], + ) + return ct.termination, position + except CableTermination.DoesNotExist: + return None, None + + @staticmethod + def get_position_list(n): + """Return a list of integers from 1 to n, inclusive.""" + return list(range(1, n + 1)) + + +# Profile naming: +# - Single: One connector per side, with one or more positions +# - Trunk: Two or more connectors per side, with one or more positions per connector +# - Breakout: One or more connectors on the A side which map to a greater number of B side connectors +# - Shuffle: A cable with nonlinear position mappings between sides + +class Single1C1PCableProfile(BaseCableProfile): + a_connectors = { + 1: 1, + } + b_connectors = a_connectors + + +class Single1C2PCableProfile(BaseCableProfile): + a_connectors = { + 1: 2, + } + b_connectors = a_connectors + + +class Single1C4PCableProfile(BaseCableProfile): + a_connectors = { + 1: 4, + } + b_connectors = a_connectors + + +class Single1C6PCableProfile(BaseCableProfile): + a_connectors = { + 1: 6, + } + b_connectors = a_connectors + + +class Single1C8PCableProfile(BaseCableProfile): + a_connectors = { + 1: 8, + } + b_connectors = a_connectors + + +class Single1C12PCableProfile(BaseCableProfile): + a_connectors = { + 1: 12, + } + b_connectors = a_connectors + + +class Single1C16PCableProfile(BaseCableProfile): + a_connectors = { + 1: 16, + } + b_connectors = a_connectors + + +class Trunk2C1PCableProfile(BaseCableProfile): + a_connectors = { + 1: 1, + 2: 1, + } + b_connectors = a_connectors + + +class Trunk2C2PCableProfile(BaseCableProfile): + a_connectors = { + 1: 2, + 2: 2, + } + b_connectors = a_connectors + + +class Trunk2C4PCableProfile(BaseCableProfile): + a_connectors = { + 1: 4, + 2: 4, + } + b_connectors = a_connectors + + +class Trunk2C6PCableProfile(BaseCableProfile): + a_connectors = { + 1: 6, + 2: 6, + } + b_connectors = a_connectors + + +class Trunk2C8PCableProfile(BaseCableProfile): + a_connectors = { + 1: 8, + 2: 8, + } + b_connectors = a_connectors + + +class Trunk2C12PCableProfile(BaseCableProfile): + a_connectors = { + 1: 12, + 2: 12, + } + b_connectors = a_connectors + + +class Trunk4C1PCableProfile(BaseCableProfile): + a_connectors = { + 1: 1, + 2: 1, + 3: 1, + 4: 1, + } + b_connectors = a_connectors + + +class Trunk4C2PCableProfile(BaseCableProfile): + a_connectors = { + 1: 2, + 2: 2, + 3: 2, + 4: 2, + } + b_connectors = a_connectors + + +class Trunk4C4PCableProfile(BaseCableProfile): + a_connectors = { + 1: 4, + 2: 4, + 3: 4, + 4: 4, + } + b_connectors = a_connectors + + +class Trunk4C6PCableProfile(BaseCableProfile): + a_connectors = { + 1: 6, + 2: 6, + 3: 6, + 4: 6, + } + b_connectors = a_connectors + + +class Trunk4C8PCableProfile(BaseCableProfile): + a_connectors = { + 1: 8, + 2: 8, + 3: 8, + 4: 8, + } + b_connectors = a_connectors + + +class Trunk8C4PCableProfile(BaseCableProfile): + a_connectors = { + 1: 4, + 2: 4, + 3: 4, + 4: 4, + 5: 4, + 6: 4, + 7: 4, + 8: 4, + } + b_connectors = a_connectors + + +class Breakout1C4Px4C1PCableProfile(BaseCableProfile): + a_connectors = { + 1: 4, + } + b_connectors = { + 1: 1, + 2: 1, + 3: 1, + 4: 1, + } + _mapping = { + (1, 1): (1, 1), + (1, 2): (2, 1), + (1, 3): (3, 1), + (1, 4): (4, 1), + (2, 1): (1, 2), + (3, 1): (1, 3), + (4, 1): (1, 4), + } + + +class Breakout1C6Px6C1PCableProfile(BaseCableProfile): + a_connectors = { + 1: 6, + } + b_connectors = { + 1: 1, + 2: 1, + 3: 1, + 4: 1, + 5: 1, + 6: 1, + } + _mapping = { + (1, 1): (1, 1), + (1, 2): (2, 1), + (1, 3): (3, 1), + (1, 4): (4, 1), + (1, 5): (5, 1), + (1, 6): (6, 1), + (2, 1): (1, 2), + (3, 1): (1, 3), + (4, 1): (1, 4), + (5, 1): (1, 5), + (6, 1): (1, 6), + } + + +class Trunk2C4PShuffleCableProfile(BaseCableProfile): + a_connectors = { + 1: 4, + 2: 4, + } + b_connectors = a_connectors + _mapping = { + (1, 1): (1, 1), + (1, 2): (1, 2), + (1, 3): (2, 1), + (1, 4): (2, 2), + (2, 1): (1, 3), + (2, 2): (1, 4), + (2, 3): (2, 3), + (2, 4): (2, 4), + } + + +class Trunk4C4PShuffleCableProfile(BaseCableProfile): + a_connectors = { + 1: 4, + 2: 4, + 3: 4, + 4: 4, + } + b_connectors = a_connectors + _mapping = { + (1, 1): (1, 1), + (1, 2): (2, 1), + (1, 3): (3, 1), + (1, 4): (4, 1), + (2, 1): (1, 2), + (2, 2): (2, 2), + (2, 3): (3, 2), + (2, 4): (4, 2), + (3, 1): (1, 3), + (3, 2): (2, 3), + (3, 3): (3, 3), + (3, 4): (4, 3), + (4, 1): (1, 4), + (4, 2): (2, 4), + (4, 3): (3, 4), + (4, 4): (4, 4), + } + + +class Breakout2C4Px8C1PShuffleCableProfile(BaseCableProfile): + a_connectors = { + 1: 4, + 2: 4, + } + b_connectors = { + 1: 1, + 2: 1, + 3: 1, + 4: 1, + 5: 1, + 6: 1, + 7: 1, + 8: 1, + } + _a_mapping = { + (1, 1): (1, 1), + (1, 2): (2, 1), + (1, 3): (5, 1), + (1, 4): (6, 1), + (2, 1): (3, 1), + (2, 2): (4, 1), + (2, 3): (7, 1), + (2, 4): (8, 1), + } + _b_mapping = { + (1, 1): (1, 1), + (2, 1): (1, 2), + (3, 1): (2, 1), + (4, 1): (2, 2), + (5, 1): (1, 3), + (6, 1): (1, 4), + (7, 1): (2, 3), + (8, 1): (2, 4), + } + + def get_mapped_position(self, side, connector, position): + if side.upper() == CableEndChoices.SIDE_A: + return self._a_mapping.get((connector, position)) + return self._b_mapping.get((connector, position)) diff --git a/netbox/dcim/choices.py b/netbox/dcim/choices.py index 977fe7101..1be3f7ca4 100644 --- a/netbox/dcim/choices.py +++ b/netbox/dcim/choices.py @@ -1721,6 +1721,77 @@ class PortTypeChoices(ChoiceSet): # Cables/links # +class CableProfileChoices(ChoiceSet): + # Singles + SINGLE_1C1P = 'single-1c1p' + SINGLE_1C2P = 'single-1c2p' + SINGLE_1C4P = 'single-1c4p' + SINGLE_1C6P = 'single-1c6p' + SINGLE_1C8P = 'single-1c8p' + SINGLE_1C12P = 'single-1c12p' + SINGLE_1C16P = 'single-1c16p' + # Trunks + TRUNK_2C1P = 'trunk-2c1p' + TRUNK_2C2P = 'trunk-2c2p' + TRUNK_2C4P = 'trunk-2c4p' + TRUNK_2C4P_SHUFFLE = 'trunk-2c4p-shuffle' + TRUNK_2C6P = 'trunk-2c6p' + TRUNK_2C8P = 'trunk-2c8p' + TRUNK_2C12P = 'trunk-2c12p' + TRUNK_4C1P = 'trunk-4c1p' + TRUNK_4C2P = 'trunk-4c2p' + TRUNK_4C4P = 'trunk-4c4p' + TRUNK_4C4P_SHUFFLE = 'trunk-4c4p-shuffle' + TRUNK_4C6P = 'trunk-4c6p' + TRUNK_4C8P = 'trunk-4c8p' + TRUNK_8C4P = 'trunk-8c4p' + # Breakouts + BREAKOUT_1C4P_4C1P = 'breakout-1c4p-4c1p' + BREAKOUT_1C6P_6C1P = 'breakout-1c6p-6c1p' + BREAKOUT_2C4P_8C1P_SHUFFLE = 'breakout-2c4p-8c1p-shuffle' + + CHOICES = ( + ( + _('Single'), + ( + (SINGLE_1C1P, _('1C1P')), + (SINGLE_1C2P, _('1C2P')), + (SINGLE_1C4P, _('1C4P')), + (SINGLE_1C6P, _('1C6P')), + (SINGLE_1C8P, _('1C8P')), + (SINGLE_1C12P, _('1C12P')), + (SINGLE_1C16P, _('1C16P')), + ), + ), + ( + _('Trunk'), + ( + (TRUNK_2C1P, _('2C1P trunk')), + (TRUNK_2C2P, _('2C2P trunk')), + (TRUNK_2C4P, _('2C4P trunk')), + (TRUNK_2C4P_SHUFFLE, _('2C4P trunk (shuffle)')), + (TRUNK_2C6P, _('2C6P trunk')), + (TRUNK_2C8P, _('2C8P trunk')), + (TRUNK_2C12P, _('2C12P trunk')), + (TRUNK_4C1P, _('4C1P trunk')), + (TRUNK_4C2P, _('4C2P trunk')), + (TRUNK_4C4P, _('4C4P trunk')), + (TRUNK_4C4P_SHUFFLE, _('4C4P trunk (shuffle)')), + (TRUNK_4C6P, _('4C6P trunk')), + (TRUNK_4C8P, _('4C8P trunk')), + (TRUNK_8C4P, _('8C4P trunk')), + ), + ), + ( + _('Breakout'), + ( + (BREAKOUT_1C4P_4C1P, _('1C4P:4C1P breakout')), + (BREAKOUT_1C6P_6C1P, _('1C6P:6C1P breakout')), + (BREAKOUT_2C4P_8C1P_SHUFFLE, _('2C4P:8C1P breakout (shuffle)')), + ), + ), + ) + class CableTypeChoices(ChoiceSet): # Copper - Twisted Pair (UTP/STP) diff --git a/netbox/dcim/constants.py b/netbox/dcim/constants.py index 387b4d6a7..669345d7c 100644 --- a/netbox/dcim/constants.py +++ b/netbox/dcim/constants.py @@ -20,12 +20,23 @@ RACK_ELEVATION_DEFAULT_MARGIN_WIDTH = 15 RACK_STARTING_UNIT_DEFAULT = 1 +# +# Cables +# + +CABLE_CONNECTOR_MIN = 1 +CABLE_CONNECTOR_MAX = 256 + +CABLE_POSITION_MIN = 1 +CABLE_POSITION_MAX = 1024 + + # # RearPorts # -REARPORT_POSITIONS_MIN = 1 -REARPORT_POSITIONS_MAX = 1024 +PORT_POSITION_MIN = 1 +PORT_POSITION_MAX = 1024 # diff --git a/netbox/dcim/filtersets.py b/netbox/dcim/filtersets.py index c792263b7..e11d32d95 100644 --- a/netbox/dcim/filtersets.py +++ b/netbox/dcim/filtersets.py @@ -11,16 +11,18 @@ from ipam.filtersets import PrimaryIPFilterSet from ipam.models import ASN, IPAddress, VLANTranslationPolicy, VRF from netbox.choices import ColorChoices from netbox.filtersets import ( - AttributeFiltersMixin, BaseFilterSet, ChangeLoggedModelFilterSet, NestedGroupModelFilterSet, NetBoxModelFilterSet, - OrganizationalModelFilterSet, + AttributeFiltersMixin, BaseFilterSet, ChangeLoggedModelFilterSet, NestedGroupModelFilterSet, + OrganizationalModelFilterSet, PrimaryModelFilterSet, NetBoxModelFilterSet, ) from tenancy.filtersets import ContactModelFilterSet, TenancyFilterSet from tenancy.models import * +from users.filterset_mixins import OwnerFilterMixin from users.models import User from utilities.filters import ( ContentTypeFilter, MultiValueCharFilter, MultiValueMACAddressFilter, MultiValueNumberFilter, MultiValueWWNFilter, NumericArrayFilter, TreeNodeMultipleChoiceFilter, ) +from utilities.filtersets import register_filterset from virtualization.models import Cluster, ClusterGroup, VirtualMachine, VMInterface from vpn.models import L2VPN from wireless.choices import WirelessChannelChoices, WirelessRoleChoices @@ -83,6 +85,7 @@ __all__ = ( ) +@register_filterset class RegionFilterSet(NestedGroupModelFilterSet, ContactModelFilterSet): parent_id = django_filters.ModelMultipleChoiceFilter( queryset=Region.objects.all(), @@ -113,6 +116,7 @@ class RegionFilterSet(NestedGroupModelFilterSet, ContactModelFilterSet): fields = ('id', 'name', 'slug', 'description') +@register_filterset class SiteGroupFilterSet(NestedGroupModelFilterSet, ContactModelFilterSet): parent_id = django_filters.ModelMultipleChoiceFilter( queryset=SiteGroup.objects.all(), @@ -143,7 +147,8 @@ class SiteGroupFilterSet(NestedGroupModelFilterSet, ContactModelFilterSet): fields = ('id', 'name', 'slug', 'description') -class SiteFilterSet(NetBoxModelFilterSet, TenancyFilterSet, ContactModelFilterSet): +@register_filterset +class SiteFilterSet(PrimaryModelFilterSet, TenancyFilterSet, ContactModelFilterSet): status = django_filters.MultipleChoiceFilter( choices=SiteStatusChoices, null_value=None @@ -207,6 +212,7 @@ class SiteFilterSet(NetBoxModelFilterSet, TenancyFilterSet, ContactModelFilterSe return queryset.filter(qs_filter).distinct() +@register_filterset class LocationFilterSet(TenancyFilterSet, ContactModelFilterSet, NestedGroupModelFilterSet): region_id = TreeNodeMultipleChoiceFilter( queryset=Region.objects.all(), @@ -286,6 +292,7 @@ class LocationFilterSet(TenancyFilterSet, ContactModelFilterSet, NestedGroupMode return queryset +@register_filterset class RackRoleFilterSet(OrganizationalModelFilterSet): class Meta: @@ -293,7 +300,8 @@ class RackRoleFilterSet(OrganizationalModelFilterSet): fields = ('id', 'name', 'slug', 'color', 'description') -class RackTypeFilterSet(NetBoxModelFilterSet): +@register_filterset +class RackTypeFilterSet(PrimaryModelFilterSet): manufacturer_id = django_filters.ModelMultipleChoiceFilter( queryset=Manufacturer.objects.all(), label=_('Manufacturer (ID)'), @@ -316,6 +324,9 @@ class RackTypeFilterSet(NetBoxModelFilterSet): fields = ( 'id', 'model', 'slug', 'u_height', 'starting_unit', 'desc_units', 'outer_width', 'outer_height', 'outer_depth', 'outer_unit', 'mounting_depth', 'weight', 'max_weight', 'weight_unit', 'description', + + # Counters + 'rack_count', ) def search(self, queryset, name, value): @@ -328,7 +339,8 @@ class RackTypeFilterSet(NetBoxModelFilterSet): ) -class RackFilterSet(NetBoxModelFilterSet, TenancyFilterSet, ContactModelFilterSet): +@register_filterset +class RackFilterSet(PrimaryModelFilterSet, TenancyFilterSet, ContactModelFilterSet): region_id = TreeNodeMultipleChoiceFilter( queryset=Region.objects.all(), field_name='site__region', @@ -444,7 +456,8 @@ class RackFilterSet(NetBoxModelFilterSet, TenancyFilterSet, ContactModelFilterSe ) -class RackReservationFilterSet(NetBoxModelFilterSet, TenancyFilterSet): +@register_filterset +class RackReservationFilterSet(PrimaryModelFilterSet, TenancyFilterSet): rack_id = django_filters.ModelMultipleChoiceFilter( queryset=Rack.objects.all(), label=_('Rack (ID)'), @@ -533,6 +546,7 @@ class RackReservationFilterSet(NetBoxModelFilterSet, TenancyFilterSet): ) +@register_filterset class ManufacturerFilterSet(OrganizationalModelFilterSet, ContactModelFilterSet): class Meta: @@ -540,7 +554,8 @@ class ManufacturerFilterSet(OrganizationalModelFilterSet, ContactModelFilterSet) fields = ('id', 'name', 'slug', 'description') -class DeviceTypeFilterSet(NetBoxModelFilterSet): +@register_filterset +class DeviceTypeFilterSet(PrimaryModelFilterSet): manufacturer_id = django_filters.ModelMultipleChoiceFilter( queryset=Manufacturer.objects.all(), label=_('Manufacturer (ID)'), @@ -626,6 +641,7 @@ class DeviceTypeFilterSet(NetBoxModelFilterSet): 'device_bay_template_count', 'module_bay_template_count', 'inventory_item_template_count', + 'device_count', ) def search(self, queryset, name, value): @@ -682,7 +698,8 @@ class DeviceTypeFilterSet(NetBoxModelFilterSet): return queryset.exclude(inventoryitemtemplates__isnull=value) -class ModuleTypeProfileFilterSet(NetBoxModelFilterSet): +@register_filterset +class ModuleTypeProfileFilterSet(PrimaryModelFilterSet): class Meta: model = ModuleTypeProfile @@ -698,7 +715,8 @@ class ModuleTypeProfileFilterSet(NetBoxModelFilterSet): ) -class ModuleTypeFilterSet(AttributeFiltersMixin, NetBoxModelFilterSet): +@register_filterset +class ModuleTypeFilterSet(AttributeFiltersMixin, PrimaryModelFilterSet): profile_id = django_filters.ModelMultipleChoiceFilter( queryset=ModuleTypeProfile.objects.all(), label=_('Profile (ID)'), @@ -746,7 +764,12 @@ class ModuleTypeFilterSet(AttributeFiltersMixin, NetBoxModelFilterSet): class Meta: model = ModuleType - fields = ('id', 'model', 'part_number', 'airflow', 'weight', 'weight_unit', 'description') + fields = ( + 'id', 'model', 'part_number', 'airflow', 'weight', 'weight_unit', 'description', + + # Counters + 'module_count', + ) def search(self, queryset, name, value): if not value.strip(): @@ -809,6 +832,7 @@ class ModularDeviceTypeComponentFilterSet(DeviceTypeComponentFilterSet): ) +@register_filterset class ConsolePortTemplateFilterSet(ChangeLoggedModelFilterSet, ModularDeviceTypeComponentFilterSet): class Meta: @@ -816,6 +840,7 @@ class ConsolePortTemplateFilterSet(ChangeLoggedModelFilterSet, ModularDeviceType fields = ('id', 'name', 'label', 'type', 'description') +@register_filterset class ConsoleServerPortTemplateFilterSet(ChangeLoggedModelFilterSet, ModularDeviceTypeComponentFilterSet): class Meta: @@ -823,6 +848,7 @@ class ConsoleServerPortTemplateFilterSet(ChangeLoggedModelFilterSet, ModularDevi fields = ('id', 'name', 'label', 'type', 'description') +@register_filterset class PowerPortTemplateFilterSet(ChangeLoggedModelFilterSet, ModularDeviceTypeComponentFilterSet): class Meta: @@ -830,6 +856,7 @@ class PowerPortTemplateFilterSet(ChangeLoggedModelFilterSet, ModularDeviceTypeCo fields = ('id', 'name', 'label', 'type', 'maximum_draw', 'allocated_draw', 'description') +@register_filterset class PowerOutletTemplateFilterSet(ChangeLoggedModelFilterSet, ModularDeviceTypeComponentFilterSet): feed_leg = django_filters.MultipleChoiceFilter( choices=PowerOutletFeedLegChoices, @@ -842,9 +869,10 @@ class PowerOutletTemplateFilterSet(ChangeLoggedModelFilterSet, ModularDeviceType class Meta: model = PowerOutletTemplate - fields = ('id', 'name', 'label', 'type', 'feed_leg', 'description') + fields = ('id', 'name', 'label', 'type', 'color', 'feed_leg', 'description') +@register_filterset class InterfaceTemplateFilterSet(ChangeLoggedModelFilterSet, ModularDeviceTypeComponentFilterSet): type = django_filters.MultipleChoiceFilter( choices=InterfaceTypeChoices, @@ -869,31 +897,43 @@ class InterfaceTemplateFilterSet(ChangeLoggedModelFilterSet, ModularDeviceTypeCo fields = ('id', 'name', 'label', 'type', 'enabled', 'mgmt_only', 'description') +@register_filterset class FrontPortTemplateFilterSet(ChangeLoggedModelFilterSet, ModularDeviceTypeComponentFilterSet): type = django_filters.MultipleChoiceFilter( choices=PortTypeChoices, null_value=None ) rear_port_id = django_filters.ModelMultipleChoiceFilter( - queryset=RearPortTemplate.objects.all() + field_name='mappings__rear_port', + queryset=RearPortTemplate.objects.all(), + to_field_name='rear_port', + label=_('Rear port (ID)'), ) class Meta: model = FrontPortTemplate - fields = ('id', 'name', 'label', 'type', 'color', 'rear_port_position', 'description') + fields = ('id', 'name', 'label', 'type', 'color', 'positions', 'description') +@register_filterset class RearPortTemplateFilterSet(ChangeLoggedModelFilterSet, ModularDeviceTypeComponentFilterSet): type = django_filters.MultipleChoiceFilter( choices=PortTypeChoices, null_value=None ) + front_port_id = django_filters.ModelMultipleChoiceFilter( + field_name='mappings__front_port', + queryset=FrontPort.objects.all(), + to_field_name='front_port', + label=_('Front port (ID)'), + ) class Meta: model = RearPortTemplate fields = ('id', 'name', 'label', 'type', 'color', 'positions', 'description') +@register_filterset class ModuleBayTemplateFilterSet(ChangeLoggedModelFilterSet, ModularDeviceTypeComponentFilterSet): class Meta: @@ -901,6 +941,7 @@ class ModuleBayTemplateFilterSet(ChangeLoggedModelFilterSet, ModularDeviceTypeCo fields = ('id', 'name', 'label', 'position', 'description') +@register_filterset class DeviceBayTemplateFilterSet(ChangeLoggedModelFilterSet, DeviceTypeComponentFilterSet): class Meta: @@ -908,6 +949,7 @@ class DeviceBayTemplateFilterSet(ChangeLoggedModelFilterSet, DeviceTypeComponent fields = ('id', 'name', 'label', 'description') +@register_filterset class InventoryItemTemplateFilterSet(ChangeLoggedModelFilterSet, DeviceTypeComponentFilterSet): parent_id = django_filters.ModelMultipleChoiceFilter( queryset=InventoryItemTemplate.objects.all(), @@ -951,7 +993,8 @@ class InventoryItemTemplateFilterSet(ChangeLoggedModelFilterSet, DeviceTypeCompo return queryset.filter(qs_filter) -class DeviceRoleFilterSet(OrganizationalModelFilterSet): +@register_filterset +class DeviceRoleFilterSet(NestedGroupModelFilterSet): config_template_id = django_filters.ModelMultipleChoiceFilter( queryset=ConfigTemplate.objects.all(), label=_('Config template (ID)'), @@ -985,7 +1028,8 @@ class DeviceRoleFilterSet(OrganizationalModelFilterSet): fields = ('id', 'name', 'slug', 'color', 'vm_role', 'description') -class PlatformFilterSet(OrganizationalModelFilterSet): +@register_filterset +class PlatformFilterSet(NestedGroupModelFilterSet): parent_id = django_filters.ModelMultipleChoiceFilter( queryset=Platform.objects.all(), label=_('Immediate parent platform (ID)'), @@ -1042,8 +1086,9 @@ class PlatformFilterSet(OrganizationalModelFilterSet): return queryset.filter(Q(manufacturer=None) | Q(manufacturer__device_types=value)) +@register_filterset class DeviceFilterSet( - NetBoxModelFilterSet, + PrimaryModelFilterSet, TenancyFilterSet, ContactModelFilterSet, LocalConfigContextFilterSet, @@ -1344,7 +1389,8 @@ class DeviceFilterSet( return queryset.exclude(params) -class VirtualDeviceContextFilterSet(NetBoxModelFilterSet, TenancyFilterSet, PrimaryIPFilterSet): +@register_filterset +class VirtualDeviceContextFilterSet(PrimaryModelFilterSet, TenancyFilterSet, PrimaryIPFilterSet): device_id = django_filters.ModelMultipleChoiceFilter( field_name='device', queryset=Device.objects.all(), @@ -1393,7 +1439,8 @@ class VirtualDeviceContextFilterSet(NetBoxModelFilterSet, TenancyFilterSet, Prim return queryset.exclude(params) -class ModuleFilterSet(NetBoxModelFilterSet): +@register_filterset +class ModuleFilterSet(PrimaryModelFilterSet): manufacturer_id = django_filters.ModelMultipleChoiceFilter( field_name='module_type__manufacturer', queryset=Manufacturer.objects.all(), @@ -1515,7 +1562,7 @@ class ModuleFilterSet(NetBoxModelFilterSet): ).distinct() -class DeviceComponentFilterSet(django_filters.FilterSet): +class DeviceComponentFilterSet(OwnerFilterMixin, NetBoxModelFilterSet): q = django_filters.CharFilter( method='search', label=_('Search'), @@ -1692,12 +1739,8 @@ class PathEndpointFilterSet(django_filters.FilterSet): return queryset.filter(Q(_path__isnull=True) | Q(_path__is_active=False)) -class ConsolePortFilterSet( - ModularDeviceComponentFilterSet, - NetBoxModelFilterSet, - CabledObjectFilterSet, - PathEndpointFilterSet -): +@register_filterset +class ConsolePortFilterSet(ModularDeviceComponentFilterSet, CabledObjectFilterSet, PathEndpointFilterSet): type = django_filters.MultipleChoiceFilter( choices=ConsolePortTypeChoices, null_value=None @@ -1705,15 +1748,13 @@ class ConsolePortFilterSet( class Meta: model = ConsolePort - fields = ('id', 'name', 'label', 'speed', 'description', 'mark_connected', 'cable_end') + fields = ( + 'id', 'name', 'label', 'speed', 'description', 'mark_connected', 'cable_end', 'cable_connector', + ) -class ConsoleServerPortFilterSet( - ModularDeviceComponentFilterSet, - NetBoxModelFilterSet, - CabledObjectFilterSet, - PathEndpointFilterSet -): +@register_filterset +class ConsoleServerPortFilterSet(ModularDeviceComponentFilterSet, CabledObjectFilterSet, PathEndpointFilterSet): type = django_filters.MultipleChoiceFilter( choices=ConsolePortTypeChoices, null_value=None @@ -1721,15 +1762,13 @@ class ConsoleServerPortFilterSet( class Meta: model = ConsoleServerPort - fields = ('id', 'name', 'label', 'speed', 'description', 'mark_connected', 'cable_end') + fields = ( + 'id', 'name', 'label', 'speed', 'description', 'mark_connected', 'cable_end', 'cable_connector', + ) -class PowerPortFilterSet( - ModularDeviceComponentFilterSet, - NetBoxModelFilterSet, - CabledObjectFilterSet, - PathEndpointFilterSet -): +@register_filterset +class PowerPortFilterSet(ModularDeviceComponentFilterSet, CabledObjectFilterSet, PathEndpointFilterSet): type = django_filters.MultipleChoiceFilter( choices=PowerPortTypeChoices, null_value=None @@ -1739,15 +1778,12 @@ class PowerPortFilterSet( model = PowerPort fields = ( 'id', 'name', 'label', 'maximum_draw', 'allocated_draw', 'description', 'mark_connected', 'cable_end', + 'cable_connector', ) -class PowerOutletFilterSet( - ModularDeviceComponentFilterSet, - NetBoxModelFilterSet, - CabledObjectFilterSet, - PathEndpointFilterSet -): +@register_filterset +class PowerOutletFilterSet(ModularDeviceComponentFilterSet, CabledObjectFilterSet, PathEndpointFilterSet): type = django_filters.MultipleChoiceFilter( choices=PowerOutletTypeChoices, null_value=None @@ -1769,10 +1805,12 @@ class PowerOutletFilterSet( model = PowerOutlet fields = ( 'id', 'name', 'status', 'label', 'feed_leg', 'description', 'color', 'mark_connected', 'cable_end', + 'cable_connector', ) -class MACAddressFilterSet(NetBoxModelFilterSet): +@register_filterset +class MACAddressFilterSet(PrimaryModelFilterSet): mac_address = MultiValueMACAddressFilter() assigned_object_type = ContentTypeFilter() device = MultiValueCharFilter( @@ -1953,9 +1991,9 @@ class CommonInterfaceFilterSet(django_filters.FilterSet): ) +@register_filterset class InterfaceFilterSet( ModularDeviceComponentFilterSet, - NetBoxModelFilterSet, CabledObjectFilterSet, PathEndpointFilterSet, CommonInterfaceFilterSet @@ -2077,7 +2115,7 @@ class InterfaceFilterSet( fields = ( 'id', 'name', 'label', 'type', 'enabled', 'mtu', 'mgmt_only', 'poe_mode', 'poe_type', 'mode', 'rf_role', 'rf_channel', 'rf_channel_frequency', 'rf_channel_width', 'tx_power', 'description', 'mark_connected', - 'cable_id', 'cable_end', + 'cable_id', 'cable_end', 'cable_connector', ) def filter_virtual_chassis_member_or_master(self, queryset, name, value): @@ -2116,44 +2154,50 @@ class InterfaceFilterSet( ) -class FrontPortFilterSet( - ModularDeviceComponentFilterSet, - NetBoxModelFilterSet, - CabledObjectFilterSet -): +@register_filterset +class FrontPortFilterSet(ModularDeviceComponentFilterSet, CabledObjectFilterSet): type = django_filters.MultipleChoiceFilter( choices=PortTypeChoices, null_value=None ) rear_port_id = django_filters.ModelMultipleChoiceFilter( - queryset=RearPort.objects.all() + field_name='mappings__rear_port', + queryset=RearPort.objects.all(), + to_field_name='rear_port', + label=_('Rear port (ID)'), ) class Meta: model = FrontPort fields = ( - 'id', 'name', 'label', 'type', 'color', 'rear_port_position', 'description', 'mark_connected', 'cable_end', + 'id', 'name', 'label', 'type', 'color', 'positions', 'description', 'mark_connected', 'cable_end', + 'cable_connector', ) -class RearPortFilterSet( - ModularDeviceComponentFilterSet, - NetBoxModelFilterSet, - CabledObjectFilterSet -): +@register_filterset +class RearPortFilterSet(ModularDeviceComponentFilterSet, CabledObjectFilterSet): type = django_filters.MultipleChoiceFilter( choices=PortTypeChoices, null_value=None ) + front_port_id = django_filters.ModelMultipleChoiceFilter( + field_name='mappings__front_port', + queryset=FrontPort.objects.all(), + to_field_name='front_port', + label=_('Front port (ID)'), + ) class Meta: model = RearPort fields = ( 'id', 'name', 'label', 'type', 'color', 'positions', 'description', 'mark_connected', 'cable_end', + 'cable_connector', ) -class ModuleBayFilterSet(ModularDeviceComponentFilterSet, NetBoxModelFilterSet): +@register_filterset +class ModuleBayFilterSet(ModularDeviceComponentFilterSet): parent_id = django_filters.ModelMultipleChoiceFilter( queryset=ModuleBay.objects.all(), label=_('Parent module bay (ID)'), @@ -2169,7 +2213,8 @@ class ModuleBayFilterSet(ModularDeviceComponentFilterSet, NetBoxModelFilterSet): fields = ('id', 'name', 'label', 'position', 'description') -class DeviceBayFilterSet(DeviceComponentFilterSet, NetBoxModelFilterSet): +@register_filterset +class DeviceBayFilterSet(DeviceComponentFilterSet): installed_device_id = django_filters.ModelMultipleChoiceFilter( queryset=Device.objects.all(), label=_('Installed device (ID)'), @@ -2186,7 +2231,8 @@ class DeviceBayFilterSet(DeviceComponentFilterSet, NetBoxModelFilterSet): fields = ('id', 'name', 'label', 'description') -class InventoryItemFilterSet(DeviceComponentFilterSet, NetBoxModelFilterSet): +@register_filterset +class InventoryItemFilterSet(DeviceComponentFilterSet): parent_id = django_filters.ModelMultipleChoiceFilter( queryset=InventoryItem.objects.all(), label=_('Parent inventory item (ID)'), @@ -2238,6 +2284,7 @@ class InventoryItemFilterSet(DeviceComponentFilterSet, NetBoxModelFilterSet): return queryset.filter(qs_filter) +@register_filterset class InventoryItemRoleFilterSet(OrganizationalModelFilterSet): class Meta: @@ -2245,7 +2292,8 @@ class InventoryItemRoleFilterSet(OrganizationalModelFilterSet): fields = ('id', 'name', 'slug', 'color', 'description') -class VirtualChassisFilterSet(NetBoxModelFilterSet): +@register_filterset +class VirtualChassisFilterSet(PrimaryModelFilterSet): master_id = django_filters.ModelMultipleChoiceFilter( queryset=Device.objects.all(), label=_('Master (ID)'), @@ -2321,7 +2369,8 @@ class VirtualChassisFilterSet(NetBoxModelFilterSet): return queryset.filter(qs_filter).distinct() -class CableFilterSet(TenancyFilterSet, NetBoxModelFilterSet): +@register_filterset +class CableFilterSet(TenancyFilterSet, PrimaryModelFilterSet): termination_a_type = ContentTypeFilter( field_name='terminations__termination_type' ) @@ -2346,6 +2395,9 @@ class CableFilterSet(TenancyFilterSet, NetBoxModelFilterSet): status = django_filters.MultipleChoiceFilter( choices=LinkStatusChoices ) + profile = django_filters.MultipleChoiceFilter( + choices=CableProfileChoices + ) color = django_filters.MultipleChoiceFilter( choices=ColorChoices ) @@ -2490,6 +2542,7 @@ class CableFilterSet(TenancyFilterSet, NetBoxModelFilterSet): return self.filter_by_termination_object(queryset, CircuitTermination, value) +@register_filterset class CableTerminationFilterSet(ChangeLoggedModelFilterSet): termination_type = ContentTypeFilter() @@ -2498,7 +2551,8 @@ class CableTerminationFilterSet(ChangeLoggedModelFilterSet): fields = ('id', 'cable', 'cable_end', 'termination_type', 'termination_id') -class PowerPanelFilterSet(NetBoxModelFilterSet, ContactModelFilterSet): +@register_filterset +class PowerPanelFilterSet(PrimaryModelFilterSet, ContactModelFilterSet): region_id = TreeNodeMultipleChoiceFilter( queryset=Region.objects.all(), field_name='site__region', @@ -2556,7 +2610,8 @@ class PowerPanelFilterSet(NetBoxModelFilterSet, ContactModelFilterSet): return queryset.filter(qs_filter) -class PowerFeedFilterSet(NetBoxModelFilterSet, CabledObjectFilterSet, PathEndpointFilterSet, TenancyFilterSet): +@register_filterset +class PowerFeedFilterSet(PrimaryModelFilterSet, CabledObjectFilterSet, PathEndpointFilterSet, TenancyFilterSet): region_id = TreeNodeMultipleChoiceFilter( queryset=Region.objects.all(), field_name='power_panel__site__region', @@ -2612,7 +2667,7 @@ class PowerFeedFilterSet(NetBoxModelFilterSet, CabledObjectFilterSet, PathEndpoi model = PowerFeed fields = ( 'id', 'name', 'status', 'type', 'supply', 'phase', 'voltage', 'amperage', 'max_utilization', - 'available_power', 'mark_connected', 'cable_end', 'description', + 'available_power', 'mark_connected', 'cable_end', 'cable_connector', 'description', ) def search(self, queryset, name, value): diff --git a/netbox/dcim/forms/bulk_edit.py b/netbox/dcim/forms/bulk_edit.py index 0f5550666..00a0667a7 100644 --- a/netbox/dcim/forms/bulk_edit.py +++ b/netbox/dcim/forms/bulk_edit.py @@ -10,14 +10,14 @@ from extras.models import ConfigTemplate from ipam.choices import VLANQinQRoleChoices from ipam.models import ASN, VLAN, VLANGroup, VRF from netbox.choices import * -from netbox.forms import NetBoxModelBulkEditForm -from netbox.forms.mixins import ChangelogMessageMixin +from netbox.forms import ( + NestedGroupModelBulkEditForm, NetBoxModelBulkEditForm, OrganizationalModelBulkEditForm, PrimaryModelBulkEditForm, +) +from netbox.forms.mixins import ChangelogMessageMixin, OwnerMixin from tenancy.models import Tenant from users.models import User from utilities.forms import BulkEditForm, add_blank_choice, form_from_model -from utilities.forms.fields import ( - ColorField, CommentField, DynamicModelChoiceField, DynamicModelMultipleChoiceField, JSONField, -) +from utilities.forms.fields import ColorField, DynamicModelChoiceField, DynamicModelMultipleChoiceField, JSONField from utilities.forms.rendering import FieldSet, InlineFields, TabbedGroups from utilities.forms.widgets import BulkEditNullBooleanSelect, NumberWithOptions from virtualization.models import Cluster @@ -71,18 +71,12 @@ __all__ = ( ) -class RegionBulkEditForm(NetBoxModelBulkEditForm): +class RegionBulkEditForm(NestedGroupModelBulkEditForm): parent = DynamicModelChoiceField( label=_('Parent'), queryset=Region.objects.all(), required=False ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = Region fieldsets = ( @@ -91,18 +85,12 @@ class RegionBulkEditForm(NetBoxModelBulkEditForm): nullable_fields = ('parent', 'description', 'comments') -class SiteGroupBulkEditForm(NetBoxModelBulkEditForm): +class SiteGroupBulkEditForm(NestedGroupModelBulkEditForm): parent = DynamicModelChoiceField( label=_('Parent'), queryset=SiteGroup.objects.all(), required=False ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = SiteGroup fieldsets = ( @@ -111,7 +99,7 @@ class SiteGroupBulkEditForm(NetBoxModelBulkEditForm): nullable_fields = ('parent', 'description', 'comments') -class SiteBulkEditForm(NetBoxModelBulkEditForm): +class SiteBulkEditForm(PrimaryModelBulkEditForm): status = forms.ChoiceField( label=_('Status'), choices=add_blank_choice(SiteStatusChoices), @@ -162,12 +150,6 @@ class SiteBulkEditForm(NetBoxModelBulkEditForm): choices=add_blank_choice(TimeZoneFormField().choices), required=False ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = Site fieldsets = ( @@ -178,7 +160,7 @@ class SiteBulkEditForm(NetBoxModelBulkEditForm): ) -class LocationBulkEditForm(NetBoxModelBulkEditForm): +class LocationBulkEditForm(NestedGroupModelBulkEditForm): site = DynamicModelChoiceField( label=_('Site'), queryset=Site.objects.all(), @@ -208,12 +190,6 @@ class LocationBulkEditForm(NetBoxModelBulkEditForm): max_length=50, required=False ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = Location fieldsets = ( @@ -222,25 +198,20 @@ class LocationBulkEditForm(NetBoxModelBulkEditForm): nullable_fields = ('parent', 'tenant', 'facility', 'description', 'comments') -class RackRoleBulkEditForm(NetBoxModelBulkEditForm): +class RackRoleBulkEditForm(OrganizationalModelBulkEditForm): color = ColorField( label=_('Color'), required=False ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) model = RackRole fieldsets = ( FieldSet('color', 'description'), ) - nullable_fields = ('color', 'description') + nullable_fields = ('color', 'description', 'comments') -class RackTypeBulkEditForm(NetBoxModelBulkEditForm): +class RackTypeBulkEditForm(PrimaryModelBulkEditForm): manufacturer = DynamicModelChoiceField( label=_('Manufacturer'), queryset=Manufacturer.objects.all(), @@ -310,12 +281,6 @@ class RackTypeBulkEditForm(NetBoxModelBulkEditForm): required=False, initial='' ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = RackType fieldsets = ( @@ -334,7 +299,7 @@ class RackTypeBulkEditForm(NetBoxModelBulkEditForm): ) -class RackBulkEditForm(NetBoxModelBulkEditForm): +class RackBulkEditForm(PrimaryModelBulkEditForm): region = DynamicModelChoiceField( label=_('Region'), queryset=Region.objects.all(), @@ -464,12 +429,6 @@ class RackBulkEditForm(NetBoxModelBulkEditForm): required=False, initial='' ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = Rack fieldsets = ( @@ -485,7 +444,7 @@ class RackBulkEditForm(NetBoxModelBulkEditForm): ) -class RackReservationBulkEditForm(NetBoxModelBulkEditForm): +class RackReservationBulkEditForm(PrimaryModelBulkEditForm): status = forms.ChoiceField( label=_('Status'), choices=add_blank_choice(RackReservationStatusChoices), @@ -502,12 +461,6 @@ class RackReservationBulkEditForm(NetBoxModelBulkEditForm): queryset=Tenant.objects.all(), required=False ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = RackReservation fieldsets = ( @@ -516,21 +469,15 @@ class RackReservationBulkEditForm(NetBoxModelBulkEditForm): nullable_fields = ('comments',) -class ManufacturerBulkEditForm(NetBoxModelBulkEditForm): - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - +class ManufacturerBulkEditForm(OrganizationalModelBulkEditForm): model = Manufacturer fieldsets = ( FieldSet('description'), ) - nullable_fields = ('description',) + nullable_fields = ('description', 'comments') -class DeviceTypeBulkEditForm(NetBoxModelBulkEditForm): +class DeviceTypeBulkEditForm(PrimaryModelBulkEditForm): manufacturer = DynamicModelChoiceField( label=_('Manufacturer'), queryset=Manufacturer.objects.all(), @@ -576,12 +523,6 @@ class DeviceTypeBulkEditForm(NetBoxModelBulkEditForm): required=False, initial='' ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = DeviceType fieldsets = ( @@ -594,17 +535,11 @@ class DeviceTypeBulkEditForm(NetBoxModelBulkEditForm): nullable_fields = ('part_number', 'airflow', 'weight', 'weight_unit', 'description', 'comments') -class ModuleTypeProfileBulkEditForm(NetBoxModelBulkEditForm): +class ModuleTypeProfileBulkEditForm(PrimaryModelBulkEditForm): schema = JSONField( label=_('Schema'), required=False ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = ModuleTypeProfile fieldsets = ( @@ -613,7 +548,7 @@ class ModuleTypeProfileBulkEditForm(NetBoxModelBulkEditForm): nullable_fields = ('description', 'comments') -class ModuleTypeBulkEditForm(NetBoxModelBulkEditForm): +class ModuleTypeBulkEditForm(PrimaryModelBulkEditForm): profile = DynamicModelChoiceField( label=_('Profile'), queryset=ModuleTypeProfile.objects.all(), @@ -644,12 +579,6 @@ class ModuleTypeBulkEditForm(NetBoxModelBulkEditForm): required=False, initial='' ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = ModuleType fieldsets = ( @@ -663,7 +592,7 @@ class ModuleTypeBulkEditForm(NetBoxModelBulkEditForm): nullable_fields = ('part_number', 'weight', 'weight_unit', 'profile', 'description', 'comments') -class DeviceRoleBulkEditForm(NetBoxModelBulkEditForm): +class DeviceRoleBulkEditForm(NestedGroupModelBulkEditForm): parent = DynamicModelChoiceField( label=_('Parent'), queryset=DeviceRole.objects.all(), @@ -683,12 +612,6 @@ class DeviceRoleBulkEditForm(NetBoxModelBulkEditForm): queryset=ConfigTemplate.objects.all(), required=False ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = DeviceRole fieldsets = ( @@ -697,7 +620,7 @@ class DeviceRoleBulkEditForm(NetBoxModelBulkEditForm): nullable_fields = ('parent', 'color', 'config_template', 'description', 'comments') -class PlatformBulkEditForm(NetBoxModelBulkEditForm): +class PlatformBulkEditForm(NestedGroupModelBulkEditForm): parent = DynamicModelChoiceField( label=_('Parent'), queryset=Platform.objects.all(), @@ -713,12 +636,6 @@ class PlatformBulkEditForm(NetBoxModelBulkEditForm): queryset=ConfigTemplate.objects.all(), required=False ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = Platform fieldsets = ( @@ -727,7 +644,7 @@ class PlatformBulkEditForm(NetBoxModelBulkEditForm): nullable_fields = ('parent', 'manufacturer', 'config_template', 'description', 'comments') -class DeviceBulkEditForm(NetBoxModelBulkEditForm): +class DeviceBulkEditForm(PrimaryModelBulkEditForm): manufacturer = DynamicModelChoiceField( label=_('Manufacturer'), queryset=Manufacturer.objects.all(), @@ -787,11 +704,6 @@ class DeviceBulkEditForm(NetBoxModelBulkEditForm): required=False, label=_('Serial Number') ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) config_template = DynamicModelChoiceField( label=_('Config template'), queryset=ConfigTemplate.objects.all(), @@ -805,7 +717,6 @@ class DeviceBulkEditForm(NetBoxModelBulkEditForm): 'site_id': ['$site', 'null'] }, ) - comments = CommentField() model = Device fieldsets = ( @@ -820,7 +731,7 @@ class DeviceBulkEditForm(NetBoxModelBulkEditForm): ) -class ModuleBulkEditForm(NetBoxModelBulkEditForm): +class ModuleBulkEditForm(PrimaryModelBulkEditForm): manufacturer = DynamicModelChoiceField( label=_('Manufacturer'), queryset=Manufacturer.objects.all(), @@ -848,12 +759,6 @@ class ModuleBulkEditForm(NetBoxModelBulkEditForm): required=False, label=_('Serial Number') ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = Module fieldsets = ( @@ -862,7 +767,7 @@ class ModuleBulkEditForm(NetBoxModelBulkEditForm): nullable_fields = ('serial', 'description', 'comments') -class CableBulkEditForm(NetBoxModelBulkEditForm): +class CableBulkEditForm(PrimaryModelBulkEditForm): type = forms.ChoiceField( label=_('Type'), choices=add_blank_choice(CableTypeChoices), @@ -875,6 +780,12 @@ class CableBulkEditForm(NetBoxModelBulkEditForm): required=False, initial='' ) + profile = forms.ChoiceField( + label=_('Profile'), + choices=add_blank_choice(CableProfileChoices), + required=False, + initial='' + ) tenant = DynamicModelChoiceField( label=_('Tenant'), queryset=Tenant.objects.all(), @@ -900,35 +811,23 @@ class CableBulkEditForm(NetBoxModelBulkEditForm): required=False, initial='' ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = Cable fieldsets = ( - FieldSet('type', 'status', 'tenant', 'label', 'description'), + FieldSet('type', 'status', 'profile', 'tenant', 'label', 'description'), FieldSet('color', 'length', 'length_unit', name=_('Attributes')), ) nullable_fields = ( - 'type', 'status', 'tenant', 'label', 'color', 'length', 'description', 'comments', + 'type', 'status', 'profile', 'tenant', 'label', 'color', 'length', 'description', 'comments', ) -class VirtualChassisBulkEditForm(NetBoxModelBulkEditForm): +class VirtualChassisBulkEditForm(PrimaryModelBulkEditForm): domain = forms.CharField( label=_('Domain'), max_length=30, required=False ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = VirtualChassis fieldsets = ( @@ -937,7 +836,7 @@ class VirtualChassisBulkEditForm(NetBoxModelBulkEditForm): nullable_fields = ('domain', 'description', 'comments') -class PowerPanelBulkEditForm(NetBoxModelBulkEditForm): +class PowerPanelBulkEditForm(PrimaryModelBulkEditForm): region = DynamicModelChoiceField( label=_('Region'), queryset=Region.objects.all(), @@ -971,12 +870,6 @@ class PowerPanelBulkEditForm(NetBoxModelBulkEditForm): 'site_id': '$site' } ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = PowerPanel fieldsets = ( @@ -985,7 +878,7 @@ class PowerPanelBulkEditForm(NetBoxModelBulkEditForm): nullable_fields = ('location', 'description', 'comments') -class PowerFeedBulkEditForm(NetBoxModelBulkEditForm): +class PowerFeedBulkEditForm(PrimaryModelBulkEditForm): power_panel = DynamicModelChoiceField( label=_('Power panel'), queryset=PowerPanel.objects.all(), @@ -1041,12 +934,6 @@ class PowerFeedBulkEditForm(NetBoxModelBulkEditForm): queryset=Tenant.objects.all(), required=False ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = PowerFeed fieldsets = ( @@ -1163,6 +1050,10 @@ class PowerOutletTemplateBulkEditForm(ComponentTemplateBulkEditForm): choices=add_blank_choice(PowerOutletTypeChoices), required=False ) + color = ColorField( + label=_('Color'), + required=False + ) power_port = forms.ModelChoiceField( label=_('Power port'), queryset=PowerPortTemplate.objects.all(), @@ -1365,7 +1256,7 @@ class InventoryItemTemplateBulkEditForm(ComponentTemplateBulkEditForm): # Device components # -class ComponentBulkEditForm(NetBoxModelBulkEditForm): +class ComponentBulkEditForm(OwnerMixin, NetBoxModelBulkEditForm): device = forms.ModelChoiceField( label=_('Device'), queryset=Device.objects.all(), @@ -1818,25 +1709,20 @@ class InventoryItemBulkEditForm( # Device component roles # -class InventoryItemRoleBulkEditForm(NetBoxModelBulkEditForm): +class InventoryItemRoleBulkEditForm(OrganizationalModelBulkEditForm): color = ColorField( label=_('Color'), required=False ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) model = InventoryItemRole fieldsets = ( FieldSet('color', 'description'), ) - nullable_fields = ('color', 'description') + nullable_fields = ('color', 'description', 'comments') -class VirtualDeviceContextBulkEditForm(NetBoxModelBulkEditForm): +class VirtualDeviceContextBulkEditForm(PrimaryModelBulkEditForm): device = DynamicModelChoiceField( label=_('Device'), queryset=Device.objects.all(), @@ -1852,6 +1738,7 @@ class VirtualDeviceContextBulkEditForm(NetBoxModelBulkEditForm): queryset=Tenant.objects.all(), required=False ) + model = VirtualDeviceContext fieldsets = ( FieldSet('device', 'status', 'tenant'), @@ -1863,14 +1750,7 @@ class VirtualDeviceContextBulkEditForm(NetBoxModelBulkEditForm): # Addressing # -class MACAddressBulkEditForm(NetBoxModelBulkEditForm): - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() - +class MACAddressBulkEditForm(PrimaryModelBulkEditForm): model = MACAddress fieldsets = ( FieldSet('description'), diff --git a/netbox/dcim/forms/bulk_import.py b/netbox/dcim/forms/bulk_import.py index f896fd047..066eb03fb 100644 --- a/netbox/dcim/forms/bulk_import.py +++ b/netbox/dcim/forms/bulk_import.py @@ -12,7 +12,10 @@ from extras.models import ConfigTemplate from ipam.choices import VLANQinQRoleChoices from ipam.models import VLAN, VRF, IPAddress, VLANGroup from netbox.choices import * -from netbox.forms import NetBoxModelImportForm +from netbox.forms import ( + NestedGroupModelImportForm, NetBoxModelImportForm, OrganizationalModelImportForm, OwnerCSVMixin, + PrimaryModelImportForm, +) from tenancy.models import Tenant from utilities.forms.fields import ( CSVChoiceField, CSVContentTypeField, CSVModelChoiceField, CSVModelMultipleChoiceField, CSVTypedChoiceField, @@ -59,7 +62,7 @@ __all__ = ( ) -class RegionImportForm(NetBoxModelImportForm): +class RegionImportForm(NestedGroupModelImportForm): parent = CSVModelChoiceField( label=_('Parent'), queryset=Region.objects.all(), @@ -70,10 +73,10 @@ class RegionImportForm(NetBoxModelImportForm): class Meta: model = Region - fields = ('name', 'slug', 'parent', 'description', 'tags', 'comments') + fields = ('name', 'slug', 'parent', 'description', 'owner', 'comments', 'tags') -class SiteGroupImportForm(NetBoxModelImportForm): +class SiteGroupImportForm(NestedGroupModelImportForm): parent = CSVModelChoiceField( label=_('Parent'), queryset=SiteGroup.objects.all(), @@ -84,10 +87,10 @@ class SiteGroupImportForm(NetBoxModelImportForm): class Meta: model = SiteGroup - fields = ('name', 'slug', 'parent', 'description', 'comments', 'tags') + fields = ('name', 'slug', 'parent', 'description', 'owner', 'comments', 'tags') -class SiteImportForm(NetBoxModelImportForm): +class SiteImportForm(PrimaryModelImportForm): status = CSVChoiceField( label=_('Status'), choices=SiteStatusChoices, @@ -119,7 +122,7 @@ class SiteImportForm(NetBoxModelImportForm): model = Site fields = ( 'name', 'slug', 'status', 'region', 'group', 'tenant', 'facility', 'time_zone', 'description', - 'physical_address', 'shipping_address', 'latitude', 'longitude', 'comments', 'tags' + 'physical_address', 'shipping_address', 'latitude', 'longitude', 'owner', 'comments', 'tags' ) help_texts = { 'time_zone': mark_safe( @@ -130,7 +133,7 @@ class SiteImportForm(NetBoxModelImportForm): } -class LocationImportForm(NetBoxModelImportForm): +class LocationImportForm(NestedGroupModelImportForm): site = CSVModelChoiceField( label=_('Site'), queryset=Site.objects.all(), @@ -163,8 +166,8 @@ class LocationImportForm(NetBoxModelImportForm): class Meta: model = Location fields = ( - 'site', 'parent', 'name', 'slug', 'status', 'tenant', 'facility', 'description', - 'tags', 'comments', + 'site', 'parent', 'name', 'slug', 'status', 'tenant', 'facility', 'description', 'owner', 'comments', + 'tags', ) def __init__(self, data=None, *args, **kwargs): @@ -176,15 +179,14 @@ class LocationImportForm(NetBoxModelImportForm): self.fields['parent'].queryset = self.fields['parent'].queryset.filter(**params) -class RackRoleImportForm(NetBoxModelImportForm): - slug = SlugField() +class RackRoleImportForm(OrganizationalModelImportForm): class Meta: model = RackRole - fields = ('name', 'slug', 'color', 'description', 'tags') + fields = ('name', 'slug', 'color', 'description', 'owner', 'comments', 'tags') -class RackTypeImportForm(NetBoxModelImportForm): +class RackTypeImportForm(PrimaryModelImportForm): manufacturer = forms.ModelChoiceField( label=_('Manufacturer'), queryset=Manufacturer.objects.all(), @@ -225,14 +227,14 @@ class RackTypeImportForm(NetBoxModelImportForm): fields = ( 'manufacturer', 'model', 'slug', 'form_factor', 'width', 'u_height', 'starting_unit', 'desc_units', 'outer_width', 'outer_height', 'outer_depth', 'outer_unit', 'mounting_depth', 'weight', 'max_weight', - 'weight_unit', 'description', 'comments', 'tags', + 'weight_unit', 'description', 'owner', 'comments', 'tags', ) def __init__(self, data=None, *args, **kwargs): super().__init__(data, *args, **kwargs) -class RackImportForm(NetBoxModelImportForm): +class RackImportForm(PrimaryModelImportForm): site = CSVModelChoiceField( label=_('Site'), queryset=Site.objects.all(), @@ -310,7 +312,8 @@ class RackImportForm(NetBoxModelImportForm): fields = ( 'site', 'location', 'name', 'facility_id', 'tenant', 'status', 'role', 'rack_type', 'form_factor', 'serial', 'asset_tag', 'width', 'u_height', 'desc_units', 'outer_width', 'outer_height', 'outer_depth', 'outer_unit', - 'mounting_depth', 'airflow', 'weight', 'max_weight', 'weight_unit', 'description', 'comments', 'tags', + 'mounting_depth', 'airflow', 'weight', 'max_weight', 'weight_unit', 'description', 'owner', 'comments', + 'tags', ) def __init__(self, data=None, *args, **kwargs): @@ -333,7 +336,7 @@ class RackImportForm(NetBoxModelImportForm): raise forms.ValidationError(_("U height must be set if not specifying a rack type.")) -class RackReservationImportForm(NetBoxModelImportForm): +class RackReservationImportForm(PrimaryModelImportForm): site = CSVModelChoiceField( label=_('Site'), queryset=Site.objects.all(), @@ -374,7 +377,7 @@ class RackReservationImportForm(NetBoxModelImportForm): class Meta: model = RackReservation - fields = ('site', 'location', 'rack', 'units', 'status', 'tenant', 'description', 'comments', 'tags') + fields = ('site', 'location', 'rack', 'units', 'status', 'tenant', 'description', 'owner', 'comments', 'tags') def __init__(self, data=None, *args, **kwargs): super().__init__(data, *args, **kwargs) @@ -393,14 +396,14 @@ class RackReservationImportForm(NetBoxModelImportForm): self.fields['rack'].queryset = self.fields['rack'].queryset.filter(**params) -class ManufacturerImportForm(NetBoxModelImportForm): +class ManufacturerImportForm(OrganizationalModelImportForm): class Meta: model = Manufacturer - fields = ('name', 'slug', 'description', 'tags') + fields = ('name', 'slug', 'description', 'owner', 'comments', 'tags') -class DeviceTypeImportForm(NetBoxModelImportForm): +class DeviceTypeImportForm(PrimaryModelImportForm): manufacturer = CSVModelChoiceField( label=_('Manufacturer'), queryset=Manufacturer.objects.all(), @@ -430,20 +433,21 @@ class DeviceTypeImportForm(NetBoxModelImportForm): model = DeviceType fields = [ 'manufacturer', 'default_platform', 'model', 'slug', 'part_number', 'u_height', 'exclude_from_utilization', - 'is_full_depth', 'subdevice_role', 'airflow', 'description', 'weight', 'weight_unit', 'comments', 'tags', + 'is_full_depth', 'subdevice_role', 'airflow', 'description', 'weight', 'weight_unit', 'owner', 'comments', + 'tags', ] -class ModuleTypeProfileImportForm(NetBoxModelImportForm): +class ModuleTypeProfileImportForm(PrimaryModelImportForm): class Meta: model = ModuleTypeProfile fields = [ - 'name', 'description', 'schema', 'comments', 'tags', + 'name', 'description', 'schema', 'owner', 'comments', 'tags', ] -class ModuleTypeImportForm(NetBoxModelImportForm): +class ModuleTypeImportForm(PrimaryModelImportForm): profile = forms.ModelChoiceField( label=_('Profile'), queryset=ModuleTypeProfile.objects.all(), @@ -482,7 +486,7 @@ class ModuleTypeImportForm(NetBoxModelImportForm): model = ModuleType fields = [ 'manufacturer', 'model', 'part_number', 'description', 'airflow', 'weight', 'weight_unit', 'profile', - 'attribute_data', 'comments', 'tags', + 'attribute_data', 'owner', 'comments', 'tags', ] def clean(self): @@ -497,7 +501,7 @@ class ModuleTypeImportForm(NetBoxModelImportForm): self.cleaned_data['attribute_data'] = {} -class DeviceRoleImportForm(NetBoxModelImportForm): +class DeviceRoleImportForm(NestedGroupModelImportForm): parent = CSVModelChoiceField( label=_('Parent'), queryset=DeviceRole.objects.all(), @@ -515,17 +519,15 @@ class DeviceRoleImportForm(NetBoxModelImportForm): required=False, help_text=_('Config template') ) - slug = SlugField() class Meta: model = DeviceRole fields = ( - 'name', 'slug', 'parent', 'color', 'vm_role', 'config_template', 'description', 'comments', 'tags' + 'name', 'slug', 'parent', 'color', 'vm_role', 'config_template', 'description', 'owner', 'comments', 'tags' ) -class PlatformImportForm(NetBoxModelImportForm): - slug = SlugField() +class PlatformImportForm(NestedGroupModelImportForm): parent = CSVModelChoiceField( label=_('Parent'), queryset=Platform.objects.all(), @@ -554,11 +556,11 @@ class PlatformImportForm(NetBoxModelImportForm): class Meta: model = Platform fields = ( - 'name', 'slug', 'parent', 'manufacturer', 'config_template', 'description', 'tags', + 'name', 'slug', 'parent', 'manufacturer', 'config_template', 'description', 'owner', 'comments', 'tags', ) -class BaseDeviceImportForm(NetBoxModelImportForm): +class BaseDeviceImportForm(PrimaryModelImportForm): role = CSVModelChoiceField( label=_('Device role'), queryset=DeviceRole.objects.all(), @@ -684,8 +686,8 @@ class DeviceImportForm(BaseDeviceImportForm): fields = [ 'name', 'role', 'tenant', 'manufacturer', 'device_type', 'platform', 'serial', 'asset_tag', 'status', 'site', 'location', 'rack', 'position', 'face', 'latitude', 'longitude', 'parent', 'device_bay', 'airflow', - 'virtual_chassis', 'vc_position', 'vc_priority', 'cluster', 'description', 'config_template', 'comments', - 'tags', + 'virtual_chassis', 'vc_position', 'vc_priority', 'cluster', 'description', 'config_template', 'owner', + 'comments', 'tags', ] def __init__(self, data=None, *args, **kwargs): @@ -732,7 +734,7 @@ class DeviceImportForm(BaseDeviceImportForm): self.instance.parent_bay = device_bay -class ModuleImportForm(ModuleCommonForm, NetBoxModelImportForm): +class ModuleImportForm(ModuleCommonForm, PrimaryModelImportForm): device = CSVModelChoiceField( label=_('Device'), queryset=Device.objects.all(), @@ -770,7 +772,7 @@ class ModuleImportForm(ModuleCommonForm, NetBoxModelImportForm): class Meta: model = Module fields = ( - 'device', 'module_bay', 'module_type', 'serial', 'asset_tag', 'status', 'description', 'comments', + 'device', 'module_bay', 'module_type', 'serial', 'asset_tag', 'status', 'description', 'owner', 'comments', 'replicate_components', 'adopt_components', 'tags', ) @@ -794,7 +796,7 @@ class ModuleImportForm(ModuleCommonForm, NetBoxModelImportForm): # Device components # -class ConsolePortImportForm(NetBoxModelImportForm): +class ConsolePortImportForm(OwnerCSVMixin, NetBoxModelImportForm): device = CSVModelChoiceField( label=_('Device'), queryset=Device.objects.all(), @@ -817,10 +819,10 @@ class ConsolePortImportForm(NetBoxModelImportForm): class Meta: model = ConsolePort - fields = ('device', 'name', 'label', 'type', 'speed', 'mark_connected', 'description', 'tags') + fields = ('device', 'name', 'label', 'type', 'speed', 'mark_connected', 'description', 'owner', 'tags') -class ConsoleServerPortImportForm(NetBoxModelImportForm): +class ConsoleServerPortImportForm(OwnerCSVMixin, NetBoxModelImportForm): device = CSVModelChoiceField( label=_('Device'), queryset=Device.objects.all(), @@ -843,10 +845,10 @@ class ConsoleServerPortImportForm(NetBoxModelImportForm): class Meta: model = ConsoleServerPort - fields = ('device', 'name', 'label', 'type', 'speed', 'mark_connected', 'description', 'tags') + fields = ('device', 'name', 'label', 'type', 'speed', 'mark_connected', 'description', 'owner', 'tags') -class PowerPortImportForm(NetBoxModelImportForm): +class PowerPortImportForm(OwnerCSVMixin, NetBoxModelImportForm): device = CSVModelChoiceField( label=_('Device'), queryset=Device.objects.all(), @@ -862,11 +864,12 @@ class PowerPortImportForm(NetBoxModelImportForm): class Meta: model = PowerPort fields = ( - 'device', 'name', 'label', 'type', 'mark_connected', 'maximum_draw', 'allocated_draw', 'description', 'tags' + 'device', 'name', 'label', 'type', 'mark_connected', 'maximum_draw', 'allocated_draw', 'description', + 'owner', 'tags', ) -class PowerOutletImportForm(NetBoxModelImportForm): +class PowerOutletImportForm(OwnerCSVMixin, NetBoxModelImportForm): device = CSVModelChoiceField( label=_('Device'), queryset=Device.objects.all(), @@ -896,7 +899,7 @@ class PowerOutletImportForm(NetBoxModelImportForm): model = PowerOutlet fields = ( 'device', 'name', 'label', 'type', 'color', 'mark_connected', 'power_port', 'feed_leg', 'description', - 'tags', + 'owner', 'tags', ) def __init__(self, *args, **kwargs): @@ -922,7 +925,7 @@ class PowerOutletImportForm(NetBoxModelImportForm): self.fields['power_port'].queryset = PowerPort.objects.none() -class InterfaceImportForm(NetBoxModelImportForm): +class InterfaceImportForm(OwnerCSVMixin, NetBoxModelImportForm): device = CSVModelChoiceField( label=_('Device'), queryset=Device.objects.all(), @@ -1040,7 +1043,7 @@ class InterfaceImportForm(NetBoxModelImportForm): 'device', 'name', 'label', 'parent', 'bridge', 'lag', 'type', 'speed', 'duplex', 'enabled', 'mark_connected', 'wwn', 'vdcs', 'mtu', 'mgmt_only', 'description', 'poe_mode', 'poe_type', 'mode', 'vlan_group', 'untagged_vlan', 'tagged_vlans', 'qinq_svlan', 'vrf', 'rf_role', 'rf_channel', - 'rf_channel_frequency', 'rf_channel_width', 'tx_power', 'tags' + 'rf_channel_frequency', 'rf_channel_width', 'tx_power', 'owner', 'tags' ) def __init__(self, data=None, *args, **kwargs): @@ -1082,18 +1085,12 @@ class InterfaceImportForm(NetBoxModelImportForm): return self.cleaned_data['vdcs'] -class FrontPortImportForm(NetBoxModelImportForm): +class FrontPortImportForm(OwnerCSVMixin, NetBoxModelImportForm): device = CSVModelChoiceField( label=_('Device'), queryset=Device.objects.all(), to_field_name='name' ) - rear_port = CSVModelChoiceField( - label=_('Rear port'), - queryset=RearPort.objects.all(), - to_field_name='name', - help_text=_('Corresponding rear port') - ) type = CSVChoiceField( label=_('Type'), choices=PortTypeChoices, @@ -1103,34 +1100,11 @@ class FrontPortImportForm(NetBoxModelImportForm): class Meta: model = FrontPort fields = ( - 'device', 'name', 'label', 'type', 'color', 'mark_connected', 'rear_port', 'rear_port_position', - 'description', 'tags' + 'device', 'name', 'label', 'type', 'color', 'mark_connected', 'positions', 'description', 'owner', 'tags' ) - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - # Limit RearPort choices to those belonging to this device (or VC master) - if self.is_bound and 'device' in self.data: - try: - device = self.fields['device'].to_python(self.data['device']) - except forms.ValidationError: - device = None - else: - try: - device = self.instance.device - except Device.DoesNotExist: - device = None - - if device: - self.fields['rear_port'].queryset = RearPort.objects.filter( - device__in=[device, device.get_vc_master()] - ) - else: - self.fields['rear_port'].queryset = RearPort.objects.none() - - -class RearPortImportForm(NetBoxModelImportForm): +class RearPortImportForm(OwnerCSVMixin, NetBoxModelImportForm): device = CSVModelChoiceField( label=_('Device'), queryset=Device.objects.all(), @@ -1144,10 +1118,12 @@ class RearPortImportForm(NetBoxModelImportForm): class Meta: model = RearPort - fields = ('device', 'name', 'label', 'type', 'color', 'mark_connected', 'positions', 'description', 'tags') + fields = ( + 'device', 'name', 'label', 'type', 'color', 'mark_connected', 'positions', 'description', 'owner', 'tags', + ) -class ModuleBayImportForm(NetBoxModelImportForm): +class ModuleBayImportForm(OwnerCSVMixin, NetBoxModelImportForm): device = CSVModelChoiceField( label=_('Device'), queryset=Device.objects.all(), @@ -1156,10 +1132,10 @@ class ModuleBayImportForm(NetBoxModelImportForm): class Meta: model = ModuleBay - fields = ('device', 'name', 'label', 'position', 'description', 'tags') + fields = ('device', 'name', 'label', 'position', 'description', 'owner', 'tags') -class DeviceBayImportForm(NetBoxModelImportForm): +class DeviceBayImportForm(OwnerCSVMixin, NetBoxModelImportForm): device = CSVModelChoiceField( label=_('Device'), queryset=Device.objects.all(), @@ -1178,7 +1154,7 @@ class DeviceBayImportForm(NetBoxModelImportForm): class Meta: model = DeviceBay - fields = ('device', 'name', 'label', 'installed_device', 'description', 'tags') + fields = ('device', 'name', 'label', 'installed_device', 'description', 'owner', 'tags') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1207,7 +1183,7 @@ class DeviceBayImportForm(NetBoxModelImportForm): self.fields['installed_device'].queryset = Device.objects.none() -class InventoryItemImportForm(NetBoxModelImportForm): +class InventoryItemImportForm(OwnerCSVMixin, NetBoxModelImportForm): device = CSVModelChoiceField( label=_('Device'), queryset=Device.objects.all(), @@ -1254,7 +1230,7 @@ class InventoryItemImportForm(NetBoxModelImportForm): model = InventoryItem fields = ( 'device', 'name', 'label', 'status', 'role', 'manufacturer', 'parent', 'part_id', 'serial', 'asset_tag', - 'discovered', 'description', 'tags', 'component_type', 'component_name', + 'discovered', 'description', 'owner', 'tags', 'component_type', 'component_name', ) def __init__(self, *args, **kwargs): @@ -1317,19 +1293,19 @@ class InventoryItemImportForm(NetBoxModelImportForm): # Device component roles # -class InventoryItemRoleImportForm(NetBoxModelImportForm): +class InventoryItemRoleImportForm(OrganizationalModelImportForm): slug = SlugField() class Meta: model = InventoryItemRole - fields = ('name', 'slug', 'color', 'description') + fields = ('name', 'slug', 'color', 'description', 'owner', 'comments') # # Addressing # -class MACAddressImportForm(NetBoxModelImportForm): +class MACAddressImportForm(PrimaryModelImportForm): device = CSVModelChoiceField( label=_('Device'), queryset=Device.objects.all(), @@ -1360,7 +1336,8 @@ class MACAddressImportForm(NetBoxModelImportForm): class Meta: model = MACAddress fields = [ - 'mac_address', 'device', 'virtual_machine', 'interface', 'is_primary', 'description', 'comments', 'tags', + 'mac_address', 'device', 'virtual_machine', 'interface', 'is_primary', 'description', 'owner', 'comments', + 'tags', ] def __init__(self, data=None, *args, **kwargs): @@ -1413,7 +1390,7 @@ class MACAddressImportForm(NetBoxModelImportForm): # Cables # -class CableImportForm(NetBoxModelImportForm): +class CableImportForm(PrimaryModelImportForm): # Termination A side_a_site = CSVModelChoiceField( label=_('Side A site'), @@ -1471,6 +1448,12 @@ class CableImportForm(NetBoxModelImportForm): required=False, help_text=_('Connection status') ) + profile = CSVChoiceField( + label=_('Profile'), + choices=CableProfileChoices, + required=False, + help_text=_('Cable connection profile') + ) type = CSVChoiceField( label=_('Type'), choices=CableTypeChoices, @@ -1501,8 +1484,8 @@ class CableImportForm(NetBoxModelImportForm): model = Cable fields = [ 'side_a_site', 'side_a_device', 'side_a_type', 'side_a_name', 'side_b_site', 'side_b_device', 'side_b_type', - 'side_b_name', 'type', 'status', 'tenant', 'label', 'color', 'length', 'length_unit', 'description', - 'comments', 'tags', + 'side_b_name', 'type', 'status', 'profile', 'tenant', 'label', 'color', 'length', 'length_unit', + 'description', 'owner', 'comments', 'tags', ] def __init__(self, data=None, *args, **kwargs): @@ -1596,7 +1579,7 @@ class CableImportForm(NetBoxModelImportForm): # -class VirtualChassisImportForm(NetBoxModelImportForm): +class VirtualChassisImportForm(PrimaryModelImportForm): master = CSVModelChoiceField( label=_('Master'), queryset=Device.objects.all(), @@ -1607,14 +1590,14 @@ class VirtualChassisImportForm(NetBoxModelImportForm): class Meta: model = VirtualChassis - fields = ('name', 'domain', 'master', 'description', 'comments', 'tags') + fields = ('name', 'domain', 'master', 'description', 'owner', 'comments', 'tags') # # Power # -class PowerPanelImportForm(NetBoxModelImportForm): +class PowerPanelImportForm(PrimaryModelImportForm): site = CSVModelChoiceField( label=_('Site'), queryset=Site.objects.all(), @@ -1630,7 +1613,7 @@ class PowerPanelImportForm(NetBoxModelImportForm): class Meta: model = PowerPanel - fields = ('site', 'location', 'name', 'description', 'comments', 'tags') + fields = ('site', 'location', 'name', 'description', 'owner', 'comments', 'tags') def __init__(self, data=None, *args, **kwargs): super().__init__(data, *args, **kwargs) @@ -1642,7 +1625,7 @@ class PowerPanelImportForm(NetBoxModelImportForm): self.fields['location'].queryset = self.fields['location'].queryset.filter(**params) -class PowerFeedImportForm(NetBoxModelImportForm): +class PowerFeedImportForm(PrimaryModelImportForm): site = CSVModelChoiceField( label=_('Site'), queryset=Site.objects.all(), @@ -1700,7 +1683,7 @@ class PowerFeedImportForm(NetBoxModelImportForm): model = PowerFeed fields = ( 'site', 'power_panel', 'location', 'rack', 'name', 'status', 'type', 'mark_connected', 'supply', 'phase', - 'voltage', 'amperage', 'max_utilization', 'tenant', 'description', 'comments', 'tags', + 'voltage', 'amperage', 'max_utilization', 'tenant', 'description', 'owner', 'comments', 'tags', ) def __init__(self, data=None, *args, **kwargs): @@ -1724,8 +1707,7 @@ class PowerFeedImportForm(NetBoxModelImportForm): self.fields['rack'].queryset = self.fields['rack'].queryset.filter(**params) -class VirtualDeviceContextImportForm(NetBoxModelImportForm): - +class VirtualDeviceContextImportForm(PrimaryModelImportForm): device = CSVModelChoiceField( label=_('Device'), queryset=Device.objects.all(), @@ -1760,7 +1742,7 @@ class VirtualDeviceContextImportForm(NetBoxModelImportForm): class Meta: fields = [ - 'name', 'device', 'status', 'tenant', 'identifier', 'comments', 'primary_ip4', 'primary_ip6', + 'name', 'device', 'status', 'tenant', 'identifier', 'owner', 'comments', 'primary_ip4', 'primary_ip6', ] model = VirtualDeviceContext diff --git a/netbox/dcim/forms/filtersets.py b/netbox/dcim/forms/filtersets.py index ba21ce260..63f59c6c8 100644 --- a/netbox/dcim/forms/filtersets.py +++ b/netbox/dcim/forms/filtersets.py @@ -8,12 +8,15 @@ from extras.forms import LocalConfigContextFilterForm from extras.models import ConfigTemplate from ipam.models import ASN, VRF, VLANTranslationPolicy from netbox.choices import * -from netbox.forms import NetBoxModelFilterSetForm +from netbox.forms import ( + NestedGroupModelFilterSetForm, NetBoxModelFilterSetForm, OrganizationalModelFilterSetForm, + PrimaryModelFilterSetForm, +) from tenancy.forms import ContactModelFilterForm, TenancyFilterForm from tenancy.models import Tenant -from users.models import User +from users.models import Owner, User from utilities.forms import BOOLEAN_WITH_BLANK_CHOICES, FilterForm, add_blank_choice -from utilities.forms.fields import ColorField, DynamicModelMultipleChoiceField, TagFilterField +from utilities.forms.fields import ColorField, DynamicModelChoiceField, DynamicModelMultipleChoiceField, TagFilterField from utilities.forms.rendering import FieldSet from utilities.forms.widgets import NumberWithOptions from virtualization.models import Cluster, ClusterGroup, VirtualMachine @@ -154,12 +157,18 @@ class DeviceComponentFilterForm(NetBoxModelFilterSetForm): required=False, label=_('Device Status'), ) + owner_id = DynamicModelChoiceField( + queryset=Owner.objects.all(), + required=False, + label=_('Owner'), + ) -class RegionFilterForm(ContactModelFilterForm, NetBoxModelFilterSetForm): +class RegionFilterForm(ContactModelFilterForm, NestedGroupModelFilterSetForm): model = Region fieldsets = ( - FieldSet('q', 'filter_id', 'tag', 'parent_id'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), + FieldSet('parent_id', name=_('Region')), FieldSet('contact', 'contact_role', 'contact_group', name=_('Contacts')) ) parent_id = DynamicModelMultipleChoiceField( @@ -170,10 +179,11 @@ class RegionFilterForm(ContactModelFilterForm, NetBoxModelFilterSetForm): tag = TagFilterField(model) -class SiteGroupFilterForm(ContactModelFilterForm, NetBoxModelFilterSetForm): +class SiteGroupFilterForm(ContactModelFilterForm, NestedGroupModelFilterSetForm): model = SiteGroup fieldsets = ( - FieldSet('q', 'filter_id', 'tag', 'parent_id'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), + FieldSet('parent_id', name=_('Site Group')), FieldSet('contact', 'contact_role', 'contact_group', name=_('Contacts')) ) parent_id = DynamicModelMultipleChoiceField( @@ -184,10 +194,10 @@ class SiteGroupFilterForm(ContactModelFilterForm, NetBoxModelFilterSetForm): tag = TagFilterField(model) -class SiteFilterForm(TenancyFilterForm, ContactModelFilterForm, NetBoxModelFilterSetForm): +class SiteFilterForm(TenancyFilterForm, ContactModelFilterForm, PrimaryModelFilterSetForm): model = Site fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('status', 'region_id', 'group_id', 'asn_id', name=_('Attributes')), FieldSet('tenant_group_id', 'tenant_id', name=_('Tenant')), FieldSet('contact', 'contact_role', 'contact_group', name=_('Contacts')), @@ -216,10 +226,10 @@ class SiteFilterForm(TenancyFilterForm, ContactModelFilterForm, NetBoxModelFilte tag = TagFilterField(model) -class LocationFilterForm(TenancyFilterForm, ContactModelFilterForm, NetBoxModelFilterSetForm): +class LocationFilterForm(TenancyFilterForm, ContactModelFilterForm, NestedGroupModelFilterSetForm): model = Location fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('region_id', 'site_group_id', 'site_id', 'parent_id', 'status', 'facility', name=_('Attributes')), FieldSet('tenant_group_id', 'tenant_id', name=_('Tenant')), FieldSet('contact', 'contact_role', 'contact_group', name=_('Contacts')), @@ -264,12 +274,15 @@ class LocationFilterForm(TenancyFilterForm, ContactModelFilterForm, NetBoxModelF tag = TagFilterField(model) -class RackRoleFilterForm(NetBoxModelFilterSetForm): +class RackRoleFilterForm(OrganizationalModelFilterSetForm): model = RackRole + fieldsets = ( + FieldSet('q', 'filter_id', 'tag', 'owner_id'), + ) tag = TagFilterField(model) -class RackBaseFilterForm(NetBoxModelFilterSetForm): +class RackBaseFilterForm(PrimaryModelFilterSetForm): form_factor = forms.MultipleChoiceField( label=_('Form factor'), choices=RackFormFactorChoices, @@ -315,8 +328,8 @@ class RackBaseFilterForm(NetBoxModelFilterSetForm): class RackTypeFilterForm(RackBaseFilterForm): model = RackType fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), - FieldSet('manufacturer_id', 'form_factor', 'width', 'u_height', name=_('Rack Type')), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), + FieldSet('manufacturer_id', 'form_factor', 'width', 'u_height', 'rack_count', name=_('Rack Type')), FieldSet('starting_unit', 'desc_units', name=_('Numbering')), FieldSet('weight', 'max_weight', 'weight_unit', name=_('Weight')), ) @@ -326,13 +339,18 @@ class RackTypeFilterForm(RackBaseFilterForm): required=False, label=_('Manufacturer') ) + rack_count = forms.IntegerField( + label=_('Rack count'), + required=False, + min_value=0, + ) tag = TagFilterField(model) class RackFilterForm(TenancyFilterForm, ContactModelFilterForm, RackBaseFilterForm): model = Rack fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('region_id', 'site_group_id', 'site_id', 'location_id', name=_('Location')), FieldSet('tenant_group_id', 'tenant_id', name=_('Tenant')), FieldSet('status', 'role_id', 'manufacturer_id', 'rack_type_id', 'serial', 'asset_tag', name=_('Rack')), @@ -430,10 +448,10 @@ class RackElevationFilterForm(RackFilterForm): ) -class RackReservationFilterForm(TenancyFilterForm, NetBoxModelFilterSetForm): +class RackReservationFilterForm(TenancyFilterForm, PrimaryModelFilterSetForm): model = RackReservation fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('status', 'user_id', name=_('Reservation')), FieldSet('region_id', 'site_group_id', 'site_id', 'location_id', 'rack_id', name=_('Rack')), FieldSet('tenant_group_id', 'tenant_id', name=_('Tenant')), @@ -488,21 +506,22 @@ class RackReservationFilterForm(TenancyFilterForm, NetBoxModelFilterSetForm): tag = TagFilterField(model) -class ManufacturerFilterForm(ContactModelFilterForm, NetBoxModelFilterSetForm): +class ManufacturerFilterForm(ContactModelFilterForm, OrganizationalModelFilterSetForm): model = Manufacturer fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('contact', 'contact_role', 'contact_group', name=_('Contacts')) ) tag = TagFilterField(model) -class DeviceTypeFilterForm(NetBoxModelFilterSetForm): +class DeviceTypeFilterForm(PrimaryModelFilterSetForm): model = DeviceType fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet( - 'manufacturer_id', 'default_platform_id', 'part_number', 'subdevice_role', 'airflow', name=_('Hardware') + 'manufacturer_id', 'default_platform_id', 'part_number', 'device_count', + 'subdevice_role', 'airflow', name=_('Hardware') ), FieldSet('has_front_image', 'has_rear_image', name=_('Images')), FieldSet( @@ -526,6 +545,11 @@ class DeviceTypeFilterForm(NetBoxModelFilterSetForm): label=_('Part number'), required=False ) + device_count = forms.IntegerField( + label=_('Device count'), + required=False, + min_value=0, + ) subdevice_role = forms.MultipleChoiceField( label=_('Subdevice role'), choices=add_blank_choice(SubdeviceRoleChoices), @@ -625,19 +649,23 @@ class DeviceTypeFilterForm(NetBoxModelFilterSetForm): ) -class ModuleTypeProfileFilterForm(NetBoxModelFilterSetForm): +class ModuleTypeProfileFilterForm(PrimaryModelFilterSetForm): model = ModuleTypeProfile fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), ) selector_fields = ('filter_id', 'q') + tag = TagFilterField(model) -class ModuleTypeFilterForm(NetBoxModelFilterSetForm): +class ModuleTypeFilterForm(PrimaryModelFilterSetForm): model = ModuleType fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), - FieldSet('profile_id', 'manufacturer_id', 'part_number', 'airflow', name=_('Hardware')), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), + FieldSet( + 'profile_id', 'manufacturer_id', 'part_number', 'module_count', + 'airflow', name=_('Hardware') + ), FieldSet( 'console_ports', 'console_server_ports', 'power_ports', 'power_outlets', 'interfaces', 'pass_through_ports', name=_('Components') @@ -659,6 +687,11 @@ class ModuleTypeFilterForm(NetBoxModelFilterSetForm): label=_('Part number'), required=False ) + module_count = forms.IntegerField( + label=_('Module count'), + required=False, + min_value=0, + ) console_ports = forms.NullBooleanField( required=False, label=_('Has console ports'), @@ -718,8 +751,12 @@ class ModuleTypeFilterForm(NetBoxModelFilterSetForm): ) -class DeviceRoleFilterForm(NetBoxModelFilterSetForm): +class DeviceRoleFilterForm(NestedGroupModelFilterSetForm): model = DeviceRole + fieldsets = ( + FieldSet('q', 'filter_id', 'tag', 'owner_id'), + FieldSet('parent_id', 'config_template_id', name=_('Device Role')) + ) config_template_id = DynamicModelMultipleChoiceField( queryset=ConfigTemplate.objects.all(), required=False, @@ -733,8 +770,12 @@ class DeviceRoleFilterForm(NetBoxModelFilterSetForm): tag = TagFilterField(model) -class PlatformFilterForm(NetBoxModelFilterSetForm): +class PlatformFilterForm(NestedGroupModelFilterSetForm): model = Platform + fieldsets = ( + FieldSet('q', 'filter_id', 'tag', 'owner_id'), + FieldSet('manufacturer_id', 'parent_id', 'config_template_id', name=_('Platform')) + ) selector_fields = ('filter_id', 'q', 'manufacturer_id') parent_id = DynamicModelMultipleChoiceField( queryset=Platform.objects.all(), @@ -758,11 +799,11 @@ class DeviceFilterForm( LocalConfigContextFilterForm, TenancyFilterForm, ContactModelFilterForm, - NetBoxModelFilterSetForm + PrimaryModelFilterSetForm ): model = Device fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('region_id', 'site_group_id', 'site_id', 'location_id', 'rack_id', name=_('Location')), FieldSet('status', 'role_id', 'airflow', 'serial', 'asset_tag', 'mac_address', name=_('Operation')), FieldSet('manufacturer_id', 'device_type_id', 'platform_id', name=_('Hardware')), @@ -952,13 +993,10 @@ class DeviceFilterForm( tag = TagFilterField(model) -class VirtualDeviceContextFilterForm( - TenancyFilterForm, - NetBoxModelFilterSetForm -): +class VirtualDeviceContextFilterForm(TenancyFilterForm, PrimaryModelFilterSetForm): model = VirtualDeviceContext fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('device', 'status', 'has_primary_ip', name=_('Attributes')), FieldSet('tenant_group_id', 'tenant_id', name=_('Tenant')), ) @@ -982,10 +1020,10 @@ class VirtualDeviceContextFilterForm( tag = TagFilterField(model) -class ModuleFilterForm(LocalConfigContextFilterForm, TenancyFilterForm, NetBoxModelFilterSetForm): +class ModuleFilterForm(LocalConfigContextFilterForm, TenancyFilterForm, PrimaryModelFilterSetForm): model = Module fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('region_id', 'site_group_id', 'site_id', 'location_id', 'rack_id', 'device_id', name=_('Location')), FieldSet('manufacturer_id', 'module_type_id', 'status', 'serial', 'asset_tag', name=_('Hardware')), ) @@ -1065,10 +1103,10 @@ class ModuleFilterForm(LocalConfigContextFilterForm, TenancyFilterForm, NetBoxMo tag = TagFilterField(model) -class VirtualChassisFilterForm(TenancyFilterForm, NetBoxModelFilterSetForm): +class VirtualChassisFilterForm(TenancyFilterForm, PrimaryModelFilterSetForm): model = VirtualChassis fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('region_id', 'site_group_id', 'site_id', name=_('Location')), FieldSet('tenant_group_id', 'tenant_id', name=_('Tenant')), ) @@ -1094,12 +1132,12 @@ class VirtualChassisFilterForm(TenancyFilterForm, NetBoxModelFilterSetForm): tag = TagFilterField(model) -class CableFilterForm(TenancyFilterForm, NetBoxModelFilterSetForm): +class CableFilterForm(TenancyFilterForm, PrimaryModelFilterSetForm): model = Cable fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('site_id', 'location_id', 'rack_id', 'device_id', name=_('Location')), - FieldSet('type', 'status', 'color', 'length', 'length_unit', 'unterminated', name=_('Attributes')), + FieldSet('type', 'status', 'profile', 'color', 'length', 'length_unit', 'unterminated', name=_('Attributes')), FieldSet('tenant_group_id', 'tenant_id', name=_('Tenant')), ) region_id = DynamicModelMultipleChoiceField( @@ -1155,6 +1193,11 @@ class CableFilterForm(TenancyFilterForm, NetBoxModelFilterSetForm): required=False, choices=add_blank_choice(LinkStatusChoices) ) + profile = forms.MultipleChoiceField( + label=_('Profile'), + required=False, + choices=add_blank_choice(CableProfileChoices) + ) color = ColorField( label=_('Color'), required=False @@ -1178,10 +1221,10 @@ class CableFilterForm(TenancyFilterForm, NetBoxModelFilterSetForm): tag = TagFilterField(model) -class PowerPanelFilterForm(ContactModelFilterForm, NetBoxModelFilterSetForm): +class PowerPanelFilterForm(ContactModelFilterForm, PrimaryModelFilterSetForm): model = PowerPanel fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('region_id', 'site_group_id', 'site_id', 'location_id', name=_('Location')), FieldSet('contact', 'contact_role', 'contact_group', name=_('Contacts')), ) @@ -1217,10 +1260,10 @@ class PowerPanelFilterForm(ContactModelFilterForm, NetBoxModelFilterSetForm): tag = TagFilterField(model) -class PowerFeedFilterForm(TenancyFilterForm, NetBoxModelFilterSetForm): +class PowerFeedFilterForm(TenancyFilterForm, PrimaryModelFilterSetForm): model = PowerFeed fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('region_id', 'site_group_id', 'site_id', 'power_panel_id', 'rack_id', name=_('Location')), FieldSet('tenant_group_id', 'tenant_id', name=_('Tenant')), FieldSet('status', 'type', 'supply', 'phase', 'voltage', 'amperage', 'max_utilization', name=_('Attributes')), @@ -1347,7 +1390,7 @@ class PathEndpointFilterForm(CabledFilterForm): class ConsolePortFilterForm(PathEndpointFilterForm, DeviceComponentFilterForm): model = ConsolePort fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('name', 'label', 'type', 'speed', name=_('Attributes')), FieldSet('region_id', 'site_group_id', 'site_id', 'location_id', 'rack_id', name=_('Location')), FieldSet( @@ -1386,7 +1429,7 @@ class ConsolePortTemplateFilterForm(ModularDeviceComponentTemplateFilterForm): class ConsoleServerPortFilterForm(PathEndpointFilterForm, DeviceComponentFilterForm): model = ConsoleServerPort fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('name', 'label', 'type', 'speed', name=_('Attributes')), FieldSet('region_id', 'site_group_id', 'site_id', 'location_id', 'rack_id', name=_('Location')), FieldSet( @@ -1425,7 +1468,7 @@ class ConsoleServerPortTemplateFilterForm(ModularDeviceComponentTemplateFilterFo class PowerPortFilterForm(PathEndpointFilterForm, DeviceComponentFilterForm): model = PowerPort fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('name', 'label', 'type', name=_('Attributes')), FieldSet('region_id', 'site_group_id', 'site_id', 'location_id', 'rack_id', name=_('Location')), FieldSet( @@ -1459,7 +1502,7 @@ class PowerPortTemplateFilterForm(ModularDeviceComponentTemplateFilterForm): class PowerOutletFilterForm(PathEndpointFilterForm, DeviceComponentFilterForm): model = PowerOutlet fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('name', 'label', 'type', 'color', 'status', name=_('Attributes')), FieldSet('region_id', 'site_group_id', 'site_id', 'location_id', 'rack_id', name=_('Location')), FieldSet( @@ -1502,7 +1545,7 @@ class PowerOutletTemplateFilterForm(ModularDeviceComponentTemplateFilterForm): class InterfaceFilterForm(PathEndpointFilterForm, DeviceComponentFilterForm): model = Interface fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('name', 'label', 'kind', 'type', 'speed', 'duplex', 'enabled', 'mgmt_only', name=_('Attributes')), FieldSet('vrf_id', 'l2vpn_id', 'mac_address', 'wwn', name=_('Addressing')), FieldSet('poe_mode', 'poe_type', name=_('PoE')), @@ -1673,7 +1716,7 @@ class InterfaceTemplateFilterForm(ModularDeviceComponentTemplateFilterForm): class FrontPortFilterForm(CabledFilterForm, DeviceComponentFilterForm): fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('name', 'label', 'type', 'color', name=_('Attributes')), FieldSet('region_id', 'site_group_id', 'site_id', 'location_id', 'rack_id', name=_('Location')), FieldSet( @@ -1716,7 +1759,7 @@ class FrontPortTemplateFilterForm(ModularDeviceComponentTemplateFilterForm): class RearPortFilterForm(CabledFilterForm, DeviceComponentFilterForm): model = RearPort fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('name', 'label', 'type', 'color', name=_('Attributes')), FieldSet('region_id', 'site_group_id', 'site_id', 'location_id', 'rack_id', name=_('Location')), FieldSet( @@ -1758,7 +1801,7 @@ class RearPortTemplateFilterForm(ModularDeviceComponentTemplateFilterForm): class ModuleBayFilterForm(DeviceComponentFilterForm): model = ModuleBay fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('name', 'label', 'position', name=_('Attributes')), FieldSet('region_id', 'site_group_id', 'site_id', 'location_id', 'rack_id', name=_('Location')), FieldSet( @@ -1789,7 +1832,7 @@ class ModuleBayTemplateFilterForm(ModularDeviceComponentTemplateFilterForm): class DeviceBayFilterForm(DeviceComponentFilterForm): model = DeviceBay fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('name', 'label', name=_('Attributes')), FieldSet('region_id', 'site_group_id', 'site_id', 'location_id', 'rack_id', name=_('Location')), FieldSet( @@ -1812,7 +1855,7 @@ class DeviceBayTemplateFilterForm(DeviceComponentTemplateFilterForm): class InventoryItemFilterForm(DeviceComponentFilterForm): model = InventoryItem fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet( 'name', 'label', 'status', 'role_id', 'manufacturer_id', 'serial', 'asset_tag', 'discovered', name=_('Attributes') @@ -1879,8 +1922,11 @@ class InventoryItemTemplateFilterForm(DeviceComponentTemplateFilterForm): # Device component roles # -class InventoryItemRoleFilterForm(NetBoxModelFilterSetForm): +class InventoryItemRoleFilterForm(OrganizationalModelFilterSetForm): model = InventoryItemRole + fieldsets = ( + FieldSet('q', 'filter_id', 'tag', 'owner_id'), + ) tag = TagFilterField(model) @@ -1888,15 +1934,12 @@ class InventoryItemRoleFilterForm(NetBoxModelFilterSetForm): # Addressing # -class MACAddressFilterForm(NetBoxModelFilterSetForm): +class MACAddressFilterForm(PrimaryModelFilterSetForm): model = MACAddress fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('mac_address', name=_('Attributes')), - FieldSet( - 'device_id', 'virtual_machine_id', 'assigned', 'primary', - name=_('Assignments'), - ), + FieldSet('device_id', 'virtual_machine_id', 'assigned', 'primary', name=_('Assignments')), ) selector_fields = ('filter_id', 'q', 'device_id', 'virtual_machine_id') mac_address = forms.CharField( diff --git a/netbox/dcim/forms/mixins.py b/netbox/dcim/forms/mixins.py index 96eb8a56b..b2fc46bc3 100644 --- a/netbox/dcim/forms/mixins.py +++ b/netbox/dcim/forms/mixins.py @@ -1,10 +1,12 @@ from django import forms from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ObjectDoesNotExist, ValidationError +from django.db import connection +from django.db.models.signals import post_save from django.utils.translation import gettext_lazy as _ from dcim.constants import LOCATION_SCOPE_TYPES -from dcim.models import Site +from dcim.models import PortMapping, PortTemplateMapping, Site from utilities.forms import get_field_value from utilities.forms.fields import ( ContentTypeChoiceField, CSVContentTypeField, DynamicModelChoiceField, @@ -13,6 +15,7 @@ from utilities.templatetags.builtins.filters import bettertitle from utilities.forms.widgets import HTMXSelect __all__ = ( + 'FrontPortFormMixin', 'ScopedBulkEditForm', 'ScopedForm', 'ScopedImportForm', @@ -128,3 +131,75 @@ class ScopedImportForm(forms.Form): "Please select a {scope_type}." ).format(scope_type=scope_type.model_class()._meta.model_name) }) + + +class FrontPortFormMixin(forms.Form): + rear_ports = forms.MultipleChoiceField( + choices=[], + label=_('Rear ports'), + widget=forms.SelectMultiple(attrs={'size': 8}) + ) + + port_mapping_model = PortMapping + parent_field = 'device' + + def clean(self): + super().clean() + + # Check that the total number of FrontPorts and positions matches the selected number of RearPort:position + # mappings. Note that `name` will be a list under FrontPortCreateForm, in which cases we multiply the number of + # FrontPorts being creation by the number of positions. + positions = self.cleaned_data['positions'] + frontport_count = len(self.cleaned_data['name']) if type(self.cleaned_data['name']) is list else 1 + rearport_count = len(self.cleaned_data['rear_ports']) + if frontport_count * positions != rearport_count: + raise forms.ValidationError({ + 'rear_ports': _( + "The total number of front port positions ({frontport_count}) must match the selected number of " + "rear port positions ({rearport_count})." + ).format( + frontport_count=frontport_count, + rearport_count=rearport_count + ) + }) + + def _save_m2m(self): + super()._save_m2m() + + # TODO: Can this be made more efficient? + # Delete existing rear port mappings + self.port_mapping_model.objects.filter(front_port_id=self.instance.pk).delete() + + # Create new rear port mappings + mappings = [] + if self.port_mapping_model is PortTemplateMapping: + params = { + 'device_type_id': self.instance.device_type_id, + 'module_type_id': self.instance.module_type_id, + } + else: + params = { + 'device_id': self.instance.device_id, + } + for i, rp_position in enumerate(self.cleaned_data['rear_ports'], start=1): + rear_port_id, rear_port_position = rp_position.split(':') + mappings.append( + self.port_mapping_model(**{ + **params, + 'front_port_id': self.instance.pk, + 'front_port_position': i, + 'rear_port_id': rear_port_id, + 'rear_port_position': rear_port_position, + }) + ) + self.port_mapping_model.objects.bulk_create(mappings) + # Send post_save signals + for mapping in mappings: + post_save.send( + sender=PortMapping, + instance=mapping, + created=True, + raw=False, + using=connection, + update_fields=None + ) diff --git a/netbox/dcim/forms/model_forms.py b/netbox/dcim/forms/model_forms.py index dcadc0713..69bd7d5cd 100644 --- a/netbox/dcim/forms/model_forms.py +++ b/netbox/dcim/forms/model_forms.py @@ -6,17 +6,18 @@ from timezone_field import TimeZoneFormField from dcim.choices import * from dcim.constants import * +from dcim.forms.mixins import FrontPortFormMixin from dcim.models import * from extras.models import ConfigTemplate from ipam.choices import VLANQinQRoleChoices from ipam.models import ASN, IPAddress, VLAN, VLANGroup, VLANTranslationPolicy, VRF -from netbox.forms import NetBoxModelForm -from netbox.forms.mixins import ChangelogMessageMixin +from netbox.forms import NestedGroupModelForm, NetBoxModelForm, OrganizationalModelForm, PrimaryModelForm +from netbox.forms.mixins import ChangelogMessageMixin, OwnerMixin from tenancy.forms import TenancyForm from users.models import User from utilities.forms import add_blank_choice, get_field_value from utilities.forms.fields import ( - CommentField, DynamicModelChoiceField, DynamicModelMultipleChoiceField, JSONField, NumericArrayField, SlugField, + DynamicModelChoiceField, DynamicModelMultipleChoiceField, JSONField, NumericArrayField, SlugField, ) from utilities.forms.rendering import FieldSet, InlineFields, TabbedGroups from utilities.forms.widgets import APISelect, ClearableFileInput, HTMXSelect, NumberWithOptions, SelectWithPK @@ -75,14 +76,12 @@ __all__ = ( ) -class RegionForm(NetBoxModelForm): +class RegionForm(NestedGroupModelForm): parent = DynamicModelChoiceField( label=_('Parent'), queryset=Region.objects.all(), required=False ) - slug = SlugField() - comments = CommentField() fieldsets = ( FieldSet('parent', 'name', 'slug', 'description', 'tags'), @@ -91,18 +90,16 @@ class RegionForm(NetBoxModelForm): class Meta: model = Region fields = ( - 'parent', 'name', 'slug', 'description', 'tags', 'comments', + 'parent', 'name', 'slug', 'description', 'owner', 'tags', 'comments', ) -class SiteGroupForm(NetBoxModelForm): +class SiteGroupForm(NestedGroupModelForm): parent = DynamicModelChoiceField( label=_('Parent'), queryset=SiteGroup.objects.all(), required=False ) - slug = SlugField() - comments = CommentField() fieldsets = ( FieldSet('parent', 'name', 'slug', 'description', 'tags'), @@ -111,11 +108,11 @@ class SiteGroupForm(NetBoxModelForm): class Meta: model = SiteGroup fields = ( - 'parent', 'name', 'slug', 'description', 'comments', 'tags', + 'parent', 'name', 'slug', 'description', 'owner', 'comments', 'tags', ) -class SiteForm(TenancyForm, NetBoxModelForm): +class SiteForm(TenancyForm, PrimaryModelForm): region = DynamicModelChoiceField( label=_('Region'), queryset=Region.objects.all(), @@ -139,7 +136,6 @@ class SiteForm(TenancyForm, NetBoxModelForm): choices=add_blank_choice(TimeZoneFormField().choices), required=False ) - comments = CommentField() fieldsets = ( FieldSet( @@ -154,7 +150,7 @@ class SiteForm(TenancyForm, NetBoxModelForm): model = Site fields = ( 'name', 'slug', 'status', 'region', 'group', 'tenant_group', 'tenant', 'facility', 'asns', 'time_zone', - 'description', 'physical_address', 'shipping_address', 'latitude', 'longitude', 'comments', 'tags', + 'description', 'physical_address', 'shipping_address', 'latitude', 'longitude', 'owner', 'comments', 'tags', ) widgets = { 'physical_address': forms.Textarea( @@ -170,7 +166,7 @@ class SiteForm(TenancyForm, NetBoxModelForm): } -class LocationForm(TenancyForm, NetBoxModelForm): +class LocationForm(TenancyForm, NestedGroupModelForm): site = DynamicModelChoiceField( label=_('Site'), queryset=Site.objects.all(), @@ -184,8 +180,6 @@ class LocationForm(TenancyForm, NetBoxModelForm): 'site_id': '$site' } ) - slug = SlugField() - comments = CommentField() fieldsets = ( FieldSet('site', 'parent', 'name', 'slug', 'status', 'facility', 'description', 'tags', name=_('Location')), @@ -195,14 +189,12 @@ class LocationForm(TenancyForm, NetBoxModelForm): class Meta: model = Location fields = ( - 'site', 'parent', 'name', 'slug', 'status', 'description', 'tenant_group', 'tenant', - 'facility', 'tags', 'comments', + 'site', 'parent', 'name', 'slug', 'status', 'description', 'tenant_group', 'tenant', 'facility', 'owner', + 'comments', 'tags', ) -class RackRoleForm(NetBoxModelForm): - slug = SlugField() - +class RackRoleForm(OrganizationalModelForm): fieldsets = ( FieldSet('name', 'slug', 'color', 'description', 'tags', name=_('Rack Role')), ) @@ -210,17 +202,16 @@ class RackRoleForm(NetBoxModelForm): class Meta: model = RackRole fields = [ - 'name', 'slug', 'color', 'description', 'tags', + 'name', 'slug', 'color', 'description', 'owner', 'comments', 'tags', ] -class RackTypeForm(NetBoxModelForm): +class RackTypeForm(PrimaryModelForm): manufacturer = DynamicModelChoiceField( label=_('Manufacturer'), queryset=Manufacturer.objects.all(), quick_add=True ) - comments = CommentField() slug = SlugField( label=_('Slug'), slug_source='model' @@ -242,11 +233,11 @@ class RackTypeForm(NetBoxModelForm): fields = [ 'manufacturer', 'model', 'slug', 'form_factor', 'width', 'u_height', 'starting_unit', 'desc_units', 'outer_width', 'outer_height', 'outer_depth', 'outer_unit', 'mounting_depth', 'weight', 'max_weight', - 'weight_unit', 'description', 'comments', 'tags', + 'weight_unit', 'description', 'owner', 'comments', 'tags', ] -class RackForm(TenancyForm, NetBoxModelForm): +class RackForm(TenancyForm, PrimaryModelForm): site = DynamicModelChoiceField( label=_('Site'), queryset=Site.objects.all(), @@ -272,7 +263,6 @@ class RackForm(TenancyForm, NetBoxModelForm): selector=True, help_text=_("Select a pre-defined rack type, or set physical characteristics below."), ) - comments = CommentField() fieldsets = ( FieldSet( @@ -289,7 +279,7 @@ class RackForm(TenancyForm, NetBoxModelForm): 'site', 'location', 'name', 'facility_id', 'tenant_group', 'tenant', 'status', 'role', 'serial', 'asset_tag', 'rack_type', 'form_factor', 'width', 'u_height', 'starting_unit', 'desc_units', 'outer_width', 'outer_height', 'outer_depth', 'outer_unit', 'mounting_depth', 'airflow', 'weight', 'max_weight', - 'weight_unit', 'description', 'comments', 'tags', + 'weight_unit', 'description', 'owner', 'comments', 'tags', ] def __init__(self, *args, **kwargs): @@ -319,7 +309,7 @@ class RackForm(TenancyForm, NetBoxModelForm): ) -class RackReservationForm(TenancyForm, NetBoxModelForm): +class RackReservationForm(TenancyForm, PrimaryModelForm): rack = DynamicModelChoiceField( label=_('Rack'), queryset=Rack.objects.all(), @@ -334,7 +324,6 @@ class RackReservationForm(TenancyForm, NetBoxModelForm): label=_('User'), queryset=User.objects.order_by('username') ) - comments = CommentField() fieldsets = ( FieldSet('rack', 'units', 'status', 'user', 'description', 'tags', name=_('Reservation')), @@ -344,13 +333,11 @@ class RackReservationForm(TenancyForm, NetBoxModelForm): class Meta: model = RackReservation fields = [ - 'rack', 'units', 'status', 'user', 'tenant_group', 'tenant', 'description', 'comments', 'tags', + 'rack', 'units', 'status', 'user', 'tenant_group', 'tenant', 'description', 'owner', 'comments', 'tags', ] -class ManufacturerForm(NetBoxModelForm): - slug = SlugField() - +class ManufacturerForm(OrganizationalModelForm): fieldsets = ( FieldSet('name', 'slug', 'description', 'tags', name=_('Manufacturer')), ) @@ -358,11 +345,11 @@ class ManufacturerForm(NetBoxModelForm): class Meta: model = Manufacturer fields = [ - 'name', 'slug', 'description', 'tags', + 'name', 'slug', 'description', 'owner', 'comments', 'tags', ] -class DeviceTypeForm(NetBoxModelForm): +class DeviceTypeForm(PrimaryModelForm): manufacturer = DynamicModelChoiceField( label=_('Manufacturer'), queryset=Manufacturer.objects.all(), @@ -381,7 +368,6 @@ class DeviceTypeForm(NetBoxModelForm): label=_('Slug'), slug_source='model' ) - comments = CommentField() fieldsets = ( FieldSet('manufacturer', 'model', 'slug', 'default_platform', 'description', 'tags', name=_('Device Type')), @@ -397,7 +383,7 @@ class DeviceTypeForm(NetBoxModelForm): fields = [ 'manufacturer', 'model', 'slug', 'default_platform', 'part_number', 'u_height', 'exclude_from_utilization', 'is_full_depth', 'subdevice_role', 'airflow', 'weight', 'weight_unit', 'front_image', 'rear_image', - 'description', 'comments', 'tags', + 'description', 'owner', 'comments', 'tags', ] widgets = { 'front_image': ClearableFileInput(attrs={ @@ -409,13 +395,12 @@ class DeviceTypeForm(NetBoxModelForm): } -class ModuleTypeProfileForm(NetBoxModelForm): +class ModuleTypeProfileForm(PrimaryModelForm): schema = JSONField( label=_('Schema'), required=False, help_text=_("Enter a valid JSON schema to define supported attributes.") ) - comments = CommentField() fieldsets = ( FieldSet('name', 'description', 'schema', 'tags', name=_('Profile')), @@ -424,11 +409,11 @@ class ModuleTypeProfileForm(NetBoxModelForm): class Meta: model = ModuleTypeProfile fields = [ - 'name', 'description', 'schema', 'comments', 'tags', + 'name', 'description', 'schema', 'owner', 'comments', 'tags', ] -class ModuleTypeForm(NetBoxModelForm): +class ModuleTypeForm(PrimaryModelForm): profile = forms.ModelChoiceField( queryset=ModuleTypeProfile.objects.all(), label=_('Profile'), @@ -439,7 +424,6 @@ class ModuleTypeForm(NetBoxModelForm): label=_('Manufacturer'), queryset=Manufacturer.objects.all() ) - comments = CommentField() @property def fieldsets(self): @@ -453,7 +437,7 @@ class ModuleTypeForm(NetBoxModelForm): model = ModuleType fields = [ 'profile', 'manufacturer', 'model', 'part_number', 'description', 'airflow', 'weight', 'weight_unit', - 'comments', 'tags', + 'owner', 'comments', 'tags', ] def __init__(self, *args, **kwargs): @@ -508,19 +492,17 @@ class ModuleTypeForm(NetBoxModelForm): return super()._post_clean() -class DeviceRoleForm(NetBoxModelForm): +class DeviceRoleForm(NestedGroupModelForm): config_template = DynamicModelChoiceField( label=_('Config template'), queryset=ConfigTemplate.objects.all(), required=False ) - slug = SlugField() parent = DynamicModelChoiceField( label=_('Parent'), queryset=DeviceRole.objects.all(), required=False, ) - comments = CommentField() fieldsets = ( FieldSet( @@ -532,11 +514,11 @@ class DeviceRoleForm(NetBoxModelForm): class Meta: model = DeviceRole fields = [ - 'name', 'slug', 'parent', 'color', 'vm_role', 'config_template', 'description', 'comments', 'tags', + 'name', 'slug', 'parent', 'color', 'vm_role', 'config_template', 'description', 'owner', 'comments', 'tags', ] -class PlatformForm(NetBoxModelForm): +class PlatformForm(NestedGroupModelForm): parent = DynamicModelChoiceField( label=_('Parent'), queryset=Platform.objects.all(), @@ -557,7 +539,6 @@ class PlatformForm(NetBoxModelForm): label=_('Slug'), max_length=64 ) - comments = CommentField() fieldsets = ( FieldSet( @@ -568,11 +549,11 @@ class PlatformForm(NetBoxModelForm): class Meta: model = Platform fields = [ - 'name', 'slug', 'parent', 'manufacturer', 'config_template', 'description', 'comments', 'tags', + 'name', 'slug', 'parent', 'manufacturer', 'config_template', 'description', 'owner', 'comments', 'tags', ] -class DeviceForm(TenancyForm, NetBoxModelForm): +class DeviceForm(TenancyForm, PrimaryModelForm): site = DynamicModelChoiceField( label=_('Site'), queryset=Site.objects.all(), @@ -642,7 +623,6 @@ class DeviceForm(TenancyForm, NetBoxModelForm): 'site_id': ['$site', 'null'] }, ) - comments = CommentField() local_context_data = JSONField( required=False, label='' @@ -678,7 +658,7 @@ class DeviceForm(TenancyForm, NetBoxModelForm): 'name', 'role', 'device_type', 'serial', 'asset_tag', 'site', 'rack', 'location', 'position', 'face', 'latitude', 'longitude', 'status', 'airflow', 'platform', 'primary_ip4', 'primary_ip6', 'oob_ip', 'cluster', 'tenant_group', 'tenant', 'virtual_chassis', 'vc_position', 'vc_priority', 'description', 'config_template', - 'comments', 'tags', 'local_context_data', + 'owner', 'comments', 'tags', 'local_context_data', ] def __init__(self, *args, **kwargs): @@ -743,7 +723,7 @@ class DeviceForm(TenancyForm, NetBoxModelForm): self.fields['position'].widget.choices = [(position, f'U{position}')] -class ModuleForm(ModuleCommonForm, NetBoxModelForm): +class ModuleForm(ModuleCommonForm, PrimaryModelForm): device = DynamicModelChoiceField( label=_('Device'), queryset=Device.objects.all(), @@ -769,7 +749,6 @@ class ModuleForm(ModuleCommonForm, NetBoxModelForm): }, selector=True ) - comments = CommentField() replicate_components = forms.BooleanField( label=_('Replicate components'), required=False, @@ -792,7 +771,7 @@ class ModuleForm(ModuleCommonForm, NetBoxModelForm): model = Module fields = [ 'device', 'module_bay', 'module_type', 'status', 'serial', 'asset_tag', 'tags', 'replicate_components', - 'adopt_components', 'description', 'comments', + 'adopt_components', 'description', 'owner', 'comments', ] def __init__(self, *args, **kwargs): @@ -813,7 +792,7 @@ def get_termination_type_choices(): ]) -class CableForm(TenancyForm, NetBoxModelForm): +class CableForm(TenancyForm, PrimaryModelForm): a_terminations_type = forms.ChoiceField( choices=get_termination_type_choices, required=False, @@ -826,17 +805,16 @@ class CableForm(TenancyForm, NetBoxModelForm): widget=HTMXSelect(), label=_('Type') ) - comments = CommentField() class Meta: model = Cable fields = [ - 'a_terminations_type', 'b_terminations_type', 'type', 'status', 'tenant_group', 'tenant', 'label', 'color', - 'length', 'length_unit', 'description', 'comments', 'tags', + 'a_terminations_type', 'b_terminations_type', 'type', 'status', 'profile', 'tenant_group', 'tenant', + 'label', 'color', 'length', 'length_unit', 'description', 'owner', 'comments', 'tags', ] -class PowerPanelForm(NetBoxModelForm): +class PowerPanelForm(PrimaryModelForm): site = DynamicModelChoiceField( label=_('Site'), queryset=Site.objects.all(), @@ -850,7 +828,6 @@ class PowerPanelForm(NetBoxModelForm): 'site_id': '$site' } ) - comments = CommentField() fieldsets = ( FieldSet('site', 'location', 'name', 'description', 'tags', name=_('Power Panel')), @@ -859,11 +836,11 @@ class PowerPanelForm(NetBoxModelForm): class Meta: model = PowerPanel fields = [ - 'site', 'location', 'name', 'description', 'comments', 'tags', + 'site', 'location', 'name', 'description', 'owner', 'comments', 'tags', ] -class PowerFeedForm(TenancyForm, NetBoxModelForm): +class PowerFeedForm(TenancyForm, PrimaryModelForm): power_panel = DynamicModelChoiceField( label=_('Power panel'), queryset=PowerPanel.objects.all(), @@ -876,7 +853,6 @@ class PowerFeedForm(TenancyForm, NetBoxModelForm): required=False, selector=True ) - comments = CommentField() fieldsets = ( FieldSet( @@ -891,7 +867,7 @@ class PowerFeedForm(TenancyForm, NetBoxModelForm): model = PowerFeed fields = [ 'power_panel', 'rack', 'name', 'status', 'type', 'mark_connected', 'supply', 'phase', 'voltage', 'amperage', - 'max_utilization', 'tenant_group', 'tenant', 'description', 'comments', 'tags' + 'max_utilization', 'tenant_group', 'tenant', 'description', 'owner', 'comments', 'tags' ] @@ -899,18 +875,17 @@ class PowerFeedForm(TenancyForm, NetBoxModelForm): # Virtual chassis # -class VirtualChassisForm(NetBoxModelForm): +class VirtualChassisForm(PrimaryModelForm): master = forms.ModelChoiceField( label=_('Master'), queryset=Device.objects.all(), required=False, ) - comments = CommentField() class Meta: model = VirtualChassis fields = [ - 'name', 'domain', 'master', 'description', 'comments', 'tags', + 'name', 'domain', 'master', 'description', 'owner', 'comments', 'tags', ] widgets = { 'master': SelectWithPK(), @@ -1096,14 +1071,14 @@ class PowerOutletTemplateForm(ModularComponentTemplateForm): FieldSet('device_type', name=_('Device Type')), FieldSet('module_type', name=_('Module Type')), ), - 'name', 'label', 'type', 'power_port', 'feed_leg', 'description', + 'name', 'label', 'type', 'color', 'power_port', 'feed_leg', 'description', ), ) class Meta: model = PowerOutletTemplate fields = [ - 'device_type', 'module_type', 'name', 'label', 'type', 'power_port', 'feed_leg', 'description', + 'device_type', 'module_type', 'name', 'label', 'type', 'color', 'power_port', 'feed_leg', 'description', ] @@ -1138,34 +1113,66 @@ class InterfaceTemplateForm(ModularComponentTemplateForm): ] -class FrontPortTemplateForm(ModularComponentTemplateForm): - rear_port = DynamicModelChoiceField( - label=_('Rear port'), - queryset=RearPortTemplate.objects.all(), - required=False, - query_params={ - 'device_type_id': '$device_type', - 'module_type_id': '$module_type', - } - ) - +class FrontPortTemplateForm(FrontPortFormMixin, ModularComponentTemplateForm): fieldsets = ( FieldSet( TabbedGroups( FieldSet('device_type', name=_('Device Type')), FieldSet('module_type', name=_('Module Type')), ), - 'name', 'label', 'type', 'color', 'rear_port', 'rear_port_position', 'description', + 'name', 'label', 'type', 'positions', 'rear_ports', 'description', ), ) + # Override FrontPortFormMixin attrs + port_mapping_model = PortTemplateMapping + parent_field = 'device_type' + class Meta: model = FrontPortTemplate fields = [ - 'device_type', 'module_type', 'name', 'label', 'type', 'color', 'rear_port', 'rear_port_position', - 'description', + 'device_type', 'module_type', 'name', 'label', 'type', 'color', 'positions', 'description', ] + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + if device_type_id := self.data.get('device_type') or self.initial.get('device_type'): + device_type = DeviceType.objects.get(pk=device_type_id) + else: + return + + # Populate rear port choices + self.fields['rear_ports'].choices = self._get_rear_port_choices(device_type, self.instance) + + # Set initial rear port mappings + if self.instance.pk: + self.initial['rear_ports'] = [ + f'{mapping.rear_port_id}:{mapping.rear_port_position}' + for mapping in PortTemplateMapping.objects.filter(front_port_id=self.instance.pk) + ] + + def _get_rear_port_choices(self, device_type, front_port): + """ + Return a list of choices representing each available rear port & position pair on the device type, excluding + those assigned to the specified instance. + """ + occupied_rear_port_positions = [ + f'{mapping.rear_port_id}:{mapping.rear_port_position}' + for mapping in device_type.port_mappings.exclude(front_port=front_port.pk) + ] + + choices = [] + for rear_port in RearPortTemplate.objects.filter(device_type=device_type): + for i in range(1, rear_port.positions + 1): + pair_id = f'{rear_port.pk}:{i}' + if pair_id not in occupied_rear_port_positions: + pair_label = f'{rear_port.name}:{i}' + choices.append( + (pair_id, pair_label) + ) + return choices + class RearPortTemplateForm(ModularComponentTemplateForm): fieldsets = ( @@ -1364,7 +1371,7 @@ class InventoryItemTemplateForm(ComponentTemplateForm): # Device components # -class DeviceComponentForm(NetBoxModelForm): +class DeviceComponentForm(OwnerMixin, NetBoxModelForm): device = DynamicModelChoiceField( label=_('Device'), queryset=Device.objects.all(), @@ -1400,7 +1407,7 @@ class ConsolePortForm(ModularDeviceComponentForm): class Meta: model = ConsolePort fields = [ - 'device', 'module', 'name', 'label', 'type', 'speed', 'mark_connected', 'description', 'tags', + 'device', 'module', 'name', 'label', 'type', 'speed', 'mark_connected', 'description', 'owner', 'tags', ] @@ -1414,7 +1421,7 @@ class ConsoleServerPortForm(ModularDeviceComponentForm): class Meta: model = ConsoleServerPort fields = [ - 'device', 'module', 'name', 'label', 'type', 'speed', 'mark_connected', 'description', 'tags', + 'device', 'module', 'name', 'label', 'type', 'speed', 'mark_connected', 'description', 'owner', 'tags', ] @@ -1430,7 +1437,7 @@ class PowerPortForm(ModularDeviceComponentForm): model = PowerPort fields = [ 'device', 'module', 'name', 'label', 'type', 'maximum_draw', 'allocated_draw', 'mark_connected', - 'description', 'tags', + 'description', 'owner', 'tags', ] @@ -1447,7 +1454,7 @@ class PowerOutletForm(ModularDeviceComponentForm): fieldsets = ( FieldSet( 'device', 'module', 'name', 'label', 'type', 'status', 'color', 'power_port', 'feed_leg', 'mark_connected', - 'description', 'tags', + 'description', 'owner', 'tags', ), ) @@ -1591,7 +1598,7 @@ class InterfaceForm(InterfaceCommonForm, ModularDeviceComponentForm): 'lag', 'wwn', 'mtu', 'mgmt_only', 'mark_connected', 'description', 'poe_mode', 'poe_type', 'mode', 'rf_role', 'rf_channel', 'rf_channel_frequency', 'rf_channel_width', 'tx_power', 'wireless_lans', 'untagged_vlan', 'tagged_vlans', 'qinq_svlan', 'vlan_translation_policy', 'vrf', 'primary_mac_address', - 'tags', + 'owner', 'tags', ] widgets = { 'speed': NumberWithOptions( @@ -1604,17 +1611,10 @@ class InterfaceForm(InterfaceCommonForm, ModularDeviceComponentForm): } -class FrontPortForm(ModularDeviceComponentForm): - rear_port = DynamicModelChoiceField( - queryset=RearPort.objects.all(), - query_params={ - 'device_id': '$device', - } - ) - +class FrontPortForm(FrontPortFormMixin, ModularDeviceComponentForm): fieldsets = ( FieldSet( - 'device', 'module', 'name', 'label', 'type', 'color', 'rear_port', 'rear_port_position', 'mark_connected', + 'device', 'module', 'name', 'label', 'type', 'color', 'positions', 'rear_ports', 'mark_connected', 'description', 'tags', ), ) @@ -1622,10 +1622,49 @@ class FrontPortForm(ModularDeviceComponentForm): class Meta: model = FrontPort fields = [ - 'device', 'module', 'name', 'label', 'type', 'color', 'rear_port', 'rear_port_position', 'mark_connected', - 'description', 'tags', + 'device', 'module', 'name', 'label', 'type', 'color', 'positions', 'mark_connected', 'description', 'owner', + 'tags', ] + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + if device_id := self.data.get('device') or self.initial.get('device'): + device = Device.objects.get(pk=device_id) + else: + return + + # Populate rear port choices + self.fields['rear_ports'].choices = self._get_rear_port_choices(device, self.instance) + + # Set initial rear port mappings + if self.instance.pk: + self.initial['rear_ports'] = [ + f'{mapping.rear_port_id}:{mapping.rear_port_position}' + for mapping in PortMapping.objects.filter(front_port_id=self.instance.pk) + ] + + def _get_rear_port_choices(self, device, front_port): + """ + Return a list of choices representing each available rear port & position pair on the device, excluding those + assigned to the specified instance. + """ + occupied_rear_port_positions = [ + f'{mapping.rear_port_id}:{mapping.rear_port_position}' + for mapping in device.port_mappings.exclude(front_port=front_port.pk) + ] + + choices = [] + for rear_port in RearPort.objects.filter(device=device): + for i in range(1, rear_port.positions + 1): + pair_id = f'{rear_port.pk}:{i}' + if pair_id not in occupied_rear_port_positions: + pair_label = f'{rear_port.name}:{i}' + choices.append( + (pair_id, pair_label) + ) + return choices + class RearPortForm(ModularDeviceComponentForm): fieldsets = ( @@ -1637,7 +1676,8 @@ class RearPortForm(ModularDeviceComponentForm): class Meta: model = RearPort fields = [ - 'device', 'module', 'name', 'label', 'type', 'color', 'positions', 'mark_connected', 'description', 'tags', + 'device', 'module', 'name', 'label', 'type', 'color', 'positions', 'mark_connected', 'description', 'owner', + 'tags', ] @@ -1649,7 +1689,7 @@ class ModuleBayForm(ModularDeviceComponentForm): class Meta: model = ModuleBay fields = [ - 'device', 'module', 'name', 'label', 'position', 'description', 'tags', + 'device', 'module', 'name', 'label', 'position', 'description', 'owner', 'tags', ] @@ -1661,7 +1701,7 @@ class DeviceBayForm(DeviceComponentForm): class Meta: model = DeviceBay fields = [ - 'device', 'name', 'label', 'description', 'tags', + 'device', 'name', 'label', 'description', 'owner', 'tags', ] @@ -1786,7 +1826,7 @@ class InventoryItemForm(DeviceComponentForm): model = InventoryItem fields = [ 'device', 'parent', 'name', 'label', 'role', 'manufacturer', 'part_id', 'serial', 'asset_tag', - 'status', 'description', 'tags', + 'status', 'description', 'owner', 'tags', ] def __init__(self, *args, **kwargs): @@ -1832,12 +1872,7 @@ class InventoryItemForm(DeviceComponentForm): self.instance.component = None -# Device component roles -# - -class InventoryItemRoleForm(NetBoxModelForm): - slug = SlugField() - +class InventoryItemRoleForm(OrganizationalModelForm): fieldsets = ( FieldSet('name', 'slug', 'color', 'description', 'tags', name=_('Inventory Item Role')), ) @@ -1845,11 +1880,11 @@ class InventoryItemRoleForm(NetBoxModelForm): class Meta: model = InventoryItemRole fields = [ - 'name', 'slug', 'color', 'description', 'tags', + 'name', 'slug', 'color', 'description', 'owner', 'comments', 'tags', ] -class VirtualDeviceContextForm(TenancyForm, NetBoxModelForm): +class VirtualDeviceContextForm(TenancyForm, PrimaryModelForm): device = DynamicModelChoiceField( label=_('Device'), queryset=Device.objects.all(), @@ -1885,7 +1920,7 @@ class VirtualDeviceContextForm(TenancyForm, NetBoxModelForm): class Meta: model = VirtualDeviceContext fields = [ - 'device', 'name', 'status', 'identifier', 'primary_ip4', 'primary_ip6', 'tenant_group', 'tenant', + 'device', 'name', 'status', 'identifier', 'primary_ip4', 'primary_ip6', 'tenant_group', 'tenant', 'owner', 'comments', 'tags' ] @@ -1894,7 +1929,7 @@ class VirtualDeviceContextForm(TenancyForm, NetBoxModelForm): # Addressing # -class MACAddressForm(NetBoxModelForm): +class MACAddressForm(PrimaryModelForm): mac_address = forms.CharField( required=True, label=_('MAC address') @@ -1933,7 +1968,7 @@ class MACAddressForm(NetBoxModelForm): class Meta: model = MACAddress fields = [ - 'mac_address', 'interface', 'vminterface', 'description', 'tags', + 'mac_address', 'interface', 'vminterface', 'description', 'owner', 'tags', ] def __init__(self, *args, **kwargs): diff --git a/netbox/dcim/forms/object_create.py b/netbox/dcim/forms/object_create.py index 9a7bd0591..8e0818326 100644 --- a/netbox/dcim/forms/object_create.py +++ b/netbox/dcim/forms/object_create.py @@ -109,85 +109,30 @@ class InterfaceTemplateCreateForm(ComponentCreateForm, model_forms.InterfaceTemp class FrontPortTemplateCreateForm(ComponentCreateForm, model_forms.FrontPortTemplateForm): - rear_port = forms.MultipleChoiceField( - choices=[], - label=_('Rear ports'), - help_text=_('Select one rear port assignment for each front port being created.'), - widget=forms.SelectMultiple(attrs={'size': 6}) - ) - # Override fieldsets from FrontPortTemplateForm to omit rear_port_position + # Override fieldsets from FrontPortTemplateForm fieldsets = ( FieldSet( TabbedGroups( FieldSet('device_type', name=_('Device Type')), FieldSet('module_type', name=_('Module Type')), ), - 'name', 'label', 'type', 'color', 'rear_port', 'description', + 'name', 'label', 'type', 'color', 'positions', 'rear_ports', 'description', ), ) - class Meta(model_forms.FrontPortTemplateForm.Meta): - exclude = ('name', 'label', 'rear_port', 'rear_port_position') - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - # TODO: This needs better validation - if 'device_type' in self.initial or self.data.get('device_type'): - parent = DeviceType.objects.get( - pk=self.initial.get('device_type') or self.data.get('device_type') - ) - elif 'module_type' in self.initial or self.data.get('module_type'): - parent = ModuleType.objects.get( - pk=self.initial.get('module_type') or self.data.get('module_type') - ) - else: - return - - # Determine which rear port positions are occupied. These will be excluded from the list of available mappings. - occupied_port_positions = [ - (front_port.rear_port_id, front_port.rear_port_position) - for front_port in parent.frontporttemplates.all() - ] - - # Populate rear port choices - choices = [] - rear_ports = parent.rearporttemplates.all() - for rear_port in rear_ports: - for i in range(1, rear_port.positions + 1): - if (rear_port.pk, i) not in occupied_port_positions: - choices.append( - ('{}:{}'.format(rear_port.pk, i), '{}:{}'.format(rear_port.name, i)) - ) - self.fields['rear_port'].choices = choices - - def clean(self): - super().clean() - - # Check that the number of FrontPortTemplates to be created matches the selected number of RearPortTemplate - # positions - frontport_count = len(self.cleaned_data['name']) - rearport_count = len(self.cleaned_data['rear_port']) - if frontport_count != rearport_count: - raise forms.ValidationError({ - 'rear_port': _( - "The number of front port templates to be created ({frontport_count}) must match the selected " - "number of rear port positions ({rearport_count})." - ).format( - frontport_count=frontport_count, - rearport_count=rearport_count - ) - }) + class Meta: + model = FrontPortTemplate + fields = ( + 'device_type', 'module_type', 'type', 'color', 'positions', 'description', + ) def get_iterative_data(self, iteration): - - # Assign rear port and position from selected set - rear_port, position = self.cleaned_data['rear_port'][iteration].split(':') + positions = self.cleaned_data['positions'] + offset = positions * iteration return { - 'rear_port': int(rear_port), - 'rear_port_position': int(position), + 'rear_ports': self.cleaned_data['rear_ports'][offset:offset + positions] } @@ -269,74 +214,26 @@ class FrontPortCreateForm(ComponentCreateForm, model_forms.FrontPortForm): } ) ) - rear_port = forms.MultipleChoiceField( - choices=[], - label=_('Rear ports'), - help_text=_('Select one rear port assignment for each front port being created.'), - widget=forms.SelectMultiple(attrs={'size': 6}) - ) # Override fieldsets from FrontPortForm to omit rear_port_position fieldsets = ( FieldSet( - 'device', 'module', 'name', 'label', 'type', 'color', 'rear_port', 'mark_connected', 'description', 'tags', + 'device', 'module', 'name', 'label', 'type', 'color', 'positions', 'rear_ports', 'mark_connected', + 'description', 'tags', ), ) - class Meta(model_forms.FrontPortForm.Meta): - exclude = ('name', 'label', 'rear_port', 'rear_port_position') - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - if device_id := self.data.get('device') or self.initial.get('device'): - device = Device.objects.get(pk=device_id) - else: - return - - # Determine which rear port positions are occupied. These will be excluded from the list of available - # mappings. - occupied_port_positions = [ - (front_port.rear_port_id, front_port.rear_port_position) - for front_port in device.frontports.all() + class Meta: + model = FrontPort + fields = [ + 'device', 'module', 'type', 'color', 'positions', 'mark_connected', 'description', 'owner', 'tags', ] - # Populate rear port choices - choices = [] - rear_ports = RearPort.objects.filter(device=device) - for rear_port in rear_ports: - for i in range(1, rear_port.positions + 1): - if (rear_port.pk, i) not in occupied_port_positions: - choices.append( - ('{}:{}'.format(rear_port.pk, i), '{}:{}'.format(rear_port.name, i)) - ) - self.fields['rear_port'].choices = choices - - def clean(self): - super().clean() - - # Check that the number of FrontPorts to be created matches the selected number of RearPort positions - frontport_count = len(self.cleaned_data['name']) - rearport_count = len(self.cleaned_data['rear_port']) - if frontport_count != rearport_count: - raise forms.ValidationError({ - 'rear_port': _( - "The number of front ports to be created ({frontport_count}) must match the selected number of " - "rear port positions ({rearport_count})." - ).format( - frontport_count=frontport_count, - rearport_count=rearport_count - ) - }) - def get_iterative_data(self, iteration): - - # Assign rear port and position from selected set - rear_port, position = self.cleaned_data['rear_port'][iteration].split(':') - + positions = self.cleaned_data['positions'] + offset = positions * iteration return { - 'rear_port': int(rear_port), - 'rear_port_position': int(position), + 'rear_ports': self.cleaned_data['rear_ports'][offset:offset + positions] } @@ -434,8 +331,8 @@ class VirtualChassisCreateForm(NetBoxModelForm): class Meta: model = VirtualChassis fields = [ - 'name', 'domain', 'description', 'region', 'site_group', 'site', 'rack', 'members', 'initial_position', - 'tags', + 'name', 'domain', 'description', 'region', 'site_group', 'site', 'rack', 'owner', 'members', + 'initial_position', 'tags', ] def clean(self): diff --git a/netbox/dcim/forms/object_import.py b/netbox/dcim/forms/object_import.py index 3f2cc3ef6..3b6a6e648 100644 --- a/netbox/dcim/forms/object_import.py +++ b/netbox/dcim/forms/object_import.py @@ -13,6 +13,7 @@ __all__ = ( 'InterfaceTemplateImportForm', 'InventoryItemTemplateImportForm', 'ModuleBayTemplateImportForm', + 'PortTemplateMappingImportForm', 'PowerOutletTemplateImportForm', 'PowerPortTemplateImportForm', 'RearPortTemplateImportForm', @@ -113,31 +114,11 @@ class FrontPortTemplateImportForm(forms.ModelForm): label=_('Type'), choices=PortTypeChoices.CHOICES ) - rear_port = forms.ModelChoiceField( - label=_('Rear port'), - queryset=RearPortTemplate.objects.all(), - to_field_name='name' - ) - - def clean_device_type(self): - if device_type := self.cleaned_data['device_type']: - rear_port = self.fields['rear_port'] - rear_port.queryset = rear_port.queryset.filter(device_type=device_type) - - return device_type - - def clean_module_type(self): - if module_type := self.cleaned_data['module_type']: - rear_port = self.fields['rear_port'] - rear_port.queryset = rear_port.queryset.filter(module_type=module_type) - - return module_type class Meta: model = FrontPortTemplate fields = [ - 'device_type', 'module_type', 'name', 'type', 'color', 'rear_port', 'rear_port_position', 'label', - 'description', + 'device_type', 'module_type', 'name', 'type', 'color', 'positions', 'label', 'description', ] @@ -154,6 +135,25 @@ class RearPortTemplateImportForm(forms.ModelForm): ] +class PortTemplateMappingImportForm(forms.ModelForm): + front_port = forms.ModelChoiceField( + label=_('Front port'), + queryset=FrontPortTemplate.objects.all(), + to_field_name='name', + ) + rear_port = forms.ModelChoiceField( + label=_('Rear port'), + queryset=RearPortTemplate.objects.all(), + to_field_name='name', + ) + + class Meta: + model = PortTemplateMapping + fields = [ + 'front_port', 'front_port_position', 'rear_port', 'rear_port_position', + ] + + class ModuleBayTemplateImportForm(forms.ModelForm): class Meta: diff --git a/netbox/dcim/graphql/enums.py b/netbox/dcim/graphql/enums.py index 62a666b45..437094d72 100644 --- a/netbox/dcim/graphql/enums.py +++ b/netbox/dcim/graphql/enums.py @@ -28,11 +28,13 @@ __all__ = ( 'PowerFeedSupplyEnum', 'PowerFeedTypeEnum', 'PowerOutletFeedLegEnum', + 'PowerOutletStatusEnum', 'PowerOutletTypeEnum', 'PowerPortTypeEnum', 'RackAirflowEnum', 'RackDimensionUnitEnum', 'RackFormFactorEnum', + 'RackReservationStatusEnum', 'RackStatusEnum', 'RackWidthEnum', 'SiteStatusEnum', @@ -65,11 +67,13 @@ PowerFeedStatusEnum = strawberry.enum(PowerFeedStatusChoices.as_enum(prefix='sta PowerFeedSupplyEnum = strawberry.enum(PowerFeedSupplyChoices.as_enum(prefix='supply')) PowerFeedTypeEnum = strawberry.enum(PowerFeedTypeChoices.as_enum(prefix='type')) PowerOutletFeedLegEnum = strawberry.enum(PowerOutletFeedLegChoices.as_enum(prefix='feed_leg')) +PowerOutletStatusEnum = strawberry.enum(PowerOutletStatusChoices.as_enum(prefix='status')) PowerOutletTypeEnum = strawberry.enum(PowerOutletTypeChoices.as_enum(prefix='type')) PowerPortTypeEnum = strawberry.enum(PowerPortTypeChoices.as_enum(prefix='type')) RackAirflowEnum = strawberry.enum(RackAirflowChoices.as_enum()) RackDimensionUnitEnum = strawberry.enum(RackDimensionUnitChoices.as_enum(prefix='unit')) RackFormFactorEnum = strawberry.enum(RackFormFactorChoices.as_enum(prefix='type')) +RackReservationStatusEnum = strawberry.enum(RackReservationStatusChoices.as_enum(prefix='status')) RackStatusEnum = strawberry.enum(RackStatusChoices.as_enum(prefix='status')) RackWidthEnum = strawberry.enum(RackWidthChoices.as_enum(prefix='width')) SiteStatusEnum = strawberry.enum(SiteStatusChoices.as_enum(prefix='status')) diff --git a/netbox/dcim/graphql/filter_mixins.py b/netbox/dcim/graphql/filter_mixins.py index 25379ad7f..c02c89948 100644 --- a/netbox/dcim/graphql/filter_mixins.py +++ b/netbox/dcim/graphql/filter_mixins.py @@ -4,11 +4,9 @@ from typing import Annotated, TYPE_CHECKING import strawberry import strawberry_django from strawberry import ID -from strawberry_django import FilterLookup +from strawberry_django import BaseFilterLookup, FilterLookup -from core.graphql.filter_mixins import BaseFilterMixin, ChangeLogFilterMixin from core.graphql.filters import ContentTypeFilter -from netbox.graphql.filter_mixins import NetBoxModelFilterMixin, PrimaryModelFilterMixin, WeightFilterMixin from .enums import * if TYPE_CHECKING: @@ -22,16 +20,16 @@ __all__ = ( 'ComponentModelFilterMixin', 'ComponentTemplateFilterMixin', 'InterfaceBaseFilterMixin', - 'ModularComponentModelFilterMixin', + 'ModularComponentFilterMixin', 'ModularComponentTemplateFilterMixin', - 'RackBaseFilterMixin', + 'RackFilterMixin', 'RenderConfigFilterMixin', 'ScopedFilterMixin', ) @dataclass -class ScopedFilterMixin(BaseFilterMixin): +class ScopedFilterMixin: scope_type: Annotated['ContentTypeFilter', strawberry.lazy('core.graphql.filters')] | None = ( strawberry_django.filter_field() ) @@ -39,7 +37,7 @@ class ScopedFilterMixin(BaseFilterMixin): @dataclass -class ComponentModelFilterMixin(NetBoxModelFilterMixin): +class ComponentModelFilterMixin: device: Annotated['DeviceFilter', strawberry.lazy('dcim.graphql.filters')] | None = strawberry_django.filter_field() device_id: ID | None = strawberry_django.filter_field() name: FilterLookup[str] | None = strawberry_django.filter_field() @@ -48,7 +46,7 @@ class ComponentModelFilterMixin(NetBoxModelFilterMixin): @dataclass -class ModularComponentModelFilterMixin(ComponentModelFilterMixin): +class ModularComponentFilterMixin(ComponentModelFilterMixin): module: Annotated['ModuleFilter', strawberry.lazy('dcim.graphql.filters')] | None = strawberry_django.filter_field() module_id: ID | None = strawberry_django.filter_field() inventory_items: Annotated['InventoryItemFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( @@ -57,15 +55,17 @@ class ModularComponentModelFilterMixin(ComponentModelFilterMixin): @dataclass -class CabledObjectModelFilterMixin(BaseFilterMixin): +class CabledObjectModelFilterMixin: cable: Annotated['CableFilter', strawberry.lazy('dcim.graphql.filters')] | None = strawberry_django.filter_field() cable_id: ID | None = strawberry_django.filter_field() - cable_end: CableEndEnum | None = strawberry_django.filter_field() + cable_end: ( + BaseFilterLookup[Annotated['CableEndEnum', strawberry.lazy('dcim.graphql.enums')]] | None + ) = strawberry_django.filter_field() mark_connected: FilterLookup[bool] | None = strawberry_django.filter_field() @dataclass -class ComponentTemplateFilterMixin(ChangeLogFilterMixin): +class ComponentTemplateFilterMixin: device_type: Annotated['DeviceTypeFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( strawberry_django.filter_field() ) @@ -83,7 +83,7 @@ class ModularComponentTemplateFilterMixin(ComponentTemplateFilterMixin): @dataclass -class RenderConfigFilterMixin(BaseFilterMixin): +class RenderConfigFilterMixin: config_template: Annotated['ConfigTemplateFilter', strawberry.lazy('extras.graphql.filters')] | None = ( strawberry_django.filter_field() ) @@ -91,12 +91,14 @@ class RenderConfigFilterMixin(BaseFilterMixin): @dataclass -class InterfaceBaseFilterMixin(BaseFilterMixin): +class InterfaceBaseFilterMixin: enabled: FilterLookup[bool] | None = strawberry_django.filter_field() mtu: Annotated['IntegerLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( strawberry_django.filter_field() ) - mode: InterfaceModeEnum | None = strawberry_django.filter_field() + mode: ( + BaseFilterLookup[Annotated['InterfaceModeEnum', strawberry.lazy('dcim.graphql.enums')]] | None + ) = strawberry_django.filter_field() bridge: Annotated['InterfaceFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( strawberry_django.filter_field() ) @@ -110,8 +112,9 @@ class InterfaceBaseFilterMixin(BaseFilterMixin): qinq_svlan: Annotated['VLANFilter', strawberry.lazy('ipam.graphql.filters')] | None = ( strawberry_django.filter_field() ) - vlan_translation_policy: Annotated['VLANTranslationPolicyFilter', strawberry.lazy('ipam.graphql.filters')] | None \ - = strawberry_django.filter_field() + vlan_translation_policy: ( + Annotated['VLANTranslationPolicyFilter', strawberry.lazy('ipam.graphql.filters')] | None + ) = strawberry_django.filter_field() primary_mac_address: Annotated['MACAddressFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( strawberry_django.filter_field() ) @@ -119,8 +122,10 @@ class InterfaceBaseFilterMixin(BaseFilterMixin): @dataclass -class RackBaseFilterMixin(WeightFilterMixin, PrimaryModelFilterMixin): - width: Annotated['RackWidthEnum', strawberry.lazy('dcim.graphql.enums')] | None = strawberry_django.filter_field() +class RackFilterMixin: + width: BaseFilterLookup[Annotated['RackWidthEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( + strawberry_django.filter_field() + ) u_height: Annotated['IntegerLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( strawberry_django.filter_field() ) @@ -137,7 +142,7 @@ class RackBaseFilterMixin(WeightFilterMixin, PrimaryModelFilterMixin): outer_depth: Annotated['IntegerLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( strawberry_django.filter_field() ) - outer_unit: Annotated['RackDimensionUnitEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + outer_unit: BaseFilterLookup[Annotated['RackDimensionUnitEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) mounting_depth: Annotated['IntegerLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( diff --git a/netbox/dcim/graphql/filters.py b/netbox/dcim/graphql/filters.py index ccf4a2d98..9e5915146 100644 --- a/netbox/dcim/graphql/filters.py +++ b/netbox/dcim/graphql/filters.py @@ -4,31 +4,27 @@ from django.db.models import Q import strawberry import strawberry_django from strawberry.scalars import ID -from strawberry_django import FilterLookup +from strawberry_django import BaseFilterLookup, ComparisonFilterLookup, FilterLookup -from core.graphql.filter_mixins import ChangeLogFilterMixin from dcim import models from dcim.constants import * from dcim.graphql.enums import InterfaceKindEnum +from dcim.graphql.filter_mixins import ( + ComponentModelFilterMixin, ComponentTemplateFilterMixin, ModularComponentFilterMixin, + ModularComponentTemplateFilterMixin, RackFilterMixin, +) from extras.graphql.filter_mixins import ConfigContextFilterMixin -from netbox.graphql.filter_mixins import ( - PrimaryModelFilterMixin, - OrganizationalModelFilterMixin, - NestedGroupModelFilterMixin, - ImageAttachmentFilterMixin, - WeightFilterMixin, +from netbox.graphql.filter_mixins import ImageAttachmentFilterMixin, WeightFilterMixin +from netbox.graphql.filters import ( + BaseModelFilter, ChangeLoggedModelFilter, NestedGroupModelFilter, OrganizationalModelFilter, PrimaryModelFilter, + NetBoxModelFilter, ) from tenancy.graphql.filter_mixins import ContactFilterMixin, TenancyFilterMixin from virtualization.models import VMInterface from .filter_mixins import ( CabledObjectModelFilterMixin, - ComponentModelFilterMixin, - ComponentTemplateFilterMixin, InterfaceBaseFilterMixin, - ModularComponentModelFilterMixin, - ModularComponentTemplateFilterMixin, - RackBaseFilterMixin, RenderConfigFilterMixin, ) @@ -75,6 +71,8 @@ __all__ = ( 'ModuleTypeFilter', 'ModuleTypeProfileFilter', 'PlatformFilter', + 'PortMappingFilter', + 'PortTemplateMappingFilter', 'PowerFeedFilter', 'PowerOutletFilter', 'PowerOutletTemplateFilter', @@ -96,15 +94,21 @@ __all__ = ( @strawberry_django.filter_type(models.Cable, lookups=True) -class CableFilter(PrimaryModelFilterMixin, TenancyFilterMixin): - type: Annotated['CableTypeEnum', strawberry.lazy('dcim.graphql.enums')] | None = strawberry_django.filter_field() - status: Annotated['LinkStatusEnum', strawberry.lazy('dcim.graphql.enums')] | None = strawberry_django.filter_field() +class CableFilter(TenancyFilterMixin, PrimaryModelFilter): + type: BaseFilterLookup[Annotated['CableTypeEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( + strawberry_django.filter_field() + ) + status: BaseFilterLookup[Annotated['LinkStatusEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( + strawberry_django.filter_field() + ) label: FilterLookup[str] | None = strawberry_django.filter_field() - color: Annotated['ColorEnum', strawberry.lazy('netbox.graphql.enums')] | None = strawberry_django.filter_field() + color: BaseFilterLookup[Annotated['ColorEnum', strawberry.lazy('netbox.graphql.enums')]] | None = ( + strawberry_django.filter_field() + ) length: Annotated['FloatLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( strawberry_django.filter_field() ) - length_unit: Annotated['CableLengthUnitEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + length_unit: BaseFilterLookup[Annotated['CableLengthUnitEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) terminations: Annotated['CableTerminationFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( @@ -113,10 +117,10 @@ class CableFilter(PrimaryModelFilterMixin, TenancyFilterMixin): @strawberry_django.filter_type(models.CableTermination, lookups=True) -class CableTerminationFilter(ChangeLogFilterMixin): +class CableTerminationFilter(ChangeLoggedModelFilter): cable: Annotated['CableFilter', strawberry.lazy('dcim.graphql.filters')] | None = strawberry_django.filter_field() cable_id: ID | None = strawberry_django.filter_field() - cable_end: Annotated['CableEndEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + cable_end: BaseFilterLookup[Annotated['CableEndEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) termination_type: Annotated['CableTerminationFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( @@ -126,35 +130,35 @@ class CableTerminationFilter(ChangeLogFilterMixin): @strawberry_django.filter_type(models.ConsolePort, lookups=True) -class ConsolePortFilter(ModularComponentModelFilterMixin, CabledObjectModelFilterMixin): - type: Annotated['ConsolePortTypeEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( +class ConsolePortFilter(ModularComponentFilterMixin, CabledObjectModelFilterMixin, NetBoxModelFilter): + type: BaseFilterLookup[Annotated['ConsolePortTypeEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) - speed: Annotated['ConsolePortSpeedEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + speed: BaseFilterLookup[Annotated['ConsolePortSpeedEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) @strawberry_django.filter_type(models.ConsolePortTemplate, lookups=True) -class ConsolePortTemplateFilter(ModularComponentTemplateFilterMixin): - type: Annotated['ConsolePortTypeEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( +class ConsolePortTemplateFilter(ModularComponentTemplateFilterMixin, ChangeLoggedModelFilter): + type: BaseFilterLookup[Annotated['ConsolePortTypeEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) @strawberry_django.filter_type(models.ConsoleServerPort, lookups=True) -class ConsoleServerPortFilter(ModularComponentModelFilterMixin, CabledObjectModelFilterMixin): - type: Annotated['ConsolePortTypeEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( +class ConsoleServerPortFilter(ModularComponentFilterMixin, CabledObjectModelFilterMixin, NetBoxModelFilter): + type: BaseFilterLookup[Annotated['ConsolePortTypeEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) - speed: Annotated['ConsolePortSpeedEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + speed: BaseFilterLookup[Annotated['ConsolePortSpeedEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) @strawberry_django.filter_type(models.ConsoleServerPortTemplate, lookups=True) -class ConsoleServerPortTemplateFilter(ModularComponentTemplateFilterMixin): - type: Annotated['ConsolePortTypeEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( +class ConsoleServerPortTemplateFilter(ModularComponentTemplateFilterMixin, ChangeLoggedModelFilter): + type: BaseFilterLookup[Annotated['ConsolePortTypeEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) @@ -166,7 +170,7 @@ class DeviceFilter( ImageAttachmentFilterMixin, RenderConfigFilterMixin, ConfigContextFilterMixin, - PrimaryModelFilterMixin, + PrimaryModelFilter, ): device_type: Annotated['DeviceTypeFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( strawberry_django.filter_field() @@ -195,11 +199,13 @@ class DeviceFilter( position: Annotated['FloatLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( strawberry_django.filter_field() ) - face: Annotated['DeviceFaceEnum', strawberry.lazy('dcim.graphql.enums')] | None = strawberry_django.filter_field() - status: Annotated['DeviceStatusEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + face: BaseFilterLookup[Annotated['DeviceFaceEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) - airflow: Annotated['DeviceAirflowEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + status: BaseFilterLookup[Annotated['DeviceStatusEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( + strawberry_django.filter_field() + ) + airflow: BaseFilterLookup[Annotated['DeviceAirflowEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) primary_ip4: Annotated['IPAddressFilter', strawberry.lazy('ipam.graphql.filters')] | None = ( @@ -277,7 +283,7 @@ class DeviceFilter( @strawberry_django.filter_type(models.DeviceBay, lookups=True) -class DeviceBayFilter(ComponentModelFilterMixin): +class DeviceBayFilter(ComponentModelFilterMixin, NetBoxModelFilter): installed_device: Annotated['DeviceFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( strawberry_django.filter_field() ) @@ -285,12 +291,12 @@ class DeviceBayFilter(ComponentModelFilterMixin): @strawberry_django.filter_type(models.DeviceBayTemplate, lookups=True) -class DeviceBayTemplateFilter(ComponentTemplateFilterMixin): +class DeviceBayTemplateFilter(ComponentTemplateFilterMixin, ChangeLoggedModelFilter): pass @strawberry_django.filter_type(models.InventoryItemTemplate, lookups=True) -class InventoryItemTemplateFilter(ComponentTemplateFilterMixin): +class InventoryItemTemplateFilter(ComponentTemplateFilterMixin, ChangeLoggedModelFilter): parent: Annotated['InventoryItemTemplateFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( strawberry_django.filter_field() ) @@ -310,13 +316,15 @@ class InventoryItemTemplateFilter(ComponentTemplateFilterMixin): @strawberry_django.filter_type(models.DeviceRole, lookups=True) -class DeviceRoleFilter(OrganizationalModelFilterMixin, RenderConfigFilterMixin): - color: Annotated['ColorEnum', strawberry.lazy('netbox.graphql.enums')] | None = strawberry_django.filter_field() +class DeviceRoleFilter(RenderConfigFilterMixin, OrganizationalModelFilter): + color: BaseFilterLookup[Annotated['ColorEnum', strawberry.lazy('netbox.graphql.enums')]] | None = ( + strawberry_django.filter_field() + ) vm_role: FilterLookup[bool] | None = strawberry_django.filter_field() @strawberry_django.filter_type(models.DeviceType, lookups=True) -class DeviceTypeFilter(ImageAttachmentFilterMixin, PrimaryModelFilterMixin, WeightFilterMixin): +class DeviceTypeFilter(ImageAttachmentFilterMixin, WeightFilterMixin, PrimaryModelFilter): manufacturer: Annotated['ManufacturerFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( strawberry_django.filter_field() ) @@ -328,15 +336,18 @@ class DeviceTypeFilter(ImageAttachmentFilterMixin, PrimaryModelFilterMixin, Weig ) default_platform_id: ID | None = strawberry_django.filter_field() part_number: FilterLookup[str] | None = strawberry_django.filter_field() + instances: Annotated['DeviceFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( + strawberry_django.filter_field() + ) u_height: Annotated['FloatLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( strawberry_django.filter_field() ) exclude_from_utilization: FilterLookup[bool] | None = strawberry_django.filter_field() is_full_depth: FilterLookup[bool] | None = strawberry_django.filter_field() - subdevice_role: Annotated['SubdeviceRoleEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + subdevice_role: BaseFilterLookup[Annotated['SubdeviceRoleEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) - airflow: Annotated['DeviceAirflowEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + airflow: BaseFilterLookup[Annotated['DeviceAirflowEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) front_image: Annotated['ImageAttachmentFilter', strawberry.lazy('extras.graphql.filters')] | None = ( @@ -385,36 +396,62 @@ class DeviceTypeFilter(ImageAttachmentFilterMixin, PrimaryModelFilterMixin, Weig device_bay_template_count: FilterLookup[int] | None = strawberry_django.filter_field() module_bay_template_count: FilterLookup[int] | None = strawberry_django.filter_field() inventory_item_template_count: FilterLookup[int] | None = strawberry_django.filter_field() + device_count: ComparisonFilterLookup[int] | None = strawberry_django.filter_field() @strawberry_django.filter_type(models.FrontPort, lookups=True) -class FrontPortFilter(ModularComponentModelFilterMixin, CabledObjectModelFilterMixin): - type: Annotated['PortTypeEnum', strawberry.lazy('dcim.graphql.enums')] | None = strawberry_django.filter_field() - color: Annotated['ColorEnum', strawberry.lazy('netbox.graphql.enums')] | None = strawberry_django.filter_field() - rear_port: Annotated['RearPortFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( +class FrontPortFilter(ModularComponentFilterMixin, CabledObjectModelFilterMixin, NetBoxModelFilter): + type: BaseFilterLookup[Annotated['PortTypeEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) - rear_port_id: ID | None = strawberry_django.filter_field() - rear_port_position: Annotated['IntegerLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( + color: BaseFilterLookup[Annotated['ColorEnum', strawberry.lazy('netbox.graphql.enums')]] | None = ( strawberry_django.filter_field() ) @strawberry_django.filter_type(models.FrontPortTemplate, lookups=True) -class FrontPortTemplateFilter(ModularComponentTemplateFilterMixin): - type: Annotated['PortTypeEnum', strawberry.lazy('dcim.graphql.enums')] | None = strawberry_django.filter_field() - color: Annotated['ColorEnum', strawberry.lazy('netbox.graphql.enums')] | None = strawberry_django.filter_field() +class FrontPortTemplateFilter(ModularComponentTemplateFilterMixin, ChangeLoggedModelFilter): + type: BaseFilterLookup[Annotated['PortTypeEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( + strawberry_django.filter_field() + ) + color: BaseFilterLookup[Annotated['ColorEnum', strawberry.lazy('netbox.graphql.enums')]] | None = ( + strawberry_django.filter_field() + ) + + +@strawberry_django.filter_type(models.PortMapping, lookups=True) +class PortMappingFilter(BaseModelFilter): + device: Annotated['DeviceFilter', strawberry.lazy('dcim.graphql.filters')] | None = strawberry_django.filter_field() + front_port: Annotated['FrontPortFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( + strawberry_django.filter_field() + ) + rear_port: Annotated['RearPortFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( + strawberry_django.filter_field() + ) + front_port_position: FilterLookup[int] | None = strawberry_django.filter_field() + rear_port_position: FilterLookup[int] | None = strawberry_django.filter_field() + + +@strawberry_django.filter_type(models.PortTemplateMapping, lookups=True) +class PortTemplateMappingFilter(BaseModelFilter): + device_type: Annotated['DeviceTypeFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( + strawberry_django.filter_field() + ) + module_type: Annotated['ModuleTypeFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( + strawberry_django.filter_field() + ) + front_port: Annotated['FrontPortTemplateFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( + strawberry_django.filter_field() + ) rear_port: Annotated['RearPortTemplateFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( strawberry_django.filter_field() ) - rear_port_id: ID | None = strawberry_django.filter_field() - rear_port_position: Annotated['IntegerLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( - strawberry_django.filter_field() - ) + front_port_position: FilterLookup[int] | None = strawberry_django.filter_field() + rear_port_position: FilterLookup[int] | None = strawberry_django.filter_field() @strawberry_django.filter_type(models.MACAddress, lookups=True) -class MACAddressFilter(PrimaryModelFilterMixin): +class MACAddressFilter(PrimaryModelFilter): mac_address: FilterLookup[str] | None = strawberry_django.filter_field() assigned_object_type: Annotated['ContentTypeFilter', strawberry.lazy('core.graphql.filters')] | None = ( strawberry_django.filter_field() @@ -441,20 +478,25 @@ class MACAddressFilter(PrimaryModelFilterMixin): @strawberry_django.filter_type(models.Interface, lookups=True) -class InterfaceFilter(ModularComponentModelFilterMixin, InterfaceBaseFilterMixin, CabledObjectModelFilterMixin): +class InterfaceFilter( + ModularComponentFilterMixin, + InterfaceBaseFilterMixin, + CabledObjectModelFilterMixin, + NetBoxModelFilter +): vcdcs: Annotated['VirtualDeviceContextFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( strawberry_django.filter_field() ) lag: Annotated['InterfaceFilter', strawberry.lazy('dcim.graphql.filters')] | None = strawberry_django.filter_field() lag_id: ID | None = strawberry_django.filter_field() - type: Annotated['InterfaceTypeEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + type: BaseFilterLookup[Annotated['InterfaceTypeEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) mgmt_only: FilterLookup[bool] | None = strawberry_django.filter_field() speed: Annotated['IntegerLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( strawberry_django.filter_field() ) - duplex: Annotated['InterfaceDuplexEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + duplex: BaseFilterLookup[Annotated['InterfaceDuplexEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) wwn: FilterLookup[str] | None = strawberry_django.filter_field() @@ -462,10 +504,10 @@ class InterfaceFilter(ModularComponentModelFilterMixin, InterfaceBaseFilterMixin strawberry_django.filter_field() ) parent_id: ID | None = strawberry_django.filter_field() - rf_role: Annotated['WirelessRoleEnum', strawberry.lazy('wireless.graphql.enums')] | None = ( + rf_role: BaseFilterLookup[Annotated['WirelessRoleEnum', strawberry.lazy('wireless.graphql.enums')]] | None = ( strawberry_django.filter_field() ) - rf_channel: Annotated['WirelessChannelEnum', strawberry.lazy('wireless.graphql.enums')] | None = ( + rf_channel: BaseFilterLookup[Annotated['WirelessChannelEnum', strawberry.lazy('wireless.graphql.enums')]] | None = ( strawberry_django.filter_field() ) rf_channel_frequency: Annotated['FloatLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( @@ -477,10 +519,10 @@ class InterfaceFilter(ModularComponentModelFilterMixin, InterfaceBaseFilterMixin tx_power: Annotated['IntegerLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( strawberry_django.filter_field() ) - poe_mode: Annotated['InterfacePoEModeEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + poe_mode: BaseFilterLookup[Annotated['InterfacePoEModeEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) - poe_type: Annotated['InterfacePoETypeEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + poe_type: BaseFilterLookup[Annotated['InterfacePoETypeEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) wireless_link: Annotated['WirelessLinkFilter', strawberry.lazy('wireless.graphql.filters')] | None = ( @@ -531,8 +573,8 @@ class InterfaceFilter(ModularComponentModelFilterMixin, InterfaceBaseFilterMixin @strawberry_django.filter_type(models.InterfaceTemplate, lookups=True) -class InterfaceTemplateFilter(ModularComponentTemplateFilterMixin): - type: Annotated['InterfaceTypeEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( +class InterfaceTemplateFilter(ModularComponentTemplateFilterMixin, ChangeLoggedModelFilter): + type: BaseFilterLookup[Annotated['InterfaceTypeEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) enabled: FilterLookup[bool] | None = strawberry_django.filter_field() @@ -541,19 +583,19 @@ class InterfaceTemplateFilter(ModularComponentTemplateFilterMixin): strawberry_django.filter_field() ) bridge_id: ID | None = strawberry_django.filter_field() - poe_mode: Annotated['InterfacePoEModeEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + poe_mode: BaseFilterLookup[Annotated['InterfacePoEModeEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) - poe_type: Annotated['InterfacePoETypeEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + poe_type: BaseFilterLookup[Annotated['InterfacePoETypeEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) - rf_role: Annotated['WirelessRoleEnum', strawberry.lazy('wireless.graphql.enums')] | None = ( + rf_role: BaseFilterLookup[Annotated['WirelessRoleEnum', strawberry.lazy('wireless.graphql.enums')]] | None = ( strawberry_django.filter_field() ) @strawberry_django.filter_type(models.InventoryItem, lookups=True) -class InventoryItemFilter(ComponentModelFilterMixin): +class InventoryItemFilter(ComponentModelFilterMixin, NetBoxModelFilter): parent: Annotated['InventoryItemFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( strawberry_django.filter_field() ) @@ -562,7 +604,7 @@ class InventoryItemFilter(ComponentModelFilterMixin): strawberry_django.filter_field() ) component_id: ID | None = strawberry_django.filter_field() - status: Annotated['InventoryItemStatusEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + status: BaseFilterLookup[Annotated['InventoryItemStatusEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) role: Annotated['InventoryItemRoleFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( @@ -580,15 +622,17 @@ class InventoryItemFilter(ComponentModelFilterMixin): @strawberry_django.filter_type(models.InventoryItemRole, lookups=True) -class InventoryItemRoleFilter(OrganizationalModelFilterMixin): - color: Annotated['ColorEnum', strawberry.lazy('netbox.graphql.enums')] | None = strawberry_django.filter_field() +class InventoryItemRoleFilter(OrganizationalModelFilter): + color: BaseFilterLookup[Annotated['ColorEnum', strawberry.lazy('netbox.graphql.enums')]] | None = ( + strawberry_django.filter_field() + ) @strawberry_django.filter_type(models.Location, lookups=True) -class LocationFilter(ContactFilterMixin, ImageAttachmentFilterMixin, TenancyFilterMixin, NestedGroupModelFilterMixin): +class LocationFilter(ContactFilterMixin, ImageAttachmentFilterMixin, TenancyFilterMixin, NestedGroupModelFilter): site: Annotated['SiteFilter', strawberry.lazy('dcim.graphql.filters')] | None = strawberry_django.filter_field() site_id: ID | None = strawberry_django.filter_field() - status: Annotated['LocationStatusEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + status: BaseFilterLookup[Annotated['LocationStatusEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) facility: FilterLookup[str] | None = strawberry_django.filter_field() @@ -601,12 +645,12 @@ class LocationFilter(ContactFilterMixin, ImageAttachmentFilterMixin, TenancyFilt @strawberry_django.filter_type(models.Manufacturer, lookups=True) -class ManufacturerFilter(ContactFilterMixin, OrganizationalModelFilterMixin): +class ManufacturerFilter(ContactFilterMixin, OrganizationalModelFilter): pass @strawberry_django.filter_type(models.Module, lookups=True) -class ModuleFilter(PrimaryModelFilterMixin, ConfigContextFilterMixin): +class ModuleFilter(ConfigContextFilterMixin, PrimaryModelFilter): device: Annotated['DeviceFilter', strawberry.lazy('dcim.graphql.filters')] | None = strawberry_django.filter_field() device_id: ID | None = strawberry_django.filter_field() module_bay: Annotated['ModuleBayFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( @@ -617,7 +661,7 @@ class ModuleFilter(PrimaryModelFilterMixin, ConfigContextFilterMixin): strawberry_django.filter_field() ) module_type_id: ID | None = strawberry_django.filter_field() - status: Annotated['ModuleStatusEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + status: BaseFilterLookup[Annotated['ModuleStatusEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) serial: FilterLookup[str] | None = strawberry_django.filter_field() @@ -655,7 +699,7 @@ class ModuleFilter(PrimaryModelFilterMixin, ConfigContextFilterMixin): @strawberry_django.filter_type(models.ModuleBay, lookups=True) -class ModuleBayFilter(ModularComponentModelFilterMixin): +class ModuleBayFilter(ModularComponentFilterMixin, NetBoxModelFilter): parent: Annotated['ModuleBayFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( strawberry_django.filter_field() ) @@ -664,17 +708,17 @@ class ModuleBayFilter(ModularComponentModelFilterMixin): @strawberry_django.filter_type(models.ModuleBayTemplate, lookups=True) -class ModuleBayTemplateFilter(ModularComponentTemplateFilterMixin): +class ModuleBayTemplateFilter(ModularComponentTemplateFilterMixin, ChangeLoggedModelFilter): position: FilterLookup[str] | None = strawberry_django.filter_field() @strawberry_django.filter_type(models.ModuleTypeProfile, lookups=True) -class ModuleTypeProfileFilter(PrimaryModelFilterMixin): +class ModuleTypeProfileFilter(PrimaryModelFilter): name: FilterLookup[str] | None = strawberry_django.filter_field() @strawberry_django.filter_type(models.ModuleType, lookups=True) -class ModuleTypeFilter(ImageAttachmentFilterMixin, PrimaryModelFilterMixin, WeightFilterMixin): +class ModuleTypeFilter(ImageAttachmentFilterMixin, WeightFilterMixin, PrimaryModelFilter): manufacturer: Annotated['ManufacturerFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( strawberry_django.filter_field() ) @@ -685,7 +729,10 @@ class ModuleTypeFilter(ImageAttachmentFilterMixin, PrimaryModelFilterMixin, Weig profile_id: ID | None = strawberry_django.filter_field() model: FilterLookup[str] | None = strawberry_django.filter_field() part_number: FilterLookup[str] | None = strawberry_django.filter_field() - airflow: Annotated['ModuleAirflowEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + instances: Annotated['ModuleFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( + strawberry_django.filter_field() + ) + airflow: BaseFilterLookup[Annotated['ModuleAirflowEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) console_port_templates: ( @@ -718,10 +765,11 @@ class ModuleTypeFilter(ImageAttachmentFilterMixin, PrimaryModelFilterMixin, Weig inventory_item_templates: ( Annotated['InventoryItemTemplateFilter', strawberry.lazy('dcim.graphql.filters')] | None ) = strawberry_django.filter_field() + module_count: ComparisonFilterLookup[int] | None = strawberry_django.filter_field() @strawberry_django.filter_type(models.Platform, lookups=True) -class PlatformFilter(OrganizationalModelFilterMixin): +class PlatformFilter(OrganizationalModelFilter): manufacturer: Annotated['ManufacturerFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( strawberry_django.filter_field() ) @@ -733,7 +781,7 @@ class PlatformFilter(OrganizationalModelFilterMixin): @strawberry_django.filter_type(models.PowerFeed, lookups=True) -class PowerFeedFilter(CabledObjectModelFilterMixin, TenancyFilterMixin, PrimaryModelFilterMixin): +class PowerFeedFilter(CabledObjectModelFilterMixin, TenancyFilterMixin, PrimaryModelFilter): power_panel: Annotated['PowerPanelFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( strawberry_django.filter_field() ) @@ -741,16 +789,16 @@ class PowerFeedFilter(CabledObjectModelFilterMixin, TenancyFilterMixin, PrimaryM rack: Annotated['RackFilter', strawberry.lazy('dcim.graphql.filters')] | None = strawberry_django.filter_field() rack_id: ID | None = strawberry_django.filter_field() name: FilterLookup[str] | None = strawberry_django.filter_field() - status: Annotated['PowerFeedStatusEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + status: BaseFilterLookup[Annotated['PowerFeedStatusEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) - type: Annotated['PowerFeedTypeEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + type: BaseFilterLookup[Annotated['PowerFeedTypeEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) - supply: Annotated['PowerFeedSupplyEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + supply: BaseFilterLookup[Annotated['PowerFeedSupplyEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) - phase: Annotated['PowerFeedPhaseEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + phase: BaseFilterLookup[Annotated['PowerFeedPhaseEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) voltage: Annotated['IntegerLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( @@ -768,36 +816,41 @@ class PowerFeedFilter(CabledObjectModelFilterMixin, TenancyFilterMixin, PrimaryM @strawberry_django.filter_type(models.PowerOutlet, lookups=True) -class PowerOutletFilter(ModularComponentModelFilterMixin, CabledObjectModelFilterMixin): - type: Annotated['PowerOutletTypeEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( +class PowerOutletFilter(ModularComponentFilterMixin, CabledObjectModelFilterMixin, NetBoxModelFilter): + type: BaseFilterLookup[Annotated['PowerOutletTypeEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) power_port: Annotated['PowerPortFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( strawberry_django.filter_field() ) power_port_id: ID | None = strawberry_django.filter_field() - feed_leg: Annotated['PowerOutletFeedLegEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + feed_leg: BaseFilterLookup[Annotated['PowerOutletFeedLegEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( + strawberry_django.filter_field() + ) + color: BaseFilterLookup[Annotated['ColorEnum', strawberry.lazy('netbox.graphql.enums')]] | None = ( + strawberry_django.filter_field() + ) + status: BaseFilterLookup[Annotated['PowerOutletStatusEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) - color: Annotated['ColorEnum', strawberry.lazy('netbox.graphql.enums')] | None = strawberry_django.filter_field() @strawberry_django.filter_type(models.PowerOutletTemplate, lookups=True) -class PowerOutletTemplateFilter(ModularComponentModelFilterMixin): - type: Annotated['PowerOutletTypeEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( +class PowerOutletTemplateFilter(ModularComponentTemplateFilterMixin, ChangeLoggedModelFilter): + type: BaseFilterLookup[Annotated['PowerOutletTypeEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) power_port: Annotated['PowerPortTemplateFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( strawberry_django.filter_field() ) power_port_id: ID | None = strawberry_django.filter_field() - feed_leg: Annotated['PowerOutletFeedLegEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + feed_leg: BaseFilterLookup[Annotated['PowerOutletFeedLegEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) @strawberry_django.filter_type(models.PowerPanel, lookups=True) -class PowerPanelFilter(ContactFilterMixin, ImageAttachmentFilterMixin, PrimaryModelFilterMixin): +class PowerPanelFilter(ContactFilterMixin, ImageAttachmentFilterMixin, PrimaryModelFilter): site: Annotated['SiteFilter', strawberry.lazy('dcim.graphql.filters')] | None = strawberry_django.filter_field() site_id: ID | None = strawberry_django.filter_field() location: Annotated['LocationFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( @@ -810,8 +863,8 @@ class PowerPanelFilter(ContactFilterMixin, ImageAttachmentFilterMixin, PrimaryMo @strawberry_django.filter_type(models.PowerPort, lookups=True) -class PowerPortFilter(ModularComponentModelFilterMixin, CabledObjectModelFilterMixin): - type: Annotated['PowerPortTypeEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( +class PowerPortFilter(ModularComponentFilterMixin, CabledObjectModelFilterMixin, NetBoxModelFilter): + type: BaseFilterLookup[Annotated['PowerPortTypeEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) maximum_draw: Annotated['IntegerLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( @@ -823,8 +876,8 @@ class PowerPortFilter(ModularComponentModelFilterMixin, CabledObjectModelFilterM @strawberry_django.filter_type(models.PowerPortTemplate, lookups=True) -class PowerPortTemplateFilter(ModularComponentTemplateFilterMixin): - type: Annotated['PowerPortTypeEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( +class PowerPortTemplateFilter(ModularComponentTemplateFilterMixin, ChangeLoggedModelFilter): + type: BaseFilterLookup[Annotated['PowerPortTypeEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) maximum_draw: Annotated['IntegerLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( @@ -836,8 +889,8 @@ class PowerPortTemplateFilter(ModularComponentTemplateFilterMixin): @strawberry_django.filter_type(models.RackType, lookups=True) -class RackTypeFilter(RackBaseFilterMixin): - form_factor: Annotated['RackFormFactorEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( +class RackTypeFilter(RackFilterMixin, WeightFilterMixin, PrimaryModelFilter): + form_factor: BaseFilterLookup[Annotated['RackFormFactorEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) manufacturer: Annotated['ManufacturerFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( @@ -846,11 +899,20 @@ class RackTypeFilter(RackBaseFilterMixin): manufacturer_id: ID | None = strawberry_django.filter_field() model: FilterLookup[str] | None = strawberry_django.filter_field() slug: FilterLookup[str] | None = strawberry_django.filter_field() + racks: Annotated['RackFilter', strawberry.lazy('dcim.graphql.filters')] | None = strawberry_django.filter_field() + rack_count: ComparisonFilterLookup[int] | None = strawberry_django.filter_field() @strawberry_django.filter_type(models.Rack, lookups=True) -class RackFilter(ContactFilterMixin, ImageAttachmentFilterMixin, TenancyFilterMixin, RackBaseFilterMixin): - form_factor: Annotated['RackFormFactorEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( +class RackFilter( + ContactFilterMixin, + ImageAttachmentFilterMixin, + TenancyFilterMixin, + WeightFilterMixin, + RackFilterMixin, + PrimaryModelFilter +): + form_factor: BaseFilterLookup[Annotated['RackFormFactorEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) rack_type: Annotated['RackTypeFilter', strawberry.lazy('dcim.graphql.filters')] | None = ( @@ -867,12 +929,14 @@ class RackFilter(ContactFilterMixin, ImageAttachmentFilterMixin, TenancyFilterMi location_id: Annotated['TreeNodeFilter', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( strawberry_django.filter_field() ) - status: Annotated['RackStatusEnum', strawberry.lazy('dcim.graphql.enums')] | None = strawberry_django.filter_field() + status: BaseFilterLookup[Annotated['RackStatusEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( + strawberry_django.filter_field() + ) role: Annotated['RackRoleFilter', strawberry.lazy('dcim.graphql.filters')] | None = strawberry_django.filter_field() role_id: ID | None = strawberry_django.filter_field() serial: FilterLookup[str] | None = strawberry_django.filter_field() asset_tag: FilterLookup[str] | None = strawberry_django.filter_field() - airflow: Annotated['RackAirflowEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + airflow: BaseFilterLookup[Annotated['RackAirflowEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( strawberry_django.filter_field() ) vlan_groups: Annotated['VLANGroupFilter', strawberry.lazy('ipam.graphql.filters')] | None = ( @@ -881,7 +945,7 @@ class RackFilter(ContactFilterMixin, ImageAttachmentFilterMixin, TenancyFilterMi @strawberry_django.filter_type(models.RackReservation, lookups=True) -class RackReservationFilter(TenancyFilterMixin, PrimaryModelFilterMixin): +class RackReservationFilter(TenancyFilterMixin, PrimaryModelFilter): rack: Annotated['RackFilter', strawberry.lazy('dcim.graphql.filters')] | None = strawberry_django.filter_field() rack_id: ID | None = strawberry_django.filter_field() units: Annotated['IntegerArrayLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( @@ -890,33 +954,46 @@ class RackReservationFilter(TenancyFilterMixin, PrimaryModelFilterMixin): user: Annotated['UserFilter', strawberry.lazy('users.graphql.filters')] | None = strawberry_django.filter_field() user_id: ID | None = strawberry_django.filter_field() description: FilterLookup[str] | None = strawberry_django.filter_field() + status: BaseFilterLookup[Annotated['RackReservationStatusEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( + strawberry_django.filter_field() + ) @strawberry_django.filter_type(models.RackRole, lookups=True) -class RackRoleFilter(OrganizationalModelFilterMixin): - color: Annotated['ColorEnum', strawberry.lazy('netbox.graphql.enums')] | None = strawberry_django.filter_field() +class RackRoleFilter(OrganizationalModelFilter): + color: BaseFilterLookup[Annotated['ColorEnum', strawberry.lazy('netbox.graphql.enums')]] | None = ( + strawberry_django.filter_field() + ) @strawberry_django.filter_type(models.RearPort, lookups=True) -class RearPortFilter(ModularComponentModelFilterMixin, CabledObjectModelFilterMixin): - type: Annotated['PortTypeEnum', strawberry.lazy('dcim.graphql.enums')] | None = strawberry_django.filter_field() - color: Annotated['ColorEnum', strawberry.lazy('netbox.graphql.enums')] | None = strawberry_django.filter_field() +class RearPortFilter(ModularComponentFilterMixin, CabledObjectModelFilterMixin, NetBoxModelFilter): + type: BaseFilterLookup[Annotated['PortTypeEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( + strawberry_django.filter_field() + ) + color: BaseFilterLookup[Annotated['ColorEnum', strawberry.lazy('netbox.graphql.enums')]] | None = ( + strawberry_django.filter_field() + ) positions: Annotated['IntegerLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( strawberry_django.filter_field() ) @strawberry_django.filter_type(models.RearPortTemplate, lookups=True) -class RearPortTemplateFilter(ModularComponentTemplateFilterMixin): - type: Annotated['PortTypeEnum', strawberry.lazy('dcim.graphql.enums')] | None = strawberry_django.filter_field() - color: Annotated['ColorEnum', strawberry.lazy('netbox.graphql.enums')] | None = strawberry_django.filter_field() +class RearPortTemplateFilter(ModularComponentTemplateFilterMixin, ChangeLoggedModelFilter): + type: BaseFilterLookup[Annotated['PortTypeEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( + strawberry_django.filter_field() + ) + color: BaseFilterLookup[Annotated['ColorEnum', strawberry.lazy('netbox.graphql.enums')]] | None = ( + strawberry_django.filter_field() + ) positions: Annotated['IntegerLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( strawberry_django.filter_field() ) @strawberry_django.filter_type(models.Region, lookups=True) -class RegionFilter(ContactFilterMixin, NestedGroupModelFilterMixin): +class RegionFilter(ContactFilterMixin, NestedGroupModelFilter): prefixes: Annotated['PrefixFilter', strawberry.lazy('ipam.graphql.filters')] | None = ( strawberry_django.filter_field() ) @@ -926,10 +1003,12 @@ class RegionFilter(ContactFilterMixin, NestedGroupModelFilterMixin): @strawberry_django.filter_type(models.Site, lookups=True) -class SiteFilter(ContactFilterMixin, ImageAttachmentFilterMixin, TenancyFilterMixin, PrimaryModelFilterMixin): +class SiteFilter(ContactFilterMixin, ImageAttachmentFilterMixin, TenancyFilterMixin, PrimaryModelFilter): name: FilterLookup[str] | None = strawberry_django.filter_field() slug: FilterLookup[str] | None = strawberry_django.filter_field() - status: Annotated['SiteStatusEnum', strawberry.lazy('dcim.graphql.enums')] | None = strawberry_django.filter_field() + status: BaseFilterLookup[Annotated['SiteStatusEnum', strawberry.lazy('dcim.graphql.enums')]] | None = ( + strawberry_django.filter_field() + ) region: Annotated['RegionFilter', strawberry.lazy('dcim.graphql.filters')] | None = strawberry_django.filter_field() region_id: Annotated['TreeNodeFilter', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( strawberry_django.filter_field() @@ -960,7 +1039,7 @@ class SiteFilter(ContactFilterMixin, ImageAttachmentFilterMixin, TenancyFilterMi @strawberry_django.filter_type(models.SiteGroup, lookups=True) -class SiteGroupFilter(ContactFilterMixin, NestedGroupModelFilterMixin): +class SiteGroupFilter(ContactFilterMixin, NestedGroupModelFilter): prefixes: Annotated['PrefixFilter', strawberry.lazy('ipam.graphql.filters')] | None = ( strawberry_django.filter_field() ) @@ -970,7 +1049,7 @@ class SiteGroupFilter(ContactFilterMixin, NestedGroupModelFilterMixin): @strawberry_django.filter_type(models.VirtualChassis, lookups=True) -class VirtualChassisFilter(PrimaryModelFilterMixin): +class VirtualChassisFilter(PrimaryModelFilter): master: Annotated['DeviceFilter', strawberry.lazy('dcim.graphql.filters')] | None = strawberry_django.filter_field() master_id: ID | None = strawberry_django.filter_field() name: FilterLookup[str] | None = strawberry_django.filter_field() @@ -982,11 +1061,13 @@ class VirtualChassisFilter(PrimaryModelFilterMixin): @strawberry_django.filter_type(models.VirtualDeviceContext, lookups=True) -class VirtualDeviceContextFilter(TenancyFilterMixin, PrimaryModelFilterMixin): +class VirtualDeviceContextFilter(TenancyFilterMixin, PrimaryModelFilter): device: Annotated['DeviceFilter', strawberry.lazy('dcim.graphql.filters')] | None = strawberry_django.filter_field() device_id: ID | None = strawberry_django.filter_field() name: FilterLookup[str] | None = strawberry_django.filter_field() - status: Annotated['VirtualDeviceContextStatusEnum', strawberry.lazy('dcim.graphql.enums')] | None = ( + status: ( + BaseFilterLookup[Annotated['VirtualDeviceContextStatusEnum', strawberry.lazy('dcim.graphql.enums')]] | None + ) = ( strawberry_django.filter_field() ) identifier: Annotated['IntegerLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( diff --git a/netbox/dcim/graphql/types.py b/netbox/dcim/graphql/types.py index 0cd5e8fd1..1132a0ca9 100644 --- a/netbox/dcim/graphql/types.py +++ b/netbox/dcim/graphql/types.py @@ -5,16 +5,13 @@ import strawberry_django from core.graphql.mixins import ChangelogMixin from dcim import models -from extras.graphql.mixins import ( - ConfigContextMixin, - ContactsMixin, - CustomFieldsMixin, - ImageAttachmentsMixin, - TagsMixin, -) +from extras.graphql.mixins import ConfigContextMixin, ContactsMixin, ImageAttachmentsMixin from ipam.graphql.mixins import IPAddressesMixin, VLANGroupsMixin from netbox.graphql.scalars import BigInt -from netbox.graphql.types import BaseObjectType, NetBoxObjectType, OrganizationalObjectType +from netbox.graphql.types import ( + BaseObjectType, NestedGroupObjectType, NetBoxObjectType, OrganizationalObjectType, PrimaryObjectType, +) +from users.graphql.mixins import OwnerMixin from .filters import * from .mixins import CabledObjectMixin, PathEndpointMixin @@ -91,12 +88,7 @@ __all__ = ( @strawberry.type -class ComponentType( - ChangelogMixin, - CustomFieldsMixin, - TagsMixin, - BaseObjectType -): +class ComponentType(OwnerMixin, NetBoxObjectType): """ Base type for device/VM components """ @@ -159,7 +151,7 @@ class CableTerminationType(NetBoxObjectType): filters=CableFilter, pagination=True ) -class CableType(NetBoxObjectType): +class CableType(PrimaryObjectType): color: str tenant: Annotated["TenantType", strawberry.lazy('tenancy.graphql.types')] | None @@ -236,7 +228,7 @@ class ConsoleServerPortTemplateType(ModularComponentTemplateType): filters=DeviceFilter, pagination=True ) -class DeviceType(ConfigContextMixin, ImageAttachmentsMixin, ContactsMixin, NetBoxObjectType): +class DeviceType(ConfigContextMixin, ImageAttachmentsMixin, ContactsMixin, PrimaryObjectType): console_port_count: BigInt console_server_port_count: BigInt power_port_count: BigInt @@ -339,7 +331,7 @@ class InventoryItemTemplateType(ComponentTemplateType): filters=DeviceRoleFilter, pagination=True ) -class DeviceRoleType(OrganizationalObjectType): +class DeviceRoleType(NestedGroupObjectType): parent: Annotated['DeviceRoleType', strawberry.lazy('dcim.graphql.types')] | None children: List[Annotated['DeviceRoleType', strawberry.lazy('dcim.graphql.types')]] color: str @@ -355,7 +347,7 @@ class DeviceRoleType(OrganizationalObjectType): filters=DeviceTypeFilter, pagination=True ) -class DeviceTypeType(NetBoxObjectType): +class DeviceTypeType(PrimaryObjectType): console_port_template_count: BigInt console_server_port_template_count: BigInt power_port_template_count: BigInt @@ -366,6 +358,7 @@ class DeviceTypeType(NetBoxObjectType): device_bay_template_count: BigInt module_bay_template_count: BigInt inventory_item_template_count: BigInt + device_count: BigInt front_image: strawberry_django.fields.types.DjangoImageType | None rear_image: strawberry_django.fields.types.DjangoImageType | None manufacturer: Annotated["ManufacturerType", strawberry.lazy('dcim.graphql.types')] @@ -392,7 +385,8 @@ class DeviceTypeType(NetBoxObjectType): ) class FrontPortType(ModularComponentType, CabledObjectMixin): color: str - rear_port: Annotated["RearPortType", strawberry.lazy('dcim.graphql.types')] + + mappings: List[Annotated["PortMappingType", strawberry.lazy('dcim.graphql.types')]] @strawberry_django.type( @@ -403,7 +397,8 @@ class FrontPortType(ModularComponentType, CabledObjectMixin): ) class FrontPortTemplateType(ModularComponentTemplateType): color: str - rear_port: Annotated["RearPortTemplateType", strawberry.lazy('dcim.graphql.types')] + + mappings: List[Annotated["PortMappingTemplateType", strawberry.lazy('dcim.graphql.types')]] @strawberry_django.type( @@ -412,7 +407,7 @@ class FrontPortTemplateType(ModularComponentTemplateType): filters=MACAddressFilter, pagination=True ) -class MACAddressType(NetBoxObjectType): +class MACAddressType(PrimaryObjectType): mac_address: str @strawberry_django.field @@ -512,7 +507,7 @@ class InventoryItemRoleType(OrganizationalObjectType): filters=LocationFilter, pagination=True ) -class LocationType(VLANGroupsMixin, ImageAttachmentsMixin, ContactsMixin, OrganizationalObjectType): +class LocationType(VLANGroupsMixin, ImageAttachmentsMixin, ContactsMixin, NestedGroupObjectType): site: Annotated["SiteType", strawberry.lazy('dcim.graphql.types')] tenant: Annotated["TenantType", strawberry.lazy('tenancy.graphql.types')] | None parent: Annotated["LocationType", strawberry.lazy('dcim.graphql.types')] | None @@ -555,7 +550,7 @@ class ManufacturerType(OrganizationalObjectType, ContactsMixin): filters=ModuleFilter, pagination=True ) -class ModuleType(NetBoxObjectType): +class ModuleType(PrimaryObjectType): device: Annotated["DeviceType", strawberry.lazy('dcim.graphql.types')] module_bay: Annotated["ModuleBayType", strawberry.lazy('dcim.graphql.types')] module_type: Annotated["ModuleTypeType", strawberry.lazy('dcim.graphql.types')] @@ -602,7 +597,7 @@ class ModuleBayTemplateType(ModularComponentTemplateType): filters=ModuleTypeProfileFilter, pagination=True ) -class ModuleTypeProfileType(NetBoxObjectType): +class ModuleTypeProfileType(PrimaryObjectType): module_types: List[Annotated["ModuleType", strawberry.lazy('dcim.graphql.types')]] @@ -612,7 +607,8 @@ class ModuleTypeProfileType(NetBoxObjectType): filters=ModuleTypeFilter, pagination=True ) -class ModuleTypeType(NetBoxObjectType): +class ModuleTypeType(PrimaryObjectType): + module_count: BigInt profile: Annotated["ModuleTypeProfileType", strawberry.lazy('dcim.graphql.types')] | None manufacturer: Annotated["ManufacturerType", strawberry.lazy('dcim.graphql.types')] @@ -632,7 +628,7 @@ class ModuleTypeType(NetBoxObjectType): filters=PlatformFilter, pagination=True ) -class PlatformType(OrganizationalObjectType): +class PlatformType(NestedGroupObjectType): parent: Annotated['PlatformType', strawberry.lazy('dcim.graphql.types')] | None children: List[Annotated['PlatformType', strawberry.lazy('dcim.graphql.types')]] manufacturer: Annotated["ManufacturerType", strawberry.lazy('dcim.graphql.types')] | None @@ -642,13 +638,35 @@ class PlatformType(OrganizationalObjectType): devices: List[Annotated["DeviceType", strawberry.lazy('dcim.graphql.types')]] +@strawberry_django.type( + models.PortMapping, + fields='__all__', + filters=PortMappingFilter, + pagination=True +) +class PortMappingType(ModularComponentTemplateType): + front_port: Annotated["FrontPortType", strawberry.lazy('dcim.graphql.types')] + rear_port: Annotated["RearPortType", strawberry.lazy('dcim.graphql.types')] + + +@strawberry_django.type( + models.PortTemplateMapping, + fields='__all__', + filters=PortTemplateMappingFilter, + pagination=True +) +class PortMappingTemplateType(ModularComponentTemplateType): + front_port: Annotated["FrontPortTemplateType", strawberry.lazy('dcim.graphql.types')] + rear_port: Annotated["RearPortTemplateType", strawberry.lazy('dcim.graphql.types')] + + @strawberry_django.type( models.PowerFeed, exclude=['_path'], filters=PowerFeedFilter, pagination=True ) -class PowerFeedType(NetBoxObjectType, CabledObjectMixin, PathEndpointMixin): +class PowerFeedType(CabledObjectMixin, PathEndpointMixin, PrimaryObjectType): power_panel: Annotated["PowerPanelType", strawberry.lazy('dcim.graphql.types')] rack: Annotated["RackType", strawberry.lazy('dcim.graphql.types')] | None tenant: Annotated["TenantType", strawberry.lazy('tenancy.graphql.types')] | None @@ -673,6 +691,7 @@ class PowerOutletType(ModularComponentType, CabledObjectMixin, PathEndpointMixin ) class PowerOutletTemplateType(ModularComponentTemplateType): power_port: Annotated["PowerPortTemplateType", strawberry.lazy('dcim.graphql.types')] | None + color: str @strawberry_django.type( @@ -681,7 +700,7 @@ class PowerOutletTemplateType(ModularComponentTemplateType): filters=PowerPanelFilter, pagination=True ) -class PowerPanelType(NetBoxObjectType, ContactsMixin): +class PowerPanelType(ContactsMixin, PrimaryObjectType): site: Annotated["SiteType", strawberry.lazy('dcim.graphql.types')] location: Annotated["LocationType", strawberry.lazy('dcim.graphql.types')] | None @@ -715,7 +734,8 @@ class PowerPortTemplateType(ModularComponentTemplateType): filters=RackTypeFilter, pagination=True ) -class RackTypeType(NetBoxObjectType): +class RackTypeType(PrimaryObjectType): + rack_count: BigInt manufacturer: Annotated["ManufacturerType", strawberry.lazy('dcim.graphql.types')] @@ -725,7 +745,7 @@ class RackTypeType(NetBoxObjectType): filters=RackFilter, pagination=True ) -class RackType(VLANGroupsMixin, ImageAttachmentsMixin, ContactsMixin, NetBoxObjectType): +class RackType(VLANGroupsMixin, ImageAttachmentsMixin, ContactsMixin, PrimaryObjectType): site: Annotated["SiteType", strawberry.lazy('dcim.graphql.types')] location: Annotated["LocationType", strawberry.lazy('dcim.graphql.types')] | None tenant: Annotated["TenantType", strawberry.lazy('tenancy.graphql.types')] | None @@ -744,7 +764,7 @@ class RackType(VLANGroupsMixin, ImageAttachmentsMixin, ContactsMixin, NetBoxObje filters=RackReservationFilter, pagination=True ) -class RackReservationType(NetBoxObjectType): +class RackReservationType(PrimaryObjectType): units: List[int] rack: Annotated["RackType", strawberry.lazy('dcim.graphql.types')] tenant: Annotated["TenantType", strawberry.lazy('tenancy.graphql.types')] | None @@ -772,7 +792,7 @@ class RackRoleType(OrganizationalObjectType): class RearPortType(ModularComponentType, CabledObjectMixin): color: str - frontports: List[Annotated["FrontPortType", strawberry.lazy('dcim.graphql.types')]] + mappings: List[Annotated["PortMappingType", strawberry.lazy('dcim.graphql.types')]] @strawberry_django.type( @@ -784,7 +804,7 @@ class RearPortType(ModularComponentType, CabledObjectMixin): class RearPortTemplateType(ModularComponentTemplateType): color: str - frontport_templates: List[Annotated["FrontPortTemplateType", strawberry.lazy('dcim.graphql.types')]] + mappings: List[Annotated["PortMappingTemplateType", strawberry.lazy('dcim.graphql.types')]] @strawberry_django.type( @@ -793,7 +813,7 @@ class RearPortTemplateType(ModularComponentTemplateType): filters=RegionFilter, pagination=True ) -class RegionType(VLANGroupsMixin, ContactsMixin, OrganizationalObjectType): +class RegionType(VLANGroupsMixin, ContactsMixin, NestedGroupObjectType): sites: List[Annotated["SiteType", strawberry.lazy('dcim.graphql.types')]] children: List[Annotated["RegionType", strawberry.lazy('dcim.graphql.types')]] @@ -819,7 +839,7 @@ class RegionType(VLANGroupsMixin, ContactsMixin, OrganizationalObjectType): filters=SiteFilter, pagination=True ) -class SiteType(VLANGroupsMixin, ImageAttachmentsMixin, ContactsMixin, NetBoxObjectType): +class SiteType(VLANGroupsMixin, ImageAttachmentsMixin, ContactsMixin, PrimaryObjectType): time_zone: str | None region: Annotated["RegionType", strawberry.lazy('dcim.graphql.types')] | None group: Annotated["SiteGroupType", strawberry.lazy('dcim.graphql.types')] | None @@ -854,7 +874,7 @@ class SiteType(VLANGroupsMixin, ImageAttachmentsMixin, ContactsMixin, NetBoxObje filters=SiteGroupFilter, pagination=True ) -class SiteGroupType(VLANGroupsMixin, ContactsMixin, OrganizationalObjectType): +class SiteGroupType(VLANGroupsMixin, ContactsMixin, NestedGroupObjectType): sites: List[Annotated["SiteType", strawberry.lazy('dcim.graphql.types')]] children: List[Annotated["SiteGroupType", strawberry.lazy('dcim.graphql.types')]] @@ -880,7 +900,7 @@ class SiteGroupType(VLANGroupsMixin, ContactsMixin, OrganizationalObjectType): filters=VirtualChassisFilter, pagination=True ) -class VirtualChassisType(NetBoxObjectType): +class VirtualChassisType(PrimaryObjectType): member_count: BigInt master: Annotated["DeviceType", strawberry.lazy('dcim.graphql.types')] | None @@ -893,7 +913,7 @@ class VirtualChassisType(NetBoxObjectType): filters=VirtualDeviceContextFilter, pagination=True ) -class VirtualDeviceContextType(NetBoxObjectType): +class VirtualDeviceContextType(PrimaryObjectType): device: Annotated["DeviceType", strawberry.lazy('dcim.graphql.types')] | None primary_ip4: Annotated["IPAddressType", strawberry.lazy('ipam.graphql.types')] | None primary_ip6: Annotated["IPAddressType", strawberry.lazy('ipam.graphql.types')] | None diff --git a/netbox/dcim/management/commands/trace_paths.py b/netbox/dcim/management/commands/trace_paths.py index 592aeb6a7..ded4e1780 100644 --- a/netbox/dcim/management/commands/trace_paths.py +++ b/netbox/dcim/management/commands/trace_paths.py @@ -4,7 +4,7 @@ from django.db import connection from django.db.models import Q from dcim.models import CablePath, ConsolePort, ConsoleServerPort, Interface, PowerFeed, PowerOutlet, PowerPort -from dcim.signals import create_cablepath +from dcim.signals import create_cablepaths ENDPOINT_MODELS = ( ConsolePort, @@ -81,7 +81,7 @@ class Command(BaseCommand): self.stdout.write(f'Retracing {origins_count} cabled {model._meta.verbose_name_plural}...') i = 0 for i, obj in enumerate(origins, start=1): - create_cablepath([obj]) + create_cablepaths([obj]) if not i % 100: self.draw_progress_bar(i * 100 / origins_count) self.draw_progress_bar(100) diff --git a/netbox/dcim/migrations/0217_poweroutlettemplate_color.py b/netbox/dcim/migrations/0217_poweroutlettemplate_color.py new file mode 100644 index 000000000..95ebad57a --- /dev/null +++ b/netbox/dcim/migrations/0217_poweroutlettemplate_color.py @@ -0,0 +1,17 @@ +import utilities.fields +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('dcim', '0216_latitude_longitude_validators'), + ] + + operations = [ + migrations.AddField( + model_name='poweroutlettemplate', + name='color', + field=utilities.fields.ColorField(blank=True, max_length=6), + ), + ] diff --git a/netbox/dcim/migrations/0218_owner.py b/netbox/dcim/migrations/0218_owner.py new file mode 100644 index 000000000..e1c9e64ac --- /dev/null +++ b/netbox/dcim/migrations/0218_owner.py @@ -0,0 +1,243 @@ +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ('dcim', '0217_poweroutlettemplate_color'), + ('users', '0015_owner'), + ] + + operations = [ + migrations.AddField( + model_name='cable', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='consoleport', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='consoleserverport', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='device', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='devicebay', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='devicerole', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='devicetype', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='frontport', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='interface', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='inventoryitem', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='inventoryitemrole', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='location', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='macaddress', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='manufacturer', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='module', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='modulebay', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='moduletype', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='moduletypeprofile', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='platform', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='powerfeed', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='poweroutlet', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='powerpanel', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='powerport', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='rack', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='rackreservation', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='rackrole', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='racktype', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='rearport', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='region', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='site', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='sitegroup', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='virtualchassis', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='virtualdevicecontext', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + ] diff --git a/netbox/dcim/migrations/0219_devicetype_device_count.py b/netbox/dcim/migrations/0219_devicetype_device_count.py new file mode 100644 index 000000000..c28304738 --- /dev/null +++ b/netbox/dcim/migrations/0219_devicetype_device_count.py @@ -0,0 +1,66 @@ +import utilities.fields +from django.db import migrations +from django.db.models import Count, OuterRef, Subquery + + +def _populate_count_for_type( + apps, schema_editor, app_name: str, model_name: str, target_field: str, related_name: str = 'instances' +): + """ + Update a CounterCache field on the specified model by annotating the count of related instances. + """ + Model = apps.get_model(app_name, model_name) + db_alias = schema_editor.connection.alias + + count_subquery = ( + Model.objects.using(db_alias) + .filter(pk=OuterRef('pk')) + .annotate(_instance_count=Count(related_name)) + .values('_instance_count') + ) + Model.objects.using(db_alias).update(**{target_field: Subquery(count_subquery)}) + + +def populate_device_type_device_count(apps, schema_editor): + _populate_count_for_type(apps, schema_editor, 'dcim', 'DeviceType', 'device_count') + + +def populate_module_type_module_count(apps, schema_editor): + _populate_count_for_type(apps, schema_editor, 'dcim', 'ModuleType', 'module_count') + + +def populate_rack_type_rack_count(apps, schema_editor): + _populate_count_for_type(apps, schema_editor, 'dcim', 'RackType', 'rack_count', related_name='racks') + + +class Migration(migrations.Migration): + dependencies = [ + ('dcim', '0218_owner'), + ] + + operations = [ + migrations.AddField( + model_name='devicetype', + name='device_count', + field=utilities.fields.CounterCacheField( + default=0, editable=False, to_field='device_type', to_model='dcim.Device' + ), + ), + migrations.RunPython(populate_device_type_device_count, migrations.RunPython.noop), + migrations.AddField( + model_name='moduletype', + name='module_count', + field=utilities.fields.CounterCacheField( + default=0, editable=False, to_field='module_type', to_model='dcim.Module' + ), + ), + migrations.RunPython(populate_module_type_module_count, migrations.RunPython.noop), + migrations.AddField( + model_name='racktype', + name='rack_count', + field=utilities.fields.CounterCacheField( + default=0, editable=False, to_field='rack_type', to_model='dcim.Rack' + ), + ), + migrations.RunPython(populate_rack_type_rack_count, migrations.RunPython.noop), + ] diff --git a/netbox/dcim/migrations/0220_cable_profile.py b/netbox/dcim/migrations/0220_cable_profile.py new file mode 100644 index 000000000..5160506ed --- /dev/null +++ b/netbox/dcim/migrations/0220_cable_profile.py @@ -0,0 +1,56 @@ +import django.contrib.postgres.fields +import django.core.validators +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('dcim', '0219_devicetype_device_count'), + ] + + operations = [ + migrations.AddField( + model_name='cable', + name='profile', + field=models.CharField(blank=True, max_length=50), + ), + migrations.AddField( + model_name='cabletermination', + name='connector', + field=models.PositiveSmallIntegerField( + blank=True, + null=True, + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(256) + ] + ), + ), + migrations.AddField( + model_name='cabletermination', + name='positions', + field=django.contrib.postgres.fields.ArrayField( + base_field=models.PositiveSmallIntegerField( + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(1024) + ] + ), + blank=True, + null=True, + size=None + ), + ), + migrations.AlterModelOptions( + name='cabletermination', + options={'ordering': ('cable', 'cable_end', 'connector', 'pk')}, # connector may be null + ), + migrations.AddConstraint( + model_name='cabletermination', + constraint=models.UniqueConstraint( + fields=('cable', 'cable_end', 'connector'), + name='dcim_cabletermination_unique_connector' + ), + ), + ] diff --git a/netbox/dcim/migrations/0221_cable_connector_positions.py b/netbox/dcim/migrations/0221_cable_connector_positions.py new file mode 100644 index 000000000..e986a28e1 --- /dev/null +++ b/netbox/dcim/migrations/0221_cable_connector_positions.py @@ -0,0 +1,228 @@ +import django.contrib.postgres.fields +import django.core.validators +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ('dcim', '0220_cable_profile'), + ] + + operations = [ + migrations.AddField( + model_name='consoleport', + name='cable_connector', + field=models.PositiveSmallIntegerField( + blank=True, + null=True, + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(256) + ], + ), + ), + migrations.AddField( + model_name='consoleport', + name='cable_positions', + field=django.contrib.postgres.fields.ArrayField( + base_field=models.PositiveSmallIntegerField( + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(1024), + ] + ), + blank=True, + null=True, + size=None, + ), + ), + migrations.AddField( + model_name='consoleserverport', + name='cable_connector', + field=models.PositiveSmallIntegerField( + blank=True, + null=True, + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(256) + ], + ), + ), + migrations.AddField( + model_name='consoleserverport', + name='cable_positions', + field=django.contrib.postgres.fields.ArrayField( + base_field=models.PositiveSmallIntegerField( + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(1024), + ] + ), + blank=True, + null=True, + size=None, + ), + ), + migrations.AddField( + model_name='frontport', + name='cable_connector', + field=models.PositiveSmallIntegerField( + blank=True, + null=True, + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(256) + ], + ), + ), + migrations.AddField( + model_name='frontport', + name='cable_positions', + field=django.contrib.postgres.fields.ArrayField( + base_field=models.PositiveSmallIntegerField( + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(1024), + ] + ), + blank=True, + null=True, + size=None, + ), + ), + migrations.AddField( + model_name='interface', + name='cable_connector', + field=models.PositiveSmallIntegerField( + blank=True, + null=True, + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(256) + ], + ), + ), + migrations.AddField( + model_name='interface', + name='cable_positions', + field=django.contrib.postgres.fields.ArrayField( + base_field=models.PositiveSmallIntegerField( + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(1024), + ] + ), + blank=True, + null=True, + size=None, + ), + ), + migrations.AddField( + model_name='powerfeed', + name='cable_connector', + field=models.PositiveSmallIntegerField( + blank=True, + null=True, + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(256) + ], + ), + ), + migrations.AddField( + model_name='powerfeed', + name='cable_positions', + field=django.contrib.postgres.fields.ArrayField( + base_field=models.PositiveSmallIntegerField( + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(1024), + ] + ), + blank=True, + null=True, + size=None, + ), + ), + migrations.AddField( + model_name='poweroutlet', + name='cable_connector', + field=models.PositiveSmallIntegerField( + blank=True, + null=True, + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(256) + ], + ), + ), + migrations.AddField( + model_name='poweroutlet', + name='cable_positions', + field=django.contrib.postgres.fields.ArrayField( + base_field=models.PositiveSmallIntegerField( + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(1024), + ] + ), + blank=True, + null=True, + size=None, + ), + ), + migrations.AddField( + model_name='powerport', + name='cable_connector', + field=models.PositiveSmallIntegerField( + blank=True, + null=True, + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(256) + ], + ), + ), + migrations.AddField( + model_name='powerport', + name='cable_positions', + field=django.contrib.postgres.fields.ArrayField( + base_field=models.PositiveSmallIntegerField( + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(1024), + ] + ), + blank=True, + null=True, + size=None, + ), + ), + migrations.AddField( + model_name='rearport', + name='cable_connector', + field=models.PositiveSmallIntegerField( + blank=True, + null=True, + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(256) + ], + ), + ), + migrations.AddField( + model_name='rearport', + name='cable_positions', + field=django.contrib.postgres.fields.ArrayField( + base_field=models.PositiveSmallIntegerField( + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(1024), + ] + ), + blank=True, + null=True, + size=None, + ), + ), + ] diff --git a/netbox/dcim/migrations/0222_port_mappings.py b/netbox/dcim/migrations/0222_port_mappings.py new file mode 100644 index 000000000..42de44dbc --- /dev/null +++ b/netbox/dcim/migrations/0222_port_mappings.py @@ -0,0 +1,219 @@ +import django.core.validators +import django.db.models.deletion +from django.db import migrations +from django.db import models +from itertools import islice + + +def chunked(iterable, size): + """ + Yield successive chunks of a given size from an iterator. + """ + iterator = iter(iterable) + while chunk := list(islice(iterator, size)): + yield chunk + + +def populate_port_template_mappings(apps, schema_editor): + FrontPortTemplate = apps.get_model('dcim', 'FrontPortTemplate') + PortTemplateMapping = apps.get_model('dcim', 'PortTemplateMapping') + + front_ports = FrontPortTemplate.objects.iterator(chunk_size=1000) + + def generate_copies(): + for front_port in front_ports: + yield PortTemplateMapping( + device_type_id=front_port.device_type_id, + module_type_id=front_port.module_type_id, + front_port_id=front_port.pk, + front_port_position=1, + rear_port_id=front_port.rear_port_id, + rear_port_position=front_port.rear_port_position, + ) + + # Bulk insert in streaming batches + for chunk in chunked(generate_copies(), 1000): + PortTemplateMapping.objects.bulk_create(chunk, batch_size=1000) + + +def populate_port_mappings(apps, schema_editor): + FrontPort = apps.get_model('dcim', 'FrontPort') + PortMapping = apps.get_model('dcim', 'PortMapping') + + front_ports = FrontPort.objects.iterator(chunk_size=1000) + + def generate_copies(): + for front_port in front_ports: + yield PortMapping( + device_id=front_port.device_id, + front_port_id=front_port.pk, + front_port_position=1, + rear_port_id=front_port.rear_port_id, + rear_port_position=front_port.rear_port_position, + ) + + # Bulk insert in streaming batches + for chunk in chunked(generate_copies(), 1000): + PortMapping.objects.bulk_create(chunk, batch_size=1000) + + +class Migration(migrations.Migration): + dependencies = [ + ('dcim', '0221_cable_connector_positions'), + ] + + operations = [ + # Create PortTemplateMapping model (for DeviceTypes) + migrations.CreateModel( + name='PortTemplateMapping', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False)), + ( + 'front_port_position', + models.PositiveSmallIntegerField( + default=1, + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(1024) + ] + ) + ), + ( + 'rear_port_position', + models.PositiveSmallIntegerField( + default=1, + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(1024) + ] + ) + ), + ( + 'device_type', + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + to='dcim.devicetype', + related_name='port_mappings', + blank=True, + null=True + ) + ), + ( + 'module_type', + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + to='dcim.moduletype', + related_name='port_mappings', + blank=True, + null=True + ) + ), + ( + 'front_port', + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + to='dcim.frontporttemplate', + related_name='mappings' + ) + ), + ( + 'rear_port', + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + to='dcim.rearporttemplate', + related_name='mappings' + ) + ), + ], + ), + migrations.AddConstraint( + model_name='porttemplatemapping', + constraint=models.UniqueConstraint( + fields=('front_port', 'front_port_position'), + name='dcim_porttemplatemapping_unique_front_port_position' + ), + ), + migrations.AddConstraint( + model_name='porttemplatemapping', + constraint=models.UniqueConstraint( + fields=('rear_port', 'rear_port_position'), + name='dcim_porttemplatemapping_unique_rear_port_position' + ), + ), + + # Create PortMapping model (for Devices) + migrations.CreateModel( + name='PortMapping', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False)), + ( + 'front_port_position', + models.PositiveSmallIntegerField( + default=1, + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(1024) + ] + ), + ), + ( + 'rear_port_position', + models.PositiveSmallIntegerField( + default=1, + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(1024), + ] + ), + ), + ( + 'device', + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + to='dcim.device', + related_name='port_mappings' + ) + ), + ( + 'front_port', + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + to='dcim.frontport', + related_name='mappings' + ) + ), + ( + 'rear_port', + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + to='dcim.rearport', + related_name='mappings' + ) + ), + ], + ), + migrations.AddConstraint( + model_name='portmapping', + constraint=models.UniqueConstraint( + fields=('front_port', 'front_port_position'), + name='dcim_portmapping_unique_front_port_position' + ), + ), + migrations.AddConstraint( + model_name='portmapping', + constraint=models.UniqueConstraint( + fields=('rear_port', 'rear_port_position'), + name='dcim_portmapping_unique_rear_port_position' + ), + ), + + # Data migration + migrations.RunPython( + code=populate_port_template_mappings, + reverse_code=migrations.RunPython.noop + ), + migrations.RunPython( + code=populate_port_mappings, + reverse_code=migrations.RunPython.noop + ), + ] diff --git a/netbox/dcim/migrations/0223_frontport_positions.py b/netbox/dcim/migrations/0223_frontport_positions.py new file mode 100644 index 000000000..fc3394738 --- /dev/null +++ b/netbox/dcim/migrations/0223_frontport_positions.py @@ -0,0 +1,65 @@ +import django.core.validators +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('dcim', '0222_port_mappings'), + ] + + operations = [ + # Remove rear_port & rear_port_position from FrontPortTemplate + migrations.RemoveConstraint( + model_name='frontporttemplate', + name='dcim_frontporttemplate_unique_rear_port_position', + ), + migrations.RemoveField( + model_name='frontporttemplate', + name='rear_port', + ), + migrations.RemoveField( + model_name='frontporttemplate', + name='rear_port_position', + ), + + # Add positions on FrontPortTemplate + migrations.AddField( + model_name='frontporttemplate', + name='positions', + field=models.PositiveSmallIntegerField( + default=1, + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(1024) + ] + ), + ), + + # Remove rear_port & rear_port_position from FrontPort + migrations.RemoveConstraint( + model_name='frontport', + name='dcim_frontport_unique_rear_port_position', + ), + migrations.RemoveField( + model_name='frontport', + name='rear_port', + ), + migrations.RemoveField( + model_name='frontport', + name='rear_port_position', + ), + + # Add positions on FrontPort + migrations.AddField( + model_name='frontport', + name='positions', + field=models.PositiveSmallIntegerField( + default=1, + validators=[ + django.core.validators.MinValueValidator(1), + django.core.validators.MaxValueValidator(1024) + ] + ), + ), + ] diff --git a/netbox/dcim/migrations/0224_add_comments_to_organizationalmodel.py b/netbox/dcim/migrations/0224_add_comments_to_organizationalmodel.py new file mode 100644 index 000000000..0ec79102f --- /dev/null +++ b/netbox/dcim/migrations/0224_add_comments_to_organizationalmodel.py @@ -0,0 +1,28 @@ +# Generated by Django 5.2.8 on 2025-12-08 17:38 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('dcim', '0223_frontport_positions'), + ] + + operations = [ + migrations.AddField( + model_name='inventoryitemrole', + name='comments', + field=models.TextField(blank=True), + ), + migrations.AddField( + model_name='manufacturer', + name='comments', + field=models.TextField(blank=True), + ), + migrations.AddField( + model_name='rackrole', + name='comments', + field=models.TextField(blank=True), + ), + ] diff --git a/netbox/dcim/migrations/0225_gfk_indexes.py b/netbox/dcim/migrations/0225_gfk_indexes.py new file mode 100644 index 000000000..393fc0f8f --- /dev/null +++ b/netbox/dcim/migrations/0225_gfk_indexes.py @@ -0,0 +1,19 @@ +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ('contenttypes', '0002_remove_content_type_name'), + ('dcim', '0224_add_comments_to_organizationalmodel'), + ('extras', '0134_owner'), + ('users', '0015_owner'), + ] + + operations = [ + migrations.AddIndex( + model_name='macaddress', + index=models.Index( + fields=['assigned_object_type', 'assigned_object_id'], name='dcim_macadd_assigne_54115d_idx' + ), + ), + ] diff --git a/netbox/dcim/models/base.py b/netbox/dcim/models/base.py new file mode 100644 index 000000000..f8021d4db --- /dev/null +++ b/netbox/dcim/models/base.py @@ -0,0 +1,61 @@ +from django.core.exceptions import ValidationError +from django.core.validators import MaxValueValidator, MinValueValidator +from django.db import models +from django.utils.translation import gettext_lazy as _ + +from dcim.constants import PORT_POSITION_MAX, PORT_POSITION_MIN + +__all__ = ( + 'PortMappingBase', +) + + +class PortMappingBase(models.Model): + """ + Base class for PortMapping and PortTemplateMapping + """ + front_port_position = models.PositiveSmallIntegerField( + default=1, + validators=( + MinValueValidator(PORT_POSITION_MIN), + MaxValueValidator(PORT_POSITION_MAX), + ), + ) + rear_port_position = models.PositiveSmallIntegerField( + default=1, + validators=( + MinValueValidator(PORT_POSITION_MIN), + MaxValueValidator(PORT_POSITION_MAX), + ), + ) + + _netbox_private = True + + class Meta: + abstract = True + constraints = ( + models.UniqueConstraint( + fields=('front_port', 'front_port_position'), + name='%(app_label)s_%(class)s_unique_front_port_position' + ), + models.UniqueConstraint( + fields=('rear_port', 'rear_port_position'), + name='%(app_label)s_%(class)s_unique_rear_port_position' + ), + ) + + def clean(self): + super().clean() + + # Validate rear port position + if self.rear_port_position > self.rear_port.positions: + raise ValidationError({ + "rear_port_position": _( + "Invalid rear port position ({rear_port_position}): Rear port {name} has only {positions} " + "positions." + ).format( + rear_port_position=self.rear_port_position, + name=self.rear_port.name, + positions=self.rear_port.positions + ) + }) diff --git a/netbox/dcim/models/cables.py b/netbox/dcim/models/cables.py index 9c8f24da0..e14e20bfb 100644 --- a/netbox/dcim/models/cables.py +++ b/netbox/dcim/models/cables.py @@ -1,8 +1,11 @@ import itertools +import logging from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType +from django.contrib.postgres.fields import ArrayField from django.core.exceptions import ValidationError +from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from django.dispatch import Signal from django.utils.translation import gettext_lazy as _ @@ -21,7 +24,7 @@ from utilities.fields import ColorField, GenericArrayForeignKey from utilities.querysets import RestrictedQuerySet from utilities.serialization import deserialize_object, serialize_object from wireless.models import WirelessLink -from .device_components import FrontPort, RearPort, PathEndpoint +from .device_components import FrontPort, PathEndpoint, PortMapping, RearPort __all__ = ( 'Cable', @@ -29,6 +32,8 @@ __all__ = ( 'CableTermination', ) +logger = logging.getLogger(f'netbox.{__name__}') + trace_paths = Signal() @@ -53,6 +58,12 @@ class Cable(PrimaryModel): choices=LinkStatusChoices, default=LinkStatusChoices.STATUS_CONNECTED ) + profile = models.CharField( + verbose_name=_('profile'), + max_length=50, + choices=CableProfileChoices, + blank=True, + ) tenant = models.ForeignKey( to='tenancy.Tenant', on_delete=models.PROTECT, @@ -91,7 +102,7 @@ class Cable(PrimaryModel): null=True ) - clone_fields = ('tenant', 'type',) + clone_fields = ('tenant', 'type', 'profile') class Meta: ordering = ('pk',) @@ -104,8 +115,9 @@ class Cable(PrimaryModel): # A copy of the PK to be used by __str__ in case the object is deleted self._pk = self.__dict__.get('id') - # Cache the original status so we can check later if it's been changed + # Cache the original profile & status so we can check later whether either has been changed self._orig_status = self.__dict__.get('status') + self._orig_profile = self.__dict__.get('profile') self._terminations_modified = False @@ -122,6 +134,36 @@ class Cable(PrimaryModel): def get_status_color(self): return LinkStatusChoices.colors.get(self.status) + @property + def profile_class(self): + from dcim import cable_profiles + return { + CableProfileChoices.SINGLE_1C1P: cable_profiles.Single1C1PCableProfile, + CableProfileChoices.SINGLE_1C2P: cable_profiles.Single1C2PCableProfile, + CableProfileChoices.SINGLE_1C4P: cable_profiles.Single1C4PCableProfile, + CableProfileChoices.SINGLE_1C6P: cable_profiles.Single1C6PCableProfile, + CableProfileChoices.SINGLE_1C8P: cable_profiles.Single1C8PCableProfile, + CableProfileChoices.SINGLE_1C12P: cable_profiles.Single1C12PCableProfile, + CableProfileChoices.SINGLE_1C16P: cable_profiles.Single1C16PCableProfile, + CableProfileChoices.TRUNK_2C1P: cable_profiles.Trunk2C1PCableProfile, + CableProfileChoices.TRUNK_2C2P: cable_profiles.Trunk2C2PCableProfile, + CableProfileChoices.TRUNK_2C4P: cable_profiles.Trunk2C4PCableProfile, + CableProfileChoices.TRUNK_2C4P_SHUFFLE: cable_profiles.Trunk2C4PShuffleCableProfile, + CableProfileChoices.TRUNK_2C6P: cable_profiles.Trunk2C6PCableProfile, + CableProfileChoices.TRUNK_2C8P: cable_profiles.Trunk2C8PCableProfile, + CableProfileChoices.TRUNK_2C12P: cable_profiles.Trunk2C12PCableProfile, + CableProfileChoices.TRUNK_4C1P: cable_profiles.Trunk4C1PCableProfile, + CableProfileChoices.TRUNK_4C2P: cable_profiles.Trunk4C2PCableProfile, + CableProfileChoices.TRUNK_4C4P: cable_profiles.Trunk4C4PCableProfile, + CableProfileChoices.TRUNK_4C4P_SHUFFLE: cable_profiles.Trunk4C4PShuffleCableProfile, + CableProfileChoices.TRUNK_4C6P: cable_profiles.Trunk4C6PCableProfile, + CableProfileChoices.TRUNK_4C8P: cable_profiles.Trunk4C8PCableProfile, + CableProfileChoices.TRUNK_8C4P: cable_profiles.Trunk8C4PCableProfile, + CableProfileChoices.BREAKOUT_1C4P_4C1P: cable_profiles.Breakout1C4Px4C1PCableProfile, + CableProfileChoices.BREAKOUT_1C6P_6C1P: cable_profiles.Breakout1C6Px6C1PCableProfile, + CableProfileChoices.BREAKOUT_2C4P_8C1P_SHUFFLE: cable_profiles.Breakout2C4Px8C1PShuffleCableProfile, + }.get(self.profile) + def _get_x_terminations(self, side): """ Return the terminating objects for the given cable end (A or B). @@ -194,6 +236,10 @@ class Cable(PrimaryModel): if self._state.adding and self.pk is None and (not self.a_terminations or not self.b_terminations): raise ValidationError(_("Must define A and B terminations when creating a new cable.")) + # Validate terminations against the assigned cable profile (if any) + if self.profile: + self.profile_class().clean(self) + if self._terminations_modified: # Check that all termination objects for either end are of the same type @@ -245,7 +291,10 @@ class Cable(PrimaryModel): # Update the private PK used in __str__() self._pk = self.pk - if self._terminations_modified: + if self._orig_profile != self.profile: + print(f'profile changed from {self._orig_profile} to {self.profile}') + self.update_terminations(force=True) + elif self._terminations_modified: self.update_terminations() super().save(*args, force_update=True, using=using, update_fields=update_fields) @@ -299,27 +348,52 @@ class Cable(PrimaryModel): return a_terminations, b_terminations - def update_terminations(self): + def update_terminations(self, force=False): """ Create/delete CableTerminations for this Cable to reflect its current state. + + Args: + force: Force the recreation of all CableTerminations, even if no changes have been made. Needed e.g. when + altering a Cable's assigned profile. """ a_terminations, b_terminations = self.get_terminations() # Delete any stale CableTerminations for termination, ct in a_terminations.items(): - if termination.pk and termination not in self.a_terminations: + if force or (termination.pk and termination not in self.a_terminations): ct.delete() for termination, ct in b_terminations.items(): - if termination.pk and termination not in self.b_terminations: + if force or (termination.pk and termination not in self.b_terminations): ct.delete() # Save any new CableTerminations - for termination in self.a_terminations: - if not termination.pk or termination not in a_terminations: - CableTermination(cable=self, cable_end='A', termination=termination).save() - for termination in self.b_terminations: - if not termination.pk or termination not in b_terminations: - CableTermination(cable=self, cable_end='B', termination=termination).save() + profile = self.profile_class() if self.profile else None + for i, termination in enumerate(self.a_terminations, start=1): + if force or not termination.pk or termination not in a_terminations: + connector = positions = None + if profile: + connector = i + positions = profile.get_position_list(profile.a_connectors[i]) + CableTermination( + cable=self, + cable_end=CableEndChoices.SIDE_A, + connector=connector, + positions=positions, + termination=termination + ).save() + for i, termination in enumerate(self.b_terminations, start=1): + if force or not termination.pk or termination not in b_terminations: + connector = positions = None + if profile: + connector = i + positions = profile.get_position_list(profile.b_connectors[i]) + CableTermination( + cable=self, + cable_end=CableEndChoices.SIDE_B, + connector=connector, + positions=positions, + termination=termination + ).save() class CableTermination(ChangeLoggedModel): @@ -346,6 +420,24 @@ class CableTermination(ChangeLoggedModel): ct_field='termination_type', fk_field='termination_id' ) + connector = models.PositiveSmallIntegerField( + blank=True, + null=True, + validators=( + MinValueValidator(CABLE_CONNECTOR_MIN), + MaxValueValidator(CABLE_CONNECTOR_MAX) + ), + ) + positions = ArrayField( + base_field=models.PositiveSmallIntegerField( + validators=( + MinValueValidator(CABLE_POSITION_MIN), + MaxValueValidator(CABLE_POSITION_MAX) + ) + ), + blank=True, + null=True, + ) # Cached associations to enable efficient filtering _device = models.ForeignKey( @@ -376,12 +468,16 @@ class CableTermination(ChangeLoggedModel): objects = RestrictedQuerySet.as_manager() class Meta: - ordering = ('cable', 'cable_end', 'pk') + ordering = ('cable', 'cable_end', 'connector', 'pk') constraints = ( models.UniqueConstraint( fields=('termination_type', 'termination_id'), name='%(app_label)s_%(class)s_unique_termination' ), + models.UniqueConstraint( + fields=('cable', 'cable_end', 'connector'), + name='%(app_label)s_%(class)s_unique_connector' + ), ) verbose_name = _('cable termination') verbose_name_plural = _('cable terminations') @@ -443,8 +539,7 @@ class CableTermination(ChangeLoggedModel): # Set the cable on the terminating object termination = self.termination._meta.model.objects.get(pk=self.termination_id) termination.snapshot() - termination.cable = self.cable - termination.cable_end = self.cable_end + termination.set_cable_termination(self) termination.save() def delete(self, *args, **kwargs): @@ -452,8 +547,7 @@ class CableTermination(ChangeLoggedModel): # Delete the cable association on the terminating object termination = self.termination._meta.model.objects.get(pk=self.termination_id) termination.snapshot() - termination.cable = None - termination.cable_end = None + termination.clear_cable_termination(self) termination.save() super().delete(*args, **kwargs) @@ -629,7 +723,13 @@ class CablePath(models.Model): is_active = True is_split = False + logger.debug(f'Tracing cable path from {terminations}...') + + segment = 0 while terminations: + segment += 1 + logger.debug(f'[Path segment #{segment}] Position stack: {position_stack}') + logger.debug(f'[Path segment #{segment}] Local terminations: {terminations}') # Terminations must all be of the same type if not all(isinstance(t, type(terminations[0])) for t in terminations[1:]): @@ -655,9 +755,15 @@ class CablePath(models.Model): path.append([ object_to_path_node(t) for t in terminations ]) + # If not null, push cable position onto the stack + if isinstance(terminations[0], PathEndpoint) and terminations[0].cable_positions: + position_stack.append([terminations[0].cable_positions[0]]) # Step 2: Determine the attached links (Cable or WirelessLink), if any - links = [termination.link for termination in terminations if termination.link is not None] + links = list(dict.fromkeys( + termination.link for termination in terminations if termination.link is not None + )) + logger.debug(f'[Path segment #{segment}] Links: {links}') if len(links) == 0: if len(path) == 1: # If this is the start of the path and no link exists, return None @@ -689,33 +795,46 @@ class CablePath(models.Model): # Step 6: Determine the far-end terminations if isinstance(links[0], Cable): - termination_type = ObjectType.objects.get_for_model(terminations[0]) - local_cable_terminations = CableTermination.objects.filter( - termination_type=termination_type, - termination_id__in=[t.pk for t in terminations] - ) + # Profile-based tracing + if links[0].profile: + cable_profile = links[0].profile_class() + position = position_stack.pop()[0] if position_stack else None + term, position = cable_profile.get_peer_termination(terminations[0], position) + remote_terminations = [term] + position_stack.append([position]) - q_filter = Q() - for lct in local_cable_terminations: - cable_end = 'A' if lct.cable_end == 'B' else 'B' - q_filter |= Q(cable=lct.cable, cable_end=cable_end) + # Legacy (positionless) behavior + else: + termination_type = ObjectType.objects.get_for_model(terminations[0]) + local_cable_terminations = CableTermination.objects.filter( + termination_type=termination_type, + termination_id__in=[t.pk for t in terminations] + ) - # Make sure this filter has been populated; if not, we have probably been given invalid data - if not q_filter: - break + q_filter = Q() + for lct in local_cable_terminations: + cable_end = 'A' if lct.cable_end == 'B' else 'B' + q_filter |= Q(cable=lct.cable, cable_end=cable_end) - remote_cable_terminations = CableTermination.objects.filter(q_filter) - remote_terminations = [ct.termination for ct in remote_cable_terminations] + # Make sure this filter has been populated; if not, we have probably been given invalid data + if not q_filter: + break + + remote_cable_terminations = CableTermination.objects.filter(q_filter) + remote_terminations = [ct.termination for ct in remote_cable_terminations] else: # WirelessLink remote_terminations = [ link.interface_b if link.interface_a is terminations[0] else link.interface_a for link in links ] + logger.debug(f'[Path segment #{segment}] Remote terminations: {remote_terminations}') + # Remote Terminations must all be of the same type, otherwise return a split path if not all(isinstance(t, type(remote_terminations[0])) for t in remote_terminations[1:]): is_complete = False is_split = True + logger.debug('Remote termination types differ; aborting trace.') break # Step 7: Record the far-end termination object(s) @@ -729,58 +848,53 @@ class CablePath(models.Model): if isinstance(remote_terminations[0], FrontPort): # Follow FrontPorts to their corresponding RearPorts - rear_ports = RearPort.objects.filter( - pk__in=[t.rear_port_id for t in remote_terminations] - ) - if len(rear_ports) > 1 or rear_ports[0].positions > 1: - position_stack.append([fp.rear_port_position for fp in remote_terminations]) - - terminations = rear_ports - - elif isinstance(remote_terminations[0], RearPort): - if len(remote_terminations) == 1 and remote_terminations[0].positions == 1: - front_ports = FrontPort.objects.filter( - rear_port_id__in=[rp.pk for rp in remote_terminations], - rear_port_position=1 - ) - # Obtain the individual front ports based on the termination and all positions - elif len(remote_terminations) > 1 and position_stack: + if remote_terminations[0].positions > 1 and position_stack: positions = position_stack.pop() - - # Ensure we have a number of positions equal to the amount of remote terminations - if len(remote_terminations) != len(positions): - raise UnsupportedCablePath( - _("All positions counts within the path on opposite ends of links must match") - ) - - # Get our front ports q_filter = Q() for rt in remote_terminations: - position = positions.pop() - q_filter |= Q(rear_port_id=rt.pk, rear_port_position=position) - if q_filter is Q(): - raise UnsupportedCablePath(_("Remote termination position filter is missing")) - front_ports = FrontPort.objects.filter(q_filter) - # Obtain the individual front ports based on the termination and position - elif position_stack: - front_ports = FrontPort.objects.filter( - rear_port_id=remote_terminations[0].pk, - rear_port_position__in=position_stack.pop() - ) - # If all rear ports have a single position, we can just get the front ports - elif all([rp.positions == 1 for rp in remote_terminations]): - front_ports = FrontPort.objects.filter(rear_port_id__in=[rp.pk for rp in remote_terminations]) - - if len(front_ports) != len(remote_terminations): - # Some rear ports does not have a front port - is_split = True - break - else: - # No position indicated: path has split, so we stop at the RearPorts + q_filter |= Q(front_port=rt, front_port_position__in=positions) + port_mappings = PortMapping.objects.filter(q_filter) + elif remote_terminations[0].positions > 1: is_split = True + logger.debug( + 'Encountered front port mapped to multiple rear ports but position stack is empty; aborting ' + 'trace.' + ) + break + else: + port_mappings = PortMapping.objects.filter(front_port__in=remote_terminations) + if not port_mappings: break - terminations = front_ports + # Compile the list of RearPorts without duplication or altering their ordering + terminations = list(dict.fromkeys(mapping.rear_port for mapping in port_mappings)) + if any(t.positions > 1 for t in terminations): + position_stack.append([mapping.rear_port_position for mapping in port_mappings]) + + elif isinstance(remote_terminations[0], RearPort): + # Follow RearPorts to their corresponding FrontPorts + if remote_terminations[0].positions > 1 and position_stack: + positions = position_stack.pop() + q_filter = Q() + for rt in remote_terminations: + q_filter |= Q(rear_port=rt, rear_port_position__in=positions) + port_mappings = PortMapping.objects.filter(q_filter) + elif remote_terminations[0].positions > 1: + is_split = True + logger.debug( + 'Encountered rear port mapped to multiple front ports but position stack is empty; aborting ' + 'trace.' + ) + break + else: + port_mappings = PortMapping.objects.filter(rear_port__in=remote_terminations) + if not port_mappings: + break + + # Compile the list of FrontPorts without duplication or altering their ordering + terminations = list(dict.fromkeys(mapping.front_port for mapping in port_mappings)) + if any(t.positions > 1 for t in terminations): + position_stack.append([mapping.front_port_position for mapping in port_mappings]) elif isinstance(remote_terminations[0], CircuitTermination): # Follow a CircuitTermination to its corresponding CircuitTermination (A to Z or vice versa) @@ -828,6 +942,7 @@ class CablePath(models.Model): # Unsupported topology, mark as split and exit is_complete = False is_split = True + logger.warning('Encountered an unsupported topology; aborting trace.') break return cls( @@ -906,16 +1021,23 @@ class CablePath(models.Model): # RearPort splitting to multiple FrontPorts with no stack position if type(nodes[0]) is RearPort: - return FrontPort.objects.filter(rear_port__in=nodes) + return [ + mapping.front_port for mapping in + PortMapping.objects.filter(rear_port__in=nodes).prefetch_related('front_port') + ] # Cable terminating to multiple FrontPorts mapped to different # RearPorts connected to different cables - elif type(nodes[0]) is FrontPort: - return RearPort.objects.filter(pk__in=[fp.rear_port_id for fp in nodes]) + if type(nodes[0]) is FrontPort: + return [ + mapping.rear_port for mapping in + PortMapping.objects.filter(front_port__in=nodes).prefetch_related('rear_port') + ] # Cable terminating to multiple CircuitTerminations - elif type(nodes[0]) is CircuitTermination: + if type(nodes[0]) is CircuitTermination: return [ ct.get_peer_termination() for ct in nodes ] + return [] def get_asymmetric_nodes(self): """ diff --git a/netbox/dcim/models/device_component_templates.py b/netbox/dcim/models/device_component_templates.py index 6eea97743..22b48bc45 100644 --- a/netbox/dcim/models/device_component_templates.py +++ b/netbox/dcim/models/device_component_templates.py @@ -7,6 +7,7 @@ from mptt.models import MPTTModel, TreeForeignKey from dcim.choices import * from dcim.constants import * +from dcim.models.base import PortMappingBase from dcim.models.mixins import InterfaceValidationMixin from netbox.models import ChangeLoggedModel from utilities.fields import ColorField, NaturalOrderingField @@ -28,6 +29,7 @@ __all__ = ( 'InterfaceTemplate', 'InventoryItemTemplate', 'ModuleBayTemplate', + 'PortTemplateMapping', 'PowerOutletTemplate', 'PowerPortTemplate', 'RearPortTemplate', @@ -339,6 +341,10 @@ class PowerOutletTemplate(ModularComponentTemplateModel): blank=True, null=True ) + color = ColorField( + verbose_name=_('color'), + blank=True + ) power_port = models.ForeignKey( to='dcim.PowerPortTemplate', on_delete=models.SET_NULL, @@ -389,6 +395,7 @@ class PowerOutletTemplate(ModularComponentTemplateModel): name=self.resolve_name(kwargs.get('module')), label=self.resolve_label(kwargs.get('module')), type=self.type, + color=self.color, power_port=power_port, feed_leg=self.feed_leg, **kwargs @@ -399,6 +406,7 @@ class PowerOutletTemplate(ModularComponentTemplateModel): return { 'name': self.name, 'type': self.type, + 'color': self.color, 'power_port': self.power_port.name if self.power_port else None, 'feed_leg': self.feed_leg, 'label': self.label, @@ -512,6 +520,53 @@ class InterfaceTemplate(InterfaceValidationMixin, ModularComponentTemplateModel) } +class PortTemplateMapping(PortMappingBase): + """ + Maps a FrontPortTemplate & position to a RearPortTemplate & position. + """ + device_type = models.ForeignKey( + to='dcim.DeviceType', + on_delete=models.CASCADE, + related_name='port_mappings', + blank=True, + null=True, + ) + module_type = models.ForeignKey( + to='dcim.ModuleType', + on_delete=models.CASCADE, + related_name='port_mappings', + blank=True, + null=True, + ) + front_port = models.ForeignKey( + to='dcim.FrontPortTemplate', + on_delete=models.CASCADE, + related_name='mappings', + ) + rear_port = models.ForeignKey( + to='dcim.RearPortTemplate', + on_delete=models.CASCADE, + related_name='mappings', + ) + + def clean(self): + super().clean() + + # Validate rear port assignment + if self.front_port.device_type_id != self.rear_port.device_type_id: + raise ValidationError({ + "rear_port": _("Rear port ({rear_port}) must belong to the same device type").format( + rear_port=self.rear_port + ) + }) + + def save(self, *args, **kwargs): + # Associate the mapping with the parent DeviceType/ModuleType + self.device_type = self.front_port.device_type + self.module_type = self.front_port.module_type + super().save(*args, **kwargs) + + class FrontPortTemplate(ModularComponentTemplateModel): """ Template for a pass-through port on the front of a new Device. @@ -525,18 +580,13 @@ class FrontPortTemplate(ModularComponentTemplateModel): verbose_name=_('color'), blank=True ) - rear_port = models.ForeignKey( - to='dcim.RearPortTemplate', - on_delete=models.CASCADE, - related_name='frontport_templates' - ) - rear_port_position = models.PositiveSmallIntegerField( - verbose_name=_('rear port position'), + positions = models.PositiveSmallIntegerField( + verbose_name=_('positions'), default=1, validators=[ - MinValueValidator(REARPORT_POSITIONS_MIN), - MaxValueValidator(REARPORT_POSITIONS_MAX) - ] + MinValueValidator(PORT_POSITION_MIN), + MaxValueValidator(PORT_POSITION_MAX) + ], ) component_model = FrontPort @@ -551,10 +601,6 @@ class FrontPortTemplate(ModularComponentTemplateModel): fields=('module_type', 'name'), name='%(app_label)s_%(class)s_unique_module_type_name' ), - models.UniqueConstraint( - fields=('rear_port', 'rear_port_position'), - name='%(app_label)s_%(class)s_unique_rear_port_position' - ), ) verbose_name = _('front port template') verbose_name_plural = _('front port templates') @@ -562,40 +608,23 @@ class FrontPortTemplate(ModularComponentTemplateModel): def clean(self): super().clean() - try: - - # Validate rear port assignment - if self.rear_port.device_type != self.device_type: - raise ValidationError( - _("Rear port ({name}) must belong to the same device type").format(name=self.rear_port) - ) - - # Validate rear port position assignment - if self.rear_port_position > self.rear_port.positions: - raise ValidationError( - _("Invalid rear port position ({position}); rear port {name} has only {count} positions").format( - position=self.rear_port_position, - name=self.rear_port.name, - count=self.rear_port.positions - ) - ) - - except RearPortTemplate.DoesNotExist: - pass + # Check that positions is greater than or equal to the number of associated RearPortTemplates + if not self._state.adding: + mapping_count = self.mappings.count() + if self.positions < mapping_count: + raise ValidationError({ + "positions": _( + "The number of positions cannot be less than the number of mapped rear port templates ({count})" + ).format(count=mapping_count) + }) def instantiate(self, **kwargs): - if self.rear_port: - rear_port_name = self.rear_port.resolve_name(kwargs.get('module')) - rear_port = RearPort.objects.get(name=rear_port_name, **kwargs) - else: - rear_port = None return self.component_model( name=self.resolve_name(kwargs.get('module')), label=self.resolve_label(kwargs.get('module')), type=self.type, color=self.color, - rear_port=rear_port, - rear_port_position=self.rear_port_position, + positions=self.positions, **kwargs ) instantiate.do_not_call_in_templates = True @@ -605,8 +634,7 @@ class FrontPortTemplate(ModularComponentTemplateModel): 'name': self.name, 'type': self.type, 'color': self.color, - 'rear_port': self.rear_port.name, - 'rear_port_position': self.rear_port_position, + 'positions': self.positions, 'label': self.label, 'description': self.description, } @@ -629,9 +657,9 @@ class RearPortTemplate(ModularComponentTemplateModel): verbose_name=_('positions'), default=1, validators=[ - MinValueValidator(REARPORT_POSITIONS_MIN), - MaxValueValidator(REARPORT_POSITIONS_MAX) - ] + MinValueValidator(PORT_POSITION_MIN), + MaxValueValidator(PORT_POSITION_MAX) + ], ) component_model = RearPort @@ -640,6 +668,20 @@ class RearPortTemplate(ModularComponentTemplateModel): verbose_name = _('rear port template') verbose_name_plural = _('rear port templates') + def clean(self): + super().clean() + + # Check that positions is greater than or equal to the number of associated FrontPortTemplates + if not self._state.adding: + mapping_count = self.mappings.count() + if self.positions < mapping_count: + raise ValidationError({ + "positions": _( + "The number of positions cannot be less than the number of mapped front port templates " + "({count})" + ).format(count=mapping_count) + }) + def instantiate(self, **kwargs): return self.component_model( name=self.resolve_name(kwargs.get('module')), diff --git a/netbox/dcim/models/device_components.py b/netbox/dcim/models/device_components.py index dc8c1e455..a16daa1e5 100644 --- a/netbox/dcim/models/device_components.py +++ b/netbox/dcim/models/device_components.py @@ -1,6 +1,7 @@ from functools import cached_property from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation +from django.contrib.postgres.fields import ArrayField from django.core.exceptions import ValidationError from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models @@ -11,9 +12,11 @@ from mptt.models import MPTTModel, TreeForeignKey from dcim.choices import * from dcim.constants import * from dcim.fields import WWNField +from dcim.models.base import PortMappingBase from dcim.models.mixins import InterfaceValidationMixin from netbox.choices import ColorChoices from netbox.models import OrganizationalModel, NetBoxModel +from netbox.models.mixins import OwnerMixin from utilities.fields import ColorField, NaturalOrderingField from utilities.mptt import TreeManager from utilities.ordering import naturalize_interface @@ -34,13 +37,14 @@ __all__ = ( 'InventoryItemRole', 'ModuleBay', 'PathEndpoint', + 'PortMapping', 'PowerOutlet', 'PowerPort', 'RearPort', ) -class ComponentModel(NetBoxModel): +class ComponentModel(OwnerMixin, NetBoxModel): """ An abstract model inherited by any model which has a parent Device. """ @@ -174,6 +178,24 @@ class CabledObjectModel(models.Model): blank=True, null=True ) + cable_connector = models.PositiveSmallIntegerField( + blank=True, + null=True, + validators=( + MinValueValidator(CABLE_CONNECTOR_MIN), + MaxValueValidator(CABLE_CONNECTOR_MAX) + ), + ) + cable_positions = ArrayField( + base_field=models.PositiveSmallIntegerField( + validators=( + MinValueValidator(CABLE_POSITION_MIN), + MaxValueValidator(CABLE_POSITION_MAX) + ) + ), + blank=True, + null=True, + ) mark_connected = models.BooleanField( verbose_name=_('mark connected'), default=False, @@ -193,18 +215,36 @@ class CabledObjectModel(models.Model): def clean(self): super().clean() - if self.cable and not self.cable_end: - raise ValidationError({ - "cable_end": _("Must specify cable end (A or B) when attaching a cable.") - }) - if self.cable_end and not self.cable: - raise ValidationError({ - "cable_end": _("Cable end must not be set without a cable.") - }) - if self.mark_connected and self.cable: - raise ValidationError({ - "mark_connected": _("Cannot mark as connected with a cable attached.") - }) + if self.cable: + if not self.cable_end: + raise ValidationError({ + "cable_end": _("Must specify cable end (A or B) when attaching a cable.") + }) + if self.cable_connector and not self.cable_positions: + raise ValidationError({ + "cable_positions": _("Must specify position(s) when specifying a cable connector.") + }) + if self.cable_positions and not self.cable_connector: + raise ValidationError({ + "cable_positions": _("Cable positions cannot be set without a cable connector.") + }) + if self.mark_connected: + raise ValidationError({ + "mark_connected": _("Cannot mark as connected with a cable attached.") + }) + else: + if self.cable_end: + raise ValidationError({ + "cable_end": _("Cable end must not be set without a cable.") + }) + if self.cable_connector: + raise ValidationError({ + "cable_connector": _("Cable connector must not be set without a cable.") + }) + if self.cable_positions: + raise ValidationError({ + "cable_positions": _("Cable termination positions must not be set without a cable.") + }) @property def link(self): @@ -239,6 +279,22 @@ class CabledObjectModel(models.Model): return None return CableEndChoices.SIDE_A if self.cable_end == CableEndChoices.SIDE_B else CableEndChoices.SIDE_B + def set_cable_termination(self, termination): + """Save attributes from the given CableTermination on the terminating object.""" + self.cable = termination.cable + self.cable_end = termination.cable_end + self.cable_connector = termination.connector + self.cable_positions = termination.positions + set_cable_termination.alters_data = True + + def clear_cable_termination(self, termination): + """Clear all cable termination attributes from the terminating object.""" + self.cable = None + self.cable_end = None + self.cable_connector = None + self.cable_positions = None + clear_cable_termination.alters_data = True + class PathEndpoint(models.Model): """ @@ -1050,6 +1106,43 @@ class Interface( # Pass-through ports # +class PortMapping(PortMappingBase): + """ + Maps a FrontPort & position to a RearPort & position. + """ + device = models.ForeignKey( + to='dcim.Device', + on_delete=models.CASCADE, + related_name='port_mappings', + ) + front_port = models.ForeignKey( + to='dcim.FrontPort', + on_delete=models.CASCADE, + related_name='mappings', + ) + rear_port = models.ForeignKey( + to='dcim.RearPort', + on_delete=models.CASCADE, + related_name='mappings', + ) + + def clean(self): + super().clean() + + # Both ports must belong to the same device + if self.front_port.device_id != self.rear_port.device_id: + raise ValidationError({ + "rear_port": _("Rear port ({rear_port}) must belong to the same device").format( + rear_port=self.rear_port + ) + }) + + def save(self, *args, **kwargs): + # Associate the mapping with the parent Device + self.device = self.front_port.device + super().save(*args, **kwargs) + + class FrontPort(ModularComponentModel, CabledObjectModel, TrackingModelMixin): """ A pass-through port on the front of a Device. @@ -1063,22 +1156,16 @@ class FrontPort(ModularComponentModel, CabledObjectModel, TrackingModelMixin): verbose_name=_('color'), blank=True ) - rear_port = models.ForeignKey( - to='dcim.RearPort', - on_delete=models.CASCADE, - related_name='frontports' - ) - rear_port_position = models.PositiveSmallIntegerField( - verbose_name=_('rear port position'), + positions = models.PositiveSmallIntegerField( + verbose_name=_('positions'), default=1, validators=[ - MinValueValidator(REARPORT_POSITIONS_MIN), - MaxValueValidator(REARPORT_POSITIONS_MAX) + MinValueValidator(PORT_POSITION_MIN), + MaxValueValidator(PORT_POSITION_MAX) ], - help_text=_('Mapped position on corresponding rear port') ) - clone_fields = ('device', 'type', 'color') + clone_fields = ('device', 'type', 'color', 'positions') class Meta(ModularComponentModel.Meta): constraints = ( @@ -1086,10 +1173,6 @@ class FrontPort(ModularComponentModel, CabledObjectModel, TrackingModelMixin): fields=('device', 'name'), name='%(app_label)s_%(class)s_unique_device_name' ), - models.UniqueConstraint( - fields=('rear_port', 'rear_port_position'), - name='%(app_label)s_%(class)s_unique_rear_port_position' - ), ) verbose_name = _('front port') verbose_name_plural = _('front ports') @@ -1097,27 +1180,14 @@ class FrontPort(ModularComponentModel, CabledObjectModel, TrackingModelMixin): def clean(self): super().clean() - if hasattr(self, 'rear_port'): - - # Validate rear port assignment - if self.rear_port.device != self.device: + # Check that positions is greater than or equal to the number of associated RearPorts + if not self._state.adding: + mapping_count = self.mappings.count() + if self.positions < mapping_count: raise ValidationError({ - "rear_port": _( - "Rear port ({rear_port}) must belong to the same device" - ).format(rear_port=self.rear_port) - }) - - # Validate rear port position assignment - if self.rear_port_position > self.rear_port.positions: - raise ValidationError({ - "rear_port_position": _( - "Invalid rear port position ({rear_port_position}): Rear port {name} has only {positions} " - "positions." - ).format( - rear_port_position=self.rear_port_position, - name=self.rear_port.name, - positions=self.rear_port.positions - ) + "positions": _( + "The number of positions cannot be less than the number of mapped rear ports ({count})" + ).format(count=mapping_count) }) @@ -1138,11 +1208,11 @@ class RearPort(ModularComponentModel, CabledObjectModel, TrackingModelMixin): verbose_name=_('positions'), default=1, validators=[ - MinValueValidator(REARPORT_POSITIONS_MIN), - MaxValueValidator(REARPORT_POSITIONS_MAX) + MinValueValidator(PORT_POSITION_MIN), + MaxValueValidator(PORT_POSITION_MAX) ], - help_text=_('Number of front ports which may be mapped') ) + clone_fields = ('device', 'type', 'color', 'positions') class Meta(ModularComponentModel.Meta): @@ -1154,13 +1224,13 @@ class RearPort(ModularComponentModel, CabledObjectModel, TrackingModelMixin): # Check that positions count is greater than or equal to the number of associated FrontPorts if not self._state.adding: - frontport_count = self.frontports.count() - if self.positions < frontport_count: + mapping_count = self.mappings.count() + if self.positions < mapping_count: raise ValidationError({ "positions": _( "The number of positions cannot be less than the number of mapped front ports " - "({frontport_count})" - ).format(frontport_count=frontport_count) + "({count})" + ).format(count=mapping_count) }) diff --git a/netbox/dcim/models/devices.py b/netbox/dcim/models/devices.py index 6c5a2d85d..65a5282b0 100644 --- a/netbox/dcim/models/devices.py +++ b/netbox/dcim/models/devices.py @@ -1,8 +1,7 @@ import decimal -import yaml - from functools import cached_property +import yaml from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ValidationError @@ -19,14 +18,14 @@ from django.utils.translation import gettext_lazy as _ from dcim.choices import * from dcim.constants import * from dcim.fields import MACAddressField -from dcim.utils import update_interface_bridges +from dcim.utils import create_port_mappings, update_interface_bridges from extras.models import ConfigContextModel, CustomField from extras.querysets import ConfigContextModelQuerySet from netbox.choices import ColorChoices from netbox.config import ConfigItem from netbox.models import NestedGroupModel, OrganizationalModel, PrimaryModel -from netbox.models.mixins import WeightMixin from netbox.models.features import ContactsMixin, ImageAttachmentsMixin +from netbox.models.mixins import WeightMixin from utilities.fields import ColorField, CounterCacheField from utilities.prefetch import get_prefetchable_fields from utilities.tracking import TrackingModelMixin @@ -34,7 +33,6 @@ from .device_components import * from .mixins import RenderConfigMixin from .modules import Module - __all__ = ( 'Device', 'DeviceRole', @@ -185,6 +183,10 @@ class DeviceType(ImageAttachmentsMixin, PrimaryModel, WeightMixin): to_model='dcim.InventoryItemTemplate', to_field='device_type' ) + device_count = CounterCacheField( + to_model='dcim.Device', + to_field='device_type' + ) clone_fields = ( 'manufacturer', 'default_platform', 'u_height', 'is_full_depth', 'subdevice_role', 'airflow', 'weight', @@ -1010,6 +1012,8 @@ class Device( self._instantiate_components(self.device_type.interfacetemplates.all()) self._instantiate_components(self.device_type.rearporttemplates.all()) self._instantiate_components(self.device_type.frontporttemplates.all()) + # Replicate any front/rear port mappings from the DeviceType + create_port_mappings(self, self.device_type) # Disable bulk_create to accommodate MPTT self._instantiate_components(self.device_type.modulebaytemplates.all(), bulk_create=False) self._instantiate_components(self.device_type.devicebaytemplates.all()) @@ -1319,7 +1323,10 @@ class MACAddress(PrimaryModel): ) class Meta: - ordering = ('mac_address', 'pk',) + ordering = ('mac_address', 'pk') + indexes = ( + models.Index(fields=('assigned_object_type', 'assigned_object_id')), + ) verbose_name = _('MAC address') verbose_name_plural = _('MAC addresses') diff --git a/netbox/dcim/models/modules.py b/netbox/dcim/models/modules.py index b5071794a..564df5550 100644 --- a/netbox/dcim/models/modules.py +++ b/netbox/dcim/models/modules.py @@ -12,8 +12,10 @@ from extras.models import ConfigContextModel, CustomField from netbox.models import PrimaryModel from netbox.models.features import ImageAttachmentsMixin from netbox.models.mixins import WeightMixin +from utilities.fields import CounterCacheField from utilities.jsonschema import validate_schema from utilities.string import title +from utilities.tracking import TrackingModelMixin from .device_components import * __all__ = ( @@ -91,6 +93,10 @@ class ModuleType(ImageAttachmentsMixin, PrimaryModel, WeightMixin): null=True, verbose_name=_('attributes') ) + module_count = CounterCacheField( + to_model='dcim.Module', + to_field='module_type' + ) clone_fields = ('profile', 'manufacturer', 'weight', 'weight_unit', 'airflow') prerequisite_models = ( @@ -185,7 +191,7 @@ class ModuleType(ImageAttachmentsMixin, PrimaryModel, WeightMixin): return yaml.dump(dict(data), sort_keys=False) -class Module(PrimaryModel, ConfigContextModel): +class Module(TrackingModelMixin, PrimaryModel, ConfigContextModel): """ A Module represents a field-installable component within a Device which may itself hold multiple device components (for example, a line card within a chassis switch). Modules are instantiated from ModuleTypes. diff --git a/netbox/dcim/models/racks.py b/netbox/dcim/models/racks.py index 02bce2019..d7afb7896 100644 --- a/netbox/dcim/models/racks.py +++ b/netbox/dcim/models/racks.py @@ -19,9 +19,11 @@ from netbox.models.mixins import WeightMixin from netbox.models.features import ContactsMixin, ImageAttachmentsMixin from utilities.conversion import to_grams from utilities.data import array_to_string, drange -from utilities.fields import ColorField +from utilities.fields import ColorField, CounterCacheField +from utilities.tracking import TrackingModelMixin from .device_components import PowerPort -from .devices import Device, Module +from .devices import Device +from .modules import Module from .power import PowerFeed __all__ = ( @@ -144,6 +146,10 @@ class RackType(RackBase): max_length=100, unique=True ) + rack_count = CounterCacheField( + to_model='dcim.Rack', + to_field='rack_type' + ) clone_fields = ( 'manufacturer', 'form_factor', 'width', 'u_height', 'desc_units', 'outer_width', 'outer_height', 'outer_depth', @@ -234,7 +240,7 @@ class RackRole(OrganizationalModel): verbose_name_plural = _('rack roles') -class Rack(ContactsMixin, ImageAttachmentsMixin, RackBase): +class Rack(ContactsMixin, ImageAttachmentsMixin, TrackingModelMixin, RackBase): """ Devices are housed within Racks. Each rack has a defined height measured in rack units, and a front and rear face. Each Rack is assigned to a Site and (optionally) a Location. @@ -509,7 +515,7 @@ class Rack(ContactsMixin, ImageAttachmentsMixin, RackBase): return [u for u in elevation.values()] - def get_available_units(self, u_height=1, rack_face=None, exclude=None, ignore_excluded_devices=False): + def get_available_units(self, u_height=1.0, rack_face=None, exclude=None, ignore_excluded_devices=False): """ Return a list of units within the rack available to accommodate a device of a given U height (default 1). Optionally exclude one or more devices when calculating empty units (needed when moving a device from one @@ -581,9 +587,10 @@ class Rack(ContactsMixin, ImageAttachmentsMixin, RackBase): :param unit_height: Height of each rack unit for the rendered drawing. Note this is not the total height of the elevation :param legend_width: Width of the unit legend, in pixels - :param margin_width: Width of the rigth-hand margin, in pixels + :param margin_width: Width of the right-hand margin, in pixels :param include_images: Embed front/rear device images where available :param base_url: Base URL for links and images. If none, URLs will be relative. + :param highlight_params: Dictionary of parameters to be passed to the RackElevationSVG.render_highlight() method """ elevation = RackElevationSVG( self, diff --git a/netbox/dcim/search.py b/netbox/dcim/search.py index 8ef6a1d44..00dcbfad5 100644 --- a/netbox/dcim/search.py +++ b/netbox/dcim/search.py @@ -137,6 +137,18 @@ class InventoryItemIndex(SearchIndex): display_attrs = ('device', 'manufacturer', 'parent', 'part_id', 'serial', 'asset_tag', 'description') +@register_search +class InventoryItemRoleIndex(SearchIndex): + model = models.InventoryItemRole + fields = ( + ('name', 100), + ('slug', 110), + ('description', 500), + ('comments', 5000), + ) + display_attrs = ('description',) + + @register_search class LocationIndex(SearchIndex): model = models.Location @@ -157,6 +169,7 @@ class ManufacturerIndex(SearchIndex): ('name', 100), ('slug', 110), ('description', 500), + ('comments', 5000), ) display_attrs = ('description',) @@ -308,6 +321,7 @@ class RackRoleIndex(SearchIndex): ('name', 100), ('slug', 110), ('description', 500), + ('comments', 5000), ) display_attrs = ('description',) diff --git a/netbox/dcim/signals.py b/netbox/dcim/signals.py index 75536afb6..6761c46aa 100644 --- a/netbox/dcim/signals.py +++ b/netbox/dcim/signals.py @@ -1,5 +1,6 @@ import logging +from django.db.models import Q from django.db.models.signals import post_delete, post_save from django.dispatch import receiver @@ -9,11 +10,11 @@ from virtualization.models import Cluster, VMInterface from wireless.models import WirelessLAN from .models import ( Cable, CablePath, CableTermination, ConsolePort, ConsoleServerPort, Device, DeviceBay, FrontPort, Interface, - InventoryItem, Location, ModuleBay, PathEndpoint, PowerOutlet, PowerPanel, PowerPort, Rack, RearPort, Site, - VirtualChassis, + InventoryItem, Location, ModuleBay, PathEndpoint, PortMapping, PowerOutlet, PowerPanel, PowerPort, Rack, RearPort, + Site, VirtualChassis, ) from .models.cables import trace_paths -from .utils import create_cablepath, rebuild_paths +from .utils import create_cablepaths, rebuild_paths COMPONENT_MODELS = ( ConsolePort, @@ -125,7 +126,7 @@ def update_connected_endpoints(instance, created, raw=False, **kwargs): if not nodes: continue if isinstance(nodes[0], PathEndpoint): - create_cablepath(nodes) + create_cablepaths(nodes) else: rebuild_paths(nodes) @@ -146,6 +147,17 @@ def retrace_cable_paths(instance, **kwargs): cablepath.retrace() +@receiver((post_delete, post_save), sender=PortMapping) +def update_passthrough_port_paths(instance, **kwargs): + """ + When a PortMapping is created or deleted, retrace any CablePaths which traverse its front and/or rear ports. + """ + for cablepath in CablePath.objects.filter( + Q(_nodes__contains=instance.front_port) | Q(_nodes__contains=instance.rear_port) + ): + cablepath.retrace() + + @receiver(post_delete, sender=CableTermination) def nullify_connected_endpoints(instance, **kwargs): """ @@ -161,17 +173,6 @@ def nullify_connected_endpoints(instance, **kwargs): cablepath.retrace() -@receiver(post_save, sender=FrontPort) -def extend_rearport_cable_paths(instance, created, raw, **kwargs): - """ - When a new FrontPort is created, add it to any CablePaths which end at its corresponding RearPort. - """ - if created and not raw: - rearport = instance.rear_port - for cablepath in CablePath.objects.filter(_nodes__contains=rearport): - cablepath.retrace() - - @receiver(post_save, sender=Interface) @receiver(post_save, sender=VMInterface) def update_mac_address_interface(instance, created, raw, **kwargs): diff --git a/netbox/dcim/tables/cables.py b/netbox/dcim/tables/cables.py index 321eb79f5..72220591e 100644 --- a/netbox/dcim/tables/cables.py +++ b/netbox/dcim/tables/cables.py @@ -1,11 +1,11 @@ -from django.utils.translation import gettext_lazy as _ import django_tables2 as tables -from django_tables2.utils import Accessor from django.utils.html import escape from django.utils.safestring import mark_safe +from django.utils.translation import gettext_lazy as _ +from django_tables2.utils import Accessor from dcim.models import Cable -from netbox.tables import NetBoxTable, columns +from netbox.tables import PrimaryModelTable, columns from tenancy.tables import TenancyColumnsMixin from .template_code import CABLE_LENGTH @@ -48,7 +48,7 @@ class CableTerminationsColumn(tables.Column): # Cables # -class CableTable(TenancyColumnsMixin, NetBoxTable): +class CableTable(TenancyColumnsMixin, PrimaryModelTable): a_terminations = CableTerminationsColumn( cable_end='A', orderable=False, @@ -108,6 +108,7 @@ class CableTable(TenancyColumnsMixin, NetBoxTable): verbose_name=_('Site B') ) status = columns.ChoiceFieldColumn() + profile = columns.ChoiceFieldColumn() length = columns.TemplateColumn( template_code=CABLE_LENGTH, order_by=('_abs_length') @@ -117,17 +118,16 @@ class CableTable(TenancyColumnsMixin, NetBoxTable): verbose_name=_('Color Name'), orderable=False ) - comments = columns.MarkdownColumn() tags = columns.TagColumn( url_name='dcim:cable_list' ) - class Meta(NetBoxTable.Meta): + class Meta(PrimaryModelTable.Meta): model = Cable fields = ( 'pk', 'id', 'label', 'a_terminations', 'b_terminations', 'device_a', 'device_b', 'rack_a', 'rack_b', - 'location_a', 'location_b', 'site_a', 'site_b', 'status', 'type', 'tenant', 'tenant_group', 'color', - 'color_name', 'length', 'description', 'comments', 'tags', 'created', 'last_updated', + 'location_a', 'location_b', 'site_a', 'site_b', 'status', 'profile', 'type', 'tenant', 'tenant_group', + 'color', 'color_name', 'length', 'description', 'comments', 'tags', 'created', 'last_updated', ) default_columns = ( 'pk', 'id', 'label', 'a_terminations', 'b_terminations', 'status', 'type', diff --git a/netbox/dcim/tables/devices.py b/netbox/dcim/tables/devices.py index 439906e96..f01a3ed2f 100644 --- a/netbox/dcim/tables/devices.py +++ b/netbox/dcim/tables/devices.py @@ -3,7 +3,7 @@ from django.utils.translation import gettext_lazy as _ from django_tables2.utils import Accessor from dcim import models -from netbox.tables import NetBoxTable, columns +from netbox.tables import NestedGroupModelTable, NetBoxTable, OrganizationalModelTable, PrimaryModelTable, columns from tenancy.tables import ContactsColumnMixin, TenancyColumnsMixin from .template_code import * @@ -58,15 +58,7 @@ MACADDRESS_COPY_BUTTON = """ # Device roles # -class DeviceRoleTable(NetBoxTable): - name = columns.MPTTColumn( - verbose_name=_('Name'), - linkify=True - ) - parent = tables.Column( - verbose_name=_('Parent'), - linkify=True, - ) +class DeviceRoleTable(NestedGroupModelTable): device_count = columns.LinkedCountColumn( viewname='dcim:device_list', url_params={'role_id': 'pk'}, @@ -89,7 +81,7 @@ class DeviceRoleTable(NetBoxTable): url_name='dcim:devicerole_list' ) - class Meta(NetBoxTable.Meta): + class Meta(NestedGroupModelTable.Meta): model = models.DeviceRole fields = ( 'pk', 'id', 'name', 'parent', 'device_count', 'vm_count', 'color', 'vm_role', 'config_template', @@ -102,15 +94,7 @@ class DeviceRoleTable(NetBoxTable): # Platforms # -class PlatformTable(NetBoxTable): - name = columns.MPTTColumn( - verbose_name=_('Name'), - linkify=True - ) - parent = tables.Column( - verbose_name=_('Parent'), - linkify=True, - ) +class PlatformTable(NestedGroupModelTable): manufacturer = tables.Column( verbose_name=_('Manufacturer'), linkify=True @@ -133,7 +117,7 @@ class PlatformTable(NetBoxTable): url_name='dcim:platform_list' ) - class Meta(NetBoxTable.Meta): + class Meta(NestedGroupModelTable.Meta): model = models.Platform fields = ( 'pk', 'id', 'name', 'parent', 'manufacturer', 'device_count', 'vm_count', 'slug', 'config_template', @@ -148,7 +132,7 @@ class PlatformTable(NetBoxTable): # Devices # -class DeviceTable(TenancyColumnsMixin, ContactsColumnMixin, NetBoxTable): +class DeviceTable(TenancyColumnsMixin, ContactsColumnMixin, PrimaryModelTable): name = tables.TemplateColumn( verbose_name=_('Name'), template_code=DEVICE_LINK, @@ -249,7 +233,6 @@ class DeviceTable(TenancyColumnsMixin, ContactsColumnMixin, NetBoxTable): accessor='parent_bay', linkify=True ) - comments = columns.MarkdownColumn() tags = columns.TagColumn( url_name='dcim:device_list' ) @@ -284,7 +267,7 @@ class DeviceTable(TenancyColumnsMixin, ContactsColumnMixin, NetBoxTable): verbose_name=_('Inventory items') ) - class Meta(NetBoxTable.Meta): + class Meta(PrimaryModelTable.Meta): model = models.Device fields = ( 'pk', 'id', 'name', 'status', 'tenant', 'tenant_group', 'role', 'manufacturer', 'device_type', @@ -766,12 +749,9 @@ class FrontPortTable(ModularDeviceComponentTable, CableTerminationTable): color = columns.ColorColumn( verbose_name=_('Color'), ) - rear_port_position = tables.Column( - verbose_name=_('Position') - ) - rear_port = tables.Column( - verbose_name=_('Rear Port'), - linkify=True + mappings = columns.ManyToManyColumn( + verbose_name=_('Mappings'), + transform=lambda obj: f'{obj.rear_port}:{obj.rear_port_position}' ) tags = columns.TagColumn( url_name='dcim:frontport_list' @@ -780,12 +760,12 @@ class FrontPortTable(ModularDeviceComponentTable, CableTerminationTable): class Meta(DeviceComponentTable.Meta): model = models.FrontPort fields = ( - 'pk', 'id', 'name', 'device', 'module_bay', 'module', 'label', 'type', 'color', 'rear_port', - 'rear_port_position', 'description', 'mark_connected', 'cable', 'cable_color', 'link_peer', - 'inventory_items', 'tags', 'created', 'last_updated', + 'pk', 'id', 'name', 'device', 'module_bay', 'module', 'label', 'type', 'color', 'positions', 'mappings', + 'description', 'mark_connected', 'cable', 'cable_color', 'link_peer', 'inventory_items', 'tags', 'created', + 'last_updated', ) default_columns = ( - 'pk', 'name', 'device', 'label', 'type', 'color', 'rear_port', 'rear_port_position', 'description', + 'pk', 'name', 'device', 'label', 'type', 'color', 'positions', 'mappings', 'description', ) @@ -803,11 +783,11 @@ class DeviceFrontPortTable(FrontPortTable): class Meta(CableTerminationTable.Meta, DeviceComponentTable.Meta): model = models.FrontPort fields = ( - 'pk', 'id', 'name', 'module_bay', 'module', 'label', 'type', 'rear_port', 'rear_port_position', + 'pk', 'id', 'name', 'module_bay', 'module', 'label', 'type', 'color', 'positions', 'mappings', 'description', 'mark_connected', 'cable', 'cable_color', 'link_peer', 'tags', 'actions', ) default_columns = ( - 'pk', 'name', 'label', 'type', 'rear_port', 'rear_port_position', 'description', 'cable', 'link_peer', + 'pk', 'name', 'label', 'type', 'color', 'positions', 'mappings', 'description', 'cable', 'link_peer', ) @@ -822,6 +802,10 @@ class RearPortTable(ModularDeviceComponentTable, CableTerminationTable): color = columns.ColorColumn( verbose_name=_('Color'), ) + mappings = columns.ManyToManyColumn( + verbose_name=_('Mappings'), + transform=lambda obj: f'{obj.front_port}:{obj.front_port_position}' + ) tags = columns.TagColumn( url_name='dcim:rearport_list' ) @@ -829,10 +813,13 @@ class RearPortTable(ModularDeviceComponentTable, CableTerminationTable): class Meta(DeviceComponentTable.Meta): model = models.RearPort fields = ( - 'pk', 'id', 'name', 'device', 'module_bay', 'module', 'label', 'type', 'color', 'positions', 'description', - 'mark_connected', 'cable', 'cable_color', 'link_peer', 'inventory_items', 'tags', 'created', 'last_updated', + 'pk', 'id', 'name', 'device', 'module_bay', 'module', 'label', 'type', 'color', 'positions', 'mappings', + 'description', 'mark_connected', 'cable', 'cable_color', 'link_peer', 'inventory_items', 'tags', 'created', + 'last_updated', + ) + default_columns = ( + 'pk', 'name', 'device', 'label', 'type', 'color', 'positions', 'mappings', 'description', ) - default_columns = ('pk', 'name', 'device', 'label', 'type', 'color', 'description') class DeviceRearPortTable(RearPortTable): @@ -849,11 +836,11 @@ class DeviceRearPortTable(RearPortTable): class Meta(CableTerminationTable.Meta, DeviceComponentTable.Meta): model = models.RearPort fields = ( - 'pk', 'id', 'name', 'module_bay', 'module', 'label', 'type', 'positions', 'description', 'mark_connected', - 'cable', 'cable_color', 'link_peer', 'tags', 'actions', + 'pk', 'id', 'name', 'module_bay', 'module', 'label', 'type', 'color', 'positions', 'mappings', + 'description', 'mark_connected', 'cable', 'cable_color', 'link_peer', 'tags', 'actions', ) default_columns = ( - 'pk', 'name', 'label', 'type', 'positions', 'description', 'cable', 'link_peer', + 'pk', 'name', 'label', 'type', 'color', 'positions', 'mappings', 'description', 'cable', 'link_peer', ) @@ -1050,7 +1037,7 @@ class DeviceInventoryItemTable(InventoryItemTable): ) -class InventoryItemRoleTable(NetBoxTable): +class InventoryItemRoleTable(OrganizationalModelTable): name = tables.Column( verbose_name=_('Name'), linkify=True @@ -1067,10 +1054,10 @@ class InventoryItemRoleTable(NetBoxTable): url_name='dcim:inventoryitemrole_list' ) - class Meta(NetBoxTable.Meta): + class Meta(OrganizationalModelTable.Meta): model = models.InventoryItemRole fields = ( - 'pk', 'id', 'name', 'inventoryitem_count', 'color', 'description', 'slug', 'tags', 'actions', + 'pk', 'id', 'name', 'inventoryitem_count', 'color', 'description', 'slug', 'comments', 'tags', 'actions', ) default_columns = ('pk', 'name', 'inventoryitem_count', 'color', 'description') @@ -1079,7 +1066,7 @@ class InventoryItemRoleTable(NetBoxTable): # Virtual chassis # -class VirtualChassisTable(NetBoxTable): +class VirtualChassisTable(PrimaryModelTable): name = tables.Column( verbose_name=_('Name'), linkify=True @@ -1093,14 +1080,11 @@ class VirtualChassisTable(NetBoxTable): url_params={'virtual_chassis_id': 'pk'}, verbose_name=_('Members') ) - comments = columns.MarkdownColumn( - verbose_name=_('Comments'), - ) tags = columns.TagColumn( url_name='dcim:virtualchassis_list' ) - class Meta(NetBoxTable.Meta): + class Meta(PrimaryModelTable.Meta): model = models.VirtualChassis fields = ( 'pk', 'id', 'name', 'domain', 'master', 'member_count', 'description', 'comments', 'tags', 'created', @@ -1109,7 +1093,7 @@ class VirtualChassisTable(NetBoxTable): default_columns = ('pk', 'name', 'domain', 'master', 'member_count') -class VirtualDeviceContextTable(TenancyColumnsMixin, NetBoxTable): +class VirtualDeviceContextTable(TenancyColumnsMixin, PrimaryModelTable): name = tables.Column( verbose_name=_('Name'), linkify=True @@ -1140,14 +1124,11 @@ class VirtualDeviceContextTable(TenancyColumnsMixin, NetBoxTable): url_params={'vdc_id': 'pk'}, verbose_name=_('Interfaces') ) - - comments = columns.MarkdownColumn() - tags = columns.TagColumn( url_name='dcim:virtualdevicecontext_list' ) - class Meta(NetBoxTable.Meta): + class Meta(PrimaryModelTable.Meta): model = models.VirtualDeviceContext fields = ( 'pk', 'id', 'name', 'status', 'identifier', 'tenant', 'tenant_group', 'primary_ip', 'primary_ip4', @@ -1158,7 +1139,7 @@ class VirtualDeviceContextTable(TenancyColumnsMixin, NetBoxTable): ) -class MACAddressTable(NetBoxTable): +class MACAddressTable(PrimaryModelTable): mac_address = tables.TemplateColumn( template_code=MACADDRESS_LINK, verbose_name=_('MAC Address') @@ -1184,7 +1165,7 @@ class MACAddressTable(NetBoxTable): extra_buttons=MACADDRESS_COPY_BUTTON ) - class Meta(DeviceComponentTable.Meta): + class Meta(PrimaryModelTable.Meta): model = models.MACAddress fields = ( 'pk', 'id', 'mac_address', 'assigned_object_parent', 'assigned_object', 'description', 'is_primary', diff --git a/netbox/dcim/tables/devicetypes.py b/netbox/dcim/tables/devicetypes.py index 91f9f3b47..ee11fe787 100644 --- a/netbox/dcim/tables/devicetypes.py +++ b/netbox/dcim/tables/devicetypes.py @@ -2,7 +2,7 @@ import django_tables2 as tables from django.utils.translation import gettext_lazy as _ from dcim import models -from netbox.tables import NetBoxTable, columns +from netbox.tables import NetBoxTable, OrganizationalModelTable, PrimaryModelTable, columns from tenancy.tables import ContactsColumnMixin from .template_code import MODULAR_COMPONENT_TEMPLATE_BUTTONS, WEIGHT @@ -26,7 +26,7 @@ __all__ = ( # Manufacturers # -class ManufacturerTable(ContactsColumnMixin, NetBoxTable): +class ManufacturerTable(ContactsColumnMixin, OrganizationalModelTable): name = tables.Column( verbose_name=_('Name'), linkify=True @@ -60,11 +60,12 @@ class ManufacturerTable(ContactsColumnMixin, NetBoxTable): url_name='dcim:manufacturer_list' ) - class Meta(NetBoxTable.Meta): + class Meta(OrganizationalModelTable.Meta): model = models.Manufacturer fields = ( 'pk', 'id', 'name', 'racktype_count', 'devicetype_count', 'moduletype_count', 'inventoryitem_count', - 'platform_count', 'description', 'slug', 'tags', 'contacts', 'actions', 'created', 'last_updated', + 'platform_count', 'description', 'slug', 'comments', 'tags', 'contacts', 'actions', 'created', + 'last_updated', ) default_columns = ( 'pk', 'name', 'racktype_count', 'devicetype_count', 'moduletype_count', 'inventoryitem_count', @@ -76,7 +77,7 @@ class ManufacturerTable(ContactsColumnMixin, NetBoxTable): # Device types # -class DeviceTypeTable(NetBoxTable): +class DeviceTypeTable(PrimaryModelTable): model = tables.Column( linkify=True, verbose_name=_('Device Type') @@ -93,9 +94,6 @@ class DeviceTypeTable(NetBoxTable): verbose_name=_('Full Depth'), false_mark=None ) - comments = columns.MarkdownColumn( - verbose_name=_('Comments'), - ) tags = columns.TagColumn( url_name='dcim:devicetype_list' ) @@ -112,10 +110,10 @@ class DeviceTypeTable(NetBoxTable): template_code=WEIGHT, order_by=('_abs_weight', 'weight_unit') ) - instance_count = columns.LinkedCountColumn( + device_count = columns.LinkedCountColumn( viewname='dcim:device_list', url_params={'device_type_id': 'pk'}, - verbose_name=_('Instances') + verbose_name=_('Device Count'), ) console_port_template_count = tables.Column( verbose_name=_('Console Ports') @@ -148,15 +146,15 @@ class DeviceTypeTable(NetBoxTable): verbose_name=_('Inventory Items') ) - class Meta(NetBoxTable.Meta): + class Meta(PrimaryModelTable.Meta): model = models.DeviceType fields = ( 'pk', 'id', 'model', 'manufacturer', 'default_platform', 'slug', 'part_number', 'u_height', 'exclude_from_utilization', 'is_full_depth', 'subdevice_role', 'airflow', 'weight', - 'description', 'comments', 'instance_count', 'tags', 'created', 'last_updated', + 'description', 'comments', 'device_count', 'tags', 'created', 'last_updated', ) default_columns = ( - 'pk', 'model', 'manufacturer', 'part_number', 'u_height', 'is_full_depth', 'instance_count', + 'pk', 'model', 'manufacturer', 'part_number', 'u_height', 'is_full_depth', 'device_count', ) @@ -211,6 +209,9 @@ class PowerPortTemplateTable(ComponentTemplateTable): class PowerOutletTemplateTable(ComponentTemplateTable): + color = columns.ColorColumn( + verbose_name=_('Color'), + ) actions = columns.ActionsColumn( actions=('edit', 'delete'), extra_buttons=MODULAR_COMPONENT_TEMPLATE_BUTTONS @@ -218,7 +219,7 @@ class PowerOutletTemplateTable(ComponentTemplateTable): class Meta(ComponentTemplateTable.Meta): model = models.PowerOutletTemplate - fields = ('pk', 'name', 'label', 'type', 'power_port', 'feed_leg', 'description', 'actions') + fields = ('pk', 'name', 'label', 'type', 'color', 'power_port', 'feed_leg', 'description', 'actions') empty_text = "None" @@ -249,12 +250,13 @@ class InterfaceTemplateTable(ComponentTemplateTable): class FrontPortTemplateTable(ComponentTemplateTable): - rear_port_position = tables.Column( - verbose_name=_('Position') - ) color = columns.ColorColumn( verbose_name=_('Color'), ) + mappings = columns.ManyToManyColumn( + verbose_name=_('Mappings'), + transform=lambda obj: f'{obj.rear_port}:{obj.rear_port_position}' + ) actions = columns.ActionsColumn( actions=('edit', 'delete'), extra_buttons=MODULAR_COMPONENT_TEMPLATE_BUTTONS @@ -262,7 +264,7 @@ class FrontPortTemplateTable(ComponentTemplateTable): class Meta(ComponentTemplateTable.Meta): model = models.FrontPortTemplate - fields = ('pk', 'name', 'label', 'type', 'color', 'rear_port', 'rear_port_position', 'description', 'actions') + fields = ('pk', 'name', 'label', 'type', 'color', 'positions', 'mappings', 'description', 'actions') empty_text = "None" @@ -270,6 +272,10 @@ class RearPortTemplateTable(ComponentTemplateTable): color = columns.ColorColumn( verbose_name=_('Color'), ) + mappings = columns.ManyToManyColumn( + verbose_name=_('Mappings'), + transform=lambda obj: f'{obj.front_port}:{obj.front_port_position}' + ) actions = columns.ActionsColumn( actions=('edit', 'delete'), extra_buttons=MODULAR_COMPONENT_TEMPLATE_BUTTONS @@ -277,7 +283,7 @@ class RearPortTemplateTable(ComponentTemplateTable): class Meta(ComponentTemplateTable.Meta): model = models.RearPortTemplate - fields = ('pk', 'name', 'label', 'type', 'color', 'positions', 'description', 'actions') + fields = ('pk', 'name', 'label', 'type', 'color', 'positions', 'mappings', 'description', 'actions') empty_text = "None" diff --git a/netbox/dcim/tables/modules.py b/netbox/dcim/tables/modules.py index 52edea8b4..92f5183b7 100644 --- a/netbox/dcim/tables/modules.py +++ b/netbox/dcim/tables/modules.py @@ -1,8 +1,8 @@ -from django.utils.translation import gettext_lazy as _ import django_tables2 as tables +from django.utils.translation import gettext_lazy as _ from dcim.models import Module, ModuleType, ModuleTypeProfile -from netbox.tables import NetBoxTable, columns +from netbox.tables import PrimaryModelTable, columns from .template_code import MODULETYPEPROFILE_ATTRIBUTES, WEIGHT __all__ = ( @@ -12,7 +12,7 @@ __all__ = ( ) -class ModuleTypeProfileTable(NetBoxTable): +class ModuleTypeProfileTable(PrimaryModelTable): name = tables.Column( verbose_name=_('Name'), linkify=True @@ -23,14 +23,11 @@ class ModuleTypeProfileTable(NetBoxTable): orderable=False, verbose_name=_('Attributes') ) - comments = columns.MarkdownColumn( - verbose_name=_('Comments'), - ) tags = columns.TagColumn( url_name='dcim:moduletypeprofile_list' ) - class Meta(NetBoxTable.Meta): + class Meta(PrimaryModelTable.Meta): model = ModuleTypeProfile fields = ( 'pk', 'id', 'name', 'description', 'comments', 'tags', 'created', 'last_updated', @@ -40,7 +37,7 @@ class ModuleTypeProfileTable(NetBoxTable): ) -class ModuleTypeTable(NetBoxTable): +class ModuleTypeTable(PrimaryModelTable): profile = tables.Column( verbose_name=_('Profile'), linkify=True @@ -59,30 +56,27 @@ class ModuleTypeTable(NetBoxTable): order_by=('_abs_weight', 'weight_unit') ) attributes = columns.DictColumn() - instance_count = columns.LinkedCountColumn( + module_count = columns.LinkedCountColumn( viewname='dcim:module_list', url_params={'module_type_id': 'pk'}, - verbose_name=_('Instances') - ) - comments = columns.MarkdownColumn( - verbose_name=_('Comments'), + verbose_name=_('Module Count'), ) tags = columns.TagColumn( url_name='dcim:moduletype_list' ) - class Meta(NetBoxTable.Meta): + class Meta(PrimaryModelTable.Meta): model = ModuleType fields = ( 'pk', 'id', 'model', 'profile', 'manufacturer', 'part_number', 'airflow', 'weight', 'description', - 'attributes', 'comments', 'tags', 'created', 'last_updated', + 'attributes', 'module_count', 'comments', 'tags', 'created', 'last_updated', ) default_columns = ( - 'pk', 'model', 'profile', 'manufacturer', 'part_number', + 'pk', 'model', 'profile', 'manufacturer', 'part_number', 'module_count', ) -class ModuleTable(NetBoxTable): +class ModuleTable(PrimaryModelTable): device = tables.Column( verbose_name=_('Device'), linkify=True @@ -103,14 +97,11 @@ class ModuleTable(NetBoxTable): status = columns.ChoiceFieldColumn( verbose_name=_('Status'), ) - comments = columns.MarkdownColumn( - verbose_name=_('Comments'), - ) tags = columns.TagColumn( url_name='dcim:module_list' ) - class Meta(NetBoxTable.Meta): + class Meta(PrimaryModelTable.Meta): model = Module fields = ( 'pk', 'id', 'device', 'module_bay', 'manufacturer', 'module_type', 'status', 'serial', 'asset_tag', diff --git a/netbox/dcim/tables/power.py b/netbox/dcim/tables/power.py index 40a58ad81..d7d62ea17 100644 --- a/netbox/dcim/tables/power.py +++ b/netbox/dcim/tables/power.py @@ -1,10 +1,9 @@ -from django.utils.translation import gettext_lazy as _ import django_tables2 as tables +from django.utils.translation import gettext_lazy as _ + from dcim.models import PowerFeed, PowerPanel +from netbox.tables import PrimaryModelTable, columns from tenancy.tables import ContactsColumnMixin, TenancyColumnsMixin - -from netbox.tables import NetBoxTable, columns - from .devices import CableTerminationTable __all__ = ( @@ -17,7 +16,7 @@ __all__ = ( # Power panels # -class PowerPanelTable(ContactsColumnMixin, NetBoxTable): +class PowerPanelTable(ContactsColumnMixin, PrimaryModelTable): name = tables.Column( verbose_name=_('Name'), linkify=True @@ -35,14 +34,11 @@ class PowerPanelTable(ContactsColumnMixin, NetBoxTable): url_params={'power_panel_id': 'pk'}, verbose_name=_('Power Feeds') ) - comments = columns.MarkdownColumn( - verbose_name=_('Comments'), - ) tags = columns.TagColumn( url_name='dcim:powerpanel_list' ) - class Meta(NetBoxTable.Meta): + class Meta(PrimaryModelTable.Meta): model = PowerPanel fields = ( 'pk', 'id', 'name', 'site', 'location', 'powerfeed_count', 'contacts', 'description', 'comments', 'tags', @@ -57,7 +53,7 @@ class PowerPanelTable(ContactsColumnMixin, NetBoxTable): # We're not using PathEndpointTable for PowerFeed because power connections # cannot traverse pass-through ports. -class PowerFeedTable(TenancyColumnsMixin, CableTerminationTable): +class PowerFeedTable(TenancyColumnsMixin, CableTerminationTable, PrimaryModelTable): name = tables.Column( verbose_name=_('Name'), linkify=True @@ -92,14 +88,11 @@ class PowerFeedTable(TenancyColumnsMixin, CableTerminationTable): linkify=True, verbose_name=_('Site'), ) - comments = columns.MarkdownColumn( - verbose_name=_('Comments'), - ) tags = columns.TagColumn( url_name='dcim:powerfeed_list' ) - class Meta(NetBoxTable.Meta): + class Meta(CableTerminationTable.Meta, PrimaryModelTable.Meta): model = PowerFeed fields = ( 'pk', 'id', 'name', 'power_panel', 'site', 'rack', 'status', 'type', 'supply', 'voltage', 'amperage', diff --git a/netbox/dcim/tables/racks.py b/netbox/dcim/tables/racks.py index 7cac619cd..c61d82434 100644 --- a/netbox/dcim/tables/racks.py +++ b/netbox/dcim/tables/racks.py @@ -1,9 +1,9 @@ -from django.utils.translation import gettext_lazy as _ import django_tables2 as tables +from django.utils.translation import gettext_lazy as _ from django_tables2.utils import Accessor from dcim.models import Rack, RackReservation, RackRole, RackType -from netbox.tables import NetBoxTable, columns +from netbox.tables import OrganizationalModelTable, PrimaryModelTable, columns from tenancy.tables import ContactsColumnMixin, TenancyColumnsMixin from .template_code import OUTER_UNIT, WEIGHT @@ -15,11 +15,7 @@ __all__ = ( ) -# -# Rack roles -# - -class RackRoleTable(NetBoxTable): +class RackRoleTable(OrganizationalModelTable): name = tables.Column( verbose_name=_('Name'), linkify=True @@ -36,20 +32,16 @@ class RackRoleTable(NetBoxTable): url_name='dcim:rackrole_list' ) - class Meta(NetBoxTable.Meta): + class Meta(OrganizationalModelTable.Meta): model = RackRole fields = ( - 'pk', 'id', 'name', 'rack_count', 'color', 'description', 'slug', 'tags', 'actions', 'created', + 'pk', 'id', 'name', 'rack_count', 'color', 'description', 'slug', 'comments', 'tags', 'actions', 'created', 'last_updated', ) default_columns = ('pk', 'name', 'rack_count', 'color', 'description') -# -# Rack Types -# - -class RackTypeTable(NetBoxTable): +class RackTypeTable(PrimaryModelTable): model = tables.Column( verbose_name=_('Model'), linkify=True @@ -84,35 +76,28 @@ class RackTypeTable(NetBoxTable): template_code=WEIGHT, order_by=('_abs_max_weight', 'weight_unit') ) - comments = columns.MarkdownColumn( - verbose_name=_('Comments'), - ) - instance_count = columns.LinkedCountColumn( + rack_count = columns.LinkedCountColumn( viewname='dcim:rack_list', url_params={'rack_type_id': 'pk'}, - verbose_name=_('Instances') + verbose_name=_('Rack Count'), ) tags = columns.TagColumn( url_name='dcim:rack_list' ) - class Meta(NetBoxTable.Meta): + class Meta(PrimaryModelTable.Meta): model = RackType fields = ( 'pk', 'id', 'model', 'manufacturer', 'form_factor', 'u_height', 'starting_unit', 'width', 'outer_width', - 'outer_height', 'outer_depth', 'mounting_depth', 'weight', 'max_weight', 'description', - 'comments', 'instance_count', 'tags', 'created', 'last_updated', + 'outer_height', 'outer_depth', 'mounting_depth', 'weight', 'max_weight', 'description', 'comments', + 'rack_count', 'tags', 'created', 'last_updated', ) default_columns = ( - 'pk', 'model', 'manufacturer', 'type', 'u_height', 'description', 'instance_count', + 'pk', 'model', 'manufacturer', 'type', 'u_height', 'description', 'rack_count', ) -# -# Racks -# - -class RackTable(TenancyColumnsMixin, ContactsColumnMixin, NetBoxTable): +class RackTable(TenancyColumnsMixin, ContactsColumnMixin, PrimaryModelTable): name = tables.Column( verbose_name=_('Name'), linkify=True @@ -144,9 +129,6 @@ class RackTable(TenancyColumnsMixin, ContactsColumnMixin, NetBoxTable): template_code="{{ value }}U", verbose_name=_('Height') ) - comments = columns.MarkdownColumn( - verbose_name=_('Comments'), - ) device_count = columns.LinkedCountColumn( viewname='dcim:device_list', url_params={'rack_id': 'pk'}, @@ -186,7 +168,7 @@ class RackTable(TenancyColumnsMixin, ContactsColumnMixin, NetBoxTable): order_by=('_abs_max_weight', 'weight_unit') ) - class Meta(NetBoxTable.Meta): + class Meta(PrimaryModelTable.Meta): model = Rack fields = ( 'pk', 'id', 'name', 'site', 'location', 'status', 'facility_id', 'tenant', 'tenant_group', 'role', @@ -201,11 +183,7 @@ class RackTable(TenancyColumnsMixin, ContactsColumnMixin, NetBoxTable): ) -# -# Rack reservations -# - -class RackReservationTable(TenancyColumnsMixin, NetBoxTable): +class RackReservationTable(TenancyColumnsMixin, PrimaryModelTable): reservation = tables.Column( verbose_name=_('Reservation'), accessor='pk', @@ -232,14 +210,11 @@ class RackReservationTable(TenancyColumnsMixin, NetBoxTable): status = columns.ChoiceFieldColumn( verbose_name=_('Status'), ) - comments = columns.MarkdownColumn( - verbose_name=_('Comments'), - ) tags = columns.TagColumn( url_name='dcim:rackreservation_list' ) - class Meta(NetBoxTable.Meta): + class Meta(PrimaryModelTable.Meta): model = RackReservation fields = ( 'pk', 'id', 'reservation', 'site', 'location', 'rack', 'unit_list', 'status', 'user', 'created', 'tenant', diff --git a/netbox/dcim/tables/sites.py b/netbox/dcim/tables/sites.py index 0f8fb9372..544fb3cf8 100644 --- a/netbox/dcim/tables/sites.py +++ b/netbox/dcim/tables/sites.py @@ -1,10 +1,9 @@ -from django.utils.translation import gettext_lazy as _ import django_tables2 as tables +from django.utils.translation import gettext_lazy as _ + from dcim.models import Location, Region, Site, SiteGroup +from netbox.tables import NestedGroupModelTable, PrimaryModelTable, columns from tenancy.tables import ContactsColumnMixin, TenancyColumnsMixin - -from netbox.tables import NetBoxTable, columns - from .template_code import LOCATION_BUTTONS __all__ = ( @@ -15,19 +14,7 @@ __all__ = ( ) -# -# Regions -# - -class RegionTable(ContactsColumnMixin, NetBoxTable): - name = columns.MPTTColumn( - verbose_name=_('Name'), - linkify=True - ) - parent = tables.Column( - verbose_name=_('Parent'), - linkify=True, - ) +class RegionTable(ContactsColumnMixin, NestedGroupModelTable): site_count = columns.LinkedCountColumn( viewname='dcim:site_list', url_params={'region_id': 'pk'}, @@ -36,11 +23,8 @@ class RegionTable(ContactsColumnMixin, NetBoxTable): tags = columns.TagColumn( url_name='dcim:region_list' ) - comments = columns.MarkdownColumn( - verbose_name=_('Comments'), - ) - class Meta(NetBoxTable.Meta): + class Meta(NestedGroupModelTable.Meta): model = Region fields = ( 'pk', 'id', 'name', 'parent', 'slug', 'site_count', 'description', 'comments', 'contacts', 'tags', @@ -49,19 +33,7 @@ class RegionTable(ContactsColumnMixin, NetBoxTable): default_columns = ('pk', 'name', 'site_count', 'description') -# -# Site groups -# - -class SiteGroupTable(ContactsColumnMixin, NetBoxTable): - name = columns.MPTTColumn( - verbose_name=_('Name'), - linkify=True - ) - parent = tables.Column( - verbose_name=_('Parent'), - linkify=True, - ) +class SiteGroupTable(ContactsColumnMixin, NestedGroupModelTable): site_count = columns.LinkedCountColumn( viewname='dcim:site_list', url_params={'group_id': 'pk'}, @@ -70,11 +42,8 @@ class SiteGroupTable(ContactsColumnMixin, NetBoxTable): tags = columns.TagColumn( url_name='dcim:sitegroup_list' ) - comments = columns.MarkdownColumn( - verbose_name=_('Comments'), - ) - class Meta(NetBoxTable.Meta): + class Meta(NestedGroupModelTable.Meta): model = SiteGroup fields = ( 'pk', 'id', 'name', 'parent', 'slug', 'site_count', 'description', 'comments', 'contacts', 'tags', @@ -83,11 +52,7 @@ class SiteGroupTable(ContactsColumnMixin, NetBoxTable): default_columns = ('pk', 'name', 'site_count', 'description') -# -# Sites -# - -class SiteTable(TenancyColumnsMixin, ContactsColumnMixin, NetBoxTable): +class SiteTable(TenancyColumnsMixin, ContactsColumnMixin, PrimaryModelTable): name = tables.Column( verbose_name=_('Name'), linkify=True @@ -117,14 +82,11 @@ class SiteTable(TenancyColumnsMixin, ContactsColumnMixin, NetBoxTable): url_params={'site_id': 'pk'}, verbose_name=_('Devices') ) - comments = columns.MarkdownColumn( - verbose_name=_('Comments'), - ) tags = columns.TagColumn( url_name='dcim:site_list' ) - class Meta(NetBoxTable.Meta): + class Meta(PrimaryModelTable.Meta): model = Site fields = ( 'pk', 'id', 'name', 'slug', 'status', 'facility', 'region', 'group', 'tenant', 'tenant_group', 'asns', @@ -134,19 +96,7 @@ class SiteTable(TenancyColumnsMixin, ContactsColumnMixin, NetBoxTable): default_columns = ('pk', 'name', 'status', 'facility', 'region', 'group', 'tenant', 'description') -# -# Locations -# - -class LocationTable(TenancyColumnsMixin, ContactsColumnMixin, NetBoxTable): - name = columns.MPTTColumn( - verbose_name=_('Name'), - linkify=True - ) - parent = tables.Column( - verbose_name=_('Parent'), - linkify=True, - ) +class LocationTable(TenancyColumnsMixin, ContactsColumnMixin, NestedGroupModelTable): site = tables.Column( verbose_name=_('Site'), linkify=True @@ -175,11 +125,8 @@ class LocationTable(TenancyColumnsMixin, ContactsColumnMixin, NetBoxTable): actions = columns.ActionsColumn( extra_buttons=LOCATION_BUTTONS ) - comments = columns.MarkdownColumn( - verbose_name=_('Comments'), - ) - class Meta(NetBoxTable.Meta): + class Meta(NestedGroupModelTable.Meta): model = Location fields = ( 'pk', 'id', 'name', 'parent', 'site', 'status', 'facility', 'tenant', 'tenant_group', 'rack_count', diff --git a/netbox/dcim/tests/test_api.py b/netbox/dcim/tests/test_api.py index e5a56dc03..1c4497e9a 100644 --- a/netbox/dcim/tests/test_api.py +++ b/netbox/dcim/tests/test_api.py @@ -13,7 +13,8 @@ from ipam.choices import VLANQinQRoleChoices from ipam.models import ASN, RIR, VLAN, VRF from netbox.api.serializers import GenericObjectSerializer from tenancy.models import Tenant -from users.models import User +from users.constants import TOKEN_PREFIX +from users.models import Token, User from utilities.testing import APITestCase, APIViewTestCases, create_test_device, disable_logging from virtualization.models import Cluster, ClusterType from wireless.choices import WirelessChannelChoices @@ -316,7 +317,7 @@ class RackRoleTest(APIViewTestCases.APIViewTestCase): class RackTypeTest(APIViewTestCases.APIViewTestCase): model = RackType - brief_fields = ['description', 'display', 'id', 'manufacturer', 'model', 'slug', 'url'] + brief_fields = ['description', 'display', 'id', 'manufacturer', 'model', 'rack_count', 'slug', 'url'] bulk_update_data = { 'description': 'new description', } @@ -609,7 +610,7 @@ class DeviceTypeTest(APIViewTestCases.APIViewTestCase): class ModuleTypeTest(APIViewTestCases.APIViewTestCase): model = ModuleType - brief_fields = ['description', 'display', 'id', 'manufacturer', 'model', 'profile', 'url'] + brief_fields = ['description', 'display', 'id', 'manufacturer', 'model', 'module_count', 'profile', 'url'] bulk_update_data = { 'part_number': 'ABC123', } @@ -972,72 +973,99 @@ class FrontPortTemplateTest(APIViewTestCases.APIViewTestCase): RearPortTemplate(device_type=devicetype, name='Rear Port Template 2', type=PortTypeChoices.TYPE_8P8C), RearPortTemplate(device_type=devicetype, name='Rear Port Template 3', type=PortTypeChoices.TYPE_8P8C), RearPortTemplate(device_type=devicetype, name='Rear Port Template 4', type=PortTypeChoices.TYPE_8P8C), - RearPortTemplate(module_type=moduletype, name='Rear Port Template 5', type=PortTypeChoices.TYPE_8P8C), - RearPortTemplate(module_type=moduletype, name='Rear Port Template 6', type=PortTypeChoices.TYPE_8P8C), - RearPortTemplate(module_type=moduletype, name='Rear Port Template 7', type=PortTypeChoices.TYPE_8P8C), - RearPortTemplate(module_type=moduletype, name='Rear Port Template 8', type=PortTypeChoices.TYPE_8P8C), + RearPortTemplate(device_type=devicetype, name='Rear Port Template 5', type=PortTypeChoices.TYPE_8P8C), + RearPortTemplate(device_type=devicetype, name='Rear Port Template 6', type=PortTypeChoices.TYPE_8P8C), ) RearPortTemplate.objects.bulk_create(rear_port_templates) - front_port_templates = ( - FrontPortTemplate( - device_type=devicetype, - name='Front Port Template 1', - type=PortTypeChoices.TYPE_8P8C, - rear_port=rear_port_templates[0] - ), - FrontPortTemplate( - device_type=devicetype, - name='Front Port Template 2', - type=PortTypeChoices.TYPE_8P8C, - rear_port=rear_port_templates[1] - ), - FrontPortTemplate( - module_type=moduletype, - name='Front Port Template 5', - type=PortTypeChoices.TYPE_8P8C, - rear_port=rear_port_templates[4] - ), - FrontPortTemplate( - module_type=moduletype, - name='Front Port Template 6', - type=PortTypeChoices.TYPE_8P8C, - rear_port=rear_port_templates[5] - ), + FrontPortTemplate(device_type=devicetype, name='Front Port Template 1', type=PortTypeChoices.TYPE_8P8C), + FrontPortTemplate(device_type=devicetype, name='Front Port Template 2', type=PortTypeChoices.TYPE_8P8C), + FrontPortTemplate(module_type=moduletype, name='Front Port Template 3', type=PortTypeChoices.TYPE_8P8C), ) FrontPortTemplate.objects.bulk_create(front_port_templates) + PortTemplateMapping.objects.bulk_create([ + PortTemplateMapping( + device_type=devicetype, + front_port=front_port_templates[0], + rear_port=rear_port_templates[0], + ), + PortTemplateMapping( + device_type=devicetype, + front_port=front_port_templates[1], + rear_port=rear_port_templates[1], + ), + PortTemplateMapping( + module_type=moduletype, + front_port=front_port_templates[2], + rear_port=rear_port_templates[2], + ), + ]) cls.create_data = [ { 'device_type': devicetype.pk, 'name': 'Front Port Template 3', 'type': PortTypeChoices.TYPE_8P8C, - 'rear_port': rear_port_templates[2].pk, - 'rear_port_position': 1, + 'rear_ports': [ + { + 'position': 1, + 'rear_port': rear_port_templates[3].pk, + 'rear_port_position': 1, + }, + ], }, { 'device_type': devicetype.pk, 'name': 'Front Port Template 4', 'type': PortTypeChoices.TYPE_8P8C, - 'rear_port': rear_port_templates[3].pk, - 'rear_port_position': 1, + 'rear_ports': [ + { + 'position': 1, + 'rear_port': rear_port_templates[4].pk, + 'rear_port_position': 1, + }, + ], }, { 'module_type': moduletype.pk, 'name': 'Front Port Template 7', 'type': PortTypeChoices.TYPE_8P8C, - 'rear_port': rear_port_templates[6].pk, - 'rear_port_position': 1, - }, - { - 'module_type': moduletype.pk, - 'name': 'Front Port Template 8', - 'type': PortTypeChoices.TYPE_8P8C, - 'rear_port': rear_port_templates[7].pk, - 'rear_port_position': 1, + 'rear_ports': [ + { + 'position': 1, + 'rear_port': rear_port_templates[5].pk, + 'rear_port_position': 1, + }, + ], }, ] + cls.update_data = { + 'type': PortTypeChoices.TYPE_LC, + 'rear_ports': [ + { + 'position': 1, + 'rear_port': rear_port_templates[3].pk, + 'rear_port_position': 1, + }, + ], + } + + def test_update_object(self): + super().test_update_object() + + # Check that the port mapping was updated after modifying the front port template + front_port_template = FrontPortTemplate.objects.get(name='Front Port Template 1') + rear_port_template = RearPortTemplate.objects.get(name='Rear Port Template 4') + self.assertTrue( + PortTemplateMapping.objects.filter( + front_port=front_port_template, + front_port_position=1, + rear_port=rear_port_template, + rear_port_position=1, + ).exists() + ) + class RearPortTemplateTest(APIViewTestCases.APIViewTestCase): model = RearPortTemplate @@ -1056,36 +1084,104 @@ class RearPortTemplateTest(APIViewTestCases.APIViewTestCase): manufacturer=manufacturer, model='Module Type 1' ) + front_port_templates = ( + FrontPortTemplate(device_type=devicetype, name='Front Port Template 1', type=PortTypeChoices.TYPE_8P8C), + FrontPortTemplate(device_type=devicetype, name='Front Port Template 2', type=PortTypeChoices.TYPE_8P8C), + FrontPortTemplate(module_type=moduletype, name='Front Port Template 3', type=PortTypeChoices.TYPE_8P8C), + FrontPortTemplate(module_type=moduletype, name='Front Port Template 4', type=PortTypeChoices.TYPE_8P8C), + FrontPortTemplate(module_type=moduletype, name='Front Port Template 5', type=PortTypeChoices.TYPE_8P8C), + FrontPortTemplate(module_type=moduletype, name='Front Port Template 6', type=PortTypeChoices.TYPE_8P8C), + ) + FrontPortTemplate.objects.bulk_create(front_port_templates) rear_port_templates = ( RearPortTemplate(device_type=devicetype, name='Rear Port Template 1', type=PortTypeChoices.TYPE_8P8C), RearPortTemplate(device_type=devicetype, name='Rear Port Template 2', type=PortTypeChoices.TYPE_8P8C), RearPortTemplate(device_type=devicetype, name='Rear Port Template 3', type=PortTypeChoices.TYPE_8P8C), ) RearPortTemplate.objects.bulk_create(rear_port_templates) + PortTemplateMapping.objects.bulk_create([ + PortTemplateMapping( + device_type=devicetype, + front_port=front_port_templates[0], + rear_port=rear_port_templates[0], + ), + PortTemplateMapping( + device_type=devicetype, + front_port=front_port_templates[1], + rear_port=rear_port_templates[1], + ), + PortTemplateMapping( + module_type=moduletype, + front_port=front_port_templates[2], + rear_port=rear_port_templates[2], + ), + ]) cls.create_data = [ { 'device_type': devicetype.pk, 'name': 'Rear Port Template 4', 'type': PortTypeChoices.TYPE_8P8C, + 'front_ports': [ + { + 'position': 1, + 'front_port': front_port_templates[3].pk, + 'front_port_position': 1, + }, + ], }, { 'device_type': devicetype.pk, 'name': 'Rear Port Template 5', 'type': PortTypeChoices.TYPE_8P8C, + 'front_ports': [ + { + 'position': 1, + 'front_port': front_port_templates[4].pk, + 'front_port_position': 1, + }, + ], }, { 'module_type': moduletype.pk, 'name': 'Rear Port Template 6', 'type': PortTypeChoices.TYPE_8P8C, - }, - { - 'module_type': moduletype.pk, - 'name': 'Rear Port Template 7', - 'type': PortTypeChoices.TYPE_8P8C, + 'front_ports': [ + { + 'position': 1, + 'front_port': front_port_templates[5].pk, + 'front_port_position': 1, + }, + ], }, ] + cls.update_data = { + 'type': PortTypeChoices.TYPE_LC, + 'front_ports': [ + { + 'position': 1, + 'front_port': front_port_templates[3].pk, + 'front_port_position': 1, + }, + ], + } + + def test_update_object(self): + super().test_update_object() + + # Check that the port mapping was updated after modifying the rear port template + front_port_template = FrontPortTemplate.objects.get(name='Front Port Template 4') + rear_port_template = RearPortTemplate.objects.get(name='Rear Port Template 1') + self.assertTrue( + PortTemplateMapping.objects.filter( + front_port=front_port_template, + front_port_position=1, + rear_port=rear_port_template, + rear_port_position=1, + ).exists() + ) + class ModuleBayTemplateTest(APIViewTestCases.APIViewTestCase): model = ModuleBayTemplate @@ -1306,7 +1402,6 @@ class DeviceTest(APIViewTestCases.APIViewTestCase): } user_permissions = ( 'dcim.view_site', 'dcim.view_rack', 'dcim.view_location', 'dcim.view_devicerole', 'dcim.view_devicetype', - 'extras.view_configtemplate', ) @classmethod @@ -1486,12 +1581,58 @@ class DeviceTest(APIViewTestCases.APIViewTestCase): device.config_template = configtemplate device.save() - self.add_permissions('dcim.add_device') - url = reverse('dcim-api:device-detail', kwargs={'pk': device.pk}) + 'render-config/' + self.add_permissions('dcim.render_config_device', 'dcim.view_device') + url = reverse('dcim-api:device-render-config', kwargs={'pk': device.pk}) response = self.client.post(url, {}, format='json', **self.header) self.assertHttpStatus(response, status.HTTP_200_OK) self.assertEqual(response.data['content'], f'Config for device {device.name}') + def test_render_config_without_permission(self): + configtemplate = ConfigTemplate.objects.create( + name='Config Template 1', + template_code='Config for device {{ device.name }}' + ) + + device = Device.objects.first() + device.config_template = configtemplate + device.save() + + # No permissions added - user has no render_config permission + url = reverse('dcim-api:device-render-config', kwargs={'pk': device.pk}) + response = self.client.post(url, {}, format='json', **self.header) + self.assertHttpStatus(response, status.HTTP_404_NOT_FOUND) + + def test_render_config_token_write_enabled(self): + configtemplate = ConfigTemplate.objects.create( + name='Config Template 1', + template_code='Config for device {{ device.name }}' + ) + + device = Device.objects.first() + device.config_template = configtemplate + device.save() + + self.add_permissions('dcim.render_config_device', 'dcim.view_device') + url = reverse('dcim-api:device-render-config', kwargs={'pk': device.pk}) + + # Request without token auth should fail with PermissionDenied + response = self.client.post(url, {}, format='json') + self.assertHttpStatus(response, status.HTTP_403_FORBIDDEN) + + # Create token with write_enabled=False + token = Token.objects.create(version=2, user=self.user, write_enabled=False) + token_header = f'Bearer {TOKEN_PREFIX}{token.key}.{token.token}' + + # Request with write-disabled token should fail + response = self.client.post(url, {}, format='json', HTTP_AUTHORIZATION=token_header) + self.assertHttpStatus(response, status.HTTP_403_FORBIDDEN) + + # Enable write and retry + token.write_enabled = True + token.save() + response = self.client.post(url, {}, format='json', HTTP_AUTHORIZATION=token_header) + self.assertHttpStatus(response, status.HTTP_200_OK) + class ModuleTest(APIViewTestCases.APIViewTestCase): model = Module @@ -1969,51 +2110,90 @@ class FrontPortTest(APIViewTestCases.APIViewTestCase): RearPort(device=device, name='Rear Port 6', type=PortTypeChoices.TYPE_8P8C), ) RearPort.objects.bulk_create(rear_ports) - front_ports = ( - FrontPort(device=device, name='Front Port 1', type=PortTypeChoices.TYPE_8P8C, rear_port=rear_ports[0]), - FrontPort(device=device, name='Front Port 2', type=PortTypeChoices.TYPE_8P8C, rear_port=rear_ports[1]), - FrontPort(device=device, name='Front Port 3', type=PortTypeChoices.TYPE_8P8C, rear_port=rear_ports[2]), + FrontPort(device=device, name='Front Port 1', type=PortTypeChoices.TYPE_8P8C), + FrontPort(device=device, name='Front Port 2', type=PortTypeChoices.TYPE_8P8C), + FrontPort(device=device, name='Front Port 3', type=PortTypeChoices.TYPE_8P8C), ) FrontPort.objects.bulk_create(front_ports) + PortMapping.objects.bulk_create([ + PortMapping(device=device, front_port=front_ports[0], rear_port=rear_ports[0]), + PortMapping(device=device, front_port=front_ports[1], rear_port=rear_ports[1]), + PortMapping(device=device, front_port=front_ports[2], rear_port=rear_ports[2]), + ]) cls.create_data = [ { 'device': device.pk, 'name': 'Front Port 4', 'type': PortTypeChoices.TYPE_8P8C, - 'rear_port': rear_ports[3].pk, - 'rear_port_position': 1, + 'rear_ports': [ + { + 'position': 1, + 'rear_port': rear_ports[3].pk, + 'rear_port_position': 1, + }, + ], }, { 'device': device.pk, 'name': 'Front Port 5', 'type': PortTypeChoices.TYPE_8P8C, - 'rear_port': rear_ports[4].pk, - 'rear_port_position': 1, + 'rear_ports': [ + { + 'position': 1, + 'rear_port': rear_ports[4].pk, + 'rear_port_position': 1, + }, + ], }, { 'device': device.pk, 'name': 'Front Port 6', 'type': PortTypeChoices.TYPE_8P8C, - 'rear_port': rear_ports[5].pk, - 'rear_port_position': 1, + 'rear_ports': [ + { + 'position': 1, + 'rear_port': rear_ports[5].pk, + 'rear_port_position': 1, + }, + ], }, ] + cls.update_data = { + 'type': PortTypeChoices.TYPE_LC, + 'rear_ports': [ + { + 'position': 1, + 'rear_port': rear_ports[3].pk, + 'rear_port_position': 1, + }, + ], + } + + def test_update_object(self): + super().test_update_object() + + # Check that the port mapping was updated after modifying the front port + front_port = FrontPort.objects.get(name='Front Port 1') + rear_port = RearPort.objects.get(name='Rear Port 4') + self.assertTrue( + PortMapping.objects.filter( + front_port=front_port, + front_port_position=1, + rear_port=rear_port, + rear_port_position=1, + ).exists() + ) + @tag('regression') # Issue #18991 def test_front_port_paths(self): device = Device.objects.first() - rear_port = RearPort.objects.create( - device=device, name='Rear Port 10', type=PortTypeChoices.TYPE_8P8C - ) interface1 = Interface.objects.create(device=device, name='Interface 1') - front_port = FrontPort.objects.create( - device=device, - name='Rear Port 10', - type=PortTypeChoices.TYPE_8P8C, - rear_port=rear_port, - ) + rear_port = RearPort.objects.create(device=device, name='Rear Port 10', type=PortTypeChoices.TYPE_8P8C) + front_port = FrontPort.objects.create(device=device, name='Front Port 10', type=PortTypeChoices.TYPE_8P8C) + PortMapping.objects.create(device=device, front_port=front_port, rear_port=rear_port) Cable.objects.create(a_terminations=[interface1], b_terminations=[front_port]) self.add_permissions(f'dcim.view_{self.model._meta.model_name}') @@ -2040,6 +2220,15 @@ class RearPortTest(APIViewTestCases.APIViewTestCase): role = DeviceRole.objects.create(name='Test Device Role 1', slug='test-device-role-1', color='ff0000') device = Device.objects.create(device_type=devicetype, role=role, name='Device 1', site=site) + front_ports = ( + FrontPort(device=device, name='Front Port 1', type=PortTypeChoices.TYPE_8P8C), + FrontPort(device=device, name='Front Port 2', type=PortTypeChoices.TYPE_8P8C), + FrontPort(device=device, name='Front Port 3', type=PortTypeChoices.TYPE_8P8C), + FrontPort(device=device, name='Front Port 4', type=PortTypeChoices.TYPE_8P8C), + FrontPort(device=device, name='Front Port 5', type=PortTypeChoices.TYPE_8P8C), + FrontPort(device=device, name='Front Port 6', type=PortTypeChoices.TYPE_8P8C), + ) + FrontPort.objects.bulk_create(front_ports) rear_ports = ( RearPort(device=device, name='Rear Port 1', type=PortTypeChoices.TYPE_8P8C), RearPort(device=device, name='Rear Port 2', type=PortTypeChoices.TYPE_8P8C), @@ -2052,19 +2241,66 @@ class RearPortTest(APIViewTestCases.APIViewTestCase): 'device': device.pk, 'name': 'Rear Port 4', 'type': PortTypeChoices.TYPE_8P8C, + 'front_ports': [ + { + 'position': 1, + 'front_port': front_ports[3].pk, + 'front_port_position': 1, + }, + ], }, { 'device': device.pk, 'name': 'Rear Port 5', 'type': PortTypeChoices.TYPE_8P8C, + 'front_ports': [ + { + 'position': 1, + 'front_port': front_ports[4].pk, + 'front_port_position': 1, + }, + ], }, { 'device': device.pk, 'name': 'Rear Port 6', 'type': PortTypeChoices.TYPE_8P8C, + 'front_ports': [ + { + 'position': 1, + 'front_port': front_ports[5].pk, + 'front_port_position': 1, + }, + ], }, ] + cls.update_data = { + 'type': PortTypeChoices.TYPE_LC, + 'front_ports': [ + { + 'position': 1, + 'front_port': front_ports[3].pk, + 'front_port_position': 1, + }, + ], + } + + def test_update_object(self): + super().test_update_object() + + # Check that the port mapping was updated after modifying the rear port + front_port = FrontPort.objects.get(name='Front Port 4') + rear_port = RearPort.objects.get(name='Rear Port 1') + self.assertTrue( + PortMapping.objects.filter( + front_port=front_port, + front_port_position=1, + rear_port=rear_port, + rear_port_position=1, + ).exists() + ) + @tag('regression') # Issue #18991 def test_rear_port_paths(self): device = Device.objects.first() @@ -2350,6 +2586,7 @@ class CableTest(APIViewTestCases.APIViewTestCase): 'object_id': interfaces[14].pk, }], 'label': 'Cable 4', + 'profile': CableProfileChoices.SINGLE_1C1P, }, { 'a_terminations': [{ @@ -2361,6 +2598,7 @@ class CableTest(APIViewTestCases.APIViewTestCase): 'object_id': interfaces[15].pk, }], 'label': 'Cable 5', + 'profile': CableProfileChoices.SINGLE_1C1P, }, { 'a_terminations': [{ @@ -2372,10 +2610,40 @@ class CableTest(APIViewTestCases.APIViewTestCase): 'object_id': interfaces[16].pk, }], 'label': 'Cable 6', + # No profile (legacy behavior) }, ] +class CableTerminationTest( + APIViewTestCases.GetObjectViewTestCase, + APIViewTestCases.ListObjectsViewTestCase, +): + model = CableTermination + brief_fields = [ + 'cable', 'cable_end', 'connector', 'display', 'id', 'positions', 'termination_id', 'termination_type', 'url', + ] + + @classmethod + def setUpTestData(cls): + device1 = create_test_device('Device 1') + device2 = create_test_device('Device 2') + + interfaces = [] + for device in (device1, device2): + for i in range(0, 10): + interfaces.append(Interface(device=device, type=InterfaceTypeChoices.TYPE_1GE_FIXED, name=f'eth{i}')) + Interface.objects.bulk_create(interfaces) + + cables = ( + Cable(a_terminations=[interfaces[0]], b_terminations=[interfaces[10]], label='Cable 1'), + Cable(a_terminations=[interfaces[1]], b_terminations=[interfaces[11]], label='Cable 2'), + Cable(a_terminations=[interfaces[2]], b_terminations=[interfaces[12]], label='Cable 3'), + ) + for cable in cables: + cable.save() + + class ConnectedDeviceTest(APITestCase): @classmethod diff --git a/netbox/dcim/tests/test_cablepaths.py b/netbox/dcim/tests/test_cablepaths.py index 95bfc7bf9..1bd613e3b 100644 --- a/netbox/dcim/tests/test_cablepaths.py +++ b/netbox/dcim/tests/test_cablepaths.py @@ -1,100 +1,21 @@ -from django.test import TestCase - from circuits.models import * from dcim.choices import LinkStatusChoices from dcim.models import * from dcim.svg import CableTraceSVG -from dcim.utils import object_to_path_node +from dcim.tests.utils import CablePathTestCase from utilities.exceptions import AbortRequest -class CablePathTestCase(TestCase): +class LegacyCablePathTests(CablePathTestCase): """ - Test NetBox's ability to trace and retrace CablePaths in response to data model changes. Tests are numbered - as follows: + Test NetBox's ability to trace and retrace CablePaths in response to data model changes, without cable profiles. + Tests are numbered as follows: 1XX: Test direct connections between different endpoint types 2XX: Test different cable topologies 3XX: Test responses to changes in existing objects 4XX: Test to exclude specific cable topologies """ - @classmethod - def setUpTestData(cls): - - # Create a single device that will hold all components - cls.site = Site.objects.create(name='Site', slug='site') - - manufacturer = Manufacturer.objects.create(name='Generic', slug='generic') - device_type = DeviceType.objects.create(manufacturer=manufacturer, model='Test Device') - role = DeviceRole.objects.create(name='Device Role', slug='device-role') - cls.device = Device.objects.create(site=cls.site, device_type=device_type, role=role, name='Test Device') - - cls.powerpanel = PowerPanel.objects.create(site=cls.site, name='Power Panel') - - provider = Provider.objects.create(name='Provider', slug='provider') - circuit_type = CircuitType.objects.create(name='Circuit Type', slug='circuit-type') - cls.circuit = Circuit.objects.create(provider=provider, type=circuit_type, cid='Circuit 1') - - def _get_cablepath(self, nodes, **kwargs): - """ - Return a given cable path - - :param nodes: Iterable of steps, with each step being either a single node or a list of nodes - - :return: The matching CablePath (if any) - """ - path = [] - for step in nodes: - if type(step) in (list, tuple): - path.append([object_to_path_node(node) for node in step]) - else: - path.append([object_to_path_node(step)]) - return CablePath.objects.filter(path=path, **kwargs).first() - - def assertPathExists(self, nodes, **kwargs): - """ - Assert that a CablePath from origin to destination with a specific intermediate path exists. Returns the - first matching CablePath, if found. - - :param nodes: Iterable of steps, with each step being either a single node or a list of nodes - """ - cablepath = self._get_cablepath(nodes, **kwargs) - self.assertIsNotNone(cablepath, msg='CablePath not found') - - return cablepath - - def assertPathDoesNotExist(self, nodes, **kwargs): - """ - Assert that a specific CablePath does *not* exist. - - :param nodes: Iterable of steps, with each step being either a single node or a list of nodes - """ - cablepath = self._get_cablepath(nodes, **kwargs) - self.assertIsNone(cablepath, msg='Unexpected CablePath found') - - def assertPathIsSet(self, origin, cablepath, msg=None): - """ - Assert that a specific CablePath instance is set as the path on the origin. - - :param origin: The originating path endpoint - :param cablepath: The CablePath instance originating from this endpoint - :param msg: Custom failure message (optional) - """ - if msg is None: - msg = f"Path #{cablepath.pk} not set on originating endpoint {origin}" - self.assertEqual(origin._path_id, cablepath.pk, msg=msg) - - def assertPathIsNotSet(self, origin, msg=None): - """ - Assert that a specific CablePath instance is set as the path on the origin. - - :param origin: The originating path endpoint - :param msg: Custom failure message (optional) - """ - if msg is None: - msg = f"Path #{origin._path_id} set as origin on {origin}; should be None!" - self.assertIsNone(origin._path_id, msg=msg) - def test_101_interface_to_interface(self): """ [IF1] --C1-- [IF2] @@ -360,9 +281,14 @@ class CablePathTestCase(TestCase): """ interface1 = Interface.objects.create(device=self.device, name='Interface 1') interface2 = Interface.objects.create(device=self.device, name='Interface 2') - rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1', positions=1) - frontport1 = FrontPort.objects.create( - device=self.device, name='Front Port 1', rear_port=rearport1, rear_port_position=1 + rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1') + frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1') + PortMapping.objects.create( + device=self.device, + front_port=frontport1, + front_port_position=1, + rear_port=rearport1, + rear_port_position=1 ) # Create cable 1 @@ -419,9 +345,14 @@ class CablePathTestCase(TestCase): interface2 = Interface.objects.create(device=self.device, name='Interface 2') interface3 = Interface.objects.create(device=self.device, name='Interface 3') interface4 = Interface.objects.create(device=self.device, name='Interface 4') - rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1', positions=1) - frontport1 = FrontPort.objects.create( - device=self.device, name='Front Port 1', rear_port=rearport1, rear_port_position=1 + rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1') + frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1') + PortMapping.objects.create( + device=self.device, + front_port=frontport1, + front_port_position=1, + rear_port=rearport1, + rear_port_position=1 ) # Create cable 1 @@ -482,18 +413,40 @@ class CablePathTestCase(TestCase): interface4 = Interface.objects.create(device=self.device, name='Interface 4') rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1', positions=4) rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2', positions=4) - frontport1_1 = FrontPort.objects.create( - device=self.device, name='Front Port 1:1', rear_port=rearport1, rear_port_position=1 - ) - frontport1_2 = FrontPort.objects.create( - device=self.device, name='Front Port 1:2', rear_port=rearport1, rear_port_position=2 - ) - frontport2_1 = FrontPort.objects.create( - device=self.device, name='Front Port 2:1', rear_port=rearport2, rear_port_position=1 - ) - frontport2_2 = FrontPort.objects.create( - device=self.device, name='Front Port 2:2', rear_port=rearport2, rear_port_position=2 - ) + frontport1_1 = FrontPort.objects.create(device=self.device, name='Front Port 1:1') + frontport1_2 = FrontPort.objects.create(device=self.device, name='Front Port 1:2') + frontport2_1 = FrontPort.objects.create(device=self.device, name='Front Port 2:1') + frontport2_2 = FrontPort.objects.create(device=self.device, name='Front Port 2:2') + PortMapping.objects.bulk_create([ + PortMapping( + device=self.device, + front_port=frontport1_1, + front_port_position=1, + rear_port=rearport1, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport1_2, + front_port_position=1, + rear_port=rearport1, + rear_port_position=2, + ), + PortMapping( + device=self.device, + front_port=frontport2_1, + front_port_position=1, + rear_port=rearport2, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport2_2, + front_port_position=1, + rear_port=rearport2, + rear_port_position=2, + ), + ]) # Create cables 1-2 cable1 = Cable( @@ -600,18 +553,40 @@ class CablePathTestCase(TestCase): interface8 = Interface.objects.create(device=self.device, name='Interface 8') rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1', positions=4) rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2', positions=4) - frontport1_1 = FrontPort.objects.create( - device=self.device, name='Front Port 1:1', rear_port=rearport1, rear_port_position=1 - ) - frontport1_2 = FrontPort.objects.create( - device=self.device, name='Front Port 1:2', rear_port=rearport1, rear_port_position=2 - ) - frontport2_1 = FrontPort.objects.create( - device=self.device, name='Front Port 2:1', rear_port=rearport2, rear_port_position=1 - ) - frontport2_2 = FrontPort.objects.create( - device=self.device, name='Front Port 2:2', rear_port=rearport2, rear_port_position=2 - ) + frontport1_1 = FrontPort.objects.create(device=self.device, name='Front Port 1:1') + frontport1_2 = FrontPort.objects.create(device=self.device, name='Front Port 1:2') + frontport2_1 = FrontPort.objects.create(device=self.device, name='Front Port 2:1') + frontport2_2 = FrontPort.objects.create(device=self.device, name='Front Port 2:2') + PortMapping.objects.bulk_create([ + PortMapping( + device=self.device, + front_port=frontport1_1, + front_port_position=1, + rear_port=rearport1, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport1_2, + front_port_position=1, + rear_port=rearport1, + rear_port_position=2, + ), + PortMapping( + device=self.device, + front_port=frontport2_1, + front_port_position=1, + rear_port=rearport2, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport2_2, + front_port_position=1, + rear_port=rearport2, + rear_port_position=2, + ), + ]) # Create cables 1-2 cable1 = Cable( @@ -759,27 +734,59 @@ class CablePathTestCase(TestCase): interface3 = Interface.objects.create(device=self.device, name='Interface 3') interface4 = Interface.objects.create(device=self.device, name='Interface 4') rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1', positions=4) - rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2', positions=1) - rearport3 = RearPort.objects.create(device=self.device, name='Rear Port 3', positions=1) + rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2') + rearport3 = RearPort.objects.create(device=self.device, name='Rear Port 3') rearport4 = RearPort.objects.create(device=self.device, name='Rear Port 4', positions=4) - frontport1_1 = FrontPort.objects.create( - device=self.device, name='Front Port 1:1', rear_port=rearport1, rear_port_position=1 - ) - frontport1_2 = FrontPort.objects.create( - device=self.device, name='Front Port 1:2', rear_port=rearport1, rear_port_position=2 - ) - frontport2 = FrontPort.objects.create( - device=self.device, name='Front Port 2', rear_port=rearport2, rear_port_position=1 - ) - frontport3 = FrontPort.objects.create( - device=self.device, name='Front Port 3', rear_port=rearport3, rear_port_position=1 - ) - frontport4_1 = FrontPort.objects.create( - device=self.device, name='Front Port 4:1', rear_port=rearport4, rear_port_position=1 - ) - frontport4_2 = FrontPort.objects.create( - device=self.device, name='Front Port 4:2', rear_port=rearport4, rear_port_position=2 - ) + frontport1_1 = FrontPort.objects.create(device=self.device, name='Front Port 1:1') + frontport1_2 = FrontPort.objects.create(device=self.device, name='Front Port 1:2') + frontport2 = FrontPort.objects.create(device=self.device, name='Front Port 2') + frontport3 = FrontPort.objects.create(device=self.device, name='Front Port 3') + frontport4_1 = FrontPort.objects.create(device=self.device, name='Front Port 4:1') + frontport4_2 = FrontPort.objects.create(device=self.device, name='Front Port 4:2') + PortMapping.objects.bulk_create([ + PortMapping( + device=self.device, + front_port=frontport1_1, + front_port_position=1, + rear_port=rearport1, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport1_2, + front_port_position=1, + rear_port=rearport1, + rear_port_position=2, + ), + PortMapping( + device=self.device, + front_port=frontport2, + front_port_position=1, + rear_port=rearport2, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport3, + front_port_position=1, + rear_port=rearport3, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport4_1, + front_port_position=1, + rear_port=rearport4, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport4_2, + front_port_position=1, + rear_port=rearport4, + rear_port_position=2, + ), + ]) # Create cables 1-2, 6-7 cable1 = Cable( @@ -880,30 +887,72 @@ class CablePathTestCase(TestCase): rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2', positions=4) rearport3 = RearPort.objects.create(device=self.device, name='Rear Port 3', positions=4) rearport4 = RearPort.objects.create(device=self.device, name='Rear Port 4', positions=4) - frontport1_1 = FrontPort.objects.create( - device=self.device, name='Front Port 1:1', rear_port=rearport1, rear_port_position=1 - ) - frontport1_2 = FrontPort.objects.create( - device=self.device, name='Front Port 1:2', rear_port=rearport1, rear_port_position=2 - ) - frontport2_1 = FrontPort.objects.create( - device=self.device, name='Front Port 2:1', rear_port=rearport2, rear_port_position=1 - ) - frontport2_2 = FrontPort.objects.create( - device=self.device, name='Front Port 2:2', rear_port=rearport2, rear_port_position=2 - ) - frontport3_1 = FrontPort.objects.create( - device=self.device, name='Front Port 3:1', rear_port=rearport3, rear_port_position=1 - ) - frontport3_2 = FrontPort.objects.create( - device=self.device, name='Front Port 3:2', rear_port=rearport3, rear_port_position=2 - ) - frontport4_1 = FrontPort.objects.create( - device=self.device, name='Front Port 4:1', rear_port=rearport4, rear_port_position=1 - ) - frontport4_2 = FrontPort.objects.create( - device=self.device, name='Front Port 4:2', rear_port=rearport4, rear_port_position=2 - ) + frontport1_1 = FrontPort.objects.create(device=self.device, name='Front Port 1:1') + frontport1_2 = FrontPort.objects.create(device=self.device, name='Front Port 1:2') + frontport2_1 = FrontPort.objects.create(device=self.device, name='Front Port 2:1') + frontport2_2 = FrontPort.objects.create(device=self.device, name='Front Port 2:2') + frontport3_1 = FrontPort.objects.create(device=self.device, name='Front Port 3:1') + frontport3_2 = FrontPort.objects.create(device=self.device, name='Front Port 3:2') + frontport4_1 = FrontPort.objects.create(device=self.device, name='Front Port 4:1') + frontport4_2 = FrontPort.objects.create(device=self.device, name='Front Port 4:2') + PortMapping.objects.bulk_create([ + PortMapping( + device=self.device, + front_port=frontport1_1, + front_port_position=1, + rear_port=rearport1, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport1_2, + front_port_position=1, + rear_port=rearport1, + rear_port_position=2, + ), + PortMapping( + device=self.device, + front_port=frontport2_1, + front_port_position=1, + rear_port=rearport2, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport2_2, + front_port_position=1, + rear_port=rearport2, + rear_port_position=2, + ), + PortMapping( + device=self.device, + front_port=frontport3_1, + front_port_position=1, + rear_port=rearport3, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport3_2, + front_port_position=1, + rear_port=rearport3, + rear_port_position=2, + ), + PortMapping( + device=self.device, + front_port=frontport4_1, + front_port_position=1, + rear_port=rearport4, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport4_2, + front_port_position=1, + rear_port=rearport4, + rear_port_position=2, + ), + ]) # Create cables 1-3, 6-8 cable1 = Cable( @@ -1007,23 +1056,50 @@ class CablePathTestCase(TestCase): interface3 = Interface.objects.create(device=self.device, name='Interface 3') interface4 = Interface.objects.create(device=self.device, name='Interface 4') rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1', positions=4) - rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 5', positions=1) - rearport3 = RearPort.objects.create(device=self.device, name='Rear Port 2', positions=4) - frontport1_1 = FrontPort.objects.create( - device=self.device, name='Front Port 1:1', rear_port=rearport1, rear_port_position=1 - ) - frontport1_2 = FrontPort.objects.create( - device=self.device, name='Front Port 1:2', rear_port=rearport1, rear_port_position=2 - ) - frontport2 = FrontPort.objects.create( - device=self.device, name='Front Port 5', rear_port=rearport2, rear_port_position=1 - ) - frontport3_1 = FrontPort.objects.create( - device=self.device, name='Front Port 2:1', rear_port=rearport3, rear_port_position=1 - ) - frontport3_2 = FrontPort.objects.create( - device=self.device, name='Front Port 2:2', rear_port=rearport3, rear_port_position=2 - ) + rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2') + rearport3 = RearPort.objects.create(device=self.device, name='Rear Port 3', positions=4) + frontport1_1 = FrontPort.objects.create(device=self.device, name='Front Port 1:1') + frontport1_2 = FrontPort.objects.create(device=self.device, name='Front Port 1:2') + frontport2 = FrontPort.objects.create(device=self.device, name='Front Port 2') + frontport3_1 = FrontPort.objects.create(device=self.device, name='Front Port 3:1') + frontport3_2 = FrontPort.objects.create(device=self.device, name='Front Port 3:2') + PortMapping.objects.bulk_create([ + PortMapping( + device=self.device, + front_port=frontport1_1, + front_port_position=1, + rear_port=rearport1, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport1_2, + front_port_position=1, + rear_port=rearport1, + rear_port_position=2, + ), + PortMapping( + device=self.device, + front_port=frontport2, + front_port_position=1, + rear_port=rearport2, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport3_1, + front_port_position=1, + rear_port=rearport3, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport3_2, + front_port_position=1, + rear_port=rearport3, + rear_port_position=2, + ), + ]) # Create cables 1-2, 5-6 cable1 = Cable( @@ -1111,13 +1187,25 @@ class CablePathTestCase(TestCase): interface1 = Interface.objects.create(device=self.device, name='Interface 1') interface2 = Interface.objects.create(device=self.device, name='Interface 2') interface3 = Interface.objects.create(device=self.device, name='Interface 3') - rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1', positions=4) - frontport1_1 = FrontPort.objects.create( - device=self.device, name='Front Port 1:1', rear_port=rearport1, rear_port_position=1 - ) - frontport1_2 = FrontPort.objects.create( - device=self.device, name='Front Port 1:2', rear_port=rearport1, rear_port_position=2 - ) + rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1', positions=2) + frontport1_1 = FrontPort.objects.create(device=self.device, name='Front Port 1:1') + frontport1_2 = FrontPort.objects.create(device=self.device, name='Front Port 1:2') + PortMapping.objects.bulk_create([ + PortMapping( + device=self.device, + front_port=frontport1_1, + front_port_position=1, + rear_port=rearport1, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport1_2, + front_port_position=1, + rear_port=rearport1, + rear_port_position=2, + ), + ]) # Create cables 1 cable1 = Cable( @@ -1177,10 +1265,11 @@ class CablePathTestCase(TestCase): [IF1] --C1-- [FP1] [RP1] --C2-- [RP2] """ interface1 = Interface.objects.create(device=self.device, name='Interface 1') - rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1', positions=1) - rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2', positions=1) - frontport1 = FrontPort.objects.create( - device=self.device, name='Front Port 1', rear_port=rearport1, rear_port_position=1 + rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1') + rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2') + frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1') + PortMapping.objects.create( + front_port=frontport1, front_port_position=1, rear_port=rearport1, rear_port_position=1, ) # Create cables @@ -1492,18 +1581,40 @@ class CablePathTestCase(TestCase): interface4 = Interface.objects.create(device=self.device, name='Interface 4') rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1', positions=4) rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2', positions=4) - frontport1_1 = FrontPort.objects.create( - device=self.device, name='Front Port 1:1', rear_port=rearport1, rear_port_position=1 - ) - frontport1_2 = FrontPort.objects.create( - device=self.device, name='Front Port 1:2', rear_port=rearport1, rear_port_position=2 - ) - frontport2_1 = FrontPort.objects.create( - device=self.device, name='Front Port 2:1', rear_port=rearport2, rear_port_position=1 - ) - frontport2_2 = FrontPort.objects.create( - device=self.device, name='Front Port 2:2', rear_port=rearport2, rear_port_position=2 - ) + frontport1_1 = FrontPort.objects.create(device=self.device, name='Front Port 1:1') + frontport1_2 = FrontPort.objects.create(device=self.device, name='Front Port 1:2') + frontport2_1 = FrontPort.objects.create(device=self.device, name='Front Port 2:1') + frontport2_2 = FrontPort.objects.create(device=self.device, name='Front Port 2:2') + PortMapping.objects.bulk_create([ + PortMapping( + device=self.device, + front_port=frontport1_1, + front_port_position=1, + rear_port=rearport1, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport1_2, + front_port_position=1, + rear_port=rearport1, + rear_port_position=2, + ), + PortMapping( + device=self.device, + front_port=frontport2_1, + front_port_position=1, + rear_port=rearport2, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport2_2, + front_port_position=1, + rear_port=rearport2, + rear_port_position=2, + ), + ]) circuittermination1 = CircuitTermination.objects.create( circuit=self.circuit, termination=self.site, @@ -1680,22 +1791,44 @@ class CablePathTestCase(TestCase): """ interface1 = Interface.objects.create(device=self.device, name='Interface 1') interface2 = Interface.objects.create(device=self.device, name='Interface 2') - rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1', positions=1) - rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2', positions=1) - rearport3 = RearPort.objects.create(device=self.device, name='Rear Port 3', positions=1) - rearport4 = RearPort.objects.create(device=self.device, name='Rear Port 4', positions=1) - frontport1 = FrontPort.objects.create( - device=self.device, name='Front Port 1', rear_port=rearport1, rear_port_position=1 - ) - frontport2 = FrontPort.objects.create( - device=self.device, name='Front Port 2', rear_port=rearport2, rear_port_position=1 - ) - frontport3 = FrontPort.objects.create( - device=self.device, name='Front Port 3', rear_port=rearport3, rear_port_position=1 - ) - frontport4 = FrontPort.objects.create( - device=self.device, name='Front Port 4', rear_port=rearport4, rear_port_position=1 - ) + rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1') + rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2') + rearport3 = RearPort.objects.create(device=self.device, name='Rear Port 3') + rearport4 = RearPort.objects.create(device=self.device, name='Rear Port 4') + frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1') + frontport2 = FrontPort.objects.create(device=self.device, name='Front Port 2') + frontport3 = FrontPort.objects.create(device=self.device, name='Front Port 3') + frontport4 = FrontPort.objects.create(device=self.device, name='Front Port 4') + PortMapping.objects.bulk_create([ + PortMapping( + device=self.device, + front_port=frontport1, + front_port_position=1, + rear_port=rearport1, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport2, + front_port_position=1, + rear_port=rearport2, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport3, + front_port_position=1, + rear_port=rearport3, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport4, + front_port_position=1, + rear_port=rearport4, + rear_port_position=1, + ), + ]) # Create cables 1-2 cable1 = Cable( @@ -1767,30 +1900,72 @@ class CablePathTestCase(TestCase): interface4 = Interface.objects.create(device=self.device, name='Interface 4') rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1', positions=4) rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2', positions=4) - frontport1_1 = FrontPort.objects.create( - device=self.device, name='Front Port 1:1', rear_port=rearport1, rear_port_position=1 - ) - frontport1_2 = FrontPort.objects.create( - device=self.device, name='Front Port 1:2', rear_port=rearport1, rear_port_position=2 - ) - frontport1_3 = FrontPort.objects.create( - device=self.device, name='Front Port 1:3', rear_port=rearport1, rear_port_position=3 - ) - frontport1_4 = FrontPort.objects.create( - device=self.device, name='Front Port 1:4', rear_port=rearport1, rear_port_position=4 - ) - frontport2_1 = FrontPort.objects.create( - device=self.device, name='Front Port 2:1', rear_port=rearport2, rear_port_position=1 - ) - frontport2_2 = FrontPort.objects.create( - device=self.device, name='Front Port 2:2', rear_port=rearport2, rear_port_position=2 - ) - frontport2_3 = FrontPort.objects.create( - device=self.device, name='Front Port 2:3', rear_port=rearport2, rear_port_position=3 - ) - frontport2_4 = FrontPort.objects.create( - device=self.device, name='Front Port 2:4', rear_port=rearport2, rear_port_position=4 - ) + frontport1_1 = FrontPort.objects.create(device=self.device, name='Front Port 1:1') + frontport1_2 = FrontPort.objects.create(device=self.device, name='Front Port 1:2') + frontport1_3 = FrontPort.objects.create(device=self.device, name='Front Port 1:3') + frontport1_4 = FrontPort.objects.create(device=self.device, name='Front Port 1:4') + frontport2_1 = FrontPort.objects.create(device=self.device, name='Front Port 2:1') + frontport2_2 = FrontPort.objects.create(device=self.device, name='Front Port 2:2') + frontport2_3 = FrontPort.objects.create(device=self.device, name='Front Port 2:3') + frontport2_4 = FrontPort.objects.create(device=self.device, name='Front Port 2:4') + PortMapping.objects.bulk_create([ + PortMapping( + device=self.device, + front_port=frontport1_1, + front_port_position=1, + rear_port=rearport1, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport1_2, + front_port_position=1, + rear_port=rearport1, + rear_port_position=2, + ), + PortMapping( + device=self.device, + front_port=frontport1_3, + front_port_position=1, + rear_port=rearport1, + rear_port_position=3, + ), + PortMapping( + device=self.device, + front_port=frontport1_4, + front_port_position=1, + rear_port=rearport1, + rear_port_position=4, + ), + PortMapping( + device=self.device, + front_port=frontport2_1, + front_port_position=1, + rear_port=rearport2, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport2_2, + front_port_position=1, + rear_port=rearport2, + rear_port_position=2, + ), + PortMapping( + device=self.device, + front_port=frontport2_3, + front_port_position=1, + rear_port=rearport2, + rear_port_position=3, + ), + PortMapping( + device=self.device, + front_port=frontport2_4, + front_port_position=1, + rear_port=rearport2, + rear_port_position=4, + ), + ]) # Create cables 1-2 cable1 = Cable( @@ -1937,22 +2112,44 @@ class CablePathTestCase(TestCase): """ interface1 = Interface.objects.create(device=self.device, name='Interface 1') interface2 = Interface.objects.create(device=self.device, name='Interface 2') - rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1', positions=1) - rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2', positions=1) - rearport3 = RearPort.objects.create(device=self.device, name='Rear Port 3', positions=1) - rearport4 = RearPort.objects.create(device=self.device, name='Rear Port 4', positions=1) - frontport1 = FrontPort.objects.create( - device=self.device, name='Front Port 1', rear_port=rearport1, rear_port_position=1 - ) - frontport2 = FrontPort.objects.create( - device=self.device, name='Front Port 2', rear_port=rearport2, rear_port_position=1 - ) - frontport3 = FrontPort.objects.create( - device=self.device, name='Front Port 3', rear_port=rearport3, rear_port_position=1 - ) - frontport4 = FrontPort.objects.create( - device=self.device, name='Front Port 4', rear_port=rearport4, rear_port_position=1 - ) + rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1') + rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2') + rearport3 = RearPort.objects.create(device=self.device, name='Rear Port 3') + rearport4 = RearPort.objects.create(device=self.device, name='Rear Port 4') + frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1') + frontport2 = FrontPort.objects.create(device=self.device, name='Front Port 2') + frontport3 = FrontPort.objects.create(device=self.device, name='Front Port 3') + frontport4 = FrontPort.objects.create(device=self.device, name='Front Port 4') + PortMapping.objects.bulk_create([ + PortMapping( + device=self.device, + front_port=frontport1, + front_port_position=1, + rear_port=rearport1, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport2, + front_port_position=1, + rear_port=rearport2, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport3, + front_port_position=1, + rear_port=rearport3, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport4, + front_port_position=1, + rear_port=rearport4, + rear_port_position=1, + ), + ]) cable2 = Cable( a_terminations=[rearport1], @@ -2016,22 +2213,44 @@ class CablePathTestCase(TestCase): interface1 = Interface.objects.create(device=self.device, name='Interface 1') interface2 = Interface.objects.create(device=self.device, name='Interface 2') interface3 = Interface.objects.create(device=self.device, name='Interface 3') - rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1', positions=1) - rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2', positions=1) - rearport3 = RearPort.objects.create(device=self.device, name='Rear Port 3', positions=1) - rearport4 = RearPort.objects.create(device=self.device, name='Rear Port 4', positions=1) - frontport1 = FrontPort.objects.create( - device=self.device, name='Front Port 1', rear_port=rearport1, rear_port_position=1 - ) - frontport2 = FrontPort.objects.create( - device=self.device, name='Front Port 2', rear_port=rearport2, rear_port_position=1 - ) - frontport3 = FrontPort.objects.create( - device=self.device, name='Front Port 3', rear_port=rearport3, rear_port_position=1 - ) - frontport4 = FrontPort.objects.create( - device=self.device, name='Front Port 4', rear_port=rearport4, rear_port_position=1 - ) + rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1') + rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2') + rearport3 = RearPort.objects.create(device=self.device, name='Rear Port 3') + rearport4 = RearPort.objects.create(device=self.device, name='Rear Port 4') + frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1') + frontport2 = FrontPort.objects.create(device=self.device, name='Front Port 2') + frontport3 = FrontPort.objects.create(device=self.device, name='Front Port 3') + frontport4 = FrontPort.objects.create(device=self.device, name='Front Port 4') + PortMapping.objects.bulk_create([ + PortMapping( + device=self.device, + front_port=frontport1, + front_port_position=1, + rear_port=rearport1, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport2, + front_port_position=1, + rear_port=rearport2, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport3, + front_port_position=1, + rear_port=rearport3, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport4, + front_port_position=1, + rear_port=rearport4, + rear_port_position=1, + ), + ]) cable2 = Cable( a_terminations=[rearport1], @@ -2112,30 +2331,62 @@ class CablePathTestCase(TestCase): interface1 = Interface.objects.create(device=self.device, name='Interface 1') interface2 = Interface.objects.create(device=self.device, name='Interface 2') interface3 = Interface.objects.create(device=self.device, name='Interface 3') - rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1', positions=1) - rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2', positions=1) - rearport3 = RearPort.objects.create(device=self.device, name='Rear Port 3', positions=1) - rearport4 = RearPort.objects.create(device=self.device, name='Rear Port 4', positions=1) - rearport5 = RearPort.objects.create(device=self.device, name='Rear Port 5', positions=1) - rearport6 = RearPort.objects.create(device=self.device, name='Rear Port 6', positions=1) - frontport1 = FrontPort.objects.create( - device=self.device, name='Front Port 1', rear_port=rearport1, rear_port_position=1 - ) - frontport2 = FrontPort.objects.create( - device=self.device, name='Front Port 2', rear_port=rearport2, rear_port_position=1 - ) - frontport3 = FrontPort.objects.create( - device=self.device, name='Front Port 3', rear_port=rearport3, rear_port_position=1 - ) - frontport4 = FrontPort.objects.create( - device=self.device, name='Front Port 4', rear_port=rearport4, rear_port_position=1 - ) - frontport5 = FrontPort.objects.create( - device=self.device, name='Front Port 5', rear_port=rearport5, rear_port_position=1 - ) - frontport6 = FrontPort.objects.create( - device=self.device, name='Front Port 6', rear_port=rearport6, rear_port_position=1 - ) + rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1') + rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2') + rearport3 = RearPort.objects.create(device=self.device, name='Rear Port 3') + rearport4 = RearPort.objects.create(device=self.device, name='Rear Port 4') + rearport5 = RearPort.objects.create(device=self.device, name='Rear Port 5') + rearport6 = RearPort.objects.create(device=self.device, name='Rear Port 6') + frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1') + frontport2 = FrontPort.objects.create(device=self.device, name='Front Port 2') + frontport3 = FrontPort.objects.create(device=self.device, name='Front Port 3') + frontport4 = FrontPort.objects.create(device=self.device, name='Front Port 4') + frontport5 = FrontPort.objects.create(device=self.device, name='Front Port 5') + frontport6 = FrontPort.objects.create(device=self.device, name='Front Port 6') + PortMapping.objects.bulk_create([ + PortMapping( + device=self.device, + front_port=frontport1, + front_port_position=1, + rear_port=rearport1, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport2, + front_port_position=1, + rear_port=rearport2, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport3, + front_port_position=1, + rear_port=rearport3, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport4, + front_port_position=1, + rear_port=rearport4, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport5, + front_port_position=1, + rear_port=rearport5, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport6, + front_port_position=1, + rear_port=rearport6, + rear_port_position=1, + ), + ]) cable2 = Cable( a_terminations=[rearport1], @@ -2234,14 +2485,26 @@ class CablePathTestCase(TestCase): """ interface1 = Interface.objects.create(device=self.device, name='Interface 1') interface2 = Interface.objects.create(device=self.device, name='Interface 2') - rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1', positions=1) - rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2', positions=1) - frontport1 = FrontPort.objects.create( - device=self.device, name='Front Port 1', rear_port=rearport1, rear_port_position=1 - ) - frontport2 = FrontPort.objects.create( - device=self.device, name='Front Port 2', rear_port=rearport2, rear_port_position=1 - ) + rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1') + rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2') + frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1') + frontport2 = FrontPort.objects.create(device=self.device, name='Front Port 2') + PortMapping.objects.bulk_create([ + PortMapping( + device=self.device, + front_port=frontport1, + front_port_position=1, + rear_port=rearport1, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport2, + front_port_position=1, + rear_port=rearport2, + rear_port_position=1, + ), + ]) cable1 = Cable( a_terminations=[interface1], @@ -2344,20 +2607,93 @@ class CablePathTestCase(TestCase): interface2.refresh_from_db() self.assertPathIsSet(interface2, path2) + def test_224_single_path_via_multiple_pass_throughs_with_breakouts(self): + """ + [IF1] --C1-- [FP1] [RP1] --C2-- [IF3] + [IF2] [FP2] [RP2] [IF4] + """ + interface1 = Interface.objects.create(device=self.device, name='Interface 1') + interface2 = Interface.objects.create(device=self.device, name='Interface 2') + interface3 = Interface.objects.create(device=self.device, name='Interface 3') + interface4 = Interface.objects.create(device=self.device, name='Interface 4') + rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1') + rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2') + frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1') + frontport2 = FrontPort.objects.create(device=self.device, name='Front Port 2') + PortMapping.objects.bulk_create([ + PortMapping( + device=self.device, + front_port=frontport1, + front_port_position=1, + rear_port=rearport1, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport2, + front_port_position=1, + rear_port=rearport2, + rear_port_position=1, + ), + ]) + + # Create cables + cable1 = Cable( + a_terminations=[interface1, interface2], + b_terminations=[frontport1, frontport2] + ) + cable1.save() + cable2 = Cable( + a_terminations=[rearport1, rearport2], + b_terminations=[interface3, interface4] + ) + cable2.save() + + # Validate paths + self.assertPathExists( + ( + [interface1, interface2], cable1, [frontport1, frontport2], + [rearport1, rearport2], cable2, [interface3, interface4], + ), + is_complete=True, + is_active=True + ) + self.assertPathExists( + ( + [interface3, interface4], cable2, [rearport1, rearport2], + [frontport1, frontport2], cable1, [interface1, interface2], + ), + is_complete=True, + is_active=True + ) + self.assertEqual(CablePath.objects.count(), 2) + def test_301_create_path_via_existing_cable(self): """ [IF1] --C1-- [FP1] [RP1] --C2-- [RP2] [FP2] --C3-- [IF2] """ interface1 = Interface.objects.create(device=self.device, name='Interface 1') interface2 = Interface.objects.create(device=self.device, name='Interface 2') - rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1', positions=1) - rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2', positions=1) - frontport1 = FrontPort.objects.create( - device=self.device, name='Front Port 1', rear_port=rearport1, rear_port_position=1 - ) - frontport2 = FrontPort.objects.create( - device=self.device, name='Front Port 2', rear_port=rearport2, rear_port_position=1 - ) + rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1') + rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2') + frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1') + frontport2 = FrontPort.objects.create(device=self.device, name='Front Port 2') + PortMapping.objects.bulk_create([ + PortMapping( + device=self.device, + front_port=frontport1, + front_port_position=1, + rear_port=rearport1, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport2, + front_port_position=1, + rear_port=rearport2, + rear_port_position=1, + ), + ]) # Create cable 2 cable2 = Cable( @@ -2403,10 +2739,17 @@ class CablePathTestCase(TestCase): """ interface1 = Interface.objects.create(device=self.device, name='Interface 1') interface2 = Interface.objects.create(device=self.device, name='Interface 2') - rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1', positions=1) - frontport1 = FrontPort.objects.create( - device=self.device, name='Front Port 1', rear_port=rearport1, rear_port_position=1 - ) + rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1') + frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1') + PortMapping.objects.bulk_create([ + PortMapping( + device=self.device, + front_port=frontport1, + front_port_position=1, + rear_port=rearport1, + rear_port_position=1, + ), + ]) # Create cables 1 and 2 cable1 = Cable( @@ -2508,22 +2851,44 @@ class CablePathTestCase(TestCase): ) interface1 = Interface.objects.create(device=self.device, name='Interface 1') interface2 = Interface.objects.create(device=self.device, name='Interface 2') - rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1', positions=1) - rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2', positions=1) - rearport3 = RearPort.objects.create(device=device, name='Rear Port 3', positions=1) - rearport4 = RearPort.objects.create(device=device, name='Rear Port 4', positions=1) - frontport1 = FrontPort.objects.create( - device=self.device, name='Front Port 1', rear_port=rearport1, rear_port_position=1 - ) - frontport2 = FrontPort.objects.create( - device=self.device, name='Front Port 2', rear_port=rearport2, rear_port_position=1 - ) - frontport3 = FrontPort.objects.create( - device=device, name='Front Port 3', rear_port=rearport3, rear_port_position=1 - ) - frontport4 = FrontPort.objects.create( - device=device, name='Front Port 4', rear_port=rearport4, rear_port_position=1 - ) + rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1') + rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2') + rearport3 = RearPort.objects.create(device=device, name='Rear Port 3') + rearport4 = RearPort.objects.create(device=device, name='Rear Port 4') + frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1') + frontport2 = FrontPort.objects.create(device=self.device, name='Front Port 2') + frontport3 = FrontPort.objects.create(device=self.device, name='Front Port 3') + frontport4 = FrontPort.objects.create(device=self.device, name='Front Port 4') + PortMapping.objects.bulk_create([ + PortMapping( + device=self.device, + front_port=frontport1, + front_port_position=1, + rear_port=rearport1, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport2, + front_port_position=1, + rear_port=rearport2, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport3, + front_port_position=1, + rear_port=rearport3, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport4, + front_port_position=1, + rear_port=rearport4, + rear_port_position=1, + ), + ]) cable2 = Cable( a_terminations=[rearport1], diff --git a/netbox/dcim/tests/test_cablepaths2.py b/netbox/dcim/tests/test_cablepaths2.py new file mode 100644 index 000000000..27ecf962f --- /dev/null +++ b/netbox/dcim/tests/test_cablepaths2.py @@ -0,0 +1,1541 @@ +from unittest import skip + +from circuits.models import CircuitTermination +from dcim.choices import CableProfileChoices +from dcim.models import * +from dcim.svg import CableTraceSVG +from dcim.tests.utils import CablePathTestCase + + +class CablePathTests(CablePathTestCase): + """ + Test the creation of CablePaths for Cables with different profiles applied. + + Tests are numbered as follows: + 1XX: Test direct connections using each profile + 2XX: Topology tests replicated from the legacy test case and adapted to use profiles + """ + + def test_101_cable_profile_single_1c1p(self): + """ + [IF1] --C1-- [IF2] + + Cable profile: Single connector, single position + """ + interfaces = [ + Interface.objects.create(device=self.device, name='Interface 1'), + Interface.objects.create(device=self.device, name='Interface 2'), + ] + + # Create cable 1 + cable1 = Cable( + profile=CableProfileChoices.SINGLE_1C1P, + a_terminations=[interfaces[0]], + b_terminations=[interfaces[1]], + ) + cable1.clean() + cable1.save() + + path1 = self.assertPathExists( + (interfaces[0], cable1, interfaces[1]), + is_complete=True, + is_active=True + ) + path2 = self.assertPathExists( + (interfaces[1], cable1, interfaces[0]), + is_complete=True, + is_active=True + ) + self.assertEqual(CablePath.objects.count(), 2) + interfaces[0].refresh_from_db() + interfaces[1].refresh_from_db() + self.assertPathIsSet(interfaces[0], path1) + self.assertPathIsSet(interfaces[1], path2) + self.assertEqual(interfaces[0].cable_connector, 1) + self.assertEqual(interfaces[0].cable_positions, [1]) + self.assertEqual(interfaces[1].cable_connector, 1) + self.assertEqual(interfaces[1].cable_positions, [1]) + + # Test SVG generation + CableTraceSVG(interfaces[0]).render() + + # Delete cable 1 + cable1.delete() + + # Check that all CablePaths have been deleted + self.assertEqual(CablePath.objects.count(), 0) + + def test_102_cable_profile_single_1c2p(self): + """ + [IF1] --C1-- [FP1][RP1] --C3-- [RP2][FP3] --C4-- [IF3] + [IF2] --C2-- [FP2] [FP4] --C5-- [IF4] + + Cable profile: Single connector, multiple positions + """ + interfaces = [ + Interface.objects.create(device=self.device, name='Interface 1'), + Interface.objects.create(device=self.device, name='Interface 2'), + Interface.objects.create(device=self.device, name='Interface 3'), + Interface.objects.create(device=self.device, name='Interface 4'), + ] + rear_ports = [ + RearPort.objects.create(device=self.device, name='Rear Port 1', positions=2), + RearPort.objects.create(device=self.device, name='Rear Port 2', positions=2), + ] + front_ports = [ + FrontPort.objects.create(device=self.device, name='Front Port 1'), + FrontPort.objects.create(device=self.device, name='Front Port 2'), + FrontPort.objects.create(device=self.device, name='Front Port 3'), + FrontPort.objects.create(device=self.device, name='Front Port 4'), + ] + PortMapping.objects.bulk_create([ + PortMapping( + device=self.device, + front_port=front_ports[0], + front_port_position=1, + rear_port=rear_ports[0], + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=front_ports[1], + front_port_position=1, + rear_port=rear_ports[0], + rear_port_position=2, + ), + PortMapping( + device=self.device, + front_port=front_ports[2], + front_port_position=1, + rear_port=rear_ports[1], + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=front_ports[3], + front_port_position=1, + rear_port=rear_ports[1], + rear_port_position=2, + ), + ]) + + # Create cables + cable1 = Cable( + a_terminations=[interfaces[0]], + b_terminations=[front_ports[0]], + ) + cable1.clean() + cable1.save() + cable2 = Cable( + a_terminations=[interfaces[1]], + b_terminations=[front_ports[1]], + ) + cable2.clean() + cable2.save() + cable3 = Cable( + profile=CableProfileChoices.SINGLE_1C2P, + a_terminations=[rear_ports[0]], + b_terminations=[rear_ports[1]], + ) + cable3.clean() + cable3.save() + cable4 = Cable( + a_terminations=[interfaces[2]], + b_terminations=[front_ports[2]], + ) + cable4.clean() + cable4.save() + cable5 = Cable( + a_terminations=[interfaces[3]], + b_terminations=[front_ports[3]], + ) + cable5.clean() + cable5.save() + + path1 = self.assertPathExists( + ( + interfaces[0], cable1, front_ports[0], rear_ports[0], cable3, rear_ports[1], front_ports[2], cable4, + interfaces[2], + ), + is_complete=True, + is_active=True + ) + path2 = self.assertPathExists( + ( + interfaces[1], cable2, front_ports[1], rear_ports[0], cable3, rear_ports[1], front_ports[3], cable5, + interfaces[3], + ), + is_complete=True, + is_active=True + ) + path3 = self.assertPathExists( + ( + interfaces[2], cable4, front_ports[2], rear_ports[1], cable3, rear_ports[0], front_ports[0], cable1, + interfaces[0], + ), + is_complete=True, + is_active=True + ) + path4 = self.assertPathExists( + ( + interfaces[3], cable5, front_ports[3], rear_ports[1], cable3, rear_ports[0], front_ports[1], cable2, + interfaces[1], + ), + is_complete=True, + is_active=True + ) + self.assertEqual(CablePath.objects.count(), 4) + for iface in interfaces: + iface.refresh_from_db() + self.assertPathIsSet(interfaces[0], path1) + self.assertPathIsSet(interfaces[1], path2) + self.assertPathIsSet(interfaces[2], path3) + self.assertPathIsSet(interfaces[3], path4) + for rear_port in rear_ports: + rear_port.refresh_from_db() + self.assertEqual(rear_ports[0].cable_connector, 1) + self.assertEqual(rear_ports[0].cable_positions, [1, 2]) + self.assertEqual(rear_ports[1].cable_connector, 1) + self.assertEqual(rear_ports[1].cable_positions, [1, 2]) + + # Test SVG generation + CableTraceSVG(interfaces[0]).render() + + def test_103_cable_profile_trunk_2c1p(self): + """ + [IF1] --C1-- [IF3] + [IF2] [IF4] + + Cable profile: Multiple connectors, single position + """ + interfaces = [ + Interface.objects.create(device=self.device, name='Interface 1'), + Interface.objects.create(device=self.device, name='Interface 2'), + Interface.objects.create(device=self.device, name='Interface 3'), + Interface.objects.create(device=self.device, name='Interface 4'), + ] + + # Create cable 1 + cable1 = Cable( + profile=CableProfileChoices.TRUNK_2C1P, + a_terminations=[interfaces[0], interfaces[1]], + b_terminations=[interfaces[2], interfaces[3]], + ) + cable1.clean() + cable1.save() + + path1 = self.assertPathExists( + (interfaces[0], cable1, interfaces[2]), + is_complete=True, + is_active=True + ) + path2 = self.assertPathExists( + (interfaces[1], cable1, interfaces[3]), + is_complete=True, + is_active=True + ) + path3 = self.assertPathExists( + (interfaces[2], cable1, interfaces[0]), + is_complete=True, + is_active=True + ) + path4 = self.assertPathExists( + (interfaces[3], cable1, interfaces[1]), + is_complete=True, + is_active=True + ) + self.assertEqual(CablePath.objects.count(), 4) + + for interface in interfaces: + interface.refresh_from_db() + self.assertPathIsSet(interfaces[0], path1) + self.assertPathIsSet(interfaces[1], path2) + self.assertPathIsSet(interfaces[2], path3) + self.assertPathIsSet(interfaces[3], path4) + self.assertEqual(interfaces[0].cable_connector, 1) + self.assertEqual(interfaces[0].cable_positions, [1]) + self.assertEqual(interfaces[1].cable_connector, 2) + self.assertEqual(interfaces[1].cable_positions, [1]) + self.assertEqual(interfaces[2].cable_connector, 1) + self.assertEqual(interfaces[2].cable_positions, [1]) + self.assertEqual(interfaces[3].cable_connector, 2) + self.assertEqual(interfaces[3].cable_positions, [1]) + + # Test SVG generation + CableTraceSVG(interfaces[0]).render() + + # Delete cable 1 + cable1.delete() + + # Check that all CablePaths have been deleted + self.assertEqual(CablePath.objects.count(), 0) + + def test_104_cable_profile_trunk_2c2p(self): + """ + [IF1] --C1-- [FP1][RP1] --C9-- [RP3][FP5] --C5-- [IF5] + [IF2] --C2-- [FP2] [FP6] --C6-- [IF6] + [IF3] --C3-- [FP3][RP2] [RP4][FP7] --C7-- [IF7] + [IF4] --C4-- [FP4] [FP8] --C8-- [IF8] + + Cable profile: Multiple connectors, multiple positions + """ + interfaces = [ + Interface.objects.create(device=self.device, name='Interface 1'), + Interface.objects.create(device=self.device, name='Interface 2'), + Interface.objects.create(device=self.device, name='Interface 3'), + Interface.objects.create(device=self.device, name='Interface 4'), + Interface.objects.create(device=self.device, name='Interface 5'), + Interface.objects.create(device=self.device, name='Interface 6'), + Interface.objects.create(device=self.device, name='Interface 7'), + Interface.objects.create(device=self.device, name='Interface 8'), + ] + rear_ports = [ + RearPort.objects.create(device=self.device, name='Rear Port 1', positions=2), + RearPort.objects.create(device=self.device, name='Rear Port 2', positions=2), + RearPort.objects.create(device=self.device, name='Rear Port 3', positions=2), + RearPort.objects.create(device=self.device, name='Rear Port 4', positions=2), + ] + front_ports = [ + FrontPort.objects.create(device=self.device, name='Front Port 1'), + FrontPort.objects.create(device=self.device, name='Front Port 2'), + FrontPort.objects.create(device=self.device, name='Front Port 3'), + FrontPort.objects.create(device=self.device, name='Front Port 4'), + FrontPort.objects.create(device=self.device, name='Front Port 5'), + FrontPort.objects.create(device=self.device, name='Front Port 6'), + FrontPort.objects.create(device=self.device, name='Front Port 7'), + FrontPort.objects.create(device=self.device, name='Front Port 8'), + ] + PortMapping.objects.bulk_create([ + PortMapping( + device=self.device, + front_port=front_ports[0], + front_port_position=1, + rear_port=rear_ports[0], + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=front_ports[1], + front_port_position=1, + rear_port=rear_ports[0], + rear_port_position=2, + ), + PortMapping( + device=self.device, + front_port=front_ports[2], + front_port_position=1, + rear_port=rear_ports[1], + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=front_ports[3], + front_port_position=1, + rear_port=rear_ports[1], + rear_port_position=2, + ), + PortMapping( + device=self.device, + front_port=front_ports[4], + front_port_position=1, + rear_port=rear_ports[2], + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=front_ports[5], + front_port_position=1, + rear_port=rear_ports[2], + rear_port_position=2, + ), + PortMapping( + device=self.device, + front_port=front_ports[6], + front_port_position=1, + rear_port=rear_ports[3], + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=front_ports[7], + front_port_position=1, + rear_port=rear_ports[3], + rear_port_position=2, + ), + ]) + + # Create cables + cable1 = Cable(a_terminations=[interfaces[0]], b_terminations=[front_ports[0]]) + cable1.clean() + cable1.save() + cable2 = Cable(a_terminations=[interfaces[1]], b_terminations=[front_ports[1]]) + cable2.clean() + cable2.save() + cable3 = Cable(a_terminations=[interfaces[2]], b_terminations=[front_ports[2]]) + cable3.clean() + cable3.save() + cable4 = Cable(a_terminations=[interfaces[3]], b_terminations=[front_ports[3]]) + cable4.clean() + cable4.save() + cable5 = Cable(a_terminations=[interfaces[4]], b_terminations=[front_ports[4]]) + cable5.clean() + cable5.save() + cable6 = Cable(a_terminations=[interfaces[5]], b_terminations=[front_ports[5]]) + cable6.clean() + cable6.save() + cable7 = Cable(a_terminations=[interfaces[6]], b_terminations=[front_ports[6]]) + cable7.clean() + cable7.save() + cable8 = Cable(a_terminations=[interfaces[7]], b_terminations=[front_ports[7]]) + cable8.clean() + cable8.save() + cable9 = Cable( + profile=CableProfileChoices.TRUNK_2C2P, + a_terminations=[rear_ports[0], rear_ports[1]], + b_terminations=[rear_ports[2], rear_ports[3]] + ) + cable9.clean() + cable9.save() + + path1 = self.assertPathExists( + ( + interfaces[0], cable1, front_ports[0], rear_ports[0], cable9, rear_ports[2], front_ports[4], cable5, + interfaces[4], + ), + is_complete=True, + is_active=True + ) + path2 = self.assertPathExists( + ( + interfaces[1], cable2, front_ports[1], rear_ports[0], cable9, rear_ports[2], front_ports[5], cable6, + interfaces[5], + ), + is_complete=True, + is_active=True + ) + path3 = self.assertPathExists( + ( + interfaces[2], cable3, front_ports[2], rear_ports[1], cable9, rear_ports[3], front_ports[6], cable7, + interfaces[6], + ), + is_complete=True, + is_active=True + ) + path4 = self.assertPathExists( + ( + interfaces[3], cable4, front_ports[3], rear_ports[1], cable9, rear_ports[3], front_ports[7], cable8, + interfaces[7], + ), + is_complete=True, + is_active=True + ) + path5 = self.assertPathExists( + ( + interfaces[4], cable5, front_ports[4], rear_ports[2], cable9, rear_ports[0], front_ports[0], cable1, + interfaces[0], + ), + is_complete=True, + is_active=True + ) + path6 = self.assertPathExists( + ( + interfaces[5], cable6, front_ports[5], rear_ports[2], cable9, rear_ports[0], front_ports[1], cable2, + interfaces[1], + ), + is_complete=True, + is_active=True + ) + path7 = self.assertPathExists( + ( + interfaces[6], cable7, front_ports[6], rear_ports[3], cable9, rear_ports[1], front_ports[2], cable3, + interfaces[2], + ), + is_complete=True, + is_active=True + ) + path8 = self.assertPathExists( + ( + interfaces[7], cable8, front_ports[7], rear_ports[3], cable9, rear_ports[1], front_ports[3], cable4, + interfaces[3], + ), + is_complete=True, + is_active=True + ) + self.assertEqual(CablePath.objects.count(), 8) + for iface in interfaces: + iface.refresh_from_db() + self.assertPathIsSet(interfaces[0], path1) + self.assertPathIsSet(interfaces[1], path2) + self.assertPathIsSet(interfaces[2], path3) + self.assertPathIsSet(interfaces[3], path4) + self.assertPathIsSet(interfaces[4], path5) + self.assertPathIsSet(interfaces[5], path6) + self.assertPathIsSet(interfaces[6], path7) + self.assertPathIsSet(interfaces[7], path8) + for rear_port in rear_ports: + rear_port.refresh_from_db() + self.assertEqual(rear_ports[0].cable_connector, 1) + self.assertEqual(rear_ports[0].cable_positions, [1, 2]) + self.assertEqual(rear_ports[1].cable_connector, 2) + self.assertEqual(rear_ports[1].cable_positions, [1, 2]) + self.assertEqual(rear_ports[2].cable_connector, 1) + self.assertEqual(rear_ports[2].cable_positions, [1, 2]) + self.assertEqual(rear_ports[3].cable_connector, 2) + self.assertEqual(rear_ports[3].cable_positions, [1, 2]) + + # Test SVG generation + CableTraceSVG(interfaces[0]).render() + + def test_105_cable_profile_breakout(self): + """ + [IF1] --C1-- [FP1][RP1] --C2-- [IF5] + [IF2] --C3-- [FP2] [IF6] + [IF3] --C4-- [FP3] [IF7] + [IF4] --C5-- [FP4] [IF8] + + Cable profile: 1:4 breakout + """ + interfaces = [ + Interface.objects.create(device=self.device, name='Interface 1'), + Interface.objects.create(device=self.device, name='Interface 2'), + Interface.objects.create(device=self.device, name='Interface 3'), + Interface.objects.create(device=self.device, name='Interface 4'), + Interface.objects.create(device=self.device, name='Interface 5'), + Interface.objects.create(device=self.device, name='Interface 6'), + Interface.objects.create(device=self.device, name='Interface 7'), + Interface.objects.create(device=self.device, name='Interface 8'), + ] + rear_ports = [ + RearPort.objects.create(device=self.device, name='Rear Port 1', positions=4), + ] + front_ports = [ + FrontPort.objects.create(device=self.device, name='Front Port 1'), + FrontPort.objects.create(device=self.device, name='Front Port 2'), + FrontPort.objects.create(device=self.device, name='Front Port 3'), + FrontPort.objects.create(device=self.device, name='Front Port 4'), + ] + PortMapping.objects.bulk_create([ + PortMapping( + device=self.device, + front_port=front_ports[0], + front_port_position=1, + rear_port=rear_ports[0], + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=front_ports[1], + front_port_position=1, + rear_port=rear_ports[0], + rear_port_position=2, + ), + PortMapping( + device=self.device, + front_port=front_ports[2], + front_port_position=1, + rear_port=rear_ports[0], + rear_port_position=3, + ), + PortMapping( + device=self.device, + front_port=front_ports[3], + front_port_position=1, + rear_port=rear_ports[0], + rear_port_position=4, + ), + ]) + + # Create cables + cable1 = Cable(a_terminations=[interfaces[0]], b_terminations=[front_ports[0]]) + cable1.clean() + cable1.save() + cable2 = Cable(a_terminations=[interfaces[1]], b_terminations=[front_ports[1]]) + cable2.clean() + cable2.save() + cable3 = Cable(a_terminations=[interfaces[2]], b_terminations=[front_ports[2]]) + cable3.clean() + cable3.save() + cable4 = Cable(a_terminations=[interfaces[3]], b_terminations=[front_ports[3]]) + cable4.clean() + cable4.save() + cable5 = Cable( + profile=CableProfileChoices.BREAKOUT_1C4P_4C1P, + a_terminations=[rear_ports[0]], + b_terminations=interfaces[4:8], + ) + cable5.clean() + cable5.save() + + path1 = self.assertPathExists( + (interfaces[0], cable1, front_ports[0], rear_ports[0], cable5, interfaces[4]), + is_complete=True, + is_active=True + ) + path2 = self.assertPathExists( + (interfaces[1], cable2, front_ports[1], rear_ports[0], cable5, interfaces[5]), + is_complete=True, + is_active=True + ) + path3 = self.assertPathExists( + (interfaces[2], cable3, front_ports[2], rear_ports[0], cable5, interfaces[6]), + is_complete=True, + is_active=True + ) + path4 = self.assertPathExists( + (interfaces[3], cable4, front_ports[3], rear_ports[0], cable5, interfaces[7]), + is_complete=True, + is_active=True + ) + path5 = self.assertPathExists( + (interfaces[4], cable5, rear_ports[0], front_ports[0], cable1, interfaces[0]), + is_complete=True, + is_active=True + ) + path6 = self.assertPathExists( + (interfaces[5], cable5, rear_ports[0], front_ports[1], cable2, interfaces[1]), + is_complete=True, + is_active=True + ) + path7 = self.assertPathExists( + (interfaces[6], cable5, rear_ports[0], front_ports[2], cable3, interfaces[2]), + is_complete=True, + is_active=True + ) + path8 = self.assertPathExists( + (interfaces[7], cable5, rear_ports[0], front_ports[3], cable4, interfaces[3]), + is_complete=True, + is_active=True + ) + self.assertEqual(CablePath.objects.count(), 8) + for interface in interfaces: + interface.refresh_from_db() + self.assertPathIsSet(interfaces[0], path1) + self.assertPathIsSet(interfaces[1], path2) + self.assertPathIsSet(interfaces[2], path3) + self.assertPathIsSet(interfaces[3], path4) + self.assertPathIsSet(interfaces[4], path5) + self.assertPathIsSet(interfaces[5], path6) + self.assertPathIsSet(interfaces[6], path7) + self.assertPathIsSet(interfaces[7], path8) + self.assertEqual(interfaces[4].cable_connector, 1) + self.assertEqual(interfaces[4].cable_positions, [1]) + self.assertEqual(interfaces[5].cable_connector, 2) + self.assertEqual(interfaces[5].cable_positions, [1]) + self.assertEqual(interfaces[6].cable_connector, 3) + self.assertEqual(interfaces[6].cable_positions, [1]) + self.assertEqual(interfaces[7].cable_connector, 4) + self.assertEqual(interfaces[7].cable_positions, [1]) + rear_ports[0].refresh_from_db() + self.assertEqual(rear_ports[0].cable_connector, 1) + self.assertEqual(rear_ports[0].cable_positions, [1, 2, 3, 4]) + + # Test SVG generation + CableTraceSVG(interfaces[0]).render() + + def test_106_cable_profile_shuffle(self): + """ + [IF1] --C1-- [FP1][RP1] --C17-- [RP3][FP9] --C9-- [IF9] + [IF2] --C2-- [FP2] [FP10] --C10-- [IF10] + [IF3] --C3-- [FP3] [FP11] --C11-- [IF11] + [IF4] --C4-- [FP4] [FP12] --C12-- [IF12] + [IF5] --C5-- [FP5][RP2] [RP4][FP13] --C13-- [IF9] + [IF6] --C6-- [FP6] [FP14] --C14-- [IF10] + [IF7] --C7-- [FP7] [FP15] --C15-- [IF11] + [IF8] --C8-- [FP8] [FP16] --C16-- [IF12] + + Cable profile: Shuffle (2x2 MPO8) + """ + interfaces = [ + # A side + Interface.objects.create(device=self.device, name='Interface 1:1'), + Interface.objects.create(device=self.device, name='Interface 1:2'), + Interface.objects.create(device=self.device, name='Interface 1:3'), + Interface.objects.create(device=self.device, name='Interface 1:4'), + Interface.objects.create(device=self.device, name='Interface 2:1'), + Interface.objects.create(device=self.device, name='Interface 2:2'), + Interface.objects.create(device=self.device, name='Interface 2:3'), + Interface.objects.create(device=self.device, name='Interface 2:4'), + # B side + Interface.objects.create(device=self.device, name='Interface 3:1'), + Interface.objects.create(device=self.device, name='Interface 3:2'), + Interface.objects.create(device=self.device, name='Interface 3:3'), + Interface.objects.create(device=self.device, name='Interface 3:4'), + Interface.objects.create(device=self.device, name='Interface 4:1'), + Interface.objects.create(device=self.device, name='Interface 4:2'), + Interface.objects.create(device=self.device, name='Interface 4:3'), + Interface.objects.create(device=self.device, name='Interface 4:4'), + ] + rear_ports = [ + RearPort.objects.create(device=self.device, name='Rear Port 1', positions=4), + RearPort.objects.create(device=self.device, name='Rear Port 2', positions=4), + RearPort.objects.create(device=self.device, name='Rear Port 3', positions=4), + RearPort.objects.create(device=self.device, name='Rear Port 4', positions=4), + ] + front_ports = [ + FrontPort.objects.create(device=self.device, name='Front Port 1'), + FrontPort.objects.create(device=self.device, name='Front Port 2'), + FrontPort.objects.create(device=self.device, name='Front Port 3'), + FrontPort.objects.create(device=self.device, name='Front Port 4'), + FrontPort.objects.create(device=self.device, name='Front Port 5'), + FrontPort.objects.create(device=self.device, name='Front Port 6'), + FrontPort.objects.create(device=self.device, name='Front Port 7'), + FrontPort.objects.create(device=self.device, name='Front Port 8'), + FrontPort.objects.create(device=self.device, name='Front Port 9'), + FrontPort.objects.create(device=self.device, name='Front Port 10'), + FrontPort.objects.create(device=self.device, name='Front Port 11'), + FrontPort.objects.create(device=self.device, name='Front Port 12'), + FrontPort.objects.create(device=self.device, name='Front Port 13'), + FrontPort.objects.create(device=self.device, name='Front Port 14'), + FrontPort.objects.create(device=self.device, name='Front Port 15'), + FrontPort.objects.create(device=self.device, name='Front Port 16'), + ] + port_mappings = [] + for i, front_port in enumerate(front_ports): + port_mappings.append( + PortMapping( + device=self.device, + front_port=front_ports[i], + front_port_position=1, + rear_port=rear_ports[int(i / 4)], + rear_port_position=(i % 4) + 1, + ), + ) + PortMapping.objects.bulk_create(port_mappings) + + # Create cables + cables = [] + for interface, front_port in zip(interfaces, front_ports): + cable = Cable(a_terminations=[interface], b_terminations=[front_port]) + cable.clean() + cable.save() + cables.append(cable) + shuffle_cable = Cable( + profile=CableProfileChoices.TRUNK_2C4P_SHUFFLE, + a_terminations=rear_ports[0:2], + b_terminations=rear_ports[2:4], + ) + shuffle_cable.clean() + shuffle_cable.save() + + paths = [ + # A-to-B paths + self.assertPathExists( + ( + interfaces[0], cables[0], front_ports[0], rear_ports[0], shuffle_cable, rear_ports[2], + front_ports[8], cables[8], interfaces[8], + ), + is_complete=True, + is_active=True + ), + self.assertPathExists( + ( + interfaces[1], cables[1], front_ports[1], rear_ports[0], shuffle_cable, rear_ports[2], + front_ports[9], cables[9], interfaces[9], + ), + is_complete=True, + is_active=True + ), + self.assertPathExists( + ( + interfaces[2], cables[2], front_ports[2], rear_ports[0], shuffle_cable, rear_ports[3], + front_ports[12], cables[12], interfaces[12], + ), + is_complete=True, + is_active=True + ), + self.assertPathExists( + ( + interfaces[3], cables[3], front_ports[3], rear_ports[0], shuffle_cable, rear_ports[3], + front_ports[13], cables[13], interfaces[13], + ), + is_complete=True, + is_active=True + ), + self.assertPathExists( + ( + interfaces[4], cables[4], front_ports[4], rear_ports[1], shuffle_cable, rear_ports[2], + front_ports[10], cables[10], interfaces[10], + ), + is_complete=True, + is_active=True + ), + self.assertPathExists( + ( + interfaces[5], cables[5], front_ports[5], rear_ports[1], shuffle_cable, rear_ports[2], + front_ports[11], cables[11], interfaces[11], + ), + is_complete=True, + is_active=True + ), + self.assertPathExists( + ( + interfaces[6], cables[6], front_ports[6], rear_ports[1], shuffle_cable, rear_ports[3], + front_ports[14], cables[14], interfaces[14], + ), + is_complete=True, + is_active=True + ), + self.assertPathExists( + ( + interfaces[7], cables[7], front_ports[7], rear_ports[1], shuffle_cable, rear_ports[3], + front_ports[15], cables[15], interfaces[15], + ), + is_complete=True, + is_active=True + ), + ] + self.assertEqual(CablePath.objects.count(), len(paths) * 2) + + for i, (interface, path) in enumerate(zip(interfaces, paths)): + interface.refresh_from_db() + self.assertPathIsSet(interface, path) + for i, rear_port in enumerate(rear_ports): + rear_port.refresh_from_db() + self.assertEqual(rear_port.cable_connector, (i % 2) + 1) + self.assertEqual(rear_port.cable_positions, [1, 2, 3, 4]) + + # Test SVG generation + CableTraceSVG(interfaces[0]).render() + + def test_202_single_path_via_pass_through_with_breakouts(self): + """ + [IF1] --C1-- [FP1] [RP1] --C2-- [IF3] + [IF2] [IF4] + """ + interfaces = [ + Interface.objects.create(device=self.device, name='Interface 1'), + Interface.objects.create(device=self.device, name='Interface 2'), + Interface.objects.create(device=self.device, name='Interface 3'), + Interface.objects.create(device=self.device, name='Interface 4'), + ] + rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1', positions=4) + frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1', positions=4) + PortMapping.objects.bulk_create([ + PortMapping( + device=self.device, + front_port=frontport1, + front_port_position=1, + rear_port=rearport1, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport1, + front_port_position=2, + rear_port=rearport1, + rear_port_position=2, + ), + PortMapping( + device=self.device, + front_port=frontport1, + front_port_position=3, + rear_port=rearport1, + rear_port_position=3, + ), + PortMapping( + device=self.device, + front_port=frontport1, + front_port_position=4, + rear_port=rearport1, + rear_port_position=4, + ), + ]) + + # Create cables + cable1 = Cable( + profile=CableProfileChoices.BREAKOUT_1C4P_4C1P, + a_terminations=[frontport1], + b_terminations=[interfaces[0], interfaces[1]], + ) + cable1.clean() + cable1.save() + cable2 = Cable( + profile=CableProfileChoices.BREAKOUT_1C4P_4C1P, + a_terminations=[rearport1], + b_terminations=[interfaces[2], interfaces[3]] + ) + cable2.clean() + cable2.save() + + paths = [ + self.assertPathExists( + (interfaces[0], cable1, frontport1, rearport1, cable2, interfaces[2]), + is_complete=True, + is_active=True + ), + self.assertPathExists( + (interfaces[1], cable1, frontport1, rearport1, cable2, interfaces[3]), + is_complete=True, + is_active=True + ), + self.assertPathExists( + (interfaces[2], cable2, rearport1, frontport1, cable1, interfaces[0]), + is_complete=True, + is_active=True + ), + self.assertPathExists( + (interfaces[3], cable2, rearport1, frontport1, cable1, interfaces[1]), + is_complete=True, + is_active=True + ), + ] + self.assertEqual(CablePath.objects.count(), 4) + for interface in interfaces: + interface.refresh_from_db() + self.assertPathIsSet(interfaces[0], paths[0]) + self.assertPathIsSet(interfaces[1], paths[1]) + self.assertPathIsSet(interfaces[2], paths[2]) + self.assertPathIsSet(interfaces[3], paths[3]) + + # Test SVG generation + CableTraceSVG(interfaces[0]).render() + + def test_204_multiple_paths_via_pass_through_with_breakouts(self): + """ + [IF1] --C1-- [FP1] [RP1] --C3-- [RP2] [FP3] --C4-- [IF5] + [IF2] [IF6] + [IF3] --C2-- [FP2] [FP4] --C5-- [IF7] + [IF4] [IF8] + """ + interfaces = [ + Interface.objects.create(device=self.device, name='Interface 1'), + Interface.objects.create(device=self.device, name='Interface 2'), + Interface.objects.create(device=self.device, name='Interface 3'), + Interface.objects.create(device=self.device, name='Interface 4'), + Interface.objects.create(device=self.device, name='Interface 5'), + Interface.objects.create(device=self.device, name='Interface 6'), + Interface.objects.create(device=self.device, name='Interface 7'), + Interface.objects.create(device=self.device, name='Interface 8'), + ] + rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1', positions=8) + rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2', positions=8) + frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1:1', positions=4) + frontport2 = FrontPort.objects.create(device=self.device, name='Front Port 1:2', positions=4) + frontport3 = FrontPort.objects.create(device=self.device, name='Front Port 2:1', positions=4) + frontport4 = FrontPort.objects.create(device=self.device, name='Front Port 2:2', positions=4) + PortMapping.objects.bulk_create([ + PortMapping( + device=self.device, + front_port=frontport1, + front_port_position=1, + rear_port=rearport1, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport1, + front_port_position=2, + rear_port=rearport1, + rear_port_position=2, + ), + PortMapping( + device=self.device, + front_port=frontport2, + front_port_position=1, + rear_port=rearport1, + rear_port_position=5, + ), + PortMapping( + device=self.device, + front_port=frontport2, + front_port_position=2, + rear_port=rearport1, + rear_port_position=6, + ), + PortMapping( + device=self.device, + front_port=frontport3, + front_port_position=1, + rear_port=rearport2, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport3, + front_port_position=2, + rear_port=rearport2, + rear_port_position=2, + ), + PortMapping( + device=self.device, + front_port=frontport4, + front_port_position=1, + rear_port=rearport2, + rear_port_position=5, + ), + PortMapping( + device=self.device, + front_port=frontport4, + front_port_position=2, + rear_port=rearport2, + rear_port_position=6, + ), + ]) + + # Create cables + cable1 = Cable( + profile=CableProfileChoices.BREAKOUT_1C4P_4C1P, + a_terminations=[frontport1], + b_terminations=[interfaces[0], interfaces[1]], + ) + cable1.clean() + cable1.save() + cable2 = Cable( + profile=CableProfileChoices.BREAKOUT_1C4P_4C1P, + a_terminations=[frontport2], + b_terminations=[interfaces[2], interfaces[3]], + ) + cable2.clean() + cable2.save() + cable3 = Cable( + profile=CableProfileChoices.SINGLE_1C8P, + a_terminations=[rearport1], + b_terminations=[rearport2] + ) + cable3.clean() + cable3.save() + cable4 = Cable( + profile=CableProfileChoices.BREAKOUT_1C4P_4C1P, + a_terminations=[frontport3], + b_terminations=[interfaces[4], interfaces[5]], + ) + cable4.clean() + cable4.save() + cable5 = Cable( + profile=CableProfileChoices.BREAKOUT_1C4P_4C1P, + a_terminations=[frontport4], + b_terminations=[interfaces[6], interfaces[7]], + ) + cable5.clean() + cable5.save() + + paths = [ + self.assertPathExists( + ( + interfaces[0], cable1, frontport1, rearport1, cable3, rearport2, frontport3, cable4, + interfaces[4], + ), + is_complete=True, + is_active=True, + ), + self.assertPathExists( + ( + interfaces[1], cable1, frontport1, rearport1, cable3, rearport2, frontport3, cable4, + interfaces[5], + ), + is_complete=True, + is_active=True, + ), + self.assertPathExists( + ( + interfaces[2], cable2, frontport2, rearport1, cable3, rearport2, frontport4, cable5, + interfaces[6], + ), + is_complete=True, + is_active=True, + ), + self.assertPathExists( + ( + interfaces[3], cable2, frontport2, rearport1, cable3, rearport2, frontport4, cable5, + interfaces[7], + ), + is_complete=True, + is_active=True, + ), + self.assertPathExists( + ( + interfaces[4], cable4, frontport3, rearport2, cable3, rearport1, frontport1, cable1, + interfaces[0], + ), + is_complete=True, + is_active=True, + ), + self.assertPathExists( + ( + interfaces[5], cable4, frontport3, rearport2, cable3, rearport1, frontport1, cable1, + interfaces[1], + ), + is_complete=True, + is_active=True, + ), + self.assertPathExists( + ( + interfaces[6], cable5, frontport4, rearport2, cable3, rearport1, frontport2, cable2, + interfaces[2], + ), + is_complete=True, + is_active=True, + ), + self.assertPathExists( + ( + interfaces[7], cable5, frontport4, rearport2, cable3, rearport1, frontport2, cable2, + interfaces[3], + ), + is_complete=True, + is_active=True, + ), + ] + self.assertEqual(CablePath.objects.count(), 8) + + for interface in interfaces: + interface.refresh_from_db() + self.assertPathIsSet(interfaces[0], paths[0]) + self.assertPathIsSet(interfaces[1], paths[1]) + self.assertPathIsSet(interfaces[2], paths[2]) + self.assertPathIsSet(interfaces[3], paths[3]) + self.assertPathIsSet(interfaces[4], paths[4]) + self.assertPathIsSet(interfaces[5], paths[5]) + self.assertPathIsSet(interfaces[6], paths[6]) + self.assertPathIsSet(interfaces[7], paths[7]) + + # Test SVG generation + CableTraceSVG(interfaces[0]).render() + + def test_212_interface_to_interface_via_circuit_with_breakouts(self): + """ + [IF1] --C1-- [CT1] [CT2] --C2-- [IF3] + [IF2] [IF4] + """ + interfaces = [ + Interface.objects.create(device=self.device, name='Interface 1'), + Interface.objects.create(device=self.device, name='Interface 2'), + Interface.objects.create(device=self.device, name='Interface 3'), + Interface.objects.create(device=self.device, name='Interface 4'), + ] + circuittermination1 = CircuitTermination.objects.create( + circuit=self.circuit, + termination=self.site, + term_side='A' + ) + circuittermination2 = CircuitTermination.objects.create( + circuit=self.circuit, + termination=self.site, + term_side='Z' + ) + + # Create cables + cable1 = Cable( + profile=CableProfileChoices.BREAKOUT_1C4P_4C1P, + a_terminations=[circuittermination1], + b_terminations=[interfaces[0], interfaces[1]], + ) + cable1.clean() + cable1.save() + cable2 = Cable( + profile=CableProfileChoices.BREAKOUT_1C4P_4C1P, + a_terminations=[circuittermination2], + b_terminations=[interfaces[2], interfaces[3]] + ) + cable2.clean() + cable2.save() + + # Check for two complete paths in either direction + paths = [ + self.assertPathExists( + (interfaces[0], cable1, circuittermination1, circuittermination2, cable2, interfaces[2]), + is_complete=True, + is_active=True, + ), + self.assertPathExists( + (interfaces[1], cable1, circuittermination1, circuittermination2, cable2, interfaces[3]), + is_complete=True, + is_active=True, + ), + self.assertPathExists( + (interfaces[2], cable2, circuittermination2, circuittermination1, cable1, interfaces[0]), + is_complete=True, + is_active=True, + ), + self.assertPathExists( + (interfaces[3], cable2, circuittermination2, circuittermination1, cable1, interfaces[1]), + is_complete=True, + is_active=True, + ), + ] + self.assertEqual(CablePath.objects.count(), 4) + + for interface in interfaces: + interface.refresh_from_db() + self.assertPathIsSet(interfaces[0], paths[0]) + self.assertPathIsSet(interfaces[1], paths[1]) + self.assertPathIsSet(interfaces[2], paths[2]) + self.assertPathIsSet(interfaces[3], paths[3]) + + # Test SVG generation + CableTraceSVG(interfaces[0]).render() + + # TBD: Is this a topology we want to support? + @skip("Test applicability TBD") + def test_217_interface_to_interface_via_rear_ports(self): + """ + [IF1] --C1-- [FP1] [RP1] --C2-- [RP3] [FP3] --C3-- [IF2] + [FP2] [RP2] [RP4] [FP4] + """ + interfaces = [ + Interface.objects.create(device=self.device, name='Interface 1'), + Interface.objects.create(device=self.device, name='Interface 2'), + ] + rear_ports = [ + RearPort.objects.create(device=self.device, name='Rear Port 1'), + RearPort.objects.create(device=self.device, name='Rear Port 2'), + RearPort.objects.create(device=self.device, name='Rear Port 3'), + RearPort.objects.create(device=self.device, name='Rear Port 4'), + ] + front_ports = [ + FrontPort.objects.create(device=self.device, name='Front Port 1'), + FrontPort.objects.create(device=self.device, name='Front Port 2'), + FrontPort.objects.create(device=self.device, name='Front Port 3'), + FrontPort.objects.create(device=self.device, name='Front Port 4'), + ] + PortMapping.objects.bulk_create([ + PortMapping( + device=self.device, + front_port=front_ports[0], + front_port_position=1, + rear_port=rear_ports[0], + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=front_ports[1], + front_port_position=1, + rear_port=rear_ports[1], + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=front_ports[2], + front_port_position=1, + rear_port=rear_ports[2], + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=front_ports[3], + front_port_position=1, + rear_port=rear_ports[3], + rear_port_position=1, + ), + ]) + + # Create cables + cable1 = Cable( + profile=CableProfileChoices.SINGLE_2C1P, + a_terminations=[interfaces[0]], + b_terminations=[front_ports[0], front_ports[1]] + ) + cable1.clean() + cable1.save() + cable2 = Cable( + a_terminations=[rear_ports[0], rear_ports[1]], + b_terminations=[rear_ports[2], rear_ports[3]] + ) + cable2.clean() + cable2.save() + cable3 = Cable( + profile=CableProfileChoices.SINGLE_2C1P, + a_terminations=[interfaces[1]], + b_terminations=[front_ports[2], front_ports[3]] + ) + cable3.clean() + cable3.save() + + # Check for one complete path in either direction + paths = [ + self.assertPathExists( + ( + interfaces[0], cable1, (front_ports[0], front_ports[1]), (rear_ports[0], rear_ports[1]), cable2, + (rear_ports[2], rear_ports[3]), (front_ports[2], front_ports[3]), cable3, interfaces[1] + ), + is_complete=True + ), + self.assertPathExists( + ( + interfaces[1], cable3, (front_ports[2], front_ports[3]), (rear_ports[2], rear_ports[3]), cable2, + (rear_ports[0], rear_ports[1]), (front_ports[0], front_ports[1]), cable1, interfaces[0] + ), + is_complete=True + ), + ] + self.assertEqual(CablePath.objects.count(), 2) + + for interface in interfaces: + interface.refresh_from_db() + self.assertPathIsSet(interfaces[0], paths[0]) + self.assertPathIsSet(interfaces[1], paths[1]) + + # Test SVG generation + CableTraceSVG(interfaces[0]).render() + + def test_223_single_path_via_multiple_pass_throughs_with_breakouts(self): + """ + [IF1] --C1-- [FP1] [RP1] --C2-- [IF3] + [IF2] [FP2] [RP2] [IF4] + """ + interfaces = [ + Interface.objects.create(device=self.device, name='Interface 1'), + Interface.objects.create(device=self.device, name='Interface 2'), + Interface.objects.create(device=self.device, name='Interface 3'), + Interface.objects.create(device=self.device, name='Interface 4'), + ] + rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1') + rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2') + frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1') + frontport2 = FrontPort.objects.create(device=self.device, name='Front Port 2') + PortMapping.objects.bulk_create([ + PortMapping( + device=self.device, + front_port=frontport1, + front_port_position=1, + rear_port=rearport1, + rear_port_position=1, + ), + PortMapping( + device=self.device, + front_port=frontport2, + front_port_position=1, + rear_port=rearport2, + rear_port_position=1, + ), + ]) + + # Create cables + cable1 = Cable( + profile=CableProfileChoices.TRUNK_2C2P, + a_terminations=[interfaces[0], interfaces[1]], + b_terminations=[frontport1, frontport2] + ) + cable1.clean() + cable1.save() + cable2 = Cable( + profile=CableProfileChoices.TRUNK_2C2P, + a_terminations=[rearport1, rearport2], + b_terminations=[interfaces[2], interfaces[3]] + ) + cable2.clean() + cable2.save() + + # Validate paths + self.assertPathExists( + (interfaces[0], cable1, frontport1, rearport1, cable2, interfaces[2]), + is_complete=True, + is_active=True + ) + self.assertPathExists( + (interfaces[1], cable1, frontport2, rearport2, cable2, interfaces[3]), + is_complete=True, + is_active=True + ) + self.assertPathExists( + (interfaces[2], cable2, rearport1, frontport1, cable1, interfaces[0]), + is_complete=True, + is_active=True + ) + self.assertPathExists( + (interfaces[3], cable2, rearport2, frontport2, cable1, interfaces[1]), + is_complete=True, + is_active=True + ) + self.assertEqual(CablePath.objects.count(), 4) + + def test_304_add_port_mapping_between_connected_ports(self): + """ + [IF1] --C1-- [FP1] [RP1] --C2-- [IF2] + """ + interface1 = Interface.objects.create(device=self.device, name='Interface 1') + interface2 = Interface.objects.create(device=self.device, name='Interface 2') + frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1') + rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1') + cable1 = Cable( + a_terminations=[interface1], + b_terminations=[frontport1] + ) + cable1.save() + cable2 = Cable( + a_terminations=[interface2], + b_terminations=[rearport1] + ) + cable2.save() + + # Check for incomplete paths + self.assertPathExists( + (interface1, cable1, frontport1), + is_complete=False, + is_active=True + ) + self.assertPathExists( + (interface2, cable2, rearport1), + is_complete=False, + is_active=True + ) + + # Create a PortMapping between frontport1 and rearport1 + PortMapping.objects.create( + device=self.device, + front_port=frontport1, + front_port_position=1, + rear_port=rearport1, + rear_port_position=1, + ) + + # Check that paths are now complete + self.assertPathExists( + (interface1, cable1, frontport1, rearport1, cable2, interface2), + is_complete=True, + is_active=True + ) + self.assertPathExists( + (interface2, cable2, rearport1, frontport1, cable1, interface1), + is_complete=True, + is_active=True + ) + + def test_305_delete_port_mapping_between_connected_ports(self): + """ + [IF1] --C1-- [FP1] [RP1] --C2-- [IF2] + """ + interface1 = Interface.objects.create(device=self.device, name='Interface 1') + interface2 = Interface.objects.create(device=self.device, name='Interface 2') + frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1') + rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1') + cable1 = Cable( + a_terminations=[interface1], + b_terminations=[frontport1] + ) + cable1.save() + cable2 = Cable( + a_terminations=[interface2], + b_terminations=[rearport1] + ) + cable2.save() + portmapping1 = PortMapping.objects.create( + device=self.device, + front_port=frontport1, + front_port_position=1, + rear_port=rearport1, + rear_port_position=1, + ) + + # Check for complete paths + self.assertPathExists( + (interface1, cable1, frontport1, rearport1, cable2, interface2), + is_complete=True, + is_active=True + ) + self.assertPathExists( + (interface2, cable2, rearport1, frontport1, cable1, interface1), + is_complete=True, + is_active=True + ) + + # Delete the PortMapping between frontport1 and rearport1 + portmapping1.delete() + + # Check that paths are no longer complete + self.assertPathExists( + (interface1, cable1, frontport1), + is_complete=False, + is_active=True + ) + self.assertPathExists( + (interface2, cable2, rearport1), + is_complete=False, + is_active=True + ) + + def test_306_change_port_mapping_between_connected_ports(self): + """ + [IF1] --C1-- [FP1] [RP1] --C3-- [IF3] + [IF2] --C2-- [FP2] [RP3] --C4-- [IF4] + """ + interface1 = Interface.objects.create(device=self.device, name='Interface 1') + interface2 = Interface.objects.create(device=self.device, name='Interface 2') + interface3 = Interface.objects.create(device=self.device, name='Interface 3') + interface4 = Interface.objects.create(device=self.device, name='Interface 4') + frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1') + frontport2 = FrontPort.objects.create(device=self.device, name='Front Port 2') + rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1') + rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2') + cable1 = Cable( + a_terminations=[interface1], + b_terminations=[frontport1] + ) + cable1.save() + cable2 = Cable( + a_terminations=[interface2], + b_terminations=[frontport2] + ) + cable2.save() + cable3 = Cable( + a_terminations=[interface3], + b_terminations=[rearport1] + ) + cable3.save() + cable4 = Cable( + a_terminations=[interface4], + b_terminations=[rearport2] + ) + cable4.save() + portmapping1 = PortMapping.objects.create( + device=self.device, + front_port=frontport1, + front_port_position=1, + rear_port=rearport1, + rear_port_position=1, + ) + + # Verify expected initial paths + self.assertPathExists( + (interface1, cable1, frontport1, rearport1, cable3, interface3), + is_complete=True, + is_active=True + ) + self.assertPathExists( + (interface3, cable3, rearport1, frontport1, cable1, interface1), + is_complete=True, + is_active=True + ) + + # Delete and replace the PortMapping to connect interface1 to interface4 + portmapping1.delete() + portmapping2 = PortMapping.objects.create( + device=self.device, + front_port=frontport1, + front_port_position=1, + rear_port=rearport2, + rear_port_position=1, + ) + + # Verify expected new paths + self.assertPathExists( + (interface1, cable1, frontport1, rearport2, cable4, interface4), + is_complete=True, + is_active=True + ) + self.assertPathExists( + (interface4, cable4, rearport2, frontport1, cable1, interface1), + is_complete=True, + is_active=True + ) + + # Delete and replace the PortMapping to connect interface2 to interface4 + portmapping2.delete() + PortMapping.objects.create( + device=self.device, + front_port=frontport2, + front_port_position=1, + rear_port=rearport2, + rear_port_position=1, + ) + + # Verify expected new paths + self.assertPathExists( + (interface2, cable2, frontport2, rearport2, cable4, interface4), + is_complete=True, + is_active=True + ) + self.assertPathExists( + (interface4, cable4, rearport2, frontport2, cable2, interface2), + is_complete=True, + is_active=True + ) diff --git a/netbox/dcim/tests/test_filtersets.py b/netbox/dcim/tests/test_filtersets.py index 33138066a..96a0f14fb 100644 --- a/netbox/dcim/tests/test_filtersets.py +++ b/netbox/dcim/tests/test_filtersets.py @@ -1362,22 +1362,15 @@ class DeviceTypeTestCase(TestCase, ChangeLoggedFilterSetTests): RearPortTemplate(device_type=device_types[1], name='Rear Port 2', type=PortTypeChoices.TYPE_8P8C), ) RearPortTemplate.objects.bulk_create(rear_ports) - FrontPortTemplate.objects.bulk_create( - ( - FrontPortTemplate( - device_type=device_types[0], - name='Front Port 1', - type=PortTypeChoices.TYPE_8P8C, - rear_port=rear_ports[0], - ), - FrontPortTemplate( - device_type=device_types[1], - name='Front Port 2', - type=PortTypeChoices.TYPE_8P8C, - rear_port=rear_ports[1], - ), - ) + front_ports = ( + FrontPortTemplate(device_type=device_types[0], name='Front Port 1', type=PortTypeChoices.TYPE_8P8C), + FrontPortTemplate(device_type=device_types[1], name='Front Port 2', type=PortTypeChoices.TYPE_8P8C), ) + FrontPortTemplate.objects.bulk_create(front_ports) + PortTemplateMapping.objects.bulk_create([ + PortTemplateMapping(device_type=device_types[0], front_port=front_ports[0], rear_port=rear_ports[0]), + PortTemplateMapping(device_type=device_types[1], front_port=front_ports[1], rear_port=rear_ports[1]), + ]) ModuleBayTemplate.objects.bulk_create(( ModuleBayTemplate(device_type=device_types[0], name='Module Bay 1'), ModuleBayTemplate(device_type=device_types[1], name='Module Bay 2'), @@ -1633,22 +1626,15 @@ class ModuleTypeTestCase(TestCase, ChangeLoggedFilterSetTests): RearPortTemplate(module_type=module_types[1], name='Rear Port 2', type=PortTypeChoices.TYPE_8P8C), ) RearPortTemplate.objects.bulk_create(rear_ports) - FrontPortTemplate.objects.bulk_create( - ( - FrontPortTemplate( - module_type=module_types[0], - name='Front Port 1', - type=PortTypeChoices.TYPE_8P8C, - rear_port=rear_ports[0], - ), - FrontPortTemplate( - module_type=module_types[1], - name='Front Port 2', - type=PortTypeChoices.TYPE_8P8C, - rear_port=rear_ports[1], - ), - ) + front_ports = ( + FrontPortTemplate(module_type=module_types[0], name='Front Port 1', type=PortTypeChoices.TYPE_8P8C), + FrontPortTemplate(module_type=module_types[1], name='Front Port 2', type=PortTypeChoices.TYPE_8P8C), ) + FrontPortTemplate.objects.bulk_create(front_ports) + PortTemplateMapping.objects.bulk_create([ + PortTemplateMapping(module_type=module_types[0], front_port=front_ports[0], rear_port=rear_ports[0]), + PortTemplateMapping(module_type=module_types[1], front_port=front_ports[1], rear_port=rear_ports[1]), + ]) def test_q(self): params = {'q': 'foobar1'} @@ -1926,18 +1912,21 @@ class PowerOutletTemplateTestCase(TestCase, DeviceComponentTemplateFilterSetTest device_type=device_types[0], name='Power Outlet 1', feed_leg=PowerOutletFeedLegChoices.FEED_LEG_A, + color=ColorChoices.COLOR_RED, description='foobar1' ), PowerOutletTemplate( device_type=device_types[1], name='Power Outlet 2', feed_leg=PowerOutletFeedLegChoices.FEED_LEG_B, + color=ColorChoices.COLOR_GREEN, description='foobar2' ), PowerOutletTemplate( device_type=device_types[2], name='Power Outlet 3', feed_leg=PowerOutletFeedLegChoices.FEED_LEG_C, + color=ColorChoices.COLOR_BLUE, description='foobar3' ), )) @@ -1950,6 +1939,10 @@ class PowerOutletTemplateTestCase(TestCase, DeviceComponentTemplateFilterSetTest params = {'feed_leg': [PowerOutletFeedLegChoices.FEED_LEG_A, PowerOutletFeedLegChoices.FEED_LEG_B]} self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2) + def test_color(self): + params = {'color': [ColorChoices.COLOR_RED, ColorChoices.COLOR_GREEN]} + self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2) + class InterfaceTemplateTestCase(TestCase, DeviceComponentTemplateFilterSetTests, ChangeLoggedFilterSetTests): queryset = InterfaceTemplate.objects.all() @@ -2057,32 +2050,38 @@ class FrontPortTemplateTestCase(TestCase, DeviceComponentTemplateFilterSetTests, ) RearPortTemplate.objects.bulk_create(rear_ports) - FrontPortTemplate.objects.bulk_create(( + front_ports = ( FrontPortTemplate( device_type=device_types[0], name='Front Port 1', - rear_port=rear_ports[0], type=PortTypeChoices.TYPE_8P8C, + positions=1, color=ColorChoices.COLOR_RED, description='foobar1' ), FrontPortTemplate( device_type=device_types[1], name='Front Port 2', - rear_port=rear_ports[1], type=PortTypeChoices.TYPE_110_PUNCH, + positions=2, color=ColorChoices.COLOR_GREEN, description='foobar2' ), FrontPortTemplate( device_type=device_types[2], name='Front Port 3', - rear_port=rear_ports[2], type=PortTypeChoices.TYPE_BNC, + positions=3, color=ColorChoices.COLOR_BLUE, description='foobar3' ), - )) + ) + FrontPortTemplate.objects.bulk_create(front_ports) + PortTemplateMapping.objects.bulk_create([ + PortTemplateMapping(device_type=device_types[0], front_port=front_ports[0], rear_port=rear_ports[0]), + PortTemplateMapping(device_type=device_types[1], front_port=front_ports[1], rear_port=rear_ports[1]), + PortTemplateMapping(device_type=device_types[2], front_port=front_ports[2], rear_port=rear_ports[2]), + ]) def test_name(self): params = {'name': ['Front Port 1', 'Front Port 2']} @@ -2096,6 +2095,10 @@ class FrontPortTemplateTestCase(TestCase, DeviceComponentTemplateFilterSetTests, params = {'color': [ColorChoices.COLOR_RED, ColorChoices.COLOR_GREEN]} self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2) + def test_positions(self): + params = {'positions': [1, 2]} + self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2) + class RearPortTemplateTestCase(TestCase, DeviceComponentTemplateFilterSetTests, ChangeLoggedFilterSetTests): queryset = RearPortTemplate.objects.all() @@ -2752,10 +2755,15 @@ class DeviceTestCase(TestCase, ChangeLoggedFilterSetTests): RearPort(device=devices[1], name='Rear Port 2', type=PortTypeChoices.TYPE_8P8C), ) RearPort.objects.bulk_create(rear_ports) - FrontPort.objects.bulk_create(( - FrontPort(device=devices[0], name='Front Port 1', type=PortTypeChoices.TYPE_8P8C, rear_port=rear_ports[0]), - FrontPort(device=devices[1], name='Front Port 2', type=PortTypeChoices.TYPE_8P8C, rear_port=rear_ports[1]), - )) + front_ports = ( + FrontPort(device=devices[0], name='Front Port 1', type=PortTypeChoices.TYPE_8P8C), + FrontPort(device=devices[1], name='Front Port 2', type=PortTypeChoices.TYPE_8P8C), + ) + FrontPort.objects.bulk_create(front_ports) + PortMapping.objects.bulk_create([ + PortMapping(device=devices[0], front_port=front_ports[0], rear_port=rear_ports[0]), + PortMapping(device=devices[1], front_port=front_ports[1], rear_port=rear_ports[1]), + ]) ModuleBay.objects.create(device=devices[0], name='Module Bay 1') ModuleBay.objects.create(device=devices[1], name='Module Bay 2') DeviceBay.objects.bulk_create(( @@ -3324,6 +3332,7 @@ class ModuleTestCase(TestCase, ChangeLoggedFilterSetTests): class ConsolePortTestCase(TestCase, DeviceComponentFilterSetTests, ChangeLoggedFilterSetTests): queryset = ConsolePort.objects.all() filterset = ConsolePortFilterSet + ignore_fields = ('cable_positions',) @classmethod def setUpTestData(cls): @@ -3574,6 +3583,7 @@ class ConsolePortTestCase(TestCase, DeviceComponentFilterSetTests, ChangeLoggedF class ConsoleServerPortTestCase(TestCase, DeviceComponentFilterSetTests, ChangeLoggedFilterSetTests): queryset = ConsoleServerPort.objects.all() filterset = ConsoleServerPortFilterSet + ignore_fields = ('cable_positions',) @classmethod def setUpTestData(cls): @@ -3824,6 +3834,7 @@ class ConsoleServerPortTestCase(TestCase, DeviceComponentFilterSetTests, ChangeL class PowerPortTestCase(TestCase, DeviceComponentFilterSetTests, ChangeLoggedFilterSetTests): queryset = PowerPort.objects.all() filterset = PowerPortFilterSet + ignore_fields = ('cable_positions',) @classmethod def setUpTestData(cls): @@ -4088,6 +4099,7 @@ class PowerPortTestCase(TestCase, DeviceComponentFilterSetTests, ChangeLoggedFil class PowerOutletTestCase(TestCase, DeviceComponentFilterSetTests, ChangeLoggedFilterSetTests): queryset = PowerOutlet.objects.all() filterset = PowerOutletFilterSet + ignore_fields = ('cable_positions',) @classmethod def setUpTestData(cls): @@ -4372,7 +4384,7 @@ class PowerOutletTestCase(TestCase, DeviceComponentFilterSetTests, ChangeLoggedF class InterfaceTestCase(TestCase, DeviceComponentFilterSetTests, ChangeLoggedFilterSetTests): queryset = Interface.objects.all() filterset = InterfaceFilterSet - ignore_fields = ('tagged_vlans', 'untagged_vlan', 'qinq_svlan', 'vdcs') + ignore_fields = ('tagged_vlans', 'untagged_vlan', 'qinq_svlan', 'vdcs', 'cable_positions') @classmethod def setUpTestData(cls): @@ -5009,6 +5021,7 @@ class InterfaceTestCase(TestCase, DeviceComponentFilterSetTests, ChangeLoggedFil class FrontPortTestCase(TestCase, DeviceComponentFilterSetTests, ChangeLoggedFilterSetTests): queryset = FrontPort.objects.all() filterset = FrontPortFilterSet + ignore_fields = ('cable_positions',) @classmethod def setUpTestData(cls): @@ -5151,8 +5164,6 @@ class FrontPortTestCase(TestCase, DeviceComponentFilterSetTests, ChangeLoggedFil label='A', type=PortTypeChoices.TYPE_8P8C, color=ColorChoices.COLOR_RED, - rear_port=rear_ports[0], - rear_port_position=1, description='First', _site=devices[0].site, _location=devices[0].location, @@ -5165,8 +5176,6 @@ class FrontPortTestCase(TestCase, DeviceComponentFilterSetTests, ChangeLoggedFil label='B', type=PortTypeChoices.TYPE_110_PUNCH, color=ColorChoices.COLOR_GREEN, - rear_port=rear_ports[1], - rear_port_position=2, description='Second', _site=devices[1].site, _location=devices[1].location, @@ -5179,8 +5188,6 @@ class FrontPortTestCase(TestCase, DeviceComponentFilterSetTests, ChangeLoggedFil label='C', type=PortTypeChoices.TYPE_BNC, color=ColorChoices.COLOR_BLUE, - rear_port=rear_ports[2], - rear_port_position=3, description='Third', _site=devices[2].site, _location=devices[2].location, @@ -5191,8 +5198,7 @@ class FrontPortTestCase(TestCase, DeviceComponentFilterSetTests, ChangeLoggedFil name='Front Port 4', label='D', type=PortTypeChoices.TYPE_FC, - rear_port=rear_ports[3], - rear_port_position=1, + positions=2, _site=devices[3].site, _location=devices[3].location, _rack=devices[3].rack, @@ -5202,8 +5208,7 @@ class FrontPortTestCase(TestCase, DeviceComponentFilterSetTests, ChangeLoggedFil name='Front Port 5', label='E', type=PortTypeChoices.TYPE_FC, - rear_port=rear_ports[4], - rear_port_position=1, + positions=3, _site=devices[3].site, _location=devices[3].location, _rack=devices[3].rack, @@ -5213,14 +5218,21 @@ class FrontPortTestCase(TestCase, DeviceComponentFilterSetTests, ChangeLoggedFil name='Front Port 6', label='F', type=PortTypeChoices.TYPE_FC, - rear_port=rear_ports[5], - rear_port_position=1, + positions=4, _site=devices[3].site, _location=devices[3].location, _rack=devices[3].rack, ), ) FrontPort.objects.bulk_create(front_ports) + PortMapping.objects.bulk_create([ + PortMapping(device=devices[0], front_port=front_ports[0], rear_port=rear_ports[0]), + PortMapping(device=devices[1], front_port=front_ports[1], rear_port=rear_ports[1], rear_port_position=2), + PortMapping(device=devices[2], front_port=front_ports[2], rear_port=rear_ports[2], rear_port_position=3), + PortMapping(device=devices[3], front_port=front_ports[3], rear_port=rear_ports[3]), + PortMapping(device=devices[3], front_port=front_ports[4], rear_port=rear_ports[4]), + PortMapping(device=devices[3], front_port=front_ports[5], rear_port=rear_ports[5]), + ]) # Cables Cable(a_terminations=[front_ports[0]], b_terminations=[front_ports[3]]).save() @@ -5243,6 +5255,10 @@ class FrontPortTestCase(TestCase, DeviceComponentFilterSetTests, ChangeLoggedFil params = {'color': [ColorChoices.COLOR_RED, ColorChoices.COLOR_GREEN]} self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2) + def test_positions(self): + params = {'positions': [2, 3]} + self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2) + def test_description(self): params = {'description': ['First', 'Second']} self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2) @@ -5310,6 +5326,7 @@ class FrontPortTestCase(TestCase, DeviceComponentFilterSetTests, ChangeLoggedFil class RearPortTestCase(TestCase, DeviceComponentFilterSetTests, ChangeLoggedFilterSetTests): queryset = RearPort.objects.all() filterset = RearPortFilterSet + ignore_fields = ('cable_positions',) @classmethod def setUpTestData(cls): @@ -6511,13 +6528,9 @@ class CableTestCase(TestCase, ChangeLoggedFilterSetTests): console_server_port = ConsoleServerPort.objects.create(device=devices[0], name='Console Server Port 1') power_port = PowerPort.objects.create(device=devices[0], name='Power Port 1') power_outlet = PowerOutlet.objects.create(device=devices[0], name='Power Outlet 1') - rear_port = RearPort.objects.create(device=devices[0], name='Rear Port 1', positions=1) - front_port = FrontPort.objects.create( - device=devices[0], - name='Front Port 1', - rear_port=rear_port, - rear_port_position=1 - ) + rear_port = RearPort.objects.create(device=devices[0], name='Rear Port 1') + front_port = FrontPort.objects.create(device=devices[0], name='Front Port 1') + PortMapping.objects.create(device=devices[0], front_port=front_port, rear_port=rear_port) power_panel = PowerPanel.objects.create(name='Power Panel 1', site=sites[0]) power_feed = PowerFeed.objects.create(name='Power Feed 1', power_panel=power_panel) @@ -6852,6 +6865,7 @@ class PowerPanelTestCase(TestCase, ChangeLoggedFilterSetTests): class PowerFeedTestCase(TestCase, ChangeLoggedFilterSetTests): queryset = PowerFeed.objects.all() filterset = PowerFeedFilterSet + ignore_fields = ('cable_positions',) @classmethod def setUpTestData(cls): diff --git a/netbox/dcim/tests/test_forms.py b/netbox/dcim/tests/test_forms.py index fa654f789..a911cbf25 100644 --- a/netbox/dcim/tests/test_forms.py +++ b/netbox/dcim/tests/test_forms.py @@ -193,7 +193,8 @@ class FrontPortTestCase(TestCase): 'name': 'FrontPort[1-4]', 'label': 'Port[1-4]', 'type': PortTypeChoices.TYPE_8P8C, - 'rear_port': [f'{rear_port.pk}:1' for rear_port in self.rear_ports], + 'positions': 1, + 'rear_ports': [f'{rear_port.pk}:1' for rear_port in self.rear_ports], } form = FrontPortCreateForm(front_port_data) @@ -208,7 +209,8 @@ class FrontPortTestCase(TestCase): 'name': 'FrontPort[1-4]', 'label': 'Port[1-2]', 'type': PortTypeChoices.TYPE_8P8C, - 'rear_port': [f'{rear_port.pk}:1' for rear_port in self.rear_ports], + 'positions': 1, + 'rear_ports': [f'{rear_port.pk}:1' for rear_port in self.rear_ports], } form = FrontPortCreateForm(bad_front_port_data) diff --git a/netbox/dcim/tests/test_models.py b/netbox/dcim/tests/test_models.py index 57da78372..c4b9e37bb 100644 --- a/netbox/dcim/tests/test_models.py +++ b/netbox/dcim/tests/test_models.py @@ -445,13 +445,19 @@ class DeviceTestCase(TestCase): ) rearport.save() - FrontPortTemplate( + frontport = FrontPortTemplate( device_type=device_type, name='Front Port 1', type=PortTypeChoices.TYPE_8P8C, + ) + frontport.save() + + PortTemplateMapping.objects.create( + device_type=device_type, + front_port=frontport, rear_port=rearport, - rear_port_position=2 - ).save() + rear_port_position=2, + ) ModuleBayTemplate( device_type=device_type, @@ -529,11 +535,12 @@ class DeviceTestCase(TestCase): device=device, name='Front Port 1', type=PortTypeChoices.TYPE_8P8C, - rear_port=rearport, - rear_port_position=2 + positions=1 ) self.assertEqual(frontport.cf['cf1'], 'foo') + self.assertTrue(PortMapping.objects.filter(front_port=frontport, rear_port=rearport).exists()) + modulebay = ModuleBay.objects.get( device=device, name='Module Bay 1' @@ -908,12 +915,18 @@ class CableTestCase(TestCase): ) RearPort.objects.bulk_create(rear_ports) front_ports = ( - FrontPort(device=patch_panel, name='FP1', type='8p8c', rear_port=rear_ports[0], rear_port_position=1), - FrontPort(device=patch_panel, name='FP2', type='8p8c', rear_port=rear_ports[1], rear_port_position=1), - FrontPort(device=patch_panel, name='FP3', type='8p8c', rear_port=rear_ports[2], rear_port_position=1), - FrontPort(device=patch_panel, name='FP4', type='8p8c', rear_port=rear_ports[3], rear_port_position=1), + FrontPort(device=patch_panel, name='FP1', type='8p8c'), + FrontPort(device=patch_panel, name='FP2', type='8p8c'), + FrontPort(device=patch_panel, name='FP3', type='8p8c'), + FrontPort(device=patch_panel, name='FP4', type='8p8c'), ) FrontPort.objects.bulk_create(front_ports) + PortMapping.objects.bulk_create([ + PortMapping(device=patch_panel, front_port=front_ports[0], rear_port=rear_ports[0]), + PortMapping(device=patch_panel, front_port=front_ports[1], rear_port=rear_ports[1]), + PortMapping(device=patch_panel, front_port=front_ports[2], rear_port=rear_ports[2]), + PortMapping(device=patch_panel, front_port=front_ports[3], rear_port=rear_ports[3]), + ]) provider = Provider.objects.create(name='Provider 1', slug='provider-1') provider_network = ProviderNetwork.objects.create(name='Provider Network 1', provider=provider) diff --git a/netbox/dcim/tests/test_views.py b/netbox/dcim/tests/test_views.py index 9103befdb..1aac72875 100644 --- a/netbox/dcim/tests/test_views.py +++ b/netbox/dcim/tests/test_views.py @@ -11,6 +11,7 @@ from core.models import ObjectType from dcim.choices import * from dcim.constants import * from dcim.models import * +from extras.models import ConfigTemplate from ipam.models import ASN, RIR, VLAN, VRF from netbox.choices import CSVDelimiterChoices, ImportFormatChoices, WeightUnitChoices from tenancy.models import Tenant @@ -741,17 +742,16 @@ class DeviceTypeTestCase( ) RearPortTemplate.objects.bulk_create(rear_ports) front_ports = ( - FrontPortTemplate( - device_type=devicetype, name='Front Port 1', rear_port=rear_ports[0], rear_port_position=1 - ), - FrontPortTemplate( - device_type=devicetype, name='Front Port 2', rear_port=rear_ports[1], rear_port_position=1 - ), - FrontPortTemplate( - device_type=devicetype, name='Front Port 3', rear_port=rear_ports[2], rear_port_position=1 - ), + FrontPortTemplate(device_type=devicetype, name='Front Port 1'), + FrontPortTemplate(device_type=devicetype, name='Front Port 2'), + FrontPortTemplate(device_type=devicetype, name='Front Port 3'), ) FrontPortTemplate.objects.bulk_create(front_ports) + PortTemplateMapping.objects.bulk_create([ + PortTemplateMapping(device_type=devicetype, front_port=front_ports[0], rear_port=rear_ports[0]), + PortTemplateMapping(device_type=devicetype, front_port=front_ports[1], rear_port=rear_ports[1]), + PortTemplateMapping(device_type=devicetype, front_port=front_ports[2], rear_port=rear_ports[2]), + ]) url = reverse('dcim:devicetype_frontports', kwargs={'pk': devicetype.pk}) self.assertHttpStatus(self.client.get(url), 200) @@ -866,12 +866,16 @@ rear-ports: front-ports: - name: Front Port 1 type: 8p8c - rear_port: Rear Port 1 - name: Front Port 2 type: 8p8c - rear_port: Rear Port 2 - name: Front Port 3 type: 8p8c +port-mappings: + - front_port: Front Port 1 + rear_port: Rear Port 1 + - front_port: Front Port 2 + rear_port: Rear Port 2 + - front_port: Front Port 3 rear_port: Rear Port 3 module-bays: - name: Module Bay 1 @@ -971,8 +975,12 @@ inventory-items: self.assertEqual(device_type.frontporttemplates.count(), 3) fp1 = FrontPortTemplate.objects.first() self.assertEqual(fp1.name, 'Front Port 1') - self.assertEqual(fp1.rear_port, rp1) - self.assertEqual(fp1.rear_port_position, 1) + + self.assertEqual(device_type.port_mappings.count(), 3) + mapping1 = PortTemplateMapping.objects.first() + self.assertEqual(mapping1.device_type, device_type) + self.assertEqual(mapping1.front_port, fp1) + self.assertEqual(mapping1.rear_port, rp1) self.assertEqual(device_type.modulebaytemplates.count(), 3) mb1 = ModuleBayTemplate.objects.first() @@ -1316,17 +1324,16 @@ class ModuleTypeTestCase(ViewTestCases.PrimaryObjectViewTestCase): ) RearPortTemplate.objects.bulk_create(rear_ports) front_ports = ( - FrontPortTemplate( - module_type=moduletype, name='Front Port 1', rear_port=rear_ports[0], rear_port_position=1 - ), - FrontPortTemplate( - module_type=moduletype, name='Front Port 2', rear_port=rear_ports[1], rear_port_position=1 - ), - FrontPortTemplate( - module_type=moduletype, name='Front Port 3', rear_port=rear_ports[2], rear_port_position=1 - ), + FrontPortTemplate(module_type=moduletype, name='Front Port 1'), + FrontPortTemplate(module_type=moduletype, name='Front Port 2'), + FrontPortTemplate(module_type=moduletype, name='Front Port 3'), ) FrontPortTemplate.objects.bulk_create(front_ports) + PortTemplateMapping.objects.bulk_create([ + PortTemplateMapping(module_type=moduletype, front_port=front_ports[0], rear_port=rear_ports[0]), + PortTemplateMapping(module_type=moduletype, front_port=front_ports[1], rear_port=rear_ports[1]), + PortTemplateMapping(module_type=moduletype, front_port=front_ports[2], rear_port=rear_ports[2]), + ]) url = reverse('dcim:moduletype_frontports', kwargs={'pk': moduletype.pk}) self.assertHttpStatus(self.client.get(url), 200) @@ -1394,12 +1401,16 @@ rear-ports: front-ports: - name: Front Port 1 type: 8p8c - rear_port: Rear Port 1 - name: Front Port 2 type: 8p8c - rear_port: Rear Port 2 - name: Front Port 3 type: 8p8c +port-mappings: + - front_port: Front Port 1 + rear_port: Rear Port 1 + - front_port: Front Port 2 + rear_port: Rear Port 2 + - front_port: Front Port 3 rear_port: Rear Port 3 module-bays: - name: Module Bay 1 @@ -1477,8 +1488,12 @@ module-bays: self.assertEqual(module_type.frontporttemplates.count(), 3) fp1 = FrontPortTemplate.objects.first() self.assertEqual(fp1.name, 'Front Port 1') - self.assertEqual(fp1.rear_port, rp1) - self.assertEqual(fp1.rear_port_position, 1) + + self.assertEqual(module_type.port_mappings.count(), 3) + mapping1 = PortTemplateMapping.objects.first() + self.assertEqual(mapping1.module_type, module_type) + self.assertEqual(mapping1.front_port, fp1) + self.assertEqual(mapping1.rear_port, rp1) self.assertEqual(module_type.modulebaytemplates.count(), 3) mb1 = ModuleBayTemplate.objects.first() @@ -1770,7 +1785,7 @@ class FrontPortTemplateTestCase(ViewTestCases.DeviceComponentTemplateViewTestCas manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1') devicetype = DeviceType.objects.create(manufacturer=manufacturer, model='Device Type 1', slug='device-type-1') - rearports = ( + rear_ports = ( RearPortTemplate(device_type=devicetype, name='Rear Port Template 1'), RearPortTemplate(device_type=devicetype, name='Rear Port Template 2'), RearPortTemplate(device_type=devicetype, name='Rear Port Template 3'), @@ -1778,35 +1793,33 @@ class FrontPortTemplateTestCase(ViewTestCases.DeviceComponentTemplateViewTestCas RearPortTemplate(device_type=devicetype, name='Rear Port Template 5'), RearPortTemplate(device_type=devicetype, name='Rear Port Template 6'), ) - RearPortTemplate.objects.bulk_create(rearports) - - FrontPortTemplate.objects.bulk_create( - ( - FrontPortTemplate( - device_type=devicetype, name='Front Port Template 1', rear_port=rearports[0], rear_port_position=1 - ), - FrontPortTemplate( - device_type=devicetype, name='Front Port Template 2', rear_port=rearports[1], rear_port_position=1 - ), - FrontPortTemplate( - device_type=devicetype, name='Front Port Template 3', rear_port=rearports[2], rear_port_position=1 - ), - ) + RearPortTemplate.objects.bulk_create(rear_ports) + front_ports = ( + FrontPortTemplate(device_type=devicetype, name='Front Port Template 1'), + FrontPortTemplate(device_type=devicetype, name='Front Port Template 2'), + FrontPortTemplate(device_type=devicetype, name='Front Port Template 3'), ) + FrontPortTemplate.objects.bulk_create(front_ports) + PortTemplateMapping.objects.bulk_create([ + PortTemplateMapping(device_type=devicetype, front_port=front_ports[0], rear_port=rear_ports[0]), + PortTemplateMapping(device_type=devicetype, front_port=front_ports[1], rear_port=rear_ports[1]), + PortTemplateMapping(device_type=devicetype, front_port=front_ports[2], rear_port=rear_ports[2]), + ]) cls.form_data = { 'device_type': devicetype.pk, 'name': 'Front Port X', 'type': PortTypeChoices.TYPE_8P8C, - 'rear_port': rearports[3].pk, - 'rear_port_position': 1, + 'positions': 1, + 'rear_ports': [f'{rear_ports[3].pk}:1'], } cls.bulk_create_data = { 'device_type': devicetype.pk, 'name': 'Front Port [4-6]', 'type': PortTypeChoices.TYPE_8P8C, - 'rear_port': [f'{rp.pk}:1' for rp in rearports[3:6]], + 'positions': 1, + 'rear_ports': [f'{rp.pk}:1' for rp in rear_ports[3:6]], } cls.bulk_edit_data = { @@ -2276,11 +2289,16 @@ class DeviceTestCase(ViewTestCases.PrimaryObjectViewTestCase): ) RearPort.objects.bulk_create(rear_ports) front_ports = ( - FrontPort(device=device, name='Front Port 1', rear_port=rear_ports[0], rear_port_position=1), - FrontPort(device=device, name='Front Port 2', rear_port=rear_ports[1], rear_port_position=1), - FrontPort(device=device, name='Front Port 3', rear_port=rear_ports[2], rear_port_position=1), + FrontPort(device=device, name='Front Port Template 1'), + FrontPort(device=device, name='Front Port Template 2'), + FrontPort(device=device, name='Front Port Template 3'), ) FrontPort.objects.bulk_create(front_ports) + PortMapping.objects.bulk_create([ + PortMapping(device=device, front_port=front_ports[0], rear_port=rear_ports[0]), + PortMapping(device=device, front_port=front_ports[1], rear_port=rear_ports[1]), + PortMapping(device=device, front_port=front_ports[2], rear_port=rear_ports[2]), + ]) url = reverse('dcim:device_frontports', kwargs={'pk': device.pk}) self.assertHttpStatus(self.client.get(url), 200) @@ -2322,6 +2340,28 @@ class DeviceTestCase(ViewTestCases.PrimaryObjectViewTestCase): url = reverse('dcim:device_inventory', kwargs={'pk': device.pk}) self.assertHttpStatus(self.client.get(url), 200) + def test_device_renderconfig(self): + configtemplate = ConfigTemplate.objects.create( + name='Test Config Template', + template_code='Config for device {{ device.name }}' + ) + device = Device.objects.first() + device.config_template = configtemplate + device.save() + url = reverse('dcim:device_render-config', kwargs={'pk': device.pk}) + + # User with only view permission should NOT be able to render config + self.add_permissions('dcim.view_device') + self.assertHttpStatus(self.client.get(url), 403) + + # With render_config permission added should be able to render config + self.add_permissions('dcim.render_config_device') + self.assertHttpStatus(self.client.get(url), 200) + + # With view permission removed should NOT be able to render config + self.remove_permissions('dcim.view_device') + self.assertHttpStatus(self.client.get(url), 403) + @override_settings(EXEMPT_VIEW_PERMISSIONS=['*']) def test_bulk_import_duplicate_ids_error_message(self): device = Device.objects.first() @@ -3091,7 +3131,7 @@ class FrontPortTestCase(ViewTestCases.DeviceComponentViewTestCase): def setUpTestData(cls): device = create_test_device('Device 1') - rearports = ( + rear_ports = ( RearPort(device=device, name='Rear Port 1'), RearPort(device=device, name='Rear Port 2'), RearPort(device=device, name='Rear Port 3'), @@ -3099,14 +3139,19 @@ class FrontPortTestCase(ViewTestCases.DeviceComponentViewTestCase): RearPort(device=device, name='Rear Port 5'), RearPort(device=device, name='Rear Port 6'), ) - RearPort.objects.bulk_create(rearports) + RearPort.objects.bulk_create(rear_ports) front_ports = ( - FrontPort(device=device, name='Front Port 1', rear_port=rearports[0]), - FrontPort(device=device, name='Front Port 2', rear_port=rearports[1]), - FrontPort(device=device, name='Front Port 3', rear_port=rearports[2]), + FrontPort(device=device, name='Front Port 1'), + FrontPort(device=device, name='Front Port 2'), + FrontPort(device=device, name='Front Port 3'), ) FrontPort.objects.bulk_create(front_ports) + PortMapping.objects.bulk_create([ + PortMapping(device=device, front_port=front_ports[0], rear_port=rear_ports[0]), + PortMapping(device=device, front_port=front_ports[1], rear_port=rear_ports[1]), + PortMapping(device=device, front_port=front_ports[2], rear_port=rear_ports[2]), + ]) tags = create_tags('Alpha', 'Bravo', 'Charlie') @@ -3114,8 +3159,8 @@ class FrontPortTestCase(ViewTestCases.DeviceComponentViewTestCase): 'device': device.pk, 'name': 'Front Port X', 'type': PortTypeChoices.TYPE_8P8C, - 'rear_port': rearports[3].pk, - 'rear_port_position': 1, + 'positions': 1, + 'rear_ports': [f'{rear_ports[3].pk}:1'], 'description': 'New description', 'tags': [t.pk for t in tags], } @@ -3124,7 +3169,8 @@ class FrontPortTestCase(ViewTestCases.DeviceComponentViewTestCase): 'device': device.pk, 'name': 'Front Port [4-6]', 'type': PortTypeChoices.TYPE_8P8C, - 'rear_port': [f'{rp.pk}:1' for rp in rearports[3:6]], + 'positions': 1, + 'rear_ports': [f'{rp.pk}:1' for rp in rear_ports[3:6]], 'description': 'New description', 'tags': [t.pk for t in tags], } @@ -3135,10 +3181,10 @@ class FrontPortTestCase(ViewTestCases.DeviceComponentViewTestCase): } cls.csv_data = ( - "device,name,type,rear_port,rear_port_position", - "Device 1,Front Port 4,8p8c,Rear Port 4,1", - "Device 1,Front Port 5,8p8c,Rear Port 5,1", - "Device 1,Front Port 6,8p8c,Rear Port 6,1", + "device,name,type,positions", + "Device 1,Front Port 4,8p8c,1", + "Device 1,Front Port 5,8p8c,1", + "Device 1,Front Port 6,8p8c,1", ) cls.csv_update_data = ( diff --git a/netbox/dcim/tests/utils.py b/netbox/dcim/tests/utils.py new file mode 100644 index 000000000..575034201 --- /dev/null +++ b/netbox/dcim/tests/utils.py @@ -0,0 +1,88 @@ +from django.test import TestCase + +from circuits.models import * +from dcim.models import * +from dcim.utils import object_to_path_node + +__all__ = ( + 'CablePathTestCase', +) + + +class CablePathTestCase(TestCase): + """ + Base class for test cases for cable paths. + """ + @classmethod + def setUpTestData(cls): + manufacturer = Manufacturer.objects.create(name='Generic', slug='generic') + device_type = DeviceType.objects.create(manufacturer=manufacturer, model='Test Device') + role = DeviceRole.objects.create(name='Device Role', slug='device-role') + provider = Provider.objects.create(name='Provider', slug='provider') + circuit_type = CircuitType.objects.create(name='Circuit Type', slug='circuit-type') + + # Create reusable test objects + cls.site = Site.objects.create(name='Site', slug='site') + cls.device = Device.objects.create(site=cls.site, device_type=device_type, role=role, name='Test Device') + cls.powerpanel = PowerPanel.objects.create(site=cls.site, name='Power Panel') + cls.circuit = Circuit.objects.create(provider=provider, type=circuit_type, cid='Circuit 1') + + def _get_cablepath(self, nodes, **kwargs): + """ + Return a given cable path + + :param nodes: Iterable of steps, with each step being either a single node or a list of nodes + + :return: The matching CablePath (if any) + """ + path = [] + for step in nodes: + if type(step) in (list, tuple): + path.append([object_to_path_node(node) for node in step]) + else: + path.append([object_to_path_node(step)]) + return CablePath.objects.filter(path=path, **kwargs).first() + + def assertPathExists(self, nodes, **kwargs): + """ + Assert that a CablePath from origin to destination with a specific intermediate path exists. Returns the + first matching CablePath, if found. + + :param nodes: Iterable of steps, with each step being either a single node or a list of nodes + """ + cablepath = self._get_cablepath(nodes, **kwargs) + self.assertIsNotNone(cablepath, msg='CablePath not found') + + return cablepath + + def assertPathDoesNotExist(self, nodes, **kwargs): + """ + Assert that a specific CablePath does *not* exist. + + :param nodes: Iterable of steps, with each step being either a single node or a list of nodes + """ + cablepath = self._get_cablepath(nodes, **kwargs) + self.assertIsNone(cablepath, msg='Unexpected CablePath found') + + def assertPathIsSet(self, origin, cablepath, msg=None): + """ + Assert that a specific CablePath instance is set as the path on the origin. + + :param origin: The originating path endpoint + :param cablepath: The CablePath instance originating from this endpoint + :param msg: Custom failure message (optional) + """ + if msg is None: + msg = f"Path #{cablepath.pk} not set on originating endpoint {origin}" + self.assertEqual(origin._path_id, cablepath.pk, msg=msg) + + def assertPathIsNotSet(self, origin, msg=None): + """ + Assert that a specific CablePath instance is set as the path on the origin. + + :param origin: The originating path endpoint + :param msg: Custom failure message (optional) + """ + if msg is None: + msg = f"Path #{origin._path_id} set as origin on {origin}; should be None!" + self.assertIsNone(origin._path_id, msg=msg) diff --git a/netbox/dcim/ui/__init__.py b/netbox/dcim/ui/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/netbox/dcim/ui/panels.py b/netbox/dcim/ui/panels.py new file mode 100644 index 000000000..87ceb9c4a --- /dev/null +++ b/netbox/dcim/ui/panels.py @@ -0,0 +1,189 @@ +from django.utils.translation import gettext_lazy as _ + +from netbox.ui import attrs, panels + + +class SitePanel(panels.ObjectAttributesPanel): + region = attrs.NestedObjectAttr('region', linkify=True) + group = attrs.NestedObjectAttr('group', linkify=True) + name = attrs.TextAttr('name') + status = attrs.ChoiceAttr('status') + tenant = attrs.RelatedObjectAttr('tenant', linkify=True, grouped_by='group') + facility = attrs.TextAttr('facility') + description = attrs.TextAttr('description') + timezone = attrs.TimezoneAttr('time_zone') + physical_address = attrs.AddressAttr('physical_address', map_url=True) + shipping_address = attrs.AddressAttr('shipping_address', map_url=True) + gps_coordinates = attrs.GPSCoordinatesAttr() + + +class LocationPanel(panels.NestedGroupObjectPanel): + site = attrs.RelatedObjectAttr('site', linkify=True, grouped_by='group') + status = attrs.ChoiceAttr('status') + tenant = attrs.RelatedObjectAttr('tenant', linkify=True, grouped_by='group') + facility = attrs.TextAttr('facility') + + +class RackDimensionsPanel(panels.ObjectAttributesPanel): + form_factor = attrs.ChoiceAttr('form_factor') + width = attrs.ChoiceAttr('width') + height = attrs.TextAttr('u_height', format_string='{}U', label=_('Height')) + outer_width = attrs.NumericAttr('outer_width', unit_accessor='get_outer_unit_display') + outer_height = attrs.NumericAttr('outer_height', unit_accessor='get_outer_unit_display') + outer_depth = attrs.NumericAttr('outer_depth', unit_accessor='get_outer_unit_display') + mounting_depth = attrs.TextAttr('mounting_depth', format_string='{}mm') + + +class RackNumberingPanel(panels.ObjectAttributesPanel): + starting_unit = attrs.TextAttr('starting_unit') + desc_units = attrs.BooleanAttr('desc_units', label=_('Descending units')) + + +class RackPanel(panels.ObjectAttributesPanel): + region = attrs.NestedObjectAttr('site.region', linkify=True) + site = attrs.RelatedObjectAttr('site', linkify=True, grouped_by='group') + location = attrs.NestedObjectAttr('location', linkify=True) + name = attrs.TextAttr('name') + facility = attrs.TextAttr('facility', label=_('Facility ID')) + tenant = attrs.RelatedObjectAttr('tenant', linkify=True, grouped_by='group') + status = attrs.ChoiceAttr('status') + rack_type = attrs.RelatedObjectAttr('rack_type', linkify=True, grouped_by='manufacturer') + role = attrs.RelatedObjectAttr('role', linkify=True) + description = attrs.TextAttr('description') + serial = attrs.TextAttr('serial', label=_('Serial number'), style='font-monospace', copy_button=True) + asset_tag = attrs.TextAttr('asset_tag', style='font-monospace', copy_button=True) + airflow = attrs.ChoiceAttr('airflow') + space_utilization = attrs.UtilizationAttr('get_utilization') + power_utilization = attrs.UtilizationAttr('get_power_utilization') + + +class RackWeightPanel(panels.ObjectAttributesPanel): + weight = attrs.NumericAttr('weight', unit_accessor='get_weight_unit_display') + max_weight = attrs.NumericAttr('max_weight', unit_accessor='get_weight_unit_display', label=_('Maximum weight')) + total_weight = attrs.TemplatedAttr('total_weight', template_name='dcim/rack/attrs/total_weight.html') + + +class RackRolePanel(panels.OrganizationalObjectPanel): + color = attrs.ColorAttr('color') + + +class RackReservationPanel(panels.ObjectAttributesPanel): + units = attrs.TextAttr('unit_list') + status = attrs.ChoiceAttr('status') + tenant = attrs.RelatedObjectAttr('tenant', linkify=True, grouped_by='group') + user = attrs.RelatedObjectAttr('user') + description = attrs.TextAttr('description') + + +class RackTypePanel(panels.ObjectAttributesPanel): + manufacturer = attrs.RelatedObjectAttr('manufacturer', linkify=True) + model = attrs.TextAttr('model') + description = attrs.TextAttr('description') + + +class DevicePanel(panels.ObjectAttributesPanel): + region = attrs.NestedObjectAttr('site.region', linkify=True) + site = attrs.RelatedObjectAttr('site', linkify=True, grouped_by='group') + location = attrs.NestedObjectAttr('location', linkify=True) + rack = attrs.TemplatedAttr('rack', template_name='dcim/device/attrs/rack.html') + virtual_chassis = attrs.RelatedObjectAttr('virtual_chassis', linkify=True) + parent_device = attrs.TemplatedAttr('parent_bay', template_name='dcim/device/attrs/parent_device.html') + gps_coordinates = attrs.GPSCoordinatesAttr() + tenant = attrs.RelatedObjectAttr('tenant', linkify=True, grouped_by='group') + device_type = attrs.RelatedObjectAttr('device_type', linkify=True, grouped_by='manufacturer') + description = attrs.TextAttr('description') + airflow = attrs.ChoiceAttr('airflow') + serial = attrs.TextAttr('serial', label=_('Serial number'), style='font-monospace', copy_button=True) + asset_tag = attrs.TextAttr('asset_tag', style='font-monospace', copy_button=True) + config_template = attrs.RelatedObjectAttr('config_template', linkify=True) + + +class DeviceManagementPanel(panels.ObjectAttributesPanel): + title = _('Management') + + status = attrs.ChoiceAttr('status') + role = attrs.NestedObjectAttr('role', linkify=True, max_depth=3) + platform = attrs.NestedObjectAttr('platform', linkify=True, max_depth=3) + primary_ip4 = attrs.TemplatedAttr( + 'primary_ip4', + label=_('Primary IPv4'), + template_name='dcim/device/attrs/ipaddress.html', + ) + primary_ip6 = attrs.TemplatedAttr( + 'primary_ip6', + label=_('Primary IPv6'), + template_name='dcim/device/attrs/ipaddress.html', + ) + oob_ip = attrs.TemplatedAttr( + 'oob_ip', + label=_('Out-of-band IP'), + template_name='dcim/device/attrs/ipaddress.html', + ) + cluster = attrs.RelatedObjectAttr('cluster', linkify=True) + + +class DeviceDimensionsPanel(panels.ObjectAttributesPanel): + title = _('Dimensions') + + height = attrs.TextAttr('device_type.u_height', format_string='{}U') + total_weight = attrs.TemplatedAttr('total_weight', template_name='dcim/device/attrs/total_weight.html') + + +class DeviceTypePanel(panels.ObjectAttributesPanel): + manufacturer = attrs.RelatedObjectAttr('manufacturer', linkify=True) + model = attrs.TextAttr('model') + part_number = attrs.TextAttr('part_number') + default_platform = attrs.RelatedObjectAttr('default_platform', linkify=True) + description = attrs.TextAttr('description') + height = attrs.TextAttr('u_height', format_string='{}U', label=_('Height')) + exclude_from_utilization = attrs.BooleanAttr('exclude_from_utilization') + full_depth = attrs.BooleanAttr('is_full_depth') + weight = attrs.NumericAttr('weight', unit_accessor='get_weight_unit_display') + subdevice_role = attrs.ChoiceAttr('subdevice_role', label=_('Parent/child')) + airflow = attrs.ChoiceAttr('airflow') + front_image = attrs.ImageAttr('front_image') + rear_image = attrs.ImageAttr('rear_image') + + +class ModuleTypeProfilePanel(panels.ObjectAttributesPanel): + name = attrs.TextAttr('name') + description = attrs.TextAttr('description') + + +class VirtualChassisMembersPanel(panels.ObjectPanel): + """ + A panel which lists all members of a virtual chassis. + """ + template_name = 'dcim/panels/virtual_chassis_members.html' + title = _('Virtual Chassis Members') + + def get_context(self, context): + return { + **super().get_context(context), + 'vc_members': context.get('vc_members'), + } + + def render(self, context): + if not context.get('vc_members'): + return '' + return super().render(context) + + +class PowerUtilizationPanel(panels.ObjectPanel): + """ + A panel which displays the power utilization statistics for a device. + """ + template_name = 'dcim/panels/power_utilization.html' + title = _('Power Utilization') + + def get_context(self, context): + return { + **super().get_context(context), + 'vc_members': context.get('vc_members'), + } + + def render(self, context): + obj = context['object'] + if not obj.powerports.exists() or not obj.poweroutlets.exists(): + return '' + return super().render(context) diff --git a/netbox/dcim/utils.py b/netbox/dcim/utils.py index a03790ea2..4b9d0fb5c 100644 --- a/netbox/dcim/utils.py +++ b/netbox/dcim/utils.py @@ -1,3 +1,5 @@ +from collections import defaultdict + from django.apps import apps from django.contrib.contenttypes.models import ContentType from django.db import router, transaction @@ -31,17 +33,22 @@ def path_node_to_object(repr): return ct.model_class().objects.filter(pk=object_id).first() -def create_cablepath(terminations): +def create_cablepaths(objects): """ Create CablePaths for all paths originating from the specified set of nodes. - :param terminations: Iterable of CableTermination objects + :param objects: Iterable of cabled objects (e.g. Interfaces) """ from dcim.models import CablePath - cp = CablePath.from_origin(terminations) - if cp: - cp.save() + # Arrange objects by cable connector. All objects with a null connector are grouped together. + origins = defaultdict(list) + for obj in objects: + origins[obj.cable_connector].append(obj) + + for connector, objects in origins.items(): + if cp := CablePath.from_origin(objects): + cp.save() def rebuild_paths(terminations): @@ -56,7 +63,7 @@ def rebuild_paths(terminations): with transaction.atomic(using=router.db_for_write(CablePath)): for cp in cable_paths: cp.delete() - create_cablepath(cp.origins) + create_cablepaths(cp.origins) def update_interface_bridges(device, interface_templates, module=None): @@ -76,3 +83,36 @@ def update_interface_bridges(device, interface_templates, module=None): ) interface.full_clean() interface.save() + + +def create_port_mappings(device, device_type, module=None): + """ + Replicate all front/rear port mappings from a DeviceType to the given device. + """ + from dcim.models import FrontPort, PortMapping, RearPort + + templates = device_type.port_mappings.prefetch_related('front_port', 'rear_port') + + # Cache front & rear ports for efficient lookups by name + front_ports = { + fp.name: fp for fp in FrontPort.objects.filter(device=device) + } + rear_ports = { + rp.name: rp for rp in RearPort.objects.filter(device=device) + } + + # Replicate PortMappings + mappings = [] + for template in templates: + front_port = front_ports.get(template.front_port.resolve_name(module=module)) + rear_port = rear_ports.get(template.rear_port.resolve_name(module=module)) + mappings.append( + PortMapping( + device_id=front_port.device_id, + front_port=front_port, + front_port_position=template.front_port_position, + rear_port=rear_port, + rear_port_position=template.rear_port_position, + ) + ) + PortMapping.objects.bulk_create(mappings) diff --git a/netbox/dcim/views.py b/netbox/dcim/views.py index cc3a5df9c..858077ca1 100644 --- a/netbox/dcim/views.py +++ b/netbox/dcim/views.py @@ -1,3 +1,4 @@ +from django.conf import settings from django.contrib import messages from django.contrib.contenttypes.models import ContentType from django.core.paginator import EmptyPage, PageNotAnInteger @@ -12,10 +13,17 @@ from django.utils.translation import gettext_lazy as _ from django.views.generic import View from circuits.models import Circuit, CircuitTermination +from dcim.ui import panels +from extras.ui.panels import CustomFieldsPanel, ImageAttachmentsPanel, TagsPanel from extras.views import ObjectConfigContextView, ObjectRenderConfigView from ipam.models import ASN, IPAddress, Prefix, VLAN, VLANGroup from ipam.tables import InterfaceVLANTable, VLANTranslationRuleTable from netbox.object_actions import * +from netbox.ui import actions, layout +from netbox.ui.panels import ( + CommentsPanel, JSONPanel, NestedGroupObjectPanel, ObjectsTablePanel, OrganizationalObjectPanel, RelatedObjectsPanel, + TemplatePanel, +) from netbox.views import generic from utilities.forms import ConfirmationForm from utilities.paginator import EnhancedPaginator, get_paginate_count @@ -34,6 +42,7 @@ from wireless.models import WirelessLAN from . import filtersets, forms, tables from .choices import DeviceFaceChoices, InterfaceModeChoices from .models import * +from .models.device_components import PortMapping from .object_actions import BulkAddComponents, BulkDisconnect CABLE_TERMINATION_TYPES = { @@ -221,6 +230,27 @@ class RegionListView(generic.ObjectListView): @register_model_view(Region) class RegionView(GetRelatedModelsMixin, generic.ObjectView): queryset = Region.objects.all() + layout = layout.SimpleLayout( + left_panels=[ + NestedGroupObjectPanel(), + TagsPanel(), + CustomFieldsPanel(), + CommentsPanel(), + ], + right_panels=[ + RelatedObjectsPanel(), + ], + bottom_panels=[ + ObjectsTablePanel( + model='dcim.Region', + title=_('Child Regions'), + filters={'parent_id': lambda ctx: ctx['object'].pk}, + actions=[ + actions.AddObject('dcim.Region', url_params={'parent': lambda ctx: ctx['object'].pk}), + ], + ), + ] + ) def get_extra_context(self, request, instance): regions = instance.get_descendants(include_self=True) @@ -332,6 +362,27 @@ class SiteGroupListView(generic.ObjectListView): @register_model_view(SiteGroup) class SiteGroupView(GetRelatedModelsMixin, generic.ObjectView): queryset = SiteGroup.objects.all() + layout = layout.SimpleLayout( + left_panels=[ + NestedGroupObjectPanel(), + TagsPanel(), + CustomFieldsPanel(), + CommentsPanel(), + ], + right_panels=[ + RelatedObjectsPanel(), + ], + bottom_panels=[ + ObjectsTablePanel( + model='dcim.SiteGroup', + title=_('Child Groups'), + filters={'parent_id': lambda ctx: ctx['object'].pk}, + actions=[ + actions.AddObject('dcim.Region', url_params={'parent': lambda ctx: ctx['object'].pk}), + ], + ), + ] + ) def get_extra_context(self, request, instance): groups = instance.get_descendants(include_self=True) @@ -461,6 +512,39 @@ class SiteListView(generic.ObjectListView): @register_model_view(Site) class SiteView(GetRelatedModelsMixin, generic.ObjectView): queryset = Site.objects.prefetch_related('tenant__group') + layout = layout.SimpleLayout( + left_panels=[ + panels.SitePanel(), + CustomFieldsPanel(), + TagsPanel(), + CommentsPanel(), + ], + right_panels=[ + RelatedObjectsPanel(), + ImageAttachmentsPanel(), + ], + bottom_panels=[ + ObjectsTablePanel( + model='dcim.Location', + filters={'site_id': lambda ctx: ctx['object'].pk}, + actions=[ + actions.AddObject('dcim.Location', url_params={'site': lambda ctx: ctx['object'].pk}), + ], + ), + ObjectsTablePanel( + model='dcim.Device', + title=_('Non-Racked Devices'), + filters={ + 'site_id': lambda ctx: ctx['object'].pk, + 'rack_id': settings.FILTERS_NULL_CHOICE_VALUE, + 'parent_bay_id': settings.FILTERS_NULL_CHOICE_VALUE, + }, + actions=[ + actions.AddObject('dcim.Device', url_params={'site': lambda ctx: ctx['object'].pk}), + ], + ), + ] + ) def get_extra_context(self, request, instance): return { @@ -561,6 +645,52 @@ class LocationListView(generic.ObjectListView): @register_model_view(Location) class LocationView(GetRelatedModelsMixin, generic.ObjectView): queryset = Location.objects.all() + layout = layout.SimpleLayout( + left_panels=[ + panels.LocationPanel(), + TagsPanel(), + CustomFieldsPanel(), + CommentsPanel(), + ], + right_panels=[ + RelatedObjectsPanel(), + ImageAttachmentsPanel(), + ], + bottom_panels=[ + ObjectsTablePanel( + model='dcim.Location', + title=_('Child Locations'), + filters={'parent_id': lambda ctx: ctx['object'].pk}, + actions=[ + actions.AddObject( + 'dcim.Location', + url_params={ + 'site': lambda ctx: ctx['object'].site_id, + 'parent': lambda ctx: ctx['object'].pk, + } + ), + ], + ), + ObjectsTablePanel( + model='dcim.Device', + title=_('Non-Racked Devices'), + filters={ + 'location_id': lambda ctx: ctx['object'].pk, + 'rack_id': settings.FILTERS_NULL_CHOICE_VALUE, + 'parent_bay_id': settings.FILTERS_NULL_CHOICE_VALUE, + }, + actions=[ + actions.AddObject( + 'dcim.Device', + url_params={ + 'site': lambda ctx: ctx['object'].site_id, + 'parent': lambda ctx: ctx['object'].pk, + } + ), + ], + ), + ] + ) def get_extra_context(self, request, instance): locations = instance.get_descendants(include_self=True) @@ -661,6 +791,17 @@ class RackRoleListView(generic.ObjectListView): @register_model_view(RackRole) class RackRoleView(GetRelatedModelsMixin, generic.ObjectView): queryset = RackRole.objects.all() + layout = layout.SimpleLayout( + left_panels=[ + panels.RackRolePanel(), + TagsPanel(), + ], + right_panels=[ + RelatedObjectsPanel(), + CustomFieldsPanel(), + CommentsPanel(), + ], + ) def get_extra_context(self, request, instance): return { @@ -717,9 +858,7 @@ class RackRoleBulkDeleteView(generic.BulkDeleteView): @register_model_view(RackType, 'list', path='', detail=False) class RackTypeListView(generic.ObjectListView): - queryset = RackType.objects.annotate( - instance_count=count_related(Rack, 'rack_type') - ) + queryset = RackType.objects.all() filterset = filtersets.RackTypeFilterSet filterset_form = forms.RackTypeFilterForm table = tables.RackTypeTable @@ -727,7 +866,22 @@ class RackTypeListView(generic.ObjectListView): @register_model_view(RackType) class RackTypeView(GetRelatedModelsMixin, generic.ObjectView): + template_name = 'generic/object.html' queryset = RackType.objects.all() + layout = layout.SimpleLayout( + left_panels=[ + panels.RackTypePanel(), + panels.RackDimensionsPanel(title=_('Dimensions')), + TagsPanel(), + CommentsPanel(), + ], + right_panels=[ + panels.RackNumberingPanel(title=_('Numbering')), + panels.RackWeightPanel(title=_('Weight'), exclude=['total_weight']), + CustomFieldsPanel(), + RelatedObjectsPanel(), + ], + ) def get_extra_context(self, request, instance): return { @@ -845,6 +999,22 @@ class RackElevationListView(generic.ObjectListView): @register_model_view(Rack) class RackView(GetRelatedModelsMixin, generic.ObjectView): queryset = Rack.objects.prefetch_related('site__region', 'tenant__group', 'location', 'role') + layout = layout.SimpleLayout( + left_panels=[ + panels.RackPanel(), + panels.RackDimensionsPanel(title=_('Dimensions')), + panels.RackNumberingPanel(title=_('Numbering')), + panels.RackWeightPanel(title=_('Weight')), + CustomFieldsPanel(), + TagsPanel(), + CommentsPanel(), + ImageAttachmentsPanel(), + ], + right_panels=[ + TemplatePanel('dcim/panels/rack_elevations.html'), + RelatedObjectsPanel(), + ], + ) def get_extra_context(self, request, instance): peer_racks = Rack.objects.restrict(request.user, 'view').filter(site=instance.site) @@ -976,6 +1146,19 @@ class RackReservationListView(generic.ObjectListView): @register_model_view(RackReservation) class RackReservationView(generic.ObjectView): queryset = RackReservation.objects.all() + layout = layout.SimpleLayout( + left_panels=[ + panels.RackPanel(accessor='object.rack', only=['region', 'site', 'location', 'name']), + panels.RackReservationPanel(title=_('Reservation')), + CustomFieldsPanel(), + TagsPanel(), + CommentsPanel(), + ], + right_panels=[ + TemplatePanel(template_name='dcim/panels/rack_reservation_elevations.html'), + RelatedObjectsPanel(), + ], + ) @register_model_view(RackReservation, 'add', detail=False) @@ -1049,6 +1232,10 @@ class ManufacturerListView(generic.ObjectListView): @register_model_view(Manufacturer) class ManufacturerView(GetRelatedModelsMixin, generic.ObjectView): queryset = Manufacturer.objects.all() + layout = layout.SimpleLayout( + left_panels=[OrganizationalObjectPanel(), TagsPanel()], + right_panels=[RelatedObjectsPanel(), CustomFieldsPanel(), CommentsPanel()], + ) def get_extra_context(self, request, instance): return { @@ -1111,9 +1298,7 @@ class ManufacturerBulkDeleteView(generic.BulkDeleteView): @register_model_view(DeviceType, 'list', path='', detail=False) class DeviceTypeListView(generic.ObjectListView): - queryset = DeviceType.objects.annotate( - instance_count=count_related(Device, 'device_type') - ) + queryset = DeviceType.objects.all() filterset = filtersets.DeviceTypeFilterSet filterset_form = forms.DeviceTypeFilterForm table = tables.DeviceTypeTable @@ -1122,6 +1307,18 @@ class DeviceTypeListView(generic.ObjectListView): @register_model_view(DeviceType) class DeviceTypeView(GetRelatedModelsMixin, generic.ObjectView): queryset = DeviceType.objects.all() + layout = layout.SimpleLayout( + left_panels=[ + panels.DeviceTypePanel(), + TagsPanel(), + ], + right_panels=[ + RelatedObjectsPanel(), + CustomFieldsPanel(), + CommentsPanel(), + ImageAttachmentsPanel(), + ], + ) def get_extra_context(self, request, instance): return { @@ -1320,6 +1517,7 @@ class DeviceTypeImportView(generic.BulkImportView): 'interfaces': forms.InterfaceTemplateImportForm, 'rear-ports': forms.RearPortTemplateImportForm, 'front-ports': forms.FrontPortTemplateImportForm, + 'port-mappings': forms.PortTemplateMappingImportForm, 'module-bays': forms.ModuleBayTemplateImportForm, 'device-bays': forms.DeviceBayTemplateImportForm, 'inventory-items': forms.InventoryItemTemplateImportForm, @@ -1332,9 +1530,7 @@ class DeviceTypeImportView(generic.BulkImportView): @register_model_view(DeviceType, 'bulk_edit', path='edit', detail=False) class DeviceTypeBulkEditView(generic.BulkEditView): - queryset = DeviceType.objects.annotate( - instance_count=count_related(Device, 'device_type') - ) + queryset = DeviceType.objects.all() filterset = filtersets.DeviceTypeFilterSet table = tables.DeviceTypeTable form = forms.DeviceTypeBulkEditForm @@ -1349,9 +1545,7 @@ class DeviceTypeBulkRenameView(generic.BulkRenameView): @register_model_view(DeviceType, 'bulk_delete', path='delete', detail=False) class DeviceTypeBulkDeleteView(generic.BulkDeleteView): - queryset = DeviceType.objects.annotate( - instance_count=count_related(Device, 'device_type') - ) + queryset = DeviceType.objects.all() filterset = filtersets.DeviceTypeFilterSet table = tables.DeviceTypeTable @@ -1372,7 +1566,36 @@ class ModuleTypeProfileListView(generic.ObjectListView): @register_model_view(ModuleTypeProfile) class ModuleTypeProfileView(GetRelatedModelsMixin, generic.ObjectView): + template_name = 'generic/object.html' queryset = ModuleTypeProfile.objects.all() + layout = layout.SimpleLayout( + left_panels=[ + panels.ModuleTypeProfilePanel(), + TagsPanel(), + CommentsPanel(), + ], + right_panels=[ + JSONPanel(field_name='schema', title=_('Schema')), + CustomFieldsPanel(), + ], + bottom_panels=[ + ObjectsTablePanel( + model='dcim.ModuleType', + title=_('Module Types'), + filters={ + 'profile_id': lambda ctx: ctx['object'].pk, + }, + actions=[ + actions.AddObject( + 'dcim.ModuleType', + url_params={ + 'profile': lambda ctx: ctx['object'].pk, + } + ), + ], + ), + ] + ) @register_model_view(ModuleTypeProfile, 'add', detail=False) @@ -1424,9 +1647,7 @@ class ModuleTypeProfileBulkDeleteView(generic.BulkDeleteView): @register_model_view(ModuleType, 'list', path='', detail=False) class ModuleTypeListView(generic.ObjectListView): - queryset = ModuleType.objects.annotate( - instance_count=count_related(Module, 'module_type') - ) + queryset = ModuleType.objects.all() filterset = filtersets.ModuleTypeFilterSet filterset_form = forms.ModuleTypeFilterForm table = tables.ModuleTypeTable @@ -1601,6 +1822,7 @@ class ModuleTypeImportView(generic.BulkImportView): 'interfaces': forms.InterfaceTemplateImportForm, 'rear-ports': forms.RearPortTemplateImportForm, 'front-ports': forms.FrontPortTemplateImportForm, + 'port-mappings': forms.PortTemplateMappingImportForm, 'module-bays': forms.ModuleBayTemplateImportForm, } @@ -2213,6 +2435,43 @@ class DeviceListView(generic.ObjectListView): @register_model_view(Device) class DeviceView(generic.ObjectView): queryset = Device.objects.all() + layout = layout.SimpleLayout( + left_panels=[ + panels.DevicePanel(), + panels.VirtualChassisMembersPanel(), + CustomFieldsPanel(), + TagsPanel(), + CommentsPanel(), + ObjectsTablePanel( + model='dcim.VirtualDeviceContext', + filters={'device_id': lambda ctx: ctx['object'].pk}, + actions=[ + actions.AddObject('dcim.VirtualDeviceContext', url_params={'device': lambda ctx: ctx['object'].pk}), + ], + ), + ], + right_panels=[ + panels.DeviceManagementPanel(), + panels.PowerUtilizationPanel(), + ObjectsTablePanel( + model='ipam.Service', + title=_('Application Services'), + filters={'device_id': lambda ctx: ctx['object'].pk}, + actions=[ + actions.AddObject( + 'ipam.Service', + url_params={ + 'parent_object_type': lambda ctx: ContentType.objects.get_for_model(ctx['object']).pk, + 'parent': lambda ctx: ctx['object'].pk + } + ), + ], + ), + ImageAttachmentsPanel(), + panels.DeviceDimensionsPanel(), + TemplatePanel('dcim/panels/device_rack_elevations.html'), + ], + ) def get_extra_context(self, request, instance): # VirtualChassis members @@ -2225,7 +2484,7 @@ class DeviceView(generic.ObjectView): return { 'vc_members': vc_members, - 'svg_extra': f'highlight=id:{instance.pk}' + 'svg_extra': f'highlight=id:{instance.pk}', } @@ -2423,6 +2682,7 @@ class DeviceConfigContextView(ObjectConfigContextView): class DeviceRenderConfigView(ObjectRenderConfigView): queryset = Device.objects.all() base_template = 'dcim/device/base.html' + additional_permissions = ['dcim.render_config_device'] tab = ViewTab( label=_('Render Config'), weight=2100, @@ -2989,6 +3249,11 @@ class FrontPortListView(generic.ObjectListView): class FrontPortView(generic.ObjectView): queryset = FrontPort.objects.all() + def get_extra_context(self, request, instance): + return { + 'rear_port_mappings': PortMapping.objects.filter(front_port=instance).prefetch_related('rear_port'), + } + @register_model_view(FrontPort, 'add', detail=False) class FrontPortCreateView(generic.ComponentCreateView): @@ -3060,6 +3325,11 @@ class RearPortListView(generic.ObjectListView): class RearPortView(generic.ObjectView): queryset = RearPort.objects.all() + def get_extra_context(self, request, instance): + return { + 'front_port_mappings': PortMapping.objects.filter(rear_port=instance).prefetch_related('front_port'), + } + @register_model_view(RearPort, 'add', detail=False) class RearPortCreateView(generic.ComponentCreateView): diff --git a/netbox/extras/api/mixins.py b/netbox/extras/api/mixins.py index aafdf32d4..ac4617bb8 100644 --- a/netbox/extras/api/mixins.py +++ b/netbox/extras/api/mixins.py @@ -4,6 +4,7 @@ from rest_framework.renderers import JSONRenderer from rest_framework.response import Response from rest_framework.status import HTTP_400_BAD_REQUEST +from netbox.api.authentication import TokenWritePermission from netbox.api.renderers import TextRenderer from .serializers import ConfigTemplateSerializer @@ -64,12 +65,24 @@ class RenderConfigMixin(ConfigTemplateRenderMixin): """ Provides a /render-config/ endpoint for REST API views whose model may have a ConfigTemplate assigned. """ + + def get_permissions(self): + # For render_config action, check only token write ability (not model permissions) + if self.action == 'render_config': + return [TokenWritePermission()] + return super().get_permissions() + @action(detail=True, methods=['post'], url_path='render-config', renderer_classes=[JSONRenderer, TextRenderer]) def render_config(self, request, pk): """ Resolve and render the preferred ConfigTemplate for this Device. """ + # Override restrict() on the default queryset to enforce the render_config & view actions + self.queryset = self.queryset.model.objects.restrict(request.user, 'render_config').restrict( + request.user, 'view' + ) instance = self.get_object() + object_type = instance._meta.model_name configtemplate = instance.get_config_template() if not configtemplate: diff --git a/netbox/extras/api/serializers_/attachments.py b/netbox/extras/api/serializers_/attachments.py index 6507a12be..613825203 100644 --- a/netbox/extras/api/serializers_/attachments.py +++ b/netbox/extras/api/serializers_/attachments.py @@ -1,12 +1,11 @@ from django.core.exceptions import ObjectDoesNotExist -from drf_spectacular.utils import extend_schema_field from rest_framework import serializers from core.models import ObjectType from extras.models import ImageAttachment from netbox.api.fields import ContentTypeField +from netbox.api.gfk_fields import GFKSerializerField from netbox.api.serializers import ValidatedModelSerializer -from utilities.api import get_serializer_for_model __all__ = ( 'ImageAttachmentSerializer', @@ -17,7 +16,7 @@ class ImageAttachmentSerializer(ValidatedModelSerializer): object_type = ContentTypeField( queryset=ObjectType.objects.all() ) - parent = serializers.SerializerMethodField(read_only=True) + parent = GFKSerializerField(read_only=True) image_width = serializers.IntegerField(read_only=True) image_height = serializers.IntegerField(read_only=True) @@ -43,9 +42,3 @@ class ImageAttachmentSerializer(ValidatedModelSerializer): super().validate(data) return data - - @extend_schema_field(serializers.JSONField(allow_null=True)) - def get_parent(self, obj): - serializer = get_serializer_for_model(obj.parent) - context = {'request': self.context['request']} - return serializer(obj.parent, nested=True, context=context).data diff --git a/netbox/extras/api/serializers_/bookmarks.py b/netbox/extras/api/serializers_/bookmarks.py index a404d83c3..a1c56f5f0 100644 --- a/netbox/extras/api/serializers_/bookmarks.py +++ b/netbox/extras/api/serializers_/bookmarks.py @@ -1,12 +1,9 @@ -from drf_spectacular.utils import extend_schema_field -from rest_framework import serializers - from core.models import ObjectType from extras.models import Bookmark from netbox.api.fields import ContentTypeField +from netbox.api.gfk_fields import GFKSerializerField from netbox.api.serializers import ValidatedModelSerializer from users.api.serializers_.users import UserSerializer -from utilities.api import get_serializer_for_model __all__ = ( 'BookmarkSerializer', @@ -17,7 +14,7 @@ class BookmarkSerializer(ValidatedModelSerializer): object_type = ContentTypeField( queryset=ObjectType.objects.with_feature('bookmarks'), ) - object = serializers.SerializerMethodField(read_only=True) + object = GFKSerializerField(read_only=True) user = UserSerializer(nested=True) class Meta: @@ -26,9 +23,3 @@ class BookmarkSerializer(ValidatedModelSerializer): 'id', 'url', 'display', 'object_type', 'object_id', 'object', 'user', 'created', ] brief_fields = ('id', 'url', 'display', 'object_id', 'object_type') - - @extend_schema_field(serializers.JSONField(allow_null=True)) - def get_object(self, instance): - serializer = get_serializer_for_model(instance.object) - context = {'request': self.context['request']} - return serializer(instance.object, nested=True, context=context).data diff --git a/netbox/extras/api/serializers_/configcontexts.py b/netbox/extras/api/serializers_/configcontexts.py index ff85f0fc6..631dc461b 100644 --- a/netbox/extras/api/serializers_/configcontexts.py +++ b/netbox/extras/api/serializers_/configcontexts.py @@ -8,7 +8,8 @@ from dcim.api.serializers_.sites import LocationSerializer, RegionSerializer, Si from dcim.models import DeviceRole, DeviceType, Location, Platform, Region, Site, SiteGroup from extras.models import ConfigContext, ConfigContextProfile, Tag from netbox.api.fields import SerializedPKRelatedField -from netbox.api.serializers import ChangeLogMessageSerializer, ValidatedModelSerializer +from netbox.api.serializers import ChangeLogMessageSerializer, PrimaryModelSerializer, ValidatedModelSerializer +from users.api.serializers_.mixins import OwnerMixin from tenancy.api.serializers_.tenants import TenantSerializer, TenantGroupSerializer from tenancy.models import Tenant, TenantGroup from virtualization.api.serializers_.clusters import ClusterSerializer, ClusterGroupSerializer, ClusterTypeSerializer @@ -20,13 +21,7 @@ __all__ = ( ) -class ConfigContextProfileSerializer(ChangeLogMessageSerializer, ValidatedModelSerializer): - tags = serializers.SlugRelatedField( - queryset=Tag.objects.all(), - slug_field='slug', - required=False, - many=True - ) +class ConfigContextProfileSerializer(PrimaryModelSerializer): data_source = DataSourceSerializer( nested=True, required=False @@ -39,13 +34,13 @@ class ConfigContextProfileSerializer(ChangeLogMessageSerializer, ValidatedModelS class Meta: model = ConfigContextProfile fields = [ - 'id', 'url', 'display_url', 'display', 'name', 'description', 'schema', 'tags', 'comments', 'data_source', - 'data_path', 'data_file', 'data_synced', 'created', 'last_updated', + 'id', 'url', 'display_url', 'display', 'name', 'description', 'schema', 'tags', 'owner', 'comments', + 'data_source', 'data_path', 'data_file', 'data_synced', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'name', 'description') -class ConfigContextSerializer(ChangeLogMessageSerializer, ValidatedModelSerializer): +class ConfigContextSerializer(OwnerMixin, ChangeLogMessageSerializer, ValidatedModelSerializer): profile = ConfigContextProfileSerializer( nested=True, required=False, @@ -156,7 +151,7 @@ class ConfigContextSerializer(ChangeLogMessageSerializer, ValidatedModelSerializ fields = [ 'id', 'url', 'display_url', 'display', 'name', 'weight', 'profile', 'description', 'is_active', 'regions', 'site_groups', 'sites', 'locations', 'device_types', 'roles', 'platforms', 'cluster_types', - 'cluster_groups', 'clusters', 'tenant_groups', 'tenants', 'tags', 'data_source', 'data_path', 'data_file', - 'data_synced', 'data', 'created', 'last_updated', + 'cluster_groups', 'clusters', 'tenant_groups', 'tenants', 'owner', 'tags', 'data_source', 'data_path', + 'data_file', 'data_synced', 'data', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'name', 'description') diff --git a/netbox/extras/api/serializers_/configtemplates.py b/netbox/extras/api/serializers_/configtemplates.py index da3874255..ac9f40738 100644 --- a/netbox/extras/api/serializers_/configtemplates.py +++ b/netbox/extras/api/serializers_/configtemplates.py @@ -2,13 +2,19 @@ from core.api.serializers_.data import DataFileSerializer, DataSourceSerializer from extras.models import ConfigTemplate from netbox.api.serializers import ChangeLogMessageSerializer, ValidatedModelSerializer from netbox.api.serializers.features import TaggableModelSerializer +from users.api.serializers_.mixins import OwnerMixin __all__ = ( 'ConfigTemplateSerializer', ) -class ConfigTemplateSerializer(ChangeLogMessageSerializer, TaggableModelSerializer, ValidatedModelSerializer): +class ConfigTemplateSerializer( + OwnerMixin, + ChangeLogMessageSerializer, + TaggableModelSerializer, + ValidatedModelSerializer +): data_source = DataSourceSerializer( nested=True, required=False @@ -23,6 +29,6 @@ class ConfigTemplateSerializer(ChangeLogMessageSerializer, TaggableModelSerializ fields = [ 'id', 'url', 'display_url', 'display', 'name', 'description', 'environment_params', 'template_code', 'mime_type', 'file_name', 'file_extension', 'as_attachment', 'data_source', 'data_path', 'data_file', - 'auto_sync_enabled', 'data_synced', 'tags', 'created', 'last_updated', + 'auto_sync_enabled', 'data_synced', 'owner', 'tags', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'name', 'description') diff --git a/netbox/extras/api/serializers_/customfields.py b/netbox/extras/api/serializers_/customfields.py index 0d982a7e6..b12979439 100644 --- a/netbox/extras/api/serializers_/customfields.py +++ b/netbox/extras/api/serializers_/customfields.py @@ -8,6 +8,7 @@ from extras.choices import * from extras.models import CustomField, CustomFieldChoiceSet from netbox.api.fields import ChoiceField, ContentTypeField from netbox.api.serializers import ChangeLogMessageSerializer, ValidatedModelSerializer +from users.api.serializers_.mixins import OwnerMixin __all__ = ( 'CustomFieldChoiceSetSerializer', @@ -15,7 +16,7 @@ __all__ = ( ) -class CustomFieldChoiceSetSerializer(ChangeLogMessageSerializer, ValidatedModelSerializer): +class CustomFieldChoiceSetSerializer(OwnerMixin, ChangeLogMessageSerializer, ValidatedModelSerializer): base_choices = ChoiceField( choices=CustomFieldChoiceSetBaseChoices, required=False @@ -32,12 +33,12 @@ class CustomFieldChoiceSetSerializer(ChangeLogMessageSerializer, ValidatedModelS model = CustomFieldChoiceSet fields = [ 'id', 'url', 'display_url', 'display', 'name', 'description', 'base_choices', 'extra_choices', - 'order_alphabetically', 'choices_count', 'created', 'last_updated', + 'order_alphabetically', 'choices_count', 'owner', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'name', 'description', 'choices_count') -class CustomFieldSerializer(ChangeLogMessageSerializer, ValidatedModelSerializer): +class CustomFieldSerializer(OwnerMixin, ChangeLogMessageSerializer, ValidatedModelSerializer): object_types = ContentTypeField( queryset=ObjectType.objects.with_feature('custom_fields'), many=True @@ -64,8 +65,8 @@ class CustomFieldSerializer(ChangeLogMessageSerializer, ValidatedModelSerializer 'id', 'url', 'display_url', 'display', 'object_types', 'type', 'related_object_type', 'data_type', 'name', 'label', 'group_name', 'description', 'required', 'unique', 'search_weight', 'filter_logic', 'ui_visible', 'ui_editable', 'is_cloneable', 'default', 'related_object_filter', 'weight', - 'validation_minimum', 'validation_maximum', 'validation_regex', 'choice_set', 'comments', 'created', - 'last_updated', + 'validation_minimum', 'validation_maximum', 'validation_regex', 'choice_set', 'owner', 'comments', + 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'name', 'description') diff --git a/netbox/extras/api/serializers_/customlinks.py b/netbox/extras/api/serializers_/customlinks.py index 951c3aded..cca38f89f 100644 --- a/netbox/extras/api/serializers_/customlinks.py +++ b/netbox/extras/api/serializers_/customlinks.py @@ -2,13 +2,14 @@ from core.models import ObjectType from extras.models import CustomLink from netbox.api.fields import ContentTypeField from netbox.api.serializers import ChangeLogMessageSerializer, ValidatedModelSerializer +from users.api.serializers_.mixins import OwnerMixin __all__ = ( 'CustomLinkSerializer', ) -class CustomLinkSerializer(ChangeLogMessageSerializer, ValidatedModelSerializer): +class CustomLinkSerializer(OwnerMixin, ChangeLogMessageSerializer, ValidatedModelSerializer): object_types = ContentTypeField( queryset=ObjectType.objects.with_feature('custom_links'), many=True @@ -18,6 +19,6 @@ class CustomLinkSerializer(ChangeLogMessageSerializer, ValidatedModelSerializer) model = CustomLink fields = [ 'id', 'url', 'display_url', 'display', 'object_types', 'name', 'enabled', 'link_text', 'link_url', - 'weight', 'group_name', 'button_class', 'new_window', 'created', 'last_updated', + 'weight', 'group_name', 'button_class', 'new_window', 'owner', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'name') diff --git a/netbox/extras/api/serializers_/events.py b/netbox/extras/api/serializers_/events.py index 926259cf3..0d72874e7 100644 --- a/netbox/extras/api/serializers_/events.py +++ b/netbox/extras/api/serializers_/events.py @@ -1,14 +1,10 @@ -from drf_spectacular.types import OpenApiTypes -from drf_spectacular.utils import extend_schema_field -from rest_framework import serializers - from core.models import ObjectType from extras.choices import * from extras.models import EventRule, Webhook from netbox.api.fields import ChoiceField, ContentTypeField +from netbox.api.gfk_fields import GFKSerializerField from netbox.api.serializers import NetBoxModelSerializer -from utilities.api import get_serializer_for_model -from .scripts import ScriptSerializer +from users.api.serializers_.mixins import OwnerMixin __all__ = ( 'EventRuleSerializer', @@ -20,7 +16,7 @@ __all__ = ( # Event Rules # -class EventRuleSerializer(NetBoxModelSerializer): +class EventRuleSerializer(OwnerMixin, NetBoxModelSerializer): object_types = ContentTypeField( queryset=ObjectType.objects.with_feature('event_rules'), many=True @@ -29,40 +25,29 @@ class EventRuleSerializer(NetBoxModelSerializer): action_object_type = ContentTypeField( queryset=ObjectType.objects.with_feature('event_rules'), ) - action_object = serializers.SerializerMethodField(read_only=True) + action_object = GFKSerializerField(read_only=True) class Meta: model = EventRule fields = [ 'id', 'url', 'display_url', 'display', 'object_types', 'name', 'enabled', 'event_types', 'conditions', 'action_type', 'action_object_type', 'action_object_id', 'action_object', 'description', 'custom_fields', - 'tags', 'created', 'last_updated', + 'owner', 'tags', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'name', 'description') - @extend_schema_field(OpenApiTypes.OBJECT) - def get_action_object(self, instance): - context = {'request': self.context['request']} - # We need to manually instantiate the serializer for scripts - if instance.action_type == EventRuleActionChoices.SCRIPT: - script = instance.action_object - return ScriptSerializer(script, nested=True, context=context).data - else: - serializer = get_serializer_for_model(instance.action_object_type.model_class()) - return serializer(instance.action_object, nested=True, context=context).data - # # Webhooks # -class WebhookSerializer(NetBoxModelSerializer): +class WebhookSerializer(OwnerMixin, NetBoxModelSerializer): class Meta: model = Webhook fields = [ 'id', 'url', 'display_url', 'display', 'name', 'description', 'payload_url', 'http_method', 'http_content_type', 'additional_headers', 'body_template', 'secret', 'ssl_verification', 'ca_file_path', - 'custom_fields', 'tags', 'created', 'last_updated', + 'custom_fields', 'owner', 'tags', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'name', 'description') diff --git a/netbox/extras/api/serializers_/exporttemplates.py b/netbox/extras/api/serializers_/exporttemplates.py index 0d3eed442..8c4e453d6 100644 --- a/netbox/extras/api/serializers_/exporttemplates.py +++ b/netbox/extras/api/serializers_/exporttemplates.py @@ -3,13 +3,14 @@ from core.models import ObjectType from extras.models import ExportTemplate from netbox.api.fields import ContentTypeField from netbox.api.serializers import ChangeLogMessageSerializer, ValidatedModelSerializer +from users.api.serializers_.mixins import OwnerMixin __all__ = ( 'ExportTemplateSerializer', ) -class ExportTemplateSerializer(ChangeLogMessageSerializer, ValidatedModelSerializer): +class ExportTemplateSerializer(OwnerMixin, ChangeLogMessageSerializer, ValidatedModelSerializer): object_types = ContentTypeField( queryset=ObjectType.objects.with_feature('export_templates'), many=True @@ -28,6 +29,6 @@ class ExportTemplateSerializer(ChangeLogMessageSerializer, ValidatedModelSeriali fields = [ 'id', 'url', 'display_url', 'display', 'object_types', 'name', 'description', 'environment_params', 'template_code', 'mime_type', 'file_name', 'file_extension', 'as_attachment', 'data_source', - 'data_path', 'data_file', 'data_synced', 'created', 'last_updated', + 'data_path', 'data_file', 'data_synced', 'owner', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'name', 'description') diff --git a/netbox/extras/api/serializers_/journaling.py b/netbox/extras/api/serializers_/journaling.py index cba56fc32..03ec34451 100644 --- a/netbox/extras/api/serializers_/journaling.py +++ b/netbox/extras/api/serializers_/journaling.py @@ -1,14 +1,13 @@ from django.core.exceptions import ObjectDoesNotExist -from drf_spectacular.utils import extend_schema_field from rest_framework import serializers from core.models import ObjectType from extras.choices import * from extras.models import JournalEntry from netbox.api.fields import ChoiceField, ContentTypeField +from netbox.api.gfk_fields import GFKSerializerField from netbox.api.serializers import NetBoxModelSerializer from users.models import User -from utilities.api import get_serializer_for_model __all__ = ( 'JournalEntrySerializer', @@ -19,7 +18,7 @@ class JournalEntrySerializer(NetBoxModelSerializer): assigned_object_type = ContentTypeField( queryset=ObjectType.objects.all() ) - assigned_object = serializers.SerializerMethodField(read_only=True) + assigned_object = GFKSerializerField(read_only=True) created_by = serializers.PrimaryKeyRelatedField( allow_null=True, queryset=User.objects.all(), @@ -51,9 +50,3 @@ class JournalEntrySerializer(NetBoxModelSerializer): ) return super().validate(data) - - @extend_schema_field(serializers.JSONField(allow_null=True)) - def get_assigned_object(self, instance): - serializer = get_serializer_for_model(instance.assigned_object_type.model_class()) - context = {'request': self.context['request']} - return serializer(instance.assigned_object, nested=True, context=context).data diff --git a/netbox/extras/api/serializers_/notifications.py b/netbox/extras/api/serializers_/notifications.py index 9f0c7cff3..4c9d08169 100644 --- a/netbox/extras/api/serializers_/notifications.py +++ b/netbox/extras/api/serializers_/notifications.py @@ -1,13 +1,10 @@ -from drf_spectacular.utils import extend_schema_field -from rest_framework import serializers - from core.models import ObjectType from extras.models import Notification, NotificationGroup, Subscription from netbox.api.fields import ContentTypeField, SerializedPKRelatedField +from netbox.api.gfk_fields import GFKSerializerField from netbox.api.serializers import ChangeLogMessageSerializer, ValidatedModelSerializer from users.api.serializers_.users import GroupSerializer, UserSerializer from users.models import Group, User -from utilities.api import get_serializer_for_model __all__ = ( 'NotificationSerializer', @@ -20,7 +17,7 @@ class NotificationSerializer(ValidatedModelSerializer): object_type = ContentTypeField( queryset=ObjectType.objects.with_feature('notifications'), ) - object = serializers.SerializerMethodField(read_only=True) + object = GFKSerializerField(read_only=True) user = UserSerializer(nested=True) class Meta: @@ -30,12 +27,6 @@ class NotificationSerializer(ValidatedModelSerializer): ] brief_fields = ('id', 'url', 'display', 'object_type', 'object_id', 'user', 'read', 'event_type') - @extend_schema_field(serializers.JSONField(allow_null=True)) - def get_object(self, instance): - serializer = get_serializer_for_model(instance.object) - context = {'request': self.context['request']} - return serializer(instance.object, nested=True, context=context).data - class NotificationGroupSerializer(ChangeLogMessageSerializer, ValidatedModelSerializer): groups = SerializedPKRelatedField( @@ -65,7 +56,7 @@ class SubscriptionSerializer(ValidatedModelSerializer): object_type = ContentTypeField( queryset=ObjectType.objects.with_feature('notifications'), ) - object = serializers.SerializerMethodField(read_only=True) + object = GFKSerializerField(read_only=True) user = UserSerializer(nested=True) class Meta: @@ -74,9 +65,3 @@ class SubscriptionSerializer(ValidatedModelSerializer): 'id', 'url', 'display', 'object_type', 'object_id', 'object', 'user', 'created', ] brief_fields = ('id', 'url', 'display', 'object_type', 'object_id', 'user') - - @extend_schema_field(serializers.JSONField(allow_null=True)) - def get_object(self, instance): - serializer = get_serializer_for_model(instance.object) - context = {'request': self.context['request']} - return serializer(instance.object, nested=True, context=context).data diff --git a/netbox/extras/api/serializers_/savedfilters.py b/netbox/extras/api/serializers_/savedfilters.py index e7128389c..830453e6f 100644 --- a/netbox/extras/api/serializers_/savedfilters.py +++ b/netbox/extras/api/serializers_/savedfilters.py @@ -2,13 +2,14 @@ from core.models import ObjectType from extras.models import SavedFilter from netbox.api.fields import ContentTypeField from netbox.api.serializers import ChangeLogMessageSerializer, ValidatedModelSerializer +from users.api.serializers_.mixins import OwnerMixin __all__ = ( 'SavedFilterSerializer', ) -class SavedFilterSerializer(ChangeLogMessageSerializer, ValidatedModelSerializer): +class SavedFilterSerializer(OwnerMixin, ChangeLogMessageSerializer, ValidatedModelSerializer): object_types = ContentTypeField( queryset=ObjectType.objects.all(), many=True @@ -18,6 +19,6 @@ class SavedFilterSerializer(ChangeLogMessageSerializer, ValidatedModelSerializer model = SavedFilter fields = [ 'id', 'url', 'display_url', 'display', 'object_types', 'name', 'slug', 'description', 'user', 'weight', - 'enabled', 'shared', 'parameters', 'created', 'last_updated', + 'enabled', 'shared', 'parameters', 'owner', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'name', 'slug', 'description') diff --git a/netbox/extras/api/serializers_/tags.py b/netbox/extras/api/serializers_/tags.py index 7567a4543..75ca4e9d2 100644 --- a/netbox/extras/api/serializers_/tags.py +++ b/netbox/extras/api/serializers_/tags.py @@ -6,6 +6,7 @@ from extras.models import Tag, TaggedItem from netbox.api.exceptions import SerializerNotFound from netbox.api.fields import ContentTypeField, RelatedObjectCountField from netbox.api.serializers import BaseModelSerializer, ChangeLogMessageSerializer, ValidatedModelSerializer +from users.api.serializers_.mixins import OwnerMixin from utilities.api import get_serializer_for_model __all__ = ( @@ -14,7 +15,7 @@ __all__ = ( ) -class TagSerializer(ChangeLogMessageSerializer, ValidatedModelSerializer): +class TagSerializer(OwnerMixin, ChangeLogMessageSerializer, ValidatedModelSerializer): object_types = ContentTypeField( queryset=ObjectType.objects.with_feature('tags'), many=True, diff --git a/netbox/extras/api/urls.py b/netbox/extras/api/urls.py index 3757157b4..52cf28b16 100644 --- a/netbox/extras/api/urls.py +++ b/netbox/extras/api/urls.py @@ -1,10 +1,8 @@ from django.urls import include, path -from core.api.views import ObjectTypeViewSet from netbox.api.routers import NetBoxRouter from . import views - router = NetBoxRouter() router.APIRootView = views.ExtrasRootView @@ -29,9 +27,6 @@ router.register('config-context-profiles', views.ConfigContextProfileViewSet) router.register('config-templates', views.ConfigTemplateViewSet) router.register('scripts', views.ScriptViewSet, basename='script') -# TODO: Remove in NetBox v4.5 -router.register('object-types', ObjectTypeViewSet) - app_name = 'extras-api' urlpatterns = [ path('dashboard/', views.DashboardView.as_view(), name='dashboard'), diff --git a/netbox/extras/api/views.py b/netbox/extras/api/views.py index e0e31ac9b..a9f6763cd 100644 --- a/netbox/extras/api/views.py +++ b/netbox/extras/api/views.py @@ -16,7 +16,7 @@ from rq import Worker from extras import filtersets from extras.jobs import ScriptJob from extras.models import * -from netbox.api.authentication import IsAuthenticatedOrLoginNotRequired +from netbox.api.authentication import IsAuthenticatedOrLoginNotRequired, TokenWritePermission from netbox.api.features import SyncedDataMixin from netbox.api.metadata import ContentTypeMetadata from netbox.api.renderers import TextRenderer @@ -238,13 +238,22 @@ class ConfigTemplateViewSet(SyncedDataMixin, ConfigTemplateRenderMixin, NetBoxMo serializer_class = serializers.ConfigTemplateSerializer filterset_class = filtersets.ConfigTemplateFilterSet + def get_permissions(self): + # For render action, check only token write ability (not model permissions) + if self.action == 'render': + return [TokenWritePermission()] + return super().get_permissions() + @action(detail=True, methods=['post'], renderer_classes=[JSONRenderer, TextRenderer]) def render(self, request, pk): """ Render a ConfigTemplate using the context data provided (if any). If the client requests "text/plain" data, return the raw rendered content, rather than serialized JSON. """ + # Override restrict() on the default queryset to enforce the render & view actions + self.queryset = self.queryset.model.objects.restrict(request.user, 'render').restrict(request.user, 'view') configtemplate = self.get_object() + context = request.data return self.render_configtemplate(request, configtemplate, context) diff --git a/netbox/extras/filtersets.py b/netbox/extras/filtersets.py index f34b21370..cdc0c75c5 100644 --- a/netbox/extras/filtersets.py +++ b/netbox/extras/filtersets.py @@ -5,12 +5,14 @@ from django.utils.translation import gettext as _ from core.models import DataSource, ObjectType from dcim.models import DeviceRole, DeviceType, Location, Platform, Region, Site, SiteGroup -from netbox.filtersets import BaseFilterSet, ChangeLoggedModelFilterSet, NetBoxModelFilterSet +from netbox.filtersets import BaseFilterSet, ChangeLoggedModelFilterSet, NetBoxModelFilterSet, PrimaryModelFilterSet from tenancy.models import Tenant, TenantGroup +from users.filterset_mixins import OwnerFilterMixin from users.models import Group, User from utilities.filters import ( ContentTypeFilter, MultiValueCharFilter, MultiValueNumberFilter ) +from utilities.filtersets import register_filterset from virtualization.models import Cluster, ClusterGroup, ClusterType from .choices import * from .filters import TagFilter, TagIDFilter @@ -39,6 +41,7 @@ __all__ = ( ) +@register_filterset class ScriptFilterSet(BaseFilterSet): q = django_filters.CharFilter( method='search', @@ -61,7 +64,8 @@ class ScriptFilterSet(BaseFilterSet): ) -class WebhookFilterSet(NetBoxModelFilterSet): +@register_filterset +class WebhookFilterSet(OwnerFilterMixin, NetBoxModelFilterSet): q = django_filters.CharFilter( method='search', label=_('Search'), @@ -90,7 +94,8 @@ class WebhookFilterSet(NetBoxModelFilterSet): ) -class EventRuleFilterSet(NetBoxModelFilterSet): +@register_filterset +class EventRuleFilterSet(OwnerFilterMixin, NetBoxModelFilterSet): q = django_filters.CharFilter( method='search', label=_('Search'), @@ -130,7 +135,8 @@ class EventRuleFilterSet(NetBoxModelFilterSet): return queryset.filter(event_types__overlap=value) -class CustomFieldFilterSet(ChangeLoggedModelFilterSet): +@register_filterset +class CustomFieldFilterSet(OwnerFilterMixin, ChangeLoggedModelFilterSet): q = django_filters.CharFilter( method='search', label=_('Search'), @@ -179,7 +185,8 @@ class CustomFieldFilterSet(ChangeLoggedModelFilterSet): ) -class CustomFieldChoiceSetFilterSet(ChangeLoggedModelFilterSet): +@register_filterset +class CustomFieldChoiceSetFilterSet(OwnerFilterMixin, ChangeLoggedModelFilterSet): q = django_filters.CharFilter( method='search', label=_('Search'), @@ -207,7 +214,8 @@ class CustomFieldChoiceSetFilterSet(ChangeLoggedModelFilterSet): return queryset.filter(extra_choices__overlap=value) -class CustomLinkFilterSet(ChangeLoggedModelFilterSet): +@register_filterset +class CustomLinkFilterSet(OwnerFilterMixin, ChangeLoggedModelFilterSet): q = django_filters.CharFilter( method='search', label=_('Search'), @@ -237,7 +245,8 @@ class CustomLinkFilterSet(ChangeLoggedModelFilterSet): ) -class ExportTemplateFilterSet(ChangeLoggedModelFilterSet): +@register_filterset +class ExportTemplateFilterSet(OwnerFilterMixin, ChangeLoggedModelFilterSet): q = django_filters.CharFilter( method='search', label=_('Search'), @@ -275,7 +284,8 @@ class ExportTemplateFilterSet(ChangeLoggedModelFilterSet): ) -class SavedFilterFilterSet(ChangeLoggedModelFilterSet): +@register_filterset +class SavedFilterFilterSet(OwnerFilterMixin, ChangeLoggedModelFilterSet): q = django_filters.CharFilter( method='search', label=_('Search'), @@ -327,6 +337,7 @@ class SavedFilterFilterSet(ChangeLoggedModelFilterSet): return queryset.filter(Q(enabled=False) | Q(Q(shared=False) & ~Q(user=user))) +@register_filterset class TableConfigFilterSet(ChangeLoggedModelFilterSet): q = django_filters.CharFilter( method='search', @@ -380,6 +391,7 @@ class TableConfigFilterSet(ChangeLoggedModelFilterSet): return queryset.filter(Q(enabled=False) | Q(Q(shared=False) & ~Q(user=user))) +@register_filterset class BookmarkFilterSet(BaseFilterSet): created = django_filters.DateTimeFilter() object_type_id = MultiValueNumberFilter() @@ -400,6 +412,7 @@ class BookmarkFilterSet(BaseFilterSet): fields = ('id', 'object_id') +@register_filterset class NotificationGroupFilterSet(ChangeLoggedModelFilterSet): q = django_filters.CharFilter( method='search', @@ -443,6 +456,7 @@ class NotificationGroupFilterSet(ChangeLoggedModelFilterSet): ) +@register_filterset class ImageAttachmentFilterSet(ChangeLoggedModelFilterSet): q = django_filters.CharFilter( method='search', @@ -464,6 +478,7 @@ class ImageAttachmentFilterSet(ChangeLoggedModelFilterSet): ) +@register_filterset class JournalEntryFilterSet(NetBoxModelFilterSet): created = django_filters.DateTimeFromToRangeFilter() assigned_object_type = ContentTypeFilter() @@ -494,7 +509,8 @@ class JournalEntryFilterSet(NetBoxModelFilterSet): return queryset.filter(comments__icontains=value) -class TagFilterSet(ChangeLoggedModelFilterSet): +@register_filterset +class TagFilterSet(OwnerFilterMixin, ChangeLoggedModelFilterSet): q = django_filters.CharFilter( method='search', label=_('Search'), @@ -554,6 +570,7 @@ class TagFilterSet(ChangeLoggedModelFilterSet): ) +@register_filterset class TaggedItemFilterSet(BaseFilterSet): q = django_filters.CharFilter( method='search', @@ -589,7 +606,8 @@ class TaggedItemFilterSet(BaseFilterSet): ) -class ConfigContextProfileFilterSet(NetBoxModelFilterSet): +@register_filterset +class ConfigContextProfileFilterSet(PrimaryModelFilterSet): q = django_filters.CharFilter( method='search', label=_('Search'), @@ -619,7 +637,8 @@ class ConfigContextProfileFilterSet(NetBoxModelFilterSet): ) -class ConfigContextFilterSet(ChangeLoggedModelFilterSet): +@register_filterset +class ConfigContextFilterSet(OwnerFilterMixin, ChangeLoggedModelFilterSet): q = django_filters.CharFilter( method='search', label=_('Search'), @@ -788,7 +807,8 @@ class ConfigContextFilterSet(ChangeLoggedModelFilterSet): ) -class ConfigTemplateFilterSet(ChangeLoggedModelFilterSet): +@register_filterset +class ConfigTemplateFilterSet(OwnerFilterMixin, ChangeLoggedModelFilterSet): q = django_filters.CharFilter( method='search', label=_('Search'), diff --git a/netbox/extras/forms/bulk_edit.py b/netbox/extras/forms/bulk_edit.py index a85a43c2c..6805898fc 100644 --- a/netbox/extras/forms/bulk_edit.py +++ b/netbox/extras/forms/bulk_edit.py @@ -4,8 +4,8 @@ from django.utils.translation import gettext_lazy as _ from extras.choices import * from extras.models import * from netbox.events import get_event_type_choices -from netbox.forms import NetBoxModelBulkEditForm -from netbox.forms.mixins import ChangelogMessageMixin +from netbox.forms import NetBoxModelBulkEditForm, PrimaryModelBulkEditForm +from netbox.forms.mixins import ChangelogMessageMixin, OwnerMixin from utilities.forms import BulkEditForm, add_blank_choice from utilities.forms.fields import ColorField, CommentField, DynamicModelChoiceField from utilities.forms.rendering import FieldSet @@ -30,7 +30,7 @@ __all__ = ( ) -class CustomFieldBulkEditForm(ChangelogMessageMixin, BulkEditForm): +class CustomFieldBulkEditForm(ChangelogMessageMixin, OwnerMixin, BulkEditForm): pk = forms.ModelMultipleChoiceField( queryset=CustomField.objects.all(), widget=forms.MultipleHiddenInput @@ -98,7 +98,7 @@ class CustomFieldBulkEditForm(ChangelogMessageMixin, BulkEditForm): nullable_fields = ('group_name', 'description', 'choice_set') -class CustomFieldChoiceSetBulkEditForm(ChangelogMessageMixin, BulkEditForm): +class CustomFieldChoiceSetBulkEditForm(ChangelogMessageMixin, OwnerMixin, BulkEditForm): pk = forms.ModelMultipleChoiceField( queryset=CustomFieldChoiceSet.objects.all(), widget=forms.MultipleHiddenInput @@ -118,7 +118,7 @@ class CustomFieldChoiceSetBulkEditForm(ChangelogMessageMixin, BulkEditForm): nullable_fields = ('base_choices', 'description') -class CustomLinkBulkEditForm(ChangelogMessageMixin, BulkEditForm): +class CustomLinkBulkEditForm(ChangelogMessageMixin, OwnerMixin, BulkEditForm): pk = forms.ModelMultipleChoiceField( queryset=CustomLink.objects.all(), widget=forms.MultipleHiddenInput @@ -144,7 +144,7 @@ class CustomLinkBulkEditForm(ChangelogMessageMixin, BulkEditForm): ) -class ExportTemplateBulkEditForm(ChangelogMessageMixin, BulkEditForm): +class ExportTemplateBulkEditForm(ChangelogMessageMixin, OwnerMixin, BulkEditForm): pk = forms.ModelMultipleChoiceField( queryset=ExportTemplate.objects.all(), widget=forms.MultipleHiddenInput @@ -177,7 +177,7 @@ class ExportTemplateBulkEditForm(ChangelogMessageMixin, BulkEditForm): nullable_fields = ('description', 'mime_type', 'file_name', 'file_extension') -class SavedFilterBulkEditForm(ChangelogMessageMixin, BulkEditForm): +class SavedFilterBulkEditForm(ChangelogMessageMixin, OwnerMixin, BulkEditForm): pk = forms.ModelMultipleChoiceField( queryset=SavedFilter.objects.all(), widget=forms.MultipleHiddenInput @@ -233,7 +233,7 @@ class TableConfigBulkEditForm(BulkEditForm): nullable_fields = ('description',) -class WebhookBulkEditForm(NetBoxModelBulkEditForm): +class WebhookBulkEditForm(OwnerMixin, NetBoxModelBulkEditForm): model = Webhook pk = forms.ModelMultipleChoiceField( @@ -271,7 +271,7 @@ class WebhookBulkEditForm(NetBoxModelBulkEditForm): nullable_fields = ('secret', 'ca_file_path') -class EventRuleBulkEditForm(NetBoxModelBulkEditForm): +class EventRuleBulkEditForm(OwnerMixin, NetBoxModelBulkEditForm): model = EventRule pk = forms.ModelMultipleChoiceField( @@ -297,7 +297,7 @@ class EventRuleBulkEditForm(NetBoxModelBulkEditForm): nullable_fields = ('description', 'conditions') -class TagBulkEditForm(ChangelogMessageMixin, BulkEditForm): +class TagBulkEditForm(ChangelogMessageMixin, OwnerMixin, BulkEditForm): pk = forms.ModelMultipleChoiceField( queryset=Tag.objects.all(), widget=forms.MultipleHiddenInput @@ -319,17 +319,11 @@ class TagBulkEditForm(ChangelogMessageMixin, BulkEditForm): nullable_fields = ('description',) -class ConfigContextProfileBulkEditForm(NetBoxModelBulkEditForm): +class ConfigContextProfileBulkEditForm(PrimaryModelBulkEditForm): pk = forms.ModelMultipleChoiceField( queryset=ConfigContextProfile.objects.all(), widget=forms.MultipleHiddenInput ) - description = forms.CharField( - label=_('Description'), - required=False, - max_length=100 - ) - comments = CommentField() model = ConfigContextProfile fieldsets = ( @@ -338,7 +332,7 @@ class ConfigContextProfileBulkEditForm(NetBoxModelBulkEditForm): nullable_fields = ('description',) -class ConfigContextBulkEditForm(ChangelogMessageMixin, BulkEditForm): +class ConfigContextBulkEditForm(ChangelogMessageMixin, OwnerMixin, BulkEditForm): pk = forms.ModelMultipleChoiceField( queryset=ConfigContext.objects.all(), widget=forms.MultipleHiddenInput @@ -369,7 +363,7 @@ class ConfigContextBulkEditForm(ChangelogMessageMixin, BulkEditForm): nullable_fields = ('profile', 'description') -class ConfigTemplateBulkEditForm(ChangelogMessageMixin, BulkEditForm): +class ConfigTemplateBulkEditForm(ChangelogMessageMixin, OwnerMixin, BulkEditForm): pk = forms.ModelMultipleChoiceField( queryset=ConfigTemplate.objects.all(), widget=forms.MultipleHiddenInput diff --git a/netbox/extras/forms/bulk_import.py b/netbox/extras/forms/bulk_import.py index 8eae1c0a0..afe0de5d1 100644 --- a/netbox/extras/forms/bulk_import.py +++ b/netbox/extras/forms/bulk_import.py @@ -9,7 +9,7 @@ from core.models import DataFile, DataSource, ObjectType from extras.choices import * from extras.models import * from netbox.events import get_event_type_choices -from netbox.forms import NetBoxModelImportForm +from netbox.forms import NetBoxModelImportForm, OwnerCSVMixin, PrimaryModelImportForm from users.models import Group, User from utilities.forms import CSVModelForm from utilities.forms.fields import ( @@ -33,7 +33,7 @@ __all__ = ( ) -class CustomFieldImportForm(CSVModelForm): +class CustomFieldImportForm(OwnerCSVMixin, CSVModelForm): object_types = CSVMultipleContentTypeField( label=_('Object types'), queryset=ObjectType.objects.with_feature('custom_fields'), @@ -75,11 +75,11 @@ class CustomFieldImportForm(CSVModelForm): fields = ( 'name', 'label', 'group_name', 'type', 'object_types', 'related_object_type', 'required', 'unique', 'description', 'search_weight', 'filter_logic', 'default', 'choice_set', 'weight', 'validation_minimum', - 'validation_maximum', 'validation_regex', 'ui_visible', 'ui_editable', 'is_cloneable', 'comments', + 'validation_maximum', 'validation_regex', 'ui_visible', 'ui_editable', 'is_cloneable', 'owner', 'comments', ) -class CustomFieldChoiceSetImportForm(CSVModelForm): +class CustomFieldChoiceSetImportForm(OwnerCSVMixin, CSVModelForm): base_choices = CSVChoiceField( choices=CustomFieldChoiceSetBaseChoices, required=False, @@ -97,7 +97,7 @@ class CustomFieldChoiceSetImportForm(CSVModelForm): class Meta: model = CustomFieldChoiceSet fields = ( - 'name', 'description', 'base_choices', 'extra_choices', 'order_alphabetically', + 'name', 'description', 'base_choices', 'extra_choices', 'order_alphabetically', 'owner', ) def clean_extra_choices(self): @@ -114,7 +114,7 @@ class CustomFieldChoiceSetImportForm(CSVModelForm): return data -class CustomLinkImportForm(CSVModelForm): +class CustomLinkImportForm(OwnerCSVMixin, CSVModelForm): object_types = CSVMultipleContentTypeField( label=_('Object types'), queryset=ObjectType.objects.with_feature('custom_links'), @@ -131,11 +131,11 @@ class CustomLinkImportForm(CSVModelForm): model = CustomLink fields = ( 'name', 'object_types', 'enabled', 'weight', 'group_name', 'button_class', 'new_window', 'link_text', - 'link_url', + 'link_url', 'owner', ) -class ExportTemplateImportForm(CSVModelForm): +class ExportTemplateImportForm(OwnerCSVMixin, CSVModelForm): object_types = CSVMultipleContentTypeField( label=_('Object types'), queryset=ObjectType.objects.with_feature('export_templates'), @@ -146,20 +146,20 @@ class ExportTemplateImportForm(CSVModelForm): model = ExportTemplate fields = ( 'name', 'object_types', 'description', 'environment_params', 'mime_type', 'file_name', 'file_extension', - 'as_attachment', 'template_code', + 'as_attachment', 'template_code', 'owner', ) -class ConfigContextProfileImportForm(NetBoxModelImportForm): +class ConfigContextProfileImportForm(PrimaryModelImportForm): class Meta: model = ConfigContextProfile fields = [ - 'name', 'description', 'schema', 'comments', 'tags', + 'name', 'description', 'schema', 'owner', 'comments', 'tags', ] -class ConfigTemplateImportForm(CSVModelForm): +class ConfigTemplateImportForm(OwnerCSVMixin, CSVModelForm): data_source = CSVModelChoiceField( label=_('Data source'), queryset=DataSource.objects.all(), @@ -184,7 +184,7 @@ class ConfigTemplateImportForm(CSVModelForm): model = ConfigTemplate fields = ( 'name', 'description', 'template_code', 'data_source', 'data_file', 'auto_sync_enabled', - 'environment_params', 'mime_type', 'file_name', 'file_extension', 'as_attachment', 'tags', + 'environment_params', 'mime_type', 'file_name', 'file_extension', 'as_attachment', 'owner', 'tags', ) def clean(self): @@ -196,7 +196,7 @@ class ConfigTemplateImportForm(CSVModelForm): return self.cleaned_data['template_code'] -class SavedFilterImportForm(CSVModelForm): +class SavedFilterImportForm(OwnerCSVMixin, CSVModelForm): object_types = CSVMultipleContentTypeField( label=_('Object types'), queryset=ObjectType.objects.all(), @@ -206,21 +206,21 @@ class SavedFilterImportForm(CSVModelForm): class Meta: model = SavedFilter fields = ( - 'name', 'slug', 'object_types', 'description', 'weight', 'enabled', 'shared', 'parameters', + 'name', 'slug', 'object_types', 'description', 'weight', 'enabled', 'shared', 'parameters', 'owner', ) -class WebhookImportForm(NetBoxModelImportForm): +class WebhookImportForm(OwnerCSVMixin, NetBoxModelImportForm): class Meta: model = Webhook fields = ( 'name', 'payload_url', 'http_method', 'http_content_type', 'additional_headers', 'body_template', - 'secret', 'ssl_verification', 'ca_file_path', 'description', 'tags' + 'secret', 'ssl_verification', 'ca_file_path', 'description', 'owner', 'tags' ) -class EventRuleImportForm(NetBoxModelImportForm): +class EventRuleImportForm(OwnerCSVMixin, NetBoxModelImportForm): object_types = CSVMultipleContentTypeField( label=_('Object types'), queryset=ObjectType.objects.with_feature('event_rules'), @@ -241,7 +241,7 @@ class EventRuleImportForm(NetBoxModelImportForm): model = EventRule fields = ( 'name', 'description', 'enabled', 'conditions', 'object_types', 'event_types', 'action_type', - 'comments', 'tags' + 'owner', 'comments', 'tags' ) def clean(self): @@ -269,7 +269,7 @@ class EventRuleImportForm(NetBoxModelImportForm): self.instance.action_object_type = ObjectType.objects.get_for_model(script, for_concrete_model=False) -class TagImportForm(CSVModelForm): +class TagImportForm(OwnerCSVMixin, CSVModelForm): slug = SlugField() weight = forms.IntegerField( label=_('Weight'), @@ -285,7 +285,7 @@ class TagImportForm(CSVModelForm): class Meta: model = Tag fields = ( - 'name', 'slug', 'color', 'weight', 'description', 'object_types', + 'name', 'slug', 'color', 'weight', 'description', 'object_types', 'owner', ) diff --git a/netbox/extras/forms/filtersets.py b/netbox/extras/forms/filtersets.py index 751664be8..0a3036597 100644 --- a/netbox/extras/forms/filtersets.py +++ b/netbox/extras/forms/filtersets.py @@ -6,13 +6,14 @@ from dcim.models import DeviceRole, DeviceType, Location, Platform, Region, Site from extras.choices import * from extras.models import * from netbox.events import get_event_type_choices -from netbox.forms.base import NetBoxModelFilterSetForm +from netbox.forms import NetBoxModelFilterSetForm, PrimaryModelFilterSetForm from netbox.forms.mixins import SavedFiltersMixin from tenancy.models import Tenant, TenantGroup -from users.models import Group, User +from users.models import Group, Owner, User from utilities.forms import BOOLEAN_WITH_BLANK_CHOICES, FilterForm, add_blank_choice from utilities.forms.fields import ( - ContentTypeChoiceField, ContentTypeMultipleChoiceField, DynamicModelMultipleChoiceField, TagFilterField, + ContentTypeChoiceField, ContentTypeMultipleChoiceField, DynamicModelChoiceField, DynamicModelMultipleChoiceField, + TagFilterField, ) from utilities.forms.rendering import FieldSet from utilities.forms.widgets import DateTimePicker @@ -118,6 +119,11 @@ class CustomFieldFilterForm(SavedFiltersMixin, FilterForm): label=_('Validation regex'), required=False ) + owner_id = DynamicModelChoiceField( + queryset=Owner.objects.all(), + required=False, + label=_('Owner'), + ) class CustomFieldChoiceSetFilterForm(SavedFiltersMixin, FilterForm): @@ -133,6 +139,11 @@ class CustomFieldChoiceSetFilterForm(SavedFiltersMixin, FilterForm): choice = forms.CharField( required=False ) + owner_id = DynamicModelChoiceField( + queryset=Owner.objects.all(), + required=False, + label=_('Owner'), + ) class CustomLinkFilterForm(SavedFiltersMixin, FilterForm): @@ -164,6 +175,11 @@ class CustomLinkFilterForm(SavedFiltersMixin, FilterForm): label=_('Weight'), required=False ) + owner_id = DynamicModelChoiceField( + queryset=Owner.objects.all(), + required=False, + label=_('Owner'), + ) class ExportTemplateFilterForm(SavedFiltersMixin, FilterForm): @@ -210,6 +226,11 @@ class ExportTemplateFilterForm(SavedFiltersMixin, FilterForm): choices=BOOLEAN_WITH_BLANK_CHOICES ) ) + owner_id = DynamicModelChoiceField( + queryset=Owner.objects.all(), + required=False, + label=_('Owner'), + ) class ImageAttachmentFilterForm(SavedFiltersMixin, FilterForm): @@ -258,9 +279,15 @@ class SavedFilterFilterForm(SavedFiltersMixin, FilterForm): label=_('Weight'), required=False ) + owner_id = DynamicModelChoiceField( + queryset=Owner.objects.all(), + required=False, + label=_('Owner'), + ) class TableConfigFilterForm(SavedFiltersMixin, FilterForm): + model = TableConfig fieldsets = ( FieldSet('q', 'filter_id'), FieldSet('object_type_id', 'enabled', 'shared', 'weight', name=_('Attributes')), @@ -293,7 +320,7 @@ class TableConfigFilterForm(SavedFiltersMixin, FilterForm): class WebhookFilterForm(NetBoxModelFilterSetForm): model = Webhook fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('payload_url', 'http_method', 'http_content_type', name=_('Attributes')), ) http_content_type = forms.CharField( @@ -309,15 +336,18 @@ class WebhookFilterForm(NetBoxModelFilterSetForm): required=False, label=_('HTTP method') ) + owner_id = DynamicModelChoiceField( + queryset=Owner.objects.all(), + required=False, + label=_('Owner'), + ) tag = TagFilterField(model) class EventRuleFilterForm(NetBoxModelFilterSetForm): model = EventRule - tag = TagFilterField(model) - fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('object_type_id', 'event_type', 'action_type', 'enabled', name=_('Attributes')), ) object_type_id = ContentTypeMultipleChoiceField( @@ -342,6 +372,12 @@ class EventRuleFilterForm(NetBoxModelFilterSetForm): choices=BOOLEAN_WITH_BLANK_CHOICES ) ) + owner_id = DynamicModelChoiceField( + queryset=Owner.objects.all(), + required=False, + label=_('Owner'), + ) + tag = TagFilterField(model) class TagFilterForm(SavedFiltersMixin, FilterForm): @@ -356,9 +392,14 @@ class TagFilterForm(SavedFiltersMixin, FilterForm): required=False, label=_('Allowed object type') ) + owner_id = DynamicModelChoiceField( + queryset=Owner.objects.all(), + required=False, + label=_('Owner'), + ) -class ConfigContextProfileFilterForm(SavedFiltersMixin, FilterForm): +class ConfigContextProfileFilterForm(PrimaryModelFilterSetForm): model = ConfigContextProfile fieldsets = ( FieldSet('q', 'filter_id'), @@ -473,6 +514,11 @@ class ConfigContextFilterForm(SavedFiltersMixin, FilterForm): required=False, label=_('Tags') ) + owner_id = DynamicModelChoiceField( + queryset=Owner.objects.all(), + required=False, + label=_('Owner'), + ) class ConfigTemplateFilterForm(SavedFiltersMixin, FilterForm): @@ -522,6 +568,11 @@ class ConfigTemplateFilterForm(SavedFiltersMixin, FilterForm): choices=BOOLEAN_WITH_BLANK_CHOICES ) ) + owner_id = DynamicModelChoiceField( + queryset=Owner.objects.all(), + required=False, + label=_('Owner'), + ) class LocalConfigContextFilterForm(forms.Form): diff --git a/netbox/extras/forms/model_forms.py b/netbox/extras/forms/model_forms.py index 17bce784a..f5833c334 100644 --- a/netbox/extras/forms/model_forms.py +++ b/netbox/extras/forms/model_forms.py @@ -12,8 +12,8 @@ from dcim.models import DeviceRole, DeviceType, Location, Platform, Region, Site from extras.choices import * from extras.models import * from netbox.events import get_event_type_choices -from netbox.forms import NetBoxModelForm -from netbox.forms.mixins import ChangelogMessageMixin +from netbox.forms import NetBoxModelForm, PrimaryModelForm +from netbox.forms.mixins import ChangelogMessageMixin, OwnerMixin from tenancy.models import Tenant, TenantGroup from users.models import Group, User from utilities.forms import get_field_value @@ -47,7 +47,7 @@ __all__ = ( ) -class CustomFieldForm(ChangelogMessageMixin, forms.ModelForm): +class CustomFieldForm(ChangelogMessageMixin, OwnerMixin, forms.ModelForm): object_types = ContentTypeMultipleChoiceField( label=_('Object types'), queryset=ObjectType.objects.with_feature('custom_fields'), @@ -166,7 +166,7 @@ class CustomFieldForm(ChangelogMessageMixin, forms.ModelForm): del self.fields['choice_set'] -class CustomFieldChoiceSetForm(ChangelogMessageMixin, forms.ModelForm): +class CustomFieldChoiceSetForm(ChangelogMessageMixin, OwnerMixin, forms.ModelForm): # TODO: The extra_choices field definition diverge from the CustomFieldChoiceSet model extra_choices = forms.CharField( widget=ChoicesWidget(), @@ -179,7 +179,7 @@ class CustomFieldChoiceSetForm(ChangelogMessageMixin, forms.ModelForm): class Meta: model = CustomFieldChoiceSet - fields = ('name', 'description', 'base_choices', 'extra_choices', 'order_alphabetically') + fields = ('name', 'description', 'base_choices', 'extra_choices', 'order_alphabetically', 'owner') def __init__(self, *args, initial=None, **kwargs): super().__init__(*args, initial=initial, **kwargs) @@ -219,7 +219,7 @@ class CustomFieldChoiceSetForm(ChangelogMessageMixin, forms.ModelForm): return data -class CustomLinkForm(ChangelogMessageMixin, forms.ModelForm): +class CustomLinkForm(ChangelogMessageMixin, OwnerMixin, forms.ModelForm): object_types = ContentTypeMultipleChoiceField( label=_('Object types'), queryset=ObjectType.objects.with_feature('custom_links') @@ -251,7 +251,7 @@ class CustomLinkForm(ChangelogMessageMixin, forms.ModelForm): } -class ExportTemplateForm(ChangelogMessageMixin, SyncedDataMixin, forms.ModelForm): +class ExportTemplateForm(ChangelogMessageMixin, SyncedDataMixin, OwnerMixin, forms.ModelForm): object_types = ContentTypeMultipleChoiceField( label=_('Object types'), queryset=ObjectType.objects.with_feature('export_templates') @@ -293,7 +293,7 @@ class ExportTemplateForm(ChangelogMessageMixin, SyncedDataMixin, forms.ModelForm return self.cleaned_data -class SavedFilterForm(ChangelogMessageMixin, forms.ModelForm): +class SavedFilterForm(ChangelogMessageMixin, OwnerMixin, forms.ModelForm): slug = SlugField() object_types = ContentTypeMultipleChoiceField( label=_('Object types'), @@ -427,7 +427,7 @@ class SubscriptionForm(forms.ModelForm): fields = ('object_type', 'object_id') -class WebhookForm(NetBoxModelForm): +class WebhookForm(OwnerMixin, NetBoxModelForm): fieldsets = ( FieldSet('name', 'description', 'tags', name=_('Webhook')), @@ -447,7 +447,7 @@ class WebhookForm(NetBoxModelForm): } -class EventRuleForm(NetBoxModelForm): +class EventRuleForm(OwnerMixin, NetBoxModelForm): object_types = ContentTypeMultipleChoiceField( label=_('Object types'), queryset=ObjectType.objects.with_feature('event_rules'), @@ -480,7 +480,7 @@ class EventRuleForm(NetBoxModelForm): model = EventRule fields = ( 'object_types', 'name', 'description', 'enabled', 'event_types', 'conditions', 'action_type', - 'action_object_type', 'action_object_id', 'action_data', 'comments', 'tags' + 'action_object_type', 'action_object_id', 'action_data', 'owner', 'comments', 'tags' ) widgets = { 'conditions': forms.Textarea(attrs={'class': 'font-monospace'}), @@ -563,7 +563,7 @@ class EventRuleForm(NetBoxModelForm): return self.cleaned_data -class TagForm(ChangelogMessageMixin, forms.ModelForm): +class TagForm(ChangelogMessageMixin, OwnerMixin, forms.ModelForm): slug = SlugField() object_types = ContentTypeMultipleChoiceField( label=_('Object types'), @@ -582,11 +582,11 @@ class TagForm(ChangelogMessageMixin, forms.ModelForm): class Meta: model = Tag fields = [ - 'name', 'slug', 'color', 'weight', 'description', 'object_types', + 'name', 'slug', 'color', 'weight', 'description', 'object_types', 'owner', ] -class ConfigContextProfileForm(SyncedDataMixin, NetBoxModelForm): +class ConfigContextProfileForm(SyncedDataMixin, PrimaryModelForm): schema = JSONField( label=_('Schema'), required=False, @@ -606,11 +606,12 @@ class ConfigContextProfileForm(SyncedDataMixin, NetBoxModelForm): class Meta: model = ConfigContextProfile fields = ( - 'name', 'description', 'schema', 'data_source', 'data_file', 'auto_sync_enabled', 'comments', 'tags', + 'name', 'description', 'schema', 'data_source', 'data_file', 'auto_sync_enabled', 'owner', 'comments', + 'tags', ) -class ConfigContextForm(ChangelogMessageMixin, SyncedDataMixin, forms.ModelForm): +class ConfigContextForm(ChangelogMessageMixin, SyncedDataMixin, OwnerMixin, forms.ModelForm): profile = DynamicModelChoiceField( label=_('Profile'), queryset=ConfigContextProfile.objects.all(), @@ -701,7 +702,7 @@ class ConfigContextForm(ChangelogMessageMixin, SyncedDataMixin, forms.ModelForm) fields = ( 'name', 'weight', 'profile', 'description', 'data', 'is_active', 'regions', 'site_groups', 'sites', 'locations', 'roles', 'device_types', 'platforms', 'cluster_types', 'cluster_groups', 'clusters', - 'tenant_groups', 'tenants', 'tags', 'data_source', 'data_file', 'auto_sync_enabled', + 'tenant_groups', 'tenants', 'owner', 'tags', 'data_source', 'data_file', 'auto_sync_enabled', ) def __init__(self, *args, initial=None, **kwargs): @@ -727,7 +728,7 @@ class ConfigContextForm(ChangelogMessageMixin, SyncedDataMixin, forms.ModelForm) return self.cleaned_data -class ConfigTemplateForm(ChangelogMessageMixin, SyncedDataMixin, forms.ModelForm): +class ConfigTemplateForm(ChangelogMessageMixin, SyncedDataMixin, OwnerMixin, forms.ModelForm): tags = DynamicModelMultipleChoiceField( label=_('Tags'), queryset=Tag.objects.all(), diff --git a/netbox/extras/graphql/filter_mixins.py b/netbox/extras/graphql/filter_mixins.py index 7e9a970f2..4b5636c0e 100644 --- a/netbox/extras/graphql/filter_mixins.py +++ b/netbox/extras/graphql/filter_mixins.py @@ -3,9 +3,6 @@ from typing import Annotated, TYPE_CHECKING import strawberry import strawberry_django -from strawberry_django import FilterLookup - -from core.graphql.filter_mixins import BaseFilterMixin if TYPE_CHECKING: from netbox.graphql.filter_lookups import JSONFilter @@ -16,37 +13,30 @@ __all__ = ( 'JournalEntriesFilterMixin', 'TagsFilterMixin', 'ConfigContextFilterMixin', - 'TagBaseFilterMixin', ) @dataclass -class CustomFieldsFilterMixin(BaseFilterMixin): +class CustomFieldsFilterMixin: custom_field_data: Annotated['JSONFilter', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( strawberry_django.filter_field() ) @dataclass -class JournalEntriesFilterMixin(BaseFilterMixin): +class JournalEntriesFilterMixin: journal_entries: Annotated['JournalEntryFilter', strawberry.lazy('extras.graphql.filters')] | None = ( strawberry_django.filter_field() ) @dataclass -class TagsFilterMixin(BaseFilterMixin): +class TagsFilterMixin: tags: Annotated['TagFilter', strawberry.lazy('extras.graphql.filters')] | None = strawberry_django.filter_field() @dataclass -class ConfigContextFilterMixin(BaseFilterMixin): +class ConfigContextFilterMixin: local_context_data: Annotated['JSONFilter', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( strawberry_django.filter_field() ) - - -@dataclass -class TagBaseFilterMixin(BaseFilterMixin): - name: FilterLookup[str] | None = strawberry_django.filter_field() - slug: FilterLookup[str] | None = strawberry_django.filter_field() diff --git a/netbox/extras/graphql/filters.py b/netbox/extras/graphql/filters.py index 13221982c..12b773f03 100644 --- a/netbox/extras/graphql/filters.py +++ b/netbox/extras/graphql/filters.py @@ -3,12 +3,12 @@ from typing import Annotated, TYPE_CHECKING import strawberry import strawberry_django from strawberry.scalars import ID -from strawberry_django import FilterLookup +from strawberry_django import BaseFilterLookup, FilterLookup -from core.graphql.filter_mixins import BaseObjectTypeFilterMixin, ChangeLogFilterMixin from extras import models -from extras.graphql.filter_mixins import TagBaseFilterMixin, CustomFieldsFilterMixin, TagsFilterMixin -from netbox.graphql.filter_mixins import PrimaryModelFilterMixin, SyncedDataFilterMixin +from extras.graphql.filter_mixins import CustomFieldsFilterMixin, TagsFilterMixin +from netbox.graphql.filter_mixins import SyncedDataFilterMixin +from netbox.graphql.filters import ChangeLoggedModelFilter, PrimaryModelFilter if TYPE_CHECKING: from core.graphql.filters import ContentTypeFilter @@ -42,7 +42,7 @@ __all__ = ( @strawberry_django.filter_type(models.ConfigContext, lookups=True) -class ConfigContextFilter(BaseObjectTypeFilterMixin, SyncedDataFilterMixin, ChangeLogFilterMixin): +class ConfigContextFilter(SyncedDataFilterMixin, ChangeLoggedModelFilter): name: FilterLookup[str] | None = strawberry_django.filter_field() weight: Annotated['IntegerLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( strawberry_django.filter_field() @@ -99,14 +99,14 @@ class ConfigContextFilter(BaseObjectTypeFilterMixin, SyncedDataFilterMixin, Chan @strawberry_django.filter_type(models.ConfigContextProfile, lookups=True) -class ConfigContextProfileFilter(SyncedDataFilterMixin, PrimaryModelFilterMixin): +class ConfigContextProfileFilter(SyncedDataFilterMixin, PrimaryModelFilter): name: FilterLookup[str] = strawberry_django.filter_field() description: FilterLookup[str] = strawberry_django.filter_field() tags: Annotated['TagFilter', strawberry.lazy('extras.graphql.filters')] | None = strawberry_django.filter_field() @strawberry_django.filter_type(models.ConfigTemplate, lookups=True) -class ConfigTemplateFilter(BaseObjectTypeFilterMixin, SyncedDataFilterMixin, ChangeLogFilterMixin): +class ConfigTemplateFilter(SyncedDataFilterMixin, ChangeLoggedModelFilter): name: FilterLookup[str] | None = strawberry_django.filter_field() description: FilterLookup[str] | None = strawberry_django.filter_field() template_code: FilterLookup[str] | None = strawberry_django.filter_field() @@ -120,8 +120,8 @@ class ConfigTemplateFilter(BaseObjectTypeFilterMixin, SyncedDataFilterMixin, Cha @strawberry_django.filter_type(models.CustomField, lookups=True) -class CustomFieldFilter(BaseObjectTypeFilterMixin, ChangeLogFilterMixin): - type: Annotated['CustomFieldTypeEnum', strawberry.lazy('extras.graphql.enums')] | None = ( +class CustomFieldFilter(ChangeLoggedModelFilter): + type: BaseFilterLookup[Annotated['CustomFieldTypeEnum', strawberry.lazy('extras.graphql.enums')]] | None = ( strawberry_django.filter_field() ) object_types: Annotated['ContentTypeFilter', strawberry.lazy('core.graphql.filters')] | None = ( @@ -139,7 +139,9 @@ class CustomFieldFilter(BaseObjectTypeFilterMixin, ChangeLogFilterMixin): search_weight: Annotated['IntegerLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( strawberry_django.filter_field() ) - filter_logic: Annotated['CustomFieldFilterLogicEnum', strawberry.lazy('extras.graphql.enums')] | None = ( + filter_logic: ( + BaseFilterLookup[Annotated['CustomFieldFilterLogicEnum', strawberry.lazy('extras.graphql.enums')]] | None + ) = ( strawberry_django.filter_field() ) default: Annotated['JSONFilter', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( @@ -162,10 +164,14 @@ class CustomFieldFilter(BaseObjectTypeFilterMixin, ChangeLogFilterMixin): strawberry_django.filter_field() ) choice_set_id: ID | None = strawberry_django.filter_field() - ui_visible: Annotated['CustomFieldUIVisibleEnum', strawberry.lazy('extras.graphql.enums')] | None = ( + ui_visible: ( + BaseFilterLookup[Annotated['CustomFieldUIVisibleEnum', strawberry.lazy('extras.graphql.enums')]] | None + ) = ( strawberry_django.filter_field() ) - ui_editable: Annotated['CustomFieldUIEditableEnum', strawberry.lazy('extras.graphql.enums')] | None = ( + ui_editable: ( + BaseFilterLookup[Annotated['CustomFieldUIEditableEnum', strawberry.lazy('extras.graphql.enums')]] | None + ) = ( strawberry_django.filter_field() ) is_cloneable: FilterLookup[bool] | None = strawberry_django.filter_field() @@ -173,10 +179,12 @@ class CustomFieldFilter(BaseObjectTypeFilterMixin, ChangeLogFilterMixin): @strawberry_django.filter_type(models.CustomFieldChoiceSet, lookups=True) -class CustomFieldChoiceSetFilter(BaseObjectTypeFilterMixin, ChangeLogFilterMixin): +class CustomFieldChoiceSetFilter(ChangeLoggedModelFilter): name: FilterLookup[str] | None = strawberry_django.filter_field() description: FilterLookup[str] | None = strawberry_django.filter_field() - base_choices: Annotated['CustomFieldChoiceSetBaseEnum', strawberry.lazy('extras.graphql.enums')] | None = ( + base_choices: ( + BaseFilterLookup[Annotated['CustomFieldChoiceSetBaseEnum', strawberry.lazy('extras.graphql.enums')]] | None + ) = ( strawberry_django.filter_field() ) extra_choices: Annotated['StringArrayLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( @@ -186,7 +194,7 @@ class CustomFieldChoiceSetFilter(BaseObjectTypeFilterMixin, ChangeLogFilterMixin @strawberry_django.filter_type(models.CustomLink, lookups=True) -class CustomLinkFilter(BaseObjectTypeFilterMixin, ChangeLogFilterMixin): +class CustomLinkFilter(ChangeLoggedModelFilter): name: FilterLookup[str] | None = strawberry_django.filter_field() enabled: FilterLookup[bool] | None = strawberry_django.filter_field() link_text: FilterLookup[str] | None = strawberry_django.filter_field() @@ -195,14 +203,16 @@ class CustomLinkFilter(BaseObjectTypeFilterMixin, ChangeLogFilterMixin): strawberry_django.filter_field() ) group_name: FilterLookup[str] | None = strawberry_django.filter_field() - button_class: Annotated['CustomLinkButtonClassEnum', strawberry.lazy('extras.graphql.enums')] | None = ( + button_class: ( + BaseFilterLookup[Annotated['CustomLinkButtonClassEnum', strawberry.lazy('extras.graphql.enums')]] | None + ) = ( strawberry_django.filter_field() ) new_window: FilterLookup[bool] | None = strawberry_django.filter_field() @strawberry_django.filter_type(models.ExportTemplate, lookups=True) -class ExportTemplateFilter(BaseObjectTypeFilterMixin, SyncedDataFilterMixin, ChangeLogFilterMixin): +class ExportTemplateFilter(SyncedDataFilterMixin, ChangeLoggedModelFilter): name: FilterLookup[str] | None = strawberry_django.filter_field() description: FilterLookup[str] | None = strawberry_django.filter_field() template_code: FilterLookup[str] | None = strawberry_django.filter_field() @@ -216,7 +226,7 @@ class ExportTemplateFilter(BaseObjectTypeFilterMixin, SyncedDataFilterMixin, Cha @strawberry_django.filter_type(models.ImageAttachment, lookups=True) -class ImageAttachmentFilter(BaseObjectTypeFilterMixin, ChangeLogFilterMixin): +class ImageAttachmentFilter(ChangeLoggedModelFilter): object_type: Annotated['ContentTypeFilter', strawberry.lazy('core.graphql.filters')] | None = ( strawberry_django.filter_field() ) @@ -231,7 +241,7 @@ class ImageAttachmentFilter(BaseObjectTypeFilterMixin, ChangeLogFilterMixin): @strawberry_django.filter_type(models.JournalEntry, lookups=True) -class JournalEntryFilter(BaseObjectTypeFilterMixin, CustomFieldsFilterMixin, TagsFilterMixin, ChangeLogFilterMixin): +class JournalEntryFilter(CustomFieldsFilterMixin, TagsFilterMixin, ChangeLoggedModelFilter): assigned_object_type: Annotated['ContentTypeFilter', strawberry.lazy('core.graphql.filters')] | None = ( strawberry_django.filter_field() ) @@ -240,14 +250,14 @@ class JournalEntryFilter(BaseObjectTypeFilterMixin, CustomFieldsFilterMixin, Tag created_by: Annotated['UserFilter', strawberry.lazy('users.graphql.filters')] | None = ( strawberry_django.filter_field() ) - kind: Annotated['JournalEntryKindEnum', strawberry.lazy('extras.graphql.enums')] | None = ( + kind: BaseFilterLookup[Annotated['JournalEntryKindEnum', strawberry.lazy('extras.graphql.enums')]] | None = ( strawberry_django.filter_field() ) comments: FilterLookup[str] | None = strawberry_django.filter_field() @strawberry_django.filter_type(models.NotificationGroup, lookups=True) -class NotificationGroupFilter(BaseObjectTypeFilterMixin, ChangeLogFilterMixin): +class NotificationGroupFilter(ChangeLoggedModelFilter): name: FilterLookup[str] | None = strawberry_django.filter_field() description: FilterLookup[str] | None = strawberry_django.filter_field() groups: Annotated['GroupFilter', strawberry.lazy('users.graphql.filters')] | None = strawberry_django.filter_field() @@ -255,7 +265,7 @@ class NotificationGroupFilter(BaseObjectTypeFilterMixin, ChangeLogFilterMixin): @strawberry_django.filter_type(models.SavedFilter, lookups=True) -class SavedFilterFilter(BaseObjectTypeFilterMixin, ChangeLogFilterMixin): +class SavedFilterFilter(ChangeLoggedModelFilter): name: FilterLookup[str] | None = strawberry_django.filter_field() slug: FilterLookup[str] | None = strawberry_django.filter_field() description: FilterLookup[str] | None = strawberry_django.filter_field() @@ -272,7 +282,7 @@ class SavedFilterFilter(BaseObjectTypeFilterMixin, ChangeLogFilterMixin): @strawberry_django.filter_type(models.TableConfig, lookups=True) -class TableConfigFilter(BaseObjectTypeFilterMixin, ChangeLogFilterMixin): +class TableConfigFilter(ChangeLoggedModelFilter): name: FilterLookup[str] | None = strawberry_django.filter_field() description: FilterLookup[str] | None = strawberry_django.filter_field() user: Annotated['UserFilter', strawberry.lazy('users.graphql.filters')] | None = strawberry_django.filter_field() @@ -285,17 +295,23 @@ class TableConfigFilter(BaseObjectTypeFilterMixin, ChangeLogFilterMixin): @strawberry_django.filter_type(models.Tag, lookups=True) -class TagFilter(BaseObjectTypeFilterMixin, ChangeLogFilterMixin, TagBaseFilterMixin): - color: Annotated['ColorEnum', strawberry.lazy('netbox.graphql.enums')] | None = strawberry_django.filter_field() +class TagFilter(ChangeLoggedModelFilter): + name: FilterLookup[str] | None = strawberry_django.filter_field() + slug: FilterLookup[str] | None = strawberry_django.filter_field() + color: BaseFilterLookup[Annotated['ColorEnum', strawberry.lazy('netbox.graphql.enums')]] | None = ( + strawberry_django.filter_field() + ) description: FilterLookup[str] | None = strawberry_django.filter_field() @strawberry_django.filter_type(models.Webhook, lookups=True) -class WebhookFilter(BaseObjectTypeFilterMixin, CustomFieldsFilterMixin, TagsFilterMixin, ChangeLogFilterMixin): +class WebhookFilter(CustomFieldsFilterMixin, TagsFilterMixin, ChangeLoggedModelFilter): name: FilterLookup[str] | None = strawberry_django.filter_field() description: FilterLookup[str] | None = strawberry_django.filter_field() payload_url: FilterLookup[str] | None = strawberry_django.filter_field() - http_method: Annotated['WebhookHttpMethodEnum', strawberry.lazy('extras.graphql.enums')] | None = ( + http_method: ( + BaseFilterLookup[Annotated['WebhookHttpMethodEnum', strawberry.lazy('extras.graphql.enums')]] | None + ) = ( strawberry_django.filter_field() ) http_content_type: FilterLookup[str] | None = strawberry_django.filter_field() @@ -310,7 +326,7 @@ class WebhookFilter(BaseObjectTypeFilterMixin, CustomFieldsFilterMixin, TagsFilt @strawberry_django.filter_type(models.EventRule, lookups=True) -class EventRuleFilter(BaseObjectTypeFilterMixin, CustomFieldsFilterMixin, TagsFilterMixin, ChangeLogFilterMixin): +class EventRuleFilter(CustomFieldsFilterMixin, TagsFilterMixin, ChangeLoggedModelFilter): name: FilterLookup[str] | None = strawberry_django.filter_field() description: FilterLookup[str] | None = strawberry_django.filter_field() event_types: Annotated['StringArrayLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( @@ -320,7 +336,7 @@ class EventRuleFilter(BaseObjectTypeFilterMixin, CustomFieldsFilterMixin, TagsFi conditions: Annotated['JSONFilter', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( strawberry_django.filter_field() ) - action_type: Annotated['EventRuleActionEnum', strawberry.lazy('extras.graphql.enums')] | None = ( + action_type: BaseFilterLookup[Annotated['EventRuleActionEnum', strawberry.lazy('extras.graphql.enums')]] | None = ( strawberry_django.filter_field() ) action_object_type: FilterLookup[str] | None = strawberry_django.filter_field() diff --git a/netbox/extras/graphql/types.py b/netbox/extras/graphql/types.py index 97637684e..8230edea8 100644 --- a/netbox/extras/graphql/types.py +++ b/netbox/extras/graphql/types.py @@ -6,7 +6,8 @@ import strawberry_django from core.graphql.mixins import SyncedDataMixin from extras import models from extras.graphql.mixins import CustomFieldsMixin, TagsMixin -from netbox.graphql.types import BaseObjectType, ContentTypeType, NetBoxObjectType, ObjectType, OrganizationalObjectType +from netbox.graphql.types import BaseObjectType, ContentTypeType, ObjectType, PrimaryObjectType +from users.graphql.mixins import OwnerMixin from .filters import * if TYPE_CHECKING: @@ -51,7 +52,7 @@ __all__ = ( filters=ConfigContextProfileFilter, pagination=True ) -class ConfigContextProfileType(SyncedDataMixin, NetBoxObjectType): +class ConfigContextProfileType(SyncedDataMixin, PrimaryObjectType): pass @@ -61,7 +62,7 @@ class ConfigContextProfileType(SyncedDataMixin, NetBoxObjectType): filters=ConfigContextFilter, pagination=True ) -class ConfigContextType(SyncedDataMixin, ObjectType): +class ConfigContextType(SyncedDataMixin, OwnerMixin, ObjectType): profile: ConfigContextProfileType | None roles: List[Annotated["DeviceRoleType", strawberry.lazy('dcim.graphql.types')]] device_types: List[Annotated["DeviceTypeType", strawberry.lazy('dcim.graphql.types')]] @@ -84,7 +85,7 @@ class ConfigContextType(SyncedDataMixin, ObjectType): filters=ConfigTemplateFilter, pagination=True ) -class ConfigTemplateType(SyncedDataMixin, TagsMixin, ObjectType): +class ConfigTemplateType(SyncedDataMixin, OwnerMixin, TagsMixin, ObjectType): virtualmachines: List[Annotated["VirtualMachineType", strawberry.lazy('virtualization.graphql.types')]] devices: List[Annotated["DeviceType", strawberry.lazy('dcim.graphql.types')]] platforms: List[Annotated["PlatformType", strawberry.lazy('dcim.graphql.types')]] @@ -97,7 +98,7 @@ class ConfigTemplateType(SyncedDataMixin, TagsMixin, ObjectType): filters=CustomFieldFilter, pagination=True ) -class CustomFieldType(ObjectType): +class CustomFieldType(OwnerMixin, ObjectType): related_object_type: Annotated["ContentTypeType", strawberry.lazy('netbox.graphql.types')] | None choice_set: Annotated["CustomFieldChoiceSetType", strawberry.lazy('extras.graphql.types')] | None @@ -108,7 +109,7 @@ class CustomFieldType(ObjectType): filters=CustomFieldChoiceSetFilter, pagination=True ) -class CustomFieldChoiceSetType(ObjectType): +class CustomFieldChoiceSetType(OwnerMixin, ObjectType): choices_for: List[Annotated["CustomFieldType", strawberry.lazy('extras.graphql.types')]] extra_choices: List[List[str]] | None @@ -120,7 +121,7 @@ class CustomFieldChoiceSetType(ObjectType): filters=CustomLinkFilter, pagination=True ) -class CustomLinkType(ObjectType): +class CustomLinkType(OwnerMixin, ObjectType): pass @@ -130,7 +131,7 @@ class CustomLinkType(ObjectType): filters=ExportTemplateFilter, pagination=True ) -class ExportTemplateType(SyncedDataMixin, ObjectType): +class ExportTemplateType(SyncedDataMixin, OwnerMixin, ObjectType): pass @@ -180,7 +181,7 @@ class NotificationGroupType(ObjectType): filters=SavedFilterFilter, pagination=True ) -class SavedFilterType(ObjectType): +class SavedFilterType(OwnerMixin, ObjectType): user: Annotated["UserType", strawberry.lazy('users.graphql.types')] | None @@ -209,7 +210,7 @@ class TableConfigType(ObjectType): filters=TagFilter, pagination=True ) -class TagType(ObjectType): +class TagType(OwnerMixin, ObjectType): color: str object_types: List[ContentTypeType] @@ -221,7 +222,7 @@ class TagType(ObjectType): filters=WebhookFilter, pagination=True ) -class WebhookType(OrganizationalObjectType): +class WebhookType(OwnerMixin, CustomFieldsMixin, TagsMixin, ObjectType): pass @@ -231,5 +232,5 @@ class WebhookType(OrganizationalObjectType): filters=EventRuleFilter, pagination=True ) -class EventRuleType(OrganizationalObjectType): +class EventRuleType(OwnerMixin, CustomFieldsMixin, TagsMixin, ObjectType): action_object_type: Annotated["ContentTypeType", strawberry.lazy('netbox.graphql.types')] | None diff --git a/netbox/extras/migrations/0134_owner.py b/netbox/extras/migrations/0134_owner.py new file mode 100644 index 000000000..2e47cc4e2 --- /dev/null +++ b/netbox/extras/migrations/0134_owner.py @@ -0,0 +1,89 @@ +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ('extras', '0133_make_cf_minmax_decimal'), + ('users', '0015_owner'), + ] + + operations = [ + migrations.AddField( + model_name='configcontext', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='configcontextprofile', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='configtemplate', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='customfield', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='customfieldchoiceset', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='customlink', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='eventrule', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='exporttemplate', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='savedfilter', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='tag', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='webhook', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + ] diff --git a/netbox/extras/models/configs.py b/netbox/extras/models/configs.py index a9d233568..ea861e673 100644 --- a/netbox/extras/models/configs.py +++ b/netbox/extras/models/configs.py @@ -13,6 +13,7 @@ from extras.models.mixins import RenderTemplateMixin from extras.querysets import ConfigContextQuerySet from netbox.models import ChangeLoggedModel, PrimaryModel from netbox.models.features import CloningMixin, CustomLinksMixin, ExportTemplatesMixin, SyncedDataMixin, TagsMixin +from netbox.models.mixins import OwnerMixin from utilities.data import deepmerge from utilities.jsonschema import validate_schema @@ -68,7 +69,7 @@ class ConfigContextProfile(SyncedDataMixin, PrimaryModel): sync_data.alters_data = True -class ConfigContext(SyncedDataMixin, CloningMixin, CustomLinksMixin, ChangeLoggedModel): +class ConfigContext(SyncedDataMixin, CloningMixin, CustomLinksMixin, OwnerMixin, ChangeLoggedModel): """ A ConfigContext represents a set of arbitrary data available to any Device or VirtualMachine matching its assigned qualifiers (region, site, etc.). For example, the data stored in a ConfigContext assigned to site A and tenant B @@ -266,7 +267,13 @@ class ConfigContextModel(models.Model): # class ConfigTemplate( - RenderTemplateMixin, SyncedDataMixin, CustomLinksMixin, ExportTemplatesMixin, TagsMixin, ChangeLoggedModel + RenderTemplateMixin, + SyncedDataMixin, + CustomLinksMixin, + ExportTemplatesMixin, + OwnerMixin, + TagsMixin, + ChangeLoggedModel, ): name = models.CharField( verbose_name=_('name'), diff --git a/netbox/extras/models/customfields.py b/netbox/extras/models/customfields.py index c97331c69..a25e7c04d 100644 --- a/netbox/extras/models/customfields.py +++ b/netbox/extras/models/customfields.py @@ -21,6 +21,7 @@ from extras.choices import * from extras.data import CHOICE_SETS from netbox.models import ChangeLoggedModel from netbox.models.features import CloningMixin, ExportTemplatesMixin +from netbox.models.mixins import OwnerMixin from netbox.search import FieldTypes from utilities import filters from utilities.datetime import datetime_from_timestamp @@ -70,7 +71,7 @@ class CustomFieldManager(models.Manager.from_queryset(RestrictedQuerySet)): } -class CustomField(CloningMixin, ExportTemplatesMixin, ChangeLoggedModel): +class CustomField(CloningMixin, ExportTemplatesMixin, OwnerMixin, ChangeLoggedModel): object_types = models.ManyToManyField( to='contenttypes.ContentType', related_name='custom_fields', @@ -797,7 +798,7 @@ class CustomField(CloningMixin, ExportTemplatesMixin, ChangeLoggedModel): raise ValidationError(_("Required field cannot be empty.")) -class CustomFieldChoiceSet(CloningMixin, ExportTemplatesMixin, ChangeLoggedModel): +class CustomFieldChoiceSet(CloningMixin, ExportTemplatesMixin, OwnerMixin, ChangeLoggedModel): """ Represents a set of choices available for choice and multi-choice custom fields. """ diff --git a/netbox/extras/models/models.py b/netbox/extras/models/models.py index 7361d087d..52ced1835 100644 --- a/netbox/extras/models/models.py +++ b/netbox/extras/models/models.py @@ -25,6 +25,7 @@ from netbox.models import ChangeLoggedModel from netbox.models.features import ( CloningMixin, CustomFieldsMixin, CustomLinksMixin, ExportTemplatesMixin, SyncedDataMixin, TagsMixin, has_feature ) +from netbox.models.mixins import OwnerMixin from utilities.html import clean_html from utilities.jinja2 import render_jinja2 from utilities.querydict import dict_to_querydict @@ -44,7 +45,7 @@ __all__ = ( ) -class EventRule(CustomFieldsMixin, ExportTemplatesMixin, TagsMixin, ChangeLoggedModel): +class EventRule(CustomFieldsMixin, ExportTemplatesMixin, OwnerMixin, TagsMixin, ChangeLoggedModel): """ An EventRule defines an action to be taken automatically in response to a specific set of events, such as when a specific type of object is created, modified, or deleted. The action to be taken might entail transmitting a @@ -155,7 +156,7 @@ class EventRule(CustomFieldsMixin, ExportTemplatesMixin, TagsMixin, ChangeLogged return False -class Webhook(CustomFieldsMixin, ExportTemplatesMixin, TagsMixin, ChangeLoggedModel): +class Webhook(CustomFieldsMixin, ExportTemplatesMixin, TagsMixin, OwnerMixin, ChangeLoggedModel): """ A Webhook defines a request that will be sent to a remote application when an object is created, updated, and/or delete in NetBox. The request will contain a representation of the object, which the remote application can act on. @@ -294,7 +295,7 @@ class Webhook(CustomFieldsMixin, ExportTemplatesMixin, TagsMixin, ChangeLoggedMo return render_jinja2(self.payload_url, context) -class CustomLink(CloningMixin, ExportTemplatesMixin, ChangeLoggedModel): +class CustomLink(CloningMixin, ExportTemplatesMixin, OwnerMixin, ChangeLoggedModel): """ A custom link to an external representation of a NetBox object. The link text and URL fields accept Jinja2 template code to be rendered with an object as context. @@ -394,7 +395,14 @@ class CustomLink(CloningMixin, ExportTemplatesMixin, ChangeLoggedModel): } -class ExportTemplate(SyncedDataMixin, CloningMixin, ExportTemplatesMixin, ChangeLoggedModel, RenderTemplateMixin): +class ExportTemplate( + SyncedDataMixin, + CloningMixin, + ExportTemplatesMixin, + OwnerMixin, + ChangeLoggedModel, + RenderTemplateMixin, +): object_types = models.ManyToManyField( to='contenttypes.ContentType', related_name='export_templates', @@ -456,7 +464,7 @@ class ExportTemplate(SyncedDataMixin, CloningMixin, ExportTemplatesMixin, Change return _context -class SavedFilter(CloningMixin, ExportTemplatesMixin, ChangeLoggedModel): +class SavedFilter(CloningMixin, ExportTemplatesMixin, OwnerMixin, ChangeLoggedModel): """ A set of predefined keyword parameters that can be reused to filter for specific objects. """ diff --git a/netbox/extras/models/tags.py b/netbox/extras/models/tags.py index 0df76d7b3..dc98ae65b 100644 --- a/netbox/extras/models/tags.py +++ b/netbox/extras/models/tags.py @@ -8,6 +8,7 @@ from taggit.models import TagBase, GenericTaggedItemBase from netbox.choices import ColorChoices from netbox.models import ChangeLoggedModel from netbox.models.features import CloningMixin, ExportTemplatesMixin +from netbox.models.mixins import OwnerMixin from utilities.fields import ColorField from utilities.querysets import RestrictedQuerySet @@ -21,7 +22,7 @@ __all__ = ( # Tags # -class Tag(CloningMixin, ExportTemplatesMixin, ChangeLoggedModel, TagBase): +class Tag(CloningMixin, ExportTemplatesMixin, OwnerMixin, ChangeLoggedModel, TagBase): id = models.BigAutoField( primary_key=True ) diff --git a/netbox/extras/querysets.py b/netbox/extras/querysets.py index e3f6a7dcf..315ec86fb 100644 --- a/netbox/extras/querysets.py +++ b/netbox/extras/querysets.py @@ -46,6 +46,10 @@ class ConfigContextQuerySet(RestrictedQuerySet): # Match against the directly assigned role as well as any parent roles. device_roles = obj.role.get_ancestors(include_self=True) if obj.role else [] + # Match against the directly assigned platform as well as any parent platforms. + platform = getattr(obj, 'platform', None) + platforms = platform.get_ancestors(include_self=True) if platform else [] + queryset = self.filter( Q(regions__in=regions) | Q(regions=None), Q(site_groups__in=sitegroups) | Q(site_groups=None), @@ -53,7 +57,7 @@ class ConfigContextQuerySet(RestrictedQuerySet): Q(locations__in=locations) | Q(locations=None), Q(device_types=device_type) | Q(device_types=None), Q(roles__in=device_roles) | Q(roles=None), - Q(platforms=obj.platform) | Q(platforms=None), + Q(platforms__in=platforms) | Q(platforms=None), Q(cluster_types=cluster_type) | Q(cluster_types=None), Q(cluster_groups=cluster_group) | Q(cluster_groups=None), Q(clusters=cluster) | Q(clusters=None), @@ -103,7 +107,6 @@ class ConfigContextModelQuerySet(RestrictedQuerySet): "content_type__model": self.model._meta.model_name } base_query = Q( - Q(platforms=OuterRef('platform')) | Q(platforms=None), Q(cluster_types=OuterRef('cluster__type')) | Q(cluster_types=None), Q(cluster_groups=OuterRef('cluster__group')) | Q(cluster_groups=None), Q(clusters=OuterRef('cluster')) | Q(clusters=None), @@ -167,6 +170,15 @@ class ConfigContextModelQuerySet(RestrictedQuerySet): ) | Q(roles=None)), Q.AND ) + base_query.add( + (Q( + platforms__tree_id=OuterRef('platform__tree_id'), + platforms__level__lte=OuterRef('platform__level'), + platforms__lft__lte=OuterRef('platform__lft'), + platforms__rght__gte=OuterRef('platform__rght'), + ) | Q(platforms=None)), + Q.AND + ) return base_query diff --git a/netbox/extras/scripts.py b/netbox/extras/scripts.py index 4855735e2..ad9e5bcc4 100644 --- a/netbox/extras/scripts.py +++ b/netbox/extras/scripts.py @@ -1,12 +1,9 @@ import inspect -import json import logging import os import re -import yaml from django import forms -from django.conf import settings from django.core.files.storage import storages from django.core.validators import RegexValidator from django.utils import timezone @@ -490,7 +487,7 @@ class BaseScript: if self.fieldsets: fieldsets.extend(self.fieldsets) else: - fields = list(name for name, _ in self._get_vars().items()) + fields = list(name for name, __ in self._get_vars().items()) fieldsets.append((_('Script Data'), fields)) # Append the default fieldset if defined in the Meta class @@ -582,40 +579,6 @@ class BaseScript: self._log(message, obj, level=LogLevelChoices.LOG_FAILURE) self.failed = True - # - # Convenience functions - # - - def load_yaml(self, filename): - """ - Return data from a YAML file - """ - # TODO: DEPRECATED: Remove this method in v4.5 - self._log( - _("load_yaml is deprecated and will be removed in v4.5"), - level=LogLevelChoices.LOG_WARNING - ) - file_path = os.path.join(settings.SCRIPTS_ROOT, filename) - with open(file_path, 'r') as datafile: - data = yaml.load(datafile, Loader=yaml.SafeLoader) - - return data - - def load_json(self, filename): - """ - Return data from a JSON file - """ - # TODO: DEPRECATED: Remove this method in v4.5 - self._log( - _("load_json is deprecated and will be removed in v4.5"), - level=LogLevelChoices.LOG_WARNING - ) - file_path = os.path.join(settings.SCRIPTS_ROOT, filename) - with open(file_path, 'r') as datafile: - data = json.load(datafile) - - return data - # # Legacy Report functionality # diff --git a/netbox/extras/tables/tables.py b/netbox/extras/tables/tables.py index 404d7ac12..09fc5cc3c 100644 --- a/netbox/extras/tables/tables.py +++ b/netbox/extras/tables/tables.py @@ -10,7 +10,7 @@ from core.tables import JobTable from core.models import Job from netbox.constants import EMPTY_TABLE_TEXT from netbox.events import get_event_text -from netbox.tables import BaseTable, NetBoxTable, columns +from netbox.tables import BaseTable, NetBoxTable, PrimaryModelTable, columns from .columns import NotificationActionsColumn __all__ = ( @@ -109,6 +109,10 @@ class CustomFieldTable(NetBoxTable): validation_regex = tables.Column( verbose_name=_('Validation Regex'), ) + owner = tables.Column( + linkify=True, + verbose_name=_('Owner') + ) class Meta(NetBoxTable.Meta): model = CustomField @@ -146,6 +150,10 @@ class CustomFieldChoiceSetTable(NetBoxTable): verbose_name=_('Order Alphabetically'), false_mark=None ) + owner = tables.Column( + linkify=True, + verbose_name=_('Owner') + ) class Meta(NetBoxTable.Meta): model = CustomFieldChoiceSet @@ -171,6 +179,10 @@ class CustomLinkTable(NetBoxTable): verbose_name=_('New Window'), false_mark=None ) + owner = tables.Column( + linkify=True, + verbose_name=_('Owner') + ) class Meta(NetBoxTable.Meta): model = CustomLink @@ -214,6 +226,10 @@ class ExportTemplateTable(NetBoxTable): orderable=False, verbose_name=_('Synced') ) + owner = tables.Column( + linkify=True, + verbose_name=_('Owner') + ) class Meta(NetBoxTable.Meta): model = ExportTemplate @@ -294,6 +310,10 @@ class SavedFilterTable(NetBoxTable): verbose_name=_('Shared'), false_mark=None ) + owner = tables.Column( + linkify=True, + verbose_name=_('Owner') + ) def value_parameters(self, value): return json.dumps(value) @@ -450,6 +470,10 @@ class WebhookTable(NetBoxTable): ssl_validation = columns.BooleanColumn( verbose_name=_('SSL Validation') ) + owner = tables.Column( + linkify=True, + verbose_name=_('Owner') + ) tags = columns.TagColumn( url_name='extras:webhook_list' ) @@ -488,6 +512,10 @@ class EventRuleTable(NetBoxTable): func=get_event_text, orderable=False ) + owner = tables.Column( + linkify=True, + verbose_name=_('Owner') + ) tags = columns.TagColumn( url_name='extras:webhook_list' ) @@ -514,6 +542,10 @@ class TagTable(NetBoxTable): object_types = columns.ContentTypesColumn( verbose_name=_('Object Types'), ) + owner = tables.Column( + linkify=True, + verbose_name=_('Owner') + ) class Meta(NetBoxTable.Meta): model = Tag @@ -547,7 +579,7 @@ class TaggedItemTable(NetBoxTable): fields = ('id', 'content_type', 'content_object') -class ConfigContextProfileTable(NetBoxTable): +class ConfigContextProfileTable(PrimaryModelTable): name = tables.Column( verbose_name=_('Name'), linkify=True @@ -568,7 +600,7 @@ class ConfigContextProfileTable(NetBoxTable): url_name='extras:configcontextprofile_list' ) - class Meta(NetBoxTable.Meta): + class Meta(PrimaryModelTable.Meta): model = ConfigContextProfile fields = ( 'pk', 'id', 'name', 'description', 'comments', 'data_source', 'data_file', 'is_synced', 'tags', 'created', @@ -601,6 +633,10 @@ class ConfigContextTable(NetBoxTable): orderable=False, verbose_name=_('Synced') ) + owner = tables.Column( + linkify=True, + verbose_name=_('Owner') + ) tags = columns.TagColumn( url_name='extras:configcontext_list' ) @@ -649,6 +685,10 @@ class ConfigTemplateTable(NetBoxTable): verbose_name=_('As Attachment'), false_mark=None ) + owner = tables.Column( + linkify=True, + verbose_name=_('Owner') + ) tags = columns.TagColumn( url_name='extras:configtemplate_list' ) diff --git a/netbox/extras/tests/test_api.py b/netbox/extras/tests/test_api.py index 4b9c3de8d..6e6ba66b6 100644 --- a/netbox/extras/tests/test_api.py +++ b/netbox/extras/tests/test_api.py @@ -12,7 +12,8 @@ from dcim.models import Device, DeviceRole, DeviceType, Manufacturer, Rack, Loca from extras.choices import * from extras.models import * from extras.scripts import BooleanVar, IntegerVar, Script as PythonClass, StringVar -from users.models import Group, User +from users.constants import TOKEN_PREFIX +from users.models import Group, Token, User from utilities.testing import APITestCase, APIViewTestCases @@ -855,6 +856,47 @@ class ConfigTemplateTest(APIViewTestCases.APIViewTestCase): ) ConfigTemplate.objects.bulk_create(config_templates) + def test_render(self): + configtemplate = ConfigTemplate.objects.first() + + self.add_permissions('extras.render_configtemplate', 'extras.view_configtemplate') + url = reverse('extras-api:configtemplate-render', kwargs={'pk': configtemplate.pk}) + response = self.client.post(url, {'foo': 'bar'}, format='json', **self.header) + self.assertHttpStatus(response, status.HTTP_200_OK) + self.assertEqual(response.data['content'], 'Foo: bar') + + def test_render_without_permission(self): + configtemplate = ConfigTemplate.objects.first() + + # No permissions added - user has no render permission + url = reverse('extras-api:configtemplate-render', kwargs={'pk': configtemplate.pk}) + response = self.client.post(url, {'foo': 'bar'}, format='json', **self.header) + self.assertHttpStatus(response, status.HTTP_404_NOT_FOUND) + + def test_render_token_write_enabled(self): + configtemplate = ConfigTemplate.objects.first() + + self.add_permissions('extras.render_configtemplate', 'extras.view_configtemplate') + url = reverse('extras-api:configtemplate-render', kwargs={'pk': configtemplate.pk}) + + # Request without token auth should fail with PermissionDenied + response = self.client.post(url, {'foo': 'bar'}, format='json') + self.assertHttpStatus(response, status.HTTP_403_FORBIDDEN) + + # Create token with write_enabled=False + token = Token.objects.create(version=2, user=self.user, write_enabled=False) + token_header = f'Bearer {TOKEN_PREFIX}{token.key}.{token.token}' + + # Request with write-disabled token should fail + response = self.client.post(url, {'foo': 'bar'}, format='json', HTTP_AUTHORIZATION=token_header) + self.assertHttpStatus(response, status.HTTP_403_FORBIDDEN) + + # Enable write and retry + token.write_enabled = True + token.save() + response = self.client.post(url, {'foo': 'bar'}, format='json', HTTP_AUTHORIZATION=token_header) + self.assertHttpStatus(response, status.HTTP_200_OK) + class ScriptTest(APITestCase): diff --git a/netbox/extras/tests/test_event_rules.py b/netbox/extras/tests/test_event_rules.py index 0c9c25de3..082550346 100644 --- a/netbox/extras/tests/test_event_rules.py +++ b/netbox/extras/tests/test_event_rules.py @@ -363,7 +363,7 @@ class EventRuleTest(APITestCase): body = json.loads(request.body) self.assertEqual(body['event'], 'created') self.assertEqual(body['timestamp'], job.kwargs['timestamp']) - self.assertEqual(body['model'], 'site') + self.assertEqual(body['object_type'], 'dcim.site') self.assertEqual(body['username'], 'testuser') self.assertEqual(body['request_id'], str(request_id)) self.assertEqual(body['data']['name'], 'Site 1') diff --git a/netbox/extras/tests/test_scripts.py b/netbox/extras/tests/test_scripts.py index 4f5d0187a..5db15bd41 100644 --- a/netbox/extras/tests/test_scripts.py +++ b/netbox/extras/tests/test_scripts.py @@ -1,5 +1,3 @@ -import logging -import tempfile from datetime import date, datetime, timezone from decimal import Decimal @@ -9,7 +7,6 @@ from netaddr import IPAddress, IPNetwork from dcim.models import DeviceRole from extras.scripts import * -from utilities.testing import disable_logging CHOICES = ( ('ff0000', 'Red'), @@ -35,35 +32,6 @@ JSON_DATA = """ """ -class ScriptTest(TestCase): - - def test_load_yaml(self): - datafile = tempfile.NamedTemporaryFile() - datafile.write(bytes(YAML_DATA, 'UTF-8')) - datafile.seek(0) - - with disable_logging(level=logging.WARNING): - data = Script().load_yaml(datafile.name) - self.assertEqual(data, { - 'Foo': 123, - 'Bar': 456, - 'Baz': ['A', 'B', 'C'], - }) - - def test_load_json(self): - datafile = tempfile.NamedTemporaryFile() - datafile.write(bytes(JSON_DATA, 'UTF-8')) - datafile.seek(0) - - with disable_logging(level=logging.WARNING): - data = Script().load_json(datafile.name) - self.assertEqual(data, { - 'Foo': 123, - 'Bar': 456, - 'Baz': ['A', 'B', 'C'], - }) - - class ScriptVariablesTest(TestCase): def test_stringvar(self): diff --git a/netbox/extras/ui/panels.py b/netbox/extras/ui/panels.py new file mode 100644 index 000000000..4e8532a64 --- /dev/null +++ b/netbox/extras/ui/panels.py @@ -0,0 +1,75 @@ +from django.contrib.contenttypes.models import ContentType +from django.template.loader import render_to_string +from django.utils.translation import gettext_lazy as _ + +from netbox.ui import actions, panels +from utilities.data import resolve_attr_path + +__all__ = ( + 'CustomFieldsPanel', + 'ImageAttachmentsPanel', + 'TagsPanel', +) + + +class CustomFieldsPanel(panels.ObjectPanel): + """ + A panel showing the value of all custom fields defined on an object. + """ + template_name = 'extras/panels/custom_fields.html' + title = _('Custom Fields') + + def get_context(self, context): + obj = resolve_attr_path(context, self.accessor) + return { + **super().get_context(context), + 'custom_fields': obj.get_custom_fields_by_group(), + } + + def render(self, context): + ctx = self.get_context(context) + # Hide the panel if no custom fields exist + if not ctx['custom_fields']: + return '' + return render_to_string(self.template_name, self.get_context(context)) + + +class ImageAttachmentsPanel(panels.ObjectsTablePanel): + """ + A panel showing all images attached to the object. + """ + actions = [ + actions.AddObject( + 'extras.imageattachment', + url_params={ + 'object_type': lambda ctx: ContentType.objects.get_for_model(ctx['object']).pk, + 'object_id': lambda ctx: ctx['object'].pk, + 'return_url': lambda ctx: ctx['object'].get_absolute_url(), + }, + label=_('Attach an image'), + ), + ] + + def __init__(self, **kwargs): + super().__init__( + 'extras.imageattachment', + filters={ + 'object_type_id': lambda ctx: ContentType.objects.get_for_model(ctx['object']).pk, + 'object_id': lambda ctx: ctx['object'].pk, + }, + **kwargs, + ) + + +class TagsPanel(panels.ObjectPanel): + """ + A panel showing the tags assigned to the object. + """ + template_name = 'extras/panels/tags.html' + title = _('Tags') + + def get_context(self, context): + return { + **super().get_context(context), + 'object': resolve_attr_path(context, self.accessor), + } diff --git a/netbox/extras/webhooks.py b/netbox/extras/webhooks.py index a68f219bd..1492eb6ea 100644 --- a/netbox/extras/webhooks.py +++ b/netbox/extras/webhooks.py @@ -52,7 +52,6 @@ def send_webhook(event_rule, object_type, event_type, data, timestamp, username, 'event': WEBHOOK_EVENT_TYPES.get(event_type, event_type), 'timestamp': timestamp, 'object_type': '.'.join(object_type.natural_key()), - 'model': object_type.model, 'username': username, 'request_id': request.id if request else None, 'data': data, @@ -100,7 +99,7 @@ def send_webhook(event_rule, object_type, event_type, data, timestamp, username, 'data': body.encode('utf8'), } logger.info( - f"Sending {params['method']} request to {params['url']} ({context['model']} {context['event']})" + f"Sending {params['method']} request to {params['url']} ({context['object_type']} {context['event']})" ) logger.debug(params) try: diff --git a/netbox/ipam/api/serializers_/asns.py b/netbox/ipam/api/serializers_/asns.py index 8baa073f5..dd821cb61 100644 --- a/netbox/ipam/api/serializers_/asns.py +++ b/netbox/ipam/api/serializers_/asns.py @@ -1,19 +1,21 @@ from rest_framework import serializers +from dcim.models import Site from ipam.models import ASN, ASNRange, RIR -from netbox.api.fields import RelatedObjectCountField -from netbox.api.serializers import NetBoxModelSerializer +from netbox.api.fields import RelatedObjectCountField, SerializedPKRelatedField +from netbox.api.serializers import OrganizationalModelSerializer, PrimaryModelSerializer from tenancy.api.serializers_.tenants import TenantSerializer __all__ = ( 'ASNRangeSerializer', 'ASNSerializer', + 'ASNSiteSerializer', 'AvailableASNSerializer', 'RIRSerializer', ) -class RIRSerializer(NetBoxModelSerializer): +class RIRSerializer(OrganizationalModelSerializer): # Related object counts aggregate_count = RelatedObjectCountField('aggregates') @@ -21,13 +23,13 @@ class RIRSerializer(NetBoxModelSerializer): class Meta: model = RIR fields = [ - 'id', 'url', 'display_url', 'display', 'name', 'slug', 'is_private', 'description', 'tags', - 'custom_fields', 'created', 'last_updated', 'aggregate_count', + 'id', 'url', 'display_url', 'display', 'name', 'slug', 'is_private', 'description', 'owner', 'comments', + 'tags', 'custom_fields', 'created', 'last_updated', 'aggregate_count', ] brief_fields = ('id', 'url', 'display', 'name', 'slug', 'description', 'aggregate_count') -class ASNRangeSerializer(NetBoxModelSerializer): +class ASNRangeSerializer(OrganizationalModelSerializer): rir = RIRSerializer(nested=True) tenant = TenantSerializer(nested=True, required=False, allow_null=True) asn_count = serializers.IntegerField(read_only=True) @@ -36,14 +38,32 @@ class ASNRangeSerializer(NetBoxModelSerializer): model = ASNRange fields = [ 'id', 'url', 'display_url', 'display', 'name', 'slug', 'rir', 'start', 'end', 'tenant', 'description', - 'tags', 'custom_fields', 'created', 'last_updated', 'asn_count', + 'owner', 'comments', 'tags', 'custom_fields', 'created', 'last_updated', 'asn_count', ] brief_fields = ('id', 'url', 'display', 'name', 'description') -class ASNSerializer(NetBoxModelSerializer): +class ASNSiteSerializer(PrimaryModelSerializer): + """ + This serializer is meant for inclusion in ASNSerializer and is only used + to avoid a circular import of SiteSerializer. + """ + class Meta: + model = Site + fields = ('id', 'url', 'display', 'name', 'description', 'slug') + brief_fields = ('id', 'url', 'display', 'name', 'description', 'slug') + + +class ASNSerializer(PrimaryModelSerializer): rir = RIRSerializer(nested=True, required=False, allow_null=True) tenant = TenantSerializer(nested=True, required=False, allow_null=True) + sites = SerializedPKRelatedField( + queryset=Site.objects.all(), + serializer=ASNSiteSerializer, + nested=True, + required=False, + many=True + ) # Related object counts site_count = RelatedObjectCountField('sites') @@ -52,8 +72,8 @@ class ASNSerializer(NetBoxModelSerializer): class Meta: model = ASN fields = [ - 'id', 'url', 'display_url', 'display', 'asn', 'rir', 'tenant', 'description', 'comments', 'tags', - 'custom_fields', 'created', 'last_updated', 'site_count', 'provider_count', + 'id', 'url', 'display_url', 'display', 'asn', 'rir', 'tenant', 'description', 'owner', 'comments', 'tags', + 'custom_fields', 'created', 'last_updated', 'site_count', 'provider_count', 'sites', ] brief_fields = ('id', 'url', 'display', 'asn', 'description') diff --git a/netbox/ipam/api/serializers_/fhrpgroups.py b/netbox/ipam/api/serializers_/fhrpgroups.py index b5bebbc95..cf8770682 100644 --- a/netbox/ipam/api/serializers_/fhrpgroups.py +++ b/netbox/ipam/api/serializers_/fhrpgroups.py @@ -1,11 +1,8 @@ from django.contrib.contenttypes.models import ContentType -from drf_spectacular.utils import extend_schema_field -from rest_framework import serializers - from ipam.models import FHRPGroup, FHRPGroupAssignment from netbox.api.fields import ContentTypeField -from netbox.api.serializers import NetBoxModelSerializer -from utilities.api import get_serializer_for_model +from netbox.api.gfk_fields import GFKSerializerField +from netbox.api.serializers import NetBoxModelSerializer, PrimaryModelSerializer from .ip import IPAddressSerializer __all__ = ( @@ -14,14 +11,14 @@ __all__ = ( ) -class FHRPGroupSerializer(NetBoxModelSerializer): +class FHRPGroupSerializer(PrimaryModelSerializer): ip_addresses = IPAddressSerializer(nested=True, many=True, read_only=True) class Meta: model = FHRPGroup fields = [ 'id', 'name', 'url', 'display_url', 'display', 'protocol', 'group_id', 'auth_type', 'auth_key', - 'description', 'comments', 'tags', 'custom_fields', 'created', 'last_updated', 'ip_addresses', + 'description', 'owner', 'comments', 'tags', 'custom_fields', 'created', 'last_updated', 'ip_addresses', ] brief_fields = ('id', 'url', 'display', 'protocol', 'group_id', 'description') @@ -31,7 +28,7 @@ class FHRPGroupAssignmentSerializer(NetBoxModelSerializer): interface_type = ContentTypeField( queryset=ContentType.objects.all() ) - interface = serializers.SerializerMethodField(read_only=True) + interface = GFKSerializerField(read_only=True) class Meta: model = FHRPGroupAssignment @@ -40,11 +37,3 @@ class FHRPGroupAssignmentSerializer(NetBoxModelSerializer): 'priority', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'group', 'interface_type', 'interface_id', 'priority') - - @extend_schema_field(serializers.JSONField(allow_null=True)) - def get_interface(self, obj): - if obj.interface is None: - return None - serializer = get_serializer_for_model(obj.interface) - context = {'request': self.context['request']} - return serializer(obj.interface, nested=True, context=context).data diff --git a/netbox/ipam/api/serializers_/ip.py b/netbox/ipam/api/serializers_/ip.py index 5337b86f1..51f23f88d 100644 --- a/netbox/ipam/api/serializers_/ip.py +++ b/netbox/ipam/api/serializers_/ip.py @@ -1,5 +1,4 @@ from django.contrib.contenttypes.models import ContentType -from drf_spectacular.utils import extend_schema_field from rest_framework import serializers from dcim.constants import LOCATION_SCOPE_TYPES @@ -7,9 +6,9 @@ from ipam.choices import * from ipam.constants import IPADDRESS_ASSIGNMENT_MODELS from ipam.models import Aggregate, IPAddress, IPRange, Prefix from netbox.api.fields import ChoiceField, ContentTypeField -from netbox.api.serializers import NetBoxModelSerializer +from netbox.api.gfk_fields import GFKSerializerField +from netbox.api.serializers import PrimaryModelSerializer from tenancy.api.serializers_.tenants import TenantSerializer -from utilities.api import get_serializer_for_model from .asns import RIRSerializer from .nested import NestedIPAddressSerializer from .roles import RoleSerializer @@ -28,7 +27,7 @@ __all__ = ( ) -class AggregateSerializer(NetBoxModelSerializer): +class AggregateSerializer(PrimaryModelSerializer): family = ChoiceField(choices=IPAddressFamilyChoices, read_only=True) rir = RIRSerializer(nested=True) tenant = TenantSerializer(nested=True, required=False, allow_null=True) @@ -38,12 +37,12 @@ class AggregateSerializer(NetBoxModelSerializer): model = Aggregate fields = [ 'id', 'url', 'display_url', 'display', 'family', 'prefix', 'rir', 'tenant', 'date_added', 'description', - 'comments', 'tags', 'custom_fields', 'created', 'last_updated', + 'owner', 'comments', 'tags', 'custom_fields', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'family', 'prefix', 'description') -class PrefixSerializer(NetBoxModelSerializer): +class PrefixSerializer(PrimaryModelSerializer): family = ChoiceField(choices=IPAddressFamilyChoices, read_only=True) vrf = VRFSerializer(nested=True, required=False, allow_null=True) scope_type = ContentTypeField( @@ -55,7 +54,7 @@ class PrefixSerializer(NetBoxModelSerializer): default=None ) scope_id = serializers.IntegerField(allow_null=True, required=False, default=None) - scope = serializers.SerializerMethodField(read_only=True) + scope = GFKSerializerField(read_only=True) tenant = TenantSerializer(nested=True, required=False, allow_null=True) vlan = VLANSerializer(nested=True, required=False, allow_null=True) status = ChoiceField(choices=PrefixStatusChoices, required=False) @@ -68,19 +67,11 @@ class PrefixSerializer(NetBoxModelSerializer): model = Prefix fields = [ 'id', 'url', 'display_url', 'display', 'family', 'prefix', 'vrf', 'scope_type', 'scope_id', 'scope', - 'tenant', 'vlan', 'status', 'role', 'is_pool', 'mark_utilized', 'description', 'comments', 'tags', + 'tenant', 'vlan', 'status', 'role', 'is_pool', 'mark_utilized', 'description', 'owner', 'comments', 'tags', 'custom_fields', 'created', 'last_updated', 'children', '_depth', ] brief_fields = ('id', 'url', 'display', 'family', 'prefix', 'description', '_depth') - @extend_schema_field(serializers.JSONField(allow_null=True)) - def get_scope(self, obj): - if obj.scope_id is None: - return None - serializer = get_serializer_for_model(obj.scope) - context = {'request': self.context['request']} - return serializer(obj.scope, nested=True, context=context).data - class PrefixLengthSerializer(serializers.Serializer): @@ -133,7 +124,7 @@ class AvailablePrefixSerializer(serializers.Serializer): # IP ranges # -class IPRangeSerializer(NetBoxModelSerializer): +class IPRangeSerializer(PrimaryModelSerializer): family = ChoiceField(choices=IPAddressFamilyChoices, read_only=True) start_address = IPAddressField() end_address = IPAddressField() @@ -146,7 +137,7 @@ class IPRangeSerializer(NetBoxModelSerializer): model = IPRange fields = [ 'id', 'url', 'display_url', 'display', 'family', 'start_address', 'end_address', 'size', 'vrf', 'tenant', - 'status', 'role', 'description', 'comments', 'tags', 'custom_fields', 'created', 'last_updated', + 'status', 'role', 'description', 'owner', 'comments', 'tags', 'custom_fields', 'created', 'last_updated', 'mark_populated', 'mark_utilized', ] brief_fields = ('id', 'url', 'display', 'family', 'start_address', 'end_address', 'description') @@ -156,7 +147,7 @@ class IPRangeSerializer(NetBoxModelSerializer): # IP addresses # -class IPAddressSerializer(NetBoxModelSerializer): +class IPAddressSerializer(PrimaryModelSerializer): family = ChoiceField(choices=IPAddressFamilyChoices, read_only=True) address = IPAddressField() vrf = VRFSerializer(nested=True, required=False, allow_null=True) @@ -168,7 +159,7 @@ class IPAddressSerializer(NetBoxModelSerializer): required=False, allow_null=True ) - assigned_object = serializers.SerializerMethodField(read_only=True) + assigned_object = GFKSerializerField(read_only=True) nat_inside = NestedIPAddressSerializer(required=False, allow_null=True) nat_outside = NestedIPAddressSerializer(many=True, read_only=True) @@ -177,18 +168,10 @@ class IPAddressSerializer(NetBoxModelSerializer): fields = [ 'id', 'url', 'display_url', 'display', 'family', 'address', 'vrf', 'tenant', 'status', 'role', 'assigned_object_type', 'assigned_object_id', 'assigned_object', 'nat_inside', 'nat_outside', - 'dns_name', 'description', 'comments', 'tags', 'custom_fields', 'created', 'last_updated', + 'dns_name', 'description', 'owner', 'comments', 'tags', 'custom_fields', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'family', 'address', 'description') - @extend_schema_field(serializers.JSONField(allow_null=True)) - def get_assigned_object(self, obj): - if obj.assigned_object is None: - return None - serializer = get_serializer_for_model(obj.assigned_object) - context = {'request': self.context['request']} - return serializer(obj.assigned_object, nested=True, context=context).data - class AvailableIPSerializer(serializers.Serializer): """ diff --git a/netbox/ipam/api/serializers_/roles.py b/netbox/ipam/api/serializers_/roles.py index 99fd6f470..80a892659 100644 --- a/netbox/ipam/api/serializers_/roles.py +++ b/netbox/ipam/api/serializers_/roles.py @@ -1,13 +1,13 @@ from ipam.models import Role from netbox.api.fields import RelatedObjectCountField -from netbox.api.serializers import NetBoxModelSerializer +from netbox.api.serializers import OrganizationalModelSerializer __all__ = ( 'RoleSerializer', ) -class RoleSerializer(NetBoxModelSerializer): +class RoleSerializer(OrganizationalModelSerializer): # Related object counts prefix_count = RelatedObjectCountField('prefixes') @@ -16,7 +16,7 @@ class RoleSerializer(NetBoxModelSerializer): class Meta: model = Role fields = [ - 'id', 'url', 'display_url', 'display', 'name', 'slug', 'weight', 'description', 'tags', 'custom_fields', - 'created', 'last_updated', 'prefix_count', 'vlan_count', + 'id', 'url', 'display_url', 'display', 'name', 'slug', 'weight', 'description', 'owner', 'comments', 'tags', + 'custom_fields', 'created', 'last_updated', 'prefix_count', 'vlan_count', ] brief_fields = ('id', 'url', 'display', 'name', 'slug', 'description', 'prefix_count', 'vlan_count') diff --git a/netbox/ipam/api/serializers_/services.py b/netbox/ipam/api/serializers_/services.py index c7c1bb136..824fc5738 100644 --- a/netbox/ipam/api/serializers_/services.py +++ b/netbox/ipam/api/serializers_/services.py @@ -1,13 +1,11 @@ from django.contrib.contenttypes.models import ContentType -from drf_spectacular.utils import extend_schema_field -from rest_framework import serializers from ipam.choices import * from ipam.constants import SERVICE_ASSIGNMENT_MODELS from ipam.models import IPAddress, Service, ServiceTemplate from netbox.api.fields import ChoiceField, ContentTypeField, SerializedPKRelatedField -from netbox.api.serializers import NetBoxModelSerializer -from utilities.api import get_serializer_for_model +from netbox.api.gfk_fields import GFKSerializerField +from netbox.api.serializers import PrimaryModelSerializer from .ip import IPAddressSerializer __all__ = ( @@ -16,19 +14,19 @@ __all__ = ( ) -class ServiceTemplateSerializer(NetBoxModelSerializer): +class ServiceTemplateSerializer(PrimaryModelSerializer): protocol = ChoiceField(choices=ServiceProtocolChoices, required=False) class Meta: model = ServiceTemplate fields = [ - 'id', 'url', 'display_url', 'display', 'name', 'protocol', 'ports', 'description', 'comments', 'tags', - 'custom_fields', 'created', 'last_updated', + 'id', 'url', 'display_url', 'display', 'name', 'protocol', 'ports', 'description', 'owner', 'comments', + 'tags', 'custom_fields', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'name', 'protocol', 'ports', 'description') -class ServiceSerializer(NetBoxModelSerializer): +class ServiceSerializer(PrimaryModelSerializer): protocol = ChoiceField(choices=ServiceProtocolChoices, required=False) ipaddresses = SerializedPKRelatedField( queryset=IPAddress.objects.all(), @@ -40,21 +38,13 @@ class ServiceSerializer(NetBoxModelSerializer): parent_object_type = ContentTypeField( queryset=ContentType.objects.filter(SERVICE_ASSIGNMENT_MODELS) ) - parent = serializers.SerializerMethodField(read_only=True) + parent = GFKSerializerField(read_only=True) class Meta: model = Service fields = [ 'id', 'url', 'display_url', 'display', 'parent_object_type', 'parent_object_id', 'parent', 'name', - 'protocol', 'ports', 'ipaddresses', 'description', 'comments', 'tags', 'custom_fields', + 'protocol', 'ports', 'ipaddresses', 'description', 'owner', 'comments', 'tags', 'custom_fields', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'name', 'protocol', 'ports', 'description') - - @extend_schema_field(serializers.JSONField(allow_null=True)) - def get_parent(self, obj): - if obj.parent is None: - return None - serializer = get_serializer_for_model(obj.parent) - context = {'request': self.context['request']} - return serializer(obj.parent, nested=True, context=context).data diff --git a/netbox/ipam/api/serializers_/vlans.py b/netbox/ipam/api/serializers_/vlans.py index 3eada3193..871d6eadb 100644 --- a/netbox/ipam/api/serializers_/vlans.py +++ b/netbox/ipam/api/serializers_/vlans.py @@ -1,5 +1,4 @@ from django.contrib.contenttypes.models import ContentType -from drf_spectacular.utils import extend_schema_field from rest_framework import serializers from dcim.api.serializers_.sites import SiteSerializer @@ -7,9 +6,9 @@ from ipam.choices import * from ipam.constants import VLANGROUP_SCOPE_TYPES from ipam.models import VLAN, VLANGroup, VLANTranslationPolicy, VLANTranslationRule from netbox.api.fields import ChoiceField, ContentTypeField, IntegerRangeSerializer, RelatedObjectCountField -from netbox.api.serializers import NetBoxModelSerializer +from netbox.api.gfk_fields import GFKSerializerField +from netbox.api.serializers import NetBoxModelSerializer, OrganizationalModelSerializer, PrimaryModelSerializer from tenancy.api.serializers_.tenants import TenantSerializer -from utilities.api import get_serializer_for_model from vpn.api.serializers_.l2vpn import L2VPNTerminationSerializer from .nested import NestedVLANSerializer from .roles import RoleSerializer @@ -24,7 +23,7 @@ __all__ = ( ) -class VLANGroupSerializer(NetBoxModelSerializer): +class VLANGroupSerializer(OrganizationalModelSerializer): scope_type = ContentTypeField( queryset=ContentType.objects.filter( model__in=VLANGROUP_SCOPE_TYPES @@ -34,7 +33,7 @@ class VLANGroupSerializer(NetBoxModelSerializer): default=None ) scope_id = serializers.IntegerField(allow_null=True, required=False, default=None) - scope = serializers.SerializerMethodField(read_only=True) + scope = GFKSerializerField(read_only=True) vid_ranges = IntegerRangeSerializer(many=True, required=False) utilization = serializers.CharField(read_only=True) tenant = TenantSerializer(nested=True, required=False, allow_null=True) @@ -46,21 +45,14 @@ class VLANGroupSerializer(NetBoxModelSerializer): model = VLANGroup fields = [ 'id', 'url', 'display_url', 'display', 'name', 'slug', 'scope_type', 'scope_id', 'scope', 'vid_ranges', - 'tenant', 'description', 'tags', 'custom_fields', 'created', 'last_updated', 'vlan_count', 'utilization' + 'tenant', 'description', 'owner', 'comments', 'tags', 'custom_fields', 'created', 'last_updated', + 'vlan_count', 'utilization', ] brief_fields = ('id', 'url', 'display', 'name', 'slug', 'description', 'vlan_count') validators = [] - @extend_schema_field(serializers.JSONField(allow_null=True)) - def get_scope(self, obj): - if obj.scope_id is None: - return None - serializer = get_serializer_for_model(obj.scope) - context = {'request': self.context['request']} - return serializer(obj.scope, nested=True, context=context).data - -class VLANSerializer(NetBoxModelSerializer): +class VLANSerializer(PrimaryModelSerializer): site = SiteSerializer(nested=True, required=False, allow_null=True) group = VLANGroupSerializer(nested=True, required=False, allow_null=True, default=None) tenant = TenantSerializer(nested=True, required=False, allow_null=True) @@ -77,7 +69,7 @@ class VLANSerializer(NetBoxModelSerializer): model = VLAN fields = [ 'id', 'url', 'display_url', 'display', 'site', 'group', 'vid', 'name', 'tenant', 'status', 'role', - 'description', 'qinq_role', 'qinq_svlan', 'comments', 'l2vpn_termination', 'tags', 'custom_fields', + 'description', 'qinq_role', 'qinq_svlan', 'owner', 'comments', 'l2vpn_termination', 'tags', 'custom_fields', 'created', 'last_updated', 'prefix_count', ] brief_fields = ('id', 'url', 'display', 'vid', 'name', 'description') @@ -125,10 +117,10 @@ class VLANTranslationRuleSerializer(NetBoxModelSerializer): fields = ['id', 'url', 'display', 'policy', 'local_vid', 'remote_vid', 'description'] -class VLANTranslationPolicySerializer(NetBoxModelSerializer): +class VLANTranslationPolicySerializer(PrimaryModelSerializer): rules = VLANTranslationRuleSerializer(many=True, read_only=True) class Meta: model = VLANTranslationPolicy - fields = ['id', 'url', 'display', 'name', 'description', 'display', 'rules'] + fields = ['id', 'url', 'display', 'name', 'description', 'display', 'rules', 'owner', 'comments'] brief_fields = ('id', 'url', 'display', 'name', 'description') diff --git a/netbox/ipam/api/serializers_/vrfs.py b/netbox/ipam/api/serializers_/vrfs.py index a23909108..67630f83c 100644 --- a/netbox/ipam/api/serializers_/vrfs.py +++ b/netbox/ipam/api/serializers_/vrfs.py @@ -1,6 +1,6 @@ from ipam.models import RouteTarget, VRF from netbox.api.fields import RelatedObjectCountField, SerializedPKRelatedField -from netbox.api.serializers import NetBoxModelSerializer +from netbox.api.serializers import PrimaryModelSerializer from tenancy.api.serializers_.tenants import TenantSerializer __all__ = ( @@ -9,19 +9,19 @@ __all__ = ( ) -class RouteTargetSerializer(NetBoxModelSerializer): +class RouteTargetSerializer(PrimaryModelSerializer): tenant = TenantSerializer(nested=True, required=False, allow_null=True) class Meta: model = RouteTarget fields = [ - 'id', 'url', 'display_url', 'display', 'name', 'tenant', 'description', 'comments', 'tags', + 'id', 'url', 'display_url', 'display', 'name', 'tenant', 'description', 'owner', 'comments', 'tags', 'custom_fields', 'created', 'last_updated', ] brief_fields = ('id', 'url', 'display', 'name', 'description') -class VRFSerializer(NetBoxModelSerializer): +class VRFSerializer(PrimaryModelSerializer): tenant = TenantSerializer(nested=True, required=False, allow_null=True) import_targets = SerializedPKRelatedField( queryset=RouteTarget.objects.all(), @@ -43,8 +43,8 @@ class VRFSerializer(NetBoxModelSerializer): class Meta: model = VRF fields = [ - 'id', 'url', 'display_url', 'display', 'name', 'rd', 'tenant', 'enforce_unique', 'description', 'comments', - 'import_targets', 'export_targets', 'tags', 'custom_fields', 'created', 'last_updated', 'ipaddress_count', - 'prefix_count', + 'id', 'url', 'display_url', 'display', 'name', 'rd', 'tenant', 'enforce_unique', 'description', 'owner', + 'comments', 'import_targets', 'export_targets', 'tags', 'custom_fields', 'created', 'last_updated', + 'ipaddress_count', 'prefix_count', ] brief_fields = ('id', 'url', 'display', 'name', 'rd', 'description', 'prefix_count') diff --git a/netbox/ipam/filtersets.py b/netbox/ipam/filtersets.py index 1e2ed91ed..5063b6a9c 100644 --- a/netbox/ipam/filtersets.py +++ b/netbox/ipam/filtersets.py @@ -1,6 +1,5 @@ import django_filters import netaddr -from dcim.base_filtersets import ScopedFilterSet from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ValidationError from django.db.models import Q @@ -10,13 +9,16 @@ from drf_spectacular.utils import extend_schema_field from netaddr.core import AddrFormatError from circuits.models import Provider +from dcim.base_filtersets import ScopedFilterSet from dcim.models import Device, Interface, Region, Site, SiteGroup -from netbox.filtersets import ChangeLoggedModelFilterSet, OrganizationalModelFilterSet, NetBoxModelFilterSet +from netbox.filtersets import ( + ChangeLoggedModelFilterSet, OrganizationalModelFilterSet, NetBoxModelFilterSet, PrimaryModelFilterSet, +) from tenancy.filtersets import ContactModelFilterSet, TenancyFilterSet - from utilities.filters import ( ContentTypeFilter, MultiValueCharFilter, MultiValueNumberFilter, NumericArrayFilter, TreeNodeMultipleChoiceFilter, ) +from utilities.filtersets import register_filterset from virtualization.models import VirtualMachine, VMInterface from vpn.models import L2VPN from .choices import * @@ -45,7 +47,8 @@ __all__ = ( ) -class VRFFilterSet(NetBoxModelFilterSet, TenancyFilterSet): +@register_filterset +class VRFFilterSet(PrimaryModelFilterSet, TenancyFilterSet): import_target_id = django_filters.ModelMultipleChoiceFilter( field_name='import_targets', queryset=RouteTarget.objects.all(), @@ -83,7 +86,8 @@ class VRFFilterSet(NetBoxModelFilterSet, TenancyFilterSet): fields = ('id', 'name', 'rd', 'enforce_unique', 'description') -class RouteTargetFilterSet(NetBoxModelFilterSet, TenancyFilterSet): +@register_filterset +class RouteTargetFilterSet(PrimaryModelFilterSet, TenancyFilterSet): importing_vrf_id = django_filters.ModelMultipleChoiceFilter( field_name='importing_vrfs', queryset=VRF.objects.all(), @@ -142,6 +146,7 @@ class RouteTargetFilterSet(NetBoxModelFilterSet, TenancyFilterSet): fields = ('id', 'name', 'description') +@register_filterset class RIRFilterSet(OrganizationalModelFilterSet): class Meta: @@ -149,7 +154,8 @@ class RIRFilterSet(OrganizationalModelFilterSet): fields = ('id', 'name', 'slug', 'is_private', 'description') -class AggregateFilterSet(NetBoxModelFilterSet, TenancyFilterSet, ContactModelFilterSet): +@register_filterset +class AggregateFilterSet(PrimaryModelFilterSet, TenancyFilterSet, ContactModelFilterSet): family = django_filters.NumberFilter( field_name='prefix', lookup_expr='family' @@ -196,6 +202,7 @@ class AggregateFilterSet(NetBoxModelFilterSet, TenancyFilterSet, ContactModelFil return queryset.none() +@register_filterset class ASNRangeFilterSet(OrganizationalModelFilterSet, TenancyFilterSet): rir_id = django_filters.ModelMultipleChoiceFilter( queryset=RIR.objects.all(), @@ -221,7 +228,8 @@ class ASNRangeFilterSet(OrganizationalModelFilterSet, TenancyFilterSet): ) -class ASNFilterSet(OrganizationalModelFilterSet, TenancyFilterSet): +@register_filterset +class ASNFilterSet(PrimaryModelFilterSet, TenancyFilterSet): rir_id = django_filters.ModelMultipleChoiceFilter( queryset=RIR.objects.all(), label=_('RIR (ID)'), @@ -283,6 +291,7 @@ class ASNFilterSet(OrganizationalModelFilterSet, TenancyFilterSet): return queryset.filter(qs_filter) +@register_filterset class RoleFilterSet(OrganizationalModelFilterSet): class Meta: @@ -290,7 +299,8 @@ class RoleFilterSet(OrganizationalModelFilterSet): fields = ('id', 'name', 'slug', 'description', 'weight') -class PrefixFilterSet(NetBoxModelFilterSet, ScopedFilterSet, TenancyFilterSet, ContactModelFilterSet): +@register_filterset +class PrefixFilterSet(PrimaryModelFilterSet, ScopedFilterSet, TenancyFilterSet, ContactModelFilterSet): family = django_filters.NumberFilter( field_name='prefix', lookup_expr='family' @@ -456,7 +466,8 @@ class PrefixFilterSet(NetBoxModelFilterSet, ScopedFilterSet, TenancyFilterSet, C ).distinct() -class IPRangeFilterSet(TenancyFilterSet, NetBoxModelFilterSet, ContactModelFilterSet): +@register_filterset +class IPRangeFilterSet(PrimaryModelFilterSet, TenancyFilterSet, ContactModelFilterSet): family = django_filters.NumberFilter( field_name='start_address', lookup_expr='family' @@ -548,7 +559,8 @@ class IPRangeFilterSet(TenancyFilterSet, NetBoxModelFilterSet, ContactModelFilte return queryset.filter(q) -class IPAddressFilterSet(NetBoxModelFilterSet, TenancyFilterSet, ContactModelFilterSet): +@register_filterset +class IPAddressFilterSet(PrimaryModelFilterSet, TenancyFilterSet, ContactModelFilterSet): family = django_filters.NumberFilter( field_name='address', lookup_expr='family' @@ -784,7 +796,8 @@ class IPAddressFilterSet(NetBoxModelFilterSet, TenancyFilterSet, ContactModelFil ) -class FHRPGroupFilterSet(NetBoxModelFilterSet): +@register_filterset +class FHRPGroupFilterSet(PrimaryModelFilterSet): protocol = django_filters.MultipleChoiceFilter( choices=FHRPGroupProtocolChoices ) @@ -831,6 +844,7 @@ class FHRPGroupFilterSet(NetBoxModelFilterSet): return queryset.filter(ip_filter) +@register_filterset class FHRPGroupAssignmentFilterSet(ChangeLoggedModelFilterSet): interface_type = ContentTypeFilter() group_id = django_filters.ModelMultipleChoiceFilter( @@ -885,6 +899,7 @@ class FHRPGroupAssignmentFilterSet(ChangeLoggedModelFilterSet): ) +@register_filterset class VLANGroupFilterSet(OrganizationalModelFilterSet, TenancyFilterSet): scope_type = ContentTypeFilter() region = django_filters.NumberFilter( @@ -934,7 +949,8 @@ class VLANGroupFilterSet(OrganizationalModelFilterSet, TenancyFilterSet): ) -class VLANFilterSet(NetBoxModelFilterSet, TenancyFilterSet): +@register_filterset +class VLANFilterSet(PrimaryModelFilterSet, TenancyFilterSet): region_id = TreeNodeMultipleChoiceFilter( queryset=Region.objects.all(), field_name='site__region', @@ -1085,7 +1101,8 @@ class VLANFilterSet(NetBoxModelFilterSet, TenancyFilterSet): ).distinct() -class VLANTranslationPolicyFilterSet(NetBoxModelFilterSet): +@register_filterset +class VLANTranslationPolicyFilterSet(PrimaryModelFilterSet): class Meta: model = VLANTranslationPolicy @@ -1101,6 +1118,7 @@ class VLANTranslationPolicyFilterSet(NetBoxModelFilterSet): return queryset.filter(qs_filter) +@register_filterset class VLANTranslationRuleFilterSet(NetBoxModelFilterSet): policy_id = django_filters.ModelMultipleChoiceFilter( queryset=VLANTranslationPolicy.objects.all(), @@ -1132,7 +1150,8 @@ class VLANTranslationRuleFilterSet(NetBoxModelFilterSet): return queryset.filter(qs_filter) -class ServiceTemplateFilterSet(NetBoxModelFilterSet): +@register_filterset +class ServiceTemplateFilterSet(PrimaryModelFilterSet): port = NumericArrayFilter( field_name='ports', lookup_expr='contains' @@ -1152,7 +1171,8 @@ class ServiceTemplateFilterSet(NetBoxModelFilterSet): return queryset.filter(qs_filter) -class ServiceFilterSet(ContactModelFilterSet, NetBoxModelFilterSet): +@register_filterset +class ServiceFilterSet(ContactModelFilterSet, PrimaryModelFilterSet): parent_object_type = ContentTypeFilter() device = MultiValueCharFilter( method='filter_device', diff --git a/netbox/ipam/forms/bulk_edit.py b/netbox/ipam/forms/bulk_edit.py index 864630bd4..b1837cfc1 100644 --- a/netbox/ipam/forms/bulk_edit.py +++ b/netbox/ipam/forms/bulk_edit.py @@ -9,11 +9,11 @@ from ipam.choices import * from ipam.constants import * from ipam.models import * from ipam.models import ASN -from netbox.forms import NetBoxModelBulkEditForm +from netbox.forms import NetBoxModelBulkEditForm, OrganizationalModelBulkEditForm, PrimaryModelBulkEditForm from tenancy.models import Tenant from utilities.forms import add_blank_choice, get_field_value from utilities.forms.fields import ( - CommentField, ContentTypeChoiceField, DynamicModelChoiceField, DynamicModelMultipleChoiceField, NumericArrayField, + ContentTypeChoiceField, DynamicModelChoiceField, DynamicModelMultipleChoiceField, NumericArrayField, NumericRangeArrayField, ) from utilities.forms.rendering import FieldSet @@ -41,7 +41,7 @@ __all__ = ( ) -class VRFBulkEditForm(NetBoxModelBulkEditForm): +class VRFBulkEditForm(PrimaryModelBulkEditForm): tenant = DynamicModelChoiceField( label=_('Tenant'), queryset=Tenant.objects.all(), @@ -52,12 +52,6 @@ class VRFBulkEditForm(NetBoxModelBulkEditForm): widget=BulkEditNullBooleanSelect(), label=_('Enforce unique space') ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = VRF fieldsets = ( @@ -66,18 +60,12 @@ class VRFBulkEditForm(NetBoxModelBulkEditForm): nullable_fields = ('tenant', 'description', 'comments') -class RouteTargetBulkEditForm(NetBoxModelBulkEditForm): +class RouteTargetBulkEditForm(PrimaryModelBulkEditForm): tenant = DynamicModelChoiceField( label=_('Tenant'), queryset=Tenant.objects.all(), required=False ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = RouteTarget fieldsets = ( @@ -86,26 +74,21 @@ class RouteTargetBulkEditForm(NetBoxModelBulkEditForm): nullable_fields = ('tenant', 'description', 'comments') -class RIRBulkEditForm(NetBoxModelBulkEditForm): +class RIRBulkEditForm(OrganizationalModelBulkEditForm): is_private = forms.NullBooleanField( label=_('Is private'), required=False, widget=BulkEditNullBooleanSelect ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) model = RIR fieldsets = ( FieldSet('is_private', 'description'), ) - nullable_fields = ('is_private', 'description') + nullable_fields = ('is_private', 'description', 'comments') -class ASNRangeBulkEditForm(NetBoxModelBulkEditForm): +class ASNRangeBulkEditForm(OrganizationalModelBulkEditForm): rir = DynamicModelChoiceField( queryset=RIR.objects.all(), required=False, @@ -116,20 +99,15 @@ class ASNRangeBulkEditForm(NetBoxModelBulkEditForm): queryset=Tenant.objects.all(), required=False ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) model = ASNRange fieldsets = ( FieldSet('rir', 'tenant', 'description'), ) - nullable_fields = ('description',) + nullable_fields = ('description', 'comments') -class ASNBulkEditForm(NetBoxModelBulkEditForm): +class ASNBulkEditForm(PrimaryModelBulkEditForm): sites = DynamicModelMultipleChoiceField( label=_('Sites'), queryset=Site.objects.all(), @@ -145,12 +123,6 @@ class ASNBulkEditForm(NetBoxModelBulkEditForm): queryset=Tenant.objects.all(), required=False ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = ASN fieldsets = ( @@ -159,7 +131,7 @@ class ASNBulkEditForm(NetBoxModelBulkEditForm): nullable_fields = ('tenant', 'description', 'comments') -class AggregateBulkEditForm(NetBoxModelBulkEditForm): +class AggregateBulkEditForm(PrimaryModelBulkEditForm): rir = DynamicModelChoiceField( queryset=RIR.objects.all(), required=False, @@ -174,12 +146,6 @@ class AggregateBulkEditForm(NetBoxModelBulkEditForm): label=_('Date added'), required=False ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = Aggregate fieldsets = ( @@ -188,25 +154,20 @@ class AggregateBulkEditForm(NetBoxModelBulkEditForm): nullable_fields = ('date_added', 'description', 'comments') -class RoleBulkEditForm(NetBoxModelBulkEditForm): +class RoleBulkEditForm(OrganizationalModelBulkEditForm): weight = forms.IntegerField( label=_('Weight'), required=False ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) model = Role fieldsets = ( FieldSet('weight', 'description'), ) - nullable_fields = ('description',) + nullable_fields = ('description', 'comments') -class PrefixBulkEditForm(ScopedBulkEditForm, NetBoxModelBulkEditForm): +class PrefixBulkEditForm(ScopedBulkEditForm, PrimaryModelBulkEditForm): vlan_group = DynamicModelChoiceField( queryset=VLANGroup.objects.all(), required=False, @@ -256,12 +217,6 @@ class PrefixBulkEditForm(ScopedBulkEditForm, NetBoxModelBulkEditForm): widget=BulkEditNullBooleanSelect(), label=_('Treat as fully utilized') ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = Prefix fieldsets = ( @@ -275,7 +230,7 @@ class PrefixBulkEditForm(ScopedBulkEditForm, NetBoxModelBulkEditForm): ) -class IPRangeBulkEditForm(NetBoxModelBulkEditForm): +class IPRangeBulkEditForm(PrimaryModelBulkEditForm): vrf = DynamicModelChoiceField( queryset=VRF.objects.all(), required=False, @@ -306,12 +261,6 @@ class IPRangeBulkEditForm(NetBoxModelBulkEditForm): widget=BulkEditNullBooleanSelect(), label=_('Treat as fully utilized') ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = IPRange fieldsets = ( @@ -322,7 +271,7 @@ class IPRangeBulkEditForm(NetBoxModelBulkEditForm): ) -class IPAddressBulkEditForm(NetBoxModelBulkEditForm): +class IPAddressBulkEditForm(PrimaryModelBulkEditForm): vrf = DynamicModelChoiceField( queryset=VRF.objects.all(), required=False, @@ -354,12 +303,6 @@ class IPAddressBulkEditForm(NetBoxModelBulkEditForm): required=False, label=_('DNS name') ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = IPAddress fieldsets = ( @@ -371,7 +314,7 @@ class IPAddressBulkEditForm(NetBoxModelBulkEditForm): ) -class FHRPGroupBulkEditForm(NetBoxModelBulkEditForm): +class FHRPGroupBulkEditForm(PrimaryModelBulkEditForm): protocol = forms.ChoiceField( label=_('Protocol'), choices=add_blank_choice(FHRPGroupProtocolChoices), @@ -397,12 +340,6 @@ class FHRPGroupBulkEditForm(NetBoxModelBulkEditForm): max_length=100, required=False ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = FHRPGroup fieldsets = ( @@ -412,12 +349,7 @@ class FHRPGroupBulkEditForm(NetBoxModelBulkEditForm): nullable_fields = ('auth_type', 'auth_key', 'name', 'description', 'comments') -class VLANGroupBulkEditForm(NetBoxModelBulkEditForm): - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) +class VLANGroupBulkEditForm(OrganizationalModelBulkEditForm): scope_type = ContentTypeChoiceField( queryset=ContentType.objects.filter(model__in=VLANGROUP_SCOPE_TYPES), widget=HTMXSelect(method='post', attrs={'hx-select': '#form_fields'}), @@ -447,7 +379,7 @@ class VLANGroupBulkEditForm(NetBoxModelBulkEditForm): FieldSet('scope_type', 'scope', name=_('Scope')), FieldSet('tenant', name=_('Tenancy')), ) - nullable_fields = ('description', 'scope') + nullable_fields = ('description', 'scope', 'comments') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -464,7 +396,7 @@ class VLANGroupBulkEditForm(NetBoxModelBulkEditForm): pass -class VLANBulkEditForm(NetBoxModelBulkEditForm): +class VLANBulkEditForm(PrimaryModelBulkEditForm): region = DynamicModelChoiceField( label=_('Region'), queryset=Region.objects.all(), @@ -507,11 +439,6 @@ class VLANBulkEditForm(NetBoxModelBulkEditForm): queryset=Role.objects.all(), required=False ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) qinq_role = forms.ChoiceField( label=_('Q-in-Q role'), choices=add_blank_choice(VLANQinQRoleChoices), @@ -525,7 +452,6 @@ class VLANBulkEditForm(NetBoxModelBulkEditForm): 'qinq_role': VLANQinQRoleChoices.ROLE_SERVICE, } ) - comments = CommentField() model = VLAN fieldsets = ( @@ -538,13 +464,7 @@ class VLANBulkEditForm(NetBoxModelBulkEditForm): ) -class VLANTranslationPolicyBulkEditForm(NetBoxModelBulkEditForm): - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - +class VLANTranslationPolicyBulkEditForm(PrimaryModelBulkEditForm): model = VLANTranslationPolicy fieldsets = ( FieldSet('description'), @@ -568,7 +488,7 @@ class VLANTranslationRuleBulkEditForm(NetBoxModelBulkEditForm): fields = ('policy', 'local_vid', 'remote_vid') -class ServiceTemplateBulkEditForm(NetBoxModelBulkEditForm): +class ServiceTemplateBulkEditForm(PrimaryModelBulkEditForm): protocol = forms.ChoiceField( label=_('Protocol'), choices=add_blank_choice(ServiceProtocolChoices), @@ -582,12 +502,6 @@ class ServiceTemplateBulkEditForm(NetBoxModelBulkEditForm): ), required=False ) - description = forms.CharField( - label=_('Description'), - max_length=200, - required=False - ) - comments = CommentField() model = ServiceTemplate fieldsets = ( diff --git a/netbox/ipam/forms/bulk_import.py b/netbox/ipam/forms/bulk_import.py index f8e45e182..d8ae22eda 100644 --- a/netbox/ipam/forms/bulk_import.py +++ b/netbox/ipam/forms/bulk_import.py @@ -7,7 +7,7 @@ from dcim.forms.mixins import ScopedImportForm from ipam.choices import * from ipam.constants import * from ipam.models import * -from netbox.forms import NetBoxModelImportForm +from netbox.forms import NetBoxModelImportForm, OrganizationalModelImportForm, PrimaryModelImportForm from tenancy.models import Tenant from utilities.forms.fields import ( CSVChoiceField, CSVContentTypeField, CSVModelChoiceField, CSVModelMultipleChoiceField, SlugField, @@ -36,7 +36,7 @@ __all__ = ( ) -class VRFImportForm(NetBoxModelImportForm): +class VRFImportForm(PrimaryModelImportForm): tenant = CSVModelChoiceField( label=_('Tenant'), queryset=Tenant.objects.all(), @@ -60,12 +60,12 @@ class VRFImportForm(NetBoxModelImportForm): class Meta: model = VRF fields = ( - 'name', 'rd', 'tenant', 'enforce_unique', 'description', 'import_targets', 'export_targets', 'comments', - 'tags', + 'name', 'rd', 'tenant', 'enforce_unique', 'description', 'import_targets', 'export_targets', 'owner', + 'comments', 'tags', ) -class RouteTargetImportForm(NetBoxModelImportForm): +class RouteTargetImportForm(PrimaryModelImportForm): tenant = CSVModelChoiceField( label=_('Tenant'), queryset=Tenant.objects.all(), @@ -76,18 +76,18 @@ class RouteTargetImportForm(NetBoxModelImportForm): class Meta: model = RouteTarget - fields = ('name', 'tenant', 'description', 'comments', 'tags') + fields = ('name', 'tenant', 'description', 'owner', 'comments', 'tags') -class RIRImportForm(NetBoxModelImportForm): +class RIRImportForm(OrganizationalModelImportForm): slug = SlugField() class Meta: model = RIR - fields = ('name', 'slug', 'is_private', 'description', 'tags') + fields = ('name', 'slug', 'is_private', 'description', 'owner', 'comments', 'tags') -class AggregateImportForm(NetBoxModelImportForm): +class AggregateImportForm(PrimaryModelImportForm): rir = CSVModelChoiceField( label=_('RIR'), queryset=RIR.objects.all(), @@ -104,10 +104,10 @@ class AggregateImportForm(NetBoxModelImportForm): class Meta: model = Aggregate - fields = ('prefix', 'rir', 'tenant', 'date_added', 'description', 'comments', 'tags') + fields = ('prefix', 'rir', 'tenant', 'date_added', 'description', 'owner', 'comments', 'tags') -class ASNRangeImportForm(NetBoxModelImportForm): +class ASNRangeImportForm(OrganizationalModelImportForm): rir = CSVModelChoiceField( label=_('RIR'), queryset=RIR.objects.all(), @@ -124,10 +124,10 @@ class ASNRangeImportForm(NetBoxModelImportForm): class Meta: model = ASNRange - fields = ('name', 'slug', 'rir', 'start', 'end', 'tenant', 'description', 'tags') + fields = ('name', 'slug', 'rir', 'start', 'end', 'tenant', 'description', 'owner', 'comments', 'tags') -class ASNImportForm(NetBoxModelImportForm): +class ASNImportForm(PrimaryModelImportForm): rir = CSVModelChoiceField( label=_('RIR'), queryset=RIR.objects.all(), @@ -144,18 +144,17 @@ class ASNImportForm(NetBoxModelImportForm): class Meta: model = ASN - fields = ('asn', 'rir', 'tenant', 'description', 'comments', 'tags') + fields = ('asn', 'rir', 'tenant', 'description', 'owner', 'comments', 'tags') -class RoleImportForm(NetBoxModelImportForm): - slug = SlugField() +class RoleImportForm(OrganizationalModelImportForm): class Meta: model = Role - fields = ('name', 'slug', 'weight', 'description', 'tags') + fields = ('name', 'slug', 'weight', 'description', 'owner', 'comments', 'tags') -class PrefixImportForm(ScopedImportForm, NetBoxModelImportForm): +class PrefixImportForm(ScopedImportForm, PrimaryModelImportForm): vrf = CSVModelChoiceField( label=_('VRF'), queryset=VRF.objects.all(), @@ -208,7 +207,7 @@ class PrefixImportForm(ScopedImportForm, NetBoxModelImportForm): model = Prefix fields = ( 'prefix', 'vrf', 'tenant', 'vlan_group', 'vlan_site', 'vlan', 'status', 'role', 'scope_type', 'scope_id', - 'is_pool', 'mark_utilized', 'description', 'comments', 'tags', + 'is_pool', 'mark_utilized', 'description', 'owner', 'comments', 'tags', ) labels = { 'scope_id': _('Scope ID'), @@ -240,7 +239,7 @@ class PrefixImportForm(ScopedImportForm, NetBoxModelImportForm): self.fields['vlan'].queryset = queryset -class IPRangeImportForm(NetBoxModelImportForm): +class IPRangeImportForm(PrimaryModelImportForm): vrf = CSVModelChoiceField( label=_('VRF'), queryset=VRF.objects.all(), @@ -272,11 +271,11 @@ class IPRangeImportForm(NetBoxModelImportForm): model = IPRange fields = ( 'start_address', 'end_address', 'vrf', 'tenant', 'status', 'role', 'mark_populated', 'mark_utilized', - 'description', 'comments', 'tags', + 'description', 'owner', 'comments', 'tags', ) -class IPAddressImportForm(NetBoxModelImportForm): +class IPAddressImportForm(PrimaryModelImportForm): vrf = CSVModelChoiceField( label=_('VRF'), queryset=VRF.objects.all(), @@ -345,7 +344,7 @@ class IPAddressImportForm(NetBoxModelImportForm): model = IPAddress fields = [ 'address', 'vrf', 'tenant', 'status', 'role', 'device', 'virtual_machine', 'interface', 'fhrp_group', - 'is_primary', 'is_oob', 'dns_name', 'description', 'comments', 'tags', + 'is_primary', 'is_oob', 'dns_name', 'description', 'owner', 'comments', 'tags', ] def __init__(self, data=None, *args, **kwargs): @@ -438,7 +437,7 @@ class IPAddressImportForm(NetBoxModelImportForm): return ipaddress -class FHRPGroupImportForm(NetBoxModelImportForm): +class FHRPGroupImportForm(PrimaryModelImportForm): protocol = CSVChoiceField( label=_('Protocol'), choices=FHRPGroupProtocolChoices @@ -451,11 +450,10 @@ class FHRPGroupImportForm(NetBoxModelImportForm): class Meta: model = FHRPGroup - fields = ('protocol', 'group_id', 'auth_type', 'auth_key', 'name', 'description', 'comments', 'tags') + fields = ('protocol', 'group_id', 'auth_type', 'auth_key', 'name', 'description', 'owner', 'comments', 'tags') -class VLANGroupImportForm(NetBoxModelImportForm): - slug = SlugField() +class VLANGroupImportForm(OrganizationalModelImportForm): scope_type = CSVContentTypeField( queryset=ContentType.objects.filter(model__in=VLANGROUP_SCOPE_TYPES), required=False, @@ -474,13 +472,15 @@ class VLANGroupImportForm(NetBoxModelImportForm): class Meta: model = VLANGroup - fields = ('name', 'slug', 'scope_type', 'scope_id', 'vid_ranges', 'tenant', 'description', 'tags') + fields = ( + 'name', 'slug', 'scope_type', 'scope_id', 'vid_ranges', 'tenant', 'description', 'owner', 'comments', 'tags' + ) labels = { 'scope_id': 'Scope ID', } -class VLANImportForm(NetBoxModelImportForm): +class VLANImportForm(PrimaryModelImportForm): site = CSVModelChoiceField( label=_('Site'), queryset=Site.objects.all(), @@ -532,15 +532,15 @@ class VLANImportForm(NetBoxModelImportForm): model = VLAN fields = ( 'site', 'group', 'vid', 'name', 'tenant', 'status', 'role', 'description', 'qinq_role', 'qinq_svlan', - 'comments', 'tags', + 'owner', 'comments', 'tags', ) -class VLANTranslationPolicyImportForm(NetBoxModelImportForm): +class VLANTranslationPolicyImportForm(PrimaryModelImportForm): class Meta: model = VLANTranslationPolicy - fields = ('name', 'description', 'tags') + fields = ('name', 'description', 'owner', 'comments', 'tags') class VLANTranslationRuleImportForm(NetBoxModelImportForm): @@ -556,7 +556,7 @@ class VLANTranslationRuleImportForm(NetBoxModelImportForm): fields = ('policy', 'local_vid', 'remote_vid') -class ServiceTemplateImportForm(NetBoxModelImportForm): +class ServiceTemplateImportForm(PrimaryModelImportForm): protocol = CSVChoiceField( label=_('Protocol'), choices=ServiceProtocolChoices, @@ -565,10 +565,10 @@ class ServiceTemplateImportForm(NetBoxModelImportForm): class Meta: model = ServiceTemplate - fields = ('name', 'protocol', 'ports', 'description', 'comments', 'tags') + fields = ('name', 'protocol', 'ports', 'description', 'owner', 'comments', 'tags') -class ServiceImportForm(NetBoxModelImportForm): +class ServiceImportForm(PrimaryModelImportForm): parent_object_type = CSVContentTypeField( queryset=ContentType.objects.filter(SERVICE_ASSIGNMENT_MODELS), required=True, @@ -600,7 +600,7 @@ class ServiceImportForm(NetBoxModelImportForm): class Meta: model = Service fields = ( - 'ipaddresses', 'name', 'protocol', 'ports', 'description', 'comments', 'tags', + 'ipaddresses', 'name', 'protocol', 'ports', 'description', 'owner', 'comments', 'tags', ) def __init__(self, data=None, *args, **kwargs): diff --git a/netbox/ipam/forms/filtersets.py b/netbox/ipam/forms/filtersets.py index dcd9ab5e2..85b0f825d 100644 --- a/netbox/ipam/forms/filtersets.py +++ b/netbox/ipam/forms/filtersets.py @@ -5,7 +5,7 @@ from dcim.models import Location, Rack, Region, Site, SiteGroup, Device from ipam.choices import * from ipam.constants import * from ipam.models import * -from netbox.forms import NetBoxModelFilterSetForm +from netbox.forms import NetBoxModelFilterSetForm, OrganizationalModelFilterSetForm, PrimaryModelFilterSetForm from tenancy.forms import ContactModelFilterForm, TenancyFilterForm from utilities.forms import BOOLEAN_WITH_BLANK_CHOICES, add_blank_choice from utilities.forms.fields import DynamicModelChoiceField, DynamicModelMultipleChoiceField, TagFilterField @@ -42,10 +42,10 @@ IPADDRESS_MASK_LENGTH_CHOICES = add_blank_choice([ ]) -class VRFFilterForm(TenancyFilterForm, NetBoxModelFilterSetForm): +class VRFFilterForm(TenancyFilterForm, PrimaryModelFilterSetForm): model = VRF fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('import_target_id', 'export_target_id', name=_('Route Targets')), FieldSet('tenant_group_id', 'tenant_id', name=_('Tenant')), ) @@ -62,10 +62,10 @@ class VRFFilterForm(TenancyFilterForm, NetBoxModelFilterSetForm): tag = TagFilterField(model) -class RouteTargetFilterForm(TenancyFilterForm, NetBoxModelFilterSetForm): +class RouteTargetFilterForm(TenancyFilterForm, PrimaryModelFilterSetForm): model = RouteTarget fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('importing_vrf_id', 'exporting_vrf_id', name=_('VRF')), FieldSet('tenant_group_id', 'tenant_id', name=_('Tenant')), ) @@ -82,8 +82,12 @@ class RouteTargetFilterForm(TenancyFilterForm, NetBoxModelFilterSetForm): tag = TagFilterField(model) -class RIRFilterForm(NetBoxModelFilterSetForm): +class RIRFilterForm(OrganizationalModelFilterSetForm): model = RIR + fieldsets = ( + FieldSet('q', 'filter_id', 'tag', 'owner_id'), + FieldSet('is_private', name=_('RIR')), + ) is_private = forms.NullBooleanField( required=False, label=_('Private'), @@ -94,10 +98,10 @@ class RIRFilterForm(NetBoxModelFilterSetForm): tag = TagFilterField(model) -class AggregateFilterForm(ContactModelFilterForm, TenancyFilterForm, NetBoxModelFilterSetForm): +class AggregateFilterForm(ContactModelFilterForm, TenancyFilterForm, PrimaryModelFilterSetForm): model = Aggregate fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('family', 'rir_id', name=_('Attributes')), FieldSet('tenant_group_id', 'tenant_id', name=_('Tenant')), FieldSet('contact', 'contact_role', 'contact_group', name=_('Contacts')), @@ -115,10 +119,10 @@ class AggregateFilterForm(ContactModelFilterForm, TenancyFilterForm, NetBoxModel tag = TagFilterField(model) -class ASNRangeFilterForm(TenancyFilterForm, NetBoxModelFilterSetForm): +class ASNRangeFilterForm(TenancyFilterForm, OrganizationalModelFilterSetForm): model = ASNRange fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('rir_id', 'start', 'end', name=_('Range')), FieldSet('tenant_group_id', 'tenant_id', name=_('Tenant')), ) @@ -138,10 +142,10 @@ class ASNRangeFilterForm(TenancyFilterForm, NetBoxModelFilterSetForm): tag = TagFilterField(model) -class ASNFilterForm(TenancyFilterForm, NetBoxModelFilterSetForm): +class ASNFilterForm(TenancyFilterForm, PrimaryModelFilterSetForm): model = ASN fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('rir_id', 'site_group_id', 'site_id', name=_('Assignment')), FieldSet('tenant_group_id', 'tenant_id', name=_('Tenant')), ) @@ -163,15 +167,18 @@ class ASNFilterForm(TenancyFilterForm, NetBoxModelFilterSetForm): tag = TagFilterField(model) -class RoleFilterForm(NetBoxModelFilterSetForm): +class RoleFilterForm(OrganizationalModelFilterSetForm): model = Role + fieldsets = ( + FieldSet('q', 'filter_id', 'tag', 'owner_id'), + ) tag = TagFilterField(model) -class PrefixFilterForm(ContactModelFilterForm, TenancyFilterForm, NetBoxModelFilterSetForm, ): +class PrefixFilterForm(ContactModelFilterForm, TenancyFilterForm, PrimaryModelFilterSetForm): model = Prefix fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet( 'within_include', 'family', 'status', 'role_id', 'mask_length', 'is_pool', 'mark_utilized', name=_('Addressing') @@ -274,10 +281,10 @@ class PrefixFilterForm(ContactModelFilterForm, TenancyFilterForm, NetBoxModelFil tag = TagFilterField(model) -class IPRangeFilterForm(ContactModelFilterForm, TenancyFilterForm, NetBoxModelFilterSetForm): +class IPRangeFilterForm(ContactModelFilterForm, TenancyFilterForm, PrimaryModelFilterSetForm): model = IPRange fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('family', 'vrf_id', 'status', 'role_id', 'mark_populated', 'mark_utilized', name=_('Attributes')), FieldSet('tenant_group_id', 'tenant_id', name=_('Tenant')), FieldSet('contact', 'contact_role', 'contact_group', name=_('Contacts')), @@ -321,10 +328,10 @@ class IPRangeFilterForm(ContactModelFilterForm, TenancyFilterForm, NetBoxModelFi tag = TagFilterField(model) -class IPAddressFilterForm(ContactModelFilterForm, TenancyFilterForm, NetBoxModelFilterSetForm): +class IPAddressFilterForm(ContactModelFilterForm, TenancyFilterForm, PrimaryModelFilterSetForm): model = IPAddress fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet( 'parent', 'family', 'status', 'role', 'mask_length', 'assigned_to_interface', 'dns_name', name=_('Attributes') @@ -399,10 +406,10 @@ class IPAddressFilterForm(ContactModelFilterForm, TenancyFilterForm, NetBoxModel tag = TagFilterField(model) -class FHRPGroupFilterForm(NetBoxModelFilterSetForm): +class FHRPGroupFilterForm(PrimaryModelFilterSetForm): model = FHRPGroup fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('name', 'protocol', 'group_id', name=_('Attributes')), FieldSet('auth_type', 'auth_key', name=_('Authentication')), ) @@ -432,9 +439,9 @@ class FHRPGroupFilterForm(NetBoxModelFilterSetForm): tag = TagFilterField(model) -class VLANGroupFilterForm(TenancyFilterForm, NetBoxModelFilterSetForm): +class VLANGroupFilterForm(TenancyFilterForm, OrganizationalModelFilterSetForm): fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('region', 'site_group', 'site', 'location', 'rack', name=_('Location')), FieldSet('cluster_group', 'cluster', name=_('Cluster')), FieldSet('contains_vid', name=_('VLANs')), @@ -485,10 +492,10 @@ class VLANGroupFilterForm(TenancyFilterForm, NetBoxModelFilterSetForm): tag = TagFilterField(model) -class VLANTranslationPolicyFilterForm(NetBoxModelFilterSetForm): +class VLANTranslationPolicyFilterForm(PrimaryModelFilterSetForm): model = VLANTranslationPolicy fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('name', name=_('Attributes')), ) name = forms.CharField( @@ -522,10 +529,10 @@ class VLANTranslationRuleFilterForm(NetBoxModelFilterSetForm): ) -class VLANFilterForm(TenancyFilterForm, NetBoxModelFilterSetForm): +class VLANFilterForm(TenancyFilterForm, PrimaryModelFilterSetForm): model = VLAN fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('region_id', 'site_group_id', 'site_id', name=_('Location')), FieldSet('group_id', 'status', 'role_id', 'vid', 'l2vpn_id', name=_('Attributes')), FieldSet('qinq_role', 'qinq_svlan_id', name=_('Q-in-Q/802.1ad')), @@ -594,10 +601,10 @@ class VLANFilterForm(TenancyFilterForm, NetBoxModelFilterSetForm): tag = TagFilterField(model) -class ServiceTemplateFilterForm(NetBoxModelFilterSetForm): +class ServiceTemplateFilterForm(PrimaryModelFilterSetForm): model = ServiceTemplate fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('protocol', 'port', name=_('Attributes')), ) protocol = forms.ChoiceField( @@ -615,7 +622,7 @@ class ServiceTemplateFilterForm(NetBoxModelFilterSetForm): class ServiceFilterForm(ContactModelFilterForm, ServiceTemplateFilterForm): model = Service fieldsets = ( - FieldSet('q', 'filter_id', 'tag'), + FieldSet('q', 'filter_id', 'tag', 'owner_id'), FieldSet('protocol', 'port', name=_('Attributes')), FieldSet('device_id', 'virtual_machine_id', 'fhrpgroup_id', name=_('Assignment')), FieldSet('contact', 'contact_role', 'contact_group', name=_('Contacts')), diff --git a/netbox/ipam/forms/model_forms.py b/netbox/ipam/forms/model_forms.py index 399198c52..645c3f72e 100644 --- a/netbox/ipam/forms/model_forms.py +++ b/netbox/ipam/forms/model_forms.py @@ -9,13 +9,13 @@ from ipam.choices import * from ipam.constants import * from ipam.formfields import IPNetworkFormField from ipam.models import * -from netbox.forms import NetBoxModelForm +from netbox.forms import NetBoxModelForm, OrganizationalModelForm, PrimaryModelForm from tenancy.forms import TenancyForm from utilities.exceptions import PermissionsViolation from utilities.forms import add_blank_choice from utilities.forms.fields import ( - CommentField, ContentTypeChoiceField, DynamicModelChoiceField, DynamicModelMultipleChoiceField, NumericArrayField, - NumericRangeArrayField, SlugField + ContentTypeChoiceField, DynamicModelChoiceField, DynamicModelMultipleChoiceField, NumericArrayField, + NumericRangeArrayField, ) from utilities.forms.rendering import FieldSet, InlineFields, ObjectAttribute, TabbedGroups from utilities.forms.utils import get_field_value @@ -49,7 +49,7 @@ __all__ = ( ) -class VRFForm(TenancyForm, NetBoxModelForm): +class VRFForm(TenancyForm, PrimaryModelForm): import_targets = DynamicModelMultipleChoiceField( label=_('Import targets'), queryset=RouteTarget.objects.all(), @@ -60,7 +60,6 @@ class VRFForm(TenancyForm, NetBoxModelForm): queryset=RouteTarget.objects.all(), required=False ) - comments = CommentField() fieldsets = ( FieldSet('name', 'rd', 'enforce_unique', 'description', 'tags', name=_('VRF')), @@ -72,30 +71,27 @@ class VRFForm(TenancyForm, NetBoxModelForm): model = VRF fields = [ 'name', 'rd', 'enforce_unique', 'import_targets', 'export_targets', 'tenant_group', 'tenant', 'description', - 'comments', 'tags', + 'owner', 'comments', 'tags', ] labels = { 'rd': "RD", } -class RouteTargetForm(TenancyForm, NetBoxModelForm): +class RouteTargetForm(TenancyForm, PrimaryModelForm): fieldsets = ( FieldSet('name', 'description', 'tags', name=_('Route Target')), FieldSet('tenant_group', 'tenant', name=_('Tenancy')), ) - comments = CommentField() class Meta: model = RouteTarget fields = [ - 'name', 'tenant_group', 'tenant', 'description', 'comments', 'tags', + 'name', 'tenant_group', 'tenant', 'description', 'owner', 'comments', 'tags', ] -class RIRForm(NetBoxModelForm): - slug = SlugField() - +class RIRForm(OrganizationalModelForm): fieldsets = ( FieldSet('name', 'slug', 'is_private', 'description', 'tags', name=_('RIR')), ) @@ -103,17 +99,16 @@ class RIRForm(NetBoxModelForm): class Meta: model = RIR fields = [ - 'name', 'slug', 'is_private', 'description', 'tags', + 'name', 'slug', 'is_private', 'description', 'owner', 'comments', 'tags', ] -class AggregateForm(TenancyForm, NetBoxModelForm): +class AggregateForm(TenancyForm, PrimaryModelForm): rir = DynamicModelChoiceField( queryset=RIR.objects.all(), label=_('RIR'), quick_add=True ) - comments = CommentField() fieldsets = ( FieldSet('prefix', 'rir', 'date_added', 'description', 'tags', name=_('Aggregate')), @@ -123,20 +118,19 @@ class AggregateForm(TenancyForm, NetBoxModelForm): class Meta: model = Aggregate fields = [ - 'prefix', 'rir', 'date_added', 'tenant_group', 'tenant', 'description', 'comments', 'tags', + 'prefix', 'rir', 'date_added', 'tenant_group', 'tenant', 'description', 'owner', 'comments', 'tags', ] widgets = { 'date_added': DatePicker(), } -class ASNRangeForm(TenancyForm, NetBoxModelForm): +class ASNRangeForm(TenancyForm, OrganizationalModelForm): rir = DynamicModelChoiceField( queryset=RIR.objects.all(), label=_('RIR'), quick_add=True ) - slug = SlugField() fieldsets = ( FieldSet('name', 'slug', 'rir', 'start', 'end', 'description', 'tags', name=_('ASN Range')), FieldSet('tenant_group', 'tenant', name=_('Tenancy')), @@ -145,11 +139,11 @@ class ASNRangeForm(TenancyForm, NetBoxModelForm): class Meta: model = ASNRange fields = [ - 'name', 'slug', 'rir', 'start', 'end', 'tenant_group', 'tenant', 'description', 'tags' + 'name', 'slug', 'rir', 'start', 'end', 'tenant_group', 'tenant', 'owner', 'description', 'comments', 'tags' ] -class ASNForm(TenancyForm, NetBoxModelForm): +class ASNForm(TenancyForm, PrimaryModelForm): rir = DynamicModelChoiceField( queryset=RIR.objects.all(), label=_('RIR'), @@ -160,7 +154,6 @@ class ASNForm(TenancyForm, NetBoxModelForm): label=_('Sites'), required=False ) - comments = CommentField() fieldsets = ( FieldSet('asn', 'rir', 'sites', 'description', 'tags', name=_('ASN')), @@ -170,7 +163,7 @@ class ASNForm(TenancyForm, NetBoxModelForm): class Meta: model = ASN fields = [ - 'asn', 'rir', 'sites', 'tenant_group', 'tenant', 'description', 'comments', 'tags' + 'asn', 'rir', 'sites', 'tenant_group', 'tenant', 'description', 'owner', 'comments', 'tags' ] widgets = { 'date_added': DatePicker(), @@ -188,9 +181,7 @@ class ASNForm(TenancyForm, NetBoxModelForm): return instance -class RoleForm(NetBoxModelForm): - slug = SlugField() - +class RoleForm(OrganizationalModelForm): fieldsets = ( FieldSet('name', 'slug', 'weight', 'description', 'tags', name=_('Role')), ) @@ -198,11 +189,11 @@ class RoleForm(NetBoxModelForm): class Meta: model = Role fields = [ - 'name', 'slug', 'weight', 'description', 'tags', + 'name', 'slug', 'weight', 'description', 'owner', 'comments', 'tags', ] -class PrefixForm(TenancyForm, ScopedForm, NetBoxModelForm): +class PrefixForm(TenancyForm, ScopedForm, PrimaryModelForm): vrf = DynamicModelChoiceField( queryset=VRF.objects.all(), required=False, @@ -223,7 +214,6 @@ class PrefixForm(TenancyForm, ScopedForm, NetBoxModelForm): required=False, quick_add=True ) - comments = CommentField() fieldsets = ( FieldSet( @@ -238,7 +228,7 @@ class PrefixForm(TenancyForm, ScopedForm, NetBoxModelForm): model = Prefix fields = [ 'prefix', 'vrf', 'vlan', 'status', 'role', 'is_pool', 'mark_utilized', 'scope_type', 'tenant_group', - 'tenant', 'description', 'comments', 'tags', + 'tenant', 'description', 'owner', 'comments', 'tags', ] def __init__(self, *args, **kwargs): @@ -250,7 +240,7 @@ class PrefixForm(TenancyForm, ScopedForm, NetBoxModelForm): self.fields['vlan'].widget.attrs.pop('data-dynamic-params', None) -class IPRangeForm(TenancyForm, NetBoxModelForm): +class IPRangeForm(TenancyForm, PrimaryModelForm): vrf = DynamicModelChoiceField( queryset=VRF.objects.all(), required=False, @@ -262,7 +252,6 @@ class IPRangeForm(TenancyForm, NetBoxModelForm): required=False, quick_add=True ) - comments = CommentField() fieldsets = ( FieldSet( @@ -276,11 +265,11 @@ class IPRangeForm(TenancyForm, NetBoxModelForm): model = IPRange fields = [ 'vrf', 'start_address', 'end_address', 'status', 'role', 'tenant_group', 'tenant', 'mark_populated', - 'mark_utilized', 'description', 'comments', 'tags', + 'mark_utilized', 'description', 'owner', 'comments', 'tags', ] -class IPAddressForm(TenancyForm, NetBoxModelForm): +class IPAddressForm(TenancyForm, PrimaryModelForm): interface = DynamicModelChoiceField( queryset=Interface.objects.all(), required=False, @@ -324,7 +313,6 @@ class IPAddressForm(TenancyForm, NetBoxModelForm): required=False, label=_('Make this the out-of-band IP for the device') ) - comments = CommentField() fieldsets = ( FieldSet('address', 'status', 'role', 'vrf', 'dns_name', 'description', 'tags', name=_('IP Address')), @@ -344,7 +332,7 @@ class IPAddressForm(TenancyForm, NetBoxModelForm): model = IPAddress fields = [ 'address', 'vrf', 'status', 'role', 'dns_name', 'primary_for_parent', 'oob_for_parent', 'nat_inside', - 'tenant_group', 'tenant', 'description', 'comments', 'tags', + 'tenant_group', 'tenant', 'description', 'owner', 'comments', 'tags', ] def __init__(self, *args, **kwargs): @@ -494,7 +482,7 @@ class IPAddressAssignForm(forms.Form): ) -class FHRPGroupForm(NetBoxModelForm): +class FHRPGroupForm(PrimaryModelForm): # Optionally create a new IPAddress along with the FHRPGroup ip_vrf = DynamicModelChoiceField( @@ -511,7 +499,6 @@ class FHRPGroupForm(NetBoxModelForm): required=False, label=_('Status') ) - comments = CommentField() fieldsets = ( FieldSet('protocol', 'group_id', 'name', 'description', 'tags', name=_('FHRP Group')), @@ -523,7 +510,7 @@ class FHRPGroupForm(NetBoxModelForm): model = FHRPGroup fields = ( 'protocol', 'group_id', 'auth_type', 'auth_key', 'name', 'ip_vrf', 'ip_address', 'ip_status', 'description', - 'comments', 'tags', + 'owner', 'comments', 'tags', ) def save(self, *args, **kwargs): @@ -599,8 +586,7 @@ class FHRPGroupAssignmentForm(forms.ModelForm): return group -class VLANGroupForm(TenancyForm, NetBoxModelForm): - slug = SlugField() +class VLANGroupForm(TenancyForm, OrganizationalModelForm): vid_ranges = NumericRangeArrayField( label=_('VLAN IDs') ) @@ -628,7 +614,8 @@ class VLANGroupForm(TenancyForm, NetBoxModelForm): class Meta: model = VLANGroup fields = [ - 'name', 'slug', 'description', 'vid_ranges', 'scope_type', 'tenant_group', 'tenant', 'tags', + 'name', 'slug', 'description', 'vid_ranges', 'scope_type', 'tenant_group', 'tenant', 'owner', 'comments', + 'tags', ] def __init__(self, *args, **kwargs): @@ -662,7 +649,7 @@ class VLANGroupForm(TenancyForm, NetBoxModelForm): self.instance.scope = self.cleaned_data.get('scope') -class VLANForm(TenancyForm, NetBoxModelForm): +class VLANForm(TenancyForm, PrimaryModelForm): group = DynamicModelChoiceField( queryset=VLANGroup.objects.all(), required=False, @@ -698,17 +685,16 @@ class VLANForm(TenancyForm, NetBoxModelForm): 'qinq_role': VLANQinQRoleChoices.ROLE_SERVICE, } ) - comments = CommentField() class Meta: model = VLAN fields = [ 'site', 'group', 'vid', 'name', 'status', 'role', 'tenant_group', 'tenant', 'qinq_role', 'qinq_svlan', - 'description', 'comments', 'tags', + 'description', 'owner', 'comments', 'tags', ] -class VLANTranslationPolicyForm(NetBoxModelForm): +class VLANTranslationPolicyForm(PrimaryModelForm): fieldsets = ( FieldSet('name', 'description', 'tags', name=_('VLAN Translation Policy')), @@ -717,7 +703,7 @@ class VLANTranslationPolicyForm(NetBoxModelForm): class Meta: model = VLANTranslationPolicy fields = [ - 'name', 'description', 'tags', + 'name', 'description', 'owner', 'tags', ] @@ -739,7 +725,7 @@ class VLANTranslationRuleForm(NetBoxModelForm): ] -class ServiceTemplateForm(NetBoxModelForm): +class ServiceTemplateForm(PrimaryModelForm): ports = NumericArrayField( label=_('Ports'), base_field=forms.IntegerField( @@ -748,7 +734,6 @@ class ServiceTemplateForm(NetBoxModelForm): ), help_text=_("Comma-separated list of one or more port numbers. A range may be specified using a hyphen.") ) - comments = CommentField() fieldsets = ( FieldSet('name', 'protocol', 'ports', 'description', 'tags', name=_('Application Service Template')), @@ -756,10 +741,10 @@ class ServiceTemplateForm(NetBoxModelForm): class Meta: model = ServiceTemplate - fields = ('name', 'protocol', 'ports', 'description', 'comments', 'tags') + fields = ('name', 'protocol', 'ports', 'description', 'owner', 'comments', 'tags') -class ServiceForm(NetBoxModelForm): +class ServiceForm(PrimaryModelForm): parent_object_type = ContentTypeChoiceField( queryset=ContentType.objects.filter(SERVICE_ASSIGNMENT_MODELS), widget=HTMXSelect(), @@ -786,7 +771,6 @@ class ServiceForm(NetBoxModelForm): required=False, label=_('IP Addresses'), ) - comments = CommentField() fieldsets = ( FieldSet( @@ -799,7 +783,7 @@ class ServiceForm(NetBoxModelForm): class Meta: model = Service fields = [ - 'name', 'protocol', 'ports', 'ipaddresses', 'description', 'comments', 'tags', + 'name', 'protocol', 'ports', 'ipaddresses', 'description', 'owner', 'comments', 'tags', 'parent_object_type', ] diff --git a/netbox/ipam/graphql/filter_mixins.py b/netbox/ipam/graphql/filter_mixins.py index 511850285..72d8e1404 100644 --- a/netbox/ipam/graphql/filter_mixins.py +++ b/netbox/ipam/graphql/filter_mixins.py @@ -3,21 +3,20 @@ from typing import Annotated, TYPE_CHECKING import strawberry import strawberry_django - -from core.graphql.filter_mixins import BaseFilterMixin +from strawberry_django import BaseFilterLookup if TYPE_CHECKING: from netbox.graphql.filter_lookups import IntegerLookup from .enums import * __all__ = ( - 'ServiceBaseFilterMixin', + 'ServiceFilterMixin', ) @dataclass -class ServiceBaseFilterMixin(BaseFilterMixin): - protocol: Annotated['ServiceProtocolEnum', strawberry.lazy('ipam.graphql.enums')] | None = ( +class ServiceFilterMixin: + protocol: BaseFilterLookup[Annotated['ServiceProtocolEnum', strawberry.lazy('ipam.graphql.enums')]] | None = ( strawberry_django.filter_field() ) ports: Annotated['IntegerLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( diff --git a/netbox/ipam/graphql/filters.py b/netbox/ipam/graphql/filters.py index c0a01d72b..c1cca193e 100644 --- a/netbox/ipam/graphql/filters.py +++ b/netbox/ipam/graphql/filters.py @@ -7,14 +7,15 @@ import strawberry_django from django.db.models import Q from netaddr.core import AddrFormatError from strawberry.scalars import ID -from strawberry_django import FilterLookup, DateFilterLookup +from strawberry_django import BaseFilterLookup, FilterLookup, DateFilterLookup -from core.graphql.filter_mixins import BaseObjectTypeFilterMixin, ChangeLogFilterMixin from dcim.graphql.filter_mixins import ScopedFilterMixin from dcim.models import Device from ipam import models -from ipam.graphql.filter_mixins import ServiceBaseFilterMixin -from netbox.graphql.filter_mixins import NetBoxModelFilterMixin, OrganizationalModelFilterMixin, PrimaryModelFilterMixin +from ipam.graphql.filter_mixins import ServiceFilterMixin +from netbox.graphql.filters import ( + ChangeLoggedModelFilter, NetBoxModelFilter, OrganizationalModelFilter, PrimaryModelFilter, +) from tenancy.graphql.filter_mixins import ContactFilterMixin, TenancyFilterMixin from virtualization.models import VMInterface @@ -49,7 +50,7 @@ __all__ = ( @strawberry_django.filter_type(models.ASN, lookups=True) -class ASNFilter(TenancyFilterMixin, PrimaryModelFilterMixin): +class ASNFilter(TenancyFilterMixin, PrimaryModelFilter): rir: Annotated['RIRFilter', strawberry.lazy('ipam.graphql.filters')] | None = strawberry_django.filter_field() rir_id: ID | None = strawberry_django.filter_field() asn: Annotated['IntegerLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( @@ -64,7 +65,7 @@ class ASNFilter(TenancyFilterMixin, PrimaryModelFilterMixin): @strawberry_django.filter_type(models.ASNRange, lookups=True) -class ASNRangeFilter(TenancyFilterMixin, OrganizationalModelFilterMixin): +class ASNRangeFilter(TenancyFilterMixin, OrganizationalModelFilter): name: FilterLookup[str] | None = strawberry_django.filter_field() slug: FilterLookup[str] | None = strawberry_django.filter_field() rir: Annotated['RIRFilter', strawberry.lazy('ipam.graphql.filters')] | None = strawberry_django.filter_field() @@ -78,7 +79,7 @@ class ASNRangeFilter(TenancyFilterMixin, OrganizationalModelFilterMixin): @strawberry_django.filter_type(models.Aggregate, lookups=True) -class AggregateFilter(ContactFilterMixin, TenancyFilterMixin, PrimaryModelFilterMixin): +class AggregateFilter(ContactFilterMixin, TenancyFilterMixin, PrimaryModelFilter): prefix: FilterLookup[str] | None = strawberry_django.filter_field() rir: Annotated['RIRFilter', strawberry.lazy('ipam.graphql.filters')] | None = strawberry_django.filter_field() rir_id: ID | None = strawberry_django.filter_field() @@ -111,15 +112,15 @@ class AggregateFilter(ContactFilterMixin, TenancyFilterMixin, PrimaryModelFilter @strawberry_django.filter_type(models.FHRPGroup, lookups=True) -class FHRPGroupFilter(PrimaryModelFilterMixin): +class FHRPGroupFilter(PrimaryModelFilter): group_id: Annotated['IntegerLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( strawberry_django.filter_field() ) name: FilterLookup[str] | None = strawberry_django.filter_field() - protocol: Annotated['FHRPGroupProtocolEnum', strawberry.lazy('ipam.graphql.enums')] | None = ( + protocol: BaseFilterLookup[Annotated['FHRPGroupProtocolEnum', strawberry.lazy('ipam.graphql.enums')]] | None = ( strawberry_django.filter_field() ) - auth_type: Annotated['FHRPGroupAuthTypeEnum', strawberry.lazy('ipam.graphql.enums')] | None = ( + auth_type: BaseFilterLookup[Annotated['FHRPGroupAuthTypeEnum', strawberry.lazy('ipam.graphql.enums')]] | None = ( strawberry_django.filter_field() ) auth_key: FilterLookup[str] | None = strawberry_django.filter_field() @@ -129,7 +130,7 @@ class FHRPGroupFilter(PrimaryModelFilterMixin): @strawberry_django.filter_type(models.FHRPGroupAssignment, lookups=True) -class FHRPGroupAssignmentFilter(BaseObjectTypeFilterMixin, ChangeLogFilterMixin): +class FHRPGroupAssignmentFilter(ChangeLoggedModelFilter): interface_type: Annotated['ContentTypeFilter', strawberry.lazy('core.graphql.filters')] | None = ( strawberry_django.filter_field() ) @@ -168,14 +169,14 @@ class FHRPGroupAssignmentFilter(BaseObjectTypeFilterMixin, ChangeLogFilterMixin) @strawberry_django.filter_type(models.IPAddress, lookups=True) -class IPAddressFilter(ContactFilterMixin, TenancyFilterMixin, PrimaryModelFilterMixin): +class IPAddressFilter(ContactFilterMixin, TenancyFilterMixin, PrimaryModelFilter): address: FilterLookup[str] | None = strawberry_django.filter_field() vrf: Annotated['VRFFilter', strawberry.lazy('ipam.graphql.filters')] | None = strawberry_django.filter_field() vrf_id: ID | None = strawberry_django.filter_field() - status: Annotated['IPAddressStatusEnum', strawberry.lazy('ipam.graphql.enums')] | None = ( + status: BaseFilterLookup[Annotated['IPAddressStatusEnum', strawberry.lazy('ipam.graphql.enums')]] | None = ( strawberry_django.filter_field() ) - role: Annotated['IPAddressRoleEnum', strawberry.lazy('ipam.graphql.enums')] | None = ( + role: BaseFilterLookup[Annotated['IPAddressRoleEnum', strawberry.lazy('ipam.graphql.enums')]] | None = ( strawberry_django.filter_field() ) assigned_object_type: Annotated['ContentTypeFilter', strawberry.lazy('core.graphql.filters')] | None = ( @@ -219,7 +220,7 @@ class IPAddressFilter(ContactFilterMixin, TenancyFilterMixin, PrimaryModelFilter @strawberry_django.filter_type(models.IPRange, lookups=True) -class IPRangeFilter(ContactFilterMixin, TenancyFilterMixin, PrimaryModelFilterMixin): +class IPRangeFilter(ContactFilterMixin, TenancyFilterMixin, PrimaryModelFilter): start_address: FilterLookup[str] | None = strawberry_django.filter_field() end_address: FilterLookup[str] | None = strawberry_django.filter_field() size: Annotated['IntegerLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( @@ -227,7 +228,7 @@ class IPRangeFilter(ContactFilterMixin, TenancyFilterMixin, PrimaryModelFilterMi ) vrf: Annotated['VRFFilter', strawberry.lazy('ipam.graphql.filters')] | None = strawberry_django.filter_field() vrf_id: ID | None = strawberry_django.filter_field() - status: Annotated['IPRangeStatusEnum', strawberry.lazy('ipam.graphql.enums')] | None = ( + status: BaseFilterLookup[Annotated['IPRangeStatusEnum', strawberry.lazy('ipam.graphql.enums')]] | None = ( strawberry_django.filter_field() ) role: Annotated['RoleFilter', strawberry.lazy('ipam.graphql.filters')] | None = strawberry_django.filter_field() @@ -273,13 +274,13 @@ class IPRangeFilter(ContactFilterMixin, TenancyFilterMixin, PrimaryModelFilterMi @strawberry_django.filter_type(models.Prefix, lookups=True) -class PrefixFilter(ContactFilterMixin, ScopedFilterMixin, TenancyFilterMixin, PrimaryModelFilterMixin): +class PrefixFilter(ContactFilterMixin, ScopedFilterMixin, TenancyFilterMixin, PrimaryModelFilter): prefix: FilterLookup[str] | None = strawberry_django.filter_field() vrf: Annotated['VRFFilter', strawberry.lazy('ipam.graphql.filters')] | None = strawberry_django.filter_field() vrf_id: ID | None = strawberry_django.filter_field() vlan: Annotated['VLANFilter', strawberry.lazy('ipam.graphql.filters')] | None = strawberry_django.filter_field() vlan_id: ID | None = strawberry_django.filter_field() - status: Annotated['PrefixStatusEnum', strawberry.lazy('ipam.graphql.enums')] | None = ( + status: BaseFilterLookup[Annotated['PrefixStatusEnum', strawberry.lazy('ipam.graphql.enums')]] | None = ( strawberry_django.filter_field() ) role: Annotated['RoleFilter', strawberry.lazy('ipam.graphql.filters')] | None = strawberry_django.filter_field() @@ -310,19 +311,19 @@ class PrefixFilter(ContactFilterMixin, ScopedFilterMixin, TenancyFilterMixin, Pr @strawberry_django.filter_type(models.RIR, lookups=True) -class RIRFilter(OrganizationalModelFilterMixin): +class RIRFilter(OrganizationalModelFilter): is_private: FilterLookup[bool] | None = strawberry_django.filter_field() @strawberry_django.filter_type(models.Role, lookups=True) -class RoleFilter(OrganizationalModelFilterMixin): +class RoleFilter(OrganizationalModelFilter): weight: Annotated['IntegerLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( strawberry_django.filter_field() ) @strawberry_django.filter_type(models.RouteTarget, lookups=True) -class RouteTargetFilter(TenancyFilterMixin, PrimaryModelFilterMixin): +class RouteTargetFilter(TenancyFilterMixin, PrimaryModelFilter): name: FilterLookup[str] | None = strawberry_django.filter_field() importing_vrfs: Annotated['VRFFilter', strawberry.lazy('ipam.graphql.filters')] | None = ( strawberry_django.filter_field() @@ -339,7 +340,7 @@ class RouteTargetFilter(TenancyFilterMixin, PrimaryModelFilterMixin): @strawberry_django.filter_type(models.Service, lookups=True) -class ServiceFilter(ContactFilterMixin, ServiceBaseFilterMixin, PrimaryModelFilterMixin): +class ServiceFilter(ContactFilterMixin, ServiceFilterMixin, PrimaryModelFilter): name: FilterLookup[str] | None = strawberry_django.filter_field() ip_addresses: Annotated['IPAddressFilter', strawberry.lazy('ipam.graphql.filters')] | None = ( strawberry_django.filter_field() @@ -351,12 +352,12 @@ class ServiceFilter(ContactFilterMixin, ServiceBaseFilterMixin, PrimaryModelFilt @strawberry_django.filter_type(models.ServiceTemplate, lookups=True) -class ServiceTemplateFilter(ServiceBaseFilterMixin, PrimaryModelFilterMixin): +class ServiceTemplateFilter(ServiceFilterMixin, PrimaryModelFilter): name: FilterLookup[str] | None = strawberry_django.filter_field() @strawberry_django.filter_type(models.VLAN, lookups=True) -class VLANFilter(TenancyFilterMixin, PrimaryModelFilterMixin): +class VLANFilter(TenancyFilterMixin, PrimaryModelFilter): site: Annotated['SiteFilter', strawberry.lazy('dcim.graphql.filters')] | None = strawberry_django.filter_field() site_id: ID | None = strawberry_django.filter_field() group: Annotated['VLANGroupFilter', strawberry.lazy('ipam.graphql.filters')] | None = ( @@ -367,7 +368,9 @@ class VLANFilter(TenancyFilterMixin, PrimaryModelFilterMixin): strawberry_django.filter_field() ) name: FilterLookup[str] | None = strawberry_django.filter_field() - status: Annotated['VLANStatusEnum', strawberry.lazy('ipam.graphql.enums')] | None = strawberry_django.filter_field() + status: BaseFilterLookup[Annotated['VLANStatusEnum', strawberry.lazy('ipam.graphql.enums')]] | None = ( + strawberry_django.filter_field() + ) role: Annotated['RoleFilter', strawberry.lazy('ipam.graphql.filters')] | None = strawberry_django.filter_field() role_id: ID | None = strawberry_django.filter_field() qinq_svlan: Annotated['VLANFilter', strawberry.lazy('ipam.graphql.filters')] | None = ( @@ -377,7 +380,7 @@ class VLANFilter(TenancyFilterMixin, PrimaryModelFilterMixin): qinq_cvlans: Annotated['VLANFilter', strawberry.lazy('ipam.graphql.filters')] | None = ( strawberry_django.filter_field() ) - qinq_role: Annotated['VLANQinQRoleEnum', strawberry.lazy('ipam.graphql.enums')] | None = ( + qinq_role: BaseFilterLookup[Annotated['VLANQinQRoleEnum', strawberry.lazy('ipam.graphql.enums')]] | None = ( strawberry_django.filter_field() ) l2vpn_terminations: Annotated['L2VPNFilter', strawberry.lazy('vpn.graphql.filters')] | None = ( @@ -386,19 +389,19 @@ class VLANFilter(TenancyFilterMixin, PrimaryModelFilterMixin): @strawberry_django.filter_type(models.VLANGroup, lookups=True) -class VLANGroupFilter(ScopedFilterMixin, OrganizationalModelFilterMixin): +class VLANGroupFilter(ScopedFilterMixin, OrganizationalModelFilter): vid_ranges: Annotated['IntegerRangeArrayLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = ( strawberry_django.filter_field() ) @strawberry_django.filter_type(models.VLANTranslationPolicy, lookups=True) -class VLANTranslationPolicyFilter(PrimaryModelFilterMixin): +class VLANTranslationPolicyFilter(PrimaryModelFilter): name: FilterLookup[str] | None = strawberry_django.filter_field() @strawberry_django.filter_type(models.VLANTranslationRule, lookups=True) -class VLANTranslationRuleFilter(NetBoxModelFilterMixin): +class VLANTranslationRuleFilter(NetBoxModelFilter): policy: Annotated['VLANTranslationPolicyFilter', strawberry.lazy('ipam.graphql.filters')] | None = ( strawberry_django.filter_field() ) @@ -413,7 +416,7 @@ class VLANTranslationRuleFilter(NetBoxModelFilterMixin): @strawberry_django.filter_type(models.VRF, lookups=True) -class VRFFilter(TenancyFilterMixin, PrimaryModelFilterMixin): +class VRFFilter(TenancyFilterMixin, PrimaryModelFilter): name: FilterLookup[str] | None = strawberry_django.filter_field() rd: FilterLookup[str] | None = strawberry_django.filter_field() enforce_unique: FilterLookup[bool] | None = strawberry_django.filter_field() diff --git a/netbox/ipam/graphql/types.py b/netbox/ipam/graphql/types.py index a07316fe4..e63f0bff3 100644 --- a/netbox/ipam/graphql/types.py +++ b/netbox/ipam/graphql/types.py @@ -8,7 +8,7 @@ from dcim.graphql.types import SiteType from extras.graphql.mixins import ContactsMixin from ipam import models from netbox.graphql.scalars import BigInt -from netbox.graphql.types import BaseObjectType, NetBoxObjectType, OrganizationalObjectType +from netbox.graphql.types import BaseObjectType, NetBoxObjectType, OrganizationalObjectType, PrimaryObjectType from .filters import * from .mixins import IPAddressesMixin @@ -74,7 +74,7 @@ class BaseIPAddressFamilyType: filters=ASNFilter, pagination=True ) -class ASNType(NetBoxObjectType, ContactsMixin): +class ASNType(ContactsMixin, PrimaryObjectType): asn: BigInt rir: Annotated["RIRType", strawberry.lazy('ipam.graphql.types')] | None tenant: Annotated["TenantType", strawberry.lazy('tenancy.graphql.types')] | None @@ -89,7 +89,7 @@ class ASNType(NetBoxObjectType, ContactsMixin): filters=ASNRangeFilter, pagination=True ) -class ASNRangeType(NetBoxObjectType): +class ASNRangeType(OrganizationalObjectType): start: BigInt end: BigInt rir: Annotated["RIRType", strawberry.lazy('ipam.graphql.types')] | None @@ -102,7 +102,7 @@ class ASNRangeType(NetBoxObjectType): filters=AggregateFilter, pagination=True ) -class AggregateType(NetBoxObjectType, ContactsMixin, BaseIPAddressFamilyType): +class AggregateType(ContactsMixin, BaseIPAddressFamilyType, PrimaryObjectType): prefix: str rir: Annotated["RIRType", strawberry.lazy('ipam.graphql.types')] | None tenant: Annotated["TenantType", strawberry.lazy('tenancy.graphql.types')] | None @@ -114,8 +114,7 @@ class AggregateType(NetBoxObjectType, ContactsMixin, BaseIPAddressFamilyType): filters=FHRPGroupFilter, pagination=True ) -class FHRPGroupType(NetBoxObjectType, IPAddressesMixin): - +class FHRPGroupType(IPAddressesMixin, PrimaryObjectType): fhrpgroupassignment_set: List[Annotated["FHRPGroupAssignmentType", strawberry.lazy('ipam.graphql.types')]] @@ -142,7 +141,7 @@ class FHRPGroupAssignmentType(BaseObjectType): filters=IPAddressFilter, pagination=True ) -class IPAddressType(NetBoxObjectType, ContactsMixin, BaseIPAddressFamilyType): +class IPAddressType(ContactsMixin, BaseIPAddressFamilyType, PrimaryObjectType): address: str vrf: Annotated["VRFType", strawberry.lazy('ipam.graphql.types')] | None tenant: Annotated["TenantType", strawberry.lazy('tenancy.graphql.types')] | None @@ -167,7 +166,7 @@ class IPAddressType(NetBoxObjectType, ContactsMixin, BaseIPAddressFamilyType): filters=IPRangeFilter, pagination=True ) -class IPRangeType(NetBoxObjectType, ContactsMixin): +class IPRangeType(ContactsMixin, PrimaryObjectType): start_address: str end_address: str vrf: Annotated["VRFType", strawberry.lazy('ipam.graphql.types')] | None @@ -181,7 +180,7 @@ class IPRangeType(NetBoxObjectType, ContactsMixin): filters=PrefixFilter, pagination=True ) -class PrefixType(NetBoxObjectType, ContactsMixin, BaseIPAddressFamilyType): +class PrefixType(ContactsMixin, BaseIPAddressFamilyType, PrimaryObjectType): prefix: str vrf: Annotated["VRFType", strawberry.lazy('ipam.graphql.types')] | None tenant: Annotated["TenantType", strawberry.lazy('tenancy.graphql.types')] | None @@ -230,7 +229,7 @@ class RoleType(OrganizationalObjectType): filters=RouteTargetFilter, pagination=True ) -class RouteTargetType(NetBoxObjectType): +class RouteTargetType(PrimaryObjectType): tenant: Annotated["TenantType", strawberry.lazy('tenancy.graphql.types')] | None importing_l2vpns: List[Annotated["L2VPNType", strawberry.lazy('vpn.graphql.types')]] @@ -245,7 +244,7 @@ class RouteTargetType(NetBoxObjectType): filters=ServiceFilter, pagination=True ) -class ServiceType(NetBoxObjectType, ContactsMixin): +class ServiceType(ContactsMixin, PrimaryObjectType): ports: List[int] ipaddresses: List[Annotated["IPAddressType", strawberry.lazy('ipam.graphql.types')]] @@ -264,7 +263,7 @@ class ServiceType(NetBoxObjectType, ContactsMixin): filters=ServiceTemplateFilter, pagination=True ) -class ServiceTemplateType(NetBoxObjectType): +class ServiceTemplateType(PrimaryObjectType): ports: List[int] @@ -274,7 +273,7 @@ class ServiceTemplateType(NetBoxObjectType): filters=VLANFilter, pagination=True ) -class VLANType(NetBoxObjectType): +class VLANType(PrimaryObjectType): site: Annotated["SiteType", strawberry.lazy('ipam.graphql.types')] | None group: Annotated["VLANGroupType", strawberry.lazy('ipam.graphql.types')] | None tenant: Annotated["TenantType", strawberry.lazy('tenancy.graphql.types')] | None @@ -323,7 +322,7 @@ class VLANGroupType(OrganizationalObjectType): filters=VLANTranslationPolicyFilter, pagination=True ) -class VLANTranslationPolicyType(NetBoxObjectType): +class VLANTranslationPolicyType(PrimaryObjectType): rules: List[Annotated["VLANTranslationRuleType", strawberry.lazy('ipam.graphql.types')]] @@ -346,7 +345,7 @@ class VLANTranslationRuleType(NetBoxObjectType): filters=VRFFilter, pagination=True ) -class VRFType(NetBoxObjectType): +class VRFType(PrimaryObjectType): tenant: Annotated["TenantType", strawberry.lazy('tenancy.graphql.types')] | None interfaces: List[Annotated["InterfaceType", strawberry.lazy('dcim.graphql.types')]] diff --git a/netbox/ipam/migrations/0084_owner.py b/netbox/ipam/migrations/0084_owner.py new file mode 100644 index 000000000..6c872c2a7 --- /dev/null +++ b/netbox/ipam/migrations/0084_owner.py @@ -0,0 +1,124 @@ +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ('ipam', '0083_vlangroup_populate_total_vlan_ids'), + ('users', '0015_owner'), + ] + + operations = [ + migrations.AddField( + model_name='aggregate', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='asn', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='asnrange', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='fhrpgroup', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='ipaddress', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='iprange', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='prefix', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='rir', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='role', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='routetarget', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='service', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='servicetemplate', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='vlan', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='vlangroup', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='vlantranslationpolicy', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + migrations.AddField( + model_name='vrf', + name='owner', + field=models.ForeignKey( + blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='users.owner' + ), + ), + ] diff --git a/netbox/ipam/migrations/0085_add_comments_to_organizationalmodel.py b/netbox/ipam/migrations/0085_add_comments_to_organizationalmodel.py new file mode 100644 index 000000000..b7d947350 --- /dev/null +++ b/netbox/ipam/migrations/0085_add_comments_to_organizationalmodel.py @@ -0,0 +1,33 @@ +# Generated by Django 5.2.8 on 2025-12-08 17:38 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('ipam', '0084_owner'), + ] + + operations = [ + migrations.AddField( + model_name='asnrange', + name='comments', + field=models.TextField(blank=True), + ), + migrations.AddField( + model_name='rir', + name='comments', + field=models.TextField(blank=True), + ), + migrations.AddField( + model_name='role', + name='comments', + field=models.TextField(blank=True), + ), + migrations.AddField( + model_name='vlangroup', + name='comments', + field=models.TextField(blank=True), + ), + ] diff --git a/netbox/ipam/migrations/0086_gfk_indexes.py b/netbox/ipam/migrations/0086_gfk_indexes.py new file mode 100644 index 000000000..a5014b7e0 --- /dev/null +++ b/netbox/ipam/migrations/0086_gfk_indexes.py @@ -0,0 +1,19 @@ +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ('contenttypes', '0002_remove_content_type_name'), + ('dcim', '0225_gfk_indexes'), + ('extras', '0134_owner'), + ('ipam', '0085_add_comments_to_organizationalmodel'), + ('tenancy', '0022_add_comments_to_organizationalmodel'), + ('users', '0015_owner'), + ] + + operations = [ + migrations.AddIndex( + model_name='prefix', + index=models.Index(fields=['scope_type', 'scope_id'], name='ipam_prefix_scope_t_fe84a6_idx'), + ), + ] diff --git a/netbox/ipam/models/ip.py b/netbox/ipam/models/ip.py index 75ab5a93b..92fff195f 100644 --- a/netbox/ipam/models/ip.py +++ b/netbox/ipam/models/ip.py @@ -282,13 +282,10 @@ class Prefix(ContactsMixin, GetAvailablePrefixesMixin, CachedScopeMixin, Primary ordering = (F('vrf').asc(nulls_first=True), 'prefix', 'pk') # (vrf, prefix) may be non-unique verbose_name = _('prefix') verbose_name_plural = _('prefixes') - indexes = [ - GistIndex( - fields=['prefix'], - name='ipam_prefix_gist_idx', - opclasses=['inet_ops'], - ), - ] + indexes = ( + models.Index(fields=('scope_type', 'scope_id')), + GistIndex(fields=['prefix'], name='ipam_prefix_gist_idx', opclasses=['inet_ops']), + ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) diff --git a/netbox/ipam/search.py b/netbox/ipam/search.py index 63437e417..0d11c2cd8 100644 --- a/netbox/ipam/search.py +++ b/netbox/ipam/search.py @@ -31,6 +31,7 @@ class ASNRangeIndex(SearchIndex): fields = ( ('name', 100), ('description', 500), + ('comments', 5000), ) display_attrs = ('rir', 'tenant', 'description') @@ -89,6 +90,7 @@ class RIRIndex(SearchIndex): ('name', 100), ('slug', 110), ('description', 500), + ('comments', 5000), ) display_attrs = ('description',) @@ -100,6 +102,7 @@ class RoleIndex(SearchIndex): ('name', 100), ('slug', 110), ('description', 500), + ('comments', 5000), ) display_attrs = ('description',) @@ -156,6 +159,7 @@ class VLANGroupIndex(SearchIndex): ('name', 100), ('slug', 110), ('description', 500), + ('comments', 5000), ) display_attrs = ('scope_type', 'description') diff --git a/netbox/ipam/tables/asn.py b/netbox/ipam/tables/asn.py index d2be90b2f..2c2ee56e4 100644 --- a/netbox/ipam/tables/asn.py +++ b/netbox/ipam/tables/asn.py @@ -2,7 +2,7 @@ import django_tables2 as tables from django.utils.translation import gettext_lazy as _ from ipam.models import * -from netbox.tables import NetBoxTable, columns +from netbox.tables import OrganizationalModelTable, PrimaryModelTable, columns from tenancy.tables import ContactsColumnMixin, TenancyColumnsMixin __all__ = ( @@ -11,7 +11,7 @@ __all__ = ( ) -class ASNRangeTable(TenancyColumnsMixin, NetBoxTable): +class ASNRangeTable(TenancyColumnsMixin, OrganizationalModelTable): name = tables.Column( verbose_name=_('Name'), linkify=True @@ -37,16 +37,16 @@ class ASNRangeTable(TenancyColumnsMixin, NetBoxTable): verbose_name=_('ASNs') ) - class Meta(NetBoxTable.Meta): + class Meta(OrganizationalModelTable.Meta): model = ASNRange fields = ( 'pk', 'name', 'slug', 'rir', 'start', 'start_asdot', 'end', 'end_asdot', 'asn_count', 'tenant', - 'tenant_group', 'description', 'tags', 'created', 'last_updated', 'actions', + 'tenant_group', 'description', 'comments', 'tags', 'created', 'last_updated', 'actions', ) default_columns = ('pk', 'name', 'rir', 'start', 'end', 'tenant', 'asn_count', 'description') -class ASNTable(TenancyColumnsMixin, ContactsColumnMixin, NetBoxTable): +class ASNTable(TenancyColumnsMixin, ContactsColumnMixin, PrimaryModelTable): asn = tables.Column( verbose_name=_('ASN'), linkify=True @@ -75,14 +75,11 @@ class ASNTable(TenancyColumnsMixin, ContactsColumnMixin, NetBoxTable): linkify_item=True, verbose_name=_('Sites') ) - comments = columns.MarkdownColumn( - verbose_name=_('Comments'), - ) tags = columns.TagColumn( url_name='ipam:asn_list' ) - class Meta(NetBoxTable.Meta): + class Meta(PrimaryModelTable.Meta): model = ASN fields = ( 'pk', 'asn', 'asn_asdot', 'rir', 'site_count', 'provider_count', 'tenant', 'tenant_group', 'description', diff --git a/netbox/ipam/tables/fhrp.py b/netbox/ipam/tables/fhrp.py index 789845f25..2d77c62c7 100644 --- a/netbox/ipam/tables/fhrp.py +++ b/netbox/ipam/tables/fhrp.py @@ -1,8 +1,8 @@ -from django.utils.translation import gettext_lazy as _ import django_tables2 as tables +from django.utils.translation import gettext_lazy as _ from ipam.models import * -from netbox.tables import NetBoxTable, columns +from netbox.tables import NetBoxTable, PrimaryModelTable, columns __all__ = ( 'FHRPGroupTable', @@ -17,7 +17,7 @@ IPADDRESSES = """ """ -class FHRPGroupTable(NetBoxTable): +class FHRPGroupTable(PrimaryModelTable): group_id = tables.Column( verbose_name=_('Group ID'), linkify=True @@ -30,9 +30,6 @@ class FHRPGroupTable(NetBoxTable): member_count = tables.Column( verbose_name=_('Members') ) - comments = columns.MarkdownColumn( - verbose_name=_('Comments'), - ) tags = columns.TagColumn( url_name='ipam:fhrpgroup_list' ) @@ -40,7 +37,7 @@ class FHRPGroupTable(NetBoxTable): def value_ip_addresses(self, value): return ",".join([str(obj.address) for obj in value.all()]) - class Meta(NetBoxTable.Meta): + class Meta(PrimaryModelTable.Meta): model = FHRPGroup fields = ( 'pk', 'group_id', 'protocol', 'name', 'auth_type', 'auth_key', 'description', 'comments', 'ip_addresses', diff --git a/netbox/ipam/tables/ip.py b/netbox/ipam/tables/ip.py index 2c0756197..707f7f5be 100644 --- a/netbox/ipam/tables/ip.py +++ b/netbox/ipam/tables/ip.py @@ -4,7 +4,7 @@ from django.utils.translation import gettext_lazy as _ from django_tables2.utils import Accessor from ipam.models import * -from netbox.tables import NetBoxTable, columns +from netbox.tables import NetBoxTable, OrganizationalModelTable, PrimaryModelTable, columns from tenancy.tables import ContactsColumnMixin, TenancyColumnsMixin, TenantColumn from .template_code import * @@ -27,7 +27,7 @@ AVAILABLE_LABEL = mark_safe('AvailableAvailable." or "Token "' + ) + # Extract the key (if v2) & token plaintext from the auth header try: - token = model.objects.prefetch_related('user').get(key=key) - except model.DoesNotExist: - raise exceptions.AuthenticationFailed("Invalid token") + auth_value = auth[1].decode() + except UnicodeError: + raise exceptions.AuthenticationFailed('Invalid authorization header: Token contains invalid characters') + + # Infer token version from presence or absence of prefix + version = 2 if auth_value.startswith(TOKEN_PREFIX) else 1 + + if version == 1: + key, plaintext = None, auth_value + else: + auth_value = auth_value.removeprefix(TOKEN_PREFIX) + try: + key, plaintext = auth_value.split('.', 1) + except ValueError: + raise exceptions.AuthenticationFailed( + "Invalid authorization header: Could not parse key from v2 token. Did you mean to use 'Token' " + "instead of 'Bearer'?" + ) + + # Look for a matching token in the database + try: + qs = Token.objects.prefetch_related('user') + if version == 1: + # Fetch v1 token by querying plaintext value directly + token = qs.get(version=version, plaintext=plaintext) + else: + # Fetch v2 token by key, then validate the plaintext + token = qs.get(version=version, key=key) + if not token.validate(plaintext): + # Key is valid but plaintext is not. Raise DoesNotExist to guard against key enumeration. + raise Token.DoesNotExist() + except Token.DoesNotExist: + raise exceptions.AuthenticationFailed(f"Invalid v{version} token") + + # Enforce source IP restrictions (if any) set on the token + if token.allowed_ips: + client_ip = get_client_ip(request) + if client_ip is None: + raise exceptions.AuthenticationFailed( + 'Client IP address could not be determined for validation. Check that the HTTP server is ' + 'correctly configured to pass the required header(s).' + ) + if not token.validate_client_ip(client_ip): + raise exceptions.AuthenticationFailed( + f"Source IP {client_ip} is not permitted to authenticate using this token." + ) + + # Enforce the Token is enabled + if not token.enabled: + raise exceptions.AuthenticationFailed('Token disabled') + + # Enforce the Token's expiration time, if one has been set. + if token.is_expired: + raise exceptions.AuthenticationFailed('Token expired') # Update last used, but only once per minute at most. This reduces write load on the database if not token.last_used or (timezone.now() - token.last_used).total_seconds() > 60: @@ -54,11 +101,8 @@ class TokenAuthentication(authentication.TokenAuthentication): else: Token.objects.filter(pk=token.pk).update(last_used=timezone.now()) - # Enforce the Token's expiration time, if one has been set. - if token.is_expired: - raise exceptions.AuthenticationFailed("Token expired") - user = token.user + # When LDAP authentication is active try to load user data from LDAP directory if 'netbox.authentication.LDAPBackend' in settings.REMOTE_AUTH_BACKEND: from netbox.authentication import LDAPBackend @@ -124,6 +168,20 @@ class TokenPermissions(DjangoObjectPermissions): return super().has_object_permission(request, view, obj) +class TokenWritePermission(BasePermission): + """ + Verify the token has write_enabled for unsafe methods, without requiring specific model permissions. + Used for custom actions that accept user data but don't map to standard CRUD operations. + """ + + def has_permission(self, request, view): + if not isinstance(request.auth, Token): + raise exceptions.PermissionDenied( + "TokenWritePermission requires token authentication." + ) + return bool(request.method in SAFE_METHODS or request.auth.write_enabled) + + class IsAuthenticatedOrLoginNotRequired(BasePermission): """ Returns True if the user is authenticated or LOGIN_REQUIRED is False. @@ -132,3 +190,17 @@ class IsAuthenticatedOrLoginNotRequired(BasePermission): if not settings.LOGIN_REQUIRED: return True return request.user.is_authenticated + + +class TokenScheme(OpenApiAuthenticationExtension): + target_class = 'netbox.api.authentication.TokenAuthentication' + name = 'tokenAuth' + match_subclasses = True + + def get_security_definition(self, auto_schema): + return { + 'type': 'apiKey', + 'in': 'header', + 'name': 'Authorization', + 'description': '`Token ` (v1) or `Bearer .` (v2)', + } diff --git a/netbox/netbox/api/gfk_fields.py b/netbox/netbox/api/gfk_fields.py new file mode 100644 index 000000000..d2bbeac4c --- /dev/null +++ b/netbox/netbox/api/gfk_fields.py @@ -0,0 +1,18 @@ +from drf_spectacular.utils import extend_schema_field +from rest_framework import serializers +from utilities.api import get_serializer_for_model + +__all__ = ( + 'GFKSerializerField', +) + + +@extend_schema_field(serializers.JSONField(allow_null=True, read_only=True)) +class GFKSerializerField(serializers.Field): + + def to_representation(self, instance, **kwargs): + if instance is None: + return None + serializer = get_serializer_for_model(instance) + context = {'request': self.context['request']} + return serializer(instance, nested=True, context=context).data diff --git a/netbox/netbox/api/serializers/__init__.py b/netbox/netbox/api/serializers/__init__.py index d7ad19565..2d95e932b 100644 --- a/netbox/netbox/api/serializers/__init__.py +++ b/netbox/netbox/api/serializers/__init__.py @@ -1,33 +1,6 @@ -from rest_framework import serializers - from .base import * from .features import * from .generic import * from .nested import * - - -# -# Base model serializers -# - -class NetBoxModelSerializer( - ChangeLogMessageSerializer, - TaggableModelSerializer, - CustomFieldModelSerializer, - ValidatedModelSerializer -): - """ - Adds support for custom fields and tags. - """ - pass - - -class NestedGroupModelSerializer(NetBoxModelSerializer): - """ - Extends PrimaryModelSerializer to include MPTT support. - """ - _depth = serializers.IntegerField(source='level', read_only=True) - - -class BulkOperationSerializer(ChangeLogMessageSerializer): - id = serializers.IntegerField() +from .models import * +from .bulk import * diff --git a/netbox/netbox/api/serializers/bulk.py b/netbox/netbox/api/serializers/bulk.py new file mode 100644 index 000000000..c9fd28534 --- /dev/null +++ b/netbox/netbox/api/serializers/bulk.py @@ -0,0 +1,11 @@ +from rest_framework import serializers + +from .features import ChangeLogMessageSerializer + +__all__ = ( + 'BulkOperationSerializer', +) + + +class BulkOperationSerializer(ChangeLogMessageSerializer): + id = serializers.IntegerField() diff --git a/netbox/netbox/api/serializers/features.py b/netbox/netbox/api/serializers/features.py index 1ee92e828..00315868e 100644 --- a/netbox/netbox/api/serializers/features.py +++ b/netbox/netbox/api/serializers/features.py @@ -2,11 +2,13 @@ from rest_framework import serializers from rest_framework.fields import CreateOnlyDefault from extras.api.customfields import CustomFieldsDataField, CustomFieldDefaultValues +from .base import ValidatedModelSerializer from .nested import NestedTagSerializer __all__ = ( 'ChangeLogMessageSerializer', 'CustomFieldModelSerializer', + 'NetBoxModelSerializer', 'TaggableModelSerializer', ) @@ -76,3 +78,15 @@ class ChangeLogMessageSerializer(serializers.Serializer): if self.instance is not None: self.instance._changelog_message = self.validated_data.get('changelog_message') return super().save(**kwargs) + + +class NetBoxModelSerializer( + ChangeLogMessageSerializer, + TaggableModelSerializer, + CustomFieldModelSerializer, + ValidatedModelSerializer +): + """ + Adds support for custom fields and tags. + """ + pass diff --git a/netbox/netbox/api/serializers/models.py b/netbox/netbox/api/serializers/models.py new file mode 100644 index 000000000..5d81f5b9a --- /dev/null +++ b/netbox/netbox/api/serializers/models.py @@ -0,0 +1,31 @@ +from rest_framework import serializers + +from .features import NetBoxModelSerializer +from users.api.serializers_.mixins import OwnerMixin + +__all__ = ( + 'NestedGroupModelSerializer', + 'OrganizationalModelSerializer', + 'PrimaryModelSerializer', +) + + +class PrimaryModelSerializer(OwnerMixin, NetBoxModelSerializer): + """ + Base serializer class for models inheriting from PrimaryModel. + """ + pass + + +class NestedGroupModelSerializer(OwnerMixin, NetBoxModelSerializer): + """ + Base serializer class for models inheriting from NestedGroupModel. + """ + _depth = serializers.IntegerField(source='level', read_only=True) + + +class OrganizationalModelSerializer(OwnerMixin, NetBoxModelSerializer): + """ + Base serializer class for models inheriting from OrganizationalModel. + """ + pass diff --git a/netbox/netbox/api/views.py b/netbox/netbox/api/views.py index 6740700b8..d781ea969 100644 --- a/netbox/netbox/api/views.py +++ b/netbox/netbox/api/views.py @@ -5,6 +5,7 @@ from django.conf import settings from django_rq.queues import get_connection from drf_spectacular.types import OpenApiTypes from drf_spectacular.utils import extend_schema +from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.reverse import reverse from rest_framework.views import APIView @@ -12,6 +13,7 @@ from rq.worker import Worker from netbox.api.authentication import IsAuthenticatedOrLoginNotRequired from netbox.plugins.utils import get_installed_plugins +from users.api.serializers import UserSerializer from utilities.apps import get_installed_apps @@ -62,3 +64,15 @@ class StatusView(APIView): 'python-version': platform.python_version(), 'rq-workers-running': Worker.count(get_connection('default')), }) + + +class AuthenticationCheckView(APIView): + """ + Return the user making the request, if authenticated successfully. + """ + permission_classes = [IsAuthenticated] + + @extend_schema(responses={200: OpenApiTypes.OBJECT}) + def get(self, request): + serializer = UserSerializer(request.user, context={'request': request}) + return Response(serializer.data) diff --git a/netbox/netbox/authentication/__init__.py b/netbox/netbox/authentication/__init__.py index 25f9b902c..8596c59ab 100644 --- a/netbox/netbox/authentication/__init__.py +++ b/netbox/netbox/authentication/__init__.py @@ -184,14 +184,13 @@ class RemoteUserBackend(_RemoteUserBackend): else: user.groups.clear() logger.debug(f"Stripping user {user} from Groups") + + # Evaluate superuser status user.is_superuser = self._is_superuser(user) logger.debug(f"User {user} is Superuser: {user.is_superuser}") logger.debug( f"User {user} should be Superuser: {self._is_superuser(user)}") - user.is_staff = self._is_staff(user) - logger.debug(f"User {user} is Staff: {user.is_staff}") - logger.debug(f"User {user} should be Staff: {self._is_staff(user)}") user.save() return user @@ -251,19 +250,8 @@ class RemoteUserBackend(_RemoteUserBackend): return bool(result) def _is_staff(self, user): - logger = logging.getLogger('netbox.auth.RemoteUserBackend') - staff_groups = settings.REMOTE_AUTH_STAFF_GROUPS - logger.debug(f"Superuser Groups: {staff_groups}") - staff_users = settings.REMOTE_AUTH_STAFF_USERS - logger.debug(f"Staff Users :{staff_users}") - user_groups = set() - for g in user.groups.all(): - user_groups.add(g.name) - logger.debug(f"User {user.username} is in Groups:{user_groups}") - result = user.username in staff_users or ( - set(user_groups) & set(staff_groups)) - logger.debug(f"User {user.username} in Staff Users :{result}") - return bool(result) + # Retain for pre-v4.5 compatibility + return user.is_superuser def configure_user(self, request, user): logger = logging.getLogger('netbox.auth.RemoteUserBackend') diff --git a/netbox/netbox/configuration_example.py b/netbox/netbox/configuration_example.py index 2a4ffbcca..61e8c6df2 100644 --- a/netbox/netbox/configuration_example.py +++ b/netbox/netbox/configuration_example.py @@ -68,6 +68,16 @@ REDIS = { # https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-SECRET_KEY SECRET_KEY = '' +# Define a mapping of cryptographic peppers to use when hashing API tokens. A minimum of one pepper is required to +# enable v2 API tokens (NetBox v4.5+). Define peppers as a mapping of numeric ID to pepper value, as shown below. Each +# pepper must be at least 50 characters in length. +# +# API_TOKEN_PEPPERS = { +# 1: "", +# 2: "", +# } +API_TOKEN_PEPPERS = {} + ######################### # # @@ -81,9 +91,6 @@ ADMINS = [ # ('John Doe', 'jdoe@example.com'), ] -# Permit the retrieval of API tokens after their creation. -ALLOW_TOKEN_RETRIEVAL = False - # Enable any desired validators for local account passwords below. For a list of included validators, please see the # Django documentation at https://docs.djangoproject.com/en/stable/topics/auth/passwords/#password-validation. AUTH_PASSWORD_VALIDATORS = [ diff --git a/netbox/netbox/configuration_testing.py b/netbox/netbox/configuration_testing.py index 52973e94d..3e552e944 100644 --- a/netbox/netbox/configuration_testing.py +++ b/netbox/netbox/configuration_testing.py @@ -43,7 +43,9 @@ SECRET_KEY = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' DEFAULT_PERMISSIONS = {} -ALLOW_TOKEN_RETRIEVAL = True +API_TOKEN_PEPPERS = { + 1: 'TEST-VALUE-DO-NOT-USE-TEST-VALUE-DO-NOT-USE-TEST-VALUE-DO-NOT-USE', +} LOGGING = { 'version': 1, diff --git a/netbox/netbox/context_processors.py b/netbox/netbox/context_processors.py index d68236da8..eeeb442b4 100644 --- a/netbox/netbox/context_processors.py +++ b/netbox/netbox/context_processors.py @@ -33,7 +33,6 @@ def preferences(request): config.COPILOT_ENABLED and not django_settings.ISOLATED_DEPLOYMENT and user_preferences.get('ui.copilot_enabled', False) == 'true' ), - 'htmx_navigation': user_preferences.get('ui.htmx_navigation', False) == 'true', } diff --git a/netbox/netbox/filtersets.py b/netbox/netbox/filtersets.py index ea24efe48..7ed98209d 100644 --- a/netbox/netbox/filtersets.py +++ b/netbox/netbox/filtersets.py @@ -14,6 +14,7 @@ from core.models import ObjectChange from extras.choices import CustomFieldFilterLogicChoices from extras.filters import TagFilter, TagIDFilter from extras.models import CustomField, SavedFilter +from users.filterset_mixins import OwnerFilterMixin from utilities.constants import ( FILTER_CHAR_BASED_LOOKUP_MAP, FILTER_NEGATION_LOOKUP_MAP, FILTER_TREENODE_NEGATION_LOOKUP_MAP, FILTER_NUMERIC_BASED_LOOKUP_MAP @@ -25,8 +26,10 @@ __all__ = ( 'AttributeFiltersMixin', 'BaseFilterSet', 'ChangeLoggedModelFilterSet', + 'NestedGroupModelFilterSet', 'NetBoxModelFilterSet', 'OrganizationalModelFilterSet', + 'PrimaryModelFilterSet', ) STANDARD_LOOKUPS = ( @@ -149,6 +152,7 @@ class BaseFilterSet(django_filters.FilterSet): elif isinstance(existing_filter, ( django_filters.filters.CharFilter, + django_filters.ChoiceFilter, django_filters.MultipleChoiceFilter, filters.MultiValueCharFilter, filters.MultiValueMACAddressFilter @@ -328,9 +332,16 @@ class NetBoxModelFilterSet(ChangeLoggedModelFilterSet): return queryset -class OrganizationalModelFilterSet(NetBoxModelFilterSet): +class PrimaryModelFilterSet(OwnerFilterMixin, NetBoxModelFilterSet): """ - A base class for adding the search method to models which only expose the `name` and `slug` fields + Base filterset for models inheriting from PrimaryModel. + """ + pass + + +class OrganizationalModelFilterSet(OwnerFilterMixin, NetBoxModelFilterSet): + """ + Base filterset for models inheriting from OrganizationalModel. """ def search(self, queryset, name, value): if not value.strip(): @@ -342,9 +353,9 @@ class OrganizationalModelFilterSet(NetBoxModelFilterSet): ) -class NestedGroupModelFilterSet(NetBoxModelFilterSet): +class NestedGroupModelFilterSet(OwnerFilterMixin, NetBoxModelFilterSet): """ - A base FilterSet for models that inherit from NestedGroupModel + Base filterset for models inheriting from NestedGroupModel. """ def search(self, queryset, name, value): if value.strip(): diff --git a/netbox/netbox/forms/__init__.py b/netbox/netbox/forms/__init__.py index f88fb18bc..fa06fafa0 100644 --- a/netbox/netbox/forms/__init__.py +++ b/netbox/netbox/forms/__init__.py @@ -1,57 +1,5 @@ -import re - -from django import forms -from django.utils.translation import gettext_lazy as _ - -from netbox.search import LookupTypes -from netbox.search.backends import search_backend - -from .base import * - -LOOKUP_CHOICES = ( - ('', _('Partial match')), - (LookupTypes.EXACT, _('Exact match')), - (LookupTypes.STARTSWITH, _('Starts with')), - (LookupTypes.ENDSWITH, _('Ends with')), - (LookupTypes.REGEX, _('Regex')), -) - - -class SearchForm(forms.Form): - q = forms.CharField( - label=_('Search'), - widget=forms.TextInput( - attrs={ - 'hx-get': '', - 'hx-target': '#object_list', - 'hx-trigger': 'keyup[target.value.length >= 3] changed delay:500ms', - } - ) - ) - obj_types = forms.MultipleChoiceField( - choices=[], - required=False, - label=_('Object type(s)') - ) - lookup = forms.ChoiceField( - choices=LOOKUP_CHOICES, - initial=LookupTypes.PARTIAL, - required=False, - label=_('Lookup') - ) - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - self.fields['obj_types'].choices = search_backend.get_object_types() - - def clean(self): - - # Validate regular expressions - if self.cleaned_data['lookup'] == LookupTypes.REGEX: - try: - re.compile(self.cleaned_data['q']) - except re.error as e: - raise forms.ValidationError({ - 'q': f'Invalid regular expression: {e}' - }) +from .model_forms import * +from .bulk_import import * +from .bulk_edit import * +from .filtersets import * +from .search import * diff --git a/netbox/netbox/forms/base.py b/netbox/netbox/forms/base.py deleted file mode 100644 index 1b22e83f8..000000000 --- a/netbox/netbox/forms/base.py +++ /dev/null @@ -1,210 +0,0 @@ -import json - -from django import forms -from django.contrib.contenttypes.models import ContentType -from django.db import models -from django.db.models import Q -from django.utils.translation import gettext_lazy as _ - -from core.models import ObjectType -from extras.choices import * -from extras.models import CustomField, Tag -from utilities.forms import BulkEditForm, CSVModelForm -from utilities.forms.fields import CSVModelMultipleChoiceField, DynamicModelMultipleChoiceField -from utilities.forms.mixins import CheckLastUpdatedMixin -from .mixins import ChangelogMessageMixin, CustomFieldsMixin, SavedFiltersMixin, TagsMixin - -__all__ = ( - 'NetBoxModelForm', - 'NetBoxModelImportForm', - 'NetBoxModelBulkEditForm', - 'NetBoxModelFilterSetForm', -) - - -class NetBoxModelForm(ChangelogMessageMixin, CheckLastUpdatedMixin, CustomFieldsMixin, TagsMixin, forms.ModelForm): - """ - Base form for creating & editing NetBox models. Extends Django's ModelForm to add support for custom fields. - - Attributes: - fieldsets: An iterable of FieldSets which define a name and set of fields to display per section of - the rendered form (optional). If not defined, the all fields will be rendered as a single section. - """ - fieldsets = () - - def _get_content_type(self): - return ContentType.objects.get_for_model(self._meta.model) - - def _get_form_field(self, customfield): - if self.instance.pk: - form_field = customfield.to_form_field(set_initial=False) - initial = self.instance.custom_field_data.get(customfield.name) - if customfield.type == CustomFieldTypeChoices.TYPE_JSON: - form_field.initial = json.dumps(initial) - else: - form_field.initial = initial - return form_field - - return customfield.to_form_field() - - def clean(self): - - # Save custom field data on instance - for cf_name, customfield in self.custom_fields.items(): - if cf_name not in self.fields: - # Custom fields may be absent when performing bulk updates via import - continue - key = cf_name[3:] # Strip "cf_" from field name - value = self.cleaned_data.get(cf_name) - - # Convert "empty" values to null - if value in self.fields[cf_name].empty_values: - self.instance.custom_field_data[key] = None - else: - if customfield.type == CustomFieldTypeChoices.TYPE_JSON and type(value) is str: - value = json.loads(value) - self.instance.custom_field_data[key] = customfield.serialize(value) - - return super().clean() - - def _post_clean(self): - """ - Override BaseModelForm's _post_clean() to store many-to-many field values on the model instance. - """ - self.instance._m2m_values = {} - for field in self.instance._meta.local_many_to_many: - if field.name in self.cleaned_data: - self.instance._m2m_values[field.name] = list(self.cleaned_data[field.name]) - - return super()._post_clean() - - -class NetBoxModelImportForm(CSVModelForm, NetBoxModelForm): - """ - Base form for creating a NetBox objects from CSV data. Used for bulk importing. - """ - tags = CSVModelMultipleChoiceField( - label=_('Tags'), - queryset=Tag.objects.all(), - required=False, - to_field_name='slug', - help_text=_('Tag slugs separated by commas, encased with double quotes (e.g. "tag1,tag2,tag3")') - ) - - def _get_custom_fields(self, content_type): - return CustomField.objects.filter( - object_types=content_type, - ui_editable=CustomFieldUIEditableChoices.YES - ) - - def _get_form_field(self, customfield): - return customfield.to_form_field(for_csv_import=True) - - def clean(self): - """ - Cleans data in a form, ensuring proper handling of model fields with `null=True`. - Overrides the `clean` method from the parent form to process and sanitize cleaned - data for defined fields in the associated model. - """ - super().clean() - cleaned = self.cleaned_data - - model = getattr(self._meta, "model", None) - if not model: - return cleaned - - for f in model._meta.get_fields(): - # Only forward, DB-backed fields (skip M2M & reverse relations) - if not isinstance(f, models.Field) or not f.concrete or f.many_to_many: - continue - - if getattr(f, "null", False): - name = f.name - if name not in cleaned: - continue - val = cleaned[name] - # Only coerce empty strings; leave other types alone - if isinstance(val, str) and val.strip() == "": - cleaned[name] = None - - return cleaned - - -class NetBoxModelBulkEditForm(ChangelogMessageMixin, CustomFieldsMixin, BulkEditForm): - """ - Base form for modifying multiple NetBox objects (of the same type) in bulk via the UI. Adds support for custom - fields and adding/removing tags. - - Attributes: - fieldsets: An iterable of two-tuples which define a heading and field set to display per section of - the rendered form (optional). If not defined, the all fields will be rendered as a single section. - """ - fieldsets = None - - pk = forms.ModelMultipleChoiceField( - queryset=None, # Set from self.model on init - widget=forms.MultipleHiddenInput - ) - add_tags = DynamicModelMultipleChoiceField( - label=_('Add tags'), - queryset=Tag.objects.all(), - required=False - ) - remove_tags = DynamicModelMultipleChoiceField( - label=_('Remove tags'), - queryset=Tag.objects.all(), - required=False - ) - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - self.fields['pk'].queryset = self.model.objects.all() - - # Restrict tag fields by model - object_type = ObjectType.objects.get_for_model(self.model) - self.fields['add_tags'].widget.add_query_param('for_object_type_id', object_type.pk) - self.fields['remove_tags'].widget.add_query_param('for_object_type_id', object_type.pk) - - self._extend_nullable_fields() - - def _get_form_field(self, customfield): - return customfield.to_form_field(set_initial=False, enforce_required=False) - - def _extend_nullable_fields(self): - nullable_custom_fields = [ - name for name, customfield in self.custom_fields.items() - if (not customfield.required and customfield.ui_editable == CustomFieldUIEditableChoices.YES) - ] - self.nullable_fields = (*self.nullable_fields, *nullable_custom_fields) - - -class NetBoxModelFilterSetForm(CustomFieldsMixin, SavedFiltersMixin, forms.Form): - """ - Base form for FilerSet forms. These are used to filter object lists in the NetBox UI. Note that the - corresponding FilterSet *must* provide a `q` filter. - - Attributes: - model: The model class associated with the form - fieldsets: An iterable of two-tuples which define a heading and field set to display per section of - the rendered form (optional). If not defined, the all fields will be rendered as a single section. - selector_fields: An iterable of names of fields to display by default when rendering the form as - a selector widget - """ - q = forms.CharField( - required=False, - label=_('Search') - ) - - selector_fields = ('filter_id', 'q') - - def _get_custom_fields(self, content_type): - return super()._get_custom_fields(content_type).exclude( - Q(filter_logic=CustomFieldFilterLogicChoices.FILTER_DISABLED) | - Q(type=CustomFieldTypeChoices.TYPE_JSON) - ) - - def _get_form_field(self, customfield): - return customfield.to_form_field( - set_initial=False, enforce_required=False, enforce_visibility=False, for_filterset_form=True - ) diff --git a/netbox/netbox/forms/bulk_edit.py b/netbox/netbox/forms/bulk_edit.py new file mode 100644 index 000000000..182342106 --- /dev/null +++ b/netbox/netbox/forms/bulk_edit.py @@ -0,0 +1,106 @@ +from django import forms +from django.utils.translation import gettext_lazy as _ + +from core.models import ObjectType +from extras.choices import * +from extras.models import Tag +from utilities.forms import BulkEditForm +from utilities.forms.fields import CommentField, DynamicModelMultipleChoiceField +from .mixins import ChangelogMessageMixin, CustomFieldsMixin, OwnerMixin + +__all__ = ( + 'NestedGroupModelBulkEditForm', + 'NetBoxModelBulkEditForm', + 'OrganizationalModelBulkEditForm', + 'PrimaryModelBulkEditForm', +) + + +class NetBoxModelBulkEditForm(ChangelogMessageMixin, CustomFieldsMixin, BulkEditForm): + """ + Base form for modifying multiple NetBox objects (of the same type) in bulk via the UI. Adds support for custom + fields and adding/removing tags. + + Attributes: + fieldsets: An iterable of two-tuples which define a heading and field set to display per section of + the rendered form (optional). If not defined, the all fields will be rendered as a single section. + """ + fieldsets = None + + pk = forms.ModelMultipleChoiceField( + queryset=None, # Set from self.model on init + widget=forms.MultipleHiddenInput + ) + add_tags = DynamicModelMultipleChoiceField( + label=_('Add tags'), + queryset=Tag.objects.all(), + required=False + ) + remove_tags = DynamicModelMultipleChoiceField( + label=_('Remove tags'), + queryset=Tag.objects.all(), + required=False + ) + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + self.fields['pk'].queryset = self.model.objects.all() + + # Restrict tag fields by model + object_type = ObjectType.objects.get_for_model(self.model) + self.fields['add_tags'].widget.add_query_param('for_object_type_id', object_type.pk) + self.fields['remove_tags'].widget.add_query_param('for_object_type_id', object_type.pk) + + self._extend_nullable_fields() + + def _get_form_field(self, customfield): + return customfield.to_form_field(set_initial=False, enforce_required=False) + + def _extend_nullable_fields(self): + nullable_common_fields = ['owner'] + nullable_custom_fields = [ + name for name, customfield in self.custom_fields.items() + if (not customfield.required and customfield.ui_editable == CustomFieldUIEditableChoices.YES) + ] + self.nullable_fields = ( + *self.nullable_fields, + *nullable_common_fields, + *nullable_custom_fields, + ) + + +class PrimaryModelBulkEditForm(OwnerMixin, NetBoxModelBulkEditForm): + """ + Bulk edit form for models which inherit from PrimaryModel. + """ + description = forms.CharField( + label=_('Description'), + max_length=100, + required=False + ) + comments = CommentField() + + +class OrganizationalModelBulkEditForm(OwnerMixin, NetBoxModelBulkEditForm): + """ + Bulk edit form for models which inherit from OrganizationalModel. + """ + description = forms.CharField( + label=_('Description'), + max_length=200, + required=False + ) + comments = CommentField() + + +class NestedGroupModelBulkEditForm(OwnerMixin, NetBoxModelBulkEditForm): + """ + Bulk edit form for models which inherit from NestedGroupModel. + """ + description = forms.CharField( + label=_('Description'), + max_length=200, + required=False + ) + comments = CommentField() diff --git a/netbox/netbox/forms/bulk_import.py b/netbox/netbox/forms/bulk_import.py new file mode 100644 index 000000000..9d04135d4 --- /dev/null +++ b/netbox/netbox/forms/bulk_import.py @@ -0,0 +1,99 @@ +from django import forms +from django.db import models +from django.utils.translation import gettext_lazy as _ + +from extras.choices import * +from extras.models import CustomField, Tag +from users.models import Owner +from utilities.forms import CSVModelForm +from utilities.forms.fields import CSVModelMultipleChoiceField, CSVModelChoiceField, SlugField +from .model_forms import NetBoxModelForm + +__all__ = ( + 'NestedGroupModelImportForm', + 'NetBoxModelImportForm', + 'OrganizationalModelImportForm', + 'OwnerCSVMixin', + 'PrimaryModelImportForm' +) + + +class NetBoxModelImportForm(CSVModelForm, NetBoxModelForm): + """ + Base form for creating NetBox objects from CSV data. Used for bulk importing. + """ + tags = CSVModelMultipleChoiceField( + label=_('Tags'), + queryset=Tag.objects.all(), + required=False, + to_field_name='slug', + help_text=_('Tag slugs separated by commas, encased with double quotes (e.g. "tag1,tag2,tag3")') + ) + + def _get_custom_fields(self, content_type): + return CustomField.objects.filter( + object_types=content_type, + ui_editable=CustomFieldUIEditableChoices.YES + ) + + def _get_form_field(self, customfield): + return customfield.to_form_field(for_csv_import=True) + + def clean(self): + """ + Cleans data in a form, ensuring proper handling of model fields with `null=True`. + Overrides the `clean` method from the parent form to process and sanitize cleaned + data for defined fields in the associated model. + """ + super().clean() + cleaned = self.cleaned_data + + model = getattr(self._meta, "model", None) + if not model: + return cleaned + + for f in model._meta.get_fields(): + # Only forward, DB-backed fields (skip M2M & reverse relations) + if not isinstance(f, models.Field) or not f.concrete or f.many_to_many: + continue + + if getattr(f, "null", False): + name = f.name + if name not in cleaned: + continue + val = cleaned[name] + # Only coerce empty strings; leave other types alone + if isinstance(val, str) and val.strip() == "": + cleaned[name] = None + + return cleaned + + +class OwnerCSVMixin(forms.Form): + owner = CSVModelChoiceField( + queryset=Owner.objects.all(), + required=False, + to_field_name='name', + help_text=_("Name of the object's owner") + ) + + +class PrimaryModelImportForm(OwnerCSVMixin, NetBoxModelImportForm): + """ + Bulk import form for models which inherit from PrimaryModel. + """ + pass + + +class OrganizationalModelImportForm(OwnerCSVMixin, NetBoxModelImportForm): + """ + Bulk import form for models which inherit from OrganizationalModel. + """ + slug = SlugField() + + +class NestedGroupModelImportForm(OwnerCSVMixin, NetBoxModelImportForm): + """ + Bulk import form for models which inherit from NestedGroupModel. + """ + slug = SlugField() diff --git a/netbox/netbox/forms/filtersets.py b/netbox/netbox/forms/filtersets.py new file mode 100644 index 000000000..d334ee914 --- /dev/null +++ b/netbox/netbox/forms/filtersets.py @@ -0,0 +1,76 @@ +from django import forms +from django.db.models import Q +from django.utils.translation import gettext_lazy as _ + +from extras.choices import * +from users.models import Owner +from utilities.forms.fields import DynamicModelChoiceField, QueryField +from utilities.forms.mixins import FilterModifierMixin +from .mixins import CustomFieldsMixin, SavedFiltersMixin + +__all__ = ( + 'NestedGroupModelFilterSetForm', + 'NetBoxModelFilterSetForm', + 'OrganizationalModelFilterSetForm', + 'PrimaryModelFilterSetForm', +) + + +class NetBoxModelFilterSetForm(FilterModifierMixin, CustomFieldsMixin, SavedFiltersMixin, forms.Form): + """ + Base form for FilerSet forms. These are used to filter object lists in the NetBox UI. Note that the + corresponding FilterSet *must* provide a `q` filter. + + Attributes: + model: The model class associated with the form + fieldsets: An iterable of two-tuples which define a heading and field set to display per section of + the rendered form (optional). If not defined, the all fields will be rendered as a single section. + selector_fields: An iterable of names of fields to display by default when rendering the form as + a selector widget + """ + q = QueryField( + required=False, + label=_('Search') + ) + + selector_fields = ('filter_id', 'q') + + def _get_custom_fields(self, content_type): + return super()._get_custom_fields(content_type).exclude( + Q(filter_logic=CustomFieldFilterLogicChoices.FILTER_DISABLED) | + Q(type=CustomFieldTypeChoices.TYPE_JSON) + ) + + def _get_form_field(self, customfield): + return customfield.to_form_field( + set_initial=False, enforce_required=False, enforce_visibility=False, for_filterset_form=True + ) + + +class OwnerFilterMixin(forms.Form): + owner_id = DynamicModelChoiceField( + queryset=Owner.objects.all(), + required=False, + label=_('Owner'), + ) + + +class PrimaryModelFilterSetForm(OwnerFilterMixin, NetBoxModelFilterSetForm): + """ + FilterSet form for models which inherit from PrimaryModel. + """ + pass + + +class OrganizationalModelFilterSetForm(OwnerFilterMixin, NetBoxModelFilterSetForm): + """ + FilterSet form for models which inherit from OrganizationalModel. + """ + pass + + +class NestedGroupModelFilterSetForm(OwnerFilterMixin, NetBoxModelFilterSetForm): + """ + FilterSet form for models which inherit from NestedGroupModel. + """ + pass diff --git a/netbox/netbox/forms/mixins.py b/netbox/netbox/forms/mixins.py index 4096ffb25..4ee11b0bb 100644 --- a/netbox/netbox/forms/mixins.py +++ b/netbox/netbox/forms/mixins.py @@ -4,11 +4,13 @@ from django.utils.translation import gettext as _ from core.models import ObjectType from extras.choices import * from extras.models import * -from utilities.forms.fields import DynamicModelMultipleChoiceField +from users.models import Owner +from utilities.forms.fields import DynamicModelChoiceField, DynamicModelMultipleChoiceField __all__ = ( 'ChangelogMessageMixin', 'CustomFieldsMixin', + 'OwnerMixin', 'SavedFiltersMixin', 'TagsMixin', ) @@ -118,3 +120,14 @@ class TagsMixin(forms.Form): object_type = ObjectType.objects.get_for_model(self._meta.model) if object_type and hasattr(self.fields['tags'].widget, 'add_query_param'): self.fields['tags'].widget.add_query_param('for_object_type_id', object_type.pk) + + +class OwnerMixin(forms.Form): + """ + Add an `owner` field to forms for models which support Owner assignment. + """ + owner = DynamicModelChoiceField( + queryset=Owner.objects.all(), + required=False, + label=_('Owner'), + ) diff --git a/netbox/netbox/forms/model_forms.py b/netbox/netbox/forms/model_forms.py new file mode 100644 index 000000000..49a724201 --- /dev/null +++ b/netbox/netbox/forms/model_forms.py @@ -0,0 +1,102 @@ +import json + +from django import forms +from django.contrib.contenttypes.models import ContentType + +from extras.choices import * +from utilities.forms.fields import CommentField, SlugField +from utilities.forms.mixins import CheckLastUpdatedMixin +from .mixins import ChangelogMessageMixin, CustomFieldsMixin, OwnerMixin, TagsMixin + +__all__ = ( + 'NestedGroupModelForm', + 'NetBoxModelForm', + 'OrganizationalModelForm', + 'PrimaryModelForm', +) + + +class NetBoxModelForm( + ChangelogMessageMixin, + CheckLastUpdatedMixin, + CustomFieldsMixin, + TagsMixin, + forms.ModelForm +): + """ + Base form for creating & editing NetBox models. Extends Django's ModelForm to add support for custom fields. + + Attributes: + fieldsets: An iterable of FieldSets which define a name and set of fields to display per section of + the rendered form (optional). If not defined, the all fields will be rendered as a single section. + """ + fieldsets = () + + def _get_content_type(self): + return ContentType.objects.get_for_model(self._meta.model) + + def _get_form_field(self, customfield): + if self.instance.pk: + form_field = customfield.to_form_field(set_initial=False) + initial = self.instance.custom_field_data.get(customfield.name) + if customfield.type == CustomFieldTypeChoices.TYPE_JSON: + form_field.initial = json.dumps(initial) + else: + form_field.initial = initial + return form_field + + return customfield.to_form_field() + + def clean(self): + + # Save custom field data on instance + for cf_name, customfield in self.custom_fields.items(): + if cf_name not in self.fields: + # Custom fields may be absent when performing bulk updates via import + continue + key = cf_name[3:] # Strip "cf_" from field name + value = self.cleaned_data.get(cf_name) + + # Convert "empty" values to null + if value in self.fields[cf_name].empty_values: + self.instance.custom_field_data[key] = None + else: + if customfield.type == CustomFieldTypeChoices.TYPE_JSON and type(value) is str: + value = json.loads(value) + self.instance.custom_field_data[key] = customfield.serialize(value) + + return super().clean() + + def _post_clean(self): + """ + Override BaseModelForm's _post_clean() to store many-to-many field values on the model instance. + """ + self.instance._m2m_values = {} + for field in self.instance._meta.local_many_to_many: + if field.name in self.cleaned_data: + self.instance._m2m_values[field.name] = list(self.cleaned_data[field.name]) + + return super()._post_clean() + + +class PrimaryModelForm(OwnerMixin, NetBoxModelForm): + """ + Form for models which inherit from PrimaryModel. + """ + comments = CommentField() + + +class OrganizationalModelForm(OwnerMixin, NetBoxModelForm): + """ + Form for models which inherit from OrganizationalModel. + """ + slug = SlugField() + comments = CommentField() + + +class NestedGroupModelForm(OwnerMixin, NetBoxModelForm): + """ + Form for models which inherit from NestedGroupModel. + """ + slug = SlugField() + comments = CommentField() diff --git a/netbox/netbox/forms/search.py b/netbox/netbox/forms/search.py new file mode 100644 index 000000000..855c8e273 --- /dev/null +++ b/netbox/netbox/forms/search.py @@ -0,0 +1,55 @@ +import re + +from django import forms +from django.utils.translation import gettext_lazy as _ + +from netbox.search import LookupTypes +from netbox.search.backends import search_backend + +LOOKUP_CHOICES = ( + ('', _('Partial match')), + (LookupTypes.EXACT, _('Exact match')), + (LookupTypes.STARTSWITH, _('Starts with')), + (LookupTypes.ENDSWITH, _('Ends with')), + (LookupTypes.REGEX, _('Regex')), +) + + +class SearchForm(forms.Form): + q = forms.CharField( + label=_('Search'), + widget=forms.TextInput( + attrs={ + 'hx-get': '', + 'hx-target': '#object_list', + 'hx-trigger': 'keyup[target.value.length >= 3] changed delay:500ms', + } + ) + ) + obj_types = forms.MultipleChoiceField( + choices=[], + required=False, + label=_('Object type(s)') + ) + lookup = forms.ChoiceField( + choices=LOOKUP_CHOICES, + initial=LookupTypes.PARTIAL, + required=False, + label=_('Lookup') + ) + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + self.fields['obj_types'].choices = search_backend.get_object_types() + + def clean(self): + + # Validate regular expressions + if self.cleaned_data['lookup'] == LookupTypes.REGEX: + try: + re.compile(self.cleaned_data['q']) + except re.error as e: + raise forms.ValidationError({ + 'q': f'Invalid regular expression: {e}' + }) diff --git a/netbox/netbox/graphql/filter_mixins.py b/netbox/netbox/graphql/filter_mixins.py index b77238325..3bb818907 100644 --- a/netbox/netbox/graphql/filter_mixins.py +++ b/netbox/netbox/graphql/filter_mixins.py @@ -4,19 +4,11 @@ from typing import TypeVar, TYPE_CHECKING, Annotated import strawberry import strawberry_django -from strawberry import ID -from strawberry_django import FilterLookup, DatetimeFilterLookup - -from core.graphql.filter_mixins import BaseFilterMixin, BaseObjectTypeFilterMixin, ChangeLogFilterMixin -from extras.graphql.filter_mixins import CustomFieldsFilterMixin, JournalEntriesFilterMixin, TagsFilterMixin +from strawberry_django import BaseFilterLookup, FilterLookup, DatetimeFilterLookup __all__ = ( 'DistanceFilterMixin', 'ImageAttachmentFilterMixin', - 'NestedGroupModelFilterMixin', - 'NetBoxModelFilterMixin', - 'OrganizationalModelFilterMixin', - 'PrimaryModelFilterMixin', 'SyncedDataFilterMixin', 'WeightFilterMixin', ) @@ -30,59 +22,23 @@ if TYPE_CHECKING: from extras.graphql.filters import * -class NetBoxModelFilterMixin( - ChangeLogFilterMixin, - CustomFieldsFilterMixin, - JournalEntriesFilterMixin, - TagsFilterMixin, - BaseObjectTypeFilterMixin, -): - pass - - @dataclass -class NestedGroupModelFilterMixin(NetBoxModelFilterMixin): - name: FilterLookup[str] | None = strawberry_django.filter_field() - slug: FilterLookup[str] | None = strawberry_django.filter_field() - description: FilterLookup[str] | None = strawberry_django.filter_field() - parent_id: ID | None = strawberry_django.filter_field() - - -@dataclass -class OrganizationalModelFilterMixin( - ChangeLogFilterMixin, - CustomFieldsFilterMixin, - TagsFilterMixin, - BaseObjectTypeFilterMixin, -): - name: FilterLookup[str] | None = strawberry_django.filter_field() - slug: FilterLookup[str] | None = strawberry_django.filter_field() - description: FilterLookup[str] | None = strawberry_django.filter_field() - - -@dataclass -class PrimaryModelFilterMixin(NetBoxModelFilterMixin): - description: FilterLookup[str] | None = strawberry_django.filter_field() - comments: FilterLookup[str] | None = strawberry_django.filter_field() - - -@dataclass -class ImageAttachmentFilterMixin(BaseFilterMixin): +class ImageAttachmentFilterMixin: images: Annotated['ImageAttachmentFilter', strawberry.lazy('extras.graphql.filters')] | None = ( strawberry_django.filter_field() ) @dataclass -class WeightFilterMixin(BaseFilterMixin): +class WeightFilterMixin: weight: FilterLookup[float] | None = strawberry_django.filter_field() - weight_unit: Annotated['WeightUnitEnum', strawberry.lazy('netbox.graphql.enums')] | None = ( + weight_unit: BaseFilterLookup[Annotated['WeightUnitEnum', strawberry.lazy('netbox.graphql.enums')]] | None = ( strawberry_django.filter_field() ) @dataclass -class SyncedDataFilterMixin(BaseFilterMixin): +class SyncedDataFilterMixin: data_source: Annotated['DataSourceFilter', strawberry.lazy('core.graphql.filters')] | None = ( strawberry_django.filter_field() ) @@ -97,8 +53,8 @@ class SyncedDataFilterMixin(BaseFilterMixin): @dataclass -class DistanceFilterMixin(BaseFilterMixin): +class DistanceFilterMixin: distance: FilterLookup[float] | None = strawberry_django.filter_field() - distance_unit: Annotated['DistanceUnitEnum', strawberry.lazy('netbox.graphql.enums')] | None = ( + distance_unit: BaseFilterLookup[Annotated['DistanceUnitEnum', strawberry.lazy('netbox.graphql.enums')]] | None = ( strawberry_django.filter_field() ) diff --git a/netbox/netbox/graphql/filters.py b/netbox/netbox/graphql/filters.py new file mode 100644 index 000000000..ca8a50371 --- /dev/null +++ b/netbox/netbox/graphql/filters.py @@ -0,0 +1,62 @@ +from dataclasses import dataclass +from typing import TYPE_CHECKING + +import strawberry_django +from strawberry import ID +from strawberry_django import FilterLookup + +from core.graphql.filter_mixins import ChangeLoggingMixin +from extras.graphql.filter_mixins import CustomFieldsFilterMixin, JournalEntriesFilterMixin, TagsFilterMixin + +if TYPE_CHECKING: + from .filters import * + +__all__ = ( + 'BaseModelFilter', + 'ChangeLoggedModelFilter', + 'NestedGroupModelFilter', + 'NetBoxModelFilter', + 'OrganizationalModelFilter', + 'PrimaryModelFilter', +) + + +@dataclass +class BaseModelFilter: + id: FilterLookup[ID] | None = strawberry_django.filter_field() + + +class ChangeLoggedModelFilter(ChangeLoggingMixin, BaseModelFilter): + pass + + +class NetBoxModelFilter( + CustomFieldsFilterMixin, + JournalEntriesFilterMixin, + TagsFilterMixin, + ChangeLoggingMixin, + BaseModelFilter +): + pass + + +@dataclass +class NestedGroupModelFilter(NetBoxModelFilter): + name: FilterLookup[str] | None = strawberry_django.filter_field() + slug: FilterLookup[str] | None = strawberry_django.filter_field() + description: FilterLookup[str] | None = strawberry_django.filter_field() + parent_id: ID | None = strawberry_django.filter_field() + + +@dataclass +class OrganizationalModelFilter(NetBoxModelFilter): + name: FilterLookup[str] | None = strawberry_django.filter_field() + slug: FilterLookup[str] | None = strawberry_django.filter_field() + description: FilterLookup[str] | None = strawberry_django.filter_field() + comments: FilterLookup[str] | None = strawberry_django.filter_field() + + +@dataclass +class PrimaryModelFilter(NetBoxModelFilter): + description: FilterLookup[str] | None = strawberry_django.filter_field() + comments: FilterLookup[str] | None = strawberry_django.filter_field() diff --git a/netbox/netbox/graphql/schema.py b/netbox/netbox/graphql/schema.py index c840e769c..a7609c9d2 100644 --- a/netbox/netbox/graphql/schema.py +++ b/netbox/netbox/graphql/schema.py @@ -1,7 +1,7 @@ import strawberry from django.conf import settings from strawberry_django.optimizer import DjangoOptimizerExtension -from strawberry.extensions import MaxAliasesLimiter # , SchemaExtension +from strawberry.extensions import MaxAliasesLimiter from strawberry.schema.config import StrawberryConfig from circuits.graphql.schema import CircuitsQuery diff --git a/netbox/netbox/graphql/types.py b/netbox/netbox/graphql/types.py index bdc38b349..df569390d 100644 --- a/netbox/netbox/graphql/types.py +++ b/netbox/netbox/graphql/types.py @@ -6,13 +6,16 @@ from django.contrib.contenttypes.models import ContentType from core.graphql.mixins import ChangelogMixin from core.models import ObjectType as ObjectType_ from extras.graphql.mixins import CustomFieldsMixin, JournalEntriesMixin, TagsMixin +from users.graphql.mixins import OwnerMixin __all__ = ( 'BaseObjectType', 'ContentTypeType', + 'NestedGroupObjectType', + 'NetBoxObjectType', 'ObjectType', 'OrganizationalObjectType', - 'NetBoxObjectType', + 'PrimaryObjectType', ) @@ -53,14 +56,44 @@ class ObjectType( pass -class OrganizationalObjectType( +class PrimaryObjectType( ChangelogMixin, CustomFieldsMixin, + JournalEntriesMixin, TagsMixin, + OwnerMixin, BaseObjectType ): """ - Base type for organizational models + Base GraphQL type for models which inherit from PrimaryModel. + """ + pass + + +class OrganizationalObjectType( + ChangelogMixin, + CustomFieldsMixin, + JournalEntriesMixin, + TagsMixin, + OwnerMixin, + BaseObjectType +): + """ + Base GraphQL type for models which inherit from OrganizationalModel. + """ + pass + + +class NestedGroupObjectType( + ChangelogMixin, + CustomFieldsMixin, + JournalEntriesMixin, + TagsMixin, + OwnerMixin, + BaseObjectType +): + """ + Base GraphQL type for models which inherit from NestedGroupModel. """ pass @@ -72,9 +105,6 @@ class NetBoxObjectType( TagsMixin, BaseObjectType ): - """ - GraphQL type for most NetBox models. Includes support for custom fields, change logging, journaling, and tags. - """ pass diff --git a/netbox/netbox/models/__init__.py b/netbox/netbox/models/__init__.py index f07f75736..496b4c4db 100644 --- a/netbox/netbox/models/__init__.py +++ b/netbox/netbox/models/__init__.py @@ -8,12 +8,12 @@ from django.utils.translation import gettext_lazy as _ from mptt.models import MPTTModel, TreeForeignKey from netbox.models.features import * +from netbox.models.mixins import OwnerMixin from utilities.mptt import TreeManager from utilities.querysets import RestrictedQuerySet -from utilities.views import get_viewname - __all__ = ( + 'AdminModel', 'ChangeLoggedModel', 'NestedGroupModel', 'NetBoxModel', @@ -43,6 +43,7 @@ class NetBoxFeatureSet( return f'{settings.STATIC_URL}docs/models/{self._meta.app_label}/{self._meta.model_name}/' def get_absolute_url(self): + from utilities.views import get_viewname return reverse(get_viewname(self), args=[self.pk]) @@ -50,21 +51,15 @@ class NetBoxFeatureSet( # Base model classes # -class ChangeLoggedModel(ChangeLoggingMixin, CustomValidationMixin, EventRulesMixin, models.Model): +class BaseModel(models.Model): """ - Base model for ancillary models; provides limited functionality for models which don't - support NetBox's full feature set. - """ - objects = RestrictedQuerySet.as_manager() + A global base model for all NetBox objects. - class Meta: - abstract = True - - -class NetBoxModel(NetBoxFeatureSet, models.Model): - """ - Base model for most object types. Suitable for use by plugins. + This class provides some important overrides to Django's default functionality, such as + - Overriding the default manager to use RestrictedQuerySet + - Extending `clean()` to validate GenericForeignKey fields """ + objects = RestrictedQuerySet.as_manager() class Meta: @@ -103,11 +98,30 @@ class NetBoxModel(NetBoxFeatureSet, models.Model): setattr(self, field.name, obj) +class ChangeLoggedModel(ChangeLoggingMixin, CustomValidationMixin, EventRulesMixin, BaseModel): + """ + Base model for ancillary models; provides limited functionality for models which don't + support NetBox's full feature set. + """ + + class Meta: + abstract = True + + +class NetBoxModel(NetBoxFeatureSet, BaseModel): + """ + Base model for most object types. Suitable for use by plugins. + """ + + class Meta: + abstract = True + + # # NetBox internal base models # -class PrimaryModel(NetBoxModel): +class PrimaryModel(OwnerMixin, NetBoxModel): """ Primary models represent real objects within the infrastructure being modeled. """ @@ -125,7 +139,7 @@ class PrimaryModel(NetBoxModel): abstract = True -class NestedGroupModel(NetBoxFeatureSet, MPTTModel): +class NestedGroupModel(OwnerMixin, NetBoxModel, MPTTModel): """ Base model for objects which are used to form a hierarchy (regions, locations, etc.). These models nest recursively using MPTT. Within each parent, each child instance must have a unique name. @@ -177,7 +191,7 @@ class NestedGroupModel(NetBoxFeatureSet, MPTTModel): }) -class OrganizationalModel(NetBoxFeatureSet, models.Model): +class OrganizationalModel(OwnerMixin, NetBoxModel): """ Organizational models are those which are used solely to categorize and qualify other objects, and do not convey any real information about the infrastructure being modeled (for example, functional device roles). Organizational @@ -201,8 +215,10 @@ class OrganizationalModel(NetBoxFeatureSet, models.Model): max_length=200, blank=True ) - - objects = RestrictedQuerySet.as_manager() + comments = models.TextField( + verbose_name=_('comments'), + blank=True + ) class Meta: abstract = True @@ -210,3 +226,26 @@ class OrganizationalModel(NetBoxFeatureSet, models.Model): def __str__(self): return self.name + + +class AdminModel( + BookmarksMixin, + CloningMixin, + CustomLinksMixin, + CustomValidationMixin, + EventRulesMixin, + ExportTemplatesMixin, + NotificationsMixin, + BaseModel, +): + """ + A model which represents an administrative resource. + """ + description = models.CharField( + verbose_name=_('description'), + max_length=200, + blank=True + ) + + class Meta: + abstract = True diff --git a/netbox/netbox/models/mixins.py b/netbox/netbox/models/mixins.py index 13af8aaf5..ef1cd9e96 100644 --- a/netbox/netbox/models/mixins.py +++ b/netbox/netbox/models/mixins.py @@ -7,10 +7,26 @@ from utilities.conversion import to_grams, to_meters __all__ = ( 'DistanceMixin', + 'OwnerMixin', 'WeightMixin', ) +class OwnerMixin(models.Model): + """ + Adds a ForeignKey to users.Owner to indicate an object's owner. + """ + owner = models.ForeignKey( + to='users.Owner', + on_delete=models.PROTECT, + blank=True, + null=True + ) + + class Meta: + abstract = True + + class WeightMixin(models.Model): weight = models.DecimalField( verbose_name=_('weight'), diff --git a/netbox/netbox/navigation/menu.py b/netbox/netbox/navigation/menu.py index ac4c2b492..34b66ada0 100644 --- a/netbox/netbox/navigation/menu.py +++ b/netbox/netbox/navigation/menu.py @@ -465,6 +465,13 @@ ADMIN_MENU = Menu( ), ), ), + MenuGroup( + label=_('Ownership'), + items=( + get_model_item('users', 'ownergroup', _('Owner Groups')), + get_model_item('users', 'owner', _('Owners')), + ), + ), MenuGroup( label=_('System'), items=( diff --git a/netbox/netbox/plugins/views.py b/netbox/netbox/plugins/views.py index feee78e82..f413b8032 100644 --- a/netbox/netbox/plugins/views.py +++ b/netbox/netbox/plugins/views.py @@ -3,12 +3,12 @@ from collections import OrderedDict from django.apps import apps from django.urls.exceptions import NoReverseMatch from drf_spectacular.utils import extend_schema -from rest_framework import permissions from rest_framework.response import Response from rest_framework.reverse import reverse from rest_framework.views import APIView from netbox.registry import registry +from utilities.api import IsSuperuser @extend_schema(exclude=True) @@ -16,7 +16,7 @@ class InstalledPluginsAPIView(APIView): """ API view for listing all installed plugins """ - permission_classes = [permissions.IsAdminUser] + permission_classes = [IsSuperuser] _ignore_model_permissions = True schema = None diff --git a/netbox/netbox/preferences.py b/netbox/netbox/preferences.py index 942efe38f..ba8a33262 100644 --- a/netbox/netbox/preferences.py +++ b/netbox/netbox/preferences.py @@ -26,16 +26,6 @@ def get_csv_delimiters(): PREFERENCES = { # User interface - 'ui.htmx_navigation': UserPreference( - label=_('HTMX Navigation'), - choices=( - ('', _('Disabled')), - ('true', _('Enabled')), - ), - description=_('Enable dynamic UI navigation'), - default=False, - warning=_('Experimental feature') - ), 'locale.language': UserPreference( label=_('Language'), choices=( diff --git a/netbox/netbox/registry.py b/netbox/netbox/registry.py index fe5ce4301..a28fd17e7 100644 --- a/netbox/netbox/registry.py +++ b/netbox/netbox/registry.py @@ -26,6 +26,7 @@ registry = Registry({ 'data_backends': dict(), 'denormalized_fields': collections.defaultdict(list), 'event_types': dict(), + 'filtersets': dict(), 'model_features': dict(), 'models': collections.defaultdict(set), 'plugins': dict(), diff --git a/netbox/netbox/settings.py b/netbox/netbox/settings.py index fff7cec84..d7aa7e5c9 100644 --- a/netbox/netbox/settings.py +++ b/netbox/netbox/settings.py @@ -20,6 +20,7 @@ from netbox.plugins import PluginConfig from netbox.registry import registry import storages.utils # type: ignore from utilities.release import load_release_data +from utilities.security import validate_peppers from utilities.string import trailing_slash from .monkey import get_unique_validators @@ -43,9 +44,9 @@ VERSION = RELEASE.full_version # Retained for backward compatibility BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Validate Python version -if sys.version_info < (3, 10): +if sys.version_info < (3, 12): raise RuntimeError( - f"NetBox requires Python 3.10 or later. (Currently installed: Python {platform.python_version()})" + f"NetBox requires Python 3.12 or later. (Currently installed: Python {platform.python_version()})" ) # @@ -75,8 +76,8 @@ elif hasattr(configuration, 'DATABASE') and hasattr(configuration, 'DATABASES'): # Set static config parameters ADMINS = getattr(configuration, 'ADMINS', []) -ALLOW_TOKEN_RETRIEVAL = getattr(configuration, 'ALLOW_TOKEN_RETRIEVAL', False) ALLOWED_HOSTS = getattr(configuration, 'ALLOWED_HOSTS') # Required +API_TOKEN_PEPPERS = getattr(configuration, 'API_TOKEN_PEPPERS', {}) AUTH_PASSWORD_VALIDATORS = getattr(configuration, 'AUTH_PASSWORD_VALIDATORS', [ { "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", @@ -136,6 +137,7 @@ EVENTS_PIPELINE = getattr(configuration, 'EVENTS_PIPELINE', [ EXEMPT_VIEW_PERMISSIONS = getattr(configuration, 'EXEMPT_VIEW_PERMISSIONS', []) FIELD_CHOICES = getattr(configuration, 'FIELD_CHOICES', {}) FILE_UPLOAD_MAX_MEMORY_SIZE = getattr(configuration, 'FILE_UPLOAD_MAX_MEMORY_SIZE', 2621440) +GRAPHQL_DEFAULT_VERSION = getattr(configuration, 'GRAPHQL_DEFAULT_VERSION', 1) GRAPHQL_MAX_ALIASES = getattr(configuration, 'GRAPHQL_MAX_ALIASES', 10) HOSTNAME = getattr(configuration, 'HOSTNAME', platform.node()) HTTP_PROXIES = getattr(configuration, 'HTTP_PROXIES', {}) @@ -174,8 +176,6 @@ REMOTE_AUTH_SUPERUSERS = getattr(configuration, 'REMOTE_AUTH_SUPERUSERS', []) REMOTE_AUTH_USER_EMAIL = getattr(configuration, 'REMOTE_AUTH_USER_EMAIL', 'HTTP_REMOTE_USER_EMAIL') REMOTE_AUTH_USER_FIRST_NAME = getattr(configuration, 'REMOTE_AUTH_USER_FIRST_NAME', 'HTTP_REMOTE_USER_FIRST_NAME') REMOTE_AUTH_USER_LAST_NAME = getattr(configuration, 'REMOTE_AUTH_USER_LAST_NAME', 'HTTP_REMOTE_USER_LAST_NAME') -REMOTE_AUTH_STAFF_GROUPS = getattr(configuration, 'REMOTE_AUTH_STAFF_GROUPS', []) -REMOTE_AUTH_STAFF_USERS = getattr(configuration, 'REMOTE_AUTH_STAFF_USERS', []) # Required by extras/migrations/0109_script_models.py REPORTS_ROOT = getattr(configuration, 'REPORTS_ROOT', os.path.join(BASE_DIR, 'reports')).rstrip('/') RQ_DEFAULT_TIMEOUT = getattr(configuration, 'RQ_DEFAULT_TIMEOUT', 300) @@ -229,6 +229,12 @@ if len(SECRET_KEY) < 50: f" python {BASE_DIR}/generate_secret_key.py" ) +# Validate API token peppers +if API_TOKEN_PEPPERS: + validate_peppers(API_TOKEN_PEPPERS) +else: + warnings.warn("API_TOKEN_PEPPERS is not defined. v2 API tokens cannot be used.") + # Validate update repo URL and timeout if RELEASE_CHECK_URL: try: diff --git a/netbox/netbox/tables/columns.py b/netbox/netbox/tables/columns.py index f480c2085..12b781cf4 100644 --- a/netbox/netbox/tables/columns.py +++ b/netbox/netbox/tables/columns.py @@ -270,7 +270,7 @@ class ActionsColumn(tables.Column): if not (self.actions or self.extra_buttons): return '' # Skip dummy records (e.g. available VLANs or IP ranges replacing individual IPs) - if type(record) is not model or not getattr(record, 'pk', None): + if not isinstance(record, model) or not getattr(record, 'pk', None): return '' if request := getattr(table, 'context', {}).get('request'): diff --git a/netbox/netbox/tables/tables.py b/netbox/netbox/tables/tables.py index 89a9c1ac2..a2ba13480 100644 --- a/netbox/netbox/tables/tables.py +++ b/netbox/netbox/tables/tables.py @@ -27,7 +27,10 @@ from .template_code import * __all__ = ( 'BaseTable', + 'NestedGroupModelTable', 'NetBoxTable', + 'OrganizationalModelTable', + 'PrimaryModelTable', 'SearchTable', ) @@ -267,6 +270,44 @@ class NetBoxTable(BaseTable): return '' +class PrimaryModelTable(NetBoxTable): + owner = tables.Column( + linkify=True, + verbose_name=_('Owner') + ) + comments = columns.MarkdownColumn( + verbose_name=_('Comments'), + ) + + +class OrganizationalModelTable(NetBoxTable): + owner = tables.Column( + linkify=True, + verbose_name=_('Owner') + ) + comments = columns.MarkdownColumn( + verbose_name=_('Comments'), + ) + + +class NestedGroupModelTable(NetBoxTable): + owner = tables.Column( + linkify=True, + verbose_name=_('Owner') + ) + name = columns.MPTTColumn( + verbose_name=_('Name'), + linkify=True + ) + parent = tables.Column( + verbose_name=_('Parent'), + linkify=True, + ) + comments = columns.MarkdownColumn( + verbose_name=_('Comments'), + ) + + class SearchTable(tables.Table): object_type = columns.ContentTypeColumn( verbose_name=_('Type'), diff --git a/netbox/netbox/tests/test_api.py b/netbox/netbox/tests/test_api.py index 61bbcd4c6..8392a49dd 100644 --- a/netbox/netbox/tests/test_api.py +++ b/netbox/netbox/tests/test_api.py @@ -32,6 +32,18 @@ class AppTest(APITestCase): self.assertEqual(response.status_code, 200) + def test_authentication_check(self): + url = reverse('api-authentication-check') + + # Test an unauthenticated request + response = self.client.get(f'{url}') + self.assertEqual(response.status_code, 403) + + # Test an authenticated request + response = self.client.get(f'{url}', **self.header) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.data['id'], self.user.pk) + class OptionalLimitOffsetPaginationTest(TestCase): diff --git a/netbox/netbox/tests/test_authentication.py b/netbox/netbox/tests/test_authentication.py index 9eb21661d..5ed335dbf 100644 --- a/netbox/netbox/tests/test_authentication.py +++ b/netbox/netbox/tests/test_authentication.py @@ -8,6 +8,7 @@ from rest_framework.test import APIClient from core.models import ObjectType from dcim.models import Rack, Site +from users.constants import TOKEN_PREFIX from users.models import Group, ObjectPermission, Token, User from utilities.testing import TestCase from utilities.testing.api import APITestCase @@ -16,67 +17,185 @@ from utilities.testing.api import APITestCase class TokenAuthenticationTestCase(APITestCase): @override_settings(LOGIN_REQUIRED=True, EXEMPT_VIEW_PERMISSIONS=['*']) - def test_token_authentication(self): - url = reverse('dcim-api:site-list') - + def test_no_token(self): # Request without a token should return a 403 - response = self.client.get(url) + response = self.client.get(reverse('dcim-api:site-list')) self.assertEqual(response.status_code, 403) + @override_settings(LOGIN_REQUIRED=True, EXEMPT_VIEW_PERMISSIONS=['*']) + def test_v1_token_valid(self): + # Create a v1 token + token = Token.objects.create(version=1, user=self.user) + # Valid token should return a 200 - token = Token.objects.create(user=self.user) - response = self.client.get(url, HTTP_AUTHORIZATION=f'Token {token.key}') - self.assertEqual(response.status_code, 200) + header = f'Token {token.token}' + response = self.client.get(reverse('dcim-api:site-list'), HTTP_AUTHORIZATION=header) + self.assertEqual(response.status_code, 200, response.data) # Check that the token's last_used time has been updated token.refresh_from_db() self.assertIsNotNone(token.last_used) + @override_settings(LOGIN_REQUIRED=True, EXEMPT_VIEW_PERMISSIONS=['*']) + def test_v1_token_invalid(self): + # Invalid token should return a 403 + header = 'Token XXXXXXXXXX' + response = self.client.get(reverse('dcim-api:site-list'), HTTP_AUTHORIZATION=header) + self.assertEqual(response.status_code, 403) + self.assertEqual(response.data['detail'], "Invalid v1 token") + + @override_settings(LOGIN_REQUIRED=True, EXEMPT_VIEW_PERMISSIONS=['*']) + def test_v2_token_valid(self): + # Create a v2 token + token = Token.objects.create(version=2, user=self.user) + + # Valid token should return a 200 + header = f'Bearer {TOKEN_PREFIX}{token.key}.{token.token}' + response = self.client.get(reverse('dcim-api:site-list'), HTTP_AUTHORIZATION=header) + self.assertEqual(response.status_code, 200, response.data) + + # Check that the token's last_used time has been updated + token.refresh_from_db() + self.assertIsNotNone(token.last_used) + + @override_settings(LOGIN_REQUIRED=True, EXEMPT_VIEW_PERMISSIONS=['*']) + def test_v2_token_invalid(self): + # Invalid token should return a 403 + header = f'Bearer {TOKEN_PREFIX}XXXXXX.XXXXXXXXXX' + response = self.client.get(reverse('dcim-api:site-list'), HTTP_AUTHORIZATION=header) + self.assertEqual(response.status_code, 403) + self.assertEqual(response.data['detail'], "Invalid v2 token") + + @override_settings(LOGIN_REQUIRED=True, EXEMPT_VIEW_PERMISSIONS=['*']) + def test_token_enabled(self): + url = reverse('dcim-api:site-list') + + # Create v1 & v2 tokens + token1 = Token.objects.create(version=1, user=self.user, enabled=True) + token2 = Token.objects.create(version=2, user=self.user, enabled=True) + + # Request with an enabled token should succeed + response = self.client.get(url, HTTP_AUTHORIZATION=f'Token {token1.token}') + self.assertEqual(response.status_code, 200) + response = self.client.get(url, HTTP_AUTHORIZATION=f'Bearer {TOKEN_PREFIX}{token2.key}.{token2.token}') + self.assertEqual(response.status_code, 200) + + # Request with a disabled token should fail + token1.enabled = False + token1.save() + token2.enabled = False + token2.save() + response = self.client.get(url, HTTP_AUTHORIZATION=f'Token {token1.token}') + self.assertEqual(response.status_code, 403) + self.assertEqual(response.data['detail'], 'Token disabled') + response = self.client.get(url, HTTP_AUTHORIZATION=f'Bearer {TOKEN_PREFIX}{token2.key}.{token2.token}') + self.assertEqual(response.status_code, 403) + self.assertEqual(response.data['detail'], 'Token disabled') + @override_settings(LOGIN_REQUIRED=True, EXEMPT_VIEW_PERMISSIONS=['*']) def test_token_expiration(self): url = reverse('dcim-api:site-list') - # Request without a non-expired token should succeed - token = Token.objects.create(user=self.user) - response = self.client.get(url, HTTP_AUTHORIZATION=f'Token {token.key}') + # Create v1 & v2 tokens + future = datetime.datetime(2100, 1, 1, tzinfo=datetime.timezone.utc) + token1 = Token.objects.create(version=1, user=self.user, expires=future) + token2 = Token.objects.create(version=2, user=self.user, expires=future) + + # Request with a non-expired token should succeed + response = self.client.get(url, HTTP_AUTHORIZATION=f'Token {token1.token}') + self.assertEqual(response.status_code, 200) + response = self.client.get(url, HTTP_AUTHORIZATION=f'Bearer {TOKEN_PREFIX}{token2.key}.{token2.token}') self.assertEqual(response.status_code, 200) # Request with an expired token should fail - token.expires = datetime.datetime(2020, 1, 1, tzinfo=datetime.timezone.utc) - token.save() - response = self.client.get(url, HTTP_AUTHORIZATION=f'Token {token.key}') + past = datetime.datetime(2020, 1, 1, tzinfo=datetime.timezone.utc) + token1.expires = past + token1.save() + token2.expires = past + token2.save() + response = self.client.get(url, HTTP_AUTHORIZATION=f'Token {token1.key}') + self.assertEqual(response.status_code, 403) + response = self.client.get(url, HTTP_AUTHORIZATION=f'Bearer {TOKEN_PREFIX}{token2.key}') self.assertEqual(response.status_code, 403) @override_settings(LOGIN_REQUIRED=True, EXEMPT_VIEW_PERMISSIONS=['*']) def test_token_write_enabled(self): url = reverse('dcim-api:site-list') - data = { - 'name': 'Site 1', - 'slug': 'site-1', - } + data = [ + { + 'name': 'Site 1', + 'slug': 'site-1', + }, + { + 'name': 'Site 2', + 'slug': 'site-2', + }, + ] + self.add_permissions('dcim.view_site', 'dcim.add_site') - # Request with a write-disabled token should fail - token = Token.objects.create(user=self.user, write_enabled=False) - response = self.client.post(url, data, format='json', HTTP_AUTHORIZATION=f'Token {token.key}') + # Create v1 & v2 tokens + token1 = Token.objects.create(version=1, user=self.user, write_enabled=False) + token2 = Token.objects.create(version=2, user=self.user, write_enabled=False) + + token1_header = f'Token {token1.token}' + token2_header = f'Bearer {TOKEN_PREFIX}{token2.key}.{token2.token}' + + # GET request with a write-disabled token should succeed + response = self.client.get(url, HTTP_AUTHORIZATION=token1_header) + self.assertEqual(response.status_code, 200) + response = self.client.get(url, HTTP_AUTHORIZATION=token2_header) + self.assertEqual(response.status_code, 200) + + # POST request with a write-disabled token should fail + response = self.client.post(url, data[0], format='json', HTTP_AUTHORIZATION=token1_header) + self.assertEqual(response.status_code, 403) + response = self.client.post(url, data[1], format='json', HTTP_AUTHORIZATION=token2_header) self.assertEqual(response.status_code, 403) - # Request with a write-enabled token should succeed - token.write_enabled = True - token.save() - response = self.client.post(url, data, format='json', HTTP_AUTHORIZATION=f'Token {token.key}') - self.assertEqual(response.status_code, 403) + # POST request with a write-enabled token should succeed + token1.write_enabled = True + token1.save() + token2.write_enabled = True + token2.save() + response = self.client.post(url, data[0], format='json', HTTP_AUTHORIZATION=token1_header) + self.assertEqual(response.status_code, 201) + response = self.client.post(url, data[1], format='json', HTTP_AUTHORIZATION=token2_header) + self.assertEqual(response.status_code, 201) @override_settings(LOGIN_REQUIRED=True, EXEMPT_VIEW_PERMISSIONS=['*']) def test_token_allowed_ips(self): url = reverse('dcim-api:site-list') + # Create v1 & v2 tokens + token1 = Token.objects.create(version=1, user=self.user, allowed_ips=['192.0.2.0/24']) + token2 = Token.objects.create(version=2, user=self.user, allowed_ips=['192.0.2.0/24']) + # Request from a non-allowed client IP should fail - token = Token.objects.create(user=self.user, allowed_ips=['192.0.2.0/24']) - response = self.client.get(url, HTTP_AUTHORIZATION=f'Token {token.key}', REMOTE_ADDR='127.0.0.1') + response = self.client.get( + url, + HTTP_AUTHORIZATION=f'Token {token1.token}', + REMOTE_ADDR='127.0.0.1' + ) + self.assertEqual(response.status_code, 403) + response = self.client.get( + url, + HTTP_AUTHORIZATION=f'Bearer {TOKEN_PREFIX}{token2.key}.{token2.token}', + REMOTE_ADDR='127.0.0.1' + ) self.assertEqual(response.status_code, 403) - # Request with an expired token should fail - response = self.client.get(url, HTTP_AUTHORIZATION=f'Token {token.key}', REMOTE_ADDR='192.0.2.1') + # Request from an allowed client IP should succeed + response = self.client.get( + url, + HTTP_AUTHORIZATION=f'Token {token1.token}', + REMOTE_ADDR='192.0.2.1' + ) + self.assertEqual(response.status_code, 200) + response = self.client.get( + url, + HTTP_AUTHORIZATION=f'Bearer {TOKEN_PREFIX}{token2.key}.{token2.token}', + REMOTE_ADDR='192.0.2.1' + ) self.assertEqual(response.status_code, 200) @@ -427,7 +546,7 @@ class ObjectPermissionAPIViewTestCase(TestCase): """ self.user = User.objects.create(username='testuser') self.token = Token.objects.create(user=self.user) - self.header = {'HTTP_AUTHORIZATION': 'Token {}'.format(self.token.key)} + self.header = {'HTTP_AUTHORIZATION': f'Bearer {TOKEN_PREFIX}{self.token.key}.{self.token.token}'} @override_settings(EXEMPT_VIEW_PERMISSIONS=[]) def test_get_object(self): diff --git a/netbox/netbox/tests/test_base_classes.py b/netbox/netbox/tests/test_base_classes.py new file mode 100644 index 000000000..0a8085a5e --- /dev/null +++ b/netbox/netbox/tests/test_base_classes.py @@ -0,0 +1,329 @@ +from django.apps import apps +from django.test import TestCase +from django.utils.module_loading import import_string + +from netbox.api.serializers import ( + NestedGroupModelSerializer, + NetBoxModelSerializer, + OrganizationalModelSerializer, + PrimaryModelSerializer, +) +from netbox.filtersets import ( + NestedGroupModelFilterSet, + NetBoxModelFilterSet, + OrganizationalModelFilterSet, + PrimaryModelFilterSet, +) +from netbox.forms.bulk_edit import ( + NestedGroupModelBulkEditForm, + NetBoxModelBulkEditForm, + OrganizationalModelBulkEditForm, + PrimaryModelBulkEditForm, +) +from netbox.forms.bulk_import import ( + NestedGroupModelImportForm, + NetBoxModelImportForm, + OrganizationalModelImportForm, + PrimaryModelImportForm, +) +from netbox.forms.filtersets import ( + NestedGroupModelFilterSetForm, + NetBoxModelFilterSetForm, + OrganizationalModelFilterSetForm, + PrimaryModelFilterSetForm, +) +from netbox.forms.model_forms import ( + NestedGroupModelForm, + NetBoxModelForm, + OrganizationalModelForm, + PrimaryModelForm, +) +from netbox.graphql.types import ( + NestedGroupObjectType, + NetBoxObjectType, + OrganizationalObjectType, + PrimaryObjectType, +) +from netbox.models import NestedGroupModel, NetBoxModel, OrganizationalModel, PrimaryModel +from netbox.tables import ( + NestedGroupModelTable, + NetBoxTable, + OrganizationalModelTable, + PrimaryModelTable, +) + + +class FormClassesTestCase(TestCase): + + @staticmethod + def get_form_for_model(model, prefix=''): + """ + Import and return the form class for a given model. + """ + app_label = model._meta.app_label + model_name = model.__name__ + return import_string(f'{app_label}.forms.{model_name}{prefix}Form') + + @staticmethod + def get_model_form_base_class(model): + """ + Return the base form class for creating/editing the given model. + """ + if model._meta.app_label == 'dummy_plugin': + return + if issubclass(model, PrimaryModel): + return PrimaryModelForm + if issubclass(model, OrganizationalModel): + return OrganizationalModelForm + if issubclass(model, NestedGroupModel): + return NestedGroupModelForm + if issubclass(model, NetBoxModel): + return NetBoxModelForm + + @staticmethod + def get_bulk_edit_form_base_class(model): + """ + Return the base form class for bulk editing the given model. + """ + if model._meta.app_label == 'dummy_plugin': + return + if issubclass(model, PrimaryModel): + return PrimaryModelBulkEditForm + if issubclass(model, OrganizationalModel): + return OrganizationalModelBulkEditForm + if issubclass(model, NestedGroupModel): + return NestedGroupModelBulkEditForm + if issubclass(model, NetBoxModel): + return NetBoxModelBulkEditForm + + @staticmethod + def get_import_form_base_class(model): + """ + Return the base form class for importing the given model. + """ + if model._meta.app_label == 'dummy_plugin': + return + if issubclass(model, PrimaryModel): + return PrimaryModelImportForm + if issubclass(model, OrganizationalModel): + return OrganizationalModelImportForm + if issubclass(model, NestedGroupModel): + return NestedGroupModelImportForm + if issubclass(model, NetBoxModel): + return NetBoxModelImportForm + + @staticmethod + def get_filterset_form_base_class(model): + """ + Return the base form class for the given model's FilterSet. + """ + if model._meta.app_label == 'dummy_plugin': + return + if issubclass(model, PrimaryModel): + return PrimaryModelFilterSetForm + if issubclass(model, OrganizationalModel): + return OrganizationalModelFilterSetForm + if issubclass(model, NestedGroupModel): + return NestedGroupModelFilterSetForm + if issubclass(model, NetBoxModel): + return NetBoxModelFilterSetForm + + def test_model_form_base_classes(self): + """ + Check that each model form inherits from the appropriate base class. + """ + for model in apps.get_models(): + if base_class := self.get_model_form_base_class(model): + form_class = self.get_form_for_model(model) + self.assertTrue(issubclass(form_class, base_class), f"{form_class} does not inherit from {base_class}") + + def test_bulk_edit_form_base_classes(self): + """ + Check that each bulk edit form inherits from the appropriate base class. + """ + for model in apps.get_models(): + if base_class := self.get_bulk_edit_form_base_class(model): + form_class = self.get_form_for_model(model, prefix='BulkEdit') + self.assertTrue(issubclass(form_class, base_class), f"{form_class} does not inherit from {base_class}") + + def test_import_form_base_classes(self): + """ + Check that each bulk import form inherits from the appropriate base class. + """ + for model in apps.get_models(): + if base_class := self.get_import_form_base_class(model): + form_class = self.get_form_for_model(model, prefix='Import') + self.assertTrue(issubclass(form_class, base_class), f"{form_class} does not inherit from {base_class}") + + def test_filterset_form_base_classes(self): + """ + Check that each filterset form inherits from the appropriate base class. + """ + for model in apps.get_models(): + if base_class := self.get_filterset_form_base_class(model): + form_class = self.get_form_for_model(model, prefix='Filter') + self.assertTrue(issubclass(form_class, base_class), f"{form_class} does not inherit from {base_class}") + + +class FilterSetClassesTestCase(TestCase): + + @staticmethod + def get_filterset_for_model(model): + """ + Import and return the filterset class for a given model. + """ + app_label = model._meta.app_label + model_name = model.__name__ + return import_string(f'{app_label}.filtersets.{model_name}FilterSet') + + @staticmethod + def get_model_filterset_base_class(model): + """ + Return the base FilterSet class for the given model. + """ + if model._meta.app_label == 'dummy_plugin': + return + if issubclass(model, PrimaryModel): + return PrimaryModelFilterSet + if issubclass(model, OrganizationalModel): + return OrganizationalModelFilterSet + if issubclass(model, NestedGroupModel): + return NestedGroupModelFilterSet + if issubclass(model, NetBoxModel): + return NetBoxModelFilterSet + + def test_model_filterset_base_classes(self): + """ + Check that each FilterSet inherits from the appropriate base class. + """ + for model in apps.get_models(): + if base_class := self.get_model_filterset_base_class(model): + filterset = self.get_filterset_for_model(model) + self.assertTrue( + issubclass(filterset, base_class), + f"{filterset} does not inherit from {base_class}", + ) + + +class TableClassesTestCase(TestCase): + + @staticmethod + def get_table_for_model(model): + """ + Import and return the table class for a given model. + """ + app_label = model._meta.app_label + model_name = model.__name__ + return import_string(f'{app_label}.tables.{model_name}Table') + + @staticmethod + def get_model_table_base_class(model): + """ + Return the base table class for the given model. + """ + if model._meta.app_label == 'dummy_plugin': + return + if issubclass(model, PrimaryModel): + return PrimaryModelTable + if issubclass(model, OrganizationalModel): + return OrganizationalModelTable + if issubclass(model, NestedGroupModel): + return NestedGroupModelTable + if issubclass(model, NetBoxModel): + return NetBoxTable + + def test_model_table_base_classes(self): + """ + Check that each table inherits from the appropriate base class. + """ + for model in apps.get_models(): + if base_class := self.get_model_table_base_class(model): + table = self.get_table_for_model(model) + self.assertTrue( + issubclass(table, base_class), + f"{table} does not inherit from {base_class}", + ) + self.assertTrue( + issubclass(table.Meta, base_class.Meta), + f"{table}.Meta does not inherit from {base_class}.Meta", + ) + + +class SerializerClassesTestCase(TestCase): + + @staticmethod + def get_serializer_for_model(model): + """ + Import and return the REST API serializer class for a given model. + """ + app_label = model._meta.app_label + model_name = model.__name__ + return import_string(f'{app_label}.api.serializers.{model_name}Serializer') + + @staticmethod + def get_model_serializer_base_class(model): + """ + Return the base serializer class for the given model. + """ + if model._meta.app_label == 'dummy_plugin': + return + if issubclass(model, PrimaryModel): + return PrimaryModelSerializer + if issubclass(model, OrganizationalModel): + return OrganizationalModelSerializer + if issubclass(model, NestedGroupModel): + return NestedGroupModelSerializer + if issubclass(model, NetBoxModel): + return NetBoxModelSerializer + + def test_model_serializer_base_classes(self): + """ + Check that each model serializer inherits from the appropriate base class. + """ + for model in apps.get_models(): + if base_class := self.get_model_serializer_base_class(model): + serializer = self.get_serializer_for_model(model) + self.assertTrue( + issubclass(serializer, base_class), + f"{serializer} does not inherit from {base_class}", + ) + + +class GraphQLTypeClassesTestCase(TestCase): + + @staticmethod + def get_type_for_model(model): + """ + Import and return the GraphQL type for a given model. + """ + app_label = model._meta.app_label + model_name = model.__name__ + return import_string(f'{app_label}.graphql.types.{model_name}Type') + + @staticmethod + def get_model_type_base_class(model): + """ + Return the base GraphQL type for the given model. + """ + if model._meta.app_label == 'dummy_plugin': + return + if issubclass(model, PrimaryModel): + return PrimaryObjectType + if issubclass(model, OrganizationalModel): + return OrganizationalObjectType + if issubclass(model, NestedGroupModel): + return NestedGroupObjectType + if issubclass(model, NetBoxModel): + return NetBoxObjectType + + def test_model_type_base_classes(self): + """ + Check that each GraphQL type inherits from the appropriate base class. + """ + for model in apps.get_models(): + if base_class := self.get_model_type_base_class(model): + graphql_type = self.get_type_for_model(model) + self.assertTrue( + issubclass(graphql_type, base_class), + f"{graphql_type} does not inherit from {base_class}", + ) diff --git a/netbox/netbox/tests/test_graphql.py b/netbox/netbox/tests/test_graphql.py index ca231526f..9dfc5d5df 100644 --- a/netbox/netbox/tests/test_graphql.py +++ b/netbox/netbox/tests/test_graphql.py @@ -96,11 +96,25 @@ class GraphQLAPITestCase(APITestCase): self.assertEqual(len(data['data']['location_list']), 1) self.assertIsNotNone(data['data']['location_list'][0]['site']) - # Test OR logic + # Test OR and exact logic query = """{ location_list( filters: { - status: STATUS_PLANNED, - OR: {status: STATUS_STAGING} + status: {exact: STATUS_PLANNED}, + OR: {status: {exact: STATUS_STAGING}} + }) { + id site {id} + } + }""" + response = self.client.post(url, data={'query': query}, format="json", **self.header) + self.assertHttpStatus(response, status.HTTP_200_OK) + data = json.loads(response.content) + self.assertNotIn('errors', data) + self.assertEqual(len(data['data']['location_list']), 2) + + # Test in_list logic + query = """{ + location_list( filters: { + status: {in_list: [STATUS_PLANNED, STATUS_STAGING]} }) { id site {id} } diff --git a/netbox/netbox/ui/__init__.py b/netbox/netbox/ui/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/netbox/netbox/ui/actions.py b/netbox/netbox/ui/actions.py new file mode 100644 index 000000000..7579e7b93 --- /dev/null +++ b/netbox/netbox/ui/actions.py @@ -0,0 +1,157 @@ +from urllib.parse import urlencode + +from django.apps import apps +from django.template.loader import render_to_string +from django.urls import reverse +from django.utils.translation import gettext_lazy as _ + +from utilities.permissions import get_permission_for_model +from utilities.views import get_viewname + +__all__ = ( + 'AddObject', + 'CopyContent', + 'LinkAction', + 'PanelAction', +) + + +class PanelAction: + """ + A link (typically a button) within a panel to perform some associated action, such as adding an object. + + Attributes: + template_name (str): The name of the template to render + + Parameters: + label (str): The human-friendly button text + permissions (list): An iterable of permissions required to display the action + button_class (str): Bootstrap CSS class for the button + button_icon (str): Name of the button's MDI icon + """ + template_name = None + + def __init__(self, label, permissions=None, button_class='primary', button_icon=None): + self.label = label + self.permissions = permissions + self.button_class = button_class + self.button_icon = button_icon + + def get_context(self, context): + """ + Return the template context used to render the action element. + + Parameters: + context (dict): The template context + """ + return { + 'label': self.label, + 'button_class': self.button_class, + 'button_icon': self.button_icon, + } + + def render(self, context): + """ + Render the action as HTML. + + Parameters: + context (dict): The template context + """ + # Enforce permissions + user = context['request'].user + if not user.has_perms(self.permissions): + return '' + + return render_to_string(self.template_name, self.get_context(context)) + + +class LinkAction(PanelAction): + """ + A hyperlink (typically a button) within a panel to perform some associated action, such as adding an object. + + Parameters: + view_name (str): Name of the view to which the action will link + view_kwargs (dict): Additional keyword arguments to pass to `reverse()` when resolving the URL + url_params (dict): A dictionary of arbitrary URL parameters to append to the action's URL. If the value of a key + is a callable, it will be passed the current template context. + """ + template_name = 'ui/actions/link.html' + + def __init__(self, view_name, view_kwargs=None, url_params=None, **kwargs): + super().__init__(**kwargs) + self.view_name = view_name + self.view_kwargs = view_kwargs or {} + self.url_params = url_params or {} + + def get_url(self, context): + """ + Resolve the URL for the action from its view name and kwargs. Append any additional URL parameters. + + Parameters: + context (dict): The template context + """ + url = reverse(self.view_name, kwargs=self.view_kwargs) + if self.url_params: + # If the param value is callable, call it with the context and save the result. + url_params = { + k: v(context) if callable(v) else v for k, v in self.url_params.items() + } + # Set the return URL if not already set and an object is available. + if 'return_url' not in url_params and 'object' in context: + url_params['return_url'] = context['object'].get_absolute_url() + url = f'{url}?{urlencode(url_params)}' + return url + + def get_context(self, context): + return { + **super().get_context(context), + 'url': self.get_url(context), + } + + +class AddObject(LinkAction): + """ + An action to add a new object. + + Parameters: + model (str): The dotted label of the model to be added (e.g. "dcim.site") + url_params (dict): A dictionary of arbitrary URL parameters to append to the resolved URL + """ + def __init__(self, model, url_params=None, **kwargs): + # Resolve the model class from its app.name label + try: + app_label, model_name = model.split('.') + model = apps.get_model(app_label, model_name) + except (ValueError, LookupError): + raise ValueError(f"Invalid model label: {model}") + view_name = get_viewname(model, 'add') + + kwargs.setdefault('label', _('Add')) + kwargs.setdefault('button_icon', 'plus-thick') + kwargs.setdefault('permissions', [get_permission_for_model(model, 'add')]) + + super().__init__(view_name=view_name, url_params=url_params, **kwargs) + + +class CopyContent(PanelAction): + """ + An action to copy the contents of a panel to the clipboard. + + Parameters: + target_id (str): The ID of the target element containing the content to be copied + """ + template_name = 'ui/actions/copy_content.html' + + def __init__(self, target_id, **kwargs): + kwargs.setdefault('label', _('Copy')) + kwargs.setdefault('button_icon', 'content-copy') + super().__init__(**kwargs) + self.target_id = target_id + + def render(self, context): + return render_to_string(self.template_name, { + 'target_id': self.target_id, + 'label': self.label, + 'button_class': self.button_class, + 'button_icon': self.button_icon, + }) diff --git a/netbox/netbox/ui/attrs.py b/netbox/netbox/ui/attrs.py new file mode 100644 index 000000000..bf55e3f3c --- /dev/null +++ b/netbox/netbox/ui/attrs.py @@ -0,0 +1,344 @@ +from django.template.loader import render_to_string +from django.utils.safestring import mark_safe +from django.utils.translation import gettext_lazy as _ + +from netbox.config import get_config +from utilities.data import resolve_attr_path + +__all__ = ( + 'AddressAttr', + 'BooleanAttr', + 'ColorAttr', + 'ChoiceAttr', + 'GPSCoordinatesAttr', + 'ImageAttr', + 'NestedObjectAttr', + 'NumericAttr', + 'ObjectAttribute', + 'RelatedObjectAttr', + 'TemplatedAttr', + 'TextAttr', + 'TimezoneAttr', + 'UtilizationAttr', +) + +PLACEHOLDER_HTML = '' + + +# +# Attributes +# + +class ObjectAttribute: + """ + Base class for representing an attribute of an object. + + Attributes: + template_name (str): The name of the template to render + placeholder (str): HTML to render for empty/null values + + Parameters: + accessor (str): The dotted path to the attribute being rendered (e.g. "site.region.name") + label (str): Human-friendly label for the rendered attribute + """ + template_name = None + label = None + placeholder = mark_safe(PLACEHOLDER_HTML) + + def __init__(self, accessor, label=None): + self.accessor = accessor + if label is not None: + self.label = label + + def get_value(self, obj): + """ + Return the value of the attribute. + + Parameters: + obj (object): The object for which the attribute is being rendered + """ + return resolve_attr_path(obj, self.accessor) + + def get_context(self, obj, context): + """ + Return any additional template context used to render the attribute value. + + Parameters: + obj (object): The object for which the attribute is being rendered + context (dict): The root template context + """ + return {} + + def render(self, obj, context): + value = self.get_value(obj) + + # If the value is empty, render a placeholder + if value in (None, ''): + return self.placeholder + + return render_to_string(self.template_name, { + **self.get_context(obj, context), + 'name': context['name'], + 'value': value, + }) + + +class TextAttr(ObjectAttribute): + """ + A text attribute. + + Parameters: + style (str): CSS class to apply to the rendered attribute + format_string (str): If specified, the value will be formatted using this string when rendering + copy_button (bool): Set to True to include a copy-to-clipboard button + """ + template_name = 'ui/attrs/text.html' + + def __init__(self, *args, style=None, format_string=None, copy_button=False, **kwargs): + super().__init__(*args, **kwargs) + self.style = style + self.format_string = format_string + self.copy_button = copy_button + + def get_value(self, obj): + value = resolve_attr_path(obj, self.accessor) + # Apply format string (if any) + if value and self.format_string: + return self.format_string.format(value) + return value + + def get_context(self, obj, context): + return { + 'style': self.style, + 'copy_button': self.copy_button, + } + + +class NumericAttr(ObjectAttribute): + """ + An integer or float attribute. + + Parameters: + unit_accessor (str): Accessor for the unit of measurement to display alongside the value (if any) + copy_button (bool): Set to True to include a copy-to-clipboard button + """ + template_name = 'ui/attrs/numeric.html' + + def __init__(self, *args, unit_accessor=None, copy_button=False, **kwargs): + super().__init__(*args, **kwargs) + self.unit_accessor = unit_accessor + self.copy_button = copy_button + + def get_context(self, obj, context): + unit = resolve_attr_path(obj, self.unit_accessor) if self.unit_accessor else None + return { + 'unit': unit, + 'copy_button': self.copy_button, + } + + +class ChoiceAttr(ObjectAttribute): + """ + A selection from a set of choices. + + The class calls get_FOO_display() on the object to retrieve the human-friendly choice label. If a get_FOO_color() + method exists on the object, it will be used to render a background color for the attribute value. + """ + template_name = 'ui/attrs/choice.html' + + def get_value(self, obj): + try: + return getattr(obj, f'get_{self.accessor}_display')() + except AttributeError: + return resolve_attr_path(obj, self.accessor) + + def get_context(self, obj, context): + try: + bg_color = getattr(obj, f'get_{self.accessor}_color')() + except AttributeError: + bg_color = None + return { + 'bg_color': bg_color, + } + + +class BooleanAttr(ObjectAttribute): + """ + A boolean attribute. + + Parameters: + display_false (bool): If False, a placeholder will be rendered instead of the "False" indication + """ + template_name = 'ui/attrs/boolean.html' + + def __init__(self, *args, display_false=True, **kwargs): + super().__init__(*args, **kwargs) + self.display_false = display_false + + def get_value(self, obj): + value = super().get_value(obj) + if value is False and self.display_false is False: + return None + return value + + +class ColorAttr(ObjectAttribute): + """ + An RGB color value. + """ + template_name = 'ui/attrs/color.html' + label = _('Color') + + +class ImageAttr(ObjectAttribute): + """ + An attribute representing an image field on the model. Displays the uploaded image. + """ + template_name = 'ui/attrs/image.html' + + +class RelatedObjectAttr(ObjectAttribute): + """ + An attribute representing a related object. + + Parameters: + linkify (bool): If True, the rendered value will be hyperlinked to the related object's detail view + grouped_by (str): A second-order object to annotate alongside the related object; for example, an attribute + representing the dcim.Site model might specify grouped_by="region" + """ + template_name = 'ui/attrs/object.html' + + def __init__(self, *args, linkify=None, grouped_by=None, **kwargs): + super().__init__(*args, **kwargs) + self.linkify = linkify + self.grouped_by = grouped_by + + def get_context(self, obj, context): + value = self.get_value(obj) + group = getattr(value, self.grouped_by, None) if self.grouped_by else None + return { + 'linkify': self.linkify, + 'group': group, + } + + +class NestedObjectAttr(ObjectAttribute): + """ + An attribute representing a related nested object. Similar to `RelatedObjectAttr`, but includes the ancestors of the + related object in the rendered output. + + Parameters: + linkify (bool): If True, the rendered value will be hyperlinked to the related object's detail view + max_depth (int): Maximum number of ancestors to display (default: all) + """ + template_name = 'ui/attrs/nested_object.html' + + def __init__(self, *args, linkify=None, max_depth=None, **kwargs): + super().__init__(*args, **kwargs) + self.linkify = linkify + self.max_depth = max_depth + + def get_context(self, obj, context): + value = self.get_value(obj) + nodes = value.get_ancestors(include_self=True) + if self.max_depth: + nodes = list(nodes)[-self.max_depth:] + return { + 'nodes': nodes, + 'linkify': self.linkify, + } + + +class AddressAttr(ObjectAttribute): + """ + A physical or mailing address. + + Parameters: + map_url (bool): If true, the address will render as a hyperlink using settings.MAPS_URL + """ + template_name = 'ui/attrs/address.html' + + def __init__(self, *args, map_url=True, **kwargs): + super().__init__(*args, **kwargs) + if map_url is True: + self.map_url = get_config().MAPS_URL + elif map_url: + self.map_url = map_url + else: + self.map_url = None + + def get_context(self, obj, context): + return { + 'map_url': self.map_url, + } + + +class GPSCoordinatesAttr(ObjectAttribute): + """ + A GPS coordinates pair comprising latitude and longitude values. + + Parameters: + latitude_attr (float): The name of the field containing the latitude value + longitude_attr (float): The name of the field containing the longitude value + map_url (bool): If true, the address will render as a hyperlink using settings.MAPS_URL + """ + template_name = 'ui/attrs/gps_coordinates.html' + label = _('GPS coordinates') + + def __init__(self, latitude_attr='latitude', longitude_attr='longitude', map_url=True, **kwargs): + super().__init__(accessor=None, **kwargs) + self.latitude_attr = latitude_attr + self.longitude_attr = longitude_attr + if map_url is True: + self.map_url = get_config().MAPS_URL + elif map_url: + self.map_url = map_url + else: + self.map_url = None + + def render(self, obj, context=None): + context = context or {} + latitude = resolve_attr_path(obj, self.latitude_attr) + longitude = resolve_attr_path(obj, self.longitude_attr) + if latitude is None or longitude is None: + return self.placeholder + return render_to_string(self.template_name, { + **context, + 'latitude': latitude, + 'longitude': longitude, + 'map_url': self.map_url, + }) + + +class TimezoneAttr(ObjectAttribute): + """ + A timezone value. Includes the numeric offset from UTC. + """ + template_name = 'ui/attrs/timezone.html' + + +class TemplatedAttr(ObjectAttribute): + """ + Renders an attribute using a custom template. + + Parameters: + template_name (str): The name of the template to render + context (dict): Additional context to pass to the template when rendering + """ + def __init__(self, *args, template_name, context=None, **kwargs): + super().__init__(*args, **kwargs) + self.template_name = template_name + self.context = context or {} + + def get_context(self, obj, context): + return { + **self.context, + 'object': obj, + } + + +class UtilizationAttr(ObjectAttribute): + """ + Renders the value of an attribute as a utilization graph. + """ + template_name = 'ui/attrs/utilization.html' diff --git a/netbox/netbox/ui/layout.py b/netbox/netbox/ui/layout.py new file mode 100644 index 000000000..b59fd7b34 --- /dev/null +++ b/netbox/netbox/ui/layout.py @@ -0,0 +1,94 @@ +from netbox.ui.panels import Panel, PluginContentPanel + +__all__ = ( + 'Column', + 'Layout', + 'Row', + 'SimpleLayout', +) + + +# +# Base classes +# + +class Layout: + """ + A collection of rows and columns comprising the layout of content within the user interface. + + Parameters: + *rows: One or more Row instances + """ + def __init__(self, *rows): + for i, row in enumerate(rows): + if type(row) is not Row: + raise TypeError(f"Row {i} must be a Row instance, not {type(row)}.") + self.rows = rows + + +class Row: + """ + A collection of columns arranged horizontally. + + Parameters: + *columns: One or more Column instances + """ + def __init__(self, *columns): + for i, column in enumerate(columns): + if type(column) is not Column: + raise TypeError(f"Column {i} must be a Column instance, not {type(column)}.") + self.columns = columns + + +class Column: + """ + A collection of panels arranged vertically. + + Parameters: + *panels: One or more Panel instances + """ + def __init__(self, *panels): + for i, panel in enumerate(panels): + if not isinstance(panel, Panel): + raise TypeError(f"Panel {i} must be an instance of a Panel, not {type(panel)}.") + self.panels = panels + + +# +# Common layouts +# + +class SimpleLayout(Layout): + """ + A layout with one row of two columns and a second row with one column. + + Plugin content registered for `left_page`, `right_page`, or `full_width_path` is included automatically. Most object + views in NetBox utilize this layout. + + ``` + +-------+-------+ + | Col 1 | Col 2 | + +-------+-------+ + | Col 3 | + +---------------+ + ``` + + Parameters: + left_panels: Panel instances to be rendered in the top lefthand column + right_panels: Panel instances to be rendered in the top righthand column + bottom_panels: Panel instances to be rendered in the bottom row + """ + def __init__(self, left_panels=None, right_panels=None, bottom_panels=None): + left_panels = left_panels or [] + right_panels = right_panels or [] + bottom_panels = bottom_panels or [] + rows = [ + Row( + Column(*left_panels, PluginContentPanel('left_page')), + Column(*right_panels, PluginContentPanel('right_page')), + ), + Row( + Column(*bottom_panels, PluginContentPanel('full_width_page')) + ) + ] + super().__init__(*rows) diff --git a/netbox/netbox/ui/panels.py b/netbox/netbox/ui/panels.py new file mode 100644 index 000000000..4d16cb8d3 --- /dev/null +++ b/netbox/netbox/ui/panels.py @@ -0,0 +1,341 @@ +from django.apps import apps +from django.template.loader import render_to_string +from django.utils.translation import gettext_lazy as _ + +from netbox.ui import attrs +from netbox.ui.actions import CopyContent +from utilities.data import resolve_attr_path +from utilities.querydict import dict_to_querydict +from utilities.string import title +from utilities.templatetags.plugins import _get_registered_content +from utilities.views import get_viewname + +__all__ = ( + 'CommentsPanel', + 'JSONPanel', + 'NestedGroupObjectPanel', + 'ObjectAttributesPanel', + 'ObjectPanel', + 'ObjectsTablePanel', + 'OrganizationalObjectPanel', + 'Panel', + 'PluginContentPanel', + 'RelatedObjectsPanel', + 'TemplatePanel', +) + + +# +# Base classes +# + +class Panel: + """ + A block of content rendered within an HTML template. + + Panels are arranged within rows and columns, (generally) render as discrete "cards" within the user interface. Each + panel has a title and may have one or more actions associated with it, which will be rendered as hyperlinks in the + top right corner of the card. + + Attributes: + template_name (str): The name of the template used to render the panel + + Parameters: + title (str): The human-friendly title of the panel + actions (list): An iterable of PanelActions to include in the panel header + """ + template_name = None + title = None + actions = None + + def __init__(self, title=None, actions=None): + if title is not None: + self.title = title + self.actions = actions or self.actions or [] + + def get_context(self, context): + """ + Return the context data to be used when rendering the panel. + + Parameters: + context (dict): The template context + """ + return { + 'request': context.get('request'), + 'object': context.get('object'), + 'title': self.title, + 'actions': self.actions, + 'panel_class': self.__class__.__name__, + } + + def render(self, context): + """ + Render the panel as HTML. + + Parameters: + context (dict): The template context + """ + return render_to_string(self.template_name, self.get_context(context)) + + +# +# Object-specific panels +# + +class ObjectPanel(Panel): + """ + Base class for object-specific panels. + + Parameters: + accessor (str): The dotted path in context data to the object being rendered (default: "object") + """ + accessor = 'object' + + def __init__(self, accessor=None, **kwargs): + super().__init__(**kwargs) + + if accessor is not None: + self.accessor = accessor + + def get_context(self, context): + obj = resolve_attr_path(context, self.accessor) + return { + **super().get_context(context), + 'title': self.title or title(obj._meta.verbose_name), + 'object': obj, + } + + +class ObjectAttributesPanelMeta(type): + + def __new__(mcls, name, bases, namespace, **kwargs): + declared = {} + + # Walk MRO parents (excluding `object`) for declared attributes + for base in reversed([b for b in bases if hasattr(b, "_attrs")]): + for key, attr in getattr(base, '_attrs', {}).items(): + if key not in declared: + declared[key] = attr + + # Add local declarations in the order they appear in the class body + for key, attr in namespace.items(): + if isinstance(attr, attrs.ObjectAttribute): + declared[key] = attr + + namespace['_attrs'] = declared + + # Remove Attrs from the class namespace to keep things tidy + local_items = [key for key, attr in namespace.items() if isinstance(attr, attrs.ObjectAttribute)] + for key in local_items: + namespace.pop(key) + + cls = super().__new__(mcls, name, bases, namespace, **kwargs) + return cls + + +class ObjectAttributesPanel(ObjectPanel, metaclass=ObjectAttributesPanelMeta): + """ + A panel which displays selected attributes of an object. + + Attributes are added to the panel by declaring ObjectAttribute instances in the class body (similar to fields on + a Django form). Attributes are displayed in the order they are declared. + + Note that the `only` and `exclude` parameters are mutually exclusive. + + Parameters: + only (list): If specified, only attributes in this list will be displayed + exclude (list): If specified, attributes in this list will be excluded from display + """ + template_name = 'ui/panels/object_attributes.html' + + def __init__(self, only=None, exclude=None, **kwargs): + super().__init__(**kwargs) + + # Set included/excluded attributes + if only is not None and exclude is not None: + raise ValueError("only and exclude cannot both be specified.") + self.only = only or [] + self.exclude = exclude or [] + + @staticmethod + def _name_to_label(name): + """ + Format an attribute's name to be presented as a human-friendly label. + """ + label = name[:1].upper() + name[1:] + label = label.replace('_', ' ') + return label + + def get_context(self, context): + # Determine which attributes to display in the panel based on only/exclude args + attr_names = set(self._attrs.keys()) + if self.only: + attr_names &= set(self.only) + elif self.exclude: + attr_names -= set(self.exclude) + + ctx = super().get_context(context) + + return { + **ctx, + 'attrs': [ + { + 'label': attr.label or self._name_to_label(name), + 'value': attr.render(ctx['object'], {'name': name}), + } for name, attr in self._attrs.items() if name in attr_names + ], + } + + +class OrganizationalObjectPanel(ObjectAttributesPanel, metaclass=ObjectAttributesPanelMeta): + """ + An ObjectPanel with attributes common to OrganizationalModels. Includes `name` and `description` attributes. + """ + name = attrs.TextAttr('name', label=_('Name')) + description = attrs.TextAttr('description', label=_('Description')) + + +class NestedGroupObjectPanel(ObjectAttributesPanel, metaclass=ObjectAttributesPanelMeta): + """ + An ObjectPanel with attributes common to NestedGroupObjects. Includes the `parent` attribute. + """ + parent = attrs.NestedObjectAttr('parent', label=_('Parent'), linkify=True) + name = attrs.TextAttr('name', label=_('Name')) + description = attrs.TextAttr('description', label=_('Description')) + + +class CommentsPanel(ObjectPanel): + """ + A panel which displays comments associated with an object. + + Parameters: + field_name (str): The name of the comment field on the object (default: "comments") + """ + template_name = 'ui/panels/comments.html' + title = _('Comments') + + def __init__(self, field_name='comments', **kwargs): + super().__init__(**kwargs) + self.field_name = field_name + + def get_context(self, context): + return { + **super().get_context(context), + 'comments': getattr(context['object'], self.field_name), + } + + +class JSONPanel(ObjectPanel): + """ + A panel which renders formatted JSON data from an object's JSONField. + + Parameters: + field_name (str): The name of the JSON field on the object + copy_button (bool): Set to True (default) to include a copy-to-clipboard button + """ + template_name = 'ui/panels/json.html' + + def __init__(self, field_name, copy_button=True, **kwargs): + super().__init__(**kwargs) + self.field_name = field_name + + if copy_button: + self.actions.append(CopyContent(f'panel_{field_name}')) + + def get_context(self, context): + return { + **super().get_context(context), + 'data': getattr(context['object'], self.field_name), + 'field_name': self.field_name, + } + + +# +# Miscellaneous panels +# + +class RelatedObjectsPanel(Panel): + """ + A panel which displays the types and counts of related objects. + """ + template_name = 'ui/panels/related_objects.html' + title = _('Related Objects') + + def get_context(self, context): + return { + **super().get_context(context), + 'related_models': context.get('related_models'), + } + + +class ObjectsTablePanel(Panel): + """ + A panel which displays a table of objects (rendered via HTMX). + + Parameters: + model (str): The dotted label of the model to be added (e.g. "dcim.site") + filters (dict): A dictionary of arbitrary URL parameters to append to the table's URL. If the value of a key is + a callable, it will be passed the current template context. + """ + template_name = 'ui/panels/objects_table.html' + title = None + + def __init__(self, model, filters=None, **kwargs): + super().__init__(**kwargs) + + # Resolve the model class from its app.name label + try: + app_label, model_name = model.split('.') + self.model = apps.get_model(app_label, model_name) + except (ValueError, LookupError): + raise ValueError(f"Invalid model label: {model}") + + self.filters = filters or {} + + # If no title is specified, derive one from the model name + if self.title is None: + self.title = title(self.model._meta.verbose_name_plural) + + def get_context(self, context): + url_params = { + k: v(context) if callable(v) else v for k, v in self.filters.items() + } + if 'return_url' not in url_params and 'object' in context: + url_params['return_url'] = context['object'].get_absolute_url() + return { + **super().get_context(context), + 'viewname': get_viewname(self.model, 'list'), + 'url_params': dict_to_querydict(url_params), + } + + +class TemplatePanel(Panel): + """ + A panel which renders custom content using an HTML template. + + Parameters: + template_name (str): The name of the template to render + """ + def __init__(self, template_name, **kwargs): + super().__init__(**kwargs) + self.template_name = template_name + + def render(self, context): + # Pass the entire context to the template + return render_to_string(self.template_name, context.flatten()) + + +class PluginContentPanel(Panel): + """ + A panel which displays embedded plugin content. + + Parameters: + method (str): The name of the plugin method to render (e.g. "left_page") + """ + def __init__(self, method, **kwargs): + super().__init__(**kwargs) + self.method = method + + def render(self, context): + obj = context.get('object') + return _get_registered_content(obj, self.method, context) diff --git a/netbox/netbox/urls.py b/netbox/netbox/urls.py index 90d70a357..e706f295f 100644 --- a/netbox/netbox/urls.py +++ b/netbox/netbox/urls.py @@ -5,7 +5,7 @@ from django.views.decorators.cache import cache_page from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView from account.views import LoginView, LogoutView -from netbox.api.views import APIRootView, StatusView +from netbox.api.views import APIRootView, AuthenticationCheckView, StatusView from netbox.graphql.schema import schema from netbox.graphql.views import NetBoxGraphQLView from netbox.plugins.urls import plugin_patterns, plugin_api_patterns @@ -40,7 +40,7 @@ _patterns = [ # HTMX views path('htmx/object-selector/', htmx.ObjectSelectorView.as_view(), name='htmx_object_selector'), - # API + # REST API path('api/', APIRootView.as_view(), name='api-root'), path('api/circuits/', include('circuits.api.urls')), path('api/core/', include('core.api.urls')), @@ -53,7 +53,9 @@ _patterns = [ path('api/vpn/', include('vpn.api.urls')), path('api/wireless/', include('wireless.api.urls')), path('api/status/', StatusView.as_view(), name='api-status'), + path('api/authentication-check/', AuthenticationCheckView.as_view(), name='api-authentication-check'), + # REST API schema path( "api/schema/", cache_page(timeout=86400, key_prefix=f"api_schema_{settings.RELEASE.version}")( diff --git a/netbox/netbox/views/generic/object_views.py b/netbox/netbox/views/generic/object_views.py index 5038d0ecc..1beaf0275 100644 --- a/netbox/netbox/views/generic/object_views.py +++ b/netbox/netbox/views/generic/object_views.py @@ -1,6 +1,5 @@ import logging from collections import defaultdict -from copy import deepcopy from django.contrib import messages from django.db import router, transaction @@ -44,9 +43,11 @@ class ObjectView(ActionsMixin, BaseObjectView): Note: If `template_name` is not specified, it will be determined automatically based on the queryset model. Attributes: + layout: An instance of `netbox.ui.layout.Layout` which defines the page layout (overrides HTML template) tab: A ViewTab instance for the view actions: An iterable of ObjectAction subclasses (see ActionsMixin) """ + layout = None tab = None actions = (CloneObject, EditObject, DeleteObject) @@ -81,6 +82,7 @@ class ObjectView(ActionsMixin, BaseObjectView): 'object': instance, 'actions': actions, 'tab': self.tab, + 'layout': self.layout, **self.get_extra_context(request, instance), }) @@ -561,7 +563,7 @@ class ComponentCreateView(GetReturnURLMixin, BaseObjectView): if form.is_valid(): changelog_message = form.cleaned_data.pop('changelog_message', '') new_components = [] - data = deepcopy(request.POST) + data = request.POST.copy() pattern_count = len(form.cleaned_data[self.form.replication_fields[0]]) for i in range(pattern_count): @@ -570,7 +572,8 @@ class ComponentCreateView(GetReturnURLMixin, BaseObjectView): data[field_name] = form.cleaned_data[field_name][i] if hasattr(form, 'get_iterative_data'): - data.update(form.get_iterative_data(i)) + for k, v in form.get_iterative_data(i).items(): + data.setlist(k, v) component_form = self.model_form(data) diff --git a/netbox/netbox/views/misc.py b/netbox/netbox/views/misc.py index ab995db66..4537f14c9 100644 --- a/netbox/netbox/views/misc.py +++ b/netbox/netbox/views/misc.py @@ -47,9 +47,9 @@ class HomeView(ConditionalLoginRequiredMixin, View): )) dashboard = get_default_dashboard(config=DEFAULT_DASHBOARD).get_layout() - # Check whether a new release is available. (Only for staff/superusers.) + # Check whether a new release is available. (Only for superusers.) new_release = None - if request.user.is_staff or request.user.is_superuser: + if request.user.is_superuser: latest_release = cache.get('latest_release') if latest_release: release_version, release_url = latest_release diff --git a/netbox/project-static/.eslintignore b/netbox/project-static/.eslintignore deleted file mode 100644 index 2ffd2eca6..000000000 --- a/netbox/project-static/.eslintignore +++ /dev/null @@ -1,3 +0,0 @@ -dist -node_modules -.cache diff --git a/netbox/project-static/.eslintrc b/netbox/project-static/.eslintrc deleted file mode 100644 index 30b47308b..000000000 --- a/netbox/project-static/.eslintrc +++ /dev/null @@ -1,53 +0,0 @@ -{ - "root": true, - "extends": [ - "eslint:recommended", - "plugin:import/typescript", - "plugin:@typescript-eslint/eslint-recommended", - "plugin:@typescript-eslint/recommended", - "plugin:prettier/recommended", - "prettier" - ], - "parser": "@typescript-eslint/parser", - "env": { - "browser": true, - "es6": true, - "node": true - }, - "parserOptions": { - "ecmaVersion": 2020, - "sourceType": "module", - "ecmaFeatures": { - "arrowFunctions": true - } - }, - "plugins": ["@typescript-eslint", "prettier"], - "settings": { - "import/parsers": { - "@typescript-eslint/parser": [".ts", ".tsx"] - }, - "import/resolver": { - "typescript": {} - } - }, - "rules": { - "@typescript-eslint/no-unused-vars": "error", - "no-unused-vars": "off", - "no-inner-declarations": "off", - "comma-dangle": ["error", "always-multiline"], - "global-require": "off", - "import/no-dynamic-require": "off", - "import/prefer-default-export": "off", - "@typescript-eslint/no-inferrable-types": "off", - "@typescript-eslint/explicit-function-return-type": "off", - "@typescript-eslint/no-var-requires": "off", - "@typescript-eslint/no-non-null-assertion": "off", - "@typescript-eslint/no-namespace": "off", - "@typescript-eslint/no-empty-interface": [ - "error", - { - "allowSingleExtends": true - } - ] - } -} diff --git a/netbox/project-static/bundle.js b/netbox/project-static/bundle.cjs similarity index 100% rename from netbox/project-static/bundle.js rename to netbox/project-static/bundle.cjs diff --git a/netbox/project-static/dist/graphiql/graphiql.min.css b/netbox/project-static/dist/graphiql/graphiql.min.css index 1bcbfba31..3083afe50 100644 --- a/netbox/project-static/dist/graphiql/graphiql.min.css +++ b/netbox/project-static/dist/graphiql/graphiql.min.css @@ -1,6 +1,3 @@ -/*!*********************************************************************************************!*\ - !*** css ../../../node_modules/css-loader/dist/cjs.js!../../graphiql-react/font/roboto.css ***! - \*********************************************************************************************/ @font-face { font-family: Roboto; font-style: italic; @@ -273,10 +270,6 @@ U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; } - -/*!************************************************************************************************!*\ - !*** css ../../../node_modules/css-loader/dist/cjs.js!../../graphiql-react/font/fira-code.css ***! - \************************************************************************************************/ @font-face { font-family: Fira Code; font-style: normal; @@ -335,24 +328,11 @@ U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; } - -/*!********************************************************************************************!*\ - !*** css ../../../node_modules/css-loader/dist/cjs.js!../../graphiql-react/dist/style.css ***! - \********************************************************************************************/ -/* a very simple box-model reset, intentionally does not include pseudo elements */ .graphiql-container * { box-sizing: border-box; font-variant-ligatures: none; } - -.graphiql-container, -.CodeMirror-info, -.CodeMirror-lint-tooltip, -.graphiql-dialog, -.graphiql-dialog-overlay, -.graphiql-tooltip, -[data-radix-popper-content-wrapper] { - /* Colors */ +.graphiql-container, .CodeMirror-info, .CodeMirror-lint-tooltip, .graphiql-dialog, .graphiql-dialog-overlay, .graphiql-tooltip, [data-radix-popper-content-wrapper] { --color-primary: 320, 95%, 43%; --color-secondary: 242, 51%, 61%; --color-tertiary: 188, 100%, 36%; @@ -362,17 +342,13 @@ --color-error: 13, 93%, 58%; --color-neutral: 219, 28%, 32%; --color-base: 219, 28%, 100%; - - /* Color alpha values */ - --alpha-secondary: 0.76; - --alpha-tertiary: 0.5; - --alpha-background-heavy: 0.15; - --alpha-background-medium: 0.1; - --alpha-background-light: 0.07; - - /* Font */ - --font-family: 'Roboto', sans-serif; - --font-family-mono: 'Fira Code', monospace; + --alpha-secondary: .76; + --alpha-tertiary: .5; + --alpha-background-heavy: .15; + --alpha-background-medium: .1; + --alpha-background-light: .07; + --font-family: "Roboto", sans-serif; + --font-family-mono: "Fira Code", monospace; --font-size-hint: calc(12rem / 16); --font-size-inline-code: calc(13rem / 16); --font-size-body: calc(15rem / 16); @@ -382,8 +358,6 @@ --font-weight-regular: 400; --font-weight-medium: 500; --line-height: 1.5; - - /* Spacing */ --px-2: 2px; --px-4: 4px; --px-6: 6px; @@ -393,33 +367,18 @@ --px-16: 16px; --px-20: 20px; --px-24: 24px; - - /* Border radius */ --border-radius-2: 2px; --border-radius-4: 4px; --border-radius-8: 8px; --border-radius-12: 12px; - - /* Popover styles (tooltip, dialog, etc) */ - --popover-box-shadow: 0px 6px 20px rgba(59, 76, 106, 0.13), - 0px 1.34018px 4.46726px rgba(59, 76, 106, 0.0774939), - 0px 0.399006px 1.33002px rgba(59, 76, 106, 0.0525061); + --popover-box-shadow: 0px 6px 20px #3b4c6a21, 0px 1.34018px 4.46726px #3b4c6a14, 0px .399006px 1.33002px #3b4c6a0d; --popover-border: none; - - /* Layout */ --sidebar-width: 60px; --toolbar-width: 40px; - --session-header-height: 51px; + --session-header-height: 38.5px; } - @media (prefers-color-scheme: dark) { - body:not(.graphiql-light) .graphiql-container, - body:not(.graphiql-light) .CodeMirror-info, - body:not(.graphiql-light) .CodeMirror-lint-tooltip, - body:not(.graphiql-light) .graphiql-dialog, - body:not(.graphiql-light) .graphiql-dialog-overlay, - body:not(.graphiql-light) .graphiql-tooltip, - body:not(.graphiql-light) [data-radix-popper-content-wrapper] { + body:not(.graphiql-light) .graphiql-container, body:not(.graphiql-light) .CodeMirror-info, body:not(.graphiql-light) .CodeMirror-lint-tooltip, body:not(.graphiql-light) .graphiql-dialog, body:not(.graphiql-light) .graphiql-dialog-overlay, body:not(.graphiql-light) .graphiql-tooltip, body:not(.graphiql-light) [data-radix-popper-content-wrapper] { --color-primary: 338, 100%, 67%; --color-secondary: 243, 100%, 77%; --color-tertiary: 188, 100%, 44%; @@ -429,19 +388,11 @@ --color-error: 13, 100%, 58%; --color-neutral: 219, 29%, 78%; --color-base: 219, 29%, 18%; - --popover-box-shadow: none; --popover-border: 1px solid hsl(var(--color-neutral)); } } - -body.graphiql-dark .graphiql-container, -body.graphiql-dark .CodeMirror-info, -body.graphiql-dark .CodeMirror-lint-tooltip, -body.graphiql-dark .graphiql-dialog, -body.graphiql-dark .graphiql-dialog-overlay, -body.graphiql-dark .graphiql-tooltip, -body.graphiql-dark [data-radix-popper-content-wrapper] { +body.graphiql-dark .graphiql-container, body.graphiql-dark .CodeMirror-info, body.graphiql-dark .CodeMirror-lint-tooltip, body.graphiql-dark .graphiql-dialog, body.graphiql-dark .graphiql-dialog-overlay, body.graphiql-dark .graphiql-tooltip, body.graphiql-dark [data-radix-popper-content-wrapper] { --color-primary: 338, 100%, 67%; --color-secondary: 243, 100%, 77%; --color-tertiary: 188, 100%, 44%; @@ -451,154 +402,936 @@ body.graphiql-dark [data-radix-popper-content-wrapper] { --color-error: 13, 100%, 58%; --color-neutral: 219, 29%, 78%; --color-base: 219, 29%, 18%; - --popover-box-shadow: none; --popover-border: 1px solid hsl(var(--color-neutral)); } - -.graphiql-container, - .CodeMirror-info, - .CodeMirror-lint-tooltip, - .graphiql-dialog, - .graphiql-container:is(button), - .CodeMirror-info:is(button), - .CodeMirror-lint-tooltip:is(button), - .graphiql-dialog:is(button) { - color: hsl(var(--color-neutral)); - font-family: var(--font-family); - font-size: var(--font-size-body); - font-weight: var(--font-weight-regular); - line-height: var(--line-height); +:is(.graphiql-container, .CodeMirror-info, .CodeMirror-lint-tooltip, .graphiql-dialog) { + color: hsl(var(--color-neutral)); + font-family: var(--font-family); + font-size: var(--font-size-body); + font-weight: var(--font-weight-regular); + line-height: var(--line-height); +} +:is(.graphiql-container, .CodeMirror-info, .CodeMirror-lint-tooltip, .graphiql-dialog):-webkit-any(button) { + color: hsl(var(--color-neutral)); + font-family: var(--font-family); + font-size: var(--font-size-body); + font-weight: var(--font-weight-regular); + line-height: var(--line-height); +} +:is(.graphiql-container, .CodeMirror-info, .CodeMirror-lint-tooltip, .graphiql-dialog):-moz-any(button) { + color: hsl(var(--color-neutral)); + font-family: var(--font-family); + font-size: var(--font-size-body); + font-weight: var(--font-weight-regular); + line-height: var(--line-height); +} +:is(.graphiql-container, .CodeMirror-info, .CodeMirror-lint-tooltip, .graphiql-dialog):is(button) { + color: hsl(var(--color-neutral)); + font-family: var(--font-family); + font-size: var(--font-size-body); + font-weight: var(--font-weight-regular); + line-height: var(--line-height); +} +:is(.graphiql-container, .CodeMirror-info, .CodeMirror-lint-tooltip, .graphiql-dialog) input { + color: hsl(var(--color-neutral)); + font-family: var(--font-family); + font-size: var(--font-size-caption); +} +:is(.graphiql-container, .CodeMirror-info, .CodeMirror-lint-tooltip, .graphiql-dialog) input::placeholder { + color: hsla(var(--color-neutral), var(--alpha-secondary)); +} +:is(.graphiql-container, .CodeMirror-info, .CodeMirror-lint-tooltip, .graphiql-dialog) a { + color: hsl(var(--color-primary)); +} +:is(.graphiql-container, .CodeMirror-info, .CodeMirror-lint-tooltip, .graphiql-dialog) a:focus { + outline: hsl(var(--color-primary)) auto 1px; +} +.CodeMirror { + color: #000; + direction: ltr; + height: 300px; + font-family: monospace; +} +.CodeMirror-lines { + padding: 4px 0; +} +.CodeMirror pre.CodeMirror-line, .CodeMirror pre.CodeMirror-line-like { + padding: 0 4px; +} +.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { + background-color: #fff; +} +.CodeMirror-gutters { + white-space: nowrap; + background-color: #f7f7f7; + border-right: 1px solid #ddd; +} +.CodeMirror-linenumber { + text-align: right; + color: #999; + white-space: nowrap; + min-width: 20px; + padding: 0 3px 0 5px; +} +.CodeMirror-guttermarker { + color: #000; +} +.CodeMirror-guttermarker-subtle { + color: #999; +} +.CodeMirror-cursor { + border-left: 1px solid #000; + border-right: none; + width: 0; +} +.CodeMirror div.CodeMirror-secondarycursor { + border-left: 1px solid silver; +} +.cm-fat-cursor .CodeMirror-cursor { + background: #7e7; + width: auto; + border: 0 !important; +} +.cm-fat-cursor div.CodeMirror-cursors { + z-index: 1; +} +.cm-fat-cursor .CodeMirror-line::selection, .cm-fat-cursor .CodeMirror-line > span::selection, .cm-fat-cursor .CodeMirror-line > span > span::selection { + background: none; +} +.cm-fat-cursor .CodeMirror-line::-moz-selection { + background: none; +} +.cm-fat-cursor .CodeMirror-line > span::-moz-selection { + background: none; +} +.cm-fat-cursor .CodeMirror-line > span > span::-moz-selection { + background: none; +} +.cm-fat-cursor { + caret-color: #0000; +} +@keyframes blink { + 0% { } -.graphiql-container input, .CodeMirror-info input, .CodeMirror-lint-tooltip input, .graphiql-dialog input { - color: hsl(var(--color-neutral)); - font-family: var(--font-family); - font-size: var(--font-size-caption) + 50% { + background-color: #0000; } -.graphiql-container input::placeholder, .CodeMirror-info input::placeholder, .CodeMirror-lint-tooltip input::placeholder, .graphiql-dialog input::placeholder { - color: hsla(var(--color-neutral), var(--alpha-secondary)); - } - -.graphiql-container a, .CodeMirror-info a, .CodeMirror-lint-tooltip a, .graphiql-dialog a { - color: hsl(var(--color-primary)) + 100% { + } +} +.cm-tab { + -webkit-text-decoration: inherit; + text-decoration: inherit; + display: inline-block; +} +.CodeMirror-rulers { + position: absolute; + top: -50px; + bottom: 0; + left: 0; + right: 0; + overflow: hidden; +} +.CodeMirror-ruler { + border-left: 1px solid #ccc; + position: absolute; + top: 0; + bottom: 0; +} +.cm-s-default .cm-header { + color: #00f; +} +.cm-s-default .cm-quote { + color: #090; +} +.cm-negative { + color: #d44; +} +.cm-positive { + color: #292; +} +.cm-header, .cm-strong { + font-weight: bold; +} +.cm-em { + font-style: italic; +} +.cm-link { + text-decoration: underline; +} +.cm-strikethrough { + text-decoration: line-through; +} +.cm-s-default .cm-keyword { + color: #708; +} +.cm-s-default .cm-atom { + color: #219; +} +.cm-s-default .cm-number { + color: #164; +} +.cm-s-default .cm-def { + color: #00f; +} +.cm-s-default .cm-variable-2 { + color: #05a; +} +.cm-s-default .cm-variable-3, .cm-s-default .cm-type { + color: #085; +} +.cm-s-default .cm-comment { + color: #a50; +} +.cm-s-default .cm-string { + color: #a11; +} +.cm-s-default .cm-string-2 { + color: #f50; +} +.cm-s-default .cm-meta, .cm-s-default .cm-qualifier { + color: #555; +} +.cm-s-default .cm-builtin { + color: #30a; +} +.cm-s-default .cm-bracket { + color: #997; +} +.cm-s-default .cm-tag { + color: #170; +} +.cm-s-default .cm-attribute { + color: #00c; +} +.cm-s-default .cm-hr { + color: #999; +} +.cm-s-default .cm-link { + color: #00c; +} +.cm-s-default .cm-error, .cm-invalidchar { + color: red; +} +.CodeMirror-composing { + border-bottom: 2px solid; +} +div.CodeMirror span.CodeMirror-matchingbracket { + color: #0b0; +} +div.CodeMirror span.CodeMirror-nonmatchingbracket { + color: #a22; +} +.CodeMirror-matchingtag { + background: #ff96004d; +} +.CodeMirror-activeline-background { + background: #e8f2ff; +} +.CodeMirror { + background: #fff; + position: relative; + overflow: hidden; +} +.CodeMirror-scroll { + z-index: 0; + outline: none; + height: 100%; + margin-bottom: -50px; + margin-right: -50px; + padding-bottom: 50px; + position: relative; + overflow: scroll !important; +} +.CodeMirror-sizer { + border-right: 50px solid #0000; + position: relative; +} +.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { + z-index: 6; + outline: none; + display: none; + position: absolute; +} +.CodeMirror-vscrollbar { + top: 0; + right: 0; + overflow: hidden scroll; +} +.CodeMirror-hscrollbar { + bottom: 0; + left: 0; + overflow: scroll hidden; +} +.CodeMirror-scrollbar-filler { + bottom: 0; + right: 0; +} +.CodeMirror-gutter-filler { + bottom: 0; + left: 0; +} +.CodeMirror-gutters { + z-index: 3; + min-height: 100%; + position: absolute; + top: 0; + left: 0; +} +.CodeMirror-gutter { + white-space: normal; + vertical-align: top; + height: 100%; + margin-bottom: -50px; + display: inline-block; +} +.CodeMirror-gutter-wrapper { + z-index: 4; + position: absolute; + background: none !important; + border: none !important; +} +.CodeMirror-gutter-background { + z-index: 4; + position: absolute; + top: 0; + bottom: 0; +} +.CodeMirror-gutter-elt { + cursor: default; + z-index: 4; + position: absolute; +} +.CodeMirror-gutter-wrapper ::selection { + background-color: #0000; +} +.CodeMirror-gutter-wrapper ::selection { + background-color: #0000; +} +.CodeMirror-lines { + cursor: text; + min-height: 1px; +} +.CodeMirror pre.CodeMirror-line, .CodeMirror pre.CodeMirror-line-like { + font-family: inherit; + font-size: inherit; + white-space: pre; + word-wrap: normal; + line-height: inherit; + color: inherit; + z-index: 2; + -webkit-tap-highlight-color: transparent; + -webkit-font-variant-ligatures: contextual; + font-variant-ligatures: contextual; + background: none; + border-width: 0; + border-radius: 0; + margin: 0; + position: relative; + overflow: visible; +} +.CodeMirror-wrap pre.CodeMirror-line, .CodeMirror-wrap pre.CodeMirror-line-like { + word-wrap: break-word; + white-space: pre-wrap; + word-break: normal; +} +.CodeMirror-linebackground { + z-index: 0; + position: absolute; + top: 0; + bottom: 0; + left: 0; + right: 0; +} +.CodeMirror-linewidget { + z-index: 2; + padding: .1px; + position: relative; +} +.CodeMirror-rtl pre { + direction: rtl; +} +.CodeMirror-code { + outline: none; +} +.CodeMirror-scroll, .CodeMirror-sizer, .CodeMirror-gutter, .CodeMirror-gutters, .CodeMirror-linenumber { + box-sizing: content-box; +} +.CodeMirror-measure { + visibility: hidden; + width: 100%; + height: 0; + position: absolute; + overflow: hidden; +} +.CodeMirror-cursor { + pointer-events: none; + position: absolute; +} +.CodeMirror-measure pre { + position: static; +} +div.CodeMirror-cursors { + visibility: hidden; + z-index: 3; + position: relative; +} +div.CodeMirror-dragcursors, .CodeMirror-focused div.CodeMirror-cursors { + visibility: visible; +} +.CodeMirror-selected { + background: #d9d9d9; +} +.CodeMirror-focused .CodeMirror-selected { + background: #d7d4f0; +} +.CodeMirror-crosshair { + cursor: crosshair; +} +.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { + background: #d7d4f0; +} +.CodeMirror-line::-moz-selection { + background: #d7d4f0; +} +.CodeMirror-line > span::-moz-selection { + background: #d7d4f0; +} +.CodeMirror-line > span > span::-moz-selection { + background: #d7d4f0; +} +.cm-searching { + background-color: #ff06; +} +.cm-force-border { + padding-right: .1px; +} +@media print { + .CodeMirror div.CodeMirror-cursors { + visibility: hidden; + } +} +.cm-tab-wrap-hack:after { + content: ""; +} +span.CodeMirror-selectedtext { + background: none; +} +.graphiql-container .CodeMirror { + width: 100%; + height: 100%; + font-family: var(--font-family-mono); + position: absolute; +} +.graphiql-container .CodeMirror, .graphiql-container .CodeMirror-gutters { + background: none; + background-color: var(--editor-background, hsl(var(--color-base))); +} +.graphiql-container .CodeMirror-linenumber { + padding: 0; +} +.graphiql-container .CodeMirror-gutters { + border: none; +} +.cm-s-graphiql { + color: hsla(var(--color-neutral), var(--alpha-tertiary)); +} +.cm-s-graphiql .cm-keyword { + color: hsl(var(--color-primary)); +} +.cm-s-graphiql .cm-def { + color: hsl(var(--color-tertiary)); +} +.cm-s-graphiql .cm-punctuation { + color: hsla(var(--color-neutral), var(--alpha-tertiary)); +} +.cm-s-graphiql .cm-variable { + color: hsl(var(--color-secondary)); +} +.cm-s-graphiql .cm-atom { + color: hsl(var(--color-tertiary)); +} +.cm-s-graphiql .cm-number { + color: hsl(var(--color-success)); +} +.cm-s-graphiql .cm-string { + color: hsl(var(--color-warning)); +} +.cm-s-graphiql .cm-builtin { + color: hsl(var(--color-success)); +} +.cm-s-graphiql .cm-string-2 { + color: hsl(var(--color-secondary)); +} +.cm-s-graphiql .cm-attribute { + color: hsl(var(--color-tertiary)); +} +.cm-s-graphiql .cm-meta { + color: hsl(var(--color-tertiary)); +} +.cm-s-graphiql .cm-property { + color: hsl(var(--color-info)); +} +.cm-s-graphiql .cm-qualifier { + color: hsl(var(--color-secondary)); +} +.cm-s-graphiql .cm-comment { + color: hsla(var(--color-neutral), var(--alpha-secondary)); +} +.cm-s-graphiql .cm-ws { + color: hsla(var(--color-neutral), var(--alpha-tertiary)); +} +.cm-s-graphiql .cm-invalidchar { + color: hsl(var(--color-error)); +} +.cm-s-graphiql .CodeMirror-cursor { + border-left: 2px solid hsla(var(--color-neutral), var(--alpha-secondary)); +} +.cm-s-graphiql .CodeMirror-linenumber { + color: hsla(var(--color-neutral), var(--alpha-tertiary)); +} +.graphiql-container div.CodeMirror span.CodeMirror-matchingbracket, .graphiql-container div.CodeMirror span.CodeMirror-nonmatchingbracket { + color: hsl(var(--color-warning)); +} +.graphiql-container .CodeMirror-selected, .graphiql-container .CodeMirror-focused .CodeMirror-selected { + background: hsla(var(--color-neutral), var(--alpha-background-heavy)); +} +.graphiql-container .CodeMirror-dialog { + background: inherit; + color: inherit; + padding: var(--px-2) var(--px-6); + z-index: 6; + position: absolute; + left: 0; + right: 0; + overflow: hidden; +} +.graphiql-container .CodeMirror-dialog-top { + border-bottom: 1px solid hsla(var(--color-neutral), var(--alpha-background-heavy)); + padding-bottom: var(--px-12); + top: 0; +} +.graphiql-container .CodeMirror-dialog-bottom { + border-top: 1px solid hsla(var(--color-neutral), var(--alpha-background-heavy)); + padding-top: var(--px-12); + bottom: 0; +} +.graphiql-container .CodeMirror-search-hint { + display: none; +} +.graphiql-container .CodeMirror-dialog input { + border: 1px solid hsla(var(--color-neutral), var(--alpha-background-heavy)); + border-radius: var(--border-radius-4); + padding: var(--px-4); +} +.graphiql-container .CodeMirror-dialog input:focus { + outline: hsl(var(--color-primary)) solid 2px; +} +.graphiql-container .cm-searching { + background-color: hsla(var(--color-warning), var(--alpha-background-light)); + padding-top: .5px; + padding-bottom: 1.5px; +} +.CodeMirror-foldmarker { + color: #00f; + text-shadow: 1px 1px 2px #b9f, -1px -1px 2px #b9f, 1px -1px 2px #b9f, -1px 1px 2px #b9f; + cursor: pointer; + font-family: arial; + line-height: .3; +} +.CodeMirror-foldgutter-open, .CodeMirror-foldgutter-folded { + cursor: pointer; +} +.CodeMirror-foldgutter-open:after { + content: "▾"; +} +.CodeMirror-foldgutter-folded:after { + content: "▸"; +} +.CodeMirror-foldgutter { + width: var(--px-12); +} +.CodeMirror-foldmarker { + background-color: hsl(var(--color-info)); + border-radius: var(--border-radius-4); + color: hsl(var(--color-base)); + margin: 0 var(--px-4); + padding: 0 var(--px-8); + text-shadow: none; + font-family: inherit; +} +.CodeMirror-foldgutter-open, .CodeMirror-foldgutter-folded { + color: hsla(var(--color-neutral), var(--alpha-tertiary)); +} +:is(.CodeMirror-foldgutter-open, .CodeMirror-foldgutter-folded):after { + margin: 0 var(--px-2); +} +.graphiql-editor { + width: 100%; + height: 100%; + position: relative; +} +.graphiql-editor.hidden { + visibility: hidden; + position: absolute; + top: -9999px; + left: -9999px; +} +.CodeMirror-lint-markers { + width: 16px; +} +.CodeMirror-lint-tooltip { + color: #000; + white-space: pre; + white-space: pre-wrap; + z-index: 100; + opacity: 0; + -o-transition: opacity .4s; + background-color: #ffd; + border: 1px solid #000; + border-radius: 4px; + max-width: 600px; + padding: 2px 5px; + font-family: monospace; + font-size: 10pt; + transition: opacity .4s; + position: fixed; + overflow: hidden; +} +.CodeMirror-lint-mark { + background-position: 0 100%; + background-repeat: repeat-x; +} +.CodeMirror-lint-marker { + cursor: pointer; + vertical-align: middle; + background-position: center; + background-repeat: no-repeat; + width: 16px; + height: 16px; + display: inline-block; + position: relative; +} +.CodeMirror-lint-message { + background-position: 0 0; + background-repeat: no-repeat; + padding-left: 18px; +} +.CodeMirror-lint-marker-warning, .CodeMirror-lint-message-warning { + background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAANlBMVEX/uwDvrwD/uwD/uwD/uwD/uwD/uwD/uwD/uwD6twD/uwAAAADurwD2tQD7uAD+ugAAAAD/uwDhmeTRAAAADHRSTlMJ8mN1EYcbmiixgACm7WbuAAAAVklEQVR42n3PUQqAIBBFUU1LLc3u/jdbOJoW1P08DA9Gba8+YWJ6gNJoNYIBzAA2chBth5kLmG9YUoG0NHAUwFXwO9LuBQL1giCQb8gC9Oro2vp5rncCIY8L8uEx5ZkAAAAASUVORK5CYII="); +} +.CodeMirror-lint-marker-error, .CodeMirror-lint-message-error { + background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAHlBMVEW7AAC7AACxAAC7AAC7AAAAAAC4AAC5AAD///+7AAAUdclpAAAABnRSTlMXnORSiwCK0ZKSAAAATUlEQVR42mWPOQ7AQAgDuQLx/z8csYRmPRIFIwRGnosRrpamvkKi0FTIiMASR3hhKW+hAN6/tIWhu9PDWiTGNEkTtIOucA5Oyr9ckPgAWm0GPBog6v4AAAAASUVORK5CYII="); +} +.CodeMirror-lint-marker-multiple { + background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAMAAADzjKfhAAAACVBMVEUAAAAAAAC/v7914kyHAAAAAXRSTlMAQObYZgAAACNJREFUeNo1ioEJAAAIwmz/H90iFFSGJgFMe3gaLZ0od+9/AQZ0ADosbYraAAAAAElFTkSuQmCC"); + background-position: 100% 100%; + background-repeat: no-repeat; + width: 100%; + height: 100%; +} +.CodeMirror-lint-line-error { + background-color: #b74c5114; +} +.CodeMirror-lint-line-warning { + background-color: #ffd3001a; +} +.CodeMirror-lint-mark-error, .CodeMirror-lint-mark-warning { + background-position: 0 95%; + background-repeat: repeat-x; + background-size: 10px 3px; +} +.cm-s-graphiql .CodeMirror-lint-mark-error { + color: hsl(var(--color-error)); +} +.CodeMirror-lint-mark-error { + background-image: linear-gradient(45deg, transparent 65%, hsl(var(--color-error)) 80%, transparent 90%), linear-gradient(135deg, transparent 5%, hsl(var(--color-error)) 15%, transparent 25%), linear-gradient(135deg, transparent 45%, hsl(var(--color-error)) 55%, transparent 65%), linear-gradient(45deg, transparent 25%, hsl(var(--color-error)) 35%, transparent 50%); +} +.cm-s-graphiql .CodeMirror-lint-mark-warning { + color: hsl(var(--color-warning)); +} +.CodeMirror-lint-mark-warning { + background-image: linear-gradient(45deg, transparent 65%, hsl(var(--color-warning)) 80%, transparent 90%), linear-gradient(135deg, transparent 5%, hsl(var(--color-warning)) 15%, transparent 25%), linear-gradient(135deg, transparent 45%, hsl(var(--color-warning)) 55%, transparent 65%), linear-gradient(45deg, transparent 25%, hsl(var(--color-warning)) 35%, transparent 50%); +} +.CodeMirror-lint-tooltip { + background-color: hsl(var(--color-base)); + border: var(--popover-border); + border-radius: var(--border-radius-8); + box-shadow: var(--popover-box-shadow); + font-size: var(--font-size-body); + font-family: var(--font-family); + max-width: 600px; + padding: var(--px-12); + overflow: hidden; +} +.CodeMirror-lint-message-error, .CodeMirror-lint-message-warning { + background-image: none; + padding: 0; +} +.CodeMirror-lint-message-error { + color: hsl(var(--color-error)); +} +.CodeMirror-lint-message-warning { + color: hsl(var(--color-warning)); +} +.CodeMirror-hints { + z-index: 10; + background: #fff; + border: 1px solid silver; + border-radius: 3px; + max-height: 20em; + margin: 0; + padding: 2px; + font-family: monospace; + font-size: 90%; + list-style: none; + position: absolute; + overflow: hidden auto; + box-shadow: 2px 3px 5px #0003; +} +.CodeMirror-hint { + white-space: pre; + color: #000; + cursor: pointer; + border-radius: 2px; + margin: 0; + padding: 0 4px; +} +li.CodeMirror-hint-active { + color: #fff; + background: #08f; +} +.CodeMirror-hints { + background: hsl(var(--color-base)); + border: var(--popover-border); + border-radius: var(--border-radius-8); + box-shadow: var(--popover-box-shadow); + font-family: var(--font-family); + font-size: var(--font-size-body); + grid-template-columns: auto fit-content(300px); + max-height: 264px; + padding: 0; + display: grid; +} +.CodeMirror-hint { + border-radius: var(--border-radius-4); + color: hsla(var(--color-neutral), var(--alpha-secondary)); + margin: var(--px-4); + grid-column: 1 / 2; + padding: var(--px-6) var(--px-8) !important; +} +.CodeMirror-hint:not(:first-child) { + margin-top: 0; +} +li.CodeMirror-hint-active { + background: hsla(var(--color-primary), var(--alpha-background-medium)); + color: hsl(var(--color-primary)); +} +.CodeMirror-hint-information { + border-left: 1px solid hsla(var(--color-neutral), var(--alpha-background-heavy)); + max-height: 264px; + padding: var(--px-12); + grid-area: 1 / 2 / 99999 / 3; + overflow: auto; +} +.CodeMirror-hint-information-header { + align-items: baseline; + display: flex; +} +.CodeMirror-hint-information-field-name { + font-size: var(--font-size-h4); + font-weight: var(--font-weight-medium); +} +.CodeMirror-hint-information-type-name-pill { + border: 1px solid hsla(var(--color-neutral), var(--alpha-tertiary)); + border-radius: var(--border-radius-4); + color: hsla(var(--color-neutral), var(--alpha-secondary)); + margin-left: var(--px-6); + padding: var(--px-4); +} +.CodeMirror-hint-information-type-name { + color: inherit; + text-decoration: none; +} +.CodeMirror-hint-information-type-name:hover { + -webkit-text-decoration: underline dotted; + text-decoration: underline dotted; +} +.CodeMirror-hint-information-description { + color: hsla(var(--color-neutral), var(--alpha-secondary)); + margin-top: var(--px-12); +} +.CodeMirror-info { + background-color: hsl(var(--color-base)); + border: var(--popover-border); + border-radius: var(--border-radius-8); + box-shadow: var(--popover-box-shadow); + color: hsl(var(--color-neutral)); + opacity: 0; + max-width: 400px; + max-height: 300px; + padding: var(--px-12); + z-index: 10; + transition: opacity .15s; + position: fixed; + overflow: auto; +} +.CodeMirror-info a { + color: inherit; + text-decoration: none; +} +.CodeMirror-info a:hover { + -webkit-text-decoration: underline dotted; + text-decoration: underline dotted; +} +.CodeMirror-info .CodeMirror-info-header { + align-items: baseline; + display: flex; +} +.CodeMirror-info .CodeMirror-info-header > .type-name { + font-size: var(--font-size-h4); + font-weight: var(--font-weight-medium); +} +.CodeMirror-info .CodeMirror-info-header > .field-name { + font-size: var(--font-size-h4); + font-weight: var(--font-weight-medium); +} +.CodeMirror-info .CodeMirror-info-header > .arg-name { + font-size: var(--font-size-h4); + font-weight: var(--font-weight-medium); +} +.CodeMirror-info .CodeMirror-info-header > .directive-name { + font-size: var(--font-size-h4); + font-weight: var(--font-weight-medium); +} +.CodeMirror-info .CodeMirror-info-header > .enum-value { + font-size: var(--font-size-h4); + font-weight: var(--font-weight-medium); +} +.CodeMirror-info .type-name-pill { + border: 1px solid hsla(var(--color-neutral), var(--alpha-tertiary)); + border-radius: var(--border-radius-4); + color: hsla(var(--color-neutral), var(--alpha-secondary)); + margin-left: var(--px-6); + padding: var(--px-4); +} +.CodeMirror-info .info-description { + color: hsla(var(--color-neutral), var(--alpha-secondary)); + margin-top: var(--px-12); + overflow: hidden; +} +.CodeMirror-jump-token { + cursor: pointer; + -webkit-text-decoration: underline dotted; + text-decoration: underline dotted; +} +.auto-inserted-leaf.cm-property { + border-radius: var(--border-radius-4); + padding: var(--px-2); + animation-name: insertionFade; + animation-duration: 6s; +} +@keyframes insertionFade { + from, to { + background-color: none; } -.graphiql-container a:focus, .CodeMirror-info a:focus, .CodeMirror-lint-tooltip a:focus, .graphiql-dialog a:focus { - outline: hsl(var(--color-primary)) auto 1px; - } -.graphiql-un-styled, -button.graphiql-un-styled { + 15%, 85% { + background-color: hsla(var(--color-warning), var(--alpha-background-light)); + } +} +.graphiql-un-styled, button.graphiql-un-styled { all: unset; border-radius: var(--border-radius-4); - cursor: pointer + cursor: pointer; } - -:is(.graphiql-un-styled,button.graphiql-un-styled):hover { - background-color: hsla(var(--color-neutral), var(--alpha-background-light)); - } - -:is(.graphiql-un-styled,button.graphiql-un-styled):active { - background-color: hsla( - var(--color-neutral), - var(--alpha-background-medium) - ); - } - -:is(.graphiql-un-styled,button.graphiql-un-styled):focus { - outline: hsla(var(--color-neutral), var(--alpha-background-heavy)) auto 1px; - } - -.graphiql-button, -button.graphiql-button { +:is(.graphiql-un-styled, button.graphiql-un-styled):hover { + background-color: hsla(var(--color-neutral), var(--alpha-background-light)); +} +:is(.graphiql-un-styled, button.graphiql-un-styled):active { + background-color: hsla(var(--color-neutral), var(--alpha-background-medium)); +} +:is(.graphiql-un-styled, button.graphiql-un-styled):focus { + outline: hsla(var(--color-neutral), var(--alpha-background-heavy)) auto 1px; +} +.graphiql-button, button.graphiql-button { background-color: hsla(var(--color-neutral), var(--alpha-background-light)); - border: none; border-radius: var(--border-radius-4); color: hsl(var(--color-neutral)); cursor: pointer; font-size: var(--font-size-body); - padding: var(--px-8) var(--px-12) + padding: var(--px-8) var(--px-12); + border: none; +} +:is(.graphiql-button, button.graphiql-button):hover { + background-color: hsla(var(--color-neutral), var(--alpha-background-medium)); +} +:is(.graphiql-button, button.graphiql-button):active { + background-color: hsla(var(--color-neutral), var(--alpha-background-medium)); +} +:is(.graphiql-button, button.graphiql-button):focus { + outline: hsla(var(--color-neutral), var(--alpha-background-heavy)) auto 1px; +} +:is(.graphiql-button, button.graphiql-button).graphiql-button-success { + background-color: hsla(var(--color-success), var(--alpha-background-heavy)); +} +:is(.graphiql-button, button.graphiql-button).graphiql-button-error { + background-color: hsla(var(--color-error), var(--alpha-background-heavy)); } - -:is(.graphiql-button,button.graphiql-button):hover, - :is(.graphiql-button,button.graphiql-button):active { - background-color: hsla( - var(--color-neutral), - var(--alpha-background-medium) - ); - } - -:is(.graphiql-button,button.graphiql-button):focus { - outline: hsla(var(--color-neutral), var(--alpha-background-heavy)) auto 1px; - } - -.graphiql-button-success:is(.graphiql-button,button.graphiql-button) { - background-color: hsla(var(--color-success), var(--alpha-background-heavy)); - } - -.graphiql-button-error:is(.graphiql-button,button.graphiql-button) { - background-color: hsla(var(--color-error), var(--alpha-background-heavy)); - } .graphiql-button-group { background-color: hsla(var(--color-neutral), var(--alpha-background-light)); - /* Border radius of button plus padding */ - border-radius: calc(var(--border-radius-4) + var(--px-4)); + border-radius: calc(var(--border-radius-4) + var(--px-4)); + padding: var(--px-4); display: flex; - padding: var(--px-4) } .graphiql-button-group > button.graphiql-button { - background-color: transparent - } -.graphiql-button-group > button.graphiql-button:hover { - background-color: hsla( - var(--color-neutral), - var(--alpha-background-light) - ); - } -.graphiql-button-group > button.graphiql-button.active { - background-color: hsl(var(--color-base)); - cursor: default; - } -.graphiql-button-group > * + * { - margin-left: var(--px-8); - } -.graphiql-dialog-overlay { - position: fixed; - inset: 0; - background-color: hsla(var(--color-neutral), var(--alpha-background-heavy)); - /** - * CodeMirror has a `z-index` set for the container of the scrollbar of the - * editor, so we have to add one here to make sure that the dialog is shown - * above the editor scrollbar (if they are visible). - */ - z-index: 10; + background-color: #0000; +} +.graphiql-button-group > button.graphiql-button:hover { + background-color: hsla(var(--color-neutral), var(--alpha-background-light)); +} +.graphiql-button-group > button.graphiql-button.active { + background-color: hsl(var(--color-base)); + cursor: default; +} +.graphiql-button-group > * + * { + margin-left: var(--px-8); +} +.graphiql-dialog-overlay { + background-color: hsla(var(--color-neutral), var(--alpha-background-heavy)); + z-index: 10; + position: fixed; + top: 0; + bottom: 0; + left: 0; + right: 0; } - .graphiql-dialog { background-color: hsl(var(--color-base)); border: var(--popover-border); border-radius: var(--border-radius-12); box-shadow: var(--popover-box-shadow); - margin: 0; - max-height: 80vh; max-width: 80vw; - overflow: auto; - padding: 0; + max-height: 80vh; width: unset; - transform: translate(-50%, -50%); + z-index: 10; + margin: 0; + padding: 0; + position: fixed; top: 50%; left: 50%; - position: fixed; - z-index: 10; + overflow: auto; + transform: translate(-50%, -50%); } - .graphiql-dialog-close > svg { color: hsla(var(--color-neutral), var(--alpha-secondary)); - display: block; height: var(--px-12); padding: var(--px-12); width: var(--px-12); + display: block; } .graphiql-dropdown-content { background-color: hsl(var(--color-base)); @@ -610,152 +1343,127 @@ button.graphiql-button { padding: var(--px-4); font-family: var(--font-family); color: hsl(var(--color-neutral)); - max-height: min( - calc(var(--radix-dropdown-menu-content-available-height) - 10px), - 400px - ); - overflow-y: scroll; + max-height: min(calc(var(--radix-dropdown-menu-content-available-height) - 10px), 400px); + overflow-y: auto; } - .graphiql-dropdown-item { border-radius: var(--border-radius-4); font-size: inherit; margin: var(--px-4); - overflow: hidden; padding: var(--px-6) var(--px-8); text-overflow: ellipsis; white-space: nowrap; - outline: none; cursor: pointer; - line-height: var(--line-height) + line-height: var(--line-height); + outline: none; + overflow: hidden; +} +.graphiql-dropdown-item[data-selected] { + background-color: hsla(var(--color-neutral), var(--alpha-background-light)); + color: inherit; +} +.graphiql-dropdown-item[data-current-nav] { + background-color: hsla(var(--color-neutral), var(--alpha-background-light)); + color: inherit; +} +.graphiql-dropdown-item:hover { + background-color: hsla(var(--color-neutral), var(--alpha-background-light)); + color: inherit; } - -.graphiql-dropdown-item[data-selected], - .graphiql-dropdown-item[data-current-nav], - .graphiql-dropdown-item:hover { - background-color: hsla(var(--color-neutral), var(--alpha-background-light)); - color: inherit; - } - .graphiql-dropdown-item:not(:first-child) { - margin-top: 0; - } -/** - * We render markdown in the following places: - * - In the hint tooltip when typing in the query editor (field description - * and, optionally, deprecation reason). - * - In the info tooltip when hovering over a field in the query editor - * (field description and, optionally, deprecation reason). - */ - -:is(.graphiql-markdown-description,.graphiql-markdown-deprecation,.CodeMirror-hint-information-description,.CodeMirror-hint-information-deprecation-reason,.CodeMirror-info .info-description,.CodeMirror-info .info-deprecation) blockquote { - margin-left: 0; - margin-right: 0; - padding-left: var(--px-8); - } - -:is(.graphiql-markdown-description,.graphiql-markdown-deprecation,.CodeMirror-hint-information-description,.CodeMirror-hint-information-deprecation-reason,.CodeMirror-info .info-description,.CodeMirror-info .info-deprecation) code, - :is(.graphiql-markdown-description,.graphiql-markdown-deprecation,.CodeMirror-hint-information-description,.CodeMirror-hint-information-deprecation-reason,.CodeMirror-info .info-description,.CodeMirror-info .info-deprecation) pre { - border-radius: var(--border-radius-4); - font-family: var(--font-family-mono); - font-size: var(--font-size-inline-code); - } - -:is(.graphiql-markdown-description,.graphiql-markdown-deprecation,.CodeMirror-hint-information-description,.CodeMirror-hint-information-deprecation-reason,.CodeMirror-info .info-description,.CodeMirror-info .info-deprecation) code { - padding: var(--px-2); - } - -:is(.graphiql-markdown-description,.graphiql-markdown-deprecation,.CodeMirror-hint-information-description,.CodeMirror-hint-information-deprecation-reason,.CodeMirror-info .info-description,.CodeMirror-info .info-deprecation) pre { - overflow: auto; - padding: var(--px-6) var(--px-8); - } - -:is(.graphiql-markdown-description,.graphiql-markdown-deprecation,.CodeMirror-hint-information-description,.CodeMirror-hint-information-deprecation-reason,.CodeMirror-info .info-description,.CodeMirror-info .info-deprecation) pre code { - background-color: initial; - border-radius: 0; - padding: 0; - } - -:is(.graphiql-markdown-description,.graphiql-markdown-deprecation,.CodeMirror-hint-information-description,.CodeMirror-hint-information-deprecation-reason,.CodeMirror-info .info-description,.CodeMirror-info .info-deprecation) ol, - :is(.graphiql-markdown-description,.graphiql-markdown-deprecation,.CodeMirror-hint-information-description,.CodeMirror-hint-information-deprecation-reason,.CodeMirror-info .info-description,.CodeMirror-info .info-deprecation) ul { - padding-left: var(--px-16); - } - -:is(.graphiql-markdown-description,.graphiql-markdown-deprecation,.CodeMirror-hint-information-description,.CodeMirror-hint-information-deprecation-reason,.CodeMirror-info .info-description,.CodeMirror-info .info-deprecation) ol { - list-style-type: decimal; - } - -:is(.graphiql-markdown-description,.graphiql-markdown-deprecation,.CodeMirror-hint-information-description,.CodeMirror-hint-information-deprecation-reason,.CodeMirror-info .info-description,.CodeMirror-info .info-deprecation) ul { - list-style-type: disc; - } - -:is(.graphiql-markdown-description,.graphiql-markdown-deprecation,.CodeMirror-hint-information-description,.CodeMirror-hint-information-deprecation-reason,.CodeMirror-info .info-description,.CodeMirror-info .info-deprecation) img { - border-radius: var(--border-radius-4); - max-height: 120px; - max-width: 100%; - } - -:is(.graphiql-markdown-description,.graphiql-markdown-deprecation,.CodeMirror-hint-information-description,.CodeMirror-hint-information-deprecation-reason,.CodeMirror-info .info-description,.CodeMirror-info .info-deprecation) > :first-child { - margin-top: 0; - } - -:is(.graphiql-markdown-description,.graphiql-markdown-deprecation,.CodeMirror-hint-information-description,.CodeMirror-hint-information-deprecation-reason,.CodeMirror-info .info-description,.CodeMirror-info .info-deprecation) > :last-child { - margin-bottom: 0; - } - -:is(.graphiql-markdown-description,.CodeMirror-hint-information-description,.CodeMirror-info .info-description) a { - color: hsl(var(--color-primary)); - text-decoration: none - } - -:is(.graphiql-markdown-description,.CodeMirror-hint-information-description,.CodeMirror-info .info-description) a:hover { - text-decoration: underline; - } - -:is(.graphiql-markdown-description,.CodeMirror-hint-information-description,.CodeMirror-info .info-description) blockquote { - border-left: 1.5px solid hsla(var(--color-neutral), var(--alpha-tertiary)); - } - -:is(.graphiql-markdown-description,.CodeMirror-hint-information-description,.CodeMirror-info .info-description) code, - :is(.graphiql-markdown-description,.CodeMirror-hint-information-description,.CodeMirror-info .info-description) pre { - background-color: hsla(var(--color-neutral), var(--alpha-background-light)); - color: hsl(var(--color-neutral)); - } - -:is(.graphiql-markdown-description,.CodeMirror-hint-information-description,.CodeMirror-info .info-description) > * { - margin: var(--px-12) 0; - } - -:is(.graphiql-markdown-deprecation,.CodeMirror-hint-information-deprecation-reason,.CodeMirror-info .info-deprecation) a { - color: hsl(var(--color-warning)); - text-decoration: underline; - } - -:is(.graphiql-markdown-deprecation,.CodeMirror-hint-information-deprecation-reason,.CodeMirror-info .info-deprecation) blockquote { - border-left: 1.5px solid hsl(var(--color-warning)); - } - -:is(.graphiql-markdown-deprecation,.CodeMirror-hint-information-deprecation-reason,.CodeMirror-info .info-deprecation) code, - :is(.graphiql-markdown-deprecation,.CodeMirror-hint-information-deprecation-reason,.CodeMirror-info .info-deprecation) pre { - background-color: hsla(var(--color-warning), var(--alpha-background-heavy)); - } - -:is(.graphiql-markdown-deprecation,.CodeMirror-hint-information-deprecation-reason,.CodeMirror-info .info-deprecation) > * { - margin: var(--px-8) 0; - } - + margin-top: 0; +} +:is(.graphiql-markdown-description, .graphiql-markdown-deprecation, .CodeMirror-hint-information-description, .CodeMirror-hint-information-deprecation-reason, .CodeMirror-info .info-description, .CodeMirror-info .info-deprecation) blockquote { + padding-left: var(--px-8); + margin-left: 0; + margin-right: 0; +} +:is(.graphiql-markdown-description, .graphiql-markdown-deprecation, .CodeMirror-hint-information-description, .CodeMirror-hint-information-deprecation-reason, .CodeMirror-info .info-description, .CodeMirror-info .info-deprecation) code { + border-radius: var(--border-radius-4); + font-family: var(--font-family-mono); + font-size: var(--font-size-inline-code); +} +:is(.graphiql-markdown-description, .graphiql-markdown-deprecation, .CodeMirror-hint-information-description, .CodeMirror-hint-information-deprecation-reason, .CodeMirror-info .info-description, .CodeMirror-info .info-deprecation) pre { + border-radius: var(--border-radius-4); + font-family: var(--font-family-mono); + font-size: var(--font-size-inline-code); +} +:is(.graphiql-markdown-description, .graphiql-markdown-deprecation, .CodeMirror-hint-information-description, .CodeMirror-hint-information-deprecation-reason, .CodeMirror-info .info-description, .CodeMirror-info .info-deprecation) code { + padding: var(--px-2); +} +:is(.graphiql-markdown-description, .graphiql-markdown-deprecation, .CodeMirror-hint-information-description, .CodeMirror-hint-information-deprecation-reason, .CodeMirror-info .info-description, .CodeMirror-info .info-deprecation) pre { + padding: var(--px-6) var(--px-8); + overflow: auto; +} +:is(.graphiql-markdown-description, .graphiql-markdown-deprecation, .CodeMirror-hint-information-description, .CodeMirror-hint-information-deprecation-reason, .CodeMirror-info .info-description, .CodeMirror-info .info-deprecation) pre code { + background-color: initial; + border-radius: 0; + padding: 0; +} +:is(.graphiql-markdown-description, .graphiql-markdown-deprecation, .CodeMirror-hint-information-description, .CodeMirror-hint-information-deprecation-reason, .CodeMirror-info .info-description, .CodeMirror-info .info-deprecation) ol { + padding-left: var(--px-16); +} +:is(.graphiql-markdown-description, .graphiql-markdown-deprecation, .CodeMirror-hint-information-description, .CodeMirror-hint-information-deprecation-reason, .CodeMirror-info .info-description, .CodeMirror-info .info-deprecation) ul { + padding-left: var(--px-16); +} +:is(.graphiql-markdown-description, .graphiql-markdown-deprecation, .CodeMirror-hint-information-description, .CodeMirror-hint-information-deprecation-reason, .CodeMirror-info .info-description, .CodeMirror-info .info-deprecation) ol { + list-style-type: decimal; +} +:is(.graphiql-markdown-description, .graphiql-markdown-deprecation, .CodeMirror-hint-information-description, .CodeMirror-hint-information-deprecation-reason, .CodeMirror-info .info-description, .CodeMirror-info .info-deprecation) ul { + list-style-type: disc; +} +:is(.graphiql-markdown-description, .graphiql-markdown-deprecation, .CodeMirror-hint-information-description, .CodeMirror-hint-information-deprecation-reason, .CodeMirror-info .info-description, .CodeMirror-info .info-deprecation) img { + border-radius: var(--border-radius-4); + max-width: 100%; + max-height: 120px; +} +:is(.graphiql-markdown-description, .graphiql-markdown-deprecation, .CodeMirror-hint-information-description, .CodeMirror-hint-information-deprecation-reason, .CodeMirror-info .info-description, .CodeMirror-info .info-deprecation) > :first-child { + margin-top: 0; +} +:is(.graphiql-markdown-description, .graphiql-markdown-deprecation, .CodeMirror-hint-information-description, .CodeMirror-hint-information-deprecation-reason, .CodeMirror-info .info-description, .CodeMirror-info .info-deprecation) > :last-child { + margin-bottom: 0; +} +:is(.graphiql-markdown-description, .CodeMirror-hint-information-description, .CodeMirror-info .info-description) a { + color: hsl(var(--color-primary)); + text-decoration: none; +} +:is(.graphiql-markdown-description, .CodeMirror-hint-information-description, .CodeMirror-info .info-description) a:hover { + text-decoration: underline; +} +:is(.graphiql-markdown-description, .CodeMirror-hint-information-description, .CodeMirror-info .info-description) blockquote { + border-left: 1.5px solid hsla(var(--color-neutral), var(--alpha-tertiary)); +} +:is(.graphiql-markdown-description, .CodeMirror-hint-information-description, .CodeMirror-info .info-description) code { + background-color: hsla(var(--color-neutral), var(--alpha-background-light)); + color: hsl(var(--color-neutral)); +} +:is(.graphiql-markdown-description, .CodeMirror-hint-information-description, .CodeMirror-info .info-description) pre { + background-color: hsla(var(--color-neutral), var(--alpha-background-light)); + color: hsl(var(--color-neutral)); +} +:is(.graphiql-markdown-description, .CodeMirror-hint-information-description, .CodeMirror-info .info-description) > * { + margin: var(--px-12) 0; +} +:is(.graphiql-markdown-deprecation, .CodeMirror-hint-information-deprecation-reason, .CodeMirror-info .info-deprecation) a { + color: hsl(var(--color-warning)); + text-decoration: underline; +} +:is(.graphiql-markdown-deprecation, .CodeMirror-hint-information-deprecation-reason, .CodeMirror-info .info-deprecation) blockquote { + border-left: 1.5px solid hsl(var(--color-warning)); +} +:is(.graphiql-markdown-deprecation, .CodeMirror-hint-information-deprecation-reason, .CodeMirror-info .info-deprecation) code { + background-color: hsla(var(--color-warning), var(--alpha-background-heavy)); +} +:is(.graphiql-markdown-deprecation, .CodeMirror-hint-information-deprecation-reason, .CodeMirror-info .info-deprecation) pre { + background-color: hsla(var(--color-warning), var(--alpha-background-heavy)); +} +:is(.graphiql-markdown-deprecation, .CodeMirror-hint-information-deprecation-reason, .CodeMirror-info .info-deprecation) > * { + margin: var(--px-8) 0; +} .graphiql-markdown-preview > :not(:first-child) { display: none; } - -/** - * We show deprecations in the following places: - * - In the hint tooltip when typing in the query editor. - * - In the info tooltip when hovering over a field in the query editor. - */ - -.CodeMirror-hint-information-deprecation, -.CodeMirror-info .info-deprecation { +.CodeMirror-hint-information-deprecation, .CodeMirror-info .info-deprecation { background-color: hsla(var(--color-warning), var(--alpha-background-light)); border: 1px solid hsl(var(--color-warning)); border-radius: var(--border-radius-4); @@ -763,44 +1471,127 @@ button.graphiql-button { margin-top: var(--px-12); padding: var(--px-6) var(--px-8); } - -.CodeMirror-hint-information-deprecation-label, -.CodeMirror-info .info-deprecation-label { +.CodeMirror-hint-information-deprecation-label, .CodeMirror-info .info-deprecation-label { font-size: var(--font-size-hint); font-weight: var(--font-weight-medium); } - -.CodeMirror-hint-information-deprecation-reason, -.CodeMirror-info .info-deprecation-reason { +.CodeMirror-hint-information-deprecation-reason, .CodeMirror-info .info-deprecation-reason { margin-top: var(--px-6); } .graphiql-spinner { height: 56px; margin: auto; margin-top: var(--px-16); - width: 56px + width: 56px; +} +.graphiql-spinner:after { + border: 4px solid #0000; + border-top: 4px solid hsla(var(--color-neutral), var(--alpha-tertiary)); + content: ""; + vertical-align: middle; + border-radius: 100%; + width: 46px; + height: 46px; + animation: .8s linear infinite rotation; + display: inline-block; } - -.graphiql-spinner::after { - animation: rotation 0.8s linear 0s infinite; - border: 4px solid transparent; - border-radius: 100%; - border-top: 4px solid hsla(var(--color-neutral), var(--alpha-tertiary)); - content: ''; - display: inline-block; - height: 46px; - vertical-align: middle; - width: 46px; - } - @keyframes rotation { from { - transform: rotate(0deg); + transform: rotate(0); } + to { transform: rotate(360deg); } } +.graphiql-tabs { + --bg: hsl(var(--color-base)); + align-items: center; + gap: var(--px-8); + border-top-left-radius: var(--border-radius-8); + margin: 0; + padding: 2px 0; + list-style: none; + display: flex; + overflow: auto; +} +.no-scrollbar { + scrollbar-width: none; + -ms-overflow-style: none; +} +.no-scrollbar::-webkit-scrollbar { + display: none; +} +.graphiql-tabs, .graphiql-tab { + min-width: 0; +} +.graphiql-tab { + border-radius: var(--border-radius-8) var(--border-radius-8) 0 0; + background: hsla(var(--color-neutral), var(--alpha-background-light)); + flex-shrink: 0; + display: flex; + position: relative; +} +.graphiql-tab:not(:focus-within) { + transform: none !important; +} +.graphiql-tab:hover { + background: var(--bg); + color: hsl(var(--color-neutral)); +} +.graphiql-tab:hover .graphiql-tab-close { + display: block; +} +.graphiql-tab:focus-within { + background: var(--bg); + color: hsl(var(--color-neutral)); +} +.graphiql-tab:focus-within .graphiql-tab-close { + display: block; +} +.graphiql-tab.graphiql-tab-active { + background: var(--bg); + color: hsl(var(--color-neutral)); +} +.graphiql-tab.graphiql-tab-active .graphiql-tab-close { + display: block; +} +.graphiql-tab .graphiql-tab-button { + border-radius: var(--border-radius-8) var(--border-radius-8) 0 0; + padding: var(--px-4) 28px var(--px-4) var(--px-8); +} +.graphiql-tab .graphiql-tab-button:hover { + background: none; +} +.graphiql-tab .graphiql-tab-close { + right: min(var(--px-4), 5%); + background: var(--bg); + padding: var(--px-6); + line-height: 0; + display: none; + position: absolute; + top: 50%; + transform: translateY(-50%); +} +.graphiql-tab .graphiql-tab-close > svg { + height: var(--px-8); + width: var(--px-8); +} +.graphiql-tab .graphiql-tab-close:hover { + background: var(--bg); + color: hsl(var(--color-neutral)); + overflow: hidden; +} +.graphiql-tab .graphiql-tab-close:hover:before { + content: ""; + z-index: -1; + background: hsla(var(--color-neutral), .3); + position: absolute; + top: 0; + bottom: 0; + left: 0; + right: 0; +} .graphiql-tooltip { background: hsl(var(--color-base)); border: var(--popover-border); @@ -811,155 +1602,128 @@ button.graphiql-button { padding: var(--px-4) var(--px-6); font-family: var(--font-family); } -.graphiql-tabs { - display: flex; +button.graphiql-toolbar-button { + height: var(--toolbar-width); + width: var(--toolbar-width); + justify-content: center; align-items: center; - overflow-x: auto; - padding: var(--px-12) + display: flex; } - -.graphiql-tabs > :not(:first-child) { - margin-left: var(--px-12); - } - -.graphiql-tab { - align-items: stretch; +button.graphiql-toolbar-button.error { + background: hsla(var(--color-error), var(--alpha-background-heavy)); +} +.graphiql-execute-button-wrapper { + position: relative; +} +button.graphiql-execute-button { + background-color: hsl(var(--color-primary)); border-radius: var(--border-radius-8); - color: hsla(var(--color-neutral), var(--alpha-secondary)); - display: flex + cursor: pointer; + height: var(--toolbar-width); + width: var(--toolbar-width); + border: none; + padding: 0; } - -.graphiql-tab > button.graphiql-tab-close { - visibility: hidden; - } - -.graphiql-tab.graphiql-tab-active > button.graphiql-tab-close, - .graphiql-tab:hover > button.graphiql-tab-close, - .graphiql-tab:focus-within > button.graphiql-tab-close { - visibility: unset; - } - -.graphiql-tab.graphiql-tab-active { - background-color: hsla(var(--color-neutral), var(--alpha-background-heavy)); - color: hsla(var(--color-neutral), 1); - } - -button.graphiql-tab-button { - padding: var(--px-4) 0 var(--px-4) var(--px-8); +button.graphiql-execute-button:hover { + background-color: hsla(var(--color-primary), .9); } - -button.graphiql-tab-close { - align-items: center; - display: flex; - padding: var(--px-4) var(--px-8) +button.graphiql-execute-button:active { + background-color: hsla(var(--color-primary), .8); +} +button.graphiql-execute-button:focus { + outline: hsla(var(--color-primary), .8) auto 1px; +} +button.graphiql-execute-button > svg { + color: #fff; + height: var(--px-16); + width: var(--px-16); + margin: auto; + display: block; +} +button.graphiql-toolbar-menu { + height: var(--toolbar-width); + width: var(--toolbar-width); + display: block; } - -button.graphiql-tab-close > svg { - height: var(--px-8); - width: var(--px-8); - } .graphiql-history-header { font-size: var(--font-size-h2); font-weight: var(--font-weight-medium); - display: flex; justify-content: space-between; align-items: center; + display: flex; } - .graphiql-history-header button { font-size: var(--font-size-inline-code); padding: var(--px-6) var(--px-10); } - .graphiql-history-items { margin: var(--px-16) 0 0; - list-style: none; padding: 0; + list-style: none; } - .graphiql-history-item { border-radius: var(--border-radius-4); color: hsla(var(--color-neutral), var(--alpha-secondary)); - display: flex; font-size: var(--font-size-inline-code); font-family: var(--font-family-mono); - height: 34px + height: 34px; + display: flex; } - .graphiql-history-item:hover { - color: hsl(var(--color-neutral)); - background-color: hsla(var(--color-neutral), var(--alpha-background-light)); - } - + color: hsl(var(--color-neutral)); + background-color: hsla(var(--color-neutral), var(--alpha-background-light)); +} .graphiql-history-item:not(:first-child) { - margin-top: var(--px-4); - } - + margin-top: var(--px-4); +} .graphiql-history-item.editable { - background-color: hsla( - var(--color-primary), - var(--alpha-background-medium) - ) - } - + background-color: hsla(var(--color-primary), var(--alpha-background-medium)); +} .graphiql-history-item.editable > input { - background: transparent; - border: none; - flex: 1; - margin: 0; - outline: none; - padding: 0 var(--px-10); - width: 100% - } - -.graphiql-history-item.editable > input::placeholder { - color: hsla(var(--color-neutral), var(--alpha-secondary)); - } - -.graphiql-history-item.editable > button { - color: hsl(var(--color-primary)); - padding: 0 var(--px-10) - } - -.graphiql-history-item.editable > button:active { - background-color: hsla( - var(--color-primary), - var(--alpha-background-heavy) - ); - } - -.graphiql-history-item.editable > button:focus { - outline: hsl(var(--color-primary)) auto 1px; - } - -.graphiql-history-item.editable > button > svg { - display: block; - } - -button.graphiql-history-item-label { + padding: 0 var(--px-10); + background: none; + border: none; + outline: none; flex: 1; + width: 100%; + margin: 0; +} +.graphiql-history-item.editable > input::placeholder { + color: hsla(var(--color-neutral), var(--alpha-secondary)); +} +.graphiql-history-item.editable > button { + color: hsl(var(--color-primary)); + padding: 0 var(--px-10); +} +.graphiql-history-item.editable > button:active { + background-color: hsla(var(--color-primary), var(--alpha-background-heavy)); +} +.graphiql-history-item.editable > button:focus { + outline: hsl(var(--color-primary)) auto 1px; +} +.graphiql-history-item.editable > button > svg { + display: block; +} +button.graphiql-history-item-label { padding: var(--px-8) var(--px-10); - overflow: hidden; text-overflow: ellipsis; white-space: nowrap; + flex: 1; + overflow: hidden; } - button.graphiql-history-item-action { - align-items: center; color: hsla(var(--color-neutral), var(--alpha-secondary)); + padding: var(--px-8) var(--px-6); + align-items: center; display: flex; - padding: var(--px-8) var(--px-6) } - button.graphiql-history-item-action:hover { - color: hsl(var(--color-neutral)); - } - + color: hsl(var(--color-neutral)); +} button.graphiql-history-item-action > svg { - height: 14px; - width: 14px; - } - + width: 14px; + height: 14px; +} .graphiql-history-item-spacer { height: var(--px-16); } @@ -968,23 +1732,20 @@ button.graphiql-history-item-action > svg { } a.graphiql-doc-explorer-type-name { color: hsl(var(--color-warning)); - text-decoration: none + text-decoration: none; } a.graphiql-doc-explorer-type-name:hover { - text-decoration: underline; - } + text-decoration: underline; +} a.graphiql-doc-explorer-type-name:focus { - outline: hsl(var(--color-warning)) auto 1px; - } - - .graphiql-doc-explorer-argument > * + * { - margin-top: var(--px-12); - } - + outline: hsl(var(--color-warning)) auto 1px; +} +.graphiql-doc-explorer-argument > * + * { + margin-top: var(--px-12); +} .graphiql-doc-explorer-argument-name { color: hsl(var(--color-secondary)); } - .graphiql-doc-explorer-argument-deprecation { background-color: hsla(var(--color-warning), var(--alpha-background-light)); border: 1px solid hsl(var(--color-warning)); @@ -992,7 +1753,6 @@ a.graphiql-doc-explorer-type-name:focus { color: hsl(var(--color-warning)); padding: var(--px-8); } - .graphiql-doc-explorer-argument-deprecation-label { font-size: var(--font-size-hint); font-weight: var(--font-weight-medium); @@ -1004,7 +1764,6 @@ a.graphiql-doc-explorer-type-name:focus { color: hsl(var(--color-warning)); padding: var(--px-8); } - .graphiql-doc-explorer-deprecation-label { font-size: var(--font-size-hint); font-weight: var(--font-weight-medium); @@ -1013,124 +1772,98 @@ a.graphiql-doc-explorer-type-name:focus { color: hsl(var(--color-secondary)); } .graphiql-doc-explorer-section-title { - align-items: center; - display: flex; font-size: var(--font-size-hint); font-weight: var(--font-weight-medium); - line-height: 1 + align-items: center; + line-height: 1; + display: flex; } - .graphiql-doc-explorer-section-title > svg { - height: var(--px-16); - margin-right: var(--px-8); - width: var(--px-16); - } - + height: var(--px-16); + margin-right: var(--px-8); + width: var(--px-16); +} .graphiql-doc-explorer-section-content { margin-left: var(--px-8); - margin-top: var(--px-16) + margin-top: var(--px-16); } - .graphiql-doc-explorer-section-content > * + * { - margin-top: var(--px-16); - } + margin-top: var(--px-16); +} .graphiql-doc-explorer-root-type { color: hsl(var(--color-info)); } .graphiql-doc-explorer-search { - color: hsla(var(--color-neutral), var(--alpha-secondary)) + color: hsla(var(--color-neutral), var(--alpha-secondary)); +} +.graphiql-doc-explorer-search:not([data-state="idle"]) { + border: var(--popover-border); + border-radius: var(--border-radius-4); + box-shadow: var(--popover-box-shadow); + color: hsl(var(--color-neutral)); +} +.graphiql-doc-explorer-search:not([data-state="idle"]) .graphiql-doc-explorer-search-input { + background: hsl(var(--color-base)); } - -.graphiql-doc-explorer-search:not([data-state='idle']) { - border: var(--popover-border); - border-radius: var(--border-radius-4); - box-shadow: var(--popover-box-shadow); - color: hsl(var(--color-neutral)) - } - -.graphiql-doc-explorer-search:not([data-state='idle']) .graphiql-doc-explorer-search-input { - background: hsl(var(--color-base)); - } - .graphiql-doc-explorer-search-input { - align-items: center; background-color: hsla(var(--color-neutral), var(--alpha-background-light)); border-radius: var(--border-radius-4); - display: flex; padding: var(--px-8) var(--px-12); + align-items: center; + display: flex; } - -.graphiql-doc-explorer-search [role='combobox'] { - border: none; - background-color: transparent; +.graphiql-doc-explorer-search [role="combobox"] { margin-left: var(--px-4); - width: 100% -} - -.graphiql-doc-explorer-search [role='combobox']:focus { - outline: none; - } - -.graphiql-doc-explorer-search [role='listbox'] { - background-color: hsl(var(--color-base)); + background-color: #0000; border: none; + width: 100%; +} +.graphiql-doc-explorer-search [role="combobox"]:focus { + outline: none; +} +.graphiql-doc-explorer-search [role="listbox"] { + background-color: hsl(var(--color-base)); border-bottom-left-radius: var(--border-radius-4); border-bottom-right-radius: var(--border-radius-4); - border-top: 1px solid - hsla(var(--color-neutral), var(--alpha-background-heavy)); + border: none; + border-top: 1px solid hsla(var(--color-neutral), var(--alpha-background-heavy)); max-height: 400px; - overflow-y: auto; - margin: 0; font-size: var(--font-size-body); padding: var(--px-4); - /** - * This makes sure that the logic for auto-scrolling the search results when - * using keyboard navigation works properly (we use `offsetTop` there). - */ + margin: 0; position: relative; + overflow-y: auto; } - -.graphiql-doc-explorer-search [role='option'] { +.graphiql-doc-explorer-search [role="option"] { border-radius: var(--border-radius-4); color: hsla(var(--color-neutral), var(--alpha-secondary)); - overflow-x: hidden; padding: var(--px-8) var(--px-12); text-overflow: ellipsis; white-space: nowrap; - cursor: pointer + cursor: pointer; + overflow-x: hidden; +} +.graphiql-doc-explorer-search [role="option"][data-headlessui-state="active"] { + background-color: hsla(var(--color-neutral), var(--alpha-background-light)); +} +.graphiql-doc-explorer-search [role="option"]:hover { + background-color: hsla(var(--color-neutral), var(--alpha-background-medium)); +} +.graphiql-doc-explorer-search [role="option"][data-headlessui-state="active"]:hover { + background-color: hsla(var(--color-neutral), var(--alpha-background-heavy)); +} +.graphiql-doc-explorer-search [role="option"] + :is(.graphiql-doc-explorer-search [role="option"]) { + margin-top: var(--px-4); } - -.graphiql-doc-explorer-search [role='option'][data-headlessui-state='active'] { - background-color: hsla(var(--color-neutral), var(--alpha-background-light)); - } - -.graphiql-doc-explorer-search [role='option']:hover { - background-color: hsla( - var(--color-neutral), - var(--alpha-background-medium) - ); - } - -.graphiql-doc-explorer-search [role='option'][data-headlessui-state='active']:hover { - background-color: hsla(var(--color-neutral), var(--alpha-background-heavy)); - } - -:is(.graphiql-doc-explorer-search [role='option']) + :is(.graphiql-doc-explorer-search [role='option']) { - margin-top: var(--px-4); - } - .graphiql-doc-explorer-search-type { color: hsl(var(--color-info)); } - .graphiql-doc-explorer-search-field { color: hsl(var(--color-warning)); } - .graphiql-doc-explorer-search-argument { color: hsl(var(--color-secondary)); } - .graphiql-doc-explorer-search-divider { color: hsla(var(--color-neutral), var(--alpha-secondary)); font-size: var(--font-size-hint); @@ -1138,116 +1871,95 @@ a.graphiql-doc-explorer-type-name:focus { margin-top: var(--px-8); padding: var(--px-8) var(--px-12); } - .graphiql-doc-explorer-search-empty { color: hsla(var(--color-neutral), var(--alpha-secondary)); padding: var(--px-8) var(--px-12); } a.graphiql-doc-explorer-field-name { color: hsl(var(--color-info)); - text-decoration: none + text-decoration: none; } a.graphiql-doc-explorer-field-name:hover { - text-decoration: underline; - } + text-decoration: underline; +} a.graphiql-doc-explorer-field-name:focus { - outline: hsl(var(--color-info)) auto 1px; - } + outline: hsl(var(--color-info)) auto 1px; +} .graphiql-doc-explorer-item > :not(:first-child) { margin-top: var(--px-12); } - .graphiql-doc-explorer-argument-multiple { margin-left: var(--px-8); } - .graphiql-doc-explorer-enum-value { color: hsl(var(--color-info)); } -/* The header of the doc explorer */ .graphiql-doc-explorer-header { - display: flex; justify-content: space-between; - position: relative + display: flex; + position: relative; } .graphiql-doc-explorer-header:focus-within .graphiql-doc-explorer-title { - /* Hide the header when focussing the search input */ - visibility: hidden; - } + visibility: hidden; +} .graphiql-doc-explorer-header:focus-within .graphiql-doc-explorer-back:not(:focus) { - /** - * Make the back link invisible when focussing the search input. Hiding - * it in any other way makes it impossible to focus the link by pressing - * Shift-Tab while the input is focussed. - */ - color: transparent; - } + color: #0000; +} .graphiql-doc-explorer-header-content { - display: flex; flex-direction: column; min-width: 0; + display: flex; } - -/* The search input in the header of the doc explorer */ .graphiql-doc-explorer-search { position: absolute; + top: 0; right: 0; - top: 0 } .graphiql-doc-explorer-search:focus-within { - left: 0; - } -.graphiql-doc-explorer-search:not(:focus-within) [role='combobox'] { - height: 24px; - width: 5ch; - } -.graphiql-doc-explorer-search [role='combobox']:focus { - width: 100%; - } - -/* The back-button in the doc explorer */ + left: 0; +} +.graphiql-doc-explorer-search:not(:focus-within) [role="combobox"] { + width: 5ch; + height: 24px; +} +.graphiql-doc-explorer-search [role="combobox"]:focus { + width: 100%; +} a.graphiql-doc-explorer-back { - align-items: center; color: hsla(var(--color-neutral), var(--alpha-secondary)); + align-items: center; + text-decoration: none; display: flex; - text-decoration: none } a.graphiql-doc-explorer-back:hover { - text-decoration: underline; - } + text-decoration: underline; +} a.graphiql-doc-explorer-back:focus { - outline: hsla(var(--color-neutral), var(--alpha-secondary)) auto 1px - } + outline: hsla(var(--color-neutral), var(--alpha-secondary)) auto 1px; +} a.graphiql-doc-explorer-back:focus + .graphiql-doc-explorer-title { - /* Don't hide the header when focussing the back link */ - visibility: unset; - } + visibility: unset; +} a.graphiql-doc-explorer-back > svg { - height: var(--px-8); - margin-right: var(--px-8); - width: var(--px-8); - } - -/* The title of the currently active page in the doc explorer */ + height: var(--px-8); + margin-right: var(--px-8); + width: var(--px-8); +} .graphiql-doc-explorer-title { font-weight: var(--font-weight-medium); font-size: var(--font-size-h2); - overflow-x: hidden; text-overflow: ellipsis; - white-space: nowrap + white-space: nowrap; + overflow-x: hidden; } .graphiql-doc-explorer-title:not(:first-child) { - font-size: var(--font-size-h3); - margin-top: var(--px-8); - } - -/* The contents of the currently active page in the doc explorer */ + font-size: var(--font-size-h3); + margin-top: var(--px-8); +} .graphiql-doc-explorer-content > * { color: hsla(var(--color-neutral), var(--alpha-secondary)); margin-top: var(--px-20); } - -/* Error message */ .graphiql-doc-explorer-error { background-color: hsla(var(--color-error), var(--alpha-background-heavy)); border: 1px solid hsl(var(--color-error)); @@ -1255,1100 +1967,6 @@ a.graphiql-doc-explorer-back > svg { color: hsl(var(--color-error)); padding: var(--px-8) var(--px-12); } -/* BASICS */ - -.CodeMirror { - /* Set height, width, borders, and global font properties here */ - font-family: monospace; - height: 300px; - color: black; - direction: ltr; -} - -/* PADDING */ - -.CodeMirror-lines { - padding: 4px 0; /* Vertical padding around content */ -} - -.CodeMirror pre.CodeMirror-line, -.CodeMirror pre.CodeMirror-line-like { - padding: 0 4px; /* Horizontal padding of content */ -} - -.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { - background-color: white; /* The little square between H and V scrollbars */ -} - -/* GUTTER */ - -.CodeMirror-gutters { - border-right: 1px solid #ddd; - background-color: #f7f7f7; - white-space: nowrap; -} - -.CodeMirror-linenumbers {} - -.CodeMirror-linenumber { - padding: 0 3px 0 5px; - min-width: 20px; - text-align: right; - color: #999; - white-space: nowrap; -} - -.CodeMirror-guttermarker { color: black; } - -.CodeMirror-guttermarker-subtle { color: #999; } - -/* CURSOR */ - -.CodeMirror-cursor { - border-left: 1px solid black; - border-right: none; - width: 0; -} - -/* Shown when moving in bi-directional text */ - -.CodeMirror div.CodeMirror-secondarycursor { - border-left: 1px solid silver; -} - -.cm-fat-cursor .CodeMirror-cursor { - width: auto; - border: 0 !important; - background: #7e7; -} - -.cm-fat-cursor div.CodeMirror-cursors { - z-index: 1; -} - -.cm-fat-cursor .CodeMirror-line::selection, -.cm-fat-cursor .CodeMirror-line > span::selection, -.cm-fat-cursor .CodeMirror-line > span > span::selection { background: transparent; } - -.cm-fat-cursor .CodeMirror-line::-moz-selection, -.cm-fat-cursor .CodeMirror-line > span::-moz-selection, -.cm-fat-cursor .CodeMirror-line > span > span::-moz-selection { background: transparent; } - -.cm-fat-cursor { caret-color: transparent; } - -@-moz-keyframes blink { - 0% {} - 50% { background-color: transparent; } - 100% {} -} - -@-webkit-keyframes blink { - 0% {} - 50% { background-color: transparent; } - 100% {} -} - -@keyframes blink { - 0% {} - 50% { background-color: transparent; } - 100% {} -} - -/* Can style cursor different in overwrite (non-insert) mode */ - -.CodeMirror-overwrite .CodeMirror-cursor {} - -.cm-tab { display: inline-block; text-decoration: inherit; } - -.CodeMirror-rulers { - position: absolute; - left: 0; right: 0; top: -50px; bottom: 0; - overflow: hidden; -} - -.CodeMirror-ruler { - border-left: 1px solid #ccc; - top: 0; bottom: 0; - position: absolute; -} - -/* DEFAULT THEME */ - -.cm-s-default .cm-header {color: blue;} - -.cm-s-default .cm-quote {color: #090;} - -.cm-negative {color: #d44;} - -.cm-positive {color: #292;} - -.cm-header, .cm-strong {font-weight: bold;} - -.cm-em {font-style: italic;} - -.cm-link {text-decoration: underline;} - -.cm-strikethrough {text-decoration: line-through;} - -.cm-s-default .cm-keyword {color: #708;} - -.cm-s-default .cm-atom {color: #219;} - -.cm-s-default .cm-number {color: #164;} - -.cm-s-default .cm-def {color: #00f;} - -.cm-s-default .cm-variable, -.cm-s-default .cm-punctuation, -.cm-s-default .cm-property, -.cm-s-default .cm-operator {} - -.cm-s-default .cm-variable-2 {color: #05a;} - -.cm-s-default .cm-variable-3, .cm-s-default .cm-type {color: #085;} - -.cm-s-default .cm-comment {color: #a50;} - -.cm-s-default .cm-string {color: #a11;} - -.cm-s-default .cm-string-2 {color: #f50;} - -.cm-s-default .cm-meta {color: #555;} - -.cm-s-default .cm-qualifier {color: #555;} - -.cm-s-default .cm-builtin {color: #30a;} - -.cm-s-default .cm-bracket {color: #997;} - -.cm-s-default .cm-tag {color: #170;} - -.cm-s-default .cm-attribute {color: #00c;} - -.cm-s-default .cm-hr {color: #999;} - -.cm-s-default .cm-link {color: #00c;} - -.cm-s-default .cm-error {color: #f00;} - -.cm-invalidchar {color: #f00;} - -.CodeMirror-composing { border-bottom: 2px solid; } - -/* Default styles for common addons */ - -div.CodeMirror span.CodeMirror-matchingbracket {color: #0b0;} - -div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #a22;} - -.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); } - -.CodeMirror-activeline-background {background: #e8f2ff;} - -/* STOP */ - -/* The rest of this file contains styles related to the mechanics of - the editor. You probably shouldn't touch them. */ - -.CodeMirror { - position: relative; - overflow: hidden; - background: white; -} - -.CodeMirror-scroll { - overflow: scroll !important; /* Things will break if this is overridden */ - /* 50px is the magic margin used to hide the element's real scrollbars */ - /* See overflow: hidden in .CodeMirror */ - margin-bottom: -50px; margin-right: -50px; - padding-bottom: 50px; - height: 100%; - outline: none; /* Prevent dragging from highlighting the element */ - position: relative; - z-index: 0; -} - -.CodeMirror-sizer { - position: relative; - border-right: 50px solid transparent; -} - -/* The fake, visible scrollbars. Used to force redraw during scrolling - before actual scrolling happens, thus preventing shaking and - flickering artifacts. */ - -.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { - position: absolute; - z-index: 6; - display: none; - outline: none; -} - -.CodeMirror-vscrollbar { - right: 0; top: 0; - overflow-x: hidden; - overflow-y: scroll; -} - -.CodeMirror-hscrollbar { - bottom: 0; left: 0; - overflow-y: hidden; - overflow-x: scroll; -} - -.CodeMirror-scrollbar-filler { - right: 0; bottom: 0; -} - -.CodeMirror-gutter-filler { - left: 0; bottom: 0; -} - -.CodeMirror-gutters { - position: absolute; left: 0; top: 0; - min-height: 100%; - z-index: 3; -} - -.CodeMirror-gutter { - white-space: normal; - height: 100%; - display: inline-block; - vertical-align: top; - margin-bottom: -50px; -} - -.CodeMirror-gutter-wrapper { - position: absolute; - z-index: 4; - background: none !important; - border: none !important; -} - -.CodeMirror-gutter-background { - position: absolute; - top: 0; bottom: 0; - z-index: 4; -} - -.CodeMirror-gutter-elt { - position: absolute; - cursor: default; - z-index: 4; -} - -.CodeMirror-gutter-wrapper ::selection { background-color: transparent } - -.CodeMirror-gutter-wrapper ::-moz-selection { background-color: transparent } - -.CodeMirror-lines { - cursor: text; - min-height: 1px; /* prevents collapsing before first draw */ -} - -.CodeMirror pre.CodeMirror-line, -.CodeMirror pre.CodeMirror-line-like { - /* Reset some styles that the rest of the page might have set */ - -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0; - border-width: 0; - background: transparent; - font-family: inherit; - font-size: inherit; - margin: 0; - white-space: pre; - word-wrap: normal; - line-height: inherit; - color: inherit; - z-index: 2; - position: relative; - overflow: visible; - -webkit-tap-highlight-color: transparent; - -webkit-font-variant-ligatures: contextual; - font-variant-ligatures: contextual; -} - -.CodeMirror-wrap pre.CodeMirror-line, -.CodeMirror-wrap pre.CodeMirror-line-like { - word-wrap: break-word; - white-space: pre-wrap; - word-break: normal; -} - -.CodeMirror-linebackground { - position: absolute; - left: 0; right: 0; top: 0; bottom: 0; - z-index: 0; -} - -.CodeMirror-linewidget { - position: relative; - z-index: 2; - padding: 0.1px; /* Force widget margins to stay inside of the container */ -} - -.CodeMirror-widget {} - -.CodeMirror-rtl pre { direction: rtl; } - -.CodeMirror-code { - outline: none; -} - -/* Force content-box sizing for the elements where we expect it */ - -.CodeMirror-scroll, -.CodeMirror-sizer, -.CodeMirror-gutter, -.CodeMirror-gutters, -.CodeMirror-linenumber { - -moz-box-sizing: content-box; - box-sizing: content-box; -} - -.CodeMirror-measure { - position: absolute; - width: 100%; - height: 0; - overflow: hidden; - visibility: hidden; -} - -.CodeMirror-cursor { - position: absolute; - pointer-events: none; -} - -.CodeMirror-measure pre { position: static; } - -div.CodeMirror-cursors { - visibility: hidden; - position: relative; - z-index: 3; -} - -div.CodeMirror-dragcursors { - visibility: visible; -} - -.CodeMirror-focused div.CodeMirror-cursors { - visibility: visible; -} - -.CodeMirror-selected { background: #d9d9d9; } - -.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; } - -.CodeMirror-crosshair { cursor: crosshair; } - -.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; } - -.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; } - -.cm-searching { - background-color: #ffa; - background-color: rgba(255, 255, 0, .4); -} - -/* Used to force a border model for a node */ - -.cm-force-border { padding-right: .1px; } - -@media print { - /* Hide the cursor when printing */ - .CodeMirror div.CodeMirror-cursors { - visibility: hidden; - } -} - -/* See issue #2901 */ - -.cm-tab-wrap-hack:after { content: ''; } - -/* Help users use markselection to safely style text background */ - -span.CodeMirror-selectedtext { background: none; } - -/* Make the editors fill up their container and make them scrollable */ - -.graphiql-container .CodeMirror { - height: 100%; - position: absolute; - width: 100%; -} - -/* Override font settings */ - -.graphiql-container .CodeMirror { - font-family: var(--font-family-mono); -} - -/* Set default background color */ - -.graphiql-container .CodeMirror, -.graphiql-container .CodeMirror-gutters { - background: none; - background-color: var(--editor-background, hsl(var(--color-base))); -} - -/* No padding around line numbers */ - -.graphiql-container .CodeMirror-linenumber { - padding: 0; -} - -/* No border between gutter and editor */ - -.graphiql-container .CodeMirror-gutters { - border: none; -} - -/** - * Editor theme - */ - -.cm-s-graphiql { - /* Default to punctuation */ - color: hsla(var(--color-neutral), var(--alpha-tertiary)) - - /* OperationType, `fragment`, `on` */ -} - -.cm-s-graphiql .cm-keyword { - color: hsl(var(--color-primary)); - } - -/* Name (OperationDefinition), FragmentName */ - -.cm-s-graphiql .cm-def { - color: hsl(var(--color-tertiary)); - } - -/* Punctuator (except `$` and `@`) */ - -.cm-s-graphiql .cm-punctuation { - color: hsla(var(--color-neutral), var(--alpha-tertiary)); - } - -/* Variable */ - -.cm-s-graphiql .cm-variable { - color: hsl(var(--color-secondary)); - } - -/* NamedType */ - -.cm-s-graphiql .cm-atom { - color: hsl(var(--color-tertiary)); - } - -/* IntValue, FloatValue */ - -.cm-s-graphiql .cm-number { - color: hsl(var(--color-success)); - } - -/* StringValue */ - -.cm-s-graphiql .cm-string { - color: hsl(var(--color-warning)); - } - -/* BooleanValue */ - -.cm-s-graphiql .cm-builtin { - color: hsl(var(--color-success)); - } - -/* EnumValue */ - -.cm-s-graphiql .cm-string-2 { - color: hsl(var(--color-secondary)); - } - -/* Name (ObjectField, Argument) */ - -.cm-s-graphiql .cm-attribute { - color: hsl(var(--color-tertiary)); - } - -/* Name (Directive) */ - -.cm-s-graphiql .cm-meta { - color: hsl(var(--color-tertiary)); - } - -/* Name (Alias, Field without Alias) */ - -.cm-s-graphiql .cm-property { - color: hsl(var(--color-info)); - } - -/* Name (Field with Alias) */ - -.cm-s-graphiql .cm-qualifier { - color: hsl(var(--color-secondary)); - } - -/* Comment */ - -.cm-s-graphiql .cm-comment { - color: hsla(var(--color-neutral), var(--alpha-secondary)); - } - -/* Whitespace */ - -.cm-s-graphiql .cm-ws { - color: hsla(var(--color-neutral), var(--alpha-tertiary)); - } - -/* Invalid characters */ - -.cm-s-graphiql .cm-invalidchar { - color: hsl(var(--color-error)); - } - -/* Cursor */ - -.cm-s-graphiql .CodeMirror-cursor { - border-left: 2px solid hsla(var(--color-neutral), var(--alpha-secondary)); - } - -/* Color for line numbers and fold-gutters */ - -.cm-s-graphiql .CodeMirror-linenumber { - color: hsla(var(--color-neutral), var(--alpha-tertiary)); - } - -/* Matching bracket colors */ - -.graphiql-container div.CodeMirror span.CodeMirror-matchingbracket, -.graphiql-container div.CodeMirror span.CodeMirror-nonmatchingbracket { - color: hsl(var(--color-warning)); -} - -/* Selected text blocks */ - -.graphiql-container .CodeMirror-selected, -.graphiql-container .CodeMirror-focused .CodeMirror-selected { - background: hsla(var(--color-neutral), var(--alpha-background-heavy)); -} - -/* Position the search dialog */ - -.graphiql-container .CodeMirror-dialog { - background: inherit; - color: inherit; - left: 0; - right: 0; - overflow: hidden; - padding: var(--px-2) var(--px-6); - position: absolute; - z-index: 6; -} - -.graphiql-container .CodeMirror-dialog-top { - border-bottom: 1px solid - hsla(var(--color-neutral), var(--alpha-background-heavy)); - padding-bottom: var(--px-12); - top: 0; -} - -.graphiql-container .CodeMirror-dialog-bottom { - border-top: 1px solid - hsla(var(--color-neutral), var(--alpha-background-heavy)); - bottom: 0; - padding-top: var(--px-12); -} - -/* Hide the search hint */ - -.graphiql-container .CodeMirror-search-hint { - display: none; -} - -/* Style the input field for searching */ - -.graphiql-container .CodeMirror-dialog input { - border: 1px solid hsla(var(--color-neutral), var(--alpha-background-heavy)); - border-radius: var(--border-radius-4); - padding: var(--px-4); -} - -.graphiql-container .CodeMirror-dialog input:focus { - outline: hsl(var(--color-primary)) solid 2px; -} - -/* Set the highlight color for search results */ - -.graphiql-container .cm-searching { - background-color: hsla(var(--color-warning), var(--alpha-background-light)); - /** - * When cycling through search results, CodeMirror overlays the current - * selection with another element that has the .CodeMirror-selected class - * applied. This adds another background color (see above), but this extra - * box does not quite match the height of this element. To match them up we - * add some extra padding here. (Note that this doesn't affect the line - * height of the CodeMirror editor as all line wrappers have a fixed height.) - */ - padding-bottom: 1.5px; - padding-top: 0.5px; -} -.CodeMirror-foldmarker { - color: blue; - text-shadow: #b9f 1px 1px 2px, #b9f -1px -1px 2px, #b9f 1px -1px 2px, #b9f -1px 1px 2px; - font-family: arial; - line-height: .3; - cursor: pointer; -} -.CodeMirror-foldgutter { - width: .7em; -} -.CodeMirror-foldgutter-open, -.CodeMirror-foldgutter-folded { - cursor: pointer; -} -.CodeMirror-foldgutter-open:after { - content: "\25BE"; -} -.CodeMirror-foldgutter-folded:after { - content: "\25B8"; -} -.CodeMirror-foldgutter { - width: var(--px-12); -} -.CodeMirror-foldmarker { - background-color: hsl(var(--color-info)); - border-radius: var(--border-radius-4); - color: hsl(var(--color-base)); - font-family: inherit; - margin: 0 var(--px-4); - padding: 0 var(--px-8); - text-shadow: none; -} -.CodeMirror-foldgutter-open, -.CodeMirror-foldgutter-folded { - color: hsla(var(--color-neutral), var(--alpha-tertiary)) -} -.CodeMirror-foldgutter-open::after, .CodeMirror-foldgutter-folded::after { - margin: 0 var(--px-2); - } -.graphiql-editor { - height: 100%; - position: relative; - width: 100% -} -.graphiql-editor.hidden { - /* Just setting `display: none;` would break the editor gutters */ - left: -9999px; - position: absolute; - top: -9999px; - visibility: hidden; - } -/* The lint marker gutter */ -.CodeMirror-lint-markers { - width: 16px; -} -.CodeMirror-lint-tooltip { - background-color: #ffd; - border: 1px solid black; - border-radius: 4px 4px 4px 4px; - color: black; - font-family: monospace; - font-size: 10pt; - overflow: hidden; - padding: 2px 5px; - position: fixed; - white-space: pre; - white-space: pre-wrap; - z-index: 100; - max-width: 600px; - opacity: 0; - transition: opacity .4s; - -moz-transition: opacity .4s; - -webkit-transition: opacity .4s; - -o-transition: opacity .4s; - -ms-transition: opacity .4s; -} -.CodeMirror-lint-mark { - background-position: left bottom; - background-repeat: repeat-x; -} -.CodeMirror-lint-mark-warning { - background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJFhQXEbhTg7YAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAMklEQVQI12NkgIIvJ3QXMjAwdDN+OaEbysDA4MPAwNDNwMCwiOHLCd1zX07o6kBVGQEAKBANtobskNMAAAAASUVORK5CYII=); -} -.CodeMirror-lint-mark-error { - background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJDw4cOCW1/KIAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAHElEQVQI12NggIL/DAz/GdA5/xkY/qPKMDAwAADLZwf5rvm+LQAAAABJRU5ErkJggg==); -} -.CodeMirror-lint-marker { - background-position: center center; - background-repeat: no-repeat; - cursor: pointer; - display: inline-block; - height: 16px; - width: 16px; - vertical-align: middle; - position: relative; -} -.CodeMirror-lint-message { - padding-left: 18px; - background-position: top left; - background-repeat: no-repeat; -} -.CodeMirror-lint-marker-warning, .CodeMirror-lint-message-warning { - background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAANlBMVEX/uwDvrwD/uwD/uwD/uwD/uwD/uwD/uwD/uwD6twD/uwAAAADurwD2tQD7uAD+ugAAAAD/uwDhmeTRAAAADHRSTlMJ8mN1EYcbmiixgACm7WbuAAAAVklEQVR42n3PUQqAIBBFUU1LLc3u/jdbOJoW1P08DA9Gba8+YWJ6gNJoNYIBzAA2chBth5kLmG9YUoG0NHAUwFXwO9LuBQL1giCQb8gC9Oro2vp5rncCIY8L8uEx5ZkAAAAASUVORK5CYII=); -} -.CodeMirror-lint-marker-error, .CodeMirror-lint-message-error { - background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAHlBMVEW7AAC7AACxAAC7AAC7AAAAAAC4AAC5AAD///+7AAAUdclpAAAABnRSTlMXnORSiwCK0ZKSAAAATUlEQVR42mWPOQ7AQAgDuQLx/z8csYRmPRIFIwRGnosRrpamvkKi0FTIiMASR3hhKW+hAN6/tIWhu9PDWiTGNEkTtIOucA5Oyr9ckPgAWm0GPBog6v4AAAAASUVORK5CYII=); -} -.CodeMirror-lint-marker-multiple { - background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAMAAADzjKfhAAAACVBMVEUAAAAAAAC/v7914kyHAAAAAXRSTlMAQObYZgAAACNJREFUeNo1ioEJAAAIwmz/H90iFFSGJgFMe3gaLZ0od+9/AQZ0ADosbYraAAAAAElFTkSuQmCC); - background-repeat: no-repeat; - background-position: right bottom; - width: 100%; height: 100%; -} -.CodeMirror-lint-line-error { - background-color: rgba(183, 76, 81, 0.08); -} -.CodeMirror-lint-line-warning { - background-color: rgba(255, 211, 0, 0.1); -} -/* Text styles */ -.CodeMirror-lint-mark-error, -.CodeMirror-lint-mark-warning { - background-repeat: repeat-x; - /** - * The following two are very specific to the font size, so we use - * "magic values" instead of variables. - */ - background-size: 10px 3px; - background-position: 0 95%; -} -.cm-s-graphiql .CodeMirror-lint-mark-error { - color: hsl(var(--color-error)); -} -.CodeMirror-lint-mark-error { - background-image: linear-gradient( - 45deg, - transparent 65%, - hsl(var(--color-error)) 80%, - transparent 90% - ), - linear-gradient( - 135deg, - transparent 5%, - hsl(var(--color-error)) 15%, - transparent 25% - ), - linear-gradient( - 135deg, - transparent 45%, - hsl(var(--color-error)) 55%, - transparent 65% - ), - linear-gradient( - 45deg, - transparent 25%, - hsl(var(--color-error)) 35%, - transparent 50% - ); -} -.cm-s-graphiql .CodeMirror-lint-mark-warning { - color: hsl(var(--color-warning)); -} -.CodeMirror-lint-mark-warning { - background-image: linear-gradient( - 45deg, - transparent 65%, - hsl(var(--color-warning)) 80%, - transparent 90% - ), - linear-gradient( - 135deg, - transparent 5%, - hsl(var(--color-warning)) 15%, - transparent 25% - ), - linear-gradient( - 135deg, - transparent 45%, - hsl(var(--color-warning)) 55%, - transparent 65% - ), - linear-gradient( - 45deg, - transparent 25%, - hsl(var(--color-warning)) 35%, - transparent 50% - ); -} -/* Popup styles */ -.CodeMirror-lint-tooltip { - background-color: hsl(var(--color-base)); - border: var(--popover-border); - border-radius: var(--border-radius-8); - box-shadow: var(--popover-box-shadow); - font-size: var(--font-size-body); - font-family: var(--font-family); - max-width: 600px; - overflow: hidden; - padding: var(--px-12); -} -.CodeMirror-lint-message-error, -.CodeMirror-lint-message-warning { - background-image: none; - padding: 0; -} -.CodeMirror-lint-message-error { - color: hsl(var(--color-error)); -} -.CodeMirror-lint-message-warning { - color: hsl(var(--color-warning)); -} -.CodeMirror-hints { - position: absolute; - z-index: 10; - overflow: hidden; - list-style: none; - - margin: 0; - padding: 2px; - - -webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2); - -moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2); - box-shadow: 2px 3px 5px rgba(0,0,0,.2); - border-radius: 3px; - border: 1px solid silver; - - background: white; - font-size: 90%; - font-family: monospace; - - max-height: 20em; - overflow-y: auto; -} - -.CodeMirror-hint { - margin: 0; - padding: 0 4px; - border-radius: 2px; - white-space: pre; - color: black; - cursor: pointer; -} - -li.CodeMirror-hint-active { - background: #08f; - color: white; -} - -/* Popup styles */ - -.CodeMirror-hints { - background: hsl(var(--color-base)); - border: var(--popover-border); - border-radius: var(--border-radius-8); - box-shadow: var(--popover-box-shadow); - display: grid; - font-family: var(--font-family); - font-size: var(--font-size-body); - grid-template-columns: auto fit-content(300px); - /* By default this is equals exactly 8 items including margins */ - max-height: 264px; - padding: 0; -} - -/* Autocomplete items */ - -.CodeMirror-hint { - border-radius: var(--border-radius-4); - color: hsla(var(--color-neutral), var(--alpha-secondary)); - grid-column: 1 / 2; - margin: var(--px-4); - /* Override element style added by codemirror */ - padding: var(--px-6) var(--px-8) !important -} - -.CodeMirror-hint:not(:first-child) { - margin-top: 0; - } - -li.CodeMirror-hint-active { - background: hsla(var(--color-primary), var(--alpha-background-medium)); - color: hsl(var(--color-primary)); -} - -/* Sidebar with additional information */ - -.CodeMirror-hint-information { - border-left: 1px solid - hsla(var(--color-neutral), var(--alpha-background-heavy)); - grid-column: 2 / 3; - grid-row: 1 / 99999; - /* Same as the popup */ - max-height: 264px; - overflow: auto; - padding: var(--px-12); -} - -.CodeMirror-hint-information-header { - display: flex; - align-items: baseline; -} - -.CodeMirror-hint-information-field-name { - font-size: var(--font-size-h4); - font-weight: var(--font-weight-medium); -} - -.CodeMirror-hint-information-type-name-pill { - border: 1px solid hsla(var(--color-neutral), var(--alpha-tertiary)); - border-radius: var(--border-radius-4); - color: hsla(var(--color-neutral), var(--alpha-secondary)); - margin-left: var(--px-6); - padding: var(--px-4); -} - -.CodeMirror-hint-information-type-name { - color: inherit; - text-decoration: none -} - -.CodeMirror-hint-information-type-name:hover { - text-decoration: underline dotted; - } - -.CodeMirror-hint-information-description { - color: hsla(var(--color-neutral), var(--alpha-secondary)); - margin-top: var(--px-12); -} -/* Popup styles */ -.CodeMirror-info { - background-color: hsl(var(--color-base)); - border: var(--popover-border); - border-radius: var(--border-radius-8); - box-shadow: var(--popover-box-shadow); - color: hsl(var(--color-neutral)); - max-height: 300px; - max-width: 400px; - opacity: 0; - overflow: auto; - padding: var(--px-12); - position: fixed; - transition: opacity 0.15s; - z-index: 10 - - /* Link styles */ -} -.CodeMirror-info a { - color: inherit; - text-decoration: none - } -.CodeMirror-info a:hover { - text-decoration: underline dotted; - } -/* Align elements in header */ -.CodeMirror-info .CodeMirror-info-header { - display: flex; - align-items: baseline; - } -/* Main elements */ -.CodeMirror-info .CodeMirror-info-header > .type-name, - .CodeMirror-info .CodeMirror-info-header > .field-name, - .CodeMirror-info .CodeMirror-info-header > .arg-name, - .CodeMirror-info .CodeMirror-info-header > .directive-name, - .CodeMirror-info .CodeMirror-info-header > .enum-value { - font-size: var(--font-size-h4); - font-weight: var(--font-weight-medium); - } -/* Type names */ -.CodeMirror-info .type-name-pill { - border: 1px solid hsla(var(--color-neutral), var(--alpha-tertiary)); - border-radius: var(--border-radius-4); - color: hsla(var(--color-neutral), var(--alpha-secondary)); - margin-left: var(--px-6); - padding: var(--px-4); - } -/* Descriptions */ -.CodeMirror-info .info-description { - color: hsla(var(--color-neutral), var(--alpha-secondary)); - margin-top: var(--px-12); - overflow: hidden; - } -/* Underline the clickable token */ -.CodeMirror-jump-token { - text-decoration: underline dotted; - cursor: pointer; -} -.auto-inserted-leaf.cm-property { - animation-duration: 6s; - animation-name: insertionFade; - border-radius: var(--border-radius-4); - padding: var(--px-2); -} - -@keyframes insertionFade { - from, - to { - background-color: none; - } - - 15%, - 85% { - background-color: hsla(var(--color-warning), var(--alpha-background-light)); - } -} -button.graphiql-toolbar-button { - display: flex; - align-items: center; - justify-content: center; - height: var(--toolbar-width); - width: var(--toolbar-width) -} -button.graphiql-toolbar-button.error { - background: hsla(var(--color-error), var(--alpha-background-heavy)); - } -.graphiql-execute-button-wrapper { - position: relative; -} - -button.graphiql-execute-button { - background-color: hsl(var(--color-primary)); - border: none; - border-radius: var(--border-radius-8); - cursor: pointer; - height: var(--toolbar-width); - padding: 0; - width: var(--toolbar-width) -} - -button.graphiql-execute-button:hover { - background-color: hsla(var(--color-primary), 0.9); - } - -button.graphiql-execute-button:active { - background-color: hsla(var(--color-primary), 0.8); - } - -button.graphiql-execute-button:focus { - outline: hsla(var(--color-primary), 0.8) auto 1px; - } - -button.graphiql-execute-button > svg { - color: white; - display: block; - height: var(--px-16); - margin: auto; - width: var(--px-16); - } -button.graphiql-toolbar-menu { - display: block; - height: var(--toolbar-width); - width: var(--toolbar-width); -} - -/*!*********************************************************************************************************************!*\ - !*** css ../../../node_modules/css-loader/dist/cjs.js!../../../node_modules/postcss-loader/dist/cjs.js!./style.css ***! - \*********************************************************************************************************************/ /* Everything */ .graphiql-container { background-color: hsl(var(--color-base)); @@ -2362,29 +1980,23 @@ button.graphiql-toolbar-menu { .graphiql-container .graphiql-sidebar { display: flex; flex-direction: column; - justify-content: space-between; padding: var(--px-8); width: var(--sidebar-width); -} -.graphiql-container .graphiql-sidebar .graphiql-sidebar-section { - display: flex; - flex-direction: column; gap: var(--px-8); + overflow-y: auto; } -.graphiql-container .graphiql-sidebar button { +.graphiql-container .graphiql-sidebar > button { display: flex; align-items: center; justify-content: center; color: hsla(var(--color-neutral), var(--alpha-secondary)); height: calc(var(--sidebar-width) - (2 * var(--px-8))); width: calc(var(--sidebar-width) - (2 * var(--px-8))); + flex-shrink: 0; } .graphiql-container .graphiql-sidebar button.active { color: hsl(var(--color-neutral)); } -.graphiql-container .graphiql-sidebar button:not(:first-child) { - margin-top: var(--px-4); -} .graphiql-container .graphiql-sidebar button > svg { height: var(--px-20); width: var(--px-20); @@ -2410,41 +2022,41 @@ button.graphiql-toolbar-menu { } /* The session header containing tabs and the logo */ .graphiql-container .graphiql-session-header { + height: var(--session-header-height); align-items: center; display: flex; - justify-content: space-between; - height: var(--session-header-height); + padding: var(--px-8) var(--px-8) 0; + gap: var(--px-8); } /* The button to add a new tab */ button.graphiql-tab-add { - height: 100%; padding: var(--px-4); -} -button.graphiql-tab-add > svg { - color: hsla(var(--color-neutral), var(--alpha-secondary)); - display: block; - height: var(--px-16); - width: var(--px-16); -} -/* The right-hand-side of the session header */ -.graphiql-container .graphiql-session-header-right { - align-items: center; - display: flex; + + & > svg { + color: hsla(var(--color-neutral), var(--alpha-secondary)); + display: block; + height: var(--px-16); + width: var(--px-16); + } } /* The GraphiQL logo */ .graphiql-container .graphiql-logo { + margin-left: auto; color: hsla(var(--color-neutral), var(--alpha-secondary)); font-size: var(--font-size-h4); font-weight: var(--font-weight-medium); - padding: var(--px-12) var(--px-16); } /* Undo default link styling for the default GraphiQL logo link */ .graphiql-container .graphiql-logo .graphiql-logo-link { color: hsla(var(--color-neutral), var(--alpha-secondary)); text-decoration: none; + + &:focus { + outline: hsla(var(--color-neutral), var(--alpha-background-heavy)) auto 1px; + } } /* The editor of the session */ -.graphiql-container .graphiql-session { +.graphiql-container #graphiql-session { display: flex; flex: 1; padding: 0 var(--px-8) var(--px-8); @@ -2452,15 +2064,12 @@ button.graphiql-tab-add > svg { /* All editors (query, variable, headers) */ .graphiql-container .graphiql-editors { background-color: hsl(var(--color-base)); - border-radius: calc(var(--border-radius-12)); + border-radius: 0 0 var(--border-radius-12) var(--border-radius-12); box-shadow: var(--popover-box-shadow); display: flex; flex: 1; flex-direction: column; } -.graphiql-container .graphiql-editors.full-height { - margin-top: calc(var(--px-8) - var(--session-header-height)); -} /* The query editor and the toolbar */ .graphiql-container .graphiql-query-editor { border-bottom: 1px solid @@ -2473,9 +2082,12 @@ button.graphiql-tab-add > svg { /* The vertical toolbar next to the query editor */ .graphiql-container .graphiql-toolbar { width: var(--toolbar-width); + display: flex; + flex-direction: column; + gap: var(--px-8); } -.graphiql-container .graphiql-toolbar > * + * { - margin-top: var(--px-8); +.graphiql-container .graphiql-toolbar > button { + flex-shrink: 0; } /* The toolbar icons */ .graphiql-toolbar-icon { @@ -2641,6 +2253,3 @@ button.graphiql-tab-add > svg { .graphiql-container svg { pointer-events: none; } - - -/*# sourceMappingURL=graphiql.min.css.map*/ \ No newline at end of file diff --git a/netbox/project-static/dist/graphiql/graphiql.min.js b/netbox/project-static/dist/graphiql/graphiql.min.js index 229d3ebe6..bd0969c1b 100644 --- a/netbox/project-static/dist/graphiql/graphiql.min.js +++ b/netbox/project-static/dist/graphiql/graphiql.min.js @@ -1,96198 +1,32 @@ -/******/ (function() { // webpackBootstrap -/******/ var __webpack_modules__ = ({ - -/***/ "../../../node_modules/@emotion/is-prop-valid/dist/is-prop-valid.browser.esm.js": -/*!**************************************************************************************!*\ - !*** ../../../node_modules/@emotion/is-prop-valid/dist/is-prop-valid.browser.esm.js ***! - \**************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _memoize = _interopRequireDefault(__webpack_require__(/*! @emotion/memoize */ "../../../node_modules/@emotion/memoize/dist/memoize.browser.esm.js")); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var reactPropsRegex = /^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|download|draggable|encType|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|inert|itemProp|itemScope|itemType|itemID|itemRef|on|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/; // https://esbench.com/bench/5bfee68a4cd7e6009ef61d23 - -var index = (0, _memoize.default)(function (prop) { - return reactPropsRegex.test(prop) || prop.charCodeAt(0) === 111 - /* o */ && prop.charCodeAt(1) === 110 - /* n */ && prop.charCodeAt(2) < 91; -} -/* Z+1 */); -var _default = exports["default"] = index; - -/***/ }), - -/***/ "../../../node_modules/@emotion/memoize/dist/memoize.browser.esm.js": -/*!**************************************************************************!*\ - !*** ../../../node_modules/@emotion/memoize/dist/memoize.browser.esm.js ***! - \**************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -function memoize(fn) { - var cache = {}; - return function (arg) { - if (cache[arg] === undefined) cache[arg] = fn(arg); - return cache[arg]; - }; -} -var _default = exports["default"] = memoize; - -/***/ }), - -/***/ "../../../node_modules/@floating-ui/core/dist/floating-ui.core.esm.js": -/*!****************************************************************************!*\ - !*** ../../../node_modules/@floating-ui/core/dist/floating-ui.core.esm.js ***! - \****************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.computePosition = exports.autoPlacement = exports.arrow = void 0; -exports.detectOverflow = detectOverflow; -exports.offset = exports.limitShift = exports.inline = exports.hide = exports.flip = void 0; -exports.rectToClientRect = rectToClientRect; -exports.size = exports.shift = void 0; -function getAlignment(placement) { - return placement.split('-')[1]; -} -function getLengthFromAxis(axis) { - return axis === 'y' ? 'height' : 'width'; -} -function getSide(placement) { - return placement.split('-')[0]; -} -function getMainAxisFromPlacement(placement) { - return ['top', 'bottom'].includes(getSide(placement)) ? 'x' : 'y'; -} -function computeCoordsFromPlacement(_ref, placement, rtl) { - let { - reference, - floating - } = _ref; - const commonX = reference.x + reference.width / 2 - floating.width / 2; - const commonY = reference.y + reference.height / 2 - floating.height / 2; - const mainAxis = getMainAxisFromPlacement(placement); - const length = getLengthFromAxis(mainAxis); - const commonAlign = reference[length] / 2 - floating[length] / 2; - const side = getSide(placement); - const isVertical = mainAxis === 'x'; - let coords; - switch (side) { - case 'top': - coords = { - x: commonX, - y: reference.y - floating.height - }; - break; - case 'bottom': - coords = { - x: commonX, - y: reference.y + reference.height - }; - break; - case 'right': - coords = { - x: reference.x + reference.width, - y: commonY - }; - break; - case 'left': - coords = { - x: reference.x - floating.width, - y: commonY - }; - break; - default: - coords = { - x: reference.x, - y: reference.y - }; - } - switch (getAlignment(placement)) { - case 'start': - coords[mainAxis] -= commonAlign * (rtl && isVertical ? -1 : 1); - break; - case 'end': - coords[mainAxis] += commonAlign * (rtl && isVertical ? -1 : 1); - break; - } - return coords; -} - +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","react-dom"],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GraphiQL=t(e.React,e.ReactDOM)}(this,(function(e,t){"use strict";function n(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const n in e)if("default"!==n){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}return t.default=e,Object.freeze(t)}function r(e,t){for(var n=0;nr[t]})}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}const i=n(e),o=n(t);function s(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var a,l,c={exports:{}},u={};var d,f,p=(l||(l=1,c.exports=function(){if(a)return u;a=1;var t=e,n=Symbol.for("react.element"),r=Symbol.for("react.fragment"),i=Object.prototype.hasOwnProperty,o=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,s={key:!0,ref:!0,__self:!0,__source:!0};function l(e,t,r){var a,l={},c=null,u=null;for(a in void 0!==r&&(c=""+r),void 0!==t.key&&(c=""+t.key),void 0!==t.ref&&(u=t.ref),t)i.call(t,a)&&!s.hasOwnProperty(a)&&(l[a]=t[a]);if(e&&e.defaultProps)for(a in t=e.defaultProps)void 0===l[a]&&(l[a]=t[a]);return{$$typeof:n,type:e,key:c,ref:u,props:l,_owner:o.current}}return u.Fragment=r,u.jsx=l,u.jsxs=l,u}()),c.exports); /** - * Computes the `x` and `y` coordinates that will place the floating element - * next to a reference element when it is given a certain positioning strategy. - * - * This export does not have any `platform` interface logic. You will need to - * write one for the platform you are using Floating UI with. - */ -const computePosition = async (reference, floating, config) => { - const { - placement = 'bottom', - strategy = 'absolute', - middleware = [], - platform - } = config; - const validMiddleware = middleware.filter(Boolean); - const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating)); - let rects = await platform.getElementRects({ - reference, - floating, - strategy - }); - let { - x, - y - } = computeCoordsFromPlacement(rects, placement, rtl); - let statefulPlacement = placement; - let middlewareData = {}; - let resetCount = 0; - for (let i = 0; i < validMiddleware.length; i++) { - const { - name, - fn - } = validMiddleware[i]; - const { - x: nextX, - y: nextY, - data, - reset - } = await fn({ - x, - y, - initialPlacement: placement, - placement: statefulPlacement, - strategy, - middlewareData, - rects, - platform, - elements: { - reference, - floating - } - }); - x = nextX != null ? nextX : x; - y = nextY != null ? nextY : y; - middlewareData = { - ...middlewareData, - [name]: { - ...middlewareData[name], - ...data - } - }; - if (reset && resetCount <= 50) { - resetCount++; - if (typeof reset === 'object') { - if (reset.placement) { - statefulPlacement = reset.placement; - } - if (reset.rects) { - rects = reset.rects === true ? await platform.getElementRects({ - reference, - floating, - strategy - }) : reset.rects; - } - ({ - x, - y - } = computeCoordsFromPlacement(rects, statefulPlacement, rtl)); - } - i = -1; - continue; - } - } - return { - x, - y, - placement: statefulPlacement, - strategy, - middlewareData - }; -}; -exports.computePosition = computePosition; -function evaluate(value, param) { - return typeof value === 'function' ? value(param) : value; -} -function expandPaddingObject(padding) { - return { - top: 0, - right: 0, - bottom: 0, - left: 0, - ...padding - }; -} -function getSideObjectFromPadding(padding) { - return typeof padding !== 'number' ? expandPaddingObject(padding) : { - top: padding, - right: padding, - bottom: padding, - left: padding - }; -} -function rectToClientRect(rect) { - return { - ...rect, - top: rect.y, - left: rect.x, - right: rect.x + rect.width, - bottom: rect.y + rect.height - }; -} - -/** - * Resolves with an object of overflow side offsets that determine how much the - * element is overflowing a given clipping boundary on each side. - * - positive = overflowing the boundary by that number of pixels - * - negative = how many pixels left before it will overflow - * - 0 = lies flush with the boundary - * @see https://floating-ui.com/docs/detectOverflow - */ -async function detectOverflow(state, options) { - var _await$platform$isEle; - if (options === void 0) { - options = {}; - } - const { - x, - y, - platform, - rects, - elements, - strategy - } = state; - const { - boundary = 'clippingAncestors', - rootBoundary = 'viewport', - elementContext = 'floating', - altBoundary = false, - padding = 0 - } = evaluate(options, state); - const paddingObject = getSideObjectFromPadding(padding); - const altContext = elementContext === 'floating' ? 'reference' : 'floating'; - const element = elements[altBoundary ? altContext : elementContext]; - const clippingClientRect = rectToClientRect(await platform.getClippingRect({ - element: ((_await$platform$isEle = await (platform.isElement == null ? void 0 : platform.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || (await (platform.getDocumentElement == null ? void 0 : platform.getDocumentElement(elements.floating))), - boundary, - rootBoundary, - strategy - })); - const rect = elementContext === 'floating' ? { - ...rects.floating, - x, - y - } : rects.reference; - const offsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating)); - const offsetScale = (await (platform.isElement == null ? void 0 : platform.isElement(offsetParent))) ? (await (platform.getScale == null ? void 0 : platform.getScale(offsetParent))) || { - x: 1, - y: 1 - } : { - x: 1, - y: 1 - }; - const elementClientRect = rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({ - rect, - offsetParent, - strategy - }) : rect); - return { - top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y, - bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y, - left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x, - right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x - }; -} -const min = Math.min; -const max = Math.max; -function within(min$1, value, max$1) { - return max(min$1, min(value, max$1)); -} - -/** - * Provides data to position an inner element of the floating element so that it - * appears centered to the reference element. - * @see https://floating-ui.com/docs/arrow - */ -const arrow = options => ({ - name: 'arrow', - options, - async fn(state) { - const { - x, - y, - placement, - rects, - platform, - elements - } = state; - // Since `element` is required, we don't Partial<> the type. - const { - element, - padding = 0 - } = evaluate(options, state) || {}; - if (element == null) { - return {}; - } - const paddingObject = getSideObjectFromPadding(padding); - const coords = { - x, - y - }; - const axis = getMainAxisFromPlacement(placement); - const length = getLengthFromAxis(axis); - const arrowDimensions = await platform.getDimensions(element); - const isYAxis = axis === 'y'; - const minProp = isYAxis ? 'top' : 'left'; - const maxProp = isYAxis ? 'bottom' : 'right'; - const clientProp = isYAxis ? 'clientHeight' : 'clientWidth'; - const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length]; - const startDiff = coords[axis] - rects.reference[axis]; - const arrowOffsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(element)); - let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0; - - // DOM platform can return `window` as the `offsetParent`. - if (!clientSize || !(await (platform.isElement == null ? void 0 : platform.isElement(arrowOffsetParent)))) { - clientSize = elements.floating[clientProp] || rects.floating[length]; - } - const centerToReference = endDiff / 2 - startDiff / 2; - - // If the padding is large enough that it causes the arrow to no longer be - // centered, modify the padding so that it is centered. - const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1; - const minPadding = min(paddingObject[minProp], largestPossiblePadding); - const maxPadding = min(paddingObject[maxProp], largestPossiblePadding); - - // Make sure the arrow doesn't overflow the floating element if the center - // point is outside the floating element's bounds. - const min$1 = minPadding; - const max = clientSize - arrowDimensions[length] - maxPadding; - const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference; - const offset = within(min$1, center, max); - - // If the reference is small enough that the arrow's padding causes it to - // to point to nothing for an aligned placement, adjust the offset of the - // floating element itself. This stops `shift()` from taking action, but can - // be worked around by calling it again after the `arrow()` if desired. - const shouldAddOffset = getAlignment(placement) != null && center != offset && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0; - const alignmentOffset = shouldAddOffset ? center < min$1 ? min$1 - center : max - center : 0; - return { - [axis]: coords[axis] - alignmentOffset, - data: { - [axis]: offset, - centerOffset: center - offset - } - }; - } -}); -exports.arrow = arrow; -const sides = ['top', 'right', 'bottom', 'left']; -const allPlacements = /*#__PURE__*/sides.reduce((acc, side) => acc.concat(side, side + "-start", side + "-end"), []); -const oppositeSideMap = { - left: 'right', - right: 'left', - bottom: 'top', - top: 'bottom' -}; -function getOppositePlacement(placement) { - return placement.replace(/left|right|bottom|top/g, side => oppositeSideMap[side]); -} -function getAlignmentSides(placement, rects, rtl) { - if (rtl === void 0) { - rtl = false; - } - const alignment = getAlignment(placement); - const mainAxis = getMainAxisFromPlacement(placement); - const length = getLengthFromAxis(mainAxis); - let mainAlignmentSide = mainAxis === 'x' ? alignment === (rtl ? 'end' : 'start') ? 'right' : 'left' : alignment === 'start' ? 'bottom' : 'top'; - if (rects.reference[length] > rects.floating[length]) { - mainAlignmentSide = getOppositePlacement(mainAlignmentSide); - } - return { - main: mainAlignmentSide, - cross: getOppositePlacement(mainAlignmentSide) - }; -} -const oppositeAlignmentMap = { - start: 'end', - end: 'start' -}; -function getOppositeAlignmentPlacement(placement) { - return placement.replace(/start|end/g, alignment => oppositeAlignmentMap[alignment]); -} -function getPlacementList(alignment, autoAlignment, allowedPlacements) { - const allowedPlacementsSortedByAlignment = alignment ? [...allowedPlacements.filter(placement => getAlignment(placement) === alignment), ...allowedPlacements.filter(placement => getAlignment(placement) !== alignment)] : allowedPlacements.filter(placement => getSide(placement) === placement); - return allowedPlacementsSortedByAlignment.filter(placement => { - if (alignment) { - return getAlignment(placement) === alignment || (autoAlignment ? getOppositeAlignmentPlacement(placement) !== placement : false); - } - return true; - }); -} -/** - * Optimizes the visibility of the floating element by choosing the placement - * that has the most space available automatically, without needing to specify a - * preferred placement. Alternative to `flip`. - * @see https://floating-ui.com/docs/autoPlacement - */ -const autoPlacement = function (options) { - if (options === void 0) { - options = {}; - } - return { - name: 'autoPlacement', - options, - async fn(state) { - var _middlewareData$autoP, _middlewareData$autoP2, _placementsThatFitOnE; - const { - rects, - middlewareData, - placement, - platform, - elements - } = state; - const { - crossAxis = false, - alignment, - allowedPlacements = allPlacements, - autoAlignment = true, - ...detectOverflowOptions - } = evaluate(options, state); - const placements = alignment !== undefined || allowedPlacements === allPlacements ? getPlacementList(alignment || null, autoAlignment, allowedPlacements) : allowedPlacements; - const overflow = await detectOverflow(state, detectOverflowOptions); - const currentIndex = ((_middlewareData$autoP = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP.index) || 0; - const currentPlacement = placements[currentIndex]; - if (currentPlacement == null) { - return {}; - } - const { - main, - cross - } = getAlignmentSides(currentPlacement, rects, await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))); - - // Make `computeCoords` start from the right place. - if (placement !== currentPlacement) { - return { - reset: { - placement: placements[0] - } - }; - } - const currentOverflows = [overflow[getSide(currentPlacement)], overflow[main], overflow[cross]]; - const allOverflows = [...(((_middlewareData$autoP2 = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP2.overflows) || []), { - placement: currentPlacement, - overflows: currentOverflows - }]; - const nextPlacement = placements[currentIndex + 1]; - - // There are more placements to check. - if (nextPlacement) { - return { - data: { - index: currentIndex + 1, - overflows: allOverflows - }, - reset: { - placement: nextPlacement - } - }; - } - const placementsSortedByMostSpace = allOverflows.map(d => { - const alignment = getAlignment(d.placement); - return [d.placement, alignment && crossAxis ? - // Check along the mainAxis and main crossAxis side. - d.overflows.slice(0, 2).reduce((acc, v) => acc + v, 0) : - // Check only the mainAxis. - d.overflows[0], d.overflows]; - }).sort((a, b) => a[1] - b[1]); - const placementsThatFitOnEachSide = placementsSortedByMostSpace.filter(d => d[2].slice(0, - // Aligned placements should not check their opposite crossAxis - // side. - getAlignment(d[0]) ? 2 : 3).every(v => v <= 0)); - const resetPlacement = ((_placementsThatFitOnE = placementsThatFitOnEachSide[0]) == null ? void 0 : _placementsThatFitOnE[0]) || placementsSortedByMostSpace[0][0]; - if (resetPlacement !== placement) { - return { - data: { - index: currentIndex + 1, - overflows: allOverflows - }, - reset: { - placement: resetPlacement - } - }; - } - return {}; - } - }; -}; -exports.autoPlacement = autoPlacement; -function getExpandedPlacements(placement) { - const oppositePlacement = getOppositePlacement(placement); - return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)]; -} -function getSideList(side, isStart, rtl) { - const lr = ['left', 'right']; - const rl = ['right', 'left']; - const tb = ['top', 'bottom']; - const bt = ['bottom', 'top']; - switch (side) { - case 'top': - case 'bottom': - if (rtl) return isStart ? rl : lr; - return isStart ? lr : rl; - case 'left': - case 'right': - return isStart ? tb : bt; - default: - return []; - } -} -function getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) { - const alignment = getAlignment(placement); - let list = getSideList(getSide(placement), direction === 'start', rtl); - if (alignment) { - list = list.map(side => side + "-" + alignment); - if (flipAlignment) { - list = list.concat(list.map(getOppositeAlignmentPlacement)); - } - } - return list; -} - -/** - * Optimizes the visibility of the floating element by flipping the `placement` - * in order to keep it in view when the preferred placement(s) will overflow the - * clipping boundary. Alternative to `autoPlacement`. - * @see https://floating-ui.com/docs/flip - */ -const flip = function (options) { - if (options === void 0) { - options = {}; - } - return { - name: 'flip', - options, - async fn(state) { - var _middlewareData$flip; - const { - placement, - middlewareData, - rects, - initialPlacement, - platform, - elements - } = state; - const { - mainAxis: checkMainAxis = true, - crossAxis: checkCrossAxis = true, - fallbackPlacements: specifiedFallbackPlacements, - fallbackStrategy = 'bestFit', - fallbackAxisSideDirection = 'none', - flipAlignment = true, - ...detectOverflowOptions - } = evaluate(options, state); - const side = getSide(placement); - const isBasePlacement = getSide(initialPlacement) === initialPlacement; - const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); - const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement)); - if (!specifiedFallbackPlacements && fallbackAxisSideDirection !== 'none') { - fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl)); - } - const placements = [initialPlacement, ...fallbackPlacements]; - const overflow = await detectOverflow(state, detectOverflowOptions); - const overflows = []; - let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || []; - if (checkMainAxis) { - overflows.push(overflow[side]); - } - if (checkCrossAxis) { - const { - main, - cross - } = getAlignmentSides(placement, rects, rtl); - overflows.push(overflow[main], overflow[cross]); - } - overflowsData = [...overflowsData, { - placement, - overflows - }]; - - // One or more sides is overflowing. - if (!overflows.every(side => side <= 0)) { - var _middlewareData$flip2, _overflowsData$filter; - const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1; - const nextPlacement = placements[nextIndex]; - if (nextPlacement) { - // Try next placement and re-run the lifecycle. - return { - data: { - index: nextIndex, - overflows: overflowsData - }, - reset: { - placement: nextPlacement - } - }; - } - - // First, find the candidates that fit on the mainAxis side of overflow, - // then find the placement that fits the best on the main crossAxis side. - let resetPlacement = (_overflowsData$filter = overflowsData.filter(d => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement; - - // Otherwise fallback. - if (!resetPlacement) { - switch (fallbackStrategy) { - case 'bestFit': - { - var _overflowsData$map$so; - const placement = (_overflowsData$map$so = overflowsData.map(d => [d.placement, d.overflows.filter(overflow => overflow > 0).reduce((acc, overflow) => acc + overflow, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$map$so[0]; - if (placement) { - resetPlacement = placement; - } - break; - } - case 'initialPlacement': - resetPlacement = initialPlacement; - break; - } - } - if (placement !== resetPlacement) { - return { - reset: { - placement: resetPlacement - } - }; - } - } - return {}; - } - }; -}; -exports.flip = flip; -function getSideOffsets(overflow, rect) { - return { - top: overflow.top - rect.height, - right: overflow.right - rect.width, - bottom: overflow.bottom - rect.height, - left: overflow.left - rect.width - }; -} -function isAnySideFullyClipped(overflow) { - return sides.some(side => overflow[side] >= 0); -} -/** - * Provides data to hide the floating element in applicable situations, such as - * when it is not in the same clipping context as the reference element. - * @see https://floating-ui.com/docs/hide - */ -const hide = function (options) { - if (options === void 0) { - options = {}; - } - return { - name: 'hide', - options, - async fn(state) { - const { - rects - } = state; - const { - strategy = 'referenceHidden', - ...detectOverflowOptions - } = evaluate(options, state); - switch (strategy) { - case 'referenceHidden': - { - const overflow = await detectOverflow(state, { - ...detectOverflowOptions, - elementContext: 'reference' - }); - const offsets = getSideOffsets(overflow, rects.reference); - return { - data: { - referenceHiddenOffsets: offsets, - referenceHidden: isAnySideFullyClipped(offsets) - } - }; - } - case 'escaped': - { - const overflow = await detectOverflow(state, { - ...detectOverflowOptions, - altBoundary: true - }); - const offsets = getSideOffsets(overflow, rects.floating); - return { - data: { - escapedOffsets: offsets, - escaped: isAnySideFullyClipped(offsets) - } - }; - } - default: - { - return {}; - } - } - } - }; -}; -exports.hide = hide; -function getBoundingRect(rects) { - const minX = min(...rects.map(rect => rect.left)); - const minY = min(...rects.map(rect => rect.top)); - const maxX = max(...rects.map(rect => rect.right)); - const maxY = max(...rects.map(rect => rect.bottom)); - return { - x: minX, - y: minY, - width: maxX - minX, - height: maxY - minY - }; -} -function getRectsByLine(rects) { - const sortedRects = rects.slice().sort((a, b) => a.y - b.y); - const groups = []; - let prevRect = null; - for (let i = 0; i < sortedRects.length; i++) { - const rect = sortedRects[i]; - if (!prevRect || rect.y - prevRect.y > prevRect.height / 2) { - groups.push([rect]); - } else { - groups[groups.length - 1].push(rect); - } - prevRect = rect; - } - return groups.map(rect => rectToClientRect(getBoundingRect(rect))); -} -/** - * Provides improved positioning for inline reference elements that can span - * over multiple lines, such as hyperlinks or range selections. - * @see https://floating-ui.com/docs/inline - */ -const inline = function (options) { - if (options === void 0) { - options = {}; - } - return { - name: 'inline', - options, - async fn(state) { - const { - placement, - elements, - rects, - platform, - strategy - } = state; - // A MouseEvent's client{X,Y} coords can be up to 2 pixels off a - // ClientRect's bounds, despite the event listener being triggered. A - // padding of 2 seems to handle this issue. - const { - padding = 2, - x, - y - } = evaluate(options, state); - const nativeClientRects = Array.from((await (platform.getClientRects == null ? void 0 : platform.getClientRects(elements.reference))) || []); - const clientRects = getRectsByLine(nativeClientRects); - const fallback = rectToClientRect(getBoundingRect(nativeClientRects)); - const paddingObject = getSideObjectFromPadding(padding); - function getBoundingClientRect() { - // There are two rects and they are disjoined. - if (clientRects.length === 2 && clientRects[0].left > clientRects[1].right && x != null && y != null) { - // Find the first rect in which the point is fully inside. - return clientRects.find(rect => x > rect.left - paddingObject.left && x < rect.right + paddingObject.right && y > rect.top - paddingObject.top && y < rect.bottom + paddingObject.bottom) || fallback; - } - - // There are 2 or more connected rects. - if (clientRects.length >= 2) { - if (getMainAxisFromPlacement(placement) === 'x') { - const firstRect = clientRects[0]; - const lastRect = clientRects[clientRects.length - 1]; - const isTop = getSide(placement) === 'top'; - const top = firstRect.top; - const bottom = lastRect.bottom; - const left = isTop ? firstRect.left : lastRect.left; - const right = isTop ? firstRect.right : lastRect.right; - const width = right - left; - const height = bottom - top; - return { - top, - bottom, - left, - right, - width, - height, - x: left, - y: top - }; - } - const isLeftSide = getSide(placement) === 'left'; - const maxRight = max(...clientRects.map(rect => rect.right)); - const minLeft = min(...clientRects.map(rect => rect.left)); - const measureRects = clientRects.filter(rect => isLeftSide ? rect.left === minLeft : rect.right === maxRight); - const top = measureRects[0].top; - const bottom = measureRects[measureRects.length - 1].bottom; - const left = minLeft; - const right = maxRight; - const width = right - left; - const height = bottom - top; - return { - top, - bottom, - left, - right, - width, - height, - x: left, - y: top - }; - } - return fallback; - } - const resetRects = await platform.getElementRects({ - reference: { - getBoundingClientRect - }, - floating: elements.floating, - strategy - }); - if (rects.reference.x !== resetRects.reference.x || rects.reference.y !== resetRects.reference.y || rects.reference.width !== resetRects.reference.width || rects.reference.height !== resetRects.reference.height) { - return { - reset: { - rects: resetRects - } - }; - } - return {}; - } - }; -}; -exports.inline = inline; -async function convertValueToCoords(state, options) { - const { - placement, - platform, - elements - } = state; - const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); - const side = getSide(placement); - const alignment = getAlignment(placement); - const isVertical = getMainAxisFromPlacement(placement) === 'x'; - const mainAxisMulti = ['left', 'top'].includes(side) ? -1 : 1; - const crossAxisMulti = rtl && isVertical ? -1 : 1; - const rawValue = evaluate(options, state); - - // eslint-disable-next-line prefer-const - let { - mainAxis, - crossAxis, - alignmentAxis - } = typeof rawValue === 'number' ? { - mainAxis: rawValue, - crossAxis: 0, - alignmentAxis: null - } : { - mainAxis: 0, - crossAxis: 0, - alignmentAxis: null, - ...rawValue - }; - if (alignment && typeof alignmentAxis === 'number') { - crossAxis = alignment === 'end' ? alignmentAxis * -1 : alignmentAxis; - } - return isVertical ? { - x: crossAxis * crossAxisMulti, - y: mainAxis * mainAxisMulti - } : { - x: mainAxis * mainAxisMulti, - y: crossAxis * crossAxisMulti - }; -} - -/** - * Modifies the placement by translating the floating element along the - * specified axes. - * A number (shorthand for `mainAxis` or distance), or an axes configuration - * object may be passed. - * @see https://floating-ui.com/docs/offset - */ -const offset = function (options) { - if (options === void 0) { - options = 0; - } - return { - name: 'offset', - options, - async fn(state) { - const { - x, - y - } = state; - const diffCoords = await convertValueToCoords(state, options); - return { - x: x + diffCoords.x, - y: y + diffCoords.y, - data: diffCoords - }; - } - }; -}; -exports.offset = offset; -function getCrossAxis(axis) { - return axis === 'x' ? 'y' : 'x'; -} - -/** - * Optimizes the visibility of the floating element by shifting it in order to - * keep it in view when it will overflow the clipping boundary. - * @see https://floating-ui.com/docs/shift - */ -const shift = function (options) { - if (options === void 0) { - options = {}; - } - return { - name: 'shift', - options, - async fn(state) { - const { - x, - y, - placement - } = state; - const { - mainAxis: checkMainAxis = true, - crossAxis: checkCrossAxis = false, - limiter = { - fn: _ref => { - let { - x, - y - } = _ref; - return { - x, - y - }; - } - }, - ...detectOverflowOptions - } = evaluate(options, state); - const coords = { - x, - y - }; - const overflow = await detectOverflow(state, detectOverflowOptions); - const mainAxis = getMainAxisFromPlacement(getSide(placement)); - const crossAxis = getCrossAxis(mainAxis); - let mainAxisCoord = coords[mainAxis]; - let crossAxisCoord = coords[crossAxis]; - if (checkMainAxis) { - const minSide = mainAxis === 'y' ? 'top' : 'left'; - const maxSide = mainAxis === 'y' ? 'bottom' : 'right'; - const min = mainAxisCoord + overflow[minSide]; - const max = mainAxisCoord - overflow[maxSide]; - mainAxisCoord = within(min, mainAxisCoord, max); - } - if (checkCrossAxis) { - const minSide = crossAxis === 'y' ? 'top' : 'left'; - const maxSide = crossAxis === 'y' ? 'bottom' : 'right'; - const min = crossAxisCoord + overflow[minSide]; - const max = crossAxisCoord - overflow[maxSide]; - crossAxisCoord = within(min, crossAxisCoord, max); - } - const limitedCoords = limiter.fn({ - ...state, - [mainAxis]: mainAxisCoord, - [crossAxis]: crossAxisCoord - }); - return { - ...limitedCoords, - data: { - x: limitedCoords.x - x, - y: limitedCoords.y - y - } - }; - } - }; -}; -/** - * Built-in `limiter` that will stop `shift()` at a certain point. - */ -exports.shift = shift; -const limitShift = function (options) { - if (options === void 0) { - options = {}; - } - return { - options, - fn(state) { - const { - x, - y, - placement, - rects, - middlewareData - } = state; - const { - offset = 0, - mainAxis: checkMainAxis = true, - crossAxis: checkCrossAxis = true - } = evaluate(options, state); - const coords = { - x, - y - }; - const mainAxis = getMainAxisFromPlacement(placement); - const crossAxis = getCrossAxis(mainAxis); - let mainAxisCoord = coords[mainAxis]; - let crossAxisCoord = coords[crossAxis]; - const rawOffset = evaluate(offset, state); - const computedOffset = typeof rawOffset === 'number' ? { - mainAxis: rawOffset, - crossAxis: 0 - } : { - mainAxis: 0, - crossAxis: 0, - ...rawOffset - }; - if (checkMainAxis) { - const len = mainAxis === 'y' ? 'height' : 'width'; - const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis; - const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis; - if (mainAxisCoord < limitMin) { - mainAxisCoord = limitMin; - } else if (mainAxisCoord > limitMax) { - mainAxisCoord = limitMax; - } - } - if (checkCrossAxis) { - var _middlewareData$offse, _middlewareData$offse2; - const len = mainAxis === 'y' ? 'width' : 'height'; - const isOriginSide = ['top', 'left'].includes(getSide(placement)); - const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis); - const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0); - if (crossAxisCoord < limitMin) { - crossAxisCoord = limitMin; - } else if (crossAxisCoord > limitMax) { - crossAxisCoord = limitMax; - } - } - return { - [mainAxis]: mainAxisCoord, - [crossAxis]: crossAxisCoord - }; - } - }; -}; - -/** - * Provides data that allows you to change the size of the floating element — - * for instance, prevent it from overflowing the clipping boundary or match the - * width of the reference element. - * @see https://floating-ui.com/docs/size - */ -exports.limitShift = limitShift; -const size = function (options) { - if (options === void 0) { - options = {}; - } - return { - name: 'size', - options, - async fn(state) { - const { - placement, - rects, - platform, - elements - } = state; - const { - apply = () => {}, - ...detectOverflowOptions - } = evaluate(options, state); - const overflow = await detectOverflow(state, detectOverflowOptions); - const side = getSide(placement); - const alignment = getAlignment(placement); - const axis = getMainAxisFromPlacement(placement); - const isXAxis = axis === 'x'; - const { - width, - height - } = rects.floating; - let heightSide; - let widthSide; - if (side === 'top' || side === 'bottom') { - heightSide = side; - widthSide = alignment === ((await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))) ? 'start' : 'end') ? 'left' : 'right'; - } else { - widthSide = side; - heightSide = alignment === 'end' ? 'top' : 'bottom'; - } - const overflowAvailableHeight = height - overflow[heightSide]; - const overflowAvailableWidth = width - overflow[widthSide]; - const noShift = !state.middlewareData.shift; - let availableHeight = overflowAvailableHeight; - let availableWidth = overflowAvailableWidth; - if (isXAxis) { - const maximumClippingWidth = width - overflow.left - overflow.right; - availableWidth = alignment || noShift ? min(overflowAvailableWidth, maximumClippingWidth) : maximumClippingWidth; - } else { - const maximumClippingHeight = height - overflow.top - overflow.bottom; - availableHeight = alignment || noShift ? min(overflowAvailableHeight, maximumClippingHeight) : maximumClippingHeight; - } - if (noShift && !alignment) { - const xMin = max(overflow.left, 0); - const xMax = max(overflow.right, 0); - const yMin = max(overflow.top, 0); - const yMax = max(overflow.bottom, 0); - if (isXAxis) { - availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right)); - } else { - availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom)); - } - } - await apply({ - ...state, - availableWidth, - availableHeight - }); - const nextDimensions = await platform.getDimensions(elements.floating); - if (width !== nextDimensions.width || height !== nextDimensions.height) { - return { - reset: { - rects: true - } - }; - } - return {}; - } - }; -}; -exports.size = size; - -/***/ }), - -/***/ "../../../node_modules/@floating-ui/dom/dist/floating-ui.dom.esm.js": -/*!**************************************************************************!*\ - !*** ../../../node_modules/@floating-ui/dom/dist/floating-ui.dom.esm.js ***! - \**************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "arrow", ({ - enumerable: true, - get: function () { - return _core.arrow; - } -})); -Object.defineProperty(exports, "autoPlacement", ({ - enumerable: true, - get: function () { - return _core.autoPlacement; - } -})); -exports.autoUpdate = autoUpdate; -exports.computePosition = void 0; -Object.defineProperty(exports, "detectOverflow", ({ - enumerable: true, - get: function () { - return _core.detectOverflow; - } -})); -Object.defineProperty(exports, "flip", ({ - enumerable: true, - get: function () { - return _core.flip; - } -})); -exports.getOverflowAncestors = getOverflowAncestors; -Object.defineProperty(exports, "hide", ({ - enumerable: true, - get: function () { - return _core.hide; - } -})); -Object.defineProperty(exports, "inline", ({ - enumerable: true, - get: function () { - return _core.inline; - } -})); -Object.defineProperty(exports, "limitShift", ({ - enumerable: true, - get: function () { - return _core.limitShift; - } -})); -Object.defineProperty(exports, "offset", ({ - enumerable: true, - get: function () { - return _core.offset; - } -})); -exports.platform = void 0; -Object.defineProperty(exports, "shift", ({ - enumerable: true, - get: function () { - return _core.shift; - } -})); -Object.defineProperty(exports, "size", ({ - enumerable: true, - get: function () { - return _core.size; - } -})); -var _core = __webpack_require__(/*! @floating-ui/core */ "../../../node_modules/@floating-ui/core/dist/floating-ui.core.esm.js"); -function getWindow(node) { - var _node$ownerDocument; - return ((_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window; -} -function getComputedStyle$1(element) { - return getWindow(element).getComputedStyle(element); -} -function isNode(value) { - return value instanceof getWindow(value).Node; -} -function getNodeName(node) { - return isNode(node) ? (node.nodeName || '').toLowerCase() : ''; -} -function isHTMLElement(value) { - return value instanceof getWindow(value).HTMLElement; -} -function isElement(value) { - return value instanceof getWindow(value).Element; -} -function isShadowRoot(node) { - // Browsers without `ShadowRoot` support. - if (typeof ShadowRoot === 'undefined') { - return false; - } - const OwnElement = getWindow(node).ShadowRoot; - return node instanceof OwnElement || node instanceof ShadowRoot; -} -function isOverflowElement(element) { - const { - overflow, - overflowX, - overflowY, - display - } = getComputedStyle$1(element); - return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && !['inline', 'contents'].includes(display); -} -function isTableElement(element) { - return ['table', 'td', 'th'].includes(getNodeName(element)); -} -function isContainingBlock(element) { - const safari = isSafari(); - const css = getComputedStyle$1(element); - - // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block - return css.transform !== 'none' || css.perspective !== 'none' || !safari && (css.backdropFilter ? css.backdropFilter !== 'none' : false) || !safari && (css.filter ? css.filter !== 'none' : false) || ['transform', 'perspective', 'filter'].some(value => (css.willChange || '').includes(value)) || ['paint', 'layout', 'strict', 'content'].some(value => (css.contain || '').includes(value)); -} -function isSafari() { - if (typeof CSS === 'undefined' || !CSS.supports) return false; - return CSS.supports('-webkit-backdrop-filter', 'none'); -} -function isLastTraversableNode(node) { - return ['html', 'body', '#document'].includes(getNodeName(node)); -} -const min = Math.min; -const max = Math.max; -const round = Math.round; -function getCssDimensions(element) { - const css = getComputedStyle$1(element); - // In testing environments, the `width` and `height` properties are empty - // strings for SVG elements, returning NaN. Fallback to `0` in this case. - let width = parseFloat(css.width) || 0; - let height = parseFloat(css.height) || 0; - const hasOffset = isHTMLElement(element); - const offsetWidth = hasOffset ? element.offsetWidth : width; - const offsetHeight = hasOffset ? element.offsetHeight : height; - const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight; - if (shouldFallback) { - width = offsetWidth; - height = offsetHeight; - } - return { - width, - height, - fallback: shouldFallback - }; -} -function unwrapElement(element) { - return !isElement(element) ? element.contextElement : element; -} -const FALLBACK_SCALE = { - x: 1, - y: 1 -}; -function getScale(element) { - const domElement = unwrapElement(element); - if (!isHTMLElement(domElement)) { - return FALLBACK_SCALE; - } - const rect = domElement.getBoundingClientRect(); - const { - width, - height, - fallback - } = getCssDimensions(domElement); - let x = (fallback ? round(rect.width) : rect.width) / width; - let y = (fallback ? round(rect.height) : rect.height) / height; - - // 0, NaN, or Infinity should always fallback to 1. - - if (!x || !Number.isFinite(x)) { - x = 1; - } - if (!y || !Number.isFinite(y)) { - y = 1; - } - return { - x, - y - }; -} -const noOffsets = { - x: 0, - y: 0 -}; -function getVisualOffsets(element, isFixed, floatingOffsetParent) { - var _win$visualViewport, _win$visualViewport2; - if (isFixed === void 0) { - isFixed = true; - } - if (!isSafari()) { - return noOffsets; - } - const win = element ? getWindow(element) : window; - if (!floatingOffsetParent || isFixed && floatingOffsetParent !== win) { - return noOffsets; - } - return { - x: ((_win$visualViewport = win.visualViewport) == null ? void 0 : _win$visualViewport.offsetLeft) || 0, - y: ((_win$visualViewport2 = win.visualViewport) == null ? void 0 : _win$visualViewport2.offsetTop) || 0 - }; -} -function getBoundingClientRect(element, includeScale, isFixedStrategy, offsetParent) { - if (includeScale === void 0) { - includeScale = false; - } - if (isFixedStrategy === void 0) { - isFixedStrategy = false; - } - const clientRect = element.getBoundingClientRect(); - const domElement = unwrapElement(element); - let scale = FALLBACK_SCALE; - if (includeScale) { - if (offsetParent) { - if (isElement(offsetParent)) { - scale = getScale(offsetParent); - } - } else { - scale = getScale(element); - } - } - const visualOffsets = getVisualOffsets(domElement, isFixedStrategy, offsetParent); - let x = (clientRect.left + visualOffsets.x) / scale.x; - let y = (clientRect.top + visualOffsets.y) / scale.y; - let width = clientRect.width / scale.x; - let height = clientRect.height / scale.y; - if (domElement) { - const win = getWindow(domElement); - const offsetWin = offsetParent && isElement(offsetParent) ? getWindow(offsetParent) : offsetParent; - let currentIFrame = win.frameElement; - while (currentIFrame && offsetParent && offsetWin !== win) { - const iframeScale = getScale(currentIFrame); - const iframeRect = currentIFrame.getBoundingClientRect(); - const css = getComputedStyle(currentIFrame); - iframeRect.x += (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x; - iframeRect.y += (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y; - x *= iframeScale.x; - y *= iframeScale.y; - width *= iframeScale.x; - height *= iframeScale.y; - x += iframeRect.x; - y += iframeRect.y; - currentIFrame = getWindow(currentIFrame).frameElement; - } - } - return (0, _core.rectToClientRect)({ - width, - height, - x, - y - }); -} -function getDocumentElement(node) { - return ((isNode(node) ? node.ownerDocument : node.document) || window.document).documentElement; -} -function getNodeScroll(element) { - if (isElement(element)) { - return { - scrollLeft: element.scrollLeft, - scrollTop: element.scrollTop - }; - } - return { - scrollLeft: element.pageXOffset, - scrollTop: element.pageYOffset - }; -} -function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) { - let { - rect, - offsetParent, - strategy - } = _ref; - const isOffsetParentAnElement = isHTMLElement(offsetParent); - const documentElement = getDocumentElement(offsetParent); - if (offsetParent === documentElement) { - return rect; - } - let scroll = { - scrollLeft: 0, - scrollTop: 0 - }; - let scale = { - x: 1, - y: 1 - }; - const offsets = { - x: 0, - y: 0 - }; - if (isOffsetParentAnElement || !isOffsetParentAnElement && strategy !== 'fixed') { - if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) { - scroll = getNodeScroll(offsetParent); - } - if (isHTMLElement(offsetParent)) { - const offsetRect = getBoundingClientRect(offsetParent); - scale = getScale(offsetParent); - offsets.x = offsetRect.x + offsetParent.clientLeft; - offsets.y = offsetRect.y + offsetParent.clientTop; - } - } - return { - width: rect.width * scale.x, - height: rect.height * scale.y, - x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x, - y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y - }; -} -function getWindowScrollBarX(element) { - // If has a CSS width greater than the viewport, then this will be - // incorrect for RTL. - return getBoundingClientRect(getDocumentElement(element)).left + getNodeScroll(element).scrollLeft; -} - -// Gets the entire size of the scrollable document area, even extending outside -// of the `` and `` rect bounds if horizontally scrollable. -function getDocumentRect(element) { - const html = getDocumentElement(element); - const scroll = getNodeScroll(element); - const body = element.ownerDocument.body; - const width = max(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth); - const height = max(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight); - let x = -scroll.scrollLeft + getWindowScrollBarX(element); - const y = -scroll.scrollTop; - if (getComputedStyle$1(body).direction === 'rtl') { - x += max(html.clientWidth, body.clientWidth) - width; - } - return { - width, - height, - x, - y - }; -} -function getParentNode(node) { - if (getNodeName(node) === 'html') { - return node; - } - const result = - // Step into the shadow DOM of the parent of a slotted node. - node.assignedSlot || - // DOM Element detected. - node.parentNode || - // ShadowRoot detected. - isShadowRoot(node) && node.host || - // Fallback. - getDocumentElement(node); - return isShadowRoot(result) ? result.host : result; -} -function getNearestOverflowAncestor(node) { - const parentNode = getParentNode(node); - if (isLastTraversableNode(parentNode)) { - // `getParentNode` will never return a `Document` due to the fallback - // check, so it's either the or element. - return parentNode.ownerDocument.body; - } - if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) { - return parentNode; - } - return getNearestOverflowAncestor(parentNode); -} -function getOverflowAncestors(node, list) { - var _node$ownerDocument; - if (list === void 0) { - list = []; - } - const scrollableAncestor = getNearestOverflowAncestor(node); - const isBody = scrollableAncestor === ((_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.body); - const win = getWindow(scrollableAncestor); - if (isBody) { - return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : []); - } - return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor)); -} -function getViewportRect(element, strategy) { - const win = getWindow(element); - const html = getDocumentElement(element); - const visualViewport = win.visualViewport; - let width = html.clientWidth; - let height = html.clientHeight; - let x = 0; - let y = 0; - if (visualViewport) { - width = visualViewport.width; - height = visualViewport.height; - const visualViewportBased = isSafari(); - if (!visualViewportBased || visualViewportBased && strategy === 'fixed') { - x = visualViewport.offsetLeft; - y = visualViewport.offsetTop; - } - } - return { - width, - height, - x, - y - }; -} - -// Returns the inner client rect, subtracting scrollbars if present. -function getInnerBoundingClientRect(element, strategy) { - const clientRect = getBoundingClientRect(element, true, strategy === 'fixed'); - const top = clientRect.top + element.clientTop; - const left = clientRect.left + element.clientLeft; - const scale = isHTMLElement(element) ? getScale(element) : { - x: 1, - y: 1 - }; - const width = element.clientWidth * scale.x; - const height = element.clientHeight * scale.y; - const x = left * scale.x; - const y = top * scale.y; - return { - width, - height, - x, - y - }; -} -function getClientRectFromClippingAncestor(element, clippingAncestor, strategy) { - let rect; - if (clippingAncestor === 'viewport') { - rect = getViewportRect(element, strategy); - } else if (clippingAncestor === 'document') { - rect = getDocumentRect(getDocumentElement(element)); - } else if (isElement(clippingAncestor)) { - rect = getInnerBoundingClientRect(clippingAncestor, strategy); - } else { - const visualOffsets = getVisualOffsets(element); - rect = { - ...clippingAncestor, - x: clippingAncestor.x - visualOffsets.x, - y: clippingAncestor.y - visualOffsets.y - }; - } - return (0, _core.rectToClientRect)(rect); -} -function hasFixedPositionAncestor(element, stopNode) { - const parentNode = getParentNode(element); - if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) { - return false; - } - return getComputedStyle$1(parentNode).position === 'fixed' || hasFixedPositionAncestor(parentNode, stopNode); -} - -// A "clipping ancestor" is an `overflow` element with the characteristic of -// clipping (or hiding) child elements. This returns all clipping ancestors -// of the given element up the tree. -function getClippingElementAncestors(element, cache) { - const cachedResult = cache.get(element); - if (cachedResult) { - return cachedResult; - } - let result = getOverflowAncestors(element).filter(el => isElement(el) && getNodeName(el) !== 'body'); - let currentContainingBlockComputedStyle = null; - const elementIsFixed = getComputedStyle$1(element).position === 'fixed'; - let currentNode = elementIsFixed ? getParentNode(element) : element; - - // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block - while (isElement(currentNode) && !isLastTraversableNode(currentNode)) { - const computedStyle = getComputedStyle$1(currentNode); - const currentNodeIsContaining = isContainingBlock(currentNode); - if (!currentNodeIsContaining && computedStyle.position === 'fixed') { - currentContainingBlockComputedStyle = null; - } - const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === 'static' && !!currentContainingBlockComputedStyle && ['absolute', 'fixed'].includes(currentContainingBlockComputedStyle.position) || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode); - if (shouldDropCurrentNode) { - // Drop non-containing blocks. - result = result.filter(ancestor => ancestor !== currentNode); - } else { - // Record last containing block for next iteration. - currentContainingBlockComputedStyle = computedStyle; - } - currentNode = getParentNode(currentNode); - } - cache.set(element, result); - return result; -} - -// Gets the maximum area that the element is visible in due to any number of -// clipping ancestors. -function getClippingRect(_ref) { - let { - element, - boundary, - rootBoundary, - strategy - } = _ref; - const elementClippingAncestors = boundary === 'clippingAncestors' ? getClippingElementAncestors(element, this._c) : [].concat(boundary); - const clippingAncestors = [...elementClippingAncestors, rootBoundary]; - const firstClippingAncestor = clippingAncestors[0]; - const clippingRect = clippingAncestors.reduce((accRect, clippingAncestor) => { - const rect = getClientRectFromClippingAncestor(element, clippingAncestor, strategy); - accRect.top = max(rect.top, accRect.top); - accRect.right = min(rect.right, accRect.right); - accRect.bottom = min(rect.bottom, accRect.bottom); - accRect.left = max(rect.left, accRect.left); - return accRect; - }, getClientRectFromClippingAncestor(element, firstClippingAncestor, strategy)); - return { - width: clippingRect.right - clippingRect.left, - height: clippingRect.bottom - clippingRect.top, - x: clippingRect.left, - y: clippingRect.top - }; -} -function getDimensions(element) { - return getCssDimensions(element); -} -function getTrueOffsetParent(element, polyfill) { - if (!isHTMLElement(element) || getComputedStyle$1(element).position === 'fixed') { - return null; - } - if (polyfill) { - return polyfill(element); - } - return element.offsetParent; -} -function getContainingBlock(element) { - let currentNode = getParentNode(element); - while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) { - if (isContainingBlock(currentNode)) { - return currentNode; - } else { - currentNode = getParentNode(currentNode); - } - } - return null; -} - -// Gets the closest ancestor positioned element. Handles some edge cases, -// such as table ancestors and cross browser bugs. -function getOffsetParent(element, polyfill) { - const window = getWindow(element); - if (!isHTMLElement(element)) { - return window; - } - let offsetParent = getTrueOffsetParent(element, polyfill); - while (offsetParent && isTableElement(offsetParent) && getComputedStyle$1(offsetParent).position === 'static') { - offsetParent = getTrueOffsetParent(offsetParent, polyfill); - } - if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle$1(offsetParent).position === 'static' && !isContainingBlock(offsetParent))) { - return window; - } - return offsetParent || getContainingBlock(element) || window; -} -function getRectRelativeToOffsetParent(element, offsetParent, strategy) { - const isOffsetParentAnElement = isHTMLElement(offsetParent); - const documentElement = getDocumentElement(offsetParent); - const isFixed = strategy === 'fixed'; - const rect = getBoundingClientRect(element, true, isFixed, offsetParent); - let scroll = { - scrollLeft: 0, - scrollTop: 0 - }; - const offsets = { - x: 0, - y: 0 - }; - if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) { - if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) { - scroll = getNodeScroll(offsetParent); - } - if (isHTMLElement(offsetParent)) { - const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent); - offsets.x = offsetRect.x + offsetParent.clientLeft; - offsets.y = offsetRect.y + offsetParent.clientTop; - } else if (documentElement) { - offsets.x = getWindowScrollBarX(documentElement); - } - } - return { - x: rect.left + scroll.scrollLeft - offsets.x, - y: rect.top + scroll.scrollTop - offsets.y, - width: rect.width, - height: rect.height - }; -} -const platform = exports.platform = { - getClippingRect, - convertOffsetParentRelativeRectToViewportRelativeRect, - isElement, - getDimensions, - getOffsetParent, - getDocumentElement, - getScale, - async getElementRects(_ref) { - let { - reference, - floating, - strategy - } = _ref; - const getOffsetParentFn = this.getOffsetParent || getOffsetParent; - const getDimensionsFn = this.getDimensions; - return { - reference: getRectRelativeToOffsetParent(reference, await getOffsetParentFn(floating), strategy), - floating: { - x: 0, - y: 0, - ...(await getDimensionsFn(floating)) - } - }; - }, - getClientRects: element => Array.from(element.getClientRects()), - isRTL: element => getComputedStyle$1(element).direction === 'rtl' -}; - -/** - * Automatically updates the position of the floating element when necessary. - * Should only be called when the floating element is mounted on the DOM or - * visible on the screen. - * @returns cleanup function that should be invoked when the floating element is - * removed from the DOM or hidden from the screen. - * @see https://floating-ui.com/docs/autoUpdate - */ -function autoUpdate(reference, floating, update, options) { - if (options === void 0) { - options = {}; - } - const { - ancestorScroll = true, - ancestorResize = true, - elementResize = true, - animationFrame = false - } = options; - const ancestors = ancestorScroll || ancestorResize ? [...(isElement(reference) ? getOverflowAncestors(reference) : reference.contextElement ? getOverflowAncestors(reference.contextElement) : []), ...getOverflowAncestors(floating)] : []; - ancestors.forEach(ancestor => { - // ignores Window, checks for [object VisualViewport] - const isVisualViewport = !isElement(ancestor) && ancestor.toString().includes('V'); - if (ancestorScroll && (animationFrame ? isVisualViewport : true)) { - ancestor.addEventListener('scroll', update, { - passive: true - }); - } - ancestorResize && ancestor.addEventListener('resize', update); - }); - let observer = null; - if (elementResize) { - observer = new ResizeObserver(() => { - update(); - }); - isElement(reference) && !animationFrame && observer.observe(reference); - if (!isElement(reference) && reference.contextElement && !animationFrame) { - observer.observe(reference.contextElement); - } - observer.observe(floating); - } - let frameId; - let prevRefRect = animationFrame ? getBoundingClientRect(reference) : null; - if (animationFrame) { - frameLoop(); - } - function frameLoop() { - const nextRefRect = getBoundingClientRect(reference); - if (prevRefRect && (nextRefRect.x !== prevRefRect.x || nextRefRect.y !== prevRefRect.y || nextRefRect.width !== prevRefRect.width || nextRefRect.height !== prevRefRect.height)) { - update(); - } - prevRefRect = nextRefRect; - frameId = requestAnimationFrame(frameLoop); - } - update(); - return () => { - var _observer; - ancestors.forEach(ancestor => { - ancestorScroll && ancestor.removeEventListener('scroll', update); - ancestorResize && ancestor.removeEventListener('resize', update); - }); - (_observer = observer) == null ? void 0 : _observer.disconnect(); - observer = null; - if (animationFrame) { - cancelAnimationFrame(frameId); - } - }; -} - -/** - * Computes the `x` and `y` coordinates that will place the floating element - * next to a reference element when it is given a certain CSS positioning - * strategy. - */ -const computePosition = (reference, floating, options) => { - // This caches the expensive `getClippingElementAncestors` function so that - // multiple lifecycle resets re-use the same result. It only lives for a - // single call. If other functions become expensive, we can add them as well. - const cache = new Map(); - const mergedOptions = { - platform, - ...options - }; - const platformWithCache = { - ...mergedOptions.platform, - _c: cache - }; - return (0, _core.computePosition)(reference, floating, { - ...mergedOptions, - platform: platformWithCache - }); -}; -exports.computePosition = computePosition; - -/***/ }), - -/***/ "../../../node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.esm.js": -/*!**************************************************************************************!*\ - !*** ../../../node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.esm.js ***! - \**************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.arrow = void 0; -Object.defineProperty(exports, "autoPlacement", ({ - enumerable: true, - get: function () { - return _dom.autoPlacement; - } -})); -Object.defineProperty(exports, "autoUpdate", ({ - enumerable: true, - get: function () { - return _dom.autoUpdate; - } -})); -Object.defineProperty(exports, "computePosition", ({ - enumerable: true, - get: function () { - return _dom.computePosition; - } -})); -Object.defineProperty(exports, "detectOverflow", ({ - enumerable: true, - get: function () { - return _dom.detectOverflow; - } -})); -Object.defineProperty(exports, "flip", ({ - enumerable: true, - get: function () { - return _dom.flip; - } -})); -Object.defineProperty(exports, "getOverflowAncestors", ({ - enumerable: true, - get: function () { - return _dom.getOverflowAncestors; - } -})); -Object.defineProperty(exports, "hide", ({ - enumerable: true, - get: function () { - return _dom.hide; - } -})); -Object.defineProperty(exports, "inline", ({ - enumerable: true, - get: function () { - return _dom.inline; - } -})); -Object.defineProperty(exports, "limitShift", ({ - enumerable: true, - get: function () { - return _dom.limitShift; - } -})); -Object.defineProperty(exports, "offset", ({ - enumerable: true, - get: function () { - return _dom.offset; - } -})); -Object.defineProperty(exports, "platform", ({ - enumerable: true, - get: function () { - return _dom.platform; - } -})); -Object.defineProperty(exports, "shift", ({ - enumerable: true, - get: function () { - return _dom.shift; - } -})); -Object.defineProperty(exports, "size", ({ - enumerable: true, - get: function () { - return _dom.size; - } -})); -exports.useFloating = useFloating; -var _dom = __webpack_require__(/*! @floating-ui/dom */ "../../../node_modules/@floating-ui/dom/dist/floating-ui.dom.esm.js"); -var _react = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); -var React = _react; -var ReactDOM = _interopRequireWildcard(__webpack_require__(/*! react-dom */ "react-dom")); -function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } -function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } -/** - * Provides data to position an inner element of the floating element so that it - * appears centered to the reference element. - * This wraps the core `arrow` middleware to allow React refs as the element. - * @see https://floating-ui.com/docs/arrow - */ -const arrow = options => { - function isRef(value) { - return {}.hasOwnProperty.call(value, 'current'); - } - return { - name: 'arrow', - options, - fn(state) { - const { - element, - padding - } = typeof options === 'function' ? options(state) : options; - if (element && isRef(element)) { - if (element.current != null) { - return (0, _dom.arrow)({ - element: element.current, - padding - }).fn(state); - } - return {}; - } else if (element) { - return (0, _dom.arrow)({ - element, - padding - }).fn(state); - } - return {}; - } - }; -}; -exports.arrow = arrow; -var index = typeof document !== 'undefined' ? _react.useLayoutEffect : _react.useEffect; - -// Fork of `fast-deep-equal` that only does the comparisons we need and compares -// functions -function deepEqual(a, b) { - if (a === b) { - return true; - } - if (typeof a !== typeof b) { - return false; - } - if (typeof a === 'function' && a.toString() === b.toString()) { - return true; - } - let length, i, keys; - if (a && b && typeof a == 'object') { - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0;) { - if (!deepEqual(a[i], b[i])) { - return false; - } - } - return true; - } - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) { - return false; - } - for (i = length; i-- !== 0;) { - if (!{}.hasOwnProperty.call(b, keys[i])) { - return false; - } - } - for (i = length; i-- !== 0;) { - const key = keys[i]; - if (key === '_owner' && a.$$typeof) { - continue; - } - if (!deepEqual(a[key], b[key])) { - return false; - } - } - return true; - } - return a !== a && b !== b; -} -function getDPR(element) { - if (typeof window === 'undefined') { - return 1; - } - const win = element.ownerDocument.defaultView || window; - return win.devicePixelRatio || 1; -} -function roundByDPR(element, value) { - const dpr = getDPR(element); - return Math.round(value * dpr) / dpr; -} -function useLatestRef(value) { - const ref = React.useRef(value); - index(() => { - ref.current = value; - }); - return ref; -} - -/** - * Provides data to position a floating element. - * @see https://floating-ui.com/docs/react - */ -function useFloating(options) { - if (options === void 0) { - options = {}; - } - const { - placement = 'bottom', - strategy = 'absolute', - middleware = [], - platform, - elements: { - reference: externalReference, - floating: externalFloating - } = {}, - transform = true, - whileElementsMounted, - open - } = options; - const [data, setData] = React.useState({ - x: 0, - y: 0, - strategy, - placement, - middlewareData: {}, - isPositioned: false - }); - const [latestMiddleware, setLatestMiddleware] = React.useState(middleware); - if (!deepEqual(latestMiddleware, middleware)) { - setLatestMiddleware(middleware); - } - const [_reference, _setReference] = React.useState(null); - const [_floating, _setFloating] = React.useState(null); - const setReference = React.useCallback(node => { - if (node != referenceRef.current) { - referenceRef.current = node; - _setReference(node); - } - }, [_setReference]); - const setFloating = React.useCallback(node => { - if (node !== floatingRef.current) { - floatingRef.current = node; - _setFloating(node); - } - }, [_setFloating]); - const referenceEl = externalReference || _reference; - const floatingEl = externalFloating || _floating; - const referenceRef = React.useRef(null); - const floatingRef = React.useRef(null); - const dataRef = React.useRef(data); - const whileElementsMountedRef = useLatestRef(whileElementsMounted); - const platformRef = useLatestRef(platform); - const update = React.useCallback(() => { - if (!referenceRef.current || !floatingRef.current) { - return; - } - const config = { - placement, - strategy, - middleware: latestMiddleware - }; - if (platformRef.current) { - config.platform = platformRef.current; - } - (0, _dom.computePosition)(referenceRef.current, floatingRef.current, config).then(data => { - const fullData = { - ...data, - isPositioned: true - }; - if (isMountedRef.current && !deepEqual(dataRef.current, fullData)) { - dataRef.current = fullData; - ReactDOM.flushSync(() => { - setData(fullData); - }); - } - }); - }, [latestMiddleware, placement, strategy, platformRef]); - index(() => { - if (open === false && dataRef.current.isPositioned) { - dataRef.current.isPositioned = false; - setData(data => ({ - ...data, - isPositioned: false - })); - } - }, [open]); - const isMountedRef = React.useRef(false); - index(() => { - isMountedRef.current = true; - return () => { - isMountedRef.current = false; - }; - }, []); - index(() => { - if (referenceEl) referenceRef.current = referenceEl; - if (floatingEl) floatingRef.current = floatingEl; - if (referenceEl && floatingEl) { - if (whileElementsMountedRef.current) { - return whileElementsMountedRef.current(referenceEl, floatingEl, update); - } else { - update(); - } - } - }, [referenceEl, floatingEl, update, whileElementsMountedRef]); - const refs = React.useMemo(() => ({ - reference: referenceRef, - floating: floatingRef, - setReference, - setFloating - }), [setReference, setFloating]); - const elements = React.useMemo(() => ({ - reference: referenceEl, - floating: floatingEl - }), [referenceEl, floatingEl]); - const floatingStyles = React.useMemo(() => { - const initialStyles = { - position: strategy, - left: 0, - top: 0 - }; - if (!elements.floating) { - return initialStyles; - } - const x = roundByDPR(elements.floating, data.x); - const y = roundByDPR(elements.floating, data.y); - if (transform) { - return { - ...initialStyles, - transform: "translate(" + x + "px, " + y + "px)", - ...(getDPR(elements.floating) >= 1.5 && { - willChange: 'transform' - }) - }; - } - return { - position: strategy, - left: x, - top: y - }; - }, [strategy, transform, elements.floating, data.x, data.y]); - return React.useMemo(() => ({ - ...data, - update, - refs, - elements, - floatingStyles - }), [data, update, refs, elements, floatingStyles]); -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/animation/dist/Animation.es.js": -/*!***********************************************************************!*\ - !*** ../../../node_modules/@motionone/animation/dist/Animation.es.js ***! - \***********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.Animation = void 0; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -var _easingEs = __webpack_require__(/*! ./utils/easing.es.js */ "../../../node_modules/@motionone/animation/dist/utils/easing.es.js"); -class Animation { - constructor(output, keyframes = [0, 1], { - easing, - duration: initialDuration = _utils.defaults.duration, - delay = _utils.defaults.delay, - endDelay = _utils.defaults.endDelay, - repeat = _utils.defaults.repeat, - offset, - direction = "normal" - } = {}) { - this.startTime = null; - this.rate = 1; - this.t = 0; - this.cancelTimestamp = null; - this.easing = _utils.noopReturn; - this.duration = 0; - this.totalDuration = 0; - this.repeat = 0; - this.playState = "idle"; - this.finished = new Promise((resolve, reject) => { - this.resolve = resolve; - this.reject = reject; - }); - easing = easing || _utils.defaults.easing; - if ((0, _utils.isEasingGenerator)(easing)) { - const custom = easing.createAnimation(keyframes); - easing = custom.easing; - keyframes = custom.keyframes || keyframes; - initialDuration = custom.duration || initialDuration; - } - this.repeat = repeat; - this.easing = (0, _utils.isEasingList)(easing) ? _utils.noopReturn : (0, _easingEs.getEasingFunction)(easing); - this.updateDuration(initialDuration); - const interpolate$1 = (0, _utils.interpolate)(keyframes, offset, (0, _utils.isEasingList)(easing) ? easing.map(_easingEs.getEasingFunction) : _utils.noopReturn); - this.tick = timestamp => { - var _a; - // TODO: Temporary fix for OptionsResolver typing - delay = delay; - let t = 0; - if (this.pauseTime !== undefined) { - t = this.pauseTime; - } else { - t = (timestamp - this.startTime) * this.rate; - } - this.t = t; - // Convert to seconds - t /= 1000; - // Rebase on delay - t = Math.max(t - delay, 0); - /** - * If this animation has finished, set the current time - * to the total duration. - */ - if (this.playState === "finished" && this.pauseTime === undefined) { - t = this.totalDuration; - } - /** - * Get the current progress (0-1) of the animation. If t is > - * than duration we'll get values like 2.5 (midway through the - * third iteration) - */ - const progress = t / this.duration; - // TODO progress += iterationStart - /** - * Get the current iteration (0 indexed). For instance the floor of - * 2.5 is 2. - */ - let currentIteration = Math.floor(progress); - /** - * Get the current progress of the iteration by taking the remainder - * so 2.5 is 0.5 through iteration 2 - */ - let iterationProgress = progress % 1.0; - if (!iterationProgress && progress >= 1) { - iterationProgress = 1; - } - /** - * If iteration progress is 1 we count that as the end - * of the previous iteration. - */ - iterationProgress === 1 && currentIteration--; - /** - * Reverse progress if we're not running in "normal" direction - */ - const iterationIsOdd = currentIteration % 2; - if (direction === "reverse" || direction === "alternate" && iterationIsOdd || direction === "alternate-reverse" && !iterationIsOdd) { - iterationProgress = 1 - iterationProgress; - } - const p = t >= this.totalDuration ? 1 : Math.min(iterationProgress, 1); - const latest = interpolate$1(this.easing(p)); - output(latest); - const isAnimationFinished = this.pauseTime === undefined && (this.playState === "finished" || t >= this.totalDuration + endDelay); - if (isAnimationFinished) { - this.playState = "finished"; - (_a = this.resolve) === null || _a === void 0 ? void 0 : _a.call(this, latest); - } else if (this.playState !== "idle") { - this.frameRequestId = requestAnimationFrame(this.tick); - } - }; - this.play(); - } - play() { - const now = performance.now(); - this.playState = "running"; - if (this.pauseTime !== undefined) { - this.startTime = now - this.pauseTime; - } else if (!this.startTime) { - this.startTime = now; - } - this.cancelTimestamp = this.startTime; - this.pauseTime = undefined; - this.frameRequestId = requestAnimationFrame(this.tick); - } - pause() { - this.playState = "paused"; - this.pauseTime = this.t; - } - finish() { - this.playState = "finished"; - this.tick(0); - } - stop() { - var _a; - this.playState = "idle"; - if (this.frameRequestId !== undefined) { - cancelAnimationFrame(this.frameRequestId); - } - (_a = this.reject) === null || _a === void 0 ? void 0 : _a.call(this, false); - } - cancel() { - this.stop(); - this.tick(this.cancelTimestamp); - } - reverse() { - this.rate *= -1; - } - commitStyles() {} - updateDuration(duration) { - this.duration = duration; - this.totalDuration = duration * (this.repeat + 1); - } - get currentTime() { - return this.t; - } - set currentTime(t) { - if (this.pauseTime !== undefined || this.rate === 0) { - this.pauseTime = t; - } else { - this.startTime = performance.now() - t / this.rate; - } - } - get playbackRate() { - return this.rate; - } - set playbackRate(rate) { - this.rate = rate; - } -} -exports.Animation = Animation; - -/***/ }), - -/***/ "../../../node_modules/@motionone/animation/dist/index.es.js": -/*!*******************************************************************!*\ - !*** ../../../node_modules/@motionone/animation/dist/index.es.js ***! - \*******************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "Animation", ({ - enumerable: true, - get: function () { - return _AnimationEs.Animation; - } -})); -Object.defineProperty(exports, "getEasingFunction", ({ - enumerable: true, - get: function () { - return _easingEs.getEasingFunction; - } -})); -var _AnimationEs = __webpack_require__(/*! ./Animation.es.js */ "../../../node_modules/@motionone/animation/dist/Animation.es.js"); -var _easingEs = __webpack_require__(/*! ./utils/easing.es.js */ "../../../node_modules/@motionone/animation/dist/utils/easing.es.js"); - -/***/ }), - -/***/ "../../../node_modules/@motionone/animation/dist/utils/easing.es.js": -/*!**************************************************************************!*\ - !*** ../../../node_modules/@motionone/animation/dist/utils/easing.es.js ***! - \**************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getEasingFunction = getEasingFunction; -var _easing = __webpack_require__(/*! @motionone/easing */ "../../../node_modules/@motionone/easing/dist/index.es.js"); -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -const namedEasings = { - ease: (0, _easing.cubicBezier)(0.25, 0.1, 0.25, 1.0), - "ease-in": (0, _easing.cubicBezier)(0.42, 0.0, 1.0, 1.0), - "ease-in-out": (0, _easing.cubicBezier)(0.42, 0.0, 0.58, 1.0), - "ease-out": (0, _easing.cubicBezier)(0.0, 0.0, 0.58, 1.0) -}; -const functionArgsRegex = /\((.*?)\)/; -function getEasingFunction(definition) { - // If already an easing function, return - if ((0, _utils.isFunction)(definition)) return definition; - // If an easing curve definition, return bezier function - if ((0, _utils.isCubicBezier)(definition)) return (0, _easing.cubicBezier)(...definition); - // If we have a predefined easing function, return - if (namedEasings[definition]) return namedEasings[definition]; - // If this is a steps function, attempt to create easing curve - if (definition.startsWith("steps")) { - const args = functionArgsRegex.exec(definition); - if (args) { - const argsArray = args[1].split(","); - return (0, _easing.steps)(parseFloat(argsArray[0]), argsArray[1].trim()); - } - } - return _utils.noopReturn; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js": -/*!*****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js ***! - \*****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.animateStyle = animateStyle; -var _dataEs = __webpack_require__(/*! ./data.es.js */ "../../../node_modules/@motionone/dom/dist/animate/data.es.js"); -var _cssVarEs = __webpack_require__(/*! ./utils/css-var.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/css-var.es.js"); -var _animation = __webpack_require__(/*! @motionone/animation */ "../../../node_modules/@motionone/animation/dist/index.es.js"); -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -var _transformsEs = __webpack_require__(/*! ./utils/transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js"); -var _easingEs = __webpack_require__(/*! ./utils/easing.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/easing.es.js"); -var _featureDetectionEs = __webpack_require__(/*! ./utils/feature-detection.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/feature-detection.es.js"); -var _keyframesEs = __webpack_require__(/*! ./utils/keyframes.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/keyframes.es.js"); -var _styleEs = __webpack_require__(/*! ./style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/style.es.js"); -var _getStyleNameEs = __webpack_require__(/*! ./utils/get-style-name.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js"); -var _stopAnimationEs = __webpack_require__(/*! ./utils/stop-animation.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/stop-animation.es.js"); -function getDevToolsRecord() { - return window.__MOTION_DEV_TOOLS_RECORD; -} -function animateStyle(element, key, keyframesDefinition, options = {}) { - const record = getDevToolsRecord(); - const isRecording = options.record !== false && record; - let animation; - let { - duration = _utils.defaults.duration, - delay = _utils.defaults.delay, - endDelay = _utils.defaults.endDelay, - repeat = _utils.defaults.repeat, - easing = _utils.defaults.easing, - direction, - offset, - allowWebkitAcceleration = false - } = options; - const data = (0, _dataEs.getAnimationData)(element); - let canAnimateNatively = _featureDetectionEs.supports.waapi(); - const valueIsTransform = (0, _transformsEs.isTransform)(key); - /** - * If this is an individual transform, we need to map its - * key to a CSS variable and update the element's transform style - */ - valueIsTransform && (0, _transformsEs.addTransformToElement)(element, key); - const name = (0, _getStyleNameEs.getStyleName)(key); - const motionValue = (0, _dataEs.getMotionValue)(data.values, name); - /** - * Get definition of value, this will be used to convert numerical - * keyframes into the default value type. - */ - const definition = _transformsEs.transformDefinitions.get(name); - /** - * Stop the current animation, if any. Because this will trigger - * commitStyles (DOM writes) and we might later trigger DOM reads, - * this is fired now and we return a factory function to create - * the actual animation that can get called in batch, - */ - (0, _stopAnimationEs.stopAnimation)(motionValue.animation, !((0, _utils.isEasingGenerator)(easing) && motionValue.generator) && options.record !== false); - /** - * Batchable factory function containing all DOM reads. - */ - return () => { - const readInitialValue = () => { - var _a, _b; - return (_b = (_a = _styleEs.style.get(element, name)) !== null && _a !== void 0 ? _a : definition === null || definition === void 0 ? void 0 : definition.initialValue) !== null && _b !== void 0 ? _b : 0; - }; - /** - * Replace null values with the previous keyframe value, or read - * it from the DOM if it's the first keyframe. - */ - let keyframes = (0, _keyframesEs.hydrateKeyframes)((0, _keyframesEs.keyframesList)(keyframesDefinition), readInitialValue); - if ((0, _utils.isEasingGenerator)(easing)) { - const custom = easing.createAnimation(keyframes, readInitialValue, valueIsTransform, name, motionValue); - easing = custom.easing; - if (custom.keyframes !== undefined) keyframes = custom.keyframes; - if (custom.duration !== undefined) duration = custom.duration; - } - /** - * If this is a CSS variable we need to register it with the browser - * before it can be animated natively. We also set it with setProperty - * rather than directly onto the element.style object. - */ - if ((0, _cssVarEs.isCssVar)(name)) { - if (_featureDetectionEs.supports.cssRegisterProperty()) { - (0, _cssVarEs.registerCssVariable)(name); - } else { - canAnimateNatively = false; - } - } - /** - * If we can animate this value with WAAPI, do so. Currently this only - * feature detects CSS.registerProperty but could check WAAPI too. - */ - if (canAnimateNatively) { - /** - * Convert numbers to default value types. Currently this only supports - * transforms but it could also support other value types. - */ - if (definition) { - keyframes = keyframes.map(value => (0, _utils.isNumber)(value) ? definition.toDefaultUnit(value) : value); - } - /** - * If this browser doesn't support partial/implicit keyframes we need to - * explicitly provide one. - */ - if (keyframes.length === 1 && (!_featureDetectionEs.supports.partialKeyframes() || isRecording)) { - keyframes.unshift(readInitialValue()); - } - const animationOptions = { - delay: _utils.time.ms(delay), - duration: _utils.time.ms(duration), - endDelay: _utils.time.ms(endDelay), - easing: !(0, _utils.isEasingList)(easing) ? (0, _easingEs.convertEasing)(easing) : undefined, - direction, - iterations: repeat + 1, - fill: "both" - }; - animation = element.animate({ - [name]: keyframes, - offset, - easing: (0, _utils.isEasingList)(easing) ? easing.map(_easingEs.convertEasing) : undefined - }, animationOptions); - /** - * Polyfill finished Promise in browsers that don't support it - */ - if (!animation.finished) { - animation.finished = new Promise((resolve, reject) => { - animation.onfinish = resolve; - animation.oncancel = reject; - }); - } - const target = keyframes[keyframes.length - 1]; - animation.finished.then(() => { - // Apply styles to target - _styleEs.style.set(element, name, target); - // Ensure fill modes don't persist - animation.cancel(); - }).catch(_utils.noop); - /** - * This forces Webkit to run animations on the main thread by exploiting - * this condition: - * https://trac.webkit.org/browser/webkit/trunk/Source/WebCore/platform/graphics/ca/GraphicsLayerCA.cpp?rev=281238#L1099 - * - * This fixes Webkit's timing bugs, like accelerated animations falling - * out of sync with main thread animations and massive delays in starting - * accelerated animations in WKWebView. - */ - if (!allowWebkitAcceleration) animation.playbackRate = 1.000001; - /** - * If we can't animate the value natively then we can fallback to the numbers-only - * polyfill for transforms. - */ - } else if (valueIsTransform) { - /** - * If any keyframe is a string (because we measured it from the DOM), we need to convert - * it into a number before passing to the Animation polyfill. - */ - keyframes = keyframes.map(value => typeof value === "string" ? parseFloat(value) : value); - /** - * If we only have a single keyframe, we need to create an initial keyframe by reading - * the current value from the DOM. - */ - if (keyframes.length === 1) { - keyframes.unshift(parseFloat(readInitialValue())); - } - const render = latest => { - if (definition) latest = definition.toDefaultUnit(latest); - _styleEs.style.set(element, name, latest); - }; - animation = new _animation.Animation(render, keyframes, Object.assign(Object.assign({}, options), { - duration, - easing - })); - } else { - const target = keyframes[keyframes.length - 1]; - _styleEs.style.set(element, name, definition && (0, _utils.isNumber)(target) ? definition.toDefaultUnit(target) : target); - } - if (isRecording) { - record(element, key, keyframes, { - duration, - delay: delay, - easing, - repeat, - offset - }, "motion-one"); - } - motionValue.setAnimation(animation); - return animation; - }; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/data.es.js": -/*!********************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/data.es.js ***! - \********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getAnimationData = getAnimationData; -exports.getMotionValue = getMotionValue; -var _types = __webpack_require__(/*! @motionone/types */ "../../../node_modules/@motionone/types/dist/index.es.js"); -const data = new WeakMap(); -function getAnimationData(element) { - if (!data.has(element)) { - data.set(element, { - transforms: [], - values: new Map() - }); - } - return data.get(element); -} -function getMotionValue(motionValues, name) { - if (!motionValues.has(name)) { - motionValues.set(name, new _types.MotionValue()); - } - return motionValues.get(name); -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/index.es.js": -/*!*********************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/index.es.js ***! - \*********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.animate = animate; -var _animateStyleEs = __webpack_require__(/*! ./animate-style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js"); -var _optionsEs = __webpack_require__(/*! ./utils/options.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/options.es.js"); -var _resolveElementsEs = __webpack_require__(/*! ../utils/resolve-elements.es.js */ "../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js"); -var _controlsEs = __webpack_require__(/*! ./utils/controls.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/controls.es.js"); -var _staggerEs = __webpack_require__(/*! ../utils/stagger.es.js */ "../../../node_modules/@motionone/dom/dist/utils/stagger.es.js"); -function animate(elements, keyframes, options = {}) { - elements = (0, _resolveElementsEs.resolveElements)(elements); - const numElements = elements.length; - /** - * Create and start new animations - */ - const animationFactories = []; - for (let i = 0; i < numElements; i++) { - const element = elements[i]; - for (const key in keyframes) { - const valueOptions = (0, _optionsEs.getOptions)(options, key); - valueOptions.delay = (0, _staggerEs.resolveOption)(valueOptions.delay, i, numElements); - const animation = (0, _animateStyleEs.animateStyle)(element, key, keyframes[key], valueOptions); - animationFactories.push(animation); - } - } - return (0, _controlsEs.withControls)(animationFactories, options, - /** - * TODO: - * If easing is set to spring or glide, duration will be dynamically - * generated. Ideally we would dynamically generate this from - * animation.effect.getComputedTiming().duration but this isn't - * supported in iOS13 or our number polyfill. Perhaps it's possible - * to Proxy animations returned from animateStyle that has duration - * as a getter. - */ - options.duration); -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/style.es.js": -/*!*********************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/style.es.js ***! - \*********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.style = void 0; -var _cssVarEs = __webpack_require__(/*! ./utils/css-var.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/css-var.es.js"); -var _getStyleNameEs = __webpack_require__(/*! ./utils/get-style-name.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js"); -var _transformsEs = __webpack_require__(/*! ./utils/transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js"); -const style = exports.style = { - get: (element, name) => { - name = (0, _getStyleNameEs.getStyleName)(name); - let value = (0, _cssVarEs.isCssVar)(name) ? element.style.getPropertyValue(name) : getComputedStyle(element)[name]; - if (!value && value !== 0) { - const definition = _transformsEs.transformDefinitions.get(name); - if (definition) value = definition.initialValue; - } - return value; - }, - set: (element, name, value) => { - name = (0, _getStyleNameEs.getStyleName)(name); - if ((0, _cssVarEs.isCssVar)(name)) { - element.style.setProperty(name, value); - } else { - element.style[name] = value; - } - } -}; - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/utils/controls.es.js": -/*!******************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/controls.es.js ***! - \******************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.withControls = exports.controls = void 0; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -var _stopAnimationEs = __webpack_require__(/*! ./stop-animation.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/stop-animation.es.js"); -const createAnimation = factory => factory(); -const withControls = (animationFactory, options, duration = _utils.defaults.duration) => { - return new Proxy({ - animations: animationFactory.map(createAnimation).filter(Boolean), - duration, - options - }, controls); -}; -/** - * TODO: - * Currently this returns the first animation, ideally it would return - * the first active animation. - */ -exports.withControls = withControls; -const getActiveAnimation = state => state.animations[0]; -const controls = exports.controls = { - get: (target, key) => { - const activeAnimation = getActiveAnimation(target); - switch (key) { - case "duration": - return target.duration; - case "currentTime": - return _utils.time.s((activeAnimation === null || activeAnimation === void 0 ? void 0 : activeAnimation[key]) || 0); - case "playbackRate": - case "playState": - return activeAnimation === null || activeAnimation === void 0 ? void 0 : activeAnimation[key]; - case "finished": - if (!target.finished) { - target.finished = Promise.all(target.animations.map(selectFinished)).catch(_utils.noop); - } - return target.finished; - case "stop": - return () => { - target.animations.forEach(animation => (0, _stopAnimationEs.stopAnimation)(animation)); - }; - case "forEachNative": - /** - * This is for internal use only, fire a callback for each - * underlying animation. - */ - return callback => { - target.animations.forEach(animation => callback(animation, target)); - }; - default: - return typeof (activeAnimation === null || activeAnimation === void 0 ? void 0 : activeAnimation[key]) === "undefined" ? undefined : () => target.animations.forEach(animation => animation[key]()); - } - }, - set: (target, key, value) => { - switch (key) { - case "currentTime": - value = _utils.time.ms(value); - case "currentTime": - case "playbackRate": - for (let i = 0; i < target.animations.length; i++) { - target.animations[i][key] = value; - } - return true; - } - return false; - } -}; -const selectFinished = animation => animation.finished; - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/utils/css-var.es.js": -/*!*****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/css-var.es.js ***! - \*****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isCssVar = void 0; -exports.registerCssVariable = registerCssVariable; -exports.registeredProperties = void 0; -var _transformsEs = __webpack_require__(/*! ./transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js"); -const isCssVar = name => name.startsWith("--"); -exports.isCssVar = isCssVar; -const registeredProperties = exports.registeredProperties = new Set(); -function registerCssVariable(name) { - if (registeredProperties.has(name)) return; - registeredProperties.add(name); - try { - const { - syntax, - initialValue - } = _transformsEs.transformDefinitions.has(name) ? _transformsEs.transformDefinitions.get(name) : {}; - CSS.registerProperty({ - name, - inherits: false, - syntax, - initialValue - }); - } catch (e) {} -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/utils/easing.es.js": -/*!****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/easing.es.js ***! - \****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.cubicBezierAsString = exports.convertEasing = void 0; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -const convertEasing = easing => (0, _utils.isCubicBezier)(easing) ? cubicBezierAsString(easing) : easing; -exports.convertEasing = convertEasing; -const cubicBezierAsString = ([a, b, c, d]) => `cubic-bezier(${a}, ${b}, ${c}, ${d})`; -exports.cubicBezierAsString = cubicBezierAsString; - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/utils/feature-detection.es.js": -/*!***************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/feature-detection.es.js ***! - \***************************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.supports = void 0; -const testAnimation = keyframes => document.createElement("div").animate(keyframes, { - duration: 0.001 -}); -const featureTests = { - cssRegisterProperty: () => typeof CSS !== "undefined" && Object.hasOwnProperty.call(CSS, "registerProperty"), - waapi: () => Object.hasOwnProperty.call(Element.prototype, "animate"), - partialKeyframes: () => { - try { - testAnimation({ - opacity: [1] - }); - } catch (e) { - return false; - } - return true; - }, - finished: () => Boolean(testAnimation({ - opacity: [0, 1] - }).finished) -}; -const results = {}; -const supports = exports.supports = {}; -for (const key in featureTests) { - supports[key] = () => { - if (results[key] === undefined) results[key] = featureTests[key](); - return results[key]; - }; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js": -/*!************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js ***! - \************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getStyleName = getStyleName; -var _transformsEs = __webpack_require__(/*! ./transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js"); -function getStyleName(key) { - if (_transformsEs.transformAlias[key]) key = _transformsEs.transformAlias[key]; - return (0, _transformsEs.isTransform)(key) ? (0, _transformsEs.asTransformCssVar)(key) : key; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/utils/keyframes.es.js": -/*!*******************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/keyframes.es.js ***! - \*******************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.hydrateKeyframes = hydrateKeyframes; -exports.keyframesList = void 0; -function hydrateKeyframes(keyframes, readInitialValue) { - for (let i = 0; i < keyframes.length; i++) { - if (keyframes[i] === null) { - keyframes[i] = i ? keyframes[i - 1] : readInitialValue(); - } - } - return keyframes; -} -const keyframesList = keyframes => Array.isArray(keyframes) ? keyframes : [keyframes]; -exports.keyframesList = keyframesList; - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/utils/options.es.js": -/*!*****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/options.es.js ***! - \*****************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getOptions = void 0; -const getOptions = (options, key) => -/** - * TODO: Make test for this - * Always return a new object otherwise delay is overwritten by results of stagger - * and this results in no stagger - */ -options[key] ? Object.assign(Object.assign({}, options), options[key]) : Object.assign({}, options); -exports.getOptions = getOptions; - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/utils/stop-animation.es.js": -/*!************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/stop-animation.es.js ***! - \************************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.stopAnimation = stopAnimation; -function stopAnimation(animation, needsCommit = true) { - if (!animation || animation.playState === "finished") return; - // Suppress error thrown by WAAPI - try { - if (animation.stop) { - animation.stop(); - } else { - needsCommit && animation.commitStyles(); - animation.cancel(); - } - } catch (e) {} -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/utils/style-object.es.js": -/*!**********************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/style-object.es.js ***! - \**********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.createStyles = createStyles; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -var _transformsEs = __webpack_require__(/*! ./transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js"); -function createStyles(keyframes) { - const initialKeyframes = {}; - const transformKeys = []; - for (let key in keyframes) { - const value = keyframes[key]; - if ((0, _transformsEs.isTransform)(key)) { - if (_transformsEs.transformAlias[key]) key = _transformsEs.transformAlias[key]; - transformKeys.push(key); - key = (0, _transformsEs.asTransformCssVar)(key); - } - let initialKeyframe = Array.isArray(value) ? value[0] : value; - /** - * If this is a number and we have a default value type, convert the number - * to this type. - */ - const definition = _transformsEs.transformDefinitions.get(key); - if (definition) { - initialKeyframe = (0, _utils.isNumber)(value) ? definition.toDefaultUnit(value) : value; - } - initialKeyframes[key] = initialKeyframe; - } - if (transformKeys.length) { - initialKeyframes.transform = (0, _transformsEs.buildTransformTemplate)(transformKeys); - } - return initialKeyframes; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/utils/style-string.es.js": -/*!**********************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/style-string.es.js ***! - \**********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.createStyleString = createStyleString; -var _styleObjectEs = __webpack_require__(/*! ./style-object.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/style-object.es.js"); -const camelLetterToPipeLetter = letter => `-${letter.toLowerCase()}`; -const camelToPipeCase = str => str.replace(/[A-Z]/g, camelLetterToPipeLetter); -function createStyleString(target = {}) { - const styles = (0, _styleObjectEs.createStyles)(target); - let style = ""; - for (const key in styles) { - style += key.startsWith("--") ? key : camelToPipeCase(key); - style += `: ${styles[key]}; `; - } - return style; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js": -/*!********************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js ***! - \********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.transformDefinitions = exports.transformAlias = exports.isTransform = exports.compareTransformOrder = exports.buildTransformTemplate = exports.axes = exports.asTransformCssVar = exports.addTransformToElement = void 0; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -var _dataEs = __webpack_require__(/*! ../data.es.js */ "../../../node_modules/@motionone/dom/dist/animate/data.es.js"); -/** - * A list of all transformable axes. We'll use this list to generated a version - * of each axes for each transform. - */ -const axes = exports.axes = ["", "X", "Y", "Z"]; -/** - * An ordered array of each transformable value. By default, transform values - * will be sorted to this order. - */ -const order = ["translate", "scale", "rotate", "skew"]; -const transformAlias = exports.transformAlias = { - x: "translateX", - y: "translateY", - z: "translateZ" -}; -const rotation = { - syntax: "", - initialValue: "0deg", - toDefaultUnit: v => v + "deg" -}; -const baseTransformProperties = { - translate: { - syntax: "", - initialValue: "0px", - toDefaultUnit: v => v + "px" - }, - rotate: rotation, - scale: { - syntax: "", - initialValue: 1, - toDefaultUnit: _utils.noopReturn - }, - skew: rotation -}; -const transformDefinitions = exports.transformDefinitions = new Map(); -const asTransformCssVar = name => `--motion-${name}`; -/** - * Generate a list of every possible transform key - */ -exports.asTransformCssVar = asTransformCssVar; -const transforms = ["x", "y", "z"]; -order.forEach(name => { - axes.forEach(axis => { - transforms.push(name + axis); - transformDefinitions.set(asTransformCssVar(name + axis), baseTransformProperties[name]); - }); -}); -/** - * A function to use with Array.sort to sort transform keys by their default order. - */ -const compareTransformOrder = (a, b) => transforms.indexOf(a) - transforms.indexOf(b); -/** - * Provide a quick way to check if a string is the name of a transform - */ -exports.compareTransformOrder = compareTransformOrder; -const transformLookup = new Set(transforms); -const isTransform = name => transformLookup.has(name); -exports.isTransform = isTransform; -const addTransformToElement = (element, name) => { - // Map x to translateX etc - if (transformAlias[name]) name = transformAlias[name]; - const { - transforms - } = (0, _dataEs.getAnimationData)(element); - (0, _utils.addUniqueItem)(transforms, name); - /** - * TODO: An optimisation here could be to cache the transform in element data - * and only update if this has changed. - */ - element.style.transform = buildTransformTemplate(transforms); -}; -exports.addTransformToElement = addTransformToElement; -const buildTransformTemplate = transforms => transforms.sort(compareTransformOrder).reduce(transformListToString, "").trim(); -exports.buildTransformTemplate = buildTransformTemplate; -const transformListToString = (template, name) => `${template} ${name}(var(${asTransformCssVar(name)}))`; - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/easing/create-generator-easing.es.js": -/*!**************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/easing/create-generator-easing.es.js ***! - \**************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.createGeneratorEasing = createGeneratorEasing; -var _generators = __webpack_require__(/*! @motionone/generators */ "../../../node_modules/@motionone/generators/dist/index.es.js"); -function createGeneratorEasing(createGenerator) { - const keyframesCache = new WeakMap(); - return (options = {}) => { - const generatorCache = new Map(); - const getGenerator = (from = 0, to = 100, velocity = 0, isScale = false) => { - const key = `${from}-${to}-${velocity}-${isScale}`; - if (!generatorCache.has(key)) { - generatorCache.set(key, createGenerator(Object.assign({ - from, - to, - velocity, - restSpeed: isScale ? 0.05 : 2, - restDistance: isScale ? 0.01 : 0.5 - }, options))); - } - return generatorCache.get(key); - }; - const getKeyframes = generator => { - if (!keyframesCache.has(generator)) { - keyframesCache.set(generator, (0, _generators.pregenerateKeyframes)(generator)); - } - return keyframesCache.get(generator); - }; - return { - createAnimation: (keyframes, getOrigin, canUseGenerator, name, motionValue) => { - var _a, _b; - let settings; - const numKeyframes = keyframes.length; - let shouldUseGenerator = canUseGenerator && numKeyframes <= 2 && keyframes.every(isNumberOrNull); - if (shouldUseGenerator) { - const target = keyframes[numKeyframes - 1]; - const unresolvedOrigin = numKeyframes === 1 ? null : keyframes[0]; - let velocity = 0; - let origin = 0; - const prevGenerator = motionValue === null || motionValue === void 0 ? void 0 : motionValue.generator; - if (prevGenerator) { - /** - * If we have a generator for this value we can use it to resolve - * the animations's current value and velocity. - */ - const { - animation, - generatorStartTime - } = motionValue; - const startTime = (animation === null || animation === void 0 ? void 0 : animation.startTime) || generatorStartTime || 0; - const currentTime = (animation === null || animation === void 0 ? void 0 : animation.currentTime) || performance.now() - startTime; - const prevGeneratorCurrent = prevGenerator(currentTime).current; - origin = (_a = unresolvedOrigin) !== null && _a !== void 0 ? _a : prevGeneratorCurrent; - if (numKeyframes === 1 || numKeyframes === 2 && keyframes[0] === null) { - velocity = (0, _generators.calcGeneratorVelocity)(t => prevGenerator(t).current, currentTime, prevGeneratorCurrent); - } - } else { - origin = (_b = unresolvedOrigin) !== null && _b !== void 0 ? _b : parseFloat(getOrigin()); - } - const generator = getGenerator(origin, target, velocity, name === null || name === void 0 ? void 0 : name.includes("scale")); - const keyframesMetadata = getKeyframes(generator); - settings = Object.assign(Object.assign({}, keyframesMetadata), { - easing: "linear" - }); - // TODO Add test for this - if (motionValue) { - motionValue.generator = generator; - motionValue.generatorStartTime = performance.now(); - } - } else { - const keyframesMetadata = getKeyframes(getGenerator(0, 100)); - settings = { - easing: "ease", - duration: keyframesMetadata.overshootDuration - }; - } - return settings; - } - }; - }; -} -const isNumberOrNull = value => typeof value !== "string"; - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/easing/glide/index.es.js": -/*!**************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/easing/glide/index.es.js ***! - \**************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.glide = void 0; -var _generators = __webpack_require__(/*! @motionone/generators */ "../../../node_modules/@motionone/generators/dist/index.es.js"); -var _createGeneratorEasingEs = __webpack_require__(/*! ../create-generator-easing.es.js */ "../../../node_modules/@motionone/dom/dist/easing/create-generator-easing.es.js"); -const glide = exports.glide = (0, _createGeneratorEasingEs.createGeneratorEasing)(_generators.glide); - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/easing/spring/index.es.js": -/*!***************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/easing/spring/index.es.js ***! - \***************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.spring = void 0; -var _generators = __webpack_require__(/*! @motionone/generators */ "../../../node_modules/@motionone/generators/dist/index.es.js"); -var _createGeneratorEasingEs = __webpack_require__(/*! ../create-generator-easing.es.js */ "../../../node_modules/@motionone/dom/dist/easing/create-generator-easing.es.js"); -const spring = exports.spring = (0, _createGeneratorEasingEs.createGeneratorEasing)(_generators.spring); - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/gestures/in-view.es.js": -/*!************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/in-view.es.js ***! - \************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.inView = inView; -var _resolveElementsEs = __webpack_require__(/*! ../utils/resolve-elements.es.js */ "../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js"); -const thresholds = { - any: 0, - all: 1 -}; -function inView(elementOrSelector, onStart, { - root, - margin: rootMargin, - amount = "any" -} = {}) { - /** - * If this browser doesn't support IntersectionObserver, return a dummy stop function. - * Default triggering of onStart is tricky - it could be used for starting/stopping - * videos, lazy loading content etc. We could provide an option to enable a fallback, or - * provide a fallback callback option. - */ - if (typeof IntersectionObserver === "undefined") { - return () => {}; - } - const elements = (0, _resolveElementsEs.resolveElements)(elementOrSelector); - const activeIntersections = new WeakMap(); - const onIntersectionChange = entries => { - entries.forEach(entry => { - const onEnd = activeIntersections.get(entry.target); - /** - * If there's no change to the intersection, we don't need to - * do anything here. - */ - if (entry.isIntersecting === Boolean(onEnd)) return; - if (entry.isIntersecting) { - const newOnEnd = onStart(entry); - if (typeof newOnEnd === "function") { - activeIntersections.set(entry.target, newOnEnd); - } else { - observer.unobserve(entry.target); - } - } else if (onEnd) { - onEnd(entry); - activeIntersections.delete(entry.target); - } - }); - }; - const observer = new IntersectionObserver(onIntersectionChange, { - root, - rootMargin, - threshold: typeof amount === "number" ? amount : thresholds[amount] - }); - elements.forEach(element => observer.observe(element)); - return () => observer.disconnect(); -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/gestures/resize/handle-element.es.js": -/*!**************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/resize/handle-element.es.js ***! - \**************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.resizeElement = resizeElement; -var _resolveElementsEs = __webpack_require__(/*! ../../utils/resolve-elements.es.js */ "../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js"); -const resizeHandlers = new WeakMap(); -let observer; -function getElementSize(target, borderBoxSize) { - if (borderBoxSize) { - const { - inlineSize, - blockSize - } = borderBoxSize[0]; - return { - width: inlineSize, - height: blockSize - }; - } else if (target instanceof SVGElement && "getBBox" in target) { - return target.getBBox(); - } else { - return { - width: target.offsetWidth, - height: target.offsetHeight - }; - } -} -function notifyTarget({ - target, - contentRect, - borderBoxSize -}) { - var _a; - (_a = resizeHandlers.get(target)) === null || _a === void 0 ? void 0 : _a.forEach(handler => { - handler({ - target, - contentSize: contentRect, - get size() { - return getElementSize(target, borderBoxSize); - } - }); - }); -} -function notifyAll(entries) { - entries.forEach(notifyTarget); -} -function createResizeObserver() { - if (typeof ResizeObserver === "undefined") return; - observer = new ResizeObserver(notifyAll); -} -function resizeElement(target, handler) { - if (!observer) createResizeObserver(); - const elements = (0, _resolveElementsEs.resolveElements)(target); - elements.forEach(element => { - let elementHandlers = resizeHandlers.get(element); - if (!elementHandlers) { - elementHandlers = new Set(); - resizeHandlers.set(element, elementHandlers); - } - elementHandlers.add(handler); - observer === null || observer === void 0 ? void 0 : observer.observe(element); - }); - return () => { - elements.forEach(element => { - const elementHandlers = resizeHandlers.get(element); - elementHandlers === null || elementHandlers === void 0 ? void 0 : elementHandlers.delete(handler); - if (!(elementHandlers === null || elementHandlers === void 0 ? void 0 : elementHandlers.size)) { - observer === null || observer === void 0 ? void 0 : observer.unobserve(element); - } - }); - }; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/gestures/resize/handle-window.es.js": -/*!*************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/resize/handle-window.es.js ***! - \*************************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.resizeWindow = resizeWindow; -const windowCallbacks = new Set(); -let windowResizeHandler; -function createWindowResizeHandler() { - windowResizeHandler = () => { - const size = { - width: window.innerWidth, - height: window.innerHeight - }; - const info = { - target: window, - size, - contentSize: size - }; - windowCallbacks.forEach(callback => callback(info)); - }; - window.addEventListener("resize", windowResizeHandler); -} -function resizeWindow(callback) { - windowCallbacks.add(callback); - if (!windowResizeHandler) createWindowResizeHandler(); - return () => { - windowCallbacks.delete(callback); - if (!windowCallbacks.size && windowResizeHandler) { - windowResizeHandler = undefined; - } - }; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/gestures/resize/index.es.js": -/*!*****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/resize/index.es.js ***! - \*****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.resize = resize; -var _handleElementEs = __webpack_require__(/*! ./handle-element.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/resize/handle-element.es.js"); -var _handleWindowEs = __webpack_require__(/*! ./handle-window.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/resize/handle-window.es.js"); -function resize(a, b) { - return typeof a === "function" ? (0, _handleWindowEs.resizeWindow)(a) : (0, _handleElementEs.resizeElement)(a, b); -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/index.es.js": -/*!*****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/index.es.js ***! - \*****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.scroll = scroll; -var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); -var _indexEs = __webpack_require__(/*! ../resize/index.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/resize/index.es.js"); -var _infoEs = __webpack_require__(/*! ./info.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/info.es.js"); -var _onScrollHandlerEs = __webpack_require__(/*! ./on-scroll-handler.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/on-scroll-handler.es.js"); -const scrollListeners = new WeakMap(); -const resizeListeners = new WeakMap(); -const onScrollHandlers = new WeakMap(); -const getEventTarget = element => element === document.documentElement ? window : element; -function scroll(onScroll, _a = {}) { - var { - container = document.documentElement - } = _a, - options = (0, _tslib.__rest)(_a, ["container"]); - let containerHandlers = onScrollHandlers.get(container); - /** - * Get the onScroll handlers for this container. - * If one isn't found, create a new one. - */ - if (!containerHandlers) { - containerHandlers = new Set(); - onScrollHandlers.set(container, containerHandlers); - } - /** - * Create a new onScroll handler for the provided callback. - */ - const info = (0, _infoEs.createScrollInfo)(); - const containerHandler = (0, _onScrollHandlerEs.createOnScrollHandler)(container, onScroll, info, options); - containerHandlers.add(containerHandler); - /** - * Check if there's a scroll event listener for this container. - * If not, create one. - */ - if (!scrollListeners.has(container)) { - const listener = () => { - const time = performance.now(); - for (const handler of containerHandlers) handler.measure(); - for (const handler of containerHandlers) handler.update(time); - for (const handler of containerHandlers) handler.notify(); - }; - scrollListeners.set(container, listener); - const target = getEventTarget(container); - window.addEventListener("resize", listener, { - passive: true - }); - if (container !== document.documentElement) { - resizeListeners.set(container, (0, _indexEs.resize)(container, listener)); - } - target.addEventListener("scroll", listener, { - passive: true - }); - } - const listener = scrollListeners.get(container); - const onLoadProcesss = requestAnimationFrame(listener); - return () => { - var _a; - if (typeof onScroll !== "function") onScroll.stop(); - cancelAnimationFrame(onLoadProcesss); - /** - * Check if we even have any handlers for this container. - */ - const containerHandlers = onScrollHandlers.get(container); - if (!containerHandlers) return; - containerHandlers.delete(containerHandler); - if (containerHandlers.size) return; - /** - * If no more handlers, remove the scroll listener too. - */ - const listener = scrollListeners.get(container); - scrollListeners.delete(container); - if (listener) { - getEventTarget(container).removeEventListener("scroll", listener); - (_a = resizeListeners.get(container)) === null || _a === void 0 ? void 0 : _a(); - window.removeEventListener("resize", listener); - } - }; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/info.es.js": -/*!****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/info.es.js ***! - \****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.createScrollInfo = void 0; -exports.updateScrollInfo = updateScrollInfo; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -/** - * A time in milliseconds, beyond which we consider the scroll velocity to be 0. - */ -const maxElapsed = 50; -const createAxisInfo = () => ({ - current: 0, - offset: [], - progress: 0, - scrollLength: 0, - targetOffset: 0, - targetLength: 0, - containerLength: 0, - velocity: 0 -}); -const createScrollInfo = () => ({ - time: 0, - x: createAxisInfo(), - y: createAxisInfo() -}); -exports.createScrollInfo = createScrollInfo; -const keys = { - x: { - length: "Width", - position: "Left" - }, - y: { - length: "Height", - position: "Top" - } -}; -function updateAxisInfo(element, axisName, info, time) { - const axis = info[axisName]; - const { - length, - position - } = keys[axisName]; - const prev = axis.current; - const prevTime = info.time; - axis.current = element["scroll" + position]; - axis.scrollLength = element["scroll" + length] - element["client" + length]; - axis.offset.length = 0; - axis.offset[0] = 0; - axis.offset[1] = axis.scrollLength; - axis.progress = (0, _utils.progress)(0, axis.scrollLength, axis.current); - const elapsed = time - prevTime; - axis.velocity = elapsed > maxElapsed ? 0 : (0, _utils.velocityPerSecond)(axis.current - prev, elapsed); -} -function updateScrollInfo(element, info, time) { - updateAxisInfo(element, "x", info, time); - updateAxisInfo(element, "y", info, time); - info.time = time; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/edge.es.js": -/*!************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/edge.es.js ***! - \************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.namedEdges = void 0; -exports.resolveEdge = resolveEdge; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -const namedEdges = exports.namedEdges = { - start: 0, - center: 0.5, - end: 1 -}; -function resolveEdge(edge, length, inset = 0) { - let delta = 0; - /** - * If we have this edge defined as a preset, replace the definition - * with the numerical value. - */ - if (namedEdges[edge] !== undefined) { - edge = namedEdges[edge]; - } - /** - * Handle unit values - */ - if ((0, _utils.isString)(edge)) { - const asNumber = parseFloat(edge); - if (edge.endsWith("px")) { - delta = asNumber; - } else if (edge.endsWith("%")) { - edge = asNumber / 100; - } else if (edge.endsWith("vw")) { - delta = asNumber / 100 * document.documentElement.clientWidth; - } else if (edge.endsWith("vh")) { - delta = asNumber / 100 * document.documentElement.clientHeight; - } else { - edge = asNumber; - } - } - /** - * If the edge is defined as a number, handle as a progress value. - */ - if ((0, _utils.isNumber)(edge)) { - delta = length * edge; - } - return inset + delta; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/index.es.js": -/*!*************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/index.es.js ***! - \*************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.resolveOffsets = resolveOffsets; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -var _insetEs = __webpack_require__(/*! ./inset.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/inset.es.js"); -var _presetsEs = __webpack_require__(/*! ./presets.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/presets.es.js"); -var _offsetEs = __webpack_require__(/*! ./offset.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/offset.es.js"); -const point = { - x: 0, - y: 0 -}; -function resolveOffsets(container, info, options) { - let { - offset: offsetDefinition = _presetsEs.ScrollOffset.All - } = options; - const { - target = container, - axis = "y" - } = options; - const lengthLabel = axis === "y" ? "height" : "width"; - const inset = target !== container ? (0, _insetEs.calcInset)(target, container) : point; - /** - * Measure the target and container. If they're the same thing then we - * use the container's scrollWidth/Height as the target, from there - * all other calculations can remain the same. - */ - const targetSize = target === container ? { - width: container.scrollWidth, - height: container.scrollHeight - } : { - width: target.clientWidth, - height: target.clientHeight - }; - const containerSize = { - width: container.clientWidth, - height: container.clientHeight - }; - /** - * Reset the length of the resolved offset array rather than creating a new one. - * TODO: More reusable data structures for targetSize/containerSize would also be good. - */ - info[axis].offset.length = 0; - /** - * Populate the offset array by resolving the user's offset definition into - * a list of pixel scroll offets. - */ - let hasChanged = !info[axis].interpolate; - const numOffsets = offsetDefinition.length; - for (let i = 0; i < numOffsets; i++) { - const offset = (0, _offsetEs.resolveOffset)(offsetDefinition[i], containerSize[lengthLabel], targetSize[lengthLabel], inset[axis]); - if (!hasChanged && offset !== info[axis].interpolatorOffsets[i]) { - hasChanged = true; - } - info[axis].offset[i] = offset; - } - /** - * If the pixel scroll offsets have changed, create a new interpolator function - * to map scroll value into a progress. - */ - if (hasChanged) { - info[axis].interpolate = (0, _utils.interpolate)((0, _utils.defaultOffset)(numOffsets), info[axis].offset); - info[axis].interpolatorOffsets = [...info[axis].offset]; - } - info[axis].progress = info[axis].interpolate(info[axis].current); -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/inset.es.js": -/*!*************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/inset.es.js ***! - \*************************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.calcInset = calcInset; -function calcInset(element, container) { - let inset = { - x: 0, - y: 0 - }; - let current = element; - while (current && current !== container) { - if (current instanceof HTMLElement) { - inset.x += current.offsetLeft; - inset.y += current.offsetTop; - current = current.offsetParent; - } else if (current instanceof SVGGraphicsElement && "getBBox" in current) { - const { - top, - left - } = current.getBBox(); - inset.x += left; - inset.y += top; - /** - * Assign the next parent element as the tag. - */ - while (current && current.tagName !== "svg") { - current = current.parentNode; - } - } - } - return inset; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/offset.es.js": -/*!**************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/offset.es.js ***! - \**************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.resolveOffset = resolveOffset; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -var _edgeEs = __webpack_require__(/*! ./edge.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/edge.es.js"); -const defaultOffset = [0, 0]; -function resolveOffset(offset, containerLength, targetLength, targetInset) { - let offsetDefinition = Array.isArray(offset) ? offset : defaultOffset; - let targetPoint = 0; - let containerPoint = 0; - if ((0, _utils.isNumber)(offset)) { - /** - * If we're provided offset: [0, 0.5, 1] then each number x should become - * [x, x], so we default to the behaviour of mapping 0 => 0 of both target - * and container etc. - */ - offsetDefinition = [offset, offset]; - } else if ((0, _utils.isString)(offset)) { - offset = offset.trim(); - if (offset.includes(" ")) { - offsetDefinition = offset.split(" "); - } else { - /** - * If we're provided a definition like "100px" then we want to apply - * that only to the top of the target point, leaving the container at 0. - * Whereas a named offset like "end" should be applied to both. - */ - offsetDefinition = [offset, _edgeEs.namedEdges[offset] ? offset : `0`]; - } - } - targetPoint = (0, _edgeEs.resolveEdge)(offsetDefinition[0], targetLength, targetInset); - containerPoint = (0, _edgeEs.resolveEdge)(offsetDefinition[1], containerLength); - return targetPoint - containerPoint; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/presets.es.js": -/*!***************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/presets.es.js ***! - \***************************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.ScrollOffset = void 0; -const ScrollOffset = exports.ScrollOffset = { - Enter: [[0, 1], [1, 1]], - Exit: [[0, 0], [1, 0]], - Any: [[1, 0], [0, 1]], - All: [[0, 0], [1, 1]] -}; - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/on-scroll-handler.es.js": -/*!*****************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/on-scroll-handler.es.js ***! - \*****************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.createOnScrollHandler = createOnScrollHandler; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -var _infoEs = __webpack_require__(/*! ./info.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/info.es.js"); -var _indexEs = __webpack_require__(/*! ./offsets/index.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/index.es.js"); -function measure(container, target = container, info) { - /** - * Find inset of target within scrollable container - */ - info.x.targetOffset = 0; - info.y.targetOffset = 0; - if (target !== container) { - let node = target; - while (node && node != container) { - info.x.targetOffset += node.offsetLeft; - info.y.targetOffset += node.offsetTop; - node = node.offsetParent; - } - } - info.x.targetLength = target === container ? target.scrollWidth : target.clientWidth; - info.y.targetLength = target === container ? target.scrollHeight : target.clientHeight; - info.x.containerLength = container.clientWidth; - info.y.containerLength = container.clientHeight; -} -function createOnScrollHandler(element, onScroll, info, options = {}) { - const axis = options.axis || "y"; - return { - measure: () => measure(element, options.target, info), - update: time => { - (0, _infoEs.updateScrollInfo)(element, info, time); - if (options.offset || options.target) { - (0, _indexEs.resolveOffsets)(element, info, options); - } - }, - notify: typeof onScroll === "function" ? () => onScroll(info) : scrubAnimation(onScroll, info[axis]) - }; -} -function scrubAnimation(controls, axisInfo) { - controls.pause(); - controls.forEachNative((animation, { - easing - }) => { - var _a, _b; - if (animation.updateDuration) { - if (!easing) animation.easing = _utils.noopReturn; - animation.updateDuration(1); - } else { - const timingOptions = { - duration: 1000 - }; - if (!easing) timingOptions.easing = "linear"; - (_b = (_a = animation.effect) === null || _a === void 0 ? void 0 : _a.updateTiming) === null || _b === void 0 ? void 0 : _b.call(_a, timingOptions); - } - }); - return () => { - controls.currentTime = axisInfo.progress; - }; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/index.es.js": -/*!*************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/index.es.js ***! - \*************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "ScrollOffset", ({ - enumerable: true, - get: function () { - return _presetsEs.ScrollOffset; - } -})); -Object.defineProperty(exports, "animate", ({ - enumerable: true, - get: function () { - return _indexEs.animate; - } -})); -Object.defineProperty(exports, "animateStyle", ({ - enumerable: true, - get: function () { - return _animateStyleEs.animateStyle; - } -})); -Object.defineProperty(exports, "createMotionState", ({ - enumerable: true, - get: function () { - return _indexEs7.createMotionState; - } -})); -Object.defineProperty(exports, "createStyleString", ({ - enumerable: true, - get: function () { - return _styleStringEs.createStyleString; - } -})); -Object.defineProperty(exports, "createStyles", ({ - enumerable: true, - get: function () { - return _styleObjectEs.createStyles; - } -})); -Object.defineProperty(exports, "getAnimationData", ({ - enumerable: true, - get: function () { - return _dataEs.getAnimationData; - } -})); -Object.defineProperty(exports, "getStyleName", ({ - enumerable: true, - get: function () { - return _getStyleNameEs.getStyleName; - } -})); -Object.defineProperty(exports, "glide", ({ - enumerable: true, - get: function () { - return _indexEs4.glide; - } -})); -Object.defineProperty(exports, "inView", ({ - enumerable: true, - get: function () { - return _inViewEs.inView; - } -})); -Object.defineProperty(exports, "mountedStates", ({ - enumerable: true, - get: function () { - return _indexEs7.mountedStates; - } -})); -Object.defineProperty(exports, "resize", ({ - enumerable: true, - get: function () { - return _indexEs5.resize; - } -})); -Object.defineProperty(exports, "scroll", ({ - enumerable: true, - get: function () { - return _indexEs6.scroll; - } -})); -Object.defineProperty(exports, "spring", ({ - enumerable: true, - get: function () { - return _indexEs3.spring; - } -})); -Object.defineProperty(exports, "stagger", ({ - enumerable: true, - get: function () { - return _staggerEs.stagger; - } -})); -Object.defineProperty(exports, "style", ({ - enumerable: true, - get: function () { - return _styleEs.style; - } -})); -Object.defineProperty(exports, "timeline", ({ - enumerable: true, - get: function () { - return _indexEs2.timeline; - } -})); -Object.defineProperty(exports, "withControls", ({ - enumerable: true, - get: function () { - return _controlsEs.withControls; - } -})); -var _indexEs = __webpack_require__(/*! ./animate/index.es.js */ "../../../node_modules/@motionone/dom/dist/animate/index.es.js"); -var _animateStyleEs = __webpack_require__(/*! ./animate/animate-style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js"); -var _indexEs2 = __webpack_require__(/*! ./timeline/index.es.js */ "../../../node_modules/@motionone/dom/dist/timeline/index.es.js"); -var _staggerEs = __webpack_require__(/*! ./utils/stagger.es.js */ "../../../node_modules/@motionone/dom/dist/utils/stagger.es.js"); -var _indexEs3 = __webpack_require__(/*! ./easing/spring/index.es.js */ "../../../node_modules/@motionone/dom/dist/easing/spring/index.es.js"); -var _indexEs4 = __webpack_require__(/*! ./easing/glide/index.es.js */ "../../../node_modules/@motionone/dom/dist/easing/glide/index.es.js"); -var _styleEs = __webpack_require__(/*! ./animate/style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/style.es.js"); -var _inViewEs = __webpack_require__(/*! ./gestures/in-view.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/in-view.es.js"); -var _indexEs5 = __webpack_require__(/*! ./gestures/resize/index.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/resize/index.es.js"); -var _indexEs6 = __webpack_require__(/*! ./gestures/scroll/index.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/index.es.js"); -var _presetsEs = __webpack_require__(/*! ./gestures/scroll/offsets/presets.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/presets.es.js"); -var _controlsEs = __webpack_require__(/*! ./animate/utils/controls.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/controls.es.js"); -var _dataEs = __webpack_require__(/*! ./animate/data.es.js */ "../../../node_modules/@motionone/dom/dist/animate/data.es.js"); -var _getStyleNameEs = __webpack_require__(/*! ./animate/utils/get-style-name.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js"); -var _indexEs7 = __webpack_require__(/*! ./state/index.es.js */ "../../../node_modules/@motionone/dom/dist/state/index.es.js"); -var _styleObjectEs = __webpack_require__(/*! ./animate/utils/style-object.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/style-object.es.js"); -var _styleStringEs = __webpack_require__(/*! ./animate/utils/style-string.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/style-string.es.js"); - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/state/gestures/hover.es.js": -/*!****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/gestures/hover.es.js ***! - \****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.hover = void 0; -var _eventsEs = __webpack_require__(/*! ../utils/events.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/events.es.js"); -const mouseEvent = (element, name, action) => event => { - if (event.pointerType && event.pointerType !== "mouse") return; - action(); - (0, _eventsEs.dispatchPointerEvent)(element, name, event); -}; -const hover = exports.hover = { - isActive: options => Boolean(options.hover), - subscribe: (element, { - enable, - disable - }) => { - const onEnter = mouseEvent(element, "hoverstart", enable); - const onLeave = mouseEvent(element, "hoverend", disable); - element.addEventListener("pointerenter", onEnter); - element.addEventListener("pointerleave", onLeave); - return () => { - element.removeEventListener("pointerenter", onEnter); - element.removeEventListener("pointerleave", onLeave); - }; - } -}; - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/state/gestures/in-view.es.js": -/*!******************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/gestures/in-view.es.js ***! - \******************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.inView = void 0; -var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); -var _eventsEs = __webpack_require__(/*! ../utils/events.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/events.es.js"); -var _inViewEs = __webpack_require__(/*! ../../gestures/in-view.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/in-view.es.js"); -const inView = exports.inView = { - isActive: options => Boolean(options.inView), - subscribe: (element, { - enable, - disable - }, { - inViewOptions = {} - }) => { - const { - once - } = inViewOptions, - viewOptions = (0, _tslib.__rest)(inViewOptions, ["once"]); - return (0, _inViewEs.inView)(element, enterEntry => { - enable(); - (0, _eventsEs.dispatchViewEvent)(element, "viewenter", enterEntry); - if (!once) { - return leaveEntry => { - disable(); - (0, _eventsEs.dispatchViewEvent)(element, "viewleave", leaveEntry); - }; - } - }, viewOptions); - } -}; - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/state/gestures/press.es.js": -/*!****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/gestures/press.es.js ***! - \****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.press = void 0; -var _eventsEs = __webpack_require__(/*! ../utils/events.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/events.es.js"); -const press = exports.press = { - isActive: options => Boolean(options.press), - subscribe: (element, { - enable, - disable - }) => { - const onPointerUp = event => { - disable(); - (0, _eventsEs.dispatchPointerEvent)(element, "pressend", event); - window.removeEventListener("pointerup", onPointerUp); - }; - const onPointerDown = event => { - enable(); - (0, _eventsEs.dispatchPointerEvent)(element, "pressstart", event); - window.addEventListener("pointerup", onPointerUp); - }; - element.addEventListener("pointerdown", onPointerDown); - return () => { - element.removeEventListener("pointerdown", onPointerDown); - window.removeEventListener("pointerup", onPointerUp); - }; - } -}; - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/state/index.es.js": -/*!*******************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/index.es.js ***! - \*******************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.createMotionState = createMotionState; -exports.mountedStates = void 0; -var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); -var _heyListen = __webpack_require__(/*! hey-listen */ "../../../node_modules/hey-listen/dist/hey-listen.es.js"); -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -var _animateStyleEs = __webpack_require__(/*! ../animate/animate-style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js"); -var _styleEs = __webpack_require__(/*! ../animate/style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/style.es.js"); -var _optionsEs = __webpack_require__(/*! ../animate/utils/options.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/options.es.js"); -var _hasChangedEs = __webpack_require__(/*! ./utils/has-changed.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/has-changed.es.js"); -var _resolveVariantEs = __webpack_require__(/*! ./utils/resolve-variant.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/resolve-variant.es.js"); -var _scheduleEs = __webpack_require__(/*! ./utils/schedule.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/schedule.es.js"); -var _inViewEs = __webpack_require__(/*! ./gestures/in-view.es.js */ "../../../node_modules/@motionone/dom/dist/state/gestures/in-view.es.js"); -var _hoverEs = __webpack_require__(/*! ./gestures/hover.es.js */ "../../../node_modules/@motionone/dom/dist/state/gestures/hover.es.js"); -var _pressEs = __webpack_require__(/*! ./gestures/press.es.js */ "../../../node_modules/@motionone/dom/dist/state/gestures/press.es.js"); -var _eventsEs = __webpack_require__(/*! ./utils/events.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/events.es.js"); -const gestures = { - inView: _inViewEs.inView, - hover: _hoverEs.hover, - press: _pressEs.press -}; -/** - * A list of state types, in priority order. If a value is defined in - * a righter-most type, it will override any definition in a lefter-most. - */ -const stateTypes = ["initial", "animate", ...Object.keys(gestures), "exit"]; -/** - * A global store of all generated motion states. This can be used to lookup - * a motion state for a given Element. - */ -const mountedStates = exports.mountedStates = new WeakMap(); -function createMotionState(options = {}, parent) { - /** - * The element represented by the motion state. This is an empty reference - * when we create the state to support SSR and allow for later mounting - * in view libraries. + * Copyright (c) Meta Platforms, Inc. and affiliates. * - * @ts-ignore - */ - let element; - /** - * Calculate a depth that we can use to order motion states by tree depth. - */ - let depth = parent ? parent.getDepth() + 1 : 0; - /** - * Track which states are currently active. - */ - const activeStates = { - initial: true, - animate: true - }; - /** - * A map of functions that, when called, will remove event listeners for - * a given gesture. - */ - const gestureSubscriptions = {}; - /** - * Initialise a context to share through motion states. This - * will be populated by variant names (if any). - */ - const context = {}; - for (const name of stateTypes) { - context[name] = typeof options[name] === "string" ? options[name] : parent === null || parent === void 0 ? void 0 : parent.getContext()[name]; - } - /** - * If initial is set to false we use the animate prop as the initial - * animation state. - */ - const initialVariantSource = options.initial === false ? "animate" : "initial"; - /** - * Destructure an initial target out from the resolved initial variant. - */ - let _a = (0, _resolveVariantEs.resolveVariant)(options[initialVariantSource] || context[initialVariantSource], options.variants) || {}, - target = (0, _tslib.__rest)(_a, ["transition"]); - /** - * The base target is a cached map of values that we'll use to animate - * back to if a value is removed from all active state types. This - * is usually the initial value as read from the DOM, for instance if - * it hasn't been defined in initial. - */ - const baseTarget = Object.assign({}, target); - /** - * A generator that will be processed by the global animation scheduler. - * This yeilds when it switches from reading the DOM to writing to it - * to prevent layout thrashing. - */ - function* animateUpdates() { - var _a, _b; - const prevTarget = target; - target = {}; - const animationOptions = {}; - for (const name of stateTypes) { - if (!activeStates[name]) continue; - const variant = (0, _resolveVariantEs.resolveVariant)(options[name]); - if (!variant) continue; - for (const key in variant) { - if (key === "transition") continue; - target[key] = variant[key]; - animationOptions[key] = (0, _optionsEs.getOptions)((_b = (_a = variant.transition) !== null && _a !== void 0 ? _a : options.transition) !== null && _b !== void 0 ? _b : {}, key); - } - } - const allTargetKeys = new Set([...Object.keys(target), ...Object.keys(prevTarget)]); - const animationFactories = []; - allTargetKeys.forEach(key => { - var _a; - if (target[key] === undefined) { - target[key] = baseTarget[key]; - } - if ((0, _hasChangedEs.hasChanged)(prevTarget[key], target[key])) { - (_a = baseTarget[key]) !== null && _a !== void 0 ? _a : baseTarget[key] = _styleEs.style.get(element, key); - animationFactories.push((0, _animateStyleEs.animateStyle)(element, key, target[key], animationOptions[key])); - } - }); - // Wait for all animation states to read from the DOM - yield; - const animations = animationFactories.map(factory => factory()).filter(Boolean); - if (!animations.length) return; - const animationTarget = target; - element.dispatchEvent((0, _eventsEs.motionEvent)("motionstart", animationTarget)); - Promise.all(animations.map(animation => animation.finished)).then(() => { - element.dispatchEvent((0, _eventsEs.motionEvent)("motioncomplete", animationTarget)); - }).catch(_utils.noop); - } - const setGesture = (name, isActive) => () => { - activeStates[name] = isActive; - (0, _scheduleEs.scheduleAnimation)(state); - }; - const updateGestureSubscriptions = () => { - for (const name in gestures) { - const isGestureActive = gestures[name].isActive(options); - const remove = gestureSubscriptions[name]; - if (isGestureActive && !remove) { - gestureSubscriptions[name] = gestures[name].subscribe(element, { - enable: setGesture(name, true), - disable: setGesture(name, false) - }, options); - } else if (!isGestureActive && remove) { - remove(); - delete gestureSubscriptions[name]; - } - } - }; - const state = { - update: newOptions => { - if (!element) return; - options = newOptions; - updateGestureSubscriptions(); - (0, _scheduleEs.scheduleAnimation)(state); - }, - setActive: (name, isActive) => { - if (!element) return; - activeStates[name] = isActive; - (0, _scheduleEs.scheduleAnimation)(state); - }, - animateUpdates, - getDepth: () => depth, - getTarget: () => target, - getOptions: () => options, - getContext: () => context, - mount: newElement => { - (0, _heyListen.invariant)(Boolean(newElement), "Animation state must be mounted with valid Element"); - element = newElement; - mountedStates.set(element, state); - updateGestureSubscriptions(); - return () => { - mountedStates.delete(element); - (0, _scheduleEs.unscheduleAnimation)(state); - for (const key in gestureSubscriptions) { - gestureSubscriptions[key](); - } - }; - }, - isMounted: () => Boolean(element) - }; - return state; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/state/utils/events.es.js": -/*!**************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/utils/events.es.js ***! - \**************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.dispatchPointerEvent = dispatchPointerEvent; -exports.dispatchViewEvent = dispatchViewEvent; -exports.motionEvent = void 0; -const motionEvent = (name, target) => new CustomEvent(name, { - detail: { - target - } -}); -exports.motionEvent = motionEvent; -function dispatchPointerEvent(element, name, event) { - element.dispatchEvent(new CustomEvent(name, { - detail: { - originalEvent: event - } - })); -} -function dispatchViewEvent(element, name, entry) { - element.dispatchEvent(new CustomEvent(name, { - detail: { - originalEntry: entry - } - })); -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/state/utils/has-changed.es.js": -/*!*******************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/utils/has-changed.es.js ***! - \*******************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.hasChanged = hasChanged; -exports.shallowCompare = shallowCompare; -function hasChanged(a, b) { - if (typeof a !== typeof b) return true; - if (Array.isArray(a) && Array.isArray(b)) return !shallowCompare(a, b); - return a !== b; -} -function shallowCompare(next, prev) { - const prevLength = prev.length; - if (prevLength !== next.length) return false; - for (let i = 0; i < prevLength; i++) { - if (prev[i] !== next[i]) return false; - } - return true; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/state/utils/is-variant.es.js": -/*!******************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/utils/is-variant.es.js ***! - \******************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isVariant = isVariant; -function isVariant(definition) { - return typeof definition === "object"; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/state/utils/resolve-variant.es.js": -/*!***********************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/utils/resolve-variant.es.js ***! - \***********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.resolveVariant = resolveVariant; -var _isVariantEs = __webpack_require__(/*! ./is-variant.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/is-variant.es.js"); -function resolveVariant(definition, variants) { - if ((0, _isVariantEs.isVariant)(definition)) { - return definition; - } else if (definition && variants) { - return variants[definition]; - } -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/state/utils/schedule.es.js": -/*!****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/utils/schedule.es.js ***! - \****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.scheduleAnimation = scheduleAnimation; -exports.unscheduleAnimation = unscheduleAnimation; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -let scheduled = undefined; -function processScheduledAnimations() { - if (!scheduled) return; - const generators = scheduled.sort(compareByDepth).map(fireAnimateUpdates); - generators.forEach(fireNext); - generators.forEach(fireNext); - scheduled = undefined; -} -function scheduleAnimation(state) { - if (!scheduled) { - scheduled = [state]; - requestAnimationFrame(processScheduledAnimations); - } else { - (0, _utils.addUniqueItem)(scheduled, state); - } -} -function unscheduleAnimation(state) { - scheduled && (0, _utils.removeItem)(scheduled, state); -} -const compareByDepth = (a, b) => a.getDepth() - b.getDepth(); -const fireAnimateUpdates = state => state.animateUpdates(); -const fireNext = iterator => iterator.next(); - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/timeline/index.es.js": -/*!**********************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/timeline/index.es.js ***! - \**********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.createAnimationsFromTimeline = createAnimationsFromTimeline; -exports.timeline = timeline; -var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); -var _heyListen = __webpack_require__(/*! hey-listen */ "../../../node_modules/hey-listen/dist/hey-listen.es.js"); -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -var _staggerEs = __webpack_require__(/*! ../utils/stagger.es.js */ "../../../node_modules/@motionone/dom/dist/utils/stagger.es.js"); -var _animateStyleEs = __webpack_require__(/*! ../animate/animate-style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js"); -var _controlsEs = __webpack_require__(/*! ../animate/utils/controls.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/controls.es.js"); -var _keyframesEs = __webpack_require__(/*! ../animate/utils/keyframes.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/keyframes.es.js"); -var _optionsEs = __webpack_require__(/*! ../animate/utils/options.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/options.es.js"); -var _resolveElementsEs = __webpack_require__(/*! ../utils/resolve-elements.es.js */ "../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js"); -var _transformsEs = __webpack_require__(/*! ../animate/utils/transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js"); -var _calcTimeEs = __webpack_require__(/*! ./utils/calc-time.es.js */ "../../../node_modules/@motionone/dom/dist/timeline/utils/calc-time.es.js"); -var _editEs = __webpack_require__(/*! ./utils/edit.es.js */ "../../../node_modules/@motionone/dom/dist/timeline/utils/edit.es.js"); -var _sortEs = __webpack_require__(/*! ./utils/sort.es.js */ "../../../node_modules/@motionone/dom/dist/timeline/utils/sort.es.js"); -function timeline(definition, options = {}) { - var _a; - const animationDefinitions = createAnimationsFromTimeline(definition, options); - /** - * Create and start animations - */ - const animationFactories = animationDefinitions.map(definition => (0, _animateStyleEs.animateStyle)(...definition)).filter(Boolean); - return (0, _controlsEs.withControls)(animationFactories, options, - // Get the duration from the first animation definition - (_a = animationDefinitions[0]) === null || _a === void 0 ? void 0 : _a[3].duration); -} -function createAnimationsFromTimeline(definition, _a = {}) { - var { - defaultOptions = {} - } = _a, - timelineOptions = (0, _tslib.__rest)(_a, ["defaultOptions"]); - const animationDefinitions = []; - const elementSequences = new Map(); - const elementCache = {}; - const timeLabels = new Map(); - let prevTime = 0; - let currentTime = 0; - let totalDuration = 0; - /** - * Build the timeline by mapping over the definition array and converting - * the definitions into keyframes and offsets with absolute time values. - * These will later get converted into relative offsets in a second pass. - */ - for (let i = 0; i < definition.length; i++) { - const segment = definition[i]; - /** - * If this is a timeline label, mark it and skip the rest of this iteration. - */ - if ((0, _utils.isString)(segment)) { - timeLabels.set(segment, currentTime); - continue; - } else if (!Array.isArray(segment)) { - timeLabels.set(segment.name, (0, _calcTimeEs.calcNextTime)(currentTime, segment.at, prevTime, timeLabels)); - continue; - } - const [elementDefinition, keyframes, options = {}] = segment; - /** - * If a relative or absolute time value has been specified we need to resolve - * it in relation to the currentTime. - */ - if (options.at !== undefined) { - currentTime = (0, _calcTimeEs.calcNextTime)(currentTime, options.at, prevTime, timeLabels); - } - /** - * Keep track of the maximum duration in this definition. This will be - * applied to currentTime once the definition has been parsed. - */ - let maxDuration = 0; - /** - * Find all the elements specified in the definition and parse value - * keyframes from their timeline definitions. - */ - const elements = (0, _resolveElementsEs.resolveElements)(elementDefinition, elementCache); - const numElements = elements.length; - for (let elementIndex = 0; elementIndex < numElements; elementIndex++) { - const element = elements[elementIndex]; - const elementSequence = getElementSequence(element, elementSequences); - for (const key in keyframes) { - const valueSequence = getValueSequence(key, elementSequence); - let valueKeyframes = (0, _keyframesEs.keyframesList)(keyframes[key]); - const valueOptions = (0, _optionsEs.getOptions)(options, key); - let { - duration = defaultOptions.duration || _utils.defaults.duration, - easing = defaultOptions.easing || _utils.defaults.easing - } = valueOptions; - if ((0, _utils.isEasingGenerator)(easing)) { - const valueIsTransform = (0, _transformsEs.isTransform)(key); - (0, _heyListen.invariant)(valueKeyframes.length === 2 || !valueIsTransform, "spring must be provided 2 keyframes within timeline"); - const custom = easing.createAnimation(valueKeyframes, - // TODO We currently only support explicit keyframes - // so this doesn't currently read from the DOM - () => "0", valueIsTransform); - easing = custom.easing; - if (custom.keyframes !== undefined) valueKeyframes = custom.keyframes; - if (custom.duration !== undefined) duration = custom.duration; - } - const delay = (0, _staggerEs.resolveOption)(options.delay, elementIndex, numElements) || 0; - const startTime = currentTime + delay; - const targetTime = startTime + duration; - /** - * - */ - let { - offset = (0, _utils.defaultOffset)(valueKeyframes.length) - } = valueOptions; - /** - * If there's only one offset of 0, fill in a second with length 1 - * - * TODO: Ensure there's a test that covers this removal - */ - if (offset.length === 1 && offset[0] === 0) { - offset[1] = 1; - } - /** - * Fill out if offset if fewer offsets than keyframes - */ - const remainder = length - valueKeyframes.length; - remainder > 0 && (0, _utils.fillOffset)(offset, remainder); - /** - * If only one value has been set, ie [1], push a null to the start of - * the keyframe array. This will let us mark a keyframe at this point - * that will later be hydrated with the previous value. - */ - valueKeyframes.length === 1 && valueKeyframes.unshift(null); - /** - * Add keyframes, mapping offsets to absolute time. - */ - (0, _editEs.addKeyframes)(valueSequence, valueKeyframes, easing, offset, startTime, targetTime); - maxDuration = Math.max(delay + duration, maxDuration); - totalDuration = Math.max(targetTime, totalDuration); - } - } - prevTime = currentTime; - currentTime += maxDuration; - } - /** - * For every element and value combination create a new animation. - */ - elementSequences.forEach((valueSequences, element) => { - for (const key in valueSequences) { - const valueSequence = valueSequences[key]; - /** - * Arrange all the keyframes in ascending time order. - */ - valueSequence.sort(_sortEs.compareByTime); - const keyframes = []; - const valueOffset = []; - const valueEasing = []; - /** - * For each keyframe, translate absolute times into - * relative offsets based on the total duration of the timeline. - */ - for (let i = 0; i < valueSequence.length; i++) { - const { - at, - value, - easing - } = valueSequence[i]; - keyframes.push(value); - valueOffset.push((0, _utils.progress)(0, totalDuration, at)); - valueEasing.push(easing || _utils.defaults.easing); - } - /** - * If the first keyframe doesn't land on offset: 0 - * provide one by duplicating the initial keyframe. This ensures - * it snaps to the first keyframe when the animation starts. - */ - if (valueOffset[0] !== 0) { - valueOffset.unshift(0); - keyframes.unshift(keyframes[0]); - valueEasing.unshift("linear"); - } - /** - * If the last keyframe doesn't land on offset: 1 - * provide one with a null wildcard value. This will ensure it - * stays static until the end of the animation. - */ - if (valueOffset[valueOffset.length - 1] !== 1) { - valueOffset.push(1); - keyframes.push(null); - } - animationDefinitions.push([element, key, keyframes, Object.assign(Object.assign(Object.assign({}, defaultOptions), { - duration: totalDuration, - easing: valueEasing, - offset: valueOffset - }), timelineOptions)]); - } - }); - return animationDefinitions; -} -function getElementSequence(element, sequences) { - !sequences.has(element) && sequences.set(element, {}); - return sequences.get(element); -} -function getValueSequence(name, sequences) { - if (!sequences[name]) sequences[name] = []; - return sequences[name]; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/timeline/utils/calc-time.es.js": -/*!********************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/timeline/utils/calc-time.es.js ***! - \********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.calcNextTime = calcNextTime; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -function calcNextTime(current, next, prev, labels) { - var _a; - if ((0, _utils.isNumber)(next)) { - return next; - } else if (next.startsWith("-") || next.startsWith("+")) { - return Math.max(0, current + parseFloat(next)); - } else if (next === "<") { - return prev; - } else { - return (_a = labels.get(next)) !== null && _a !== void 0 ? _a : current; - } -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/timeline/utils/edit.es.js": -/*!***************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/timeline/utils/edit.es.js ***! - \***************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.addKeyframes = addKeyframes; -exports.eraseKeyframes = eraseKeyframes; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -function eraseKeyframes(sequence, startTime, endTime) { - for (let i = 0; i < sequence.length; i++) { - const keyframe = sequence[i]; - if (keyframe.at > startTime && keyframe.at < endTime) { - (0, _utils.removeItem)(sequence, keyframe); - // If we remove this item we have to push the pointer back one - i--; - } - } -} -function addKeyframes(sequence, keyframes, easing, offset, startTime, endTime) { - /** - * Erase every existing value between currentTime and targetTime, - * this will essentially splice this timeline into any currently - * defined ones. - */ - eraseKeyframes(sequence, startTime, endTime); - for (let i = 0; i < keyframes.length; i++) { - sequence.push({ - value: keyframes[i], - at: (0, _utils.mix)(startTime, endTime, offset[i]), - easing: (0, _utils.getEasingForSegment)(easing, i) - }); - } -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/timeline/utils/sort.es.js": -/*!***************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/timeline/utils/sort.es.js ***! - \***************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.compareByTime = compareByTime; -function compareByTime(a, b) { - if (a.at === b.at) { - return a.value === null ? 1 : -1; - } else { - return a.at - b.at; - } -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js": -/*!******************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js ***! - \******************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.resolveElements = resolveElements; -function resolveElements(elements, selectorCache) { - var _a; - if (typeof elements === "string") { - if (selectorCache) { - (_a = selectorCache[elements]) !== null && _a !== void 0 ? _a : selectorCache[elements] = document.querySelectorAll(elements); - elements = selectorCache[elements]; - } else { - elements = document.querySelectorAll(elements); - } - } else if (elements instanceof Element) { - elements = [elements]; - } - /** - * Return an empty array - */ - return Array.from(elements || []); -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/utils/stagger.es.js": -/*!*********************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/utils/stagger.es.js ***! - \*********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getFromIndex = getFromIndex; -exports.resolveOption = resolveOption; -exports.stagger = stagger; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -var _animation = __webpack_require__(/*! @motionone/animation */ "../../../node_modules/@motionone/animation/dist/index.es.js"); -function stagger(duration = 0.1, { - start = 0, - from = 0, - easing -} = {}) { - return (i, total) => { - const fromIndex = (0, _utils.isNumber)(from) ? from : getFromIndex(from, total); - const distance = Math.abs(fromIndex - i); - let delay = duration * distance; - if (easing) { - const maxDelay = total * duration; - const easingFunction = (0, _animation.getEasingFunction)(easing); - delay = easingFunction(delay / maxDelay) * maxDelay; - } - return start + delay; - }; -} -function getFromIndex(from, total) { - if (from === "first") { - return 0; - } else { - const lastIndex = total - 1; - return from === "last" ? lastIndex : lastIndex / 2; - } -} -function resolveOption(option, i, total) { - return typeof option === "function" ? option(i, total) : option; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/easing/dist/cubic-bezier.es.js": -/*!***********************************************************************!*\ - !*** ../../../node_modules/@motionone/easing/dist/cubic-bezier.es.js ***! - \***********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.cubicBezier = cubicBezier; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -/* - Bezier function generator - - This has been modified from Gaëtan Renaudeau's BezierEasing - https://github.com/gre/bezier-easing/blob/master/src/index.js - https://github.com/gre/bezier-easing/blob/master/LICENSE - - I've removed the newtonRaphsonIterate algo because in benchmarking it - wasn't noticiably faster than binarySubdivision, indeed removing it - usually improved times, depending on the curve. - - I also removed the lookup table, as for the added bundle size and loop we're - only cutting ~4 or so subdivision iterations. I bumped the max iterations up - to 12 to compensate and this still tended to be faster for no perceivable - loss in accuracy. - - Usage - const easeOut = cubicBezier(.17,.67,.83,.67); - const x = easeOut(0.5); // returns 0.627... -*/ -// Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2. -const calcBezier = (t, a1, a2) => (((1.0 - 3.0 * a2 + 3.0 * a1) * t + (3.0 * a2 - 6.0 * a1)) * t + 3.0 * a1) * t; -const subdivisionPrecision = 0.0000001; -const subdivisionMaxIterations = 12; -function binarySubdivide(x, lowerBound, upperBound, mX1, mX2) { - let currentX; - let currentT; - let i = 0; - do { - currentT = lowerBound + (upperBound - lowerBound) / 2.0; - currentX = calcBezier(currentT, mX1, mX2) - x; - if (currentX > 0.0) { - upperBound = currentT; - } else { - lowerBound = currentT; - } - } while (Math.abs(currentX) > subdivisionPrecision && ++i < subdivisionMaxIterations); - return currentT; -} -function cubicBezier(mX1, mY1, mX2, mY2) { - // If this is a linear gradient, return linear easing - if (mX1 === mY1 && mX2 === mY2) return _utils.noopReturn; - const getTForX = aX => binarySubdivide(aX, 0, 1, mX1, mX2); - // If animation is at start/end, return t without easing - return t => t === 0 || t === 1 ? t : calcBezier(getTForX(t), mY1, mY2); -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/easing/dist/index.es.js": -/*!****************************************************************!*\ - !*** ../../../node_modules/@motionone/easing/dist/index.es.js ***! - \****************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "cubicBezier", ({ - enumerable: true, - get: function () { - return _cubicBezierEs.cubicBezier; - } -})); -Object.defineProperty(exports, "steps", ({ - enumerable: true, - get: function () { - return _stepsEs.steps; - } -})); -var _cubicBezierEs = __webpack_require__(/*! ./cubic-bezier.es.js */ "../../../node_modules/@motionone/easing/dist/cubic-bezier.es.js"); -var _stepsEs = __webpack_require__(/*! ./steps.es.js */ "../../../node_modules/@motionone/easing/dist/steps.es.js"); - -/***/ }), - -/***/ "../../../node_modules/@motionone/easing/dist/steps.es.js": -/*!****************************************************************!*\ - !*** ../../../node_modules/@motionone/easing/dist/steps.es.js ***! - \****************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.steps = void 0; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -const steps = (steps, direction = "end") => progress => { - progress = direction === "end" ? Math.min(progress, 0.999) : Math.max(progress, 0.001); - const expanded = progress * steps; - const rounded = direction === "end" ? Math.floor(expanded) : Math.ceil(expanded); - return (0, _utils.clamp)(0, 1, rounded / steps); -}; -exports.steps = steps; - -/***/ }), - -/***/ "../../../node_modules/@motionone/generators/dist/glide/index.es.js": -/*!**************************************************************************!*\ - !*** ../../../node_modules/@motionone/generators/dist/glide/index.es.js ***! - \**************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.glide = void 0; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -var _velocityEs = __webpack_require__(/*! ../utils/velocity.es.js */ "../../../node_modules/@motionone/generators/dist/utils/velocity.es.js"); -var _indexEs = __webpack_require__(/*! ../spring/index.es.js */ "../../../node_modules/@motionone/generators/dist/spring/index.es.js"); -const glide = ({ - from = 0, - velocity = 0.0, - power = 0.8, - decay = 0.325, - bounceDamping, - bounceStiffness, - changeTarget, - min, - max, - restDistance = 0.5, - restSpeed -}) => { - decay = _utils.time.ms(decay); - const state = { - hasReachedTarget: false, - done: false, - current: from, - target: from - }; - const isOutOfBounds = v => min !== undefined && v < min || max !== undefined && v > max; - const nearestBoundary = v => { - if (min === undefined) return max; - if (max === undefined) return min; - return Math.abs(min - v) < Math.abs(max - v) ? min : max; - }; - let amplitude = power * velocity; - const ideal = from + amplitude; - const target = changeTarget === undefined ? ideal : changeTarget(ideal); - state.target = target; - /** - * If the target has changed we need to re-calculate the amplitude, otherwise - * the animation will start from the wrong position. - */ - if (target !== ideal) amplitude = target - from; - const calcDelta = t => -amplitude * Math.exp(-t / decay); - const calcLatest = t => target + calcDelta(t); - const applyFriction = t => { - const delta = calcDelta(t); - const latest = calcLatest(t); - state.done = Math.abs(delta) <= restDistance; - state.current = state.done ? target : latest; - }; - /** - * Ideally this would resolve for t in a stateless way, we could - * do that by always precalculating the animation but as we know - * this will be done anyway we can assume that spring will - * be discovered during that. - */ - let timeReachedBoundary; - let spring$1; - const checkCatchBoundary = t => { - if (!isOutOfBounds(state.current)) return; - timeReachedBoundary = t; - spring$1 = (0, _indexEs.spring)({ - from: state.current, - to: nearestBoundary(state.current), - velocity: (0, _velocityEs.calcGeneratorVelocity)(calcLatest, t, state.current), - damping: bounceDamping, - stiffness: bounceStiffness, - restDistance, - restSpeed - }); - }; - checkCatchBoundary(0); - return t => { - /** - * We need to resolve the friction to figure out if we need a - * spring but we don't want to do this twice per frame. So here - * we flag if we updated for this frame and later if we did - * we can skip doing it again. - */ - let hasUpdatedFrame = false; - if (!spring$1 && timeReachedBoundary === undefined) { - hasUpdatedFrame = true; - applyFriction(t); - checkCatchBoundary(t); - } - /** - * If we have a spring and the provided t is beyond the moment the friction - * animation crossed the min/max boundary, use the spring. - */ - if (timeReachedBoundary !== undefined && t > timeReachedBoundary) { - state.hasReachedTarget = true; - return spring$1(t - timeReachedBoundary); - } else { - state.hasReachedTarget = false; - !hasUpdatedFrame && applyFriction(t); - return state; - } - }; -}; -exports.glide = glide; - -/***/ }), - -/***/ "../../../node_modules/@motionone/generators/dist/index.es.js": -/*!********************************************************************!*\ - !*** ../../../node_modules/@motionone/generators/dist/index.es.js ***! - \********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "calcGeneratorVelocity", ({ - enumerable: true, - get: function () { - return _velocityEs.calcGeneratorVelocity; - } -})); -Object.defineProperty(exports, "glide", ({ - enumerable: true, - get: function () { - return _indexEs.glide; - } -})); -Object.defineProperty(exports, "pregenerateKeyframes", ({ - enumerable: true, - get: function () { - return _pregenerateKeyframesEs.pregenerateKeyframes; - } -})); -Object.defineProperty(exports, "spring", ({ - enumerable: true, - get: function () { - return _indexEs2.spring; - } -})); -var _indexEs = __webpack_require__(/*! ./glide/index.es.js */ "../../../node_modules/@motionone/generators/dist/glide/index.es.js"); -var _indexEs2 = __webpack_require__(/*! ./spring/index.es.js */ "../../../node_modules/@motionone/generators/dist/spring/index.es.js"); -var _pregenerateKeyframesEs = __webpack_require__(/*! ./utils/pregenerate-keyframes.es.js */ "../../../node_modules/@motionone/generators/dist/utils/pregenerate-keyframes.es.js"); -var _velocityEs = __webpack_require__(/*! ./utils/velocity.es.js */ "../../../node_modules/@motionone/generators/dist/utils/velocity.es.js"); - -/***/ }), - -/***/ "../../../node_modules/@motionone/generators/dist/spring/defaults.es.js": -/*!******************************************************************************!*\ - !*** ../../../node_modules/@motionone/generators/dist/spring/defaults.es.js ***! - \******************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.defaults = void 0; -const defaults = exports.defaults = { - stiffness: 100.0, - damping: 10.0, - mass: 1.0 -}; - -/***/ }), - -/***/ "../../../node_modules/@motionone/generators/dist/spring/index.es.js": -/*!***************************************************************************!*\ - !*** ../../../node_modules/@motionone/generators/dist/spring/index.es.js ***! - \***************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.spring = void 0; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -var _defaultsEs = __webpack_require__(/*! ./defaults.es.js */ "../../../node_modules/@motionone/generators/dist/spring/defaults.es.js"); -var _utilsEs = __webpack_require__(/*! ./utils.es.js */ "../../../node_modules/@motionone/generators/dist/spring/utils.es.js"); -var _hasReachedTargetEs = __webpack_require__(/*! ../utils/has-reached-target.es.js */ "../../../node_modules/@motionone/generators/dist/utils/has-reached-target.es.js"); -var _velocityEs = __webpack_require__(/*! ../utils/velocity.es.js */ "../../../node_modules/@motionone/generators/dist/utils/velocity.es.js"); -const spring = ({ - stiffness = _defaultsEs.defaults.stiffness, - damping = _defaultsEs.defaults.damping, - mass = _defaultsEs.defaults.mass, - from = 0, - to = 1, - velocity = 0.0, - restSpeed = 2, - restDistance = 0.5 -} = {}) => { - velocity = velocity ? _utils.time.s(velocity) : 0.0; - const state = { - done: false, - hasReachedTarget: false, - current: from, - target: to - }; - const initialDelta = to - from; - const undampedAngularFreq = Math.sqrt(stiffness / mass) / 1000; - const dampingRatio = (0, _utilsEs.calcDampingRatio)(stiffness, damping, mass); - let resolveSpring; - if (dampingRatio < 1) { - const angularFreq = undampedAngularFreq * Math.sqrt(1 - dampingRatio * dampingRatio); - // Underdamped spring (bouncy) - resolveSpring = t => to - Math.exp(-dampingRatio * undampedAngularFreq * t) * ((-velocity + dampingRatio * undampedAngularFreq * initialDelta) / angularFreq * Math.sin(angularFreq * t) + initialDelta * Math.cos(angularFreq * t)); - } else { - // Critically damped spring - resolveSpring = t => { - return to - Math.exp(-undampedAngularFreq * t) * (initialDelta + (-velocity + undampedAngularFreq * initialDelta) * t); - }; - } - return t => { - state.current = resolveSpring(t); - const currentVelocity = t === 0 ? velocity : (0, _velocityEs.calcGeneratorVelocity)(resolveSpring, t, state.current); - const isBelowVelocityThreshold = Math.abs(currentVelocity) <= restSpeed; - const isBelowDisplacementThreshold = Math.abs(to - state.current) <= restDistance; - state.done = isBelowVelocityThreshold && isBelowDisplacementThreshold; - state.hasReachedTarget = (0, _hasReachedTargetEs.hasReachedTarget)(from, to, state.current); - return state; - }; -}; -exports.spring = spring; - -/***/ }), - -/***/ "../../../node_modules/@motionone/generators/dist/spring/utils.es.js": -/*!***************************************************************************!*\ - !*** ../../../node_modules/@motionone/generators/dist/spring/utils.es.js ***! - \***************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.calcDampingRatio = void 0; -var _defaultsEs = __webpack_require__(/*! ./defaults.es.js */ "../../../node_modules/@motionone/generators/dist/spring/defaults.es.js"); -const calcDampingRatio = (stiffness = _defaultsEs.defaults.stiffness, damping = _defaultsEs.defaults.damping, mass = _defaultsEs.defaults.mass) => damping / (2 * Math.sqrt(stiffness * mass)); -exports.calcDampingRatio = calcDampingRatio; - -/***/ }), - -/***/ "../../../node_modules/@motionone/generators/dist/utils/has-reached-target.es.js": -/*!***************************************************************************************!*\ - !*** ../../../node_modules/@motionone/generators/dist/utils/has-reached-target.es.js ***! - \***************************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.hasReachedTarget = hasReachedTarget; -function hasReachedTarget(origin, target, current) { - return origin < target && current >= target || origin > target && current <= target; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/generators/dist/utils/pregenerate-keyframes.es.js": -/*!******************************************************************************************!*\ - !*** ../../../node_modules/@motionone/generators/dist/utils/pregenerate-keyframes.es.js ***! - \******************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.pregenerateKeyframes = pregenerateKeyframes; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -const timeStep = 10; -const maxDuration = 10000; -function pregenerateKeyframes(generator, toUnit = _utils.noopReturn) { - let overshootDuration = undefined; - let timestamp = timeStep; - let state = generator(0); - const keyframes = [toUnit(state.current)]; - while (!state.done && timestamp < maxDuration) { - state = generator(timestamp); - keyframes.push(toUnit(state.done ? state.target : state.current)); - if (overshootDuration === undefined && state.hasReachedTarget) { - overshootDuration = timestamp; - } - timestamp += timeStep; - } - const duration = timestamp - timeStep; - /** - * If generating an animation that didn't actually move, - * generate a second keyframe so we have an origin and target. - */ - if (keyframes.length === 1) keyframes.push(state.current); - return { - keyframes, - duration: duration / 1000, - overshootDuration: (overshootDuration !== null && overshootDuration !== void 0 ? overshootDuration : duration) / 1000 - }; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/generators/dist/utils/velocity.es.js": -/*!*****************************************************************************!*\ - !*** ../../../node_modules/@motionone/generators/dist/utils/velocity.es.js ***! - \*****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.calcGeneratorVelocity = calcGeneratorVelocity; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -const sampleT = 5; // ms -function calcGeneratorVelocity(resolveValue, t, current) { - const prevT = Math.max(t - sampleT, 0); - return (0, _utils.velocityPerSecond)(current - resolveValue(prevT), t - prevT); -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/types/dist/MotionValue.es.js": -/*!*********************************************************************!*\ - !*** ../../../node_modules/@motionone/types/dist/MotionValue.es.js ***! - \*********************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.MotionValue = void 0; -/** - * The MotionValue tracks the state of a single animatable - * value. Currently, updatedAt and current are unused. The - * long term idea is to use this to minimise the number - * of DOM reads, and to abstract the DOM interactions here. - */ -class MotionValue { - setAnimation(animation) { - this.animation = animation; - animation === null || animation === void 0 ? void 0 : animation.finished.then(() => this.clearAnimation()).catch(() => {}); - } - clearAnimation() { - this.animation = this.generator = undefined; - } -} -exports.MotionValue = MotionValue; - -/***/ }), - -/***/ "../../../node_modules/@motionone/types/dist/index.es.js": -/*!***************************************************************!*\ - !*** ../../../node_modules/@motionone/types/dist/index.es.js ***! - \***************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "MotionValue", ({ - enumerable: true, - get: function () { - return _MotionValueEs.MotionValue; - } -})); -var _MotionValueEs = __webpack_require__(/*! ./MotionValue.es.js */ "../../../node_modules/@motionone/types/dist/MotionValue.es.js"); - -/***/ }), - -/***/ "../../../node_modules/@motionone/utils/dist/array.es.js": -/*!***************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/array.es.js ***! - \***************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.addUniqueItem = addUniqueItem; -exports.removeItem = removeItem; -function addUniqueItem(array, item) { - array.indexOf(item) === -1 && array.push(item); -} -function removeItem(arr, item) { - const index = arr.indexOf(item); - index > -1 && arr.splice(index, 1); -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/utils/dist/clamp.es.js": -/*!***************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/clamp.es.js ***! - \***************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.clamp = void 0; -const clamp = (min, max, v) => Math.min(Math.max(v, min), max); -exports.clamp = clamp; - -/***/ }), - -/***/ "../../../node_modules/@motionone/utils/dist/defaults.es.js": -/*!******************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/defaults.es.js ***! - \******************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.defaults = void 0; -const defaults = exports.defaults = { - duration: 0.3, - delay: 0, - endDelay: 0, - repeat: 0, - easing: "ease" -}; - -/***/ }), - -/***/ "../../../node_modules/@motionone/utils/dist/easing.es.js": -/*!****************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/easing.es.js ***! - \****************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getEasingForSegment = getEasingForSegment; -var _isEasingListEs = __webpack_require__(/*! ./is-easing-list.es.js */ "../../../node_modules/@motionone/utils/dist/is-easing-list.es.js"); -var _wrapEs = __webpack_require__(/*! ./wrap.es.js */ "../../../node_modules/@motionone/utils/dist/wrap.es.js"); -function getEasingForSegment(easing, i) { - return (0, _isEasingListEs.isEasingList)(easing) ? easing[(0, _wrapEs.wrap)(0, easing.length, i)] : easing; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/utils/dist/index.es.js": -/*!***************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/index.es.js ***! - \***************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "addUniqueItem", ({ - enumerable: true, - get: function () { - return _arrayEs.addUniqueItem; - } -})); -Object.defineProperty(exports, "clamp", ({ - enumerable: true, - get: function () { - return _clampEs.clamp; - } -})); -Object.defineProperty(exports, "defaultOffset", ({ - enumerable: true, - get: function () { - return _offsetEs.defaultOffset; - } -})); -Object.defineProperty(exports, "defaults", ({ - enumerable: true, - get: function () { - return _defaultsEs.defaults; - } -})); -Object.defineProperty(exports, "fillOffset", ({ - enumerable: true, - get: function () { - return _offsetEs.fillOffset; - } -})); -Object.defineProperty(exports, "getEasingForSegment", ({ - enumerable: true, - get: function () { - return _easingEs.getEasingForSegment; - } -})); -Object.defineProperty(exports, "interpolate", ({ - enumerable: true, - get: function () { - return _interpolateEs.interpolate; - } -})); -Object.defineProperty(exports, "isCubicBezier", ({ - enumerable: true, - get: function () { - return _isCubicBezierEs.isCubicBezier; - } -})); -Object.defineProperty(exports, "isEasingGenerator", ({ - enumerable: true, - get: function () { - return _isEasingGeneratorEs.isEasingGenerator; - } -})); -Object.defineProperty(exports, "isEasingList", ({ - enumerable: true, - get: function () { - return _isEasingListEs.isEasingList; - } -})); -Object.defineProperty(exports, "isFunction", ({ - enumerable: true, - get: function () { - return _isFunctionEs.isFunction; - } -})); -Object.defineProperty(exports, "isNumber", ({ - enumerable: true, - get: function () { - return _isNumberEs.isNumber; - } -})); -Object.defineProperty(exports, "isString", ({ - enumerable: true, - get: function () { - return _isStringEs.isString; - } -})); -Object.defineProperty(exports, "mix", ({ - enumerable: true, - get: function () { - return _mixEs.mix; - } -})); -Object.defineProperty(exports, "noop", ({ - enumerable: true, - get: function () { - return _noopEs.noop; - } -})); -Object.defineProperty(exports, "noopReturn", ({ - enumerable: true, - get: function () { - return _noopEs.noopReturn; - } -})); -Object.defineProperty(exports, "progress", ({ - enumerable: true, - get: function () { - return _progressEs.progress; - } -})); -Object.defineProperty(exports, "removeItem", ({ - enumerable: true, - get: function () { - return _arrayEs.removeItem; - } -})); -Object.defineProperty(exports, "time", ({ - enumerable: true, - get: function () { - return _timeEs.time; - } -})); -Object.defineProperty(exports, "velocityPerSecond", ({ - enumerable: true, - get: function () { - return _velocityEs.velocityPerSecond; - } -})); -Object.defineProperty(exports, "wrap", ({ - enumerable: true, - get: function () { - return _wrapEs.wrap; - } -})); -var _arrayEs = __webpack_require__(/*! ./array.es.js */ "../../../node_modules/@motionone/utils/dist/array.es.js"); -var _clampEs = __webpack_require__(/*! ./clamp.es.js */ "../../../node_modules/@motionone/utils/dist/clamp.es.js"); -var _defaultsEs = __webpack_require__(/*! ./defaults.es.js */ "../../../node_modules/@motionone/utils/dist/defaults.es.js"); -var _easingEs = __webpack_require__(/*! ./easing.es.js */ "../../../node_modules/@motionone/utils/dist/easing.es.js"); -var _interpolateEs = __webpack_require__(/*! ./interpolate.es.js */ "../../../node_modules/@motionone/utils/dist/interpolate.es.js"); -var _isCubicBezierEs = __webpack_require__(/*! ./is-cubic-bezier.es.js */ "../../../node_modules/@motionone/utils/dist/is-cubic-bezier.es.js"); -var _isEasingGeneratorEs = __webpack_require__(/*! ./is-easing-generator.es.js */ "../../../node_modules/@motionone/utils/dist/is-easing-generator.es.js"); -var _isEasingListEs = __webpack_require__(/*! ./is-easing-list.es.js */ "../../../node_modules/@motionone/utils/dist/is-easing-list.es.js"); -var _isFunctionEs = __webpack_require__(/*! ./is-function.es.js */ "../../../node_modules/@motionone/utils/dist/is-function.es.js"); -var _isNumberEs = __webpack_require__(/*! ./is-number.es.js */ "../../../node_modules/@motionone/utils/dist/is-number.es.js"); -var _isStringEs = __webpack_require__(/*! ./is-string.es.js */ "../../../node_modules/@motionone/utils/dist/is-string.es.js"); -var _mixEs = __webpack_require__(/*! ./mix.es.js */ "../../../node_modules/@motionone/utils/dist/mix.es.js"); -var _noopEs = __webpack_require__(/*! ./noop.es.js */ "../../../node_modules/@motionone/utils/dist/noop.es.js"); -var _offsetEs = __webpack_require__(/*! ./offset.es.js */ "../../../node_modules/@motionone/utils/dist/offset.es.js"); -var _progressEs = __webpack_require__(/*! ./progress.es.js */ "../../../node_modules/@motionone/utils/dist/progress.es.js"); -var _timeEs = __webpack_require__(/*! ./time.es.js */ "../../../node_modules/@motionone/utils/dist/time.es.js"); -var _velocityEs = __webpack_require__(/*! ./velocity.es.js */ "../../../node_modules/@motionone/utils/dist/velocity.es.js"); -var _wrapEs = __webpack_require__(/*! ./wrap.es.js */ "../../../node_modules/@motionone/utils/dist/wrap.es.js"); - -/***/ }), - -/***/ "../../../node_modules/@motionone/utils/dist/interpolate.es.js": -/*!*********************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/interpolate.es.js ***! - \*********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.interpolate = interpolate; -var _mixEs = __webpack_require__(/*! ./mix.es.js */ "../../../node_modules/@motionone/utils/dist/mix.es.js"); -var _noopEs = __webpack_require__(/*! ./noop.es.js */ "../../../node_modules/@motionone/utils/dist/noop.es.js"); -var _offsetEs = __webpack_require__(/*! ./offset.es.js */ "../../../node_modules/@motionone/utils/dist/offset.es.js"); -var _progressEs = __webpack_require__(/*! ./progress.es.js */ "../../../node_modules/@motionone/utils/dist/progress.es.js"); -var _easingEs = __webpack_require__(/*! ./easing.es.js */ "../../../node_modules/@motionone/utils/dist/easing.es.js"); -var _clampEs = __webpack_require__(/*! ./clamp.es.js */ "../../../node_modules/@motionone/utils/dist/clamp.es.js"); -function interpolate(output, input = (0, _offsetEs.defaultOffset)(output.length), easing = _noopEs.noopReturn) { - const length = output.length; - /** - * If the input length is lower than the output we - * fill the input to match. This currently assumes the input - * is an animation progress value so is a good candidate for - * moving outside the function. - */ - const remainder = length - input.length; - remainder > 0 && (0, _offsetEs.fillOffset)(input, remainder); - return t => { - let i = 0; - for (; i < length - 2; i++) { - if (t < input[i + 1]) break; - } - let progressInRange = (0, _clampEs.clamp)(0, 1, (0, _progressEs.progress)(input[i], input[i + 1], t)); - const segmentEasing = (0, _easingEs.getEasingForSegment)(easing, i); - progressInRange = segmentEasing(progressInRange); - return (0, _mixEs.mix)(output[i], output[i + 1], progressInRange); - }; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/utils/dist/is-cubic-bezier.es.js": -/*!*************************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/is-cubic-bezier.es.js ***! - \*************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isCubicBezier = void 0; -var _isNumberEs = __webpack_require__(/*! ./is-number.es.js */ "../../../node_modules/@motionone/utils/dist/is-number.es.js"); -const isCubicBezier = easing => Array.isArray(easing) && (0, _isNumberEs.isNumber)(easing[0]); -exports.isCubicBezier = isCubicBezier; - -/***/ }), - -/***/ "../../../node_modules/@motionone/utils/dist/is-easing-generator.es.js": -/*!*****************************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/is-easing-generator.es.js ***! - \*****************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isEasingGenerator = void 0; -const isEasingGenerator = easing => typeof easing === "object" && Boolean(easing.createAnimation); -exports.isEasingGenerator = isEasingGenerator; - -/***/ }), - -/***/ "../../../node_modules/@motionone/utils/dist/is-easing-list.es.js": -/*!************************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/is-easing-list.es.js ***! - \************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isEasingList = void 0; -var _isNumberEs = __webpack_require__(/*! ./is-number.es.js */ "../../../node_modules/@motionone/utils/dist/is-number.es.js"); -const isEasingList = easing => Array.isArray(easing) && !(0, _isNumberEs.isNumber)(easing[0]); -exports.isEasingList = isEasingList; - -/***/ }), - -/***/ "../../../node_modules/@motionone/utils/dist/is-function.es.js": -/*!*********************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/is-function.es.js ***! - \*********************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isFunction = void 0; -const isFunction = value => typeof value === "function"; -exports.isFunction = isFunction; - -/***/ }), - -/***/ "../../../node_modules/@motionone/utils/dist/is-number.es.js": -/*!*******************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/is-number.es.js ***! - \*******************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isNumber = void 0; -const isNumber = value => typeof value === "number"; -exports.isNumber = isNumber; - -/***/ }), - -/***/ "../../../node_modules/@motionone/utils/dist/is-string.es.js": -/*!*******************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/is-string.es.js ***! - \*******************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isString = void 0; -const isString = value => typeof value === "string"; -exports.isString = isString; - -/***/ }), - -/***/ "../../../node_modules/@motionone/utils/dist/mix.es.js": -/*!*************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/mix.es.js ***! - \*************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.mix = void 0; -const mix = (min, max, progress) => -progress * min + progress * max + min; -exports.mix = mix; - -/***/ }), - -/***/ "../../../node_modules/@motionone/utils/dist/noop.es.js": -/*!**************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/noop.es.js ***! - \**************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.noopReturn = exports.noop = void 0; -const noop = () => {}; -exports.noop = noop; -const noopReturn = v => v; -exports.noopReturn = noopReturn; - -/***/ }), - -/***/ "../../../node_modules/@motionone/utils/dist/offset.es.js": -/*!****************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/offset.es.js ***! - \****************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.defaultOffset = defaultOffset; -exports.fillOffset = fillOffset; -var _mixEs = __webpack_require__(/*! ./mix.es.js */ "../../../node_modules/@motionone/utils/dist/mix.es.js"); -var _progressEs = __webpack_require__(/*! ./progress.es.js */ "../../../node_modules/@motionone/utils/dist/progress.es.js"); -function fillOffset(offset, remaining) { - const min = offset[offset.length - 1]; - for (let i = 1; i <= remaining; i++) { - const offsetProgress = (0, _progressEs.progress)(0, remaining, i); - offset.push((0, _mixEs.mix)(min, 1, offsetProgress)); - } -} -function defaultOffset(length) { - const offset = [0]; - fillOffset(offset, length - 1); - return offset; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/utils/dist/progress.es.js": -/*!******************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/progress.es.js ***! - \******************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.progress = void 0; -const progress = (min, max, value) => max - min === 0 ? 1 : (value - min) / (max - min); -exports.progress = progress; - -/***/ }), - -/***/ "../../../node_modules/@motionone/utils/dist/time.es.js": -/*!**************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/time.es.js ***! - \**************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.time = void 0; -const time = exports.time = { - ms: seconds => seconds * 1000, - s: milliseconds => milliseconds / 1000 -}; - -/***/ }), - -/***/ "../../../node_modules/@motionone/utils/dist/velocity.es.js": -/*!******************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/velocity.es.js ***! - \******************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.velocityPerSecond = velocityPerSecond; -/* - Convert velocity into velocity per second - - @param [number]: Unit per frame - @param [number]: Frame duration in ms -*/ -function velocityPerSecond(velocity, frameDuration) { - return frameDuration ? velocity * (1000 / frameDuration) : 0; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/utils/dist/wrap.es.js": -/*!**************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/wrap.es.js ***! - \**************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.wrap = void 0; -const wrap = (min, max, v) => { - const rangeSize = max - min; - return ((v - min) % rangeSize + rangeSize) % rangeSize + min; -}; -exports.wrap = wrap; - -/***/ }), - -/***/ "../../../node_modules/@n1ru4l/push-pull-async-iterable-iterator/index.js": -/*!********************************************************************************!*\ - !*** ../../../node_modules/@n1ru4l/push-pull-async-iterable-iterator/index.js ***! - \********************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -function createDeferred() { - const d = {}; - d.promise = new Promise((resolve, reject) => { - d.resolve = resolve; - d.reject = reject; - }); - return d; -} -const SYMBOL_FINISHED = Symbol(); -const SYMBOL_NEW_VALUE = Symbol(); -/** - * makePushPullAsyncIterableIterator - * - * The iterable will publish values until return or throw is called. - * Afterwards it is in the completed state and cannot be used for publishing any further values. - * It will handle back-pressure and keep pushed values until they are consumed by a source. - */ -function makePushPullAsyncIterableIterator() { - let isRunning = true; - const values = []; - let newValueD = createDeferred(); - const finishedD = createDeferred(); - const asyncIterableIterator = async function* PushPullAsyncIterableIterator() { - while (true) { - if (values.length > 0) { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - yield values.shift(); - } else { - const result = await Promise.race([newValueD.promise, finishedD.promise]); - if (result === SYMBOL_FINISHED) { - break; - } - if (result !== SYMBOL_NEW_VALUE) { - throw result; - } - } - } - }(); - function pushValue(value) { - if (isRunning === false) { - // TODO: Should this throw? - return; - } - values.push(value); - newValueD.resolve(SYMBOL_NEW_VALUE); - newValueD = createDeferred(); - } - // We monkey patch the original generator for clean-up - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const originalReturn = asyncIterableIterator.return.bind(asyncIterableIterator); - asyncIterableIterator.return = ( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - ...args) => { - isRunning = false; - finishedD.resolve(SYMBOL_FINISHED); - return originalReturn(...args); - }; - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const originalThrow = asyncIterableIterator.throw.bind(asyncIterableIterator); - asyncIterableIterator.throw = err => { - isRunning = false; - finishedD.resolve(err); - return originalThrow(err); - }; - return { - pushValue, - asyncIterableIterator - }; -} -const makeAsyncIterableIteratorFromSink = make => { - const { - pushValue, - asyncIterableIterator - } = makePushPullAsyncIterableIterator(); - const dispose = make({ - next: value => { - pushValue(value); - }, - complete: () => { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - asyncIterableIterator.return(); - }, - error: err => { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - asyncIterableIterator.throw(err); - } - }); - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const originalReturn = asyncIterableIterator.return; - let returnValue = undefined; - asyncIterableIterator.return = () => { - if (returnValue === undefined) { - dispose(); - returnValue = originalReturn(); - } - return returnValue; - }; - return asyncIterableIterator; -}; -function applyAsyncIterableIteratorToSink(asyncIterableIterator, sink) { - const run = async () => { - try { - for await (const value of asyncIterableIterator) { - sink.next(value); - } - sink.complete(); - } catch (err) { - sink.error(err); - } - }; - run(); - return () => { - var _a; - (_a = asyncIterableIterator.return) === null || _a === void 0 ? void 0 : _a.call(asyncIterableIterator); - }; -} -function isAsyncIterable(input) { - return typeof input === "object" && input !== null && ( - // The AsyncGenerator check is for Safari on iOS which currently does not have - // Symbol.asyncIterator implemented - // That means every custom AsyncIterable must be built using a AsyncGeneratorFunction (async function * () {}) - // eslint-disable-next-line @typescript-eslint/no-explicit-any - input[Symbol.toStringTag] === "AsyncGenerator" || Symbol.asyncIterator && Symbol.asyncIterator in input); -} -exports.applyAsyncIterableIteratorToSink = applyAsyncIterableIteratorToSink; -exports.isAsyncIterable = isAsyncIterable; -exports.makeAsyncIterableIteratorFromSink = makeAsyncIterableIteratorFromSink; -exports.makePushPullAsyncIterableIterator = makePushPullAsyncIterableIterator; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/primitive/dist/index.js": -/*!***************************************************************!*\ - !*** ../../../node_modules/@radix-ui/primitive/dist/index.js ***! - \***************************************************************/ -/***/ (function(module) { - -"use strict"; - - -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -$parcel$export(module.exports, "composeEventHandlers", () => $1a6a90a521dcd173$export$b9ecd428b558ff10); -function $1a6a90a521dcd173$export$b9ecd428b558ff10(originalEventHandler, ourEventHandler, { - checkForDefaultPrevented = true -} = {}) { - return function handleEvent(event) { - originalEventHandler === null || originalEventHandler === void 0 || originalEventHandler(event); - if (checkForDefaultPrevented === false || !event.defaultPrevented) return ourEventHandler === null || ourEventHandler === void 0 ? void 0 : ourEventHandler(event); - }; -} - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-arrow/dist/index.js": -/*!*****************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-arrow/dist/index.js ***! - \*****************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var $eQpDd$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); -var $eQpDd$react = __webpack_require__(/*! react */ "react"); -var $eQpDd$radixuireactprimitive = __webpack_require__(/*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "Arrow", () => $09f4ad68a9251bc3$export$21b07c8f274aebd5); -$parcel$export(module.exports, "Root", () => $09f4ad68a9251bc3$export$be92b6f5f03c0fe9); - -/* ------------------------------------------------------------------------------------------------- - * Arrow - * -----------------------------------------------------------------------------------------------*/ -const $09f4ad68a9251bc3$var$NAME = 'Arrow'; -const $09f4ad68a9251bc3$export$21b07c8f274aebd5 = /*#__PURE__*/$eQpDd$react.forwardRef((props, forwardedRef) => { - const { - children: children, - width = 10, - height = 5, - ...arrowProps - } = props; - return /*#__PURE__*/$eQpDd$react.createElement($eQpDd$radixuireactprimitive.Primitive.svg, $parcel$interopDefault($eQpDd$babelruntimehelpersextends)({}, arrowProps, { - ref: forwardedRef, - width: width, - height: height, - viewBox: "0 0 30 10", - preserveAspectRatio: "none" - }), props.asChild ? children : /*#__PURE__*/$eQpDd$react.createElement("polygon", { - points: "0,0 30,0 15,10" - })); -}); -/*#__PURE__*/ -Object.assign($09f4ad68a9251bc3$export$21b07c8f274aebd5, { - displayName: $09f4ad68a9251bc3$var$NAME -}); -/* -----------------------------------------------------------------------------------------------*/ -const $09f4ad68a9251bc3$export$be92b6f5f03c0fe9 = $09f4ad68a9251bc3$export$21b07c8f274aebd5; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-collection/dist/index.js": -/*!**********************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-collection/dist/index.js ***! - \**********************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var $hnlpS$react = __webpack_require__(/*! react */ "react"); -var $hnlpS$radixuireactcontext = __webpack_require__(/*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js"); -var $hnlpS$radixuireactcomposerefs = __webpack_require__(/*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js"); -var $hnlpS$radixuireactslot = __webpack_require__(/*! @radix-ui/react-slot */ "../../../node_modules/@radix-ui/react-slot/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "createCollection", () => $1a96635ec239608b$export$c74125a8e3af6bb2); - -// We have resorted to returning slots directly rather than exposing primitives that can then -// be slotted like ``. -// This is because we encountered issues with generic types that cannot be statically analysed -// due to creating them dynamically via createCollection. -function $1a96635ec239608b$export$c74125a8e3af6bb2(name) { - /* ----------------------------------------------------------------------------------------------- - * CollectionProvider - * ---------------------------------------------------------------------------------------------*/ - const PROVIDER_NAME = name + 'CollectionProvider'; - const [createCollectionContext, createCollectionScope] = $hnlpS$radixuireactcontext.createContextScope(PROVIDER_NAME); - const [CollectionProviderImpl, useCollectionContext] = createCollectionContext(PROVIDER_NAME, { - collectionRef: { - current: null - }, - itemMap: new Map() - }); - const CollectionProvider = props => { - const { - scope: scope, - children: children - } = props; - const ref = $parcel$interopDefault($hnlpS$react).useRef(null); - const itemMap = $parcel$interopDefault($hnlpS$react).useRef(new Map()).current; - return /*#__PURE__*/$parcel$interopDefault($hnlpS$react).createElement(CollectionProviderImpl, { - scope: scope, - itemMap: itemMap, - collectionRef: ref - }, children); - }; - /*#__PURE__*/ - Object.assign(CollectionProvider, { - displayName: PROVIDER_NAME - }); - /* ----------------------------------------------------------------------------------------------- - * CollectionSlot - * ---------------------------------------------------------------------------------------------*/ - const COLLECTION_SLOT_NAME = name + 'CollectionSlot'; - const CollectionSlot = /*#__PURE__*/$parcel$interopDefault($hnlpS$react).forwardRef((props, forwardedRef) => { - const { - scope: scope, - children: children - } = props; - const context = useCollectionContext(COLLECTION_SLOT_NAME, scope); - const composedRefs = $hnlpS$radixuireactcomposerefs.useComposedRefs(forwardedRef, context.collectionRef); - return /*#__PURE__*/$parcel$interopDefault($hnlpS$react).createElement($hnlpS$radixuireactslot.Slot, { - ref: composedRefs - }, children); - }); - /*#__PURE__*/ - Object.assign(CollectionSlot, { - displayName: COLLECTION_SLOT_NAME - }); - /* ----------------------------------------------------------------------------------------------- - * CollectionItem - * ---------------------------------------------------------------------------------------------*/ - const ITEM_SLOT_NAME = name + 'CollectionItemSlot'; - const ITEM_DATA_ATTR = 'data-radix-collection-item'; - const CollectionItemSlot = /*#__PURE__*/$parcel$interopDefault($hnlpS$react).forwardRef((props, forwardedRef) => { - const { - scope: scope, - children: children, - ...itemData - } = props; - const ref = $parcel$interopDefault($hnlpS$react).useRef(null); - const composedRefs = $hnlpS$radixuireactcomposerefs.useComposedRefs(forwardedRef, ref); - const context = useCollectionContext(ITEM_SLOT_NAME, scope); - $parcel$interopDefault($hnlpS$react).useEffect(() => { - context.itemMap.set(ref, { - ref: ref, - ...itemData - }); - return () => void context.itemMap.delete(ref); - }); - return /*#__PURE__*/$parcel$interopDefault($hnlpS$react).createElement($hnlpS$radixuireactslot.Slot, { - [ITEM_DATA_ATTR]: '', - ref: composedRefs - }, children); - }); - /*#__PURE__*/ - Object.assign(CollectionItemSlot, { - displayName: ITEM_SLOT_NAME - }); - /* ----------------------------------------------------------------------------------------------- - * useCollection - * ---------------------------------------------------------------------------------------------*/ - function useCollection(scope) { - const context = useCollectionContext(name + 'CollectionConsumer', scope); - const getItems = $parcel$interopDefault($hnlpS$react).useCallback(() => { - const collectionNode = context.collectionRef.current; - if (!collectionNode) return []; - const orderedNodes = Array.from(collectionNode.querySelectorAll(`[${ITEM_DATA_ATTR}]`)); - const items = Array.from(context.itemMap.values()); - const orderedItems = items.sort((a, b) => orderedNodes.indexOf(a.ref.current) - orderedNodes.indexOf(b.ref.current)); - return orderedItems; - }, [context.collectionRef, context.itemMap]); - return getItems; - } - return [{ - Provider: CollectionProvider, - Slot: CollectionSlot, - ItemSlot: CollectionItemSlot - }, useCollection, createCollectionScope]; -} - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js": -/*!************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-compose-refs/dist/index.js ***! - \************************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var $dJwbH$react = __webpack_require__(/*! react */ "react"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -$parcel$export(module.exports, "composeRefs", () => $9c2aaba23466b352$export$43e446d32b3d21af); -$parcel$export(module.exports, "useComposedRefs", () => $9c2aaba23466b352$export$c7b2cbe3552a0d05); - -/** - * Set a given ref to a given value - * This utility takes care of different types of refs: callback refs and RefObject(s) - */ -function $9c2aaba23466b352$var$setRef(ref, value) { - if (typeof ref === 'function') ref(value);else if (ref !== null && ref !== undefined) ref.current = value; -} -/** - * A utility to compose multiple refs together - * Accepts callback refs and RefObject(s) - */ -function $9c2aaba23466b352$export$43e446d32b3d21af(...refs) { - return node => refs.forEach(ref => $9c2aaba23466b352$var$setRef(ref, node)); -} -/** - * A custom hook that composes multiple refs - * Accepts callback refs and RefObject(s) - */ -function $9c2aaba23466b352$export$c7b2cbe3552a0d05(...refs) { - // eslint-disable-next-line react-hooks/exhaustive-deps - return $dJwbH$react.useCallback($9c2aaba23466b352$export$43e446d32b3d21af(...refs), refs); -} - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-context/dist/index.js": -/*!*******************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-context/dist/index.js ***! - \*******************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var $4O1Ne$react = __webpack_require__(/*! react */ "react"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -$parcel$export(module.exports, "createContext", () => $dec3cc0142d4f286$export$fd42f52fd3ae1109); -$parcel$export(module.exports, "createContextScope", () => $dec3cc0142d4f286$export$50c7b4e9d9f19c1); -function $dec3cc0142d4f286$export$fd42f52fd3ae1109(rootComponentName, defaultContext) { - const Context = /*#__PURE__*/$4O1Ne$react.createContext(defaultContext); - function Provider(props) { - const { - children: children, - ...context - } = props; // Only re-memoize when prop values change - // eslint-disable-next-line react-hooks/exhaustive-deps - const value = $4O1Ne$react.useMemo(() => context, Object.values(context)); - return /*#__PURE__*/$4O1Ne$react.createElement(Context.Provider, { - value: value - }, children); - } - function useContext(consumerName) { - const context = $4O1Ne$react.useContext(Context); - if (context) return context; - if (defaultContext !== undefined) return defaultContext; // if a defaultContext wasn't specified, it's a required context. - throw new Error(`\`${consumerName}\` must be used within \`${rootComponentName}\``); - } - Provider.displayName = rootComponentName + 'Provider'; - return [Provider, useContext]; -} -/* ------------------------------------------------------------------------------------------------- - * createContextScope - * -----------------------------------------------------------------------------------------------*/ -function $dec3cc0142d4f286$export$50c7b4e9d9f19c1(scopeName, createContextScopeDeps = []) { - let defaultContexts = []; - /* ----------------------------------------------------------------------------------------------- - * createContext - * ---------------------------------------------------------------------------------------------*/ - function $dec3cc0142d4f286$export$fd42f52fd3ae1109(rootComponentName, defaultContext) { - const BaseContext = /*#__PURE__*/$4O1Ne$react.createContext(defaultContext); - const index = defaultContexts.length; - defaultContexts = [...defaultContexts, defaultContext]; - function Provider(props) { - const { - scope: scope, - children: children, - ...context - } = props; - const Context = (scope === null || scope === void 0 ? void 0 : scope[scopeName][index]) || BaseContext; // Only re-memoize when prop values change - // eslint-disable-next-line react-hooks/exhaustive-deps - const value = $4O1Ne$react.useMemo(() => context, Object.values(context)); - return /*#__PURE__*/$4O1Ne$react.createElement(Context.Provider, { - value: value - }, children); - } - function useContext(consumerName, scope) { - const Context = (scope === null || scope === void 0 ? void 0 : scope[scopeName][index]) || BaseContext; - const context = $4O1Ne$react.useContext(Context); - if (context) return context; - if (defaultContext !== undefined) return defaultContext; // if a defaultContext wasn't specified, it's a required context. - throw new Error(`\`${consumerName}\` must be used within \`${rootComponentName}\``); - } - Provider.displayName = rootComponentName + 'Provider'; - return [Provider, useContext]; - } - /* ----------------------------------------------------------------------------------------------- - * createScope - * ---------------------------------------------------------------------------------------------*/ - const createScope = () => { - const scopeContexts = defaultContexts.map(defaultContext => { - return /*#__PURE__*/$4O1Ne$react.createContext(defaultContext); - }); - return function useScope(scope) { - const contexts = (scope === null || scope === void 0 ? void 0 : scope[scopeName]) || scopeContexts; - return $4O1Ne$react.useMemo(() => ({ - [`__scope${scopeName}`]: { - ...scope, - [scopeName]: contexts - } - }), [scope, contexts]); - }; - }; - createScope.scopeName = scopeName; - return [$dec3cc0142d4f286$export$fd42f52fd3ae1109, $dec3cc0142d4f286$var$composeContextScopes(createScope, ...createContextScopeDeps)]; -} -/* ------------------------------------------------------------------------------------------------- - * composeContextScopes - * -----------------------------------------------------------------------------------------------*/ -function $dec3cc0142d4f286$var$composeContextScopes(...scopes) { - const baseScope = scopes[0]; - if (scopes.length === 1) return baseScope; - const createScope1 = () => { - const scopeHooks = scopes.map(createScope => ({ - useScope: createScope(), - scopeName: createScope.scopeName - })); - return function useComposedScopes(overrideScopes) { - const nextScopes1 = scopeHooks.reduce((nextScopes, { - useScope: useScope, - scopeName: scopeName - }) => { - // We are calling a hook inside a callback which React warns against to avoid inconsistent - // renders, however, scoping doesn't have render side effects so we ignore the rule. - // eslint-disable-next-line react-hooks/rules-of-hooks - const scopeProps = useScope(overrideScopes); - const currentScope = scopeProps[`__scope${scopeName}`]; - return { - ...nextScopes, - ...currentScope - }; - }, {}); - return $4O1Ne$react.useMemo(() => ({ - [`__scope${baseScope.scopeName}`]: nextScopes1 - }), [nextScopes1]); - }; - }; - createScope1.scopeName = baseScope.scopeName; - return createScope1; -} - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-dialog/dist/index.js": -/*!******************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-dialog/dist/index.js ***! - \******************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var $aJCrN$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); -var $aJCrN$react = __webpack_require__(/*! react */ "react"); -var $aJCrN$radixuiprimitive = __webpack_require__(/*! @radix-ui/primitive */ "../../../node_modules/@radix-ui/primitive/dist/index.js"); -var $aJCrN$radixuireactcomposerefs = __webpack_require__(/*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js"); -var $aJCrN$radixuireactcontext = __webpack_require__(/*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js"); -var $aJCrN$radixuireactid = __webpack_require__(/*! @radix-ui/react-id */ "../../../node_modules/@radix-ui/react-id/dist/index.js"); -var $aJCrN$radixuireactusecontrollablestate = __webpack_require__(/*! @radix-ui/react-use-controllable-state */ "../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js"); -var $aJCrN$radixuireactdismissablelayer = __webpack_require__(/*! @radix-ui/react-dismissable-layer */ "../../../node_modules/@radix-ui/react-dismissable-layer/dist/index.js"); -var $aJCrN$radixuireactfocusscope = __webpack_require__(/*! @radix-ui/react-focus-scope */ "../../../node_modules/@radix-ui/react-focus-scope/dist/index.js"); -var $aJCrN$radixuireactportal = __webpack_require__(/*! @radix-ui/react-portal */ "../../../node_modules/@radix-ui/react-portal/dist/index.js"); -var $aJCrN$radixuireactpresence = __webpack_require__(/*! @radix-ui/react-presence */ "../../../node_modules/@radix-ui/react-presence/dist/index.js"); -var $aJCrN$radixuireactprimitive = __webpack_require__(/*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js"); -var $aJCrN$radixuireactfocusguards = __webpack_require__(/*! @radix-ui/react-focus-guards */ "../../../node_modules/@radix-ui/react-focus-guards/dist/index.js"); -var $aJCrN$reactremovescroll = __webpack_require__(/*! react-remove-scroll */ "../../../node_modules/react-remove-scroll/dist/es2015/index.js"); -var $aJCrN$ariahidden = __webpack_require__(/*! aria-hidden */ "../../../node_modules/aria-hidden/dist/es2015/index.js"); -var $aJCrN$radixuireactslot = __webpack_require__(/*! @radix-ui/react-slot */ "../../../node_modules/@radix-ui/react-slot/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "createDialogScope", () => $f4833395aa1bca1a$export$cc702773b8ea3e41); -$parcel$export(module.exports, "Dialog", () => $f4833395aa1bca1a$export$3ddf2d174ce01153); -$parcel$export(module.exports, "DialogTrigger", () => $f4833395aa1bca1a$export$2e1e1122cf0cba88); -$parcel$export(module.exports, "DialogPortal", () => $f4833395aa1bca1a$export$dad7c95542bacce0); -$parcel$export(module.exports, "DialogOverlay", () => $f4833395aa1bca1a$export$bd1d06c79be19e17); -$parcel$export(module.exports, "DialogContent", () => $f4833395aa1bca1a$export$b6d9565de1e068cf); -$parcel$export(module.exports, "DialogTitle", () => $f4833395aa1bca1a$export$16f7638e4a34b909); -$parcel$export(module.exports, "DialogDescription", () => $f4833395aa1bca1a$export$94e94c2ec2c954d5); -$parcel$export(module.exports, "DialogClose", () => $f4833395aa1bca1a$export$fba2fb7cd781b7ac); -$parcel$export(module.exports, "Root", () => $f4833395aa1bca1a$export$be92b6f5f03c0fe9); -$parcel$export(module.exports, "Trigger", () => $f4833395aa1bca1a$export$41fb9f06171c75f4); -$parcel$export(module.exports, "Portal", () => $f4833395aa1bca1a$export$602eac185826482c); -$parcel$export(module.exports, "Overlay", () => $f4833395aa1bca1a$export$c6fdb837b070b4ff); -$parcel$export(module.exports, "Content", () => $f4833395aa1bca1a$export$7c6e2c02157bb7d2); -$parcel$export(module.exports, "Title", () => $f4833395aa1bca1a$export$f99233281efd08a0); -$parcel$export(module.exports, "Description", () => $f4833395aa1bca1a$export$393edc798c47379d); -$parcel$export(module.exports, "Close", () => $f4833395aa1bca1a$export$f39c2d165cd861fe); -$parcel$export(module.exports, "WarningProvider", () => $f4833395aa1bca1a$export$69b62a49393917d6); - -/* ------------------------------------------------------------------------------------------------- - * Dialog - * -----------------------------------------------------------------------------------------------*/ -const $f4833395aa1bca1a$var$DIALOG_NAME = 'Dialog'; -const [$f4833395aa1bca1a$var$createDialogContext, $f4833395aa1bca1a$export$cc702773b8ea3e41] = $aJCrN$radixuireactcontext.createContextScope($f4833395aa1bca1a$var$DIALOG_NAME); -const [$f4833395aa1bca1a$var$DialogProvider, $f4833395aa1bca1a$var$useDialogContext] = $f4833395aa1bca1a$var$createDialogContext($f4833395aa1bca1a$var$DIALOG_NAME); -const $f4833395aa1bca1a$export$3ddf2d174ce01153 = props => { - const { - __scopeDialog: __scopeDialog, - children: children, - open: openProp, - defaultOpen: defaultOpen, - onOpenChange: onOpenChange, - modal = true - } = props; - const triggerRef = $aJCrN$react.useRef(null); - const contentRef = $aJCrN$react.useRef(null); - const [open = false, setOpen] = $aJCrN$radixuireactusecontrollablestate.useControllableState({ - prop: openProp, - defaultProp: defaultOpen, - onChange: onOpenChange - }); - return /*#__PURE__*/$aJCrN$react.createElement($f4833395aa1bca1a$var$DialogProvider, { - scope: __scopeDialog, - triggerRef: triggerRef, - contentRef: contentRef, - contentId: $aJCrN$radixuireactid.useId(), - titleId: $aJCrN$radixuireactid.useId(), - descriptionId: $aJCrN$radixuireactid.useId(), - open: open, - onOpenChange: setOpen, - onOpenToggle: $aJCrN$react.useCallback(() => setOpen(prevOpen => !prevOpen), [setOpen]), - modal: modal - }, children); -}; -/*#__PURE__*/ -Object.assign($f4833395aa1bca1a$export$3ddf2d174ce01153, { - displayName: $f4833395aa1bca1a$var$DIALOG_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DialogTrigger - * -----------------------------------------------------------------------------------------------*/ -const $f4833395aa1bca1a$var$TRIGGER_NAME = 'DialogTrigger'; -const $f4833395aa1bca1a$export$2e1e1122cf0cba88 = /*#__PURE__*/$aJCrN$react.forwardRef((props, forwardedRef) => { - const { - __scopeDialog: __scopeDialog, - ...triggerProps - } = props; - const context = $f4833395aa1bca1a$var$useDialogContext($f4833395aa1bca1a$var$TRIGGER_NAME, __scopeDialog); - const composedTriggerRef = $aJCrN$radixuireactcomposerefs.useComposedRefs(forwardedRef, context.triggerRef); - return /*#__PURE__*/$aJCrN$react.createElement($aJCrN$radixuireactprimitive.Primitive.button, $parcel$interopDefault($aJCrN$babelruntimehelpersextends)({ - type: "button", - "aria-haspopup": "dialog", - "aria-expanded": context.open, - "aria-controls": context.contentId, - "data-state": $f4833395aa1bca1a$var$getState(context.open) - }, triggerProps, { - ref: composedTriggerRef, - onClick: $aJCrN$radixuiprimitive.composeEventHandlers(props.onClick, context.onOpenToggle) - })); -}); -/*#__PURE__*/ -Object.assign($f4833395aa1bca1a$export$2e1e1122cf0cba88, { - displayName: $f4833395aa1bca1a$var$TRIGGER_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DialogPortal - * -----------------------------------------------------------------------------------------------*/ -const $f4833395aa1bca1a$var$PORTAL_NAME = 'DialogPortal'; -const [$f4833395aa1bca1a$var$PortalProvider, $f4833395aa1bca1a$var$usePortalContext] = $f4833395aa1bca1a$var$createDialogContext($f4833395aa1bca1a$var$PORTAL_NAME, { - forceMount: undefined -}); -const $f4833395aa1bca1a$export$dad7c95542bacce0 = props => { - const { - __scopeDialog: __scopeDialog, - forceMount: forceMount, - children: children, - container: container - } = props; - const context = $f4833395aa1bca1a$var$useDialogContext($f4833395aa1bca1a$var$PORTAL_NAME, __scopeDialog); - return /*#__PURE__*/$aJCrN$react.createElement($f4833395aa1bca1a$var$PortalProvider, { - scope: __scopeDialog, - forceMount: forceMount - }, $aJCrN$react.Children.map(children, child => /*#__PURE__*/$aJCrN$react.createElement($aJCrN$radixuireactpresence.Presence, { - present: forceMount || context.open - }, /*#__PURE__*/$aJCrN$react.createElement($aJCrN$radixuireactportal.Portal, { - asChild: true, - container: container - }, child)))); -}; -/*#__PURE__*/ -Object.assign($f4833395aa1bca1a$export$dad7c95542bacce0, { - displayName: $f4833395aa1bca1a$var$PORTAL_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DialogOverlay - * -----------------------------------------------------------------------------------------------*/ -const $f4833395aa1bca1a$var$OVERLAY_NAME = 'DialogOverlay'; -const $f4833395aa1bca1a$export$bd1d06c79be19e17 = /*#__PURE__*/$aJCrN$react.forwardRef((props, forwardedRef) => { - const portalContext = $f4833395aa1bca1a$var$usePortalContext($f4833395aa1bca1a$var$OVERLAY_NAME, props.__scopeDialog); - const { - forceMount = portalContext.forceMount, - ...overlayProps - } = props; - const context = $f4833395aa1bca1a$var$useDialogContext($f4833395aa1bca1a$var$OVERLAY_NAME, props.__scopeDialog); - return context.modal ? /*#__PURE__*/$aJCrN$react.createElement($aJCrN$radixuireactpresence.Presence, { - present: forceMount || context.open - }, /*#__PURE__*/$aJCrN$react.createElement($f4833395aa1bca1a$var$DialogOverlayImpl, $parcel$interopDefault($aJCrN$babelruntimehelpersextends)({}, overlayProps, { - ref: forwardedRef - }))) : null; -}); -/*#__PURE__*/ -Object.assign($f4833395aa1bca1a$export$bd1d06c79be19e17, { - displayName: $f4833395aa1bca1a$var$OVERLAY_NAME -}); -const $f4833395aa1bca1a$var$DialogOverlayImpl = /*#__PURE__*/$aJCrN$react.forwardRef((props, forwardedRef) => { - const { - __scopeDialog: __scopeDialog, - ...overlayProps - } = props; - const context = $f4833395aa1bca1a$var$useDialogContext($f4833395aa1bca1a$var$OVERLAY_NAME, __scopeDialog); - return /*#__PURE__*/ (// Make sure `Content` is scrollable even when it doesn't live inside `RemoveScroll` - // ie. when `Overlay` and `Content` are siblings - $aJCrN$react.createElement($aJCrN$reactremovescroll.RemoveScroll, { - as: $aJCrN$radixuireactslot.Slot, - allowPinchZoom: true, - shards: [context.contentRef] - }, /*#__PURE__*/$aJCrN$react.createElement($aJCrN$radixuireactprimitive.Primitive.div, $parcel$interopDefault($aJCrN$babelruntimehelpersextends)({ - "data-state": $f4833395aa1bca1a$var$getState(context.open) - }, overlayProps, { - ref: forwardedRef // We re-enable pointer-events prevented by `Dialog.Content` to allow scrolling the overlay. - , - - style: { - pointerEvents: 'auto', - ...overlayProps.style - } - }))) - ); -}); -/* ------------------------------------------------------------------------------------------------- - * DialogContent - * -----------------------------------------------------------------------------------------------*/ -const $f4833395aa1bca1a$var$CONTENT_NAME = 'DialogContent'; -const $f4833395aa1bca1a$export$b6d9565de1e068cf = /*#__PURE__*/$aJCrN$react.forwardRef((props, forwardedRef) => { - const portalContext = $f4833395aa1bca1a$var$usePortalContext($f4833395aa1bca1a$var$CONTENT_NAME, props.__scopeDialog); - const { - forceMount = portalContext.forceMount, - ...contentProps - } = props; - const context = $f4833395aa1bca1a$var$useDialogContext($f4833395aa1bca1a$var$CONTENT_NAME, props.__scopeDialog); - return /*#__PURE__*/$aJCrN$react.createElement($aJCrN$radixuireactpresence.Presence, { - present: forceMount || context.open - }, context.modal ? /*#__PURE__*/$aJCrN$react.createElement($f4833395aa1bca1a$var$DialogContentModal, $parcel$interopDefault($aJCrN$babelruntimehelpersextends)({}, contentProps, { - ref: forwardedRef - })) : /*#__PURE__*/$aJCrN$react.createElement($f4833395aa1bca1a$var$DialogContentNonModal, $parcel$interopDefault($aJCrN$babelruntimehelpersextends)({}, contentProps, { - ref: forwardedRef - }))); -}); -/*#__PURE__*/ -Object.assign($f4833395aa1bca1a$export$b6d9565de1e068cf, { - displayName: $f4833395aa1bca1a$var$CONTENT_NAME -}); -/* -----------------------------------------------------------------------------------------------*/ -const $f4833395aa1bca1a$var$DialogContentModal = /*#__PURE__*/$aJCrN$react.forwardRef((props, forwardedRef) => { - const context = $f4833395aa1bca1a$var$useDialogContext($f4833395aa1bca1a$var$CONTENT_NAME, props.__scopeDialog); - const contentRef = $aJCrN$react.useRef(null); - const composedRefs = $aJCrN$radixuireactcomposerefs.useComposedRefs(forwardedRef, context.contentRef, contentRef); // aria-hide everything except the content (better supported equivalent to setting aria-modal) - $aJCrN$react.useEffect(() => { - const content = contentRef.current; - if (content) return $aJCrN$ariahidden.hideOthers(content); - }, []); - return /*#__PURE__*/$aJCrN$react.createElement($f4833395aa1bca1a$var$DialogContentImpl, $parcel$interopDefault($aJCrN$babelruntimehelpersextends)({}, props, { - ref: composedRefs // we make sure focus isn't trapped once `DialogContent` has been closed - , - - trapFocus: context.open, - disableOutsidePointerEvents: true, - onCloseAutoFocus: $aJCrN$radixuiprimitive.composeEventHandlers(props.onCloseAutoFocus, event => { - var _context$triggerRef$c; - event.preventDefault(); - (_context$triggerRef$c = context.triggerRef.current) === null || _context$triggerRef$c === void 0 || _context$triggerRef$c.focus(); - }), - onPointerDownOutside: $aJCrN$radixuiprimitive.composeEventHandlers(props.onPointerDownOutside, event => { - const originalEvent = event.detail.originalEvent; - const ctrlLeftClick = originalEvent.button === 0 && originalEvent.ctrlKey === true; - const isRightClick = originalEvent.button === 2 || ctrlLeftClick; // If the event is a right-click, we shouldn't close because - // it is effectively as if we right-clicked the `Overlay`. - if (isRightClick) event.preventDefault(); - }) // When focus is trapped, a `focusout` event may still happen. - , - - onFocusOutside: $aJCrN$radixuiprimitive.composeEventHandlers(props.onFocusOutside, event => event.preventDefault()) - })); -}); -/* -----------------------------------------------------------------------------------------------*/ -const $f4833395aa1bca1a$var$DialogContentNonModal = /*#__PURE__*/$aJCrN$react.forwardRef((props, forwardedRef) => { - const context = $f4833395aa1bca1a$var$useDialogContext($f4833395aa1bca1a$var$CONTENT_NAME, props.__scopeDialog); - const hasInteractedOutsideRef = $aJCrN$react.useRef(false); - const hasPointerDownOutsideRef = $aJCrN$react.useRef(false); - return /*#__PURE__*/$aJCrN$react.createElement($f4833395aa1bca1a$var$DialogContentImpl, $parcel$interopDefault($aJCrN$babelruntimehelpersextends)({}, props, { - ref: forwardedRef, - trapFocus: false, - disableOutsidePointerEvents: false, - onCloseAutoFocus: event => { - var _props$onCloseAutoFoc; - (_props$onCloseAutoFoc = props.onCloseAutoFocus) === null || _props$onCloseAutoFoc === void 0 || _props$onCloseAutoFoc.call(props, event); - if (!event.defaultPrevented) { - var _context$triggerRef$c2; - if (!hasInteractedOutsideRef.current) (_context$triggerRef$c2 = context.triggerRef.current) === null || _context$triggerRef$c2 === void 0 || _context$triggerRef$c2.focus(); // Always prevent auto focus because we either focus manually or want user agent focus - event.preventDefault(); - } - hasInteractedOutsideRef.current = false; - hasPointerDownOutsideRef.current = false; - }, - onInteractOutside: event => { - var _props$onInteractOuts, _context$triggerRef$c3; - (_props$onInteractOuts = props.onInteractOutside) === null || _props$onInteractOuts === void 0 || _props$onInteractOuts.call(props, event); - if (!event.defaultPrevented) { - hasInteractedOutsideRef.current = true; - if (event.detail.originalEvent.type === 'pointerdown') hasPointerDownOutsideRef.current = true; - } // Prevent dismissing when clicking the trigger. - // As the trigger is already setup to close, without doing so would - // cause it to close and immediately open. - const target = event.target; - const targetIsTrigger = (_context$triggerRef$c3 = context.triggerRef.current) === null || _context$triggerRef$c3 === void 0 ? void 0 : _context$triggerRef$c3.contains(target); - if (targetIsTrigger) event.preventDefault(); // On Safari if the trigger is inside a container with tabIndex={0}, when clicked - // we will get the pointer down outside event on the trigger, but then a subsequent - // focus outside event on the container, we ignore any focus outside event when we've - // already had a pointer down outside event. - if (event.detail.originalEvent.type === 'focusin' && hasPointerDownOutsideRef.current) event.preventDefault(); - } - })); -}); -/* -----------------------------------------------------------------------------------------------*/ -const $f4833395aa1bca1a$var$DialogContentImpl = /*#__PURE__*/$aJCrN$react.forwardRef((props, forwardedRef) => { - const { - __scopeDialog: __scopeDialog, - trapFocus: trapFocus, - onOpenAutoFocus: onOpenAutoFocus, - onCloseAutoFocus: onCloseAutoFocus, - ...contentProps - } = props; - const context = $f4833395aa1bca1a$var$useDialogContext($f4833395aa1bca1a$var$CONTENT_NAME, __scopeDialog); - const contentRef = $aJCrN$react.useRef(null); - const composedRefs = $aJCrN$radixuireactcomposerefs.useComposedRefs(forwardedRef, contentRef); // Make sure the whole tree has focus guards as our `Dialog` will be - // the last element in the DOM (beacuse of the `Portal`) - $aJCrN$radixuireactfocusguards.useFocusGuards(); - return /*#__PURE__*/$aJCrN$react.createElement($aJCrN$react.Fragment, null, /*#__PURE__*/$aJCrN$react.createElement($aJCrN$radixuireactfocusscope.FocusScope, { - asChild: true, - loop: true, - trapped: trapFocus, - onMountAutoFocus: onOpenAutoFocus, - onUnmountAutoFocus: onCloseAutoFocus - }, /*#__PURE__*/$aJCrN$react.createElement($aJCrN$radixuireactdismissablelayer.DismissableLayer, $parcel$interopDefault($aJCrN$babelruntimehelpersextends)({ - role: "dialog", - id: context.contentId, - "aria-describedby": context.descriptionId, - "aria-labelledby": context.titleId, - "data-state": $f4833395aa1bca1a$var$getState(context.open) - }, contentProps, { - ref: composedRefs, - onDismiss: () => context.onOpenChange(false) - }))), false); -}); -/* ------------------------------------------------------------------------------------------------- - * DialogTitle - * -----------------------------------------------------------------------------------------------*/ -const $f4833395aa1bca1a$var$TITLE_NAME = 'DialogTitle'; -const $f4833395aa1bca1a$export$16f7638e4a34b909 = /*#__PURE__*/$aJCrN$react.forwardRef((props, forwardedRef) => { - const { - __scopeDialog: __scopeDialog, - ...titleProps - } = props; - const context = $f4833395aa1bca1a$var$useDialogContext($f4833395aa1bca1a$var$TITLE_NAME, __scopeDialog); - return /*#__PURE__*/$aJCrN$react.createElement($aJCrN$radixuireactprimitive.Primitive.h2, $parcel$interopDefault($aJCrN$babelruntimehelpersextends)({ - id: context.titleId - }, titleProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($f4833395aa1bca1a$export$16f7638e4a34b909, { - displayName: $f4833395aa1bca1a$var$TITLE_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DialogDescription - * -----------------------------------------------------------------------------------------------*/ -const $f4833395aa1bca1a$var$DESCRIPTION_NAME = 'DialogDescription'; -const $f4833395aa1bca1a$export$94e94c2ec2c954d5 = /*#__PURE__*/$aJCrN$react.forwardRef((props, forwardedRef) => { - const { - __scopeDialog: __scopeDialog, - ...descriptionProps - } = props; - const context = $f4833395aa1bca1a$var$useDialogContext($f4833395aa1bca1a$var$DESCRIPTION_NAME, __scopeDialog); - return /*#__PURE__*/$aJCrN$react.createElement($aJCrN$radixuireactprimitive.Primitive.p, $parcel$interopDefault($aJCrN$babelruntimehelpersextends)({ - id: context.descriptionId - }, descriptionProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($f4833395aa1bca1a$export$94e94c2ec2c954d5, { - displayName: $f4833395aa1bca1a$var$DESCRIPTION_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DialogClose - * -----------------------------------------------------------------------------------------------*/ -const $f4833395aa1bca1a$var$CLOSE_NAME = 'DialogClose'; -const $f4833395aa1bca1a$export$fba2fb7cd781b7ac = /*#__PURE__*/$aJCrN$react.forwardRef((props, forwardedRef) => { - const { - __scopeDialog: __scopeDialog, - ...closeProps - } = props; - const context = $f4833395aa1bca1a$var$useDialogContext($f4833395aa1bca1a$var$CLOSE_NAME, __scopeDialog); - return /*#__PURE__*/$aJCrN$react.createElement($aJCrN$radixuireactprimitive.Primitive.button, $parcel$interopDefault($aJCrN$babelruntimehelpersextends)({ - type: "button" - }, closeProps, { - ref: forwardedRef, - onClick: $aJCrN$radixuiprimitive.composeEventHandlers(props.onClick, () => context.onOpenChange(false)) - })); -}); -/*#__PURE__*/ -Object.assign($f4833395aa1bca1a$export$fba2fb7cd781b7ac, { - displayName: $f4833395aa1bca1a$var$CLOSE_NAME -}); -/* -----------------------------------------------------------------------------------------------*/ -function $f4833395aa1bca1a$var$getState(open) { - return open ? 'open' : 'closed'; -} -const $f4833395aa1bca1a$var$TITLE_WARNING_NAME = 'DialogTitleWarning'; -const [$f4833395aa1bca1a$export$69b62a49393917d6, $f4833395aa1bca1a$var$useWarningContext] = $aJCrN$radixuireactcontext.createContext($f4833395aa1bca1a$var$TITLE_WARNING_NAME, { - contentName: $f4833395aa1bca1a$var$CONTENT_NAME, - titleName: $f4833395aa1bca1a$var$TITLE_NAME, - docsSlug: 'dialog' -}); -const $f4833395aa1bca1a$var$TitleWarning = ({ - titleId: titleId -}) => { - const titleWarningContext = $f4833395aa1bca1a$var$useWarningContext($f4833395aa1bca1a$var$TITLE_WARNING_NAME); - const MESSAGE = `\`${titleWarningContext.contentName}\` requires a \`${titleWarningContext.titleName}\` for the component to be accessible for screen reader users. - -If you want to hide the \`${titleWarningContext.titleName}\`, you can wrap it with our VisuallyHidden component. - -For more information, see https://radix-ui.com/primitives/docs/components/${titleWarningContext.docsSlug}`; - $aJCrN$react.useEffect(() => { - if (titleId) { - const hasTitle = document.getElementById(titleId); - if (!hasTitle) throw new Error(MESSAGE); - } - }, [MESSAGE, titleId]); - return null; -}; -const $f4833395aa1bca1a$var$DESCRIPTION_WARNING_NAME = 'DialogDescriptionWarning'; -const $f4833395aa1bca1a$var$DescriptionWarning = ({ - contentRef: contentRef, - descriptionId: descriptionId -}) => { - const descriptionWarningContext = $f4833395aa1bca1a$var$useWarningContext($f4833395aa1bca1a$var$DESCRIPTION_WARNING_NAME); - const MESSAGE = `Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${descriptionWarningContext.contentName}}.`; - $aJCrN$react.useEffect(() => { - var _contentRef$current; - const describedById = (_contentRef$current = contentRef.current) === null || _contentRef$current === void 0 ? void 0 : _contentRef$current.getAttribute('aria-describedby'); // if we have an id and the user hasn't set aria-describedby={undefined} - if (descriptionId && describedById) { - const hasDescription = document.getElementById(descriptionId); - if (!hasDescription) console.warn(MESSAGE); - } - }, [MESSAGE, contentRef, descriptionId]); - return null; -}; -const $f4833395aa1bca1a$export$be92b6f5f03c0fe9 = $f4833395aa1bca1a$export$3ddf2d174ce01153; -const $f4833395aa1bca1a$export$41fb9f06171c75f4 = $f4833395aa1bca1a$export$2e1e1122cf0cba88; -const $f4833395aa1bca1a$export$602eac185826482c = $f4833395aa1bca1a$export$dad7c95542bacce0; -const $f4833395aa1bca1a$export$c6fdb837b070b4ff = $f4833395aa1bca1a$export$bd1d06c79be19e17; -const $f4833395aa1bca1a$export$7c6e2c02157bb7d2 = $f4833395aa1bca1a$export$b6d9565de1e068cf; -const $f4833395aa1bca1a$export$f99233281efd08a0 = $f4833395aa1bca1a$export$16f7638e4a34b909; -const $f4833395aa1bca1a$export$393edc798c47379d = $f4833395aa1bca1a$export$94e94c2ec2c954d5; -const $f4833395aa1bca1a$export$f39c2d165cd861fe = $f4833395aa1bca1a$export$fba2fb7cd781b7ac; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-direction/dist/index.js": -/*!*********************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-direction/dist/index.js ***! - \*********************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var $9g4ps$react = __webpack_require__(/*! react */ "react"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -$parcel$export(module.exports, "useDirection", () => $cc45c1b701a63adc$export$b39126d51d94e6f3); -$parcel$export(module.exports, "Provider", () => $cc45c1b701a63adc$export$2881499e37b75b9a); -$parcel$export(module.exports, "DirectionProvider", () => $cc45c1b701a63adc$export$c760c09fdd558351); -const $cc45c1b701a63adc$var$DirectionContext = /*#__PURE__*/$9g4ps$react.createContext(undefined); -/* ------------------------------------------------------------------------------------------------- - * Direction - * -----------------------------------------------------------------------------------------------*/ -const $cc45c1b701a63adc$export$c760c09fdd558351 = props => { - const { - dir: dir, - children: children - } = props; - return /*#__PURE__*/$9g4ps$react.createElement($cc45c1b701a63adc$var$DirectionContext.Provider, { - value: dir - }, children); -}; -/* -----------------------------------------------------------------------------------------------*/ -function $cc45c1b701a63adc$export$b39126d51d94e6f3(localDir) { - const globalDir = $9g4ps$react.useContext($cc45c1b701a63adc$var$DirectionContext); - return localDir || globalDir || 'ltr'; -} -const $cc45c1b701a63adc$export$2881499e37b75b9a = $cc45c1b701a63adc$export$c760c09fdd558351; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-dismissable-layer/dist/index.js": -/*!*****************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-dismissable-layer/dist/index.js ***! - \*****************************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var $g2vWm$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); -var $g2vWm$react = __webpack_require__(/*! react */ "react"); -var $g2vWm$radixuiprimitive = __webpack_require__(/*! @radix-ui/primitive */ "../../../node_modules/@radix-ui/primitive/dist/index.js"); -var $g2vWm$radixuireactprimitive = __webpack_require__(/*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js"); -var $g2vWm$radixuireactcomposerefs = __webpack_require__(/*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js"); -var $g2vWm$radixuireactusecallbackref = __webpack_require__(/*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js"); -var $g2vWm$radixuireactuseescapekeydown = __webpack_require__(/*! @radix-ui/react-use-escape-keydown */ "../../../node_modules/@radix-ui/react-use-escape-keydown/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "DismissableLayer", () => $d715e0554b679f1f$export$177fb62ff3ec1f22); -$parcel$export(module.exports, "DismissableLayerBranch", () => $d715e0554b679f1f$export$4d5eb2109db14228); -$parcel$export(module.exports, "Root", () => $d715e0554b679f1f$export$be92b6f5f03c0fe9); -$parcel$export(module.exports, "Branch", () => $d715e0554b679f1f$export$aecb2ddcb55c95be); - -/* ------------------------------------------------------------------------------------------------- - * DismissableLayer - * -----------------------------------------------------------------------------------------------*/ -const $d715e0554b679f1f$var$DISMISSABLE_LAYER_NAME = 'DismissableLayer'; -const $d715e0554b679f1f$var$CONTEXT_UPDATE = 'dismissableLayer.update'; -const $d715e0554b679f1f$var$POINTER_DOWN_OUTSIDE = 'dismissableLayer.pointerDownOutside'; -const $d715e0554b679f1f$var$FOCUS_OUTSIDE = 'dismissableLayer.focusOutside'; -let $d715e0554b679f1f$var$originalBodyPointerEvents; -const $d715e0554b679f1f$var$DismissableLayerContext = /*#__PURE__*/$g2vWm$react.createContext({ - layers: new Set(), - layersWithOutsidePointerEventsDisabled: new Set(), - branches: new Set() -}); -const $d715e0554b679f1f$export$177fb62ff3ec1f22 = /*#__PURE__*/$g2vWm$react.forwardRef((props, forwardedRef) => { - var _node$ownerDocument; - const { - disableOutsidePointerEvents = false, - onEscapeKeyDown: onEscapeKeyDown, - onPointerDownOutside: onPointerDownOutside, - onFocusOutside: onFocusOutside, - onInteractOutside: onInteractOutside, - onDismiss: onDismiss, - ...layerProps - } = props; - const context = $g2vWm$react.useContext($d715e0554b679f1f$var$DismissableLayerContext); - const [node1, setNode] = $g2vWm$react.useState(null); - const ownerDocument = (_node$ownerDocument = node1 === null || node1 === void 0 ? void 0 : node1.ownerDocument) !== null && _node$ownerDocument !== void 0 ? _node$ownerDocument : globalThis === null || globalThis === void 0 ? void 0 : globalThis.document; - const [, force] = $g2vWm$react.useState({}); - const composedRefs = $g2vWm$radixuireactcomposerefs.useComposedRefs(forwardedRef, node => setNode(node)); - const layers = Array.from(context.layers); - const [highestLayerWithOutsidePointerEventsDisabled] = [...context.layersWithOutsidePointerEventsDisabled].slice(-1); // prettier-ignore - const highestLayerWithOutsidePointerEventsDisabledIndex = layers.indexOf(highestLayerWithOutsidePointerEventsDisabled); // prettier-ignore - const index = node1 ? layers.indexOf(node1) : -1; - const isBodyPointerEventsDisabled = context.layersWithOutsidePointerEventsDisabled.size > 0; - const isPointerEventsEnabled = index >= highestLayerWithOutsidePointerEventsDisabledIndex; - const pointerDownOutside = $d715e0554b679f1f$var$usePointerDownOutside(event => { - const target = event.target; - const isPointerDownOnBranch = [...context.branches].some(branch => branch.contains(target)); - if (!isPointerEventsEnabled || isPointerDownOnBranch) return; - onPointerDownOutside === null || onPointerDownOutside === void 0 || onPointerDownOutside(event); - onInteractOutside === null || onInteractOutside === void 0 || onInteractOutside(event); - if (!event.defaultPrevented) onDismiss === null || onDismiss === void 0 || onDismiss(); - }, ownerDocument); - const focusOutside = $d715e0554b679f1f$var$useFocusOutside(event => { - const target = event.target; - const isFocusInBranch = [...context.branches].some(branch => branch.contains(target)); - if (isFocusInBranch) return; - onFocusOutside === null || onFocusOutside === void 0 || onFocusOutside(event); - onInteractOutside === null || onInteractOutside === void 0 || onInteractOutside(event); - if (!event.defaultPrevented) onDismiss === null || onDismiss === void 0 || onDismiss(); - }, ownerDocument); - $g2vWm$radixuireactuseescapekeydown.useEscapeKeydown(event => { - const isHighestLayer = index === context.layers.size - 1; - if (!isHighestLayer) return; - onEscapeKeyDown === null || onEscapeKeyDown === void 0 || onEscapeKeyDown(event); - if (!event.defaultPrevented && onDismiss) { - event.preventDefault(); - onDismiss(); - } - }, ownerDocument); - $g2vWm$react.useEffect(() => { - if (!node1) return; - if (disableOutsidePointerEvents) { - if (context.layersWithOutsidePointerEventsDisabled.size === 0) { - $d715e0554b679f1f$var$originalBodyPointerEvents = ownerDocument.body.style.pointerEvents; - ownerDocument.body.style.pointerEvents = 'none'; - } - context.layersWithOutsidePointerEventsDisabled.add(node1); - } - context.layers.add(node1); - $d715e0554b679f1f$var$dispatchUpdate(); - return () => { - if (disableOutsidePointerEvents && context.layersWithOutsidePointerEventsDisabled.size === 1) ownerDocument.body.style.pointerEvents = $d715e0554b679f1f$var$originalBodyPointerEvents; - }; - }, [node1, ownerDocument, disableOutsidePointerEvents, context]); - /** - * We purposefully prevent combining this effect with the `disableOutsidePointerEvents` effect - * because a change to `disableOutsidePointerEvents` would remove this layer from the stack - * and add it to the end again so the layering order wouldn't be _creation order_. - * We only want them to be removed from context stacks when unmounted. - */ - $g2vWm$react.useEffect(() => { - return () => { - if (!node1) return; - context.layers.delete(node1); - context.layersWithOutsidePointerEventsDisabled.delete(node1); - $d715e0554b679f1f$var$dispatchUpdate(); - }; - }, [node1, context]); - $g2vWm$react.useEffect(() => { - const handleUpdate = () => force({}); - document.addEventListener($d715e0554b679f1f$var$CONTEXT_UPDATE, handleUpdate); - return () => document.removeEventListener($d715e0554b679f1f$var$CONTEXT_UPDATE, handleUpdate); - }, []); - return /*#__PURE__*/$g2vWm$react.createElement($g2vWm$radixuireactprimitive.Primitive.div, $parcel$interopDefault($g2vWm$babelruntimehelpersextends)({}, layerProps, { - ref: composedRefs, - style: { - pointerEvents: isBodyPointerEventsDisabled ? isPointerEventsEnabled ? 'auto' : 'none' : undefined, - ...props.style - }, - onFocusCapture: $g2vWm$radixuiprimitive.composeEventHandlers(props.onFocusCapture, focusOutside.onFocusCapture), - onBlurCapture: $g2vWm$radixuiprimitive.composeEventHandlers(props.onBlurCapture, focusOutside.onBlurCapture), - onPointerDownCapture: $g2vWm$radixuiprimitive.composeEventHandlers(props.onPointerDownCapture, pointerDownOutside.onPointerDownCapture) - })); -}); -/*#__PURE__*/ -Object.assign($d715e0554b679f1f$export$177fb62ff3ec1f22, { - displayName: $d715e0554b679f1f$var$DISMISSABLE_LAYER_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DismissableLayerBranch - * -----------------------------------------------------------------------------------------------*/ -const $d715e0554b679f1f$var$BRANCH_NAME = 'DismissableLayerBranch'; -const $d715e0554b679f1f$export$4d5eb2109db14228 = /*#__PURE__*/$g2vWm$react.forwardRef((props, forwardedRef) => { - const context = $g2vWm$react.useContext($d715e0554b679f1f$var$DismissableLayerContext); - const ref = $g2vWm$react.useRef(null); - const composedRefs = $g2vWm$radixuireactcomposerefs.useComposedRefs(forwardedRef, ref); - $g2vWm$react.useEffect(() => { - const node = ref.current; - if (node) { - context.branches.add(node); - return () => { - context.branches.delete(node); - }; - } - }, [context.branches]); - return /*#__PURE__*/$g2vWm$react.createElement($g2vWm$radixuireactprimitive.Primitive.div, $parcel$interopDefault($g2vWm$babelruntimehelpersextends)({}, props, { - ref: composedRefs - })); -}); -/*#__PURE__*/ -Object.assign($d715e0554b679f1f$export$4d5eb2109db14228, { - displayName: $d715e0554b679f1f$var$BRANCH_NAME -}); -/* -----------------------------------------------------------------------------------------------*/ /** - * Listens for `pointerdown` outside a react subtree. We use `pointerdown` rather than `pointerup` - * to mimic layer dismissing behaviour present in OS. - * Returns props to pass to the node we want to check for outside events. - */ -function $d715e0554b679f1f$var$usePointerDownOutside(onPointerDownOutside, ownerDocument = globalThis === null || globalThis === void 0 ? void 0 : globalThis.document) { - const handlePointerDownOutside = $g2vWm$radixuireactusecallbackref.useCallbackRef(onPointerDownOutside); - const isPointerInsideReactTreeRef = $g2vWm$react.useRef(false); - const handleClickRef = $g2vWm$react.useRef(() => {}); - $g2vWm$react.useEffect(() => { - const handlePointerDown = event => { - if (event.target && !isPointerInsideReactTreeRef.current) { - const eventDetail = { - originalEvent: event - }; - function handleAndDispatchPointerDownOutsideEvent() { - $d715e0554b679f1f$var$handleAndDispatchCustomEvent($d715e0554b679f1f$var$POINTER_DOWN_OUTSIDE, handlePointerDownOutside, eventDetail, { - discrete: true - }); - } - /** - * On touch devices, we need to wait for a click event because browsers implement - * a ~350ms delay between the time the user stops touching the display and when the - * browser executres events. We need to ensure we don't reactivate pointer-events within - * this timeframe otherwise the browser may execute events that should have been prevented. - * - * Additionally, this also lets us deal automatically with cancellations when a click event - * isn't raised because the page was considered scrolled/drag-scrolled, long-pressed, etc. - * - * This is why we also continuously remove the previous listener, because we cannot be - * certain that it was raised, and therefore cleaned-up. - */ - if (event.pointerType === 'touch') { - ownerDocument.removeEventListener('click', handleClickRef.current); - handleClickRef.current = handleAndDispatchPointerDownOutsideEvent; - ownerDocument.addEventListener('click', handleClickRef.current, { - once: true - }); - } else handleAndDispatchPointerDownOutsideEvent(); - } - isPointerInsideReactTreeRef.current = false; - }; - /** - * if this hook executes in a component that mounts via a `pointerdown` event, the event - * would bubble up to the document and trigger a `pointerDownOutside` event. We avoid - * this by delaying the event listener registration on the document. - * This is not React specific, but rather how the DOM works, ie: - * ``` - * button.addEventListener('pointerdown', () => { - * console.log('I will log'); - * document.addEventListener('pointerdown', () => { - * console.log('I will also log'); - * }) - * }); - */ - const timerId = window.setTimeout(() => { - ownerDocument.addEventListener('pointerdown', handlePointerDown); - }, 0); - return () => { - window.clearTimeout(timerId); - ownerDocument.removeEventListener('pointerdown', handlePointerDown); - ownerDocument.removeEventListener('click', handleClickRef.current); - }; - }, [ownerDocument, handlePointerDownOutside]); - return { - // ensures we check React component tree (not just DOM tree) - onPointerDownCapture: () => isPointerInsideReactTreeRef.current = true - }; -} -/** - * Listens for when focus happens outside a react subtree. - * Returns props to pass to the root (node) of the subtree we want to check. - */ -function $d715e0554b679f1f$var$useFocusOutside(onFocusOutside, ownerDocument = globalThis === null || globalThis === void 0 ? void 0 : globalThis.document) { - const handleFocusOutside = $g2vWm$radixuireactusecallbackref.useCallbackRef(onFocusOutside); - const isFocusInsideReactTreeRef = $g2vWm$react.useRef(false); - $g2vWm$react.useEffect(() => { - const handleFocus = event => { - if (event.target && !isFocusInsideReactTreeRef.current) { - const eventDetail = { - originalEvent: event - }; - $d715e0554b679f1f$var$handleAndDispatchCustomEvent($d715e0554b679f1f$var$FOCUS_OUTSIDE, handleFocusOutside, eventDetail, { - discrete: false - }); - } - }; - ownerDocument.addEventListener('focusin', handleFocus); - return () => ownerDocument.removeEventListener('focusin', handleFocus); - }, [ownerDocument, handleFocusOutside]); - return { - onFocusCapture: () => isFocusInsideReactTreeRef.current = true, - onBlurCapture: () => isFocusInsideReactTreeRef.current = false - }; -} -function $d715e0554b679f1f$var$dispatchUpdate() { - const event = new CustomEvent($d715e0554b679f1f$var$CONTEXT_UPDATE); - document.dispatchEvent(event); -} -function $d715e0554b679f1f$var$handleAndDispatchCustomEvent(name, handler, detail, { - discrete: discrete -}) { - const target = detail.originalEvent.target; - const event = new CustomEvent(name, { - bubbles: false, - cancelable: true, - detail: detail - }); - if (handler) target.addEventListener(name, handler, { - once: true - }); - if (discrete) $g2vWm$radixuireactprimitive.dispatchDiscreteCustomEvent(target, event);else target.dispatchEvent(event); -} -const $d715e0554b679f1f$export$be92b6f5f03c0fe9 = $d715e0554b679f1f$export$177fb62ff3ec1f22; -const $d715e0554b679f1f$export$aecb2ddcb55c95be = $d715e0554b679f1f$export$4d5eb2109db14228; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-dropdown-menu/dist/index.js": -/*!*************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-dropdown-menu/dist/index.js ***! - \*************************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var $7dQ7Q$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); -var $7dQ7Q$react = __webpack_require__(/*! react */ "react"); -var $7dQ7Q$radixuiprimitive = __webpack_require__(/*! @radix-ui/primitive */ "../../../node_modules/@radix-ui/primitive/dist/index.js"); -var $7dQ7Q$radixuireactcomposerefs = __webpack_require__(/*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js"); -var $7dQ7Q$radixuireactcontext = __webpack_require__(/*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js"); -var $7dQ7Q$radixuireactusecontrollablestate = __webpack_require__(/*! @radix-ui/react-use-controllable-state */ "../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js"); -var $7dQ7Q$radixuireactprimitive = __webpack_require__(/*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js"); -var $7dQ7Q$radixuireactmenu = __webpack_require__(/*! @radix-ui/react-menu */ "../../../node_modules/@radix-ui/react-menu/dist/index.js"); -var $7dQ7Q$radixuireactid = __webpack_require__(/*! @radix-ui/react-id */ "../../../node_modules/@radix-ui/react-id/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "createDropdownMenuScope", () => $d1bf075a6b218014$export$c0623cd925aeb687); -$parcel$export(module.exports, "DropdownMenu", () => $d1bf075a6b218014$export$e44a253a59704894); -$parcel$export(module.exports, "DropdownMenuTrigger", () => $d1bf075a6b218014$export$d2469213b3befba9); -$parcel$export(module.exports, "DropdownMenuPortal", () => $d1bf075a6b218014$export$cd369b4d4d54efc9); -$parcel$export(module.exports, "DropdownMenuContent", () => $d1bf075a6b218014$export$6e76d93a37c01248); -$parcel$export(module.exports, "DropdownMenuGroup", () => $d1bf075a6b218014$export$246bebaba3a2f70e); -$parcel$export(module.exports, "DropdownMenuLabel", () => $d1bf075a6b218014$export$76e48c5b57f24495); -$parcel$export(module.exports, "DropdownMenuItem", () => $d1bf075a6b218014$export$ed97964d1871885d); -$parcel$export(module.exports, "DropdownMenuCheckboxItem", () => $d1bf075a6b218014$export$53a69729da201fa9); -$parcel$export(module.exports, "DropdownMenuRadioGroup", () => $d1bf075a6b218014$export$3323ad73d55f587e); -$parcel$export(module.exports, "DropdownMenuRadioItem", () => $d1bf075a6b218014$export$e4f69b41b1637536); -$parcel$export(module.exports, "DropdownMenuItemIndicator", () => $d1bf075a6b218014$export$42355ae145153fb6); -$parcel$export(module.exports, "DropdownMenuSeparator", () => $d1bf075a6b218014$export$da160178fd3bc7e9); -$parcel$export(module.exports, "DropdownMenuArrow", () => $d1bf075a6b218014$export$34b8980744021ec5); -$parcel$export(module.exports, "DropdownMenuSub", () => $d1bf075a6b218014$export$2f307d81a64f5442); -$parcel$export(module.exports, "DropdownMenuSubTrigger", () => $d1bf075a6b218014$export$21dcb7ec56f874cf); -$parcel$export(module.exports, "DropdownMenuSubContent", () => $d1bf075a6b218014$export$f34ec8bc2482cc5f); -$parcel$export(module.exports, "Root", () => $d1bf075a6b218014$export$be92b6f5f03c0fe9); -$parcel$export(module.exports, "Trigger", () => $d1bf075a6b218014$export$41fb9f06171c75f4); -$parcel$export(module.exports, "Portal", () => $d1bf075a6b218014$export$602eac185826482c); -$parcel$export(module.exports, "Content", () => $d1bf075a6b218014$export$7c6e2c02157bb7d2); -$parcel$export(module.exports, "Group", () => $d1bf075a6b218014$export$eb2fcfdbd7ba97d4); -$parcel$export(module.exports, "Label", () => $d1bf075a6b218014$export$b04be29aa201d4f5); -$parcel$export(module.exports, "Item", () => $d1bf075a6b218014$export$6d08773d2e66f8f2); -$parcel$export(module.exports, "CheckboxItem", () => $d1bf075a6b218014$export$16ce288f89fa631c); -$parcel$export(module.exports, "RadioGroup", () => $d1bf075a6b218014$export$a98f0dcb43a68a25); -$parcel$export(module.exports, "RadioItem", () => $d1bf075a6b218014$export$371ab307eab489c0); -$parcel$export(module.exports, "ItemIndicator", () => $d1bf075a6b218014$export$c3468e2714d175fa); -$parcel$export(module.exports, "Separator", () => $d1bf075a6b218014$export$1ff3c3f08ae963c0); -$parcel$export(module.exports, "Arrow", () => $d1bf075a6b218014$export$21b07c8f274aebd5); -$parcel$export(module.exports, "Sub", () => $d1bf075a6b218014$export$d7a01e11500dfb6f); -$parcel$export(module.exports, "SubTrigger", () => $d1bf075a6b218014$export$2ea8a7a591ac5eac); -$parcel$export(module.exports, "SubContent", () => $d1bf075a6b218014$export$6d4de93b380beddf); - -/* ------------------------------------------------------------------------------------------------- - * DropdownMenu - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$DROPDOWN_MENU_NAME = 'DropdownMenu'; -const [$d1bf075a6b218014$var$createDropdownMenuContext, $d1bf075a6b218014$export$c0623cd925aeb687] = $7dQ7Q$radixuireactcontext.createContextScope($d1bf075a6b218014$var$DROPDOWN_MENU_NAME, [$7dQ7Q$radixuireactmenu.createMenuScope]); -const $d1bf075a6b218014$var$useMenuScope = $7dQ7Q$radixuireactmenu.createMenuScope(); -const [$d1bf075a6b218014$var$DropdownMenuProvider, $d1bf075a6b218014$var$useDropdownMenuContext] = $d1bf075a6b218014$var$createDropdownMenuContext($d1bf075a6b218014$var$DROPDOWN_MENU_NAME); -const $d1bf075a6b218014$export$e44a253a59704894 = props => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - children: children, - dir: dir, - open: openProp, - defaultOpen: defaultOpen, - onOpenChange: onOpenChange, - modal = true - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - const triggerRef = $7dQ7Q$react.useRef(null); - const [open = false, setOpen] = $7dQ7Q$radixuireactusecontrollablestate.useControllableState({ - prop: openProp, - defaultProp: defaultOpen, - onChange: onOpenChange - }); - return /*#__PURE__*/$7dQ7Q$react.createElement($d1bf075a6b218014$var$DropdownMenuProvider, { - scope: __scopeDropdownMenu, - triggerId: $7dQ7Q$radixuireactid.useId(), - triggerRef: triggerRef, - contentId: $7dQ7Q$radixuireactid.useId(), - open: open, - onOpenChange: setOpen, - onOpenToggle: $7dQ7Q$react.useCallback(() => setOpen(prevOpen => !prevOpen), [setOpen]), - modal: modal - }, /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.Root, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, { - open: open, - onOpenChange: setOpen, - dir: dir, - modal: modal - }), children)); -}; -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$e44a253a59704894, { - displayName: $d1bf075a6b218014$var$DROPDOWN_MENU_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuTrigger - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$TRIGGER_NAME = 'DropdownMenuTrigger'; -const $d1bf075a6b218014$export$d2469213b3befba9 = /*#__PURE__*/$7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - disabled = false, - ...triggerProps - } = props; - const context = $d1bf075a6b218014$var$useDropdownMenuContext($d1bf075a6b218014$var$TRIGGER_NAME, __scopeDropdownMenu); - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.Anchor, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({ - asChild: true - }, menuScope), /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactprimitive.Primitive.button, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({ - type: "button", - id: context.triggerId, - "aria-haspopup": "menu", - "aria-expanded": context.open, - "aria-controls": context.open ? context.contentId : undefined, - "data-state": context.open ? 'open' : 'closed', - "data-disabled": disabled ? '' : undefined, - disabled: disabled - }, triggerProps, { - ref: $7dQ7Q$radixuireactcomposerefs.composeRefs(forwardedRef, context.triggerRef), - onPointerDown: $7dQ7Q$radixuiprimitive.composeEventHandlers(props.onPointerDown, event => { - // only call handler if it's the left button (mousedown gets triggered by all mouse buttons) - // but not when the control key is pressed (avoiding MacOS right click) - if (!disabled && event.button === 0 && event.ctrlKey === false) { - context.onOpenToggle(); // prevent trigger focusing when opening - // this allows the content to be given focus without competition - if (!context.open) event.preventDefault(); - } - }), - onKeyDown: $7dQ7Q$radixuiprimitive.composeEventHandlers(props.onKeyDown, event => { - if (disabled) return; - if (['Enter', ' '].includes(event.key)) context.onOpenToggle(); - if (event.key === 'ArrowDown') context.onOpenChange(true); // prevent keydown from scrolling window / first focused item to execute - // that keydown (inadvertently closing the menu) - if (['Enter', ' ', 'ArrowDown'].includes(event.key)) event.preventDefault(); - }) - }))); -}); -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$d2469213b3befba9, { - displayName: $d1bf075a6b218014$var$TRIGGER_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuPortal - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$PORTAL_NAME = 'DropdownMenuPortal'; -const $d1bf075a6b218014$export$cd369b4d4d54efc9 = props => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...portalProps - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.Portal, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, portalProps)); -}; -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$cd369b4d4d54efc9, { - displayName: $d1bf075a6b218014$var$PORTAL_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuContent - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$CONTENT_NAME = 'DropdownMenuContent'; -const $d1bf075a6b218014$export$6e76d93a37c01248 = /*#__PURE__*/$7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...contentProps - } = props; - const context = $d1bf075a6b218014$var$useDropdownMenuContext($d1bf075a6b218014$var$CONTENT_NAME, __scopeDropdownMenu); - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - const hasInteractedOutsideRef = $7dQ7Q$react.useRef(false); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.Content, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({ - id: context.contentId, - "aria-labelledby": context.triggerId - }, menuScope, contentProps, { - ref: forwardedRef, - onCloseAutoFocus: $7dQ7Q$radixuiprimitive.composeEventHandlers(props.onCloseAutoFocus, event => { - var _context$triggerRef$c; - if (!hasInteractedOutsideRef.current) (_context$triggerRef$c = context.triggerRef.current) === null || _context$triggerRef$c === void 0 || _context$triggerRef$c.focus(); - hasInteractedOutsideRef.current = false; // Always prevent auto focus because we either focus manually or want user agent focus - event.preventDefault(); - }), - onInteractOutside: $7dQ7Q$radixuiprimitive.composeEventHandlers(props.onInteractOutside, event => { - const originalEvent = event.detail.originalEvent; - const ctrlLeftClick = originalEvent.button === 0 && originalEvent.ctrlKey === true; - const isRightClick = originalEvent.button === 2 || ctrlLeftClick; - if (!context.modal || isRightClick) hasInteractedOutsideRef.current = true; - }), - style: { - ...props.style, - '--radix-dropdown-menu-content-transform-origin': 'var(--radix-popper-transform-origin)', - '--radix-dropdown-menu-content-available-width': 'var(--radix-popper-available-width)', - '--radix-dropdown-menu-content-available-height': 'var(--radix-popper-available-height)', - '--radix-dropdown-menu-trigger-width': 'var(--radix-popper-anchor-width)', - '--radix-dropdown-menu-trigger-height': 'var(--radix-popper-anchor-height)' - } - })); -}); -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$6e76d93a37c01248, { - displayName: $d1bf075a6b218014$var$CONTENT_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuGroup - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$GROUP_NAME = 'DropdownMenuGroup'; -const $d1bf075a6b218014$export$246bebaba3a2f70e = /*#__PURE__*/$7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...groupProps - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.Group, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, groupProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$246bebaba3a2f70e, { - displayName: $d1bf075a6b218014$var$GROUP_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuLabel - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$LABEL_NAME = 'DropdownMenuLabel'; -const $d1bf075a6b218014$export$76e48c5b57f24495 = /*#__PURE__*/$7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...labelProps - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.Label, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, labelProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$76e48c5b57f24495, { - displayName: $d1bf075a6b218014$var$LABEL_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuItem - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$ITEM_NAME = 'DropdownMenuItem'; -const $d1bf075a6b218014$export$ed97964d1871885d = /*#__PURE__*/$7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...itemProps - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.Item, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, itemProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$ed97964d1871885d, { - displayName: $d1bf075a6b218014$var$ITEM_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuCheckboxItem - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$CHECKBOX_ITEM_NAME = 'DropdownMenuCheckboxItem'; -const $d1bf075a6b218014$export$53a69729da201fa9 = /*#__PURE__*/$7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...checkboxItemProps - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.CheckboxItem, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, checkboxItemProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$53a69729da201fa9, { - displayName: $d1bf075a6b218014$var$CHECKBOX_ITEM_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuRadioGroup - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$RADIO_GROUP_NAME = 'DropdownMenuRadioGroup'; -const $d1bf075a6b218014$export$3323ad73d55f587e = /*#__PURE__*/$7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...radioGroupProps - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.RadioGroup, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, radioGroupProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$3323ad73d55f587e, { - displayName: $d1bf075a6b218014$var$RADIO_GROUP_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuRadioItem - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$RADIO_ITEM_NAME = 'DropdownMenuRadioItem'; -const $d1bf075a6b218014$export$e4f69b41b1637536 = /*#__PURE__*/$7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...radioItemProps - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.RadioItem, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, radioItemProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$e4f69b41b1637536, { - displayName: $d1bf075a6b218014$var$RADIO_ITEM_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuItemIndicator - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$INDICATOR_NAME = 'DropdownMenuItemIndicator'; -const $d1bf075a6b218014$export$42355ae145153fb6 = /*#__PURE__*/$7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...itemIndicatorProps - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.ItemIndicator, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, itemIndicatorProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$42355ae145153fb6, { - displayName: $d1bf075a6b218014$var$INDICATOR_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuSeparator - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$SEPARATOR_NAME = 'DropdownMenuSeparator'; -const $d1bf075a6b218014$export$da160178fd3bc7e9 = /*#__PURE__*/$7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...separatorProps - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.Separator, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, separatorProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$da160178fd3bc7e9, { - displayName: $d1bf075a6b218014$var$SEPARATOR_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuArrow - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$ARROW_NAME = 'DropdownMenuArrow'; -const $d1bf075a6b218014$export$34b8980744021ec5 = /*#__PURE__*/$7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...arrowProps - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.Arrow, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, arrowProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$34b8980744021ec5, { - displayName: $d1bf075a6b218014$var$ARROW_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuSub - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$export$2f307d81a64f5442 = props => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - children: children, - open: openProp, - onOpenChange: onOpenChange, - defaultOpen: defaultOpen - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - const [open = false, setOpen] = $7dQ7Q$radixuireactusecontrollablestate.useControllableState({ - prop: openProp, - defaultProp: defaultOpen, - onChange: onOpenChange - }); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.Sub, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, { - open: open, - onOpenChange: setOpen - }), children); -}; -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuSubTrigger - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$SUB_TRIGGER_NAME = 'DropdownMenuSubTrigger'; -const $d1bf075a6b218014$export$21dcb7ec56f874cf = /*#__PURE__*/$7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...subTriggerProps - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.SubTrigger, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, subTriggerProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$21dcb7ec56f874cf, { - displayName: $d1bf075a6b218014$var$SUB_TRIGGER_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuSubContent - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$SUB_CONTENT_NAME = 'DropdownMenuSubContent'; -const $d1bf075a6b218014$export$f34ec8bc2482cc5f = /*#__PURE__*/$7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...subContentProps - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.SubContent, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, subContentProps, { - ref: forwardedRef, - style: { - ...props.style, - '--radix-dropdown-menu-content-transform-origin': 'var(--radix-popper-transform-origin)', - '--radix-dropdown-menu-content-available-width': 'var(--radix-popper-available-width)', - '--radix-dropdown-menu-content-available-height': 'var(--radix-popper-available-height)', - '--radix-dropdown-menu-trigger-width': 'var(--radix-popper-anchor-width)', - '--radix-dropdown-menu-trigger-height': 'var(--radix-popper-anchor-height)' - } - })); -}); -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$f34ec8bc2482cc5f, { - displayName: $d1bf075a6b218014$var$SUB_CONTENT_NAME -}); -/* -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$export$be92b6f5f03c0fe9 = $d1bf075a6b218014$export$e44a253a59704894; -const $d1bf075a6b218014$export$41fb9f06171c75f4 = $d1bf075a6b218014$export$d2469213b3befba9; -const $d1bf075a6b218014$export$602eac185826482c = $d1bf075a6b218014$export$cd369b4d4d54efc9; -const $d1bf075a6b218014$export$7c6e2c02157bb7d2 = $d1bf075a6b218014$export$6e76d93a37c01248; -const $d1bf075a6b218014$export$eb2fcfdbd7ba97d4 = $d1bf075a6b218014$export$246bebaba3a2f70e; -const $d1bf075a6b218014$export$b04be29aa201d4f5 = $d1bf075a6b218014$export$76e48c5b57f24495; -const $d1bf075a6b218014$export$6d08773d2e66f8f2 = $d1bf075a6b218014$export$ed97964d1871885d; -const $d1bf075a6b218014$export$16ce288f89fa631c = $d1bf075a6b218014$export$53a69729da201fa9; -const $d1bf075a6b218014$export$a98f0dcb43a68a25 = $d1bf075a6b218014$export$3323ad73d55f587e; -const $d1bf075a6b218014$export$371ab307eab489c0 = $d1bf075a6b218014$export$e4f69b41b1637536; -const $d1bf075a6b218014$export$c3468e2714d175fa = $d1bf075a6b218014$export$42355ae145153fb6; -const $d1bf075a6b218014$export$1ff3c3f08ae963c0 = $d1bf075a6b218014$export$da160178fd3bc7e9; -const $d1bf075a6b218014$export$21b07c8f274aebd5 = $d1bf075a6b218014$export$34b8980744021ec5; -const $d1bf075a6b218014$export$d7a01e11500dfb6f = $d1bf075a6b218014$export$2f307d81a64f5442; -const $d1bf075a6b218014$export$2ea8a7a591ac5eac = $d1bf075a6b218014$export$21dcb7ec56f874cf; -const $d1bf075a6b218014$export$6d4de93b380beddf = $d1bf075a6b218014$export$f34ec8bc2482cc5f; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-focus-guards/dist/index.js": -/*!************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-focus-guards/dist/index.js ***! - \************************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var $cnctE$react = __webpack_require__(/*! react */ "react"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -$parcel$export(module.exports, "FocusGuards", () => $71476a6ed7dbbaf3$export$ac5b58043b79449b); -$parcel$export(module.exports, "Root", () => $71476a6ed7dbbaf3$export$be92b6f5f03c0fe9); -$parcel$export(module.exports, "useFocusGuards", () => $71476a6ed7dbbaf3$export$b7ece24a22aeda8c); - -/** Number of components which have requested interest to have focus guards */ -let $71476a6ed7dbbaf3$var$count = 0; -function $71476a6ed7dbbaf3$export$ac5b58043b79449b(props) { - $71476a6ed7dbbaf3$export$b7ece24a22aeda8c(); - return props.children; -} -/** - * Injects a pair of focus guards at the edges of the whole DOM tree - * to ensure `focusin` & `focusout` events can be caught consistently. - */ -function $71476a6ed7dbbaf3$export$b7ece24a22aeda8c() { - $cnctE$react.useEffect(() => { - var _edgeGuards$, _edgeGuards$2; - const edgeGuards = document.querySelectorAll('[data-radix-focus-guard]'); - document.body.insertAdjacentElement('afterbegin', (_edgeGuards$ = edgeGuards[0]) !== null && _edgeGuards$ !== void 0 ? _edgeGuards$ : $71476a6ed7dbbaf3$var$createFocusGuard()); - document.body.insertAdjacentElement('beforeend', (_edgeGuards$2 = edgeGuards[1]) !== null && _edgeGuards$2 !== void 0 ? _edgeGuards$2 : $71476a6ed7dbbaf3$var$createFocusGuard()); - $71476a6ed7dbbaf3$var$count++; - return () => { - if ($71476a6ed7dbbaf3$var$count === 1) document.querySelectorAll('[data-radix-focus-guard]').forEach(node => node.remove()); - $71476a6ed7dbbaf3$var$count--; - }; - }, []); -} -function $71476a6ed7dbbaf3$var$createFocusGuard() { - const element = document.createElement('span'); - element.setAttribute('data-radix-focus-guard', ''); - element.tabIndex = 0; - element.style.cssText = 'outline: none; opacity: 0; position: fixed; pointer-events: none'; - return element; -} -const $71476a6ed7dbbaf3$export$be92b6f5f03c0fe9 = $71476a6ed7dbbaf3$export$ac5b58043b79449b; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-focus-scope/dist/index.js": -/*!***********************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-focus-scope/dist/index.js ***! - \***********************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var $buum9$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); -var $buum9$react = __webpack_require__(/*! react */ "react"); -var $buum9$radixuireactcomposerefs = __webpack_require__(/*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js"); -var $buum9$radixuireactprimitive = __webpack_require__(/*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js"); -var $buum9$radixuireactusecallbackref = __webpack_require__(/*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "FocusScope", () => $2bc01e66e04aa9ed$export$20e40289641fbbb6); -$parcel$export(module.exports, "Root", () => $2bc01e66e04aa9ed$export$be92b6f5f03c0fe9); -const $2bc01e66e04aa9ed$var$AUTOFOCUS_ON_MOUNT = 'focusScope.autoFocusOnMount'; -const $2bc01e66e04aa9ed$var$AUTOFOCUS_ON_UNMOUNT = 'focusScope.autoFocusOnUnmount'; -const $2bc01e66e04aa9ed$var$EVENT_OPTIONS = { - bubbles: false, - cancelable: true -}; -/* ------------------------------------------------------------------------------------------------- - * FocusScope - * -----------------------------------------------------------------------------------------------*/ -const $2bc01e66e04aa9ed$var$FOCUS_SCOPE_NAME = 'FocusScope'; -const $2bc01e66e04aa9ed$export$20e40289641fbbb6 = /*#__PURE__*/$buum9$react.forwardRef((props, forwardedRef) => { - const { - loop = false, - trapped = false, - onMountAutoFocus: onMountAutoFocusProp, - onUnmountAutoFocus: onUnmountAutoFocusProp, - ...scopeProps - } = props; - const [container1, setContainer] = $buum9$react.useState(null); - const onMountAutoFocus = $buum9$radixuireactusecallbackref.useCallbackRef(onMountAutoFocusProp); - const onUnmountAutoFocus = $buum9$radixuireactusecallbackref.useCallbackRef(onUnmountAutoFocusProp); - const lastFocusedElementRef = $buum9$react.useRef(null); - const composedRefs = $buum9$radixuireactcomposerefs.useComposedRefs(forwardedRef, node => setContainer(node)); - const focusScope = $buum9$react.useRef({ - paused: false, - pause() { - this.paused = true; - }, - resume() { - this.paused = false; - } - }).current; // Takes care of trapping focus if focus is moved outside programmatically for example - $buum9$react.useEffect(() => { - if (trapped) { - function handleFocusIn(event) { - if (focusScope.paused || !container1) return; - const target = event.target; - if (container1.contains(target)) lastFocusedElementRef.current = target;else $2bc01e66e04aa9ed$var$focus(lastFocusedElementRef.current, { - select: true - }); - } - function handleFocusOut(event) { - if (focusScope.paused || !container1) return; - const relatedTarget = event.relatedTarget; // A `focusout` event with a `null` `relatedTarget` will happen in at least two cases: - // - // 1. When the user switches app/tabs/windows/the browser itself loses focus. - // 2. In Google Chrome, when the focused element is removed from the DOM. - // - // We let the browser do its thing here because: - // - // 1. The browser already keeps a memory of what's focused for when the page gets refocused. - // 2. In Google Chrome, if we try to focus the deleted focused element (as per below), it - // throws the CPU to 100%, so we avoid doing anything for this reason here too. - if (relatedTarget === null) return; // If the focus has moved to an actual legitimate element (`relatedTarget !== null`) - // that is outside the container, we move focus to the last valid focused element inside. - if (!container1.contains(relatedTarget)) $2bc01e66e04aa9ed$var$focus(lastFocusedElementRef.current, { - select: true - }); - } // When the focused element gets removed from the DOM, browsers move focus - // back to the document.body. In this case, we move focus to the container - // to keep focus trapped correctly. - function handleMutations(mutations) { - const focusedElement = document.activeElement; - for (const mutation of mutations) { - if (mutation.removedNodes.length > 0) { - if (!(container1 !== null && container1 !== void 0 && container1.contains(focusedElement))) $2bc01e66e04aa9ed$var$focus(container1); - } - } - } - document.addEventListener('focusin', handleFocusIn); - document.addEventListener('focusout', handleFocusOut); - const mutationObserver = new MutationObserver(handleMutations); - if (container1) mutationObserver.observe(container1, { - childList: true, - subtree: true - }); - return () => { - document.removeEventListener('focusin', handleFocusIn); - document.removeEventListener('focusout', handleFocusOut); - mutationObserver.disconnect(); - }; - } - }, [trapped, container1, focusScope.paused]); - $buum9$react.useEffect(() => { - if (container1) { - $2bc01e66e04aa9ed$var$focusScopesStack.add(focusScope); - const previouslyFocusedElement = document.activeElement; - const hasFocusedCandidate = container1.contains(previouslyFocusedElement); - if (!hasFocusedCandidate) { - const mountEvent = new CustomEvent($2bc01e66e04aa9ed$var$AUTOFOCUS_ON_MOUNT, $2bc01e66e04aa9ed$var$EVENT_OPTIONS); - container1.addEventListener($2bc01e66e04aa9ed$var$AUTOFOCUS_ON_MOUNT, onMountAutoFocus); - container1.dispatchEvent(mountEvent); - if (!mountEvent.defaultPrevented) { - $2bc01e66e04aa9ed$var$focusFirst($2bc01e66e04aa9ed$var$removeLinks($2bc01e66e04aa9ed$var$getTabbableCandidates(container1)), { - select: true - }); - if (document.activeElement === previouslyFocusedElement) $2bc01e66e04aa9ed$var$focus(container1); - } - } - return () => { - container1.removeEventListener($2bc01e66e04aa9ed$var$AUTOFOCUS_ON_MOUNT, onMountAutoFocus); // We hit a react bug (fixed in v17) with focusing in unmount. - // We need to delay the focus a little to get around it for now. - // See: https://github.com/facebook/react/issues/17894 - setTimeout(() => { - const unmountEvent = new CustomEvent($2bc01e66e04aa9ed$var$AUTOFOCUS_ON_UNMOUNT, $2bc01e66e04aa9ed$var$EVENT_OPTIONS); - container1.addEventListener($2bc01e66e04aa9ed$var$AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus); - container1.dispatchEvent(unmountEvent); - if (!unmountEvent.defaultPrevented) $2bc01e66e04aa9ed$var$focus(previouslyFocusedElement !== null && previouslyFocusedElement !== void 0 ? previouslyFocusedElement : document.body, { - select: true - }); - // we need to remove the listener after we `dispatchEvent` - container1.removeEventListener($2bc01e66e04aa9ed$var$AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus); - $2bc01e66e04aa9ed$var$focusScopesStack.remove(focusScope); - }, 0); - }; - } - }, [container1, onMountAutoFocus, onUnmountAutoFocus, focusScope]); // Takes care of looping focus (when tabbing whilst at the edges) - const handleKeyDown = $buum9$react.useCallback(event => { - if (!loop && !trapped) return; - if (focusScope.paused) return; - const isTabKey = event.key === 'Tab' && !event.altKey && !event.ctrlKey && !event.metaKey; - const focusedElement = document.activeElement; - if (isTabKey && focusedElement) { - const container = event.currentTarget; - const [first, last] = $2bc01e66e04aa9ed$var$getTabbableEdges(container); - const hasTabbableElementsInside = first && last; // we can only wrap focus if we have tabbable edges - if (!hasTabbableElementsInside) { - if (focusedElement === container) event.preventDefault(); - } else { - if (!event.shiftKey && focusedElement === last) { - event.preventDefault(); - if (loop) $2bc01e66e04aa9ed$var$focus(first, { - select: true - }); - } else if (event.shiftKey && focusedElement === first) { - event.preventDefault(); - if (loop) $2bc01e66e04aa9ed$var$focus(last, { - select: true - }); - } - } - } - }, [loop, trapped, focusScope.paused]); - return /*#__PURE__*/$buum9$react.createElement($buum9$radixuireactprimitive.Primitive.div, $parcel$interopDefault($buum9$babelruntimehelpersextends)({ - tabIndex: -1 - }, scopeProps, { - ref: composedRefs, - onKeyDown: handleKeyDown - })); -}); -/*#__PURE__*/ -Object.assign($2bc01e66e04aa9ed$export$20e40289641fbbb6, { - displayName: $2bc01e66e04aa9ed$var$FOCUS_SCOPE_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * Utils - * -----------------------------------------------------------------------------------------------*/ /** - * Attempts focusing the first element in a list of candidates. - * Stops when focus has actually moved. - */ -function $2bc01e66e04aa9ed$var$focusFirst(candidates, { - select = false -} = {}) { - const previouslyFocusedElement = document.activeElement; - for (const candidate of candidates) { - $2bc01e66e04aa9ed$var$focus(candidate, { - select: select - }); - if (document.activeElement !== previouslyFocusedElement) return; - } -} -/** - * Returns the first and last tabbable elements inside a container. - */ -function $2bc01e66e04aa9ed$var$getTabbableEdges(container) { - const candidates = $2bc01e66e04aa9ed$var$getTabbableCandidates(container); - const first = $2bc01e66e04aa9ed$var$findVisible(candidates, container); - const last = $2bc01e66e04aa9ed$var$findVisible(candidates.reverse(), container); - return [first, last]; -} -/** - * Returns a list of potential tabbable candidates. - * - * NOTE: This is only a close approximation. For example it doesn't take into account cases like when - * elements are not visible. This cannot be worked out easily by just reading a property, but rather - * necessitate runtime knowledge (computed styles, etc). We deal with these cases separately. - * - * See: https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker - * Credit: https://github.com/discord/focus-layers/blob/master/src/util/wrapFocus.tsx#L1 - */ -function $2bc01e66e04aa9ed$var$getTabbableCandidates(container) { - const nodes = []; - const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, { - acceptNode: node => { - const isHiddenInput = node.tagName === 'INPUT' && node.type === 'hidden'; - if (node.disabled || node.hidden || isHiddenInput) return NodeFilter.FILTER_SKIP; // `.tabIndex` is not the same as the `tabindex` attribute. It works on the - // runtime's understanding of tabbability, so this automatically accounts - // for any kind of element that could be tabbed to. - return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP; - } - }); - while (walker.nextNode()) nodes.push(walker.currentNode); // we do not take into account the order of nodes with positive `tabIndex` as it - // hinders accessibility to have tab order different from visual order. - return nodes; -} -/** - * Returns the first visible element in a list. - * NOTE: Only checks visibility up to the `container`. - */ -function $2bc01e66e04aa9ed$var$findVisible(elements, container) { - for (const element of elements) { - // we stop checking if it's hidden at the `container` level (excluding) - if (!$2bc01e66e04aa9ed$var$isHidden(element, { - upTo: container - })) return element; - } -} -function $2bc01e66e04aa9ed$var$isHidden(node, { - upTo: upTo -}) { - if (getComputedStyle(node).visibility === 'hidden') return true; - while (node) { - // we stop at `upTo` (excluding it) - if (upTo !== undefined && node === upTo) return false; - if (getComputedStyle(node).display === 'none') return true; - node = node.parentElement; - } - return false; -} -function $2bc01e66e04aa9ed$var$isSelectableInput(element) { - return element instanceof HTMLInputElement && 'select' in element; -} -function $2bc01e66e04aa9ed$var$focus(element, { - select = false -} = {}) { - // only focus if that element is focusable - if (element && element.focus) { - const previouslyFocusedElement = document.activeElement; // NOTE: we prevent scrolling on focus, to minimize jarring transitions for users - element.focus({ - preventScroll: true - }); // only select if its not the same element, it supports selection and we need to select - if (element !== previouslyFocusedElement && $2bc01e66e04aa9ed$var$isSelectableInput(element) && select) element.select(); - } -} -/* ------------------------------------------------------------------------------------------------- - * FocusScope stack - * -----------------------------------------------------------------------------------------------*/ -const $2bc01e66e04aa9ed$var$focusScopesStack = $2bc01e66e04aa9ed$var$createFocusScopesStack(); -function $2bc01e66e04aa9ed$var$createFocusScopesStack() { - /** A stack of focus scopes, with the active one at the top */let stack = []; - return { - add(focusScope) { - // pause the currently active focus scope (at the top of the stack) - const activeFocusScope = stack[0]; - if (focusScope !== activeFocusScope) activeFocusScope === null || activeFocusScope === void 0 || activeFocusScope.pause(); - // remove in case it already exists (because we'll re-add it at the top of the stack) - stack = $2bc01e66e04aa9ed$var$arrayRemove(stack, focusScope); - stack.unshift(focusScope); - }, - remove(focusScope) { - var _stack$; - stack = $2bc01e66e04aa9ed$var$arrayRemove(stack, focusScope); - (_stack$ = stack[0]) === null || _stack$ === void 0 || _stack$.resume(); - } - }; -} -function $2bc01e66e04aa9ed$var$arrayRemove(array, item) { - const updatedArray = [...array]; - const index = updatedArray.indexOf(item); - if (index !== -1) updatedArray.splice(index, 1); - return updatedArray; -} -function $2bc01e66e04aa9ed$var$removeLinks(items) { - return items.filter(item => item.tagName !== 'A'); -} -const $2bc01e66e04aa9ed$export$be92b6f5f03c0fe9 = $2bc01e66e04aa9ed$export$20e40289641fbbb6; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-id/dist/index.js": -/*!**************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-id/dist/index.js ***! - \**************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var $47woD$react = __webpack_require__(/*! react */ "react"); -var $47woD$radixuireactuselayouteffect = __webpack_require__(/*! @radix-ui/react-use-layout-effect */ "../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -$parcel$export(module.exports, "useId", () => $dc478e4659f630c5$export$f680877a34711e37); -const $dc478e4659f630c5$var$useReactId = $47woD$react['useId'.toString()] || (() => undefined); -let $dc478e4659f630c5$var$count = 0; -function $dc478e4659f630c5$export$f680877a34711e37(deterministicId) { - const [id, setId] = $47woD$react.useState($dc478e4659f630c5$var$useReactId()); // React versions older than 18 will have client-side ids only. - $47woD$radixuireactuselayouteffect.useLayoutEffect(() => { - if (!deterministicId) setId(reactId => reactId !== null && reactId !== void 0 ? reactId : String($dc478e4659f630c5$var$count++)); - }, [deterministicId]); - return deterministicId || (id ? `radix-${id}` : ''); -} - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-menu/dist/index.js": -/*!****************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-menu/dist/index.js ***! - \****************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var $cnSS2$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); -var $cnSS2$react = __webpack_require__(/*! react */ "react"); -var $cnSS2$radixuiprimitive = __webpack_require__(/*! @radix-ui/primitive */ "../../../node_modules/@radix-ui/primitive/dist/index.js"); -var $cnSS2$radixuireactcollection = __webpack_require__(/*! @radix-ui/react-collection */ "../../../node_modules/@radix-ui/react-collection/dist/index.js"); -var $cnSS2$radixuireactcomposerefs = __webpack_require__(/*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js"); -var $cnSS2$radixuireactcontext = __webpack_require__(/*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js"); -var $cnSS2$radixuireactdirection = __webpack_require__(/*! @radix-ui/react-direction */ "../../../node_modules/@radix-ui/react-direction/dist/index.js"); -var $cnSS2$radixuireactdismissablelayer = __webpack_require__(/*! @radix-ui/react-dismissable-layer */ "../../../node_modules/@radix-ui/react-dismissable-layer/dist/index.js"); -var $cnSS2$radixuireactfocusguards = __webpack_require__(/*! @radix-ui/react-focus-guards */ "../../../node_modules/@radix-ui/react-focus-guards/dist/index.js"); -var $cnSS2$radixuireactfocusscope = __webpack_require__(/*! @radix-ui/react-focus-scope */ "../../../node_modules/@radix-ui/react-focus-scope/dist/index.js"); -var $cnSS2$radixuireactid = __webpack_require__(/*! @radix-ui/react-id */ "../../../node_modules/@radix-ui/react-id/dist/index.js"); -var $cnSS2$radixuireactpopper = __webpack_require__(/*! @radix-ui/react-popper */ "../../../node_modules/@radix-ui/react-popper/dist/index.js"); -var $cnSS2$radixuireactportal = __webpack_require__(/*! @radix-ui/react-portal */ "../../../node_modules/@radix-ui/react-portal/dist/index.js"); -var $cnSS2$radixuireactpresence = __webpack_require__(/*! @radix-ui/react-presence */ "../../../node_modules/@radix-ui/react-presence/dist/index.js"); -var $cnSS2$radixuireactprimitive = __webpack_require__(/*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js"); -var $cnSS2$radixuireactrovingfocus = __webpack_require__(/*! @radix-ui/react-roving-focus */ "../../../node_modules/@radix-ui/react-roving-focus/dist/index.js"); -var $cnSS2$radixuireactslot = __webpack_require__(/*! @radix-ui/react-slot */ "../../../node_modules/@radix-ui/react-slot/dist/index.js"); -var $cnSS2$radixuireactusecallbackref = __webpack_require__(/*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js"); -var $cnSS2$ariahidden = __webpack_require__(/*! aria-hidden */ "../../../node_modules/aria-hidden/dist/es2015/index.js"); -var $cnSS2$reactremovescroll = __webpack_require__(/*! react-remove-scroll */ "../../../node_modules/react-remove-scroll/dist/es2015/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "createMenuScope", () => $213e4d2df823067d$export$4027731b685e72eb); -$parcel$export(module.exports, "Menu", () => $213e4d2df823067d$export$d9b273488cd8ce6f); -$parcel$export(module.exports, "MenuAnchor", () => $213e4d2df823067d$export$9fa5ebd18bee4d43); -$parcel$export(module.exports, "MenuPortal", () => $213e4d2df823067d$export$793392f970497feb); -$parcel$export(module.exports, "MenuContent", () => $213e4d2df823067d$export$479f0f2f71193efe); -$parcel$export(module.exports, "MenuGroup", () => $213e4d2df823067d$export$22a631d1f72787bb); -$parcel$export(module.exports, "MenuLabel", () => $213e4d2df823067d$export$dd37bec0e8a99143); -$parcel$export(module.exports, "MenuItem", () => $213e4d2df823067d$export$2ce376c2cc3355c8); -$parcel$export(module.exports, "MenuCheckboxItem", () => $213e4d2df823067d$export$f6f243521332502d); -$parcel$export(module.exports, "MenuRadioGroup", () => $213e4d2df823067d$export$ea2200c9eee416b3); -$parcel$export(module.exports, "MenuRadioItem", () => $213e4d2df823067d$export$69bd225e9817f6d0); -$parcel$export(module.exports, "MenuItemIndicator", () => $213e4d2df823067d$export$a2593e23056970a3); -$parcel$export(module.exports, "MenuSeparator", () => $213e4d2df823067d$export$1cec7dcdd713e220); -$parcel$export(module.exports, "MenuArrow", () => $213e4d2df823067d$export$bcdda4773debf5fa); -$parcel$export(module.exports, "MenuSub", () => $213e4d2df823067d$export$71bdb9d1e2909932); -$parcel$export(module.exports, "MenuSubTrigger", () => $213e4d2df823067d$export$5fbbb3ba7297405f); -$parcel$export(module.exports, "MenuSubContent", () => $213e4d2df823067d$export$e7142ab31822bde6); -$parcel$export(module.exports, "Root", () => $213e4d2df823067d$export$be92b6f5f03c0fe9); -$parcel$export(module.exports, "Anchor", () => $213e4d2df823067d$export$b688253958b8dfe7); -$parcel$export(module.exports, "Portal", () => $213e4d2df823067d$export$602eac185826482c); -$parcel$export(module.exports, "Content", () => $213e4d2df823067d$export$7c6e2c02157bb7d2); -$parcel$export(module.exports, "Group", () => $213e4d2df823067d$export$eb2fcfdbd7ba97d4); -$parcel$export(module.exports, "Label", () => $213e4d2df823067d$export$b04be29aa201d4f5); -$parcel$export(module.exports, "Item", () => $213e4d2df823067d$export$6d08773d2e66f8f2); -$parcel$export(module.exports, "CheckboxItem", () => $213e4d2df823067d$export$16ce288f89fa631c); -$parcel$export(module.exports, "RadioGroup", () => $213e4d2df823067d$export$a98f0dcb43a68a25); -$parcel$export(module.exports, "RadioItem", () => $213e4d2df823067d$export$371ab307eab489c0); -$parcel$export(module.exports, "ItemIndicator", () => $213e4d2df823067d$export$c3468e2714d175fa); -$parcel$export(module.exports, "Separator", () => $213e4d2df823067d$export$1ff3c3f08ae963c0); -$parcel$export(module.exports, "Arrow", () => $213e4d2df823067d$export$21b07c8f274aebd5); -$parcel$export(module.exports, "Sub", () => $213e4d2df823067d$export$d7a01e11500dfb6f); -$parcel$export(module.exports, "SubTrigger", () => $213e4d2df823067d$export$2ea8a7a591ac5eac); -$parcel$export(module.exports, "SubContent", () => $213e4d2df823067d$export$6d4de93b380beddf); -const $213e4d2df823067d$var$SELECTION_KEYS = ['Enter', ' ']; -const $213e4d2df823067d$var$FIRST_KEYS = ['ArrowDown', 'PageUp', 'Home']; -const $213e4d2df823067d$var$LAST_KEYS = ['ArrowUp', 'PageDown', 'End']; -const $213e4d2df823067d$var$FIRST_LAST_KEYS = [...$213e4d2df823067d$var$FIRST_KEYS, ...$213e4d2df823067d$var$LAST_KEYS]; -const $213e4d2df823067d$var$SUB_OPEN_KEYS = { - ltr: [...$213e4d2df823067d$var$SELECTION_KEYS, 'ArrowRight'], - rtl: [...$213e4d2df823067d$var$SELECTION_KEYS, 'ArrowLeft'] -}; -const $213e4d2df823067d$var$SUB_CLOSE_KEYS = { - ltr: ['ArrowLeft'], - rtl: ['ArrowRight'] -}; -/* ------------------------------------------------------------------------------------------------- - * Menu - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$MENU_NAME = 'Menu'; -const [$213e4d2df823067d$var$Collection, $213e4d2df823067d$var$useCollection, $213e4d2df823067d$var$createCollectionScope] = $cnSS2$radixuireactcollection.createCollection($213e4d2df823067d$var$MENU_NAME); -const [$213e4d2df823067d$var$createMenuContext, $213e4d2df823067d$export$4027731b685e72eb] = $cnSS2$radixuireactcontext.createContextScope($213e4d2df823067d$var$MENU_NAME, [$213e4d2df823067d$var$createCollectionScope, $cnSS2$radixuireactpopper.createPopperScope, $cnSS2$radixuireactrovingfocus.createRovingFocusGroupScope]); -const $213e4d2df823067d$var$usePopperScope = $cnSS2$radixuireactpopper.createPopperScope(); -const $213e4d2df823067d$var$useRovingFocusGroupScope = $cnSS2$radixuireactrovingfocus.createRovingFocusGroupScope(); -const [$213e4d2df823067d$var$MenuProvider, $213e4d2df823067d$var$useMenuContext] = $213e4d2df823067d$var$createMenuContext($213e4d2df823067d$var$MENU_NAME); -const [$213e4d2df823067d$var$MenuRootProvider, $213e4d2df823067d$var$useMenuRootContext] = $213e4d2df823067d$var$createMenuContext($213e4d2df823067d$var$MENU_NAME); -const $213e4d2df823067d$export$d9b273488cd8ce6f = props => { - const { - __scopeMenu: __scopeMenu, - open = false, - children: children, - dir: dir, - onOpenChange: onOpenChange, - modal = true - } = props; - const popperScope = $213e4d2df823067d$var$usePopperScope(__scopeMenu); - const [content, setContent] = $cnSS2$react.useState(null); - const isUsingKeyboardRef = $cnSS2$react.useRef(false); - const handleOpenChange = $cnSS2$radixuireactusecallbackref.useCallbackRef(onOpenChange); - const direction = $cnSS2$radixuireactdirection.useDirection(dir); - $cnSS2$react.useEffect(() => { - // Capture phase ensures we set the boolean before any side effects execute - // in response to the key or pointer event as they might depend on this value. - const handleKeyDown = () => { - isUsingKeyboardRef.current = true; - document.addEventListener('pointerdown', handlePointer, { - capture: true, - once: true - }); - document.addEventListener('pointermove', handlePointer, { - capture: true, - once: true - }); - }; - const handlePointer = () => isUsingKeyboardRef.current = false; - document.addEventListener('keydown', handleKeyDown, { - capture: true - }); - return () => { - document.removeEventListener('keydown', handleKeyDown, { - capture: true - }); - document.removeEventListener('pointerdown', handlePointer, { - capture: true - }); - document.removeEventListener('pointermove', handlePointer, { - capture: true - }); - }; - }, []); - return /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactpopper.Root, popperScope, /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$MenuProvider, { - scope: __scopeMenu, - open: open, - onOpenChange: handleOpenChange, - content: content, - onContentChange: setContent - }, /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$MenuRootProvider, { - scope: __scopeMenu, - onClose: $cnSS2$react.useCallback(() => handleOpenChange(false), [handleOpenChange]), - isUsingKeyboardRef: isUsingKeyboardRef, - dir: direction, - modal: modal - }, children))); -}; -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$d9b273488cd8ce6f, { - displayName: $213e4d2df823067d$var$MENU_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuAnchor - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$ANCHOR_NAME = 'MenuAnchor'; -const $213e4d2df823067d$export$9fa5ebd18bee4d43 = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const { - __scopeMenu: __scopeMenu, - ...anchorProps - } = props; - const popperScope = $213e4d2df823067d$var$usePopperScope(__scopeMenu); - return /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactpopper.Anchor, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({}, popperScope, anchorProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$9fa5ebd18bee4d43, { - displayName: $213e4d2df823067d$var$ANCHOR_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuPortal - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$PORTAL_NAME = 'MenuPortal'; -const [$213e4d2df823067d$var$PortalProvider, $213e4d2df823067d$var$usePortalContext] = $213e4d2df823067d$var$createMenuContext($213e4d2df823067d$var$PORTAL_NAME, { - forceMount: undefined -}); -const $213e4d2df823067d$export$793392f970497feb = props => { - const { - __scopeMenu: __scopeMenu, - forceMount: forceMount, - children: children, - container: container - } = props; - const context = $213e4d2df823067d$var$useMenuContext($213e4d2df823067d$var$PORTAL_NAME, __scopeMenu); - return /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$PortalProvider, { - scope: __scopeMenu, - forceMount: forceMount - }, /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactpresence.Presence, { - present: forceMount || context.open - }, /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactportal.Portal, { - asChild: true, - container: container - }, children))); -}; -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$793392f970497feb, { - displayName: $213e4d2df823067d$var$PORTAL_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuContent - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$CONTENT_NAME = 'MenuContent'; -const [$213e4d2df823067d$var$MenuContentProvider, $213e4d2df823067d$var$useMenuContentContext] = $213e4d2df823067d$var$createMenuContext($213e4d2df823067d$var$CONTENT_NAME); -const $213e4d2df823067d$export$479f0f2f71193efe = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const portalContext = $213e4d2df823067d$var$usePortalContext($213e4d2df823067d$var$CONTENT_NAME, props.__scopeMenu); - const { - forceMount = portalContext.forceMount, - ...contentProps - } = props; - const context = $213e4d2df823067d$var$useMenuContext($213e4d2df823067d$var$CONTENT_NAME, props.__scopeMenu); - const rootContext = $213e4d2df823067d$var$useMenuRootContext($213e4d2df823067d$var$CONTENT_NAME, props.__scopeMenu); - return /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$Collection.Provider, { - scope: props.__scopeMenu - }, /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactpresence.Presence, { - present: forceMount || context.open - }, /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$Collection.Slot, { - scope: props.__scopeMenu - }, rootContext.modal ? /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$MenuRootContentModal, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({}, contentProps, { - ref: forwardedRef - })) : /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$MenuRootContentNonModal, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({}, contentProps, { - ref: forwardedRef - }))))); -}); -/* ---------------------------------------------------------------------------------------------- */ -const $213e4d2df823067d$var$MenuRootContentModal = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const context = $213e4d2df823067d$var$useMenuContext($213e4d2df823067d$var$CONTENT_NAME, props.__scopeMenu); - const ref = $cnSS2$react.useRef(null); - const composedRefs = $cnSS2$radixuireactcomposerefs.useComposedRefs(forwardedRef, ref); // Hide everything from ARIA except the `MenuContent` - $cnSS2$react.useEffect(() => { - const content = ref.current; - if (content) return $cnSS2$ariahidden.hideOthers(content); - }, []); - return /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$MenuContentImpl, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({}, props, { - ref: composedRefs // we make sure we're not trapping once it's been closed - , - - trapFocus: context.open // make sure to only disable pointer events when open - , - - disableOutsidePointerEvents: context.open, - disableOutsideScroll: true // When focus is trapped, a `focusout` event may still happen. - , - - onFocusOutside: $cnSS2$radixuiprimitive.composeEventHandlers(props.onFocusOutside, event => event.preventDefault(), { - checkForDefaultPrevented: false - }), - onDismiss: () => context.onOpenChange(false) - })); -}); -const $213e4d2df823067d$var$MenuRootContentNonModal = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const context = $213e4d2df823067d$var$useMenuContext($213e4d2df823067d$var$CONTENT_NAME, props.__scopeMenu); - return /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$MenuContentImpl, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({}, props, { - ref: forwardedRef, - trapFocus: false, - disableOutsidePointerEvents: false, - disableOutsideScroll: false, - onDismiss: () => context.onOpenChange(false) - })); -}); -/* ---------------------------------------------------------------------------------------------- */ -const $213e4d2df823067d$var$MenuContentImpl = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const { - __scopeMenu: __scopeMenu, - loop = false, - trapFocus: trapFocus, - onOpenAutoFocus: onOpenAutoFocus, - onCloseAutoFocus: onCloseAutoFocus, - disableOutsidePointerEvents: disableOutsidePointerEvents, - onEntryFocus: onEntryFocus, - onEscapeKeyDown: onEscapeKeyDown, - onPointerDownOutside: onPointerDownOutside, - onFocusOutside: onFocusOutside, - onInteractOutside: onInteractOutside, - onDismiss: onDismiss, - disableOutsideScroll: disableOutsideScroll, - ...contentProps - } = props; - const context = $213e4d2df823067d$var$useMenuContext($213e4d2df823067d$var$CONTENT_NAME, __scopeMenu); - const rootContext = $213e4d2df823067d$var$useMenuRootContext($213e4d2df823067d$var$CONTENT_NAME, __scopeMenu); - const popperScope = $213e4d2df823067d$var$usePopperScope(__scopeMenu); - const rovingFocusGroupScope = $213e4d2df823067d$var$useRovingFocusGroupScope(__scopeMenu); - const getItems = $213e4d2df823067d$var$useCollection(__scopeMenu); - const [currentItemId, setCurrentItemId] = $cnSS2$react.useState(null); - const contentRef = $cnSS2$react.useRef(null); - const composedRefs = $cnSS2$radixuireactcomposerefs.useComposedRefs(forwardedRef, contentRef, context.onContentChange); - const timerRef = $cnSS2$react.useRef(0); - const searchRef = $cnSS2$react.useRef(''); - const pointerGraceTimerRef = $cnSS2$react.useRef(0); - const pointerGraceIntentRef = $cnSS2$react.useRef(null); - const pointerDirRef = $cnSS2$react.useRef('right'); - const lastPointerXRef = $cnSS2$react.useRef(0); - const ScrollLockWrapper = disableOutsideScroll ? $cnSS2$reactremovescroll.RemoveScroll : $cnSS2$react.Fragment; - const scrollLockWrapperProps = disableOutsideScroll ? { - as: $cnSS2$radixuireactslot.Slot, - allowPinchZoom: true - } : undefined; - const handleTypeaheadSearch = key => { - var _items$find, _items$find2; - const search = searchRef.current + key; - const items = getItems().filter(item => !item.disabled); - const currentItem = document.activeElement; - const currentMatch = (_items$find = items.find(item => item.ref.current === currentItem)) === null || _items$find === void 0 ? void 0 : _items$find.textValue; - const values = items.map(item => item.textValue); - const nextMatch = $213e4d2df823067d$var$getNextMatch(values, search, currentMatch); - const newItem = (_items$find2 = items.find(item => item.textValue === nextMatch)) === null || _items$find2 === void 0 ? void 0 : _items$find2.ref.current; // Reset `searchRef` 1 second after it was last updated - (function updateSearch(value) { - searchRef.current = value; - window.clearTimeout(timerRef.current); - if (value !== '') timerRef.current = window.setTimeout(() => updateSearch(''), 1000); - })(search); - if (newItem) - /** - * Imperative focus during keydown is risky so we prevent React's batching updates - * to avoid potential bugs. See: https://github.com/facebook/react/issues/20332 - */ - setTimeout(() => newItem.focus()); - }; - $cnSS2$react.useEffect(() => { - return () => window.clearTimeout(timerRef.current); - }, []); // Make sure the whole tree has focus guards as our `MenuContent` may be - // the last element in the DOM (beacuse of the `Portal`) - $cnSS2$radixuireactfocusguards.useFocusGuards(); - const isPointerMovingToSubmenu = $cnSS2$react.useCallback(event => { - var _pointerGraceIntentRe, _pointerGraceIntentRe2; - const isMovingTowards = pointerDirRef.current === ((_pointerGraceIntentRe = pointerGraceIntentRef.current) === null || _pointerGraceIntentRe === void 0 ? void 0 : _pointerGraceIntentRe.side); - return isMovingTowards && $213e4d2df823067d$var$isPointerInGraceArea(event, (_pointerGraceIntentRe2 = pointerGraceIntentRef.current) === null || _pointerGraceIntentRe2 === void 0 ? void 0 : _pointerGraceIntentRe2.area); - }, []); - return /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$MenuContentProvider, { - scope: __scopeMenu, - searchRef: searchRef, - onItemEnter: $cnSS2$react.useCallback(event => { - if (isPointerMovingToSubmenu(event)) event.preventDefault(); - }, [isPointerMovingToSubmenu]), - onItemLeave: $cnSS2$react.useCallback(event => { - var _contentRef$current; - if (isPointerMovingToSubmenu(event)) return; - (_contentRef$current = contentRef.current) === null || _contentRef$current === void 0 || _contentRef$current.focus(); - setCurrentItemId(null); - }, [isPointerMovingToSubmenu]), - onTriggerLeave: $cnSS2$react.useCallback(event => { - if (isPointerMovingToSubmenu(event)) event.preventDefault(); - }, [isPointerMovingToSubmenu]), - pointerGraceTimerRef: pointerGraceTimerRef, - onPointerGraceIntentChange: $cnSS2$react.useCallback(intent => { - pointerGraceIntentRef.current = intent; - }, []) - }, /*#__PURE__*/$cnSS2$react.createElement(ScrollLockWrapper, scrollLockWrapperProps, /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactfocusscope.FocusScope, { - asChild: true, - trapped: trapFocus, - onMountAutoFocus: $cnSS2$radixuiprimitive.composeEventHandlers(onOpenAutoFocus, event => { - var _contentRef$current2; - // when opening, explicitly focus the content area only and leave - // `onEntryFocus` in control of focusing first item - event.preventDefault(); - (_contentRef$current2 = contentRef.current) === null || _contentRef$current2 === void 0 || _contentRef$current2.focus(); - }), - onUnmountAutoFocus: onCloseAutoFocus - }, /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactdismissablelayer.DismissableLayer, { - asChild: true, - disableOutsidePointerEvents: disableOutsidePointerEvents, - onEscapeKeyDown: onEscapeKeyDown, - onPointerDownOutside: onPointerDownOutside, - onFocusOutside: onFocusOutside, - onInteractOutside: onInteractOutside, - onDismiss: onDismiss - }, /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactrovingfocus.Root, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({ - asChild: true - }, rovingFocusGroupScope, { - dir: rootContext.dir, - orientation: "vertical", - loop: loop, - currentTabStopId: currentItemId, - onCurrentTabStopIdChange: setCurrentItemId, - onEntryFocus: $cnSS2$radixuiprimitive.composeEventHandlers(onEntryFocus, event => { - // only focus first item when using keyboard - if (!rootContext.isUsingKeyboardRef.current) event.preventDefault(); - }) - }), /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactpopper.Content, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({ - role: "menu", - "aria-orientation": "vertical", - "data-state": $213e4d2df823067d$var$getOpenState(context.open), - "data-radix-menu-content": "", - dir: rootContext.dir - }, popperScope, contentProps, { - ref: composedRefs, - style: { - outline: 'none', - ...contentProps.style - }, - onKeyDown: $cnSS2$radixuiprimitive.composeEventHandlers(contentProps.onKeyDown, event => { - // submenu key events bubble through portals. We only care about keys in this menu. - const target = event.target; - const isKeyDownInside = target.closest('[data-radix-menu-content]') === event.currentTarget; - const isModifierKey = event.ctrlKey || event.altKey || event.metaKey; - const isCharacterKey = event.key.length === 1; - if (isKeyDownInside) { - // menus should not be navigated using tab key so we prevent it - if (event.key === 'Tab') event.preventDefault(); - if (!isModifierKey && isCharacterKey) handleTypeaheadSearch(event.key); - } // focus first/last item based on key pressed - const content = contentRef.current; - if (event.target !== content) return; - if (!$213e4d2df823067d$var$FIRST_LAST_KEYS.includes(event.key)) return; - event.preventDefault(); - const items = getItems().filter(item => !item.disabled); - const candidateNodes = items.map(item => item.ref.current); - if ($213e4d2df823067d$var$LAST_KEYS.includes(event.key)) candidateNodes.reverse(); - $213e4d2df823067d$var$focusFirst(candidateNodes); - }), - onBlur: $cnSS2$radixuiprimitive.composeEventHandlers(props.onBlur, event => { - // clear search buffer when leaving the menu - if (!event.currentTarget.contains(event.target)) { - window.clearTimeout(timerRef.current); - searchRef.current = ''; - } - }), - onPointerMove: $cnSS2$radixuiprimitive.composeEventHandlers(props.onPointerMove, $213e4d2df823067d$var$whenMouse(event => { - const target = event.target; - const pointerXHasChanged = lastPointerXRef.current !== event.clientX; // We don't use `event.movementX` for this check because Safari will - // always return `0` on a pointer event. - if (event.currentTarget.contains(target) && pointerXHasChanged) { - const newDir = event.clientX > lastPointerXRef.current ? 'right' : 'left'; - pointerDirRef.current = newDir; - lastPointerXRef.current = event.clientX; - } - })) - }))))))); -}); -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$479f0f2f71193efe, { - displayName: $213e4d2df823067d$var$CONTENT_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuGroup - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$GROUP_NAME = 'MenuGroup'; -const $213e4d2df823067d$export$22a631d1f72787bb = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const { - __scopeMenu: __scopeMenu, - ...groupProps - } = props; - return /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactprimitive.Primitive.div, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({ - role: "group" - }, groupProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$22a631d1f72787bb, { - displayName: $213e4d2df823067d$var$GROUP_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuLabel - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$LABEL_NAME = 'MenuLabel'; -const $213e4d2df823067d$export$dd37bec0e8a99143 = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const { - __scopeMenu: __scopeMenu, - ...labelProps - } = props; - return /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactprimitive.Primitive.div, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({}, labelProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$dd37bec0e8a99143, { - displayName: $213e4d2df823067d$var$LABEL_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuItem - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$ITEM_NAME = 'MenuItem'; -const $213e4d2df823067d$var$ITEM_SELECT = 'menu.itemSelect'; -const $213e4d2df823067d$export$2ce376c2cc3355c8 = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const { - disabled = false, - onSelect: onSelect, - ...itemProps - } = props; - const ref = $cnSS2$react.useRef(null); - const rootContext = $213e4d2df823067d$var$useMenuRootContext($213e4d2df823067d$var$ITEM_NAME, props.__scopeMenu); - const contentContext = $213e4d2df823067d$var$useMenuContentContext($213e4d2df823067d$var$ITEM_NAME, props.__scopeMenu); - const composedRefs = $cnSS2$radixuireactcomposerefs.useComposedRefs(forwardedRef, ref); - const isPointerDownRef = $cnSS2$react.useRef(false); - const handleSelect = () => { - const menuItem = ref.current; - if (!disabled && menuItem) { - const itemSelectEvent = new CustomEvent($213e4d2df823067d$var$ITEM_SELECT, { - bubbles: true, - cancelable: true - }); - menuItem.addEventListener($213e4d2df823067d$var$ITEM_SELECT, event => onSelect === null || onSelect === void 0 ? void 0 : onSelect(event), { - once: true - }); - $cnSS2$radixuireactprimitive.dispatchDiscreteCustomEvent(menuItem, itemSelectEvent); - if (itemSelectEvent.defaultPrevented) isPointerDownRef.current = false;else rootContext.onClose(); - } - }; - return /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$MenuItemImpl, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({}, itemProps, { - ref: composedRefs, - disabled: disabled, - onClick: $cnSS2$radixuiprimitive.composeEventHandlers(props.onClick, handleSelect), - onPointerDown: event => { - var _props$onPointerDown; - (_props$onPointerDown = props.onPointerDown) === null || _props$onPointerDown === void 0 || _props$onPointerDown.call(props, event); - isPointerDownRef.current = true; - }, - onPointerUp: $cnSS2$radixuiprimitive.composeEventHandlers(props.onPointerUp, event => { - var _event$currentTarget; - // Pointer down can move to a different menu item which should activate it on pointer up. - // We dispatch a click for selection to allow composition with click based triggers and to - // prevent Firefox from getting stuck in text selection mode when the menu closes. - if (!isPointerDownRef.current) (_event$currentTarget = event.currentTarget) === null || _event$currentTarget === void 0 || _event$currentTarget.click(); - }), - onKeyDown: $cnSS2$radixuiprimitive.composeEventHandlers(props.onKeyDown, event => { - const isTypingAhead = contentContext.searchRef.current !== ''; - if (disabled || isTypingAhead && event.key === ' ') return; - if ($213e4d2df823067d$var$SELECTION_KEYS.includes(event.key)) { - event.currentTarget.click(); - /** - * We prevent default browser behaviour for selection keys as they should trigger - * a selection only: - * - prevents space from scrolling the page. - * - if keydown causes focus to move, prevents keydown from firing on the new target. - */ - event.preventDefault(); - } - }) - })); -}); -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$2ce376c2cc3355c8, { - displayName: $213e4d2df823067d$var$ITEM_NAME -}); -/* ---------------------------------------------------------------------------------------------- */ -const $213e4d2df823067d$var$MenuItemImpl = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const { - __scopeMenu: __scopeMenu, - disabled = false, - textValue: textValue, - ...itemProps - } = props; - const contentContext = $213e4d2df823067d$var$useMenuContentContext($213e4d2df823067d$var$ITEM_NAME, __scopeMenu); - const rovingFocusGroupScope = $213e4d2df823067d$var$useRovingFocusGroupScope(__scopeMenu); - const ref = $cnSS2$react.useRef(null); - const composedRefs = $cnSS2$radixuireactcomposerefs.useComposedRefs(forwardedRef, ref); - const [isFocused, setIsFocused] = $cnSS2$react.useState(false); // get the item's `.textContent` as default strategy for typeahead `textValue` - const [textContent, setTextContent] = $cnSS2$react.useState(''); - $cnSS2$react.useEffect(() => { - const menuItem = ref.current; - if (menuItem) { - var _menuItem$textContent; - setTextContent(((_menuItem$textContent = menuItem.textContent) !== null && _menuItem$textContent !== void 0 ? _menuItem$textContent : '').trim()); - } - }, [itemProps.children]); - return /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$Collection.ItemSlot, { - scope: __scopeMenu, - disabled: disabled, - textValue: textValue !== null && textValue !== void 0 ? textValue : textContent - }, /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactrovingfocus.Item, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({ - asChild: true - }, rovingFocusGroupScope, { - focusable: !disabled - }), /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactprimitive.Primitive.div, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({ - role: "menuitem", - "data-highlighted": isFocused ? '' : undefined, - "aria-disabled": disabled || undefined, - "data-disabled": disabled ? '' : undefined - }, itemProps, { - ref: composedRefs, - onPointerMove: $cnSS2$radixuiprimitive.composeEventHandlers(props.onPointerMove, $213e4d2df823067d$var$whenMouse(event => { - if (disabled) contentContext.onItemLeave(event);else { - contentContext.onItemEnter(event); - if (!event.defaultPrevented) { - const item = event.currentTarget; - item.focus(); - } - } - })), - onPointerLeave: $cnSS2$radixuiprimitive.composeEventHandlers(props.onPointerLeave, $213e4d2df823067d$var$whenMouse(event => contentContext.onItemLeave(event))), - onFocus: $cnSS2$radixuiprimitive.composeEventHandlers(props.onFocus, () => setIsFocused(true)), - onBlur: $cnSS2$radixuiprimitive.composeEventHandlers(props.onBlur, () => setIsFocused(false)) - })))); -}); -/* ------------------------------------------------------------------------------------------------- - * MenuCheckboxItem - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$CHECKBOX_ITEM_NAME = 'MenuCheckboxItem'; -const $213e4d2df823067d$export$f6f243521332502d = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const { - checked = false, - onCheckedChange: onCheckedChange, - ...checkboxItemProps - } = props; - return /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$ItemIndicatorProvider, { - scope: props.__scopeMenu, - checked: checked - }, /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$export$2ce376c2cc3355c8, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({ - role: "menuitemcheckbox", - "aria-checked": $213e4d2df823067d$var$isIndeterminate(checked) ? 'mixed' : checked - }, checkboxItemProps, { - ref: forwardedRef, - "data-state": $213e4d2df823067d$var$getCheckedState(checked), - onSelect: $cnSS2$radixuiprimitive.composeEventHandlers(checkboxItemProps.onSelect, () => onCheckedChange === null || onCheckedChange === void 0 ? void 0 : onCheckedChange($213e4d2df823067d$var$isIndeterminate(checked) ? true : !checked), { - checkForDefaultPrevented: false - }) - }))); -}); -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$f6f243521332502d, { - displayName: $213e4d2df823067d$var$CHECKBOX_ITEM_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuRadioGroup - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$RADIO_GROUP_NAME = 'MenuRadioGroup'; -const [$213e4d2df823067d$var$RadioGroupProvider, $213e4d2df823067d$var$useRadioGroupContext] = $213e4d2df823067d$var$createMenuContext($213e4d2df823067d$var$RADIO_GROUP_NAME, { - value: undefined, - onValueChange: () => {} -}); -const $213e4d2df823067d$export$ea2200c9eee416b3 = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const { - value: value, - onValueChange: onValueChange, - ...groupProps - } = props; - const handleValueChange = $cnSS2$radixuireactusecallbackref.useCallbackRef(onValueChange); - return /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$RadioGroupProvider, { - scope: props.__scopeMenu, - value: value, - onValueChange: handleValueChange - }, /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$export$22a631d1f72787bb, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({}, groupProps, { - ref: forwardedRef - }))); -}); -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$ea2200c9eee416b3, { - displayName: $213e4d2df823067d$var$RADIO_GROUP_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuRadioItem - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$RADIO_ITEM_NAME = 'MenuRadioItem'; -const $213e4d2df823067d$export$69bd225e9817f6d0 = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const { - value: value, - ...radioItemProps - } = props; - const context = $213e4d2df823067d$var$useRadioGroupContext($213e4d2df823067d$var$RADIO_ITEM_NAME, props.__scopeMenu); - const checked = value === context.value; - return /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$ItemIndicatorProvider, { - scope: props.__scopeMenu, - checked: checked - }, /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$export$2ce376c2cc3355c8, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({ - role: "menuitemradio", - "aria-checked": checked - }, radioItemProps, { - ref: forwardedRef, - "data-state": $213e4d2df823067d$var$getCheckedState(checked), - onSelect: $cnSS2$radixuiprimitive.composeEventHandlers(radioItemProps.onSelect, () => { - var _context$onValueChang; - return (_context$onValueChang = context.onValueChange) === null || _context$onValueChang === void 0 ? void 0 : _context$onValueChang.call(context, value); - }, { - checkForDefaultPrevented: false - }) - }))); -}); -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$69bd225e9817f6d0, { - displayName: $213e4d2df823067d$var$RADIO_ITEM_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuItemIndicator - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$ITEM_INDICATOR_NAME = 'MenuItemIndicator'; -const [$213e4d2df823067d$var$ItemIndicatorProvider, $213e4d2df823067d$var$useItemIndicatorContext] = $213e4d2df823067d$var$createMenuContext($213e4d2df823067d$var$ITEM_INDICATOR_NAME, { - checked: false -}); -const $213e4d2df823067d$export$a2593e23056970a3 = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const { - __scopeMenu: __scopeMenu, - forceMount: forceMount, - ...itemIndicatorProps - } = props; - const indicatorContext = $213e4d2df823067d$var$useItemIndicatorContext($213e4d2df823067d$var$ITEM_INDICATOR_NAME, __scopeMenu); - return /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactpresence.Presence, { - present: forceMount || $213e4d2df823067d$var$isIndeterminate(indicatorContext.checked) || indicatorContext.checked === true - }, /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactprimitive.Primitive.span, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({}, itemIndicatorProps, { - ref: forwardedRef, - "data-state": $213e4d2df823067d$var$getCheckedState(indicatorContext.checked) - }))); -}); -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$a2593e23056970a3, { - displayName: $213e4d2df823067d$var$ITEM_INDICATOR_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuSeparator - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$SEPARATOR_NAME = 'MenuSeparator'; -const $213e4d2df823067d$export$1cec7dcdd713e220 = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const { - __scopeMenu: __scopeMenu, - ...separatorProps - } = props; - return /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactprimitive.Primitive.div, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({ - role: "separator", - "aria-orientation": "horizontal" - }, separatorProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$1cec7dcdd713e220, { - displayName: $213e4d2df823067d$var$SEPARATOR_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuArrow - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$ARROW_NAME = 'MenuArrow'; -const $213e4d2df823067d$export$bcdda4773debf5fa = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const { - __scopeMenu: __scopeMenu, - ...arrowProps - } = props; - const popperScope = $213e4d2df823067d$var$usePopperScope(__scopeMenu); - return /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactpopper.Arrow, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({}, popperScope, arrowProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$bcdda4773debf5fa, { - displayName: $213e4d2df823067d$var$ARROW_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuSub - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$SUB_NAME = 'MenuSub'; -const [$213e4d2df823067d$var$MenuSubProvider, $213e4d2df823067d$var$useMenuSubContext] = $213e4d2df823067d$var$createMenuContext($213e4d2df823067d$var$SUB_NAME); -const $213e4d2df823067d$export$71bdb9d1e2909932 = props => { - const { - __scopeMenu: __scopeMenu, - children: children, - open = false, - onOpenChange: onOpenChange - } = props; - const parentMenuContext = $213e4d2df823067d$var$useMenuContext($213e4d2df823067d$var$SUB_NAME, __scopeMenu); - const popperScope = $213e4d2df823067d$var$usePopperScope(__scopeMenu); - const [trigger, setTrigger] = $cnSS2$react.useState(null); - const [content, setContent] = $cnSS2$react.useState(null); - const handleOpenChange = $cnSS2$radixuireactusecallbackref.useCallbackRef(onOpenChange); // Prevent the parent menu from reopening with open submenus. - $cnSS2$react.useEffect(() => { - if (parentMenuContext.open === false) handleOpenChange(false); - return () => handleOpenChange(false); - }, [parentMenuContext.open, handleOpenChange]); - return /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactpopper.Root, popperScope, /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$MenuProvider, { - scope: __scopeMenu, - open: open, - onOpenChange: handleOpenChange, - content: content, - onContentChange: setContent - }, /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$MenuSubProvider, { - scope: __scopeMenu, - contentId: $cnSS2$radixuireactid.useId(), - triggerId: $cnSS2$radixuireactid.useId(), - trigger: trigger, - onTriggerChange: setTrigger - }, children))); -}; -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$71bdb9d1e2909932, { - displayName: $213e4d2df823067d$var$SUB_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuSubTrigger - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$SUB_TRIGGER_NAME = 'MenuSubTrigger'; -const $213e4d2df823067d$export$5fbbb3ba7297405f = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const context = $213e4d2df823067d$var$useMenuContext($213e4d2df823067d$var$SUB_TRIGGER_NAME, props.__scopeMenu); - const rootContext = $213e4d2df823067d$var$useMenuRootContext($213e4d2df823067d$var$SUB_TRIGGER_NAME, props.__scopeMenu); - const subContext = $213e4d2df823067d$var$useMenuSubContext($213e4d2df823067d$var$SUB_TRIGGER_NAME, props.__scopeMenu); - const contentContext = $213e4d2df823067d$var$useMenuContentContext($213e4d2df823067d$var$SUB_TRIGGER_NAME, props.__scopeMenu); - const openTimerRef = $cnSS2$react.useRef(null); - const { - pointerGraceTimerRef: pointerGraceTimerRef, - onPointerGraceIntentChange: onPointerGraceIntentChange - } = contentContext; - const scope = { - __scopeMenu: props.__scopeMenu - }; - const clearOpenTimer = $cnSS2$react.useCallback(() => { - if (openTimerRef.current) window.clearTimeout(openTimerRef.current); - openTimerRef.current = null; - }, []); - $cnSS2$react.useEffect(() => clearOpenTimer, [clearOpenTimer]); - $cnSS2$react.useEffect(() => { - const pointerGraceTimer = pointerGraceTimerRef.current; - return () => { - window.clearTimeout(pointerGraceTimer); - onPointerGraceIntentChange(null); - }; - }, [pointerGraceTimerRef, onPointerGraceIntentChange]); - return /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$export$9fa5ebd18bee4d43, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({ - asChild: true - }, scope), /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$MenuItemImpl, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({ - id: subContext.triggerId, - "aria-haspopup": "menu", - "aria-expanded": context.open, - "aria-controls": subContext.contentId, - "data-state": $213e4d2df823067d$var$getOpenState(context.open) - }, props, { - ref: $cnSS2$radixuireactcomposerefs.composeRefs(forwardedRef, subContext.onTriggerChange) // This is redundant for mouse users but we cannot determine pointer type from - , - - onClick: event => { - var _props$onClick; - (_props$onClick = props.onClick) === null || _props$onClick === void 0 || _props$onClick.call(props, event); - if (props.disabled || event.defaultPrevented) return; - /** - * We manually focus because iOS Safari doesn't always focus on click (e.g. buttons) - * and we rely heavily on `onFocusOutside` for submenus to close when switching - * between separate submenus. - */ - event.currentTarget.focus(); - if (!context.open) context.onOpenChange(true); - }, - onPointerMove: $cnSS2$radixuiprimitive.composeEventHandlers(props.onPointerMove, $213e4d2df823067d$var$whenMouse(event => { - contentContext.onItemEnter(event); - if (event.defaultPrevented) return; - if (!props.disabled && !context.open && !openTimerRef.current) { - contentContext.onPointerGraceIntentChange(null); - openTimerRef.current = window.setTimeout(() => { - context.onOpenChange(true); - clearOpenTimer(); - }, 100); - } - })), - onPointerLeave: $cnSS2$radixuiprimitive.composeEventHandlers(props.onPointerLeave, $213e4d2df823067d$var$whenMouse(event => { - var _context$content; - clearOpenTimer(); - const contentRect = (_context$content = context.content) === null || _context$content === void 0 ? void 0 : _context$content.getBoundingClientRect(); - if (contentRect) { - var _context$content2; - // TODO: make sure to update this when we change positioning logic - const side = (_context$content2 = context.content) === null || _context$content2 === void 0 ? void 0 : _context$content2.dataset.side; - const rightSide = side === 'right'; - const bleed = rightSide ? -5 : 5; - const contentNearEdge = contentRect[rightSide ? 'left' : 'right']; - const contentFarEdge = contentRect[rightSide ? 'right' : 'left']; - contentContext.onPointerGraceIntentChange({ - area: [ - // consistently within polygon bounds - { - x: event.clientX + bleed, - y: event.clientY - }, { - x: contentNearEdge, - y: contentRect.top - }, { - x: contentFarEdge, - y: contentRect.top - }, { - x: contentFarEdge, - y: contentRect.bottom - }, { - x: contentNearEdge, - y: contentRect.bottom - }], - side: side - }); - window.clearTimeout(pointerGraceTimerRef.current); - pointerGraceTimerRef.current = window.setTimeout(() => contentContext.onPointerGraceIntentChange(null), 300); - } else { - contentContext.onTriggerLeave(event); - if (event.defaultPrevented) return; // There's 100ms where the user may leave an item before the submenu was opened. - contentContext.onPointerGraceIntentChange(null); - } - })), - onKeyDown: $cnSS2$radixuiprimitive.composeEventHandlers(props.onKeyDown, event => { - const isTypingAhead = contentContext.searchRef.current !== ''; - if (props.disabled || isTypingAhead && event.key === ' ') return; - if ($213e4d2df823067d$var$SUB_OPEN_KEYS[rootContext.dir].includes(event.key)) { - var _context$content3; - context.onOpenChange(true); // The trigger may hold focus if opened via pointer interaction - // so we ensure content is given focus again when switching to keyboard. - (_context$content3 = context.content) === null || _context$content3 === void 0 || _context$content3.focus(); // prevent window from scrolling - event.preventDefault(); - } - }) - }))); -}); -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$5fbbb3ba7297405f, { - displayName: $213e4d2df823067d$var$SUB_TRIGGER_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuSubContent - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$SUB_CONTENT_NAME = 'MenuSubContent'; -const $213e4d2df823067d$export$e7142ab31822bde6 = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const portalContext = $213e4d2df823067d$var$usePortalContext($213e4d2df823067d$var$CONTENT_NAME, props.__scopeMenu); - const { - forceMount = portalContext.forceMount, - ...subContentProps - } = props; - const context = $213e4d2df823067d$var$useMenuContext($213e4d2df823067d$var$CONTENT_NAME, props.__scopeMenu); - const rootContext = $213e4d2df823067d$var$useMenuRootContext($213e4d2df823067d$var$CONTENT_NAME, props.__scopeMenu); - const subContext = $213e4d2df823067d$var$useMenuSubContext($213e4d2df823067d$var$SUB_CONTENT_NAME, props.__scopeMenu); - const ref = $cnSS2$react.useRef(null); - const composedRefs = $cnSS2$radixuireactcomposerefs.useComposedRefs(forwardedRef, ref); - return /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$Collection.Provider, { - scope: props.__scopeMenu - }, /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactpresence.Presence, { - present: forceMount || context.open - }, /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$Collection.Slot, { - scope: props.__scopeMenu - }, /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$MenuContentImpl, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({ - id: subContext.contentId, - "aria-labelledby": subContext.triggerId - }, subContentProps, { - ref: composedRefs, - align: "start", - side: rootContext.dir === 'rtl' ? 'left' : 'right', - disableOutsidePointerEvents: false, - disableOutsideScroll: false, - trapFocus: false, - onOpenAutoFocus: event => { - var _ref$current; - // when opening a submenu, focus content for keyboard users only - if (rootContext.isUsingKeyboardRef.current) (_ref$current = ref.current) === null || _ref$current === void 0 || _ref$current.focus(); - event.preventDefault(); - } // The menu might close because of focusing another menu item in the parent menu. We - , - - onCloseAutoFocus: event => event.preventDefault(), - onFocusOutside: $cnSS2$radixuiprimitive.composeEventHandlers(props.onFocusOutside, event => { - // We prevent closing when the trigger is focused to avoid triggering a re-open animation - // on pointer interaction. - if (event.target !== subContext.trigger) context.onOpenChange(false); - }), - onEscapeKeyDown: $cnSS2$radixuiprimitive.composeEventHandlers(props.onEscapeKeyDown, event => { - rootContext.onClose(); // ensure pressing escape in submenu doesn't escape full screen mode - event.preventDefault(); - }), - onKeyDown: $cnSS2$radixuiprimitive.composeEventHandlers(props.onKeyDown, event => { - // Submenu key events bubble through portals. We only care about keys in this menu. - const isKeyDownInside = event.currentTarget.contains(event.target); - const isCloseKey = $213e4d2df823067d$var$SUB_CLOSE_KEYS[rootContext.dir].includes(event.key); - if (isKeyDownInside && isCloseKey) { - var _subContext$trigger; - context.onOpenChange(false); // We focus manually because we prevented it in `onCloseAutoFocus` - (_subContext$trigger = subContext.trigger) === null || _subContext$trigger === void 0 || _subContext$trigger.focus(); // prevent window from scrolling - event.preventDefault(); - } - }) - }))))); -}); -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$e7142ab31822bde6, { - displayName: $213e4d2df823067d$var$SUB_CONTENT_NAME -}); -/* -----------------------------------------------------------------------------------------------*/ -function $213e4d2df823067d$var$getOpenState(open) { - return open ? 'open' : 'closed'; -} -function $213e4d2df823067d$var$isIndeterminate(checked) { - return checked === 'indeterminate'; -} -function $213e4d2df823067d$var$getCheckedState(checked) { - return $213e4d2df823067d$var$isIndeterminate(checked) ? 'indeterminate' : checked ? 'checked' : 'unchecked'; -} -function $213e4d2df823067d$var$focusFirst(candidates) { - const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement; - for (const candidate of candidates) { - // if focus is already where we want to go, we don't want to keep going through the candidates - if (candidate === PREVIOUSLY_FOCUSED_ELEMENT) return; - candidate.focus(); - if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT) return; - } -} -/** - * Wraps an array around itself at a given start index - * Example: `wrapArray(['a', 'b', 'c', 'd'], 2) === ['c', 'd', 'a', 'b']` - */ -function $213e4d2df823067d$var$wrapArray(array, startIndex) { - return array.map((_, index) => array[(startIndex + index) % array.length]); -} -/** - * This is the "meat" of the typeahead matching logic. It takes in all the values, - * the search and the current match, and returns the next match (or `undefined`). - * - * We normalize the search because if a user has repeatedly pressed a character, - * we want the exact same behavior as if we only had that one character - * (ie. cycle through options starting with that character) - * - * We also reorder the values by wrapping the array around the current match. - * This is so we always look forward from the current match, and picking the first - * match will always be the correct one. - * - * Finally, if the normalized search is exactly one character, we exclude the - * current match from the values because otherwise it would be the first to match always - * and focus would never move. This is as opposed to the regular case, where we - * don't want focus to move if the current match still matches. - */ -function $213e4d2df823067d$var$getNextMatch(values, search, currentMatch) { - const isRepeated = search.length > 1 && Array.from(search).every(char => char === search[0]); - const normalizedSearch = isRepeated ? search[0] : search; - const currentMatchIndex = currentMatch ? values.indexOf(currentMatch) : -1; - let wrappedValues = $213e4d2df823067d$var$wrapArray(values, Math.max(currentMatchIndex, 0)); - const excludeCurrentMatch = normalizedSearch.length === 1; - if (excludeCurrentMatch) wrappedValues = wrappedValues.filter(v => v !== currentMatch); - const nextMatch = wrappedValues.find(value => value.toLowerCase().startsWith(normalizedSearch.toLowerCase())); - return nextMatch !== currentMatch ? nextMatch : undefined; -} -// Determine if a point is inside of a polygon. -// Based on https://github.com/substack/point-in-polygon -function $213e4d2df823067d$var$isPointInPolygon(point, polygon) { - const { - x: x, - y: y - } = point; - let inside = false; - for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { - const xi = polygon[i].x; - const yi = polygon[i].y; - const xj = polygon[j].x; - const yj = polygon[j].y; // prettier-ignore - const intersect = yi > y !== yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi; - if (intersect) inside = !inside; - } - return inside; -} -function $213e4d2df823067d$var$isPointerInGraceArea(event, area) { - if (!area) return false; - const cursorPos = { - x: event.clientX, - y: event.clientY - }; - return $213e4d2df823067d$var$isPointInPolygon(cursorPos, area); -} -function $213e4d2df823067d$var$whenMouse(handler) { - return event => event.pointerType === 'mouse' ? handler(event) : undefined; -} -const $213e4d2df823067d$export$be92b6f5f03c0fe9 = $213e4d2df823067d$export$d9b273488cd8ce6f; -const $213e4d2df823067d$export$b688253958b8dfe7 = $213e4d2df823067d$export$9fa5ebd18bee4d43; -const $213e4d2df823067d$export$602eac185826482c = $213e4d2df823067d$export$793392f970497feb; -const $213e4d2df823067d$export$7c6e2c02157bb7d2 = $213e4d2df823067d$export$479f0f2f71193efe; -const $213e4d2df823067d$export$eb2fcfdbd7ba97d4 = $213e4d2df823067d$export$22a631d1f72787bb; -const $213e4d2df823067d$export$b04be29aa201d4f5 = $213e4d2df823067d$export$dd37bec0e8a99143; -const $213e4d2df823067d$export$6d08773d2e66f8f2 = $213e4d2df823067d$export$2ce376c2cc3355c8; -const $213e4d2df823067d$export$16ce288f89fa631c = $213e4d2df823067d$export$f6f243521332502d; -const $213e4d2df823067d$export$a98f0dcb43a68a25 = $213e4d2df823067d$export$ea2200c9eee416b3; -const $213e4d2df823067d$export$371ab307eab489c0 = $213e4d2df823067d$export$69bd225e9817f6d0; -const $213e4d2df823067d$export$c3468e2714d175fa = $213e4d2df823067d$export$a2593e23056970a3; -const $213e4d2df823067d$export$1ff3c3f08ae963c0 = $213e4d2df823067d$export$1cec7dcdd713e220; -const $213e4d2df823067d$export$21b07c8f274aebd5 = $213e4d2df823067d$export$bcdda4773debf5fa; -const $213e4d2df823067d$export$d7a01e11500dfb6f = $213e4d2df823067d$export$71bdb9d1e2909932; -const $213e4d2df823067d$export$2ea8a7a591ac5eac = $213e4d2df823067d$export$5fbbb3ba7297405f; -const $213e4d2df823067d$export$6d4de93b380beddf = $213e4d2df823067d$export$e7142ab31822bde6; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-popper/dist/index.js": -/*!******************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-popper/dist/index.js ***! - \******************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var $50Iv9$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); -var $50Iv9$react = __webpack_require__(/*! react */ "react"); -var $50Iv9$floatinguireactdom = __webpack_require__(/*! @floating-ui/react-dom */ "../../../node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.esm.js"); -var $50Iv9$radixuireactarrow = __webpack_require__(/*! @radix-ui/react-arrow */ "../../../node_modules/@radix-ui/react-arrow/dist/index.js"); -var $50Iv9$radixuireactcomposerefs = __webpack_require__(/*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js"); -var $50Iv9$radixuireactcontext = __webpack_require__(/*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js"); -var $50Iv9$radixuireactprimitive = __webpack_require__(/*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js"); -var $50Iv9$radixuireactusecallbackref = __webpack_require__(/*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js"); -var $50Iv9$radixuireactuselayouteffect = __webpack_require__(/*! @radix-ui/react-use-layout-effect */ "../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js"); -var $50Iv9$radixuireactusesize = __webpack_require__(/*! @radix-ui/react-use-size */ "../../../node_modules/@radix-ui/react-use-size/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "createPopperScope", () => $34310caa050a8d63$export$722aac194ae923); -$parcel$export(module.exports, "Popper", () => $34310caa050a8d63$export$badac9ada3a0bdf9); -$parcel$export(module.exports, "PopperAnchor", () => $34310caa050a8d63$export$ecd4e1ccab6ed6d); -$parcel$export(module.exports, "PopperContent", () => $34310caa050a8d63$export$bc4ae5855d3c4fc); -$parcel$export(module.exports, "PopperArrow", () => $34310caa050a8d63$export$79d62cd4e10a3fd0); -$parcel$export(module.exports, "Root", () => $34310caa050a8d63$export$be92b6f5f03c0fe9); -$parcel$export(module.exports, "Anchor", () => $34310caa050a8d63$export$b688253958b8dfe7); -$parcel$export(module.exports, "Content", () => $34310caa050a8d63$export$7c6e2c02157bb7d2); -$parcel$export(module.exports, "Arrow", () => $34310caa050a8d63$export$21b07c8f274aebd5); -$parcel$export(module.exports, "SIDE_OPTIONS", () => $34310caa050a8d63$export$36f0086da09c4b9f); -$parcel$export(module.exports, "ALIGN_OPTIONS", () => $34310caa050a8d63$export$3671ffab7b302fc9); -const $34310caa050a8d63$export$36f0086da09c4b9f = ['top', 'right', 'bottom', 'left']; -const $34310caa050a8d63$export$3671ffab7b302fc9 = ['start', 'center', 'end']; -/* ------------------------------------------------------------------------------------------------- - * Popper - * -----------------------------------------------------------------------------------------------*/ -const $34310caa050a8d63$var$POPPER_NAME = 'Popper'; -const [$34310caa050a8d63$var$createPopperContext, $34310caa050a8d63$export$722aac194ae923] = $50Iv9$radixuireactcontext.createContextScope($34310caa050a8d63$var$POPPER_NAME); -const [$34310caa050a8d63$var$PopperProvider, $34310caa050a8d63$var$usePopperContext] = $34310caa050a8d63$var$createPopperContext($34310caa050a8d63$var$POPPER_NAME); -const $34310caa050a8d63$export$badac9ada3a0bdf9 = props => { - const { - __scopePopper: __scopePopper, - children: children - } = props; - const [anchor, setAnchor] = $50Iv9$react.useState(null); - return /*#__PURE__*/$50Iv9$react.createElement($34310caa050a8d63$var$PopperProvider, { - scope: __scopePopper, - anchor: anchor, - onAnchorChange: setAnchor - }, children); -}; -/*#__PURE__*/ -Object.assign($34310caa050a8d63$export$badac9ada3a0bdf9, { - displayName: $34310caa050a8d63$var$POPPER_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * PopperAnchor - * -----------------------------------------------------------------------------------------------*/ -const $34310caa050a8d63$var$ANCHOR_NAME = 'PopperAnchor'; -const $34310caa050a8d63$export$ecd4e1ccab6ed6d = /*#__PURE__*/$50Iv9$react.forwardRef((props, forwardedRef) => { - const { - __scopePopper: __scopePopper, - virtualRef: virtualRef, - ...anchorProps - } = props; - const context = $34310caa050a8d63$var$usePopperContext($34310caa050a8d63$var$ANCHOR_NAME, __scopePopper); - const ref = $50Iv9$react.useRef(null); - const composedRefs = $50Iv9$radixuireactcomposerefs.useComposedRefs(forwardedRef, ref); - $50Iv9$react.useEffect(() => { - // Consumer can anchor the popper to something that isn't - // a DOM node e.g. pointer position, so we override the - // `anchorRef` with their virtual ref in this case. - context.onAnchorChange((virtualRef === null || virtualRef === void 0 ? void 0 : virtualRef.current) || ref.current); - }); - return virtualRef ? null : /*#__PURE__*/$50Iv9$react.createElement($50Iv9$radixuireactprimitive.Primitive.div, $parcel$interopDefault($50Iv9$babelruntimehelpersextends)({}, anchorProps, { - ref: composedRefs - })); -}); -/*#__PURE__*/ -Object.assign($34310caa050a8d63$export$ecd4e1ccab6ed6d, { - displayName: $34310caa050a8d63$var$ANCHOR_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * PopperContent - * -----------------------------------------------------------------------------------------------*/ -const $34310caa050a8d63$var$CONTENT_NAME = 'PopperContent'; -const [$34310caa050a8d63$var$PopperContentProvider, $34310caa050a8d63$var$useContentContext] = $34310caa050a8d63$var$createPopperContext($34310caa050a8d63$var$CONTENT_NAME); -const $34310caa050a8d63$export$bc4ae5855d3c4fc = /*#__PURE__*/$50Iv9$react.forwardRef((props, forwardedRef) => { - var _arrowSize$width, _arrowSize$height, _middlewareData$arrow, _middlewareData$arrow2, _middlewareData$arrow3, _middlewareData$trans, _middlewareData$trans2, _middlewareData$hide; - const { - __scopePopper: __scopePopper, - side = 'bottom', - sideOffset = 0, - align = 'center', - alignOffset = 0, - arrowPadding = 0, - collisionBoundary = [], - collisionPadding: collisionPaddingProp = 0, - sticky = 'partial', - hideWhenDetached = false, - avoidCollisions = true, - onPlaced: onPlaced, - ...contentProps - } = props; - const context = $34310caa050a8d63$var$usePopperContext($34310caa050a8d63$var$CONTENT_NAME, __scopePopper); - const [content, setContent] = $50Iv9$react.useState(null); - const composedRefs = $50Iv9$radixuireactcomposerefs.useComposedRefs(forwardedRef, node => setContent(node)); - const [arrow, setArrow] = $50Iv9$react.useState(null); - const arrowSize = $50Iv9$radixuireactusesize.useSize(arrow); - const arrowWidth = (_arrowSize$width = arrowSize === null || arrowSize === void 0 ? void 0 : arrowSize.width) !== null && _arrowSize$width !== void 0 ? _arrowSize$width : 0; - const arrowHeight = (_arrowSize$height = arrowSize === null || arrowSize === void 0 ? void 0 : arrowSize.height) !== null && _arrowSize$height !== void 0 ? _arrowSize$height : 0; - const desiredPlacement = side + (align !== 'center' ? '-' + align : ''); - const collisionPadding = typeof collisionPaddingProp === 'number' ? collisionPaddingProp : { - top: 0, - right: 0, - bottom: 0, - left: 0, - ...collisionPaddingProp - }; - const boundary = Array.isArray(collisionBoundary) ? collisionBoundary : [collisionBoundary]; - const hasExplicitBoundaries = boundary.length > 0; - const detectOverflowOptions = { - padding: collisionPadding, - boundary: boundary.filter($34310caa050a8d63$var$isNotNull), - // with `strategy: 'fixed'`, this is the only way to get it to respect boundaries - altBoundary: hasExplicitBoundaries - }; - const { - refs: refs, - floatingStyles: floatingStyles, - placement: placement, - isPositioned: isPositioned, - middlewareData: middlewareData - } = $50Iv9$floatinguireactdom.useFloating({ - // default to `fixed` strategy so users don't have to pick and we also avoid focus scroll issues - strategy: 'fixed', - placement: desiredPlacement, - whileElementsMounted: $50Iv9$floatinguireactdom.autoUpdate, - elements: { - reference: context.anchor - }, - middleware: [$50Iv9$floatinguireactdom.offset({ - mainAxis: sideOffset + arrowHeight, - alignmentAxis: alignOffset - }), avoidCollisions && $50Iv9$floatinguireactdom.shift({ - mainAxis: true, - crossAxis: false, - limiter: sticky === 'partial' ? $50Iv9$floatinguireactdom.limitShift() : undefined, - ...detectOverflowOptions - }), avoidCollisions && $50Iv9$floatinguireactdom.flip({ - ...detectOverflowOptions - }), $50Iv9$floatinguireactdom.size({ - ...detectOverflowOptions, - apply: ({ - elements: elements, - rects: rects, - availableWidth: availableWidth, - availableHeight: availableHeight - }) => { - const { - width: anchorWidth, - height: anchorHeight - } = rects.reference; - const contentStyle = elements.floating.style; - contentStyle.setProperty('--radix-popper-available-width', `${availableWidth}px`); - contentStyle.setProperty('--radix-popper-available-height', `${availableHeight}px`); - contentStyle.setProperty('--radix-popper-anchor-width', `${anchorWidth}px`); - contentStyle.setProperty('--radix-popper-anchor-height', `${anchorHeight}px`); - } - }), arrow && $50Iv9$floatinguireactdom.arrow({ - element: arrow, - padding: arrowPadding - }), $34310caa050a8d63$var$transformOrigin({ - arrowWidth: arrowWidth, - arrowHeight: arrowHeight - }), hideWhenDetached && $50Iv9$floatinguireactdom.hide({ - strategy: 'referenceHidden' - })] - }); - const [placedSide, placedAlign] = $34310caa050a8d63$var$getSideAndAlignFromPlacement(placement); - const handlePlaced = $50Iv9$radixuireactusecallbackref.useCallbackRef(onPlaced); - $50Iv9$radixuireactuselayouteffect.useLayoutEffect(() => { - if (isPositioned) handlePlaced === null || handlePlaced === void 0 || handlePlaced(); - }, [isPositioned, handlePlaced]); - const arrowX = (_middlewareData$arrow = middlewareData.arrow) === null || _middlewareData$arrow === void 0 ? void 0 : _middlewareData$arrow.x; - const arrowY = (_middlewareData$arrow2 = middlewareData.arrow) === null || _middlewareData$arrow2 === void 0 ? void 0 : _middlewareData$arrow2.y; - const cannotCenterArrow = ((_middlewareData$arrow3 = middlewareData.arrow) === null || _middlewareData$arrow3 === void 0 ? void 0 : _middlewareData$arrow3.centerOffset) !== 0; - const [contentZIndex, setContentZIndex] = $50Iv9$react.useState(); - $50Iv9$radixuireactuselayouteffect.useLayoutEffect(() => { - if (content) setContentZIndex(window.getComputedStyle(content).zIndex); - }, [content]); - return /*#__PURE__*/$50Iv9$react.createElement("div", { - ref: refs.setFloating, - "data-radix-popper-content-wrapper": "", - style: { - ...floatingStyles, - transform: isPositioned ? floatingStyles.transform : 'translate(0, -200%)', - // keep off the page when measuring - minWidth: 'max-content', - zIndex: contentZIndex, - ['--radix-popper-transform-origin']: [(_middlewareData$trans = middlewareData.transformOrigin) === null || _middlewareData$trans === void 0 ? void 0 : _middlewareData$trans.x, (_middlewareData$trans2 = middlewareData.transformOrigin) === null || _middlewareData$trans2 === void 0 ? void 0 : _middlewareData$trans2.y].join(' ') - } // Floating UI interally calculates logical alignment based the `dir` attribute on - , - - dir: props.dir - }, /*#__PURE__*/$50Iv9$react.createElement($34310caa050a8d63$var$PopperContentProvider, { - scope: __scopePopper, - placedSide: placedSide, - onArrowChange: setArrow, - arrowX: arrowX, - arrowY: arrowY, - shouldHideArrow: cannotCenterArrow - }, /*#__PURE__*/$50Iv9$react.createElement($50Iv9$radixuireactprimitive.Primitive.div, $parcel$interopDefault($50Iv9$babelruntimehelpersextends)({ - "data-side": placedSide, - "data-align": placedAlign - }, contentProps, { - ref: composedRefs, - style: { - ...contentProps.style, - // if the PopperContent hasn't been placed yet (not all measurements done) - // we prevent animations so that users's animation don't kick in too early referring wrong sides - animation: !isPositioned ? 'none' : undefined, - // hide the content if using the hide middleware and should be hidden - opacity: (_middlewareData$hide = middlewareData.hide) !== null && _middlewareData$hide !== void 0 && _middlewareData$hide.referenceHidden ? 0 : undefined - } - })))); -}); -/*#__PURE__*/ -Object.assign($34310caa050a8d63$export$bc4ae5855d3c4fc, { - displayName: $34310caa050a8d63$var$CONTENT_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * PopperArrow - * -----------------------------------------------------------------------------------------------*/ -const $34310caa050a8d63$var$ARROW_NAME = 'PopperArrow'; -const $34310caa050a8d63$var$OPPOSITE_SIDE = { - top: 'bottom', - right: 'left', - bottom: 'top', - left: 'right' -}; -const $34310caa050a8d63$export$79d62cd4e10a3fd0 = /*#__PURE__*/$50Iv9$react.forwardRef(function $34310caa050a8d63$export$79d62cd4e10a3fd0(props, forwardedRef) { - const { - __scopePopper: __scopePopper, - ...arrowProps - } = props; - const contentContext = $34310caa050a8d63$var$useContentContext($34310caa050a8d63$var$ARROW_NAME, __scopePopper); - const baseSide = $34310caa050a8d63$var$OPPOSITE_SIDE[contentContext.placedSide]; - return /*#__PURE__*/ (// we have to use an extra wrapper because `ResizeObserver` (used by `useSize`) - // doesn't report size as we'd expect on SVG elements. - // it reports their bounding box which is effectively the largest path inside the SVG. - $50Iv9$react.createElement("span", { - ref: contentContext.onArrowChange, - style: { - position: 'absolute', - left: contentContext.arrowX, - top: contentContext.arrowY, - [baseSide]: 0, - transformOrigin: { - top: '', - right: '0 0', - bottom: 'center 0', - left: '100% 0' - }[contentContext.placedSide], - transform: { - top: 'translateY(100%)', - right: 'translateY(50%) rotate(90deg) translateX(-50%)', - bottom: `rotate(180deg)`, - left: 'translateY(50%) rotate(-90deg) translateX(50%)' - }[contentContext.placedSide], - visibility: contentContext.shouldHideArrow ? 'hidden' : undefined - } - }, /*#__PURE__*/$50Iv9$react.createElement($50Iv9$radixuireactarrow.Root, $parcel$interopDefault($50Iv9$babelruntimehelpersextends)({}, arrowProps, { - ref: forwardedRef, - style: { - ...arrowProps.style, - // ensures the element can be measured correctly (mostly for if SVG) - display: 'block' - } - }))) - ); -}); -/*#__PURE__*/ -Object.assign($34310caa050a8d63$export$79d62cd4e10a3fd0, { - displayName: $34310caa050a8d63$var$ARROW_NAME -}); -/* -----------------------------------------------------------------------------------------------*/ -function $34310caa050a8d63$var$isNotNull(value) { - return value !== null; -} -const $34310caa050a8d63$var$transformOrigin = options => ({ - name: 'transformOrigin', - options: options, - fn(data) { - var _middlewareData$arrow4, _middlewareData$arrow5, _middlewareData$arrow6, _middlewareData$arrow7, _middlewareData$arrow8; - const { - placement: placement, - rects: rects, - middlewareData: middlewareData - } = data; - const cannotCenterArrow = ((_middlewareData$arrow4 = middlewareData.arrow) === null || _middlewareData$arrow4 === void 0 ? void 0 : _middlewareData$arrow4.centerOffset) !== 0; - const isArrowHidden = cannotCenterArrow; - const arrowWidth = isArrowHidden ? 0 : options.arrowWidth; - const arrowHeight = isArrowHidden ? 0 : options.arrowHeight; - const [placedSide, placedAlign] = $34310caa050a8d63$var$getSideAndAlignFromPlacement(placement); - const noArrowAlign = { - start: '0%', - center: '50%', - end: '100%' - }[placedAlign]; - const arrowXCenter = ((_middlewareData$arrow5 = (_middlewareData$arrow6 = middlewareData.arrow) === null || _middlewareData$arrow6 === void 0 ? void 0 : _middlewareData$arrow6.x) !== null && _middlewareData$arrow5 !== void 0 ? _middlewareData$arrow5 : 0) + arrowWidth / 2; - const arrowYCenter = ((_middlewareData$arrow7 = (_middlewareData$arrow8 = middlewareData.arrow) === null || _middlewareData$arrow8 === void 0 ? void 0 : _middlewareData$arrow8.y) !== null && _middlewareData$arrow7 !== void 0 ? _middlewareData$arrow7 : 0) + arrowHeight / 2; - let x = ''; - let y = ''; - if (placedSide === 'bottom') { - x = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`; - y = `${-arrowHeight}px`; - } else if (placedSide === 'top') { - x = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`; - y = `${rects.floating.height + arrowHeight}px`; - } else if (placedSide === 'right') { - x = `${-arrowHeight}px`; - y = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`; - } else if (placedSide === 'left') { - x = `${rects.floating.width + arrowHeight}px`; - y = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`; - } - return { - data: { - x: x, - y: y - } - }; - } -}); -function $34310caa050a8d63$var$getSideAndAlignFromPlacement(placement) { - const [side, align = 'center'] = placement.split('-'); - return [side, align]; -} -const $34310caa050a8d63$export$be92b6f5f03c0fe9 = $34310caa050a8d63$export$badac9ada3a0bdf9; -const $34310caa050a8d63$export$b688253958b8dfe7 = $34310caa050a8d63$export$ecd4e1ccab6ed6d; -const $34310caa050a8d63$export$7c6e2c02157bb7d2 = $34310caa050a8d63$export$bc4ae5855d3c4fc; -const $34310caa050a8d63$export$21b07c8f274aebd5 = $34310caa050a8d63$export$79d62cd4e10a3fd0; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-portal/dist/index.js": -/*!******************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-portal/dist/index.js ***! - \******************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var $amzHf$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); -var $amzHf$react = __webpack_require__(/*! react */ "react"); -var $amzHf$reactdom = __webpack_require__(/*! react-dom */ "react-dom"); -var $amzHf$radixuireactprimitive = __webpack_require__(/*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "Portal", () => $913a70b877676c16$export$602eac185826482c); -$parcel$export(module.exports, "Root", () => $913a70b877676c16$export$be92b6f5f03c0fe9); - -/* ------------------------------------------------------------------------------------------------- - * Portal - * -----------------------------------------------------------------------------------------------*/ -const $913a70b877676c16$var$PORTAL_NAME = 'Portal'; -const $913a70b877676c16$export$602eac185826482c = /*#__PURE__*/$amzHf$react.forwardRef((props, forwardedRef) => { - var _globalThis$document; - const { - container = globalThis === null || globalThis === void 0 ? void 0 : (_globalThis$document = globalThis.document) === null || _globalThis$document === void 0 ? void 0 : _globalThis$document.body, - ...portalProps - } = props; - return container ? /*#__PURE__*/$parcel$interopDefault($amzHf$reactdom).createPortal( /*#__PURE__*/$amzHf$react.createElement($amzHf$radixuireactprimitive.Primitive.div, $parcel$interopDefault($amzHf$babelruntimehelpersextends)({}, portalProps, { - ref: forwardedRef - })), container) : null; -}); -/*#__PURE__*/ -Object.assign($913a70b877676c16$export$602eac185826482c, { - displayName: $913a70b877676c16$var$PORTAL_NAME -}); -/* -----------------------------------------------------------------------------------------------*/ -const $913a70b877676c16$export$be92b6f5f03c0fe9 = $913a70b877676c16$export$602eac185826482c; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-presence/dist/index.js": -/*!********************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-presence/dist/index.js ***! - \********************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var $fnLeV$react = __webpack_require__(/*! react */ "react"); -var $fnLeV$reactdom = __webpack_require__(/*! react-dom */ "react-dom"); -var $fnLeV$radixuireactcomposerefs = __webpack_require__(/*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js"); -var $fnLeV$radixuireactuselayouteffect = __webpack_require__(/*! @radix-ui/react-use-layout-effect */ "../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -$parcel$export(module.exports, "Presence", () => $a2fa0214bb2735a1$export$99c2b779aa4e8b8b); -function $8f63844556d0d3cd$export$3e6543de14f8614f(initialState, machine) { - return $fnLeV$react.useReducer((state, event) => { - const nextState = machine[state][event]; - return nextState !== null && nextState !== void 0 ? nextState : state; - }, initialState); -} -const $a2fa0214bb2735a1$export$99c2b779aa4e8b8b = props => { - const { - present: present, - children: children - } = props; - const presence = $a2fa0214bb2735a1$var$usePresence(present); - const child = typeof children === 'function' ? children({ - present: presence.isPresent - }) : $fnLeV$react.Children.only(children); - const ref = $fnLeV$radixuireactcomposerefs.useComposedRefs(presence.ref, child.ref); - const forceMount = typeof children === 'function'; - return forceMount || presence.isPresent ? /*#__PURE__*/$fnLeV$react.cloneElement(child, { - ref: ref - }) : null; -}; -$a2fa0214bb2735a1$export$99c2b779aa4e8b8b.displayName = 'Presence'; -/* ------------------------------------------------------------------------------------------------- - * usePresence - * -----------------------------------------------------------------------------------------------*/ -function $a2fa0214bb2735a1$var$usePresence(present) { - const [node1, setNode] = $fnLeV$react.useState(); - const stylesRef = $fnLeV$react.useRef({}); - const prevPresentRef = $fnLeV$react.useRef(present); - const prevAnimationNameRef = $fnLeV$react.useRef('none'); - const initialState = present ? 'mounted' : 'unmounted'; - const [state, send] = $8f63844556d0d3cd$export$3e6543de14f8614f(initialState, { - mounted: { - UNMOUNT: 'unmounted', - ANIMATION_OUT: 'unmountSuspended' - }, - unmountSuspended: { - MOUNT: 'mounted', - ANIMATION_END: 'unmounted' - }, - unmounted: { - MOUNT: 'mounted' - } - }); - $fnLeV$react.useEffect(() => { - const currentAnimationName = $a2fa0214bb2735a1$var$getAnimationName(stylesRef.current); - prevAnimationNameRef.current = state === 'mounted' ? currentAnimationName : 'none'; - }, [state]); - $fnLeV$radixuireactuselayouteffect.useLayoutEffect(() => { - const styles = stylesRef.current; - const wasPresent = prevPresentRef.current; - const hasPresentChanged = wasPresent !== present; - if (hasPresentChanged) { - const prevAnimationName = prevAnimationNameRef.current; - const currentAnimationName = $a2fa0214bb2735a1$var$getAnimationName(styles); - if (present) send('MOUNT');else if (currentAnimationName === 'none' || (styles === null || styles === void 0 ? void 0 : styles.display) === 'none') - // If there is no exit animation or the element is hidden, animations won't run - // so we unmount instantly - send('UNMOUNT');else { - /** - * When `present` changes to `false`, we check changes to animation-name to - * determine whether an animation has started. We chose this approach (reading - * computed styles) because there is no `animationrun` event and `animationstart` - * fires after `animation-delay` has expired which would be too late. - */ - const isAnimating = prevAnimationName !== currentAnimationName; - if (wasPresent && isAnimating) send('ANIMATION_OUT');else send('UNMOUNT'); - } - prevPresentRef.current = present; - } - }, [present, send]); - $fnLeV$radixuireactuselayouteffect.useLayoutEffect(() => { - if (node1) { - /** - * Triggering an ANIMATION_OUT during an ANIMATION_IN will fire an `animationcancel` - * event for ANIMATION_IN after we have entered `unmountSuspended` state. So, we - * make sure we only trigger ANIMATION_END for the currently active animation. - */ - const handleAnimationEnd = event => { - const currentAnimationName = $a2fa0214bb2735a1$var$getAnimationName(stylesRef.current); - const isCurrentAnimation = currentAnimationName.includes(event.animationName); - if (event.target === node1 && isCurrentAnimation) - // With React 18 concurrency this update is applied - // a frame after the animation ends, creating a flash of visible content. - // By manually flushing we ensure they sync within a frame, removing the flash. - $fnLeV$reactdom.flushSync(() => send('ANIMATION_END')); - }; - const handleAnimationStart = event => { - if (event.target === node1) - // if animation occurred, store its name as the previous animation. - prevAnimationNameRef.current = $a2fa0214bb2735a1$var$getAnimationName(stylesRef.current); - }; - node1.addEventListener('animationstart', handleAnimationStart); - node1.addEventListener('animationcancel', handleAnimationEnd); - node1.addEventListener('animationend', handleAnimationEnd); - return () => { - node1.removeEventListener('animationstart', handleAnimationStart); - node1.removeEventListener('animationcancel', handleAnimationEnd); - node1.removeEventListener('animationend', handleAnimationEnd); - }; - } else - // Transition to the unmounted state if the node is removed prematurely. - // We avoid doing so during cleanup as the node may change but still exist. - send('ANIMATION_END'); - }, [node1, send]); - return { - isPresent: ['mounted', 'unmountSuspended'].includes(state), - ref: $fnLeV$react.useCallback(node => { - if (node) stylesRef.current = getComputedStyle(node); - setNode(node); - }, []) - }; -} -/* -----------------------------------------------------------------------------------------------*/ -function $a2fa0214bb2735a1$var$getAnimationName(styles) { - return (styles === null || styles === void 0 ? void 0 : styles.animationName) || 'none'; -} - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-primitive/dist/index.js": -/*!*********************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-primitive/dist/index.js ***! - \*********************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var $iMixA$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); -var $iMixA$react = __webpack_require__(/*! react */ "react"); -var $iMixA$reactdom = __webpack_require__(/*! react-dom */ "react-dom"); -var $iMixA$radixuireactslot = __webpack_require__(/*! @radix-ui/react-slot */ "../../../node_modules/@radix-ui/react-slot/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "Primitive", () => $c3def6332c2749a6$export$250ffa63cdc0d034); -$parcel$export(module.exports, "Root", () => $c3def6332c2749a6$export$be92b6f5f03c0fe9); -$parcel$export(module.exports, "dispatchDiscreteCustomEvent", () => $c3def6332c2749a6$export$6d1a0317bde7de7f); -const $c3def6332c2749a6$var$NODES = ['a', 'button', 'div', 'form', 'h2', 'h3', 'img', 'input', 'label', 'li', 'nav', 'ol', 'p', 'span', 'svg', 'ul']; // Temporary while we await merge of this fix: -// https://github.com/DefinitelyTyped/DefinitelyTyped/pull/55396 -// prettier-ignore -/* ------------------------------------------------------------------------------------------------- - * Primitive - * -----------------------------------------------------------------------------------------------*/ -const $c3def6332c2749a6$export$250ffa63cdc0d034 = $c3def6332c2749a6$var$NODES.reduce((primitive, node) => { - const Node = /*#__PURE__*/$iMixA$react.forwardRef((props, forwardedRef) => { - const { - asChild: asChild, - ...primitiveProps - } = props; - const Comp = asChild ? $iMixA$radixuireactslot.Slot : node; - $iMixA$react.useEffect(() => { - window[Symbol.for('radix-ui')] = true; - }, []); - return /*#__PURE__*/$iMixA$react.createElement(Comp, $parcel$interopDefault($iMixA$babelruntimehelpersextends)({}, primitiveProps, { - ref: forwardedRef - })); - }); - Node.displayName = `Primitive.${node}`; - return { - ...primitive, - [node]: Node - }; -}, {}); -/* ------------------------------------------------------------------------------------------------- - * Utils - * -----------------------------------------------------------------------------------------------*/ /** - * Flush custom event dispatch - * https://github.com/radix-ui/primitives/pull/1378 - * - * React batches *all* event handlers since version 18, this introduces certain considerations when using custom event types. - * - * Internally, React prioritises events in the following order: - * - discrete - * - continuous - * - default - * - * https://github.com/facebook/react/blob/a8a4742f1c54493df00da648a3f9d26e3db9c8b5/packages/react-dom/src/events/ReactDOMEventListener.js#L294-L350 - * - * `discrete` is an important distinction as updates within these events are applied immediately. - * React however, is not able to infer the priority of custom event types due to how they are detected internally. - * Because of this, it's possible for updates from custom events to be unexpectedly batched when - * dispatched by another `discrete` event. - * - * In order to ensure that updates from custom events are applied predictably, we need to manually flush the batch. - * This utility should be used when dispatching a custom event from within another `discrete` event, this utility - * is not nessesary when dispatching known event types, or if dispatching a custom type inside a non-discrete event. - * For example: - * - * dispatching a known click 👎 - * target.dispatchEvent(new Event(‘click’)) - * - * dispatching a custom type within a non-discrete event 👎 - * onScroll={(event) => event.target.dispatchEvent(new CustomEvent(‘customType’))} - * - * dispatching a custom type within a `discrete` event 👍 - * onPointerDown={(event) => dispatchDiscreteCustomEvent(event.target, new CustomEvent(‘customType’))} - * - * Note: though React classifies `focus`, `focusin` and `focusout` events as `discrete`, it's not recommended to use - * this utility with them. This is because it's possible for those handlers to be called implicitly during render - * e.g. when focus is within a component as it is unmounted, or when managing focus on mount. - */ -function $c3def6332c2749a6$export$6d1a0317bde7de7f(target, event) { - if (target) $iMixA$reactdom.flushSync(() => target.dispatchEvent(event)); -} -/* -----------------------------------------------------------------------------------------------*/ -const $c3def6332c2749a6$export$be92b6f5f03c0fe9 = $c3def6332c2749a6$export$250ffa63cdc0d034; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-roving-focus/dist/index.js": -/*!************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-roving-focus/dist/index.js ***! - \************************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var $9QJ9Y$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); -var $9QJ9Y$react = __webpack_require__(/*! react */ "react"); -var $9QJ9Y$radixuiprimitive = __webpack_require__(/*! @radix-ui/primitive */ "../../../node_modules/@radix-ui/primitive/dist/index.js"); -var $9QJ9Y$radixuireactcollection = __webpack_require__(/*! @radix-ui/react-collection */ "../../../node_modules/@radix-ui/react-collection/dist/index.js"); -var $9QJ9Y$radixuireactcomposerefs = __webpack_require__(/*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js"); -var $9QJ9Y$radixuireactcontext = __webpack_require__(/*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js"); -var $9QJ9Y$radixuireactid = __webpack_require__(/*! @radix-ui/react-id */ "../../../node_modules/@radix-ui/react-id/dist/index.js"); -var $9QJ9Y$radixuireactprimitive = __webpack_require__(/*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js"); -var $9QJ9Y$radixuireactusecallbackref = __webpack_require__(/*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js"); -var $9QJ9Y$radixuireactusecontrollablestate = __webpack_require__(/*! @radix-ui/react-use-controllable-state */ "../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js"); -var $9QJ9Y$radixuireactdirection = __webpack_require__(/*! @radix-ui/react-direction */ "../../../node_modules/@radix-ui/react-direction/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "createRovingFocusGroupScope", () => $0063afae63b3fa70$export$c7109489551a4f4); -$parcel$export(module.exports, "RovingFocusGroup", () => $0063afae63b3fa70$export$8699f7c8af148338); -$parcel$export(module.exports, "RovingFocusGroupItem", () => $0063afae63b3fa70$export$ab9df7c53fe8454); -$parcel$export(module.exports, "Root", () => $0063afae63b3fa70$export$be92b6f5f03c0fe9); -$parcel$export(module.exports, "Item", () => $0063afae63b3fa70$export$6d08773d2e66f8f2); -const $0063afae63b3fa70$var$ENTRY_FOCUS = 'rovingFocusGroup.onEntryFocus'; -const $0063afae63b3fa70$var$EVENT_OPTIONS = { - bubbles: false, - cancelable: true -}; -/* ------------------------------------------------------------------------------------------------- - * RovingFocusGroup - * -----------------------------------------------------------------------------------------------*/ -const $0063afae63b3fa70$var$GROUP_NAME = 'RovingFocusGroup'; -const [$0063afae63b3fa70$var$Collection, $0063afae63b3fa70$var$useCollection, $0063afae63b3fa70$var$createCollectionScope] = $9QJ9Y$radixuireactcollection.createCollection($0063afae63b3fa70$var$GROUP_NAME); -const [$0063afae63b3fa70$var$createRovingFocusGroupContext, $0063afae63b3fa70$export$c7109489551a4f4] = $9QJ9Y$radixuireactcontext.createContextScope($0063afae63b3fa70$var$GROUP_NAME, [$0063afae63b3fa70$var$createCollectionScope]); -const [$0063afae63b3fa70$var$RovingFocusProvider, $0063afae63b3fa70$var$useRovingFocusContext] = $0063afae63b3fa70$var$createRovingFocusGroupContext($0063afae63b3fa70$var$GROUP_NAME); -const $0063afae63b3fa70$export$8699f7c8af148338 = /*#__PURE__*/$9QJ9Y$react.forwardRef((props, forwardedRef) => { - return /*#__PURE__*/$9QJ9Y$react.createElement($0063afae63b3fa70$var$Collection.Provider, { - scope: props.__scopeRovingFocusGroup - }, /*#__PURE__*/$9QJ9Y$react.createElement($0063afae63b3fa70$var$Collection.Slot, { - scope: props.__scopeRovingFocusGroup - }, /*#__PURE__*/$9QJ9Y$react.createElement($0063afae63b3fa70$var$RovingFocusGroupImpl, $parcel$interopDefault($9QJ9Y$babelruntimehelpersextends)({}, props, { - ref: forwardedRef - })))); -}); -/*#__PURE__*/ -Object.assign($0063afae63b3fa70$export$8699f7c8af148338, { - displayName: $0063afae63b3fa70$var$GROUP_NAME -}); -/* -----------------------------------------------------------------------------------------------*/ -const $0063afae63b3fa70$var$RovingFocusGroupImpl = /*#__PURE__*/$9QJ9Y$react.forwardRef((props, forwardedRef) => { - const { - __scopeRovingFocusGroup: __scopeRovingFocusGroup, - orientation: orientation, - loop = false, - dir: dir, - currentTabStopId: currentTabStopIdProp, - defaultCurrentTabStopId: defaultCurrentTabStopId, - onCurrentTabStopIdChange: onCurrentTabStopIdChange, - onEntryFocus: onEntryFocus, - ...groupProps - } = props; - const ref = $9QJ9Y$react.useRef(null); - const composedRefs = $9QJ9Y$radixuireactcomposerefs.useComposedRefs(forwardedRef, ref); - const direction = $9QJ9Y$radixuireactdirection.useDirection(dir); - const [currentTabStopId = null, setCurrentTabStopId] = $9QJ9Y$radixuireactusecontrollablestate.useControllableState({ - prop: currentTabStopIdProp, - defaultProp: defaultCurrentTabStopId, - onChange: onCurrentTabStopIdChange - }); - const [isTabbingBackOut, setIsTabbingBackOut] = $9QJ9Y$react.useState(false); - const handleEntryFocus = $9QJ9Y$radixuireactusecallbackref.useCallbackRef(onEntryFocus); - const getItems = $0063afae63b3fa70$var$useCollection(__scopeRovingFocusGroup); - const isClickFocusRef = $9QJ9Y$react.useRef(false); - const [focusableItemsCount, setFocusableItemsCount] = $9QJ9Y$react.useState(0); - $9QJ9Y$react.useEffect(() => { - const node = ref.current; - if (node) { - node.addEventListener($0063afae63b3fa70$var$ENTRY_FOCUS, handleEntryFocus); - return () => node.removeEventListener($0063afae63b3fa70$var$ENTRY_FOCUS, handleEntryFocus); - } - }, [handleEntryFocus]); - return /*#__PURE__*/$9QJ9Y$react.createElement($0063afae63b3fa70$var$RovingFocusProvider, { - scope: __scopeRovingFocusGroup, - orientation: orientation, - dir: direction, - loop: loop, - currentTabStopId: currentTabStopId, - onItemFocus: $9QJ9Y$react.useCallback(tabStopId => setCurrentTabStopId(tabStopId), [setCurrentTabStopId]), - onItemShiftTab: $9QJ9Y$react.useCallback(() => setIsTabbingBackOut(true), []), - onFocusableItemAdd: $9QJ9Y$react.useCallback(() => setFocusableItemsCount(prevCount => prevCount + 1), []), - onFocusableItemRemove: $9QJ9Y$react.useCallback(() => setFocusableItemsCount(prevCount => prevCount - 1), []) - }, /*#__PURE__*/$9QJ9Y$react.createElement($9QJ9Y$radixuireactprimitive.Primitive.div, $parcel$interopDefault($9QJ9Y$babelruntimehelpersextends)({ - tabIndex: isTabbingBackOut || focusableItemsCount === 0 ? -1 : 0, - "data-orientation": orientation - }, groupProps, { - ref: composedRefs, - style: { - outline: 'none', - ...props.style - }, - onMouseDown: $9QJ9Y$radixuiprimitive.composeEventHandlers(props.onMouseDown, () => { - isClickFocusRef.current = true; - }), - onFocus: $9QJ9Y$radixuiprimitive.composeEventHandlers(props.onFocus, event => { - // We normally wouldn't need this check, because we already check - // that the focus is on the current target and not bubbling to it. - // We do this because Safari doesn't focus buttons when clicked, and - // instead, the wrapper will get focused and not through a bubbling event. - const isKeyboardFocus = !isClickFocusRef.current; - if (event.target === event.currentTarget && isKeyboardFocus && !isTabbingBackOut) { - const entryFocusEvent = new CustomEvent($0063afae63b3fa70$var$ENTRY_FOCUS, $0063afae63b3fa70$var$EVENT_OPTIONS); - event.currentTarget.dispatchEvent(entryFocusEvent); - if (!entryFocusEvent.defaultPrevented) { - const items = getItems().filter(item => item.focusable); - const activeItem = items.find(item => item.active); - const currentItem = items.find(item => item.id === currentTabStopId); - const candidateItems = [activeItem, currentItem, ...items].filter(Boolean); - const candidateNodes = candidateItems.map(item => item.ref.current); - $0063afae63b3fa70$var$focusFirst(candidateNodes); - } - } - isClickFocusRef.current = false; - }), - onBlur: $9QJ9Y$radixuiprimitive.composeEventHandlers(props.onBlur, () => setIsTabbingBackOut(false)) - }))); -}); -/* ------------------------------------------------------------------------------------------------- - * RovingFocusGroupItem - * -----------------------------------------------------------------------------------------------*/ -const $0063afae63b3fa70$var$ITEM_NAME = 'RovingFocusGroupItem'; -const $0063afae63b3fa70$export$ab9df7c53fe8454 = /*#__PURE__*/$9QJ9Y$react.forwardRef((props, forwardedRef) => { - const { - __scopeRovingFocusGroup: __scopeRovingFocusGroup, - focusable = true, - active = false, - tabStopId: tabStopId, - ...itemProps - } = props; - const autoId = $9QJ9Y$radixuireactid.useId(); - const id = tabStopId || autoId; - const context = $0063afae63b3fa70$var$useRovingFocusContext($0063afae63b3fa70$var$ITEM_NAME, __scopeRovingFocusGroup); - const isCurrentTabStop = context.currentTabStopId === id; - const getItems = $0063afae63b3fa70$var$useCollection(__scopeRovingFocusGroup); - const { - onFocusableItemAdd: onFocusableItemAdd, - onFocusableItemRemove: onFocusableItemRemove - } = context; - $9QJ9Y$react.useEffect(() => { - if (focusable) { - onFocusableItemAdd(); - return () => onFocusableItemRemove(); - } - }, [focusable, onFocusableItemAdd, onFocusableItemRemove]); - return /*#__PURE__*/$9QJ9Y$react.createElement($0063afae63b3fa70$var$Collection.ItemSlot, { - scope: __scopeRovingFocusGroup, - id: id, - focusable: focusable, - active: active - }, /*#__PURE__*/$9QJ9Y$react.createElement($9QJ9Y$radixuireactprimitive.Primitive.span, $parcel$interopDefault($9QJ9Y$babelruntimehelpersextends)({ - tabIndex: isCurrentTabStop ? 0 : -1, - "data-orientation": context.orientation - }, itemProps, { - ref: forwardedRef, - onMouseDown: $9QJ9Y$radixuiprimitive.composeEventHandlers(props.onMouseDown, event => { - // We prevent focusing non-focusable items on `mousedown`. - // Even though the item has tabIndex={-1}, that only means take it out of the tab order. - if (!focusable) event.preventDefault(); // Safari doesn't focus a button when clicked so we run our logic on mousedown also - else context.onItemFocus(id); - }), - onFocus: $9QJ9Y$radixuiprimitive.composeEventHandlers(props.onFocus, () => context.onItemFocus(id)), - onKeyDown: $9QJ9Y$radixuiprimitive.composeEventHandlers(props.onKeyDown, event => { - if (event.key === 'Tab' && event.shiftKey) { - context.onItemShiftTab(); - return; - } - if (event.target !== event.currentTarget) return; - const focusIntent = $0063afae63b3fa70$var$getFocusIntent(event, context.orientation, context.dir); - if (focusIntent !== undefined) { - event.preventDefault(); - const items = getItems().filter(item => item.focusable); - let candidateNodes = items.map(item => item.ref.current); - if (focusIntent === 'last') candidateNodes.reverse();else if (focusIntent === 'prev' || focusIntent === 'next') { - if (focusIntent === 'prev') candidateNodes.reverse(); - const currentIndex = candidateNodes.indexOf(event.currentTarget); - candidateNodes = context.loop ? $0063afae63b3fa70$var$wrapArray(candidateNodes, currentIndex + 1) : candidateNodes.slice(currentIndex + 1); - } - /** - * Imperative focus during keydown is risky so we prevent React's batching updates - * to avoid potential bugs. See: https://github.com/facebook/react/issues/20332 - */ - setTimeout(() => $0063afae63b3fa70$var$focusFirst(candidateNodes)); - } - }) - }))); -}); -/*#__PURE__*/ -Object.assign($0063afae63b3fa70$export$ab9df7c53fe8454, { - displayName: $0063afae63b3fa70$var$ITEM_NAME -}); -/* -----------------------------------------------------------------------------------------------*/ // prettier-ignore -const $0063afae63b3fa70$var$MAP_KEY_TO_FOCUS_INTENT = { - ArrowLeft: 'prev', - ArrowUp: 'prev', - ArrowRight: 'next', - ArrowDown: 'next', - PageUp: 'first', - Home: 'first', - PageDown: 'last', - End: 'last' -}; -function $0063afae63b3fa70$var$getDirectionAwareKey(key, dir) { - if (dir !== 'rtl') return key; - return key === 'ArrowLeft' ? 'ArrowRight' : key === 'ArrowRight' ? 'ArrowLeft' : key; -} -function $0063afae63b3fa70$var$getFocusIntent(event, orientation, dir) { - const key = $0063afae63b3fa70$var$getDirectionAwareKey(event.key, dir); - if (orientation === 'vertical' && ['ArrowLeft', 'ArrowRight'].includes(key)) return undefined; - if (orientation === 'horizontal' && ['ArrowUp', 'ArrowDown'].includes(key)) return undefined; - return $0063afae63b3fa70$var$MAP_KEY_TO_FOCUS_INTENT[key]; -} -function $0063afae63b3fa70$var$focusFirst(candidates) { - const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement; - for (const candidate of candidates) { - // if focus is already where we want to go, we don't want to keep going through the candidates - if (candidate === PREVIOUSLY_FOCUSED_ELEMENT) return; - candidate.focus(); - if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT) return; - } -} -/** - * Wraps an array around itself at a given start index - * Example: `wrapArray(['a', 'b', 'c', 'd'], 2) === ['c', 'd', 'a', 'b']` - */ -function $0063afae63b3fa70$var$wrapArray(array, startIndex) { - return array.map((_, index) => array[(startIndex + index) % array.length]); -} -const $0063afae63b3fa70$export$be92b6f5f03c0fe9 = $0063afae63b3fa70$export$8699f7c8af148338; -const $0063afae63b3fa70$export$6d08773d2e66f8f2 = $0063afae63b3fa70$export$ab9df7c53fe8454; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-slot/dist/index.js": -/*!****************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-slot/dist/index.js ***! - \****************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var $dAvBt$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); -var $dAvBt$react = __webpack_require__(/*! react */ "react"); -var $dAvBt$radixuireactcomposerefs = __webpack_require__(/*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "Slot", () => $82dc8d030dec7549$export$8c6ed5c666ac1360); -$parcel$export(module.exports, "Slottable", () => $82dc8d030dec7549$export$d9f1ccf0bdb05d45); -$parcel$export(module.exports, "Root", () => $82dc8d030dec7549$export$be92b6f5f03c0fe9); - -/* ------------------------------------------------------------------------------------------------- - * Slot - * -----------------------------------------------------------------------------------------------*/ -const $82dc8d030dec7549$export$8c6ed5c666ac1360 = /*#__PURE__*/$dAvBt$react.forwardRef((props, forwardedRef) => { - const { - children: children, - ...slotProps - } = props; - const childrenArray = $dAvBt$react.Children.toArray(children); - const slottable = childrenArray.find($82dc8d030dec7549$var$isSlottable); - if (slottable) { - // the new element to render is the one passed as a child of `Slottable` - const newElement = slottable.props.children; - const newChildren = childrenArray.map(child => { - if (child === slottable) { - // because the new element will be the one rendered, we are only interested - // in grabbing its children (`newElement.props.children`) - if ($dAvBt$react.Children.count(newElement) > 1) return $dAvBt$react.Children.only(null); - return /*#__PURE__*/$dAvBt$react.isValidElement(newElement) ? newElement.props.children : null; - } else return child; - }); - return /*#__PURE__*/$dAvBt$react.createElement($82dc8d030dec7549$var$SlotClone, $parcel$interopDefault($dAvBt$babelruntimehelpersextends)({}, slotProps, { - ref: forwardedRef - }), /*#__PURE__*/$dAvBt$react.isValidElement(newElement) ? /*#__PURE__*/$dAvBt$react.cloneElement(newElement, undefined, newChildren) : null); - } - return /*#__PURE__*/$dAvBt$react.createElement($82dc8d030dec7549$var$SlotClone, $parcel$interopDefault($dAvBt$babelruntimehelpersextends)({}, slotProps, { - ref: forwardedRef - }), children); -}); -$82dc8d030dec7549$export$8c6ed5c666ac1360.displayName = 'Slot'; -/* ------------------------------------------------------------------------------------------------- - * SlotClone - * -----------------------------------------------------------------------------------------------*/ -const $82dc8d030dec7549$var$SlotClone = /*#__PURE__*/$dAvBt$react.forwardRef((props, forwardedRef) => { - const { - children: children, - ...slotProps - } = props; - if ( /*#__PURE__*/$dAvBt$react.isValidElement(children)) return /*#__PURE__*/$dAvBt$react.cloneElement(children, { - ...$82dc8d030dec7549$var$mergeProps(slotProps, children.props), - ref: forwardedRef ? $dAvBt$radixuireactcomposerefs.composeRefs(forwardedRef, children.ref) : children.ref - }); - return $dAvBt$react.Children.count(children) > 1 ? $dAvBt$react.Children.only(null) : null; -}); -$82dc8d030dec7549$var$SlotClone.displayName = 'SlotClone'; -/* ------------------------------------------------------------------------------------------------- - * Slottable - * -----------------------------------------------------------------------------------------------*/ -const $82dc8d030dec7549$export$d9f1ccf0bdb05d45 = ({ - children: children -}) => { - return /*#__PURE__*/$dAvBt$react.createElement($dAvBt$react.Fragment, null, children); -}; -/* ---------------------------------------------------------------------------------------------- */ -function $82dc8d030dec7549$var$isSlottable(child) { - return /*#__PURE__*/$dAvBt$react.isValidElement(child) && child.type === $82dc8d030dec7549$export$d9f1ccf0bdb05d45; -} -function $82dc8d030dec7549$var$mergeProps(slotProps, childProps) { - // all child props should override - const overrideProps = { - ...childProps - }; - for (const propName in childProps) { - const slotPropValue = slotProps[propName]; - const childPropValue = childProps[propName]; - const isHandler = /^on[A-Z]/.test(propName); - if (isHandler) { - // if the handler exists on both, we compose them - if (slotPropValue && childPropValue) overrideProps[propName] = (...args) => { - childPropValue(...args); - slotPropValue(...args); - };else if (slotPropValue) overrideProps[propName] = slotPropValue; - } else if (propName === 'style') overrideProps[propName] = { - ...slotPropValue, - ...childPropValue - };else if (propName === 'className') overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(' '); - } - return { - ...slotProps, - ...overrideProps - }; -} -const $82dc8d030dec7549$export$be92b6f5f03c0fe9 = $82dc8d030dec7549$export$8c6ed5c666ac1360; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-tooltip/dist/index.js": -/*!*******************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-tooltip/dist/index.js ***! - \*******************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var $iVrL9$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); -var $iVrL9$react = __webpack_require__(/*! react */ "react"); -var $iVrL9$radixuiprimitive = __webpack_require__(/*! @radix-ui/primitive */ "../../../node_modules/@radix-ui/primitive/dist/index.js"); -var $iVrL9$radixuireactcomposerefs = __webpack_require__(/*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js"); -var $iVrL9$radixuireactcontext = __webpack_require__(/*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js"); -var $iVrL9$radixuireactdismissablelayer = __webpack_require__(/*! @radix-ui/react-dismissable-layer */ "../../../node_modules/@radix-ui/react-dismissable-layer/dist/index.js"); -var $iVrL9$radixuireactid = __webpack_require__(/*! @radix-ui/react-id */ "../../../node_modules/@radix-ui/react-id/dist/index.js"); -var $iVrL9$radixuireactpopper = __webpack_require__(/*! @radix-ui/react-popper */ "../../../node_modules/@radix-ui/react-popper/dist/index.js"); -var $iVrL9$radixuireactportal = __webpack_require__(/*! @radix-ui/react-portal */ "../../../node_modules/@radix-ui/react-portal/dist/index.js"); -var $iVrL9$radixuireactpresence = __webpack_require__(/*! @radix-ui/react-presence */ "../../../node_modules/@radix-ui/react-presence/dist/index.js"); -var $iVrL9$radixuireactprimitive = __webpack_require__(/*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js"); -var $iVrL9$radixuireactslot = __webpack_require__(/*! @radix-ui/react-slot */ "../../../node_modules/@radix-ui/react-slot/dist/index.js"); -var $iVrL9$radixuireactusecontrollablestate = __webpack_require__(/*! @radix-ui/react-use-controllable-state */ "../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js"); -var $iVrL9$radixuireactvisuallyhidden = __webpack_require__(/*! @radix-ui/react-visually-hidden */ "../../../node_modules/@radix-ui/react-visually-hidden/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "createTooltipScope", () => $c34afbc43c90cc6f$export$1c540a2224f0d865); -$parcel$export(module.exports, "TooltipProvider", () => $c34afbc43c90cc6f$export$f78649fb9ca566b8); -$parcel$export(module.exports, "Tooltip", () => $c34afbc43c90cc6f$export$28c660c63b792dea); -$parcel$export(module.exports, "TooltipTrigger", () => $c34afbc43c90cc6f$export$8c610744efcf8a1d); -$parcel$export(module.exports, "TooltipPortal", () => $c34afbc43c90cc6f$export$7b36b8f925ab7497); -$parcel$export(module.exports, "TooltipContent", () => $c34afbc43c90cc6f$export$e9003e2be37ec060); -$parcel$export(module.exports, "TooltipArrow", () => $c34afbc43c90cc6f$export$c27ee0ad710f7559); -$parcel$export(module.exports, "Provider", () => $c34afbc43c90cc6f$export$2881499e37b75b9a); -$parcel$export(module.exports, "Root", () => $c34afbc43c90cc6f$export$be92b6f5f03c0fe9); -$parcel$export(module.exports, "Trigger", () => $c34afbc43c90cc6f$export$41fb9f06171c75f4); -$parcel$export(module.exports, "Portal", () => $c34afbc43c90cc6f$export$602eac185826482c); -$parcel$export(module.exports, "Content", () => $c34afbc43c90cc6f$export$7c6e2c02157bb7d2); -$parcel$export(module.exports, "Arrow", () => $c34afbc43c90cc6f$export$21b07c8f274aebd5); -const [$c34afbc43c90cc6f$var$createTooltipContext, $c34afbc43c90cc6f$export$1c540a2224f0d865] = $iVrL9$radixuireactcontext.createContextScope('Tooltip', [$iVrL9$radixuireactpopper.createPopperScope]); -const $c34afbc43c90cc6f$var$usePopperScope = $iVrL9$radixuireactpopper.createPopperScope(); -/* ------------------------------------------------------------------------------------------------- - * TooltipProvider - * -----------------------------------------------------------------------------------------------*/ -const $c34afbc43c90cc6f$var$PROVIDER_NAME = 'TooltipProvider'; -const $c34afbc43c90cc6f$var$DEFAULT_DELAY_DURATION = 700; -const $c34afbc43c90cc6f$var$TOOLTIP_OPEN = 'tooltip.open'; -const [$c34afbc43c90cc6f$var$TooltipProviderContextProvider, $c34afbc43c90cc6f$var$useTooltipProviderContext] = $c34afbc43c90cc6f$var$createTooltipContext($c34afbc43c90cc6f$var$PROVIDER_NAME); -const $c34afbc43c90cc6f$export$f78649fb9ca566b8 = props => { - const { - __scopeTooltip: __scopeTooltip, - delayDuration = $c34afbc43c90cc6f$var$DEFAULT_DELAY_DURATION, - skipDelayDuration = 300, - disableHoverableContent = false, - children: children - } = props; - const [isOpenDelayed, setIsOpenDelayed] = $iVrL9$react.useState(true); - const isPointerInTransitRef = $iVrL9$react.useRef(false); - const skipDelayTimerRef = $iVrL9$react.useRef(0); - $iVrL9$react.useEffect(() => { - const skipDelayTimer = skipDelayTimerRef.current; - return () => window.clearTimeout(skipDelayTimer); - }, []); - return /*#__PURE__*/$iVrL9$react.createElement($c34afbc43c90cc6f$var$TooltipProviderContextProvider, { - scope: __scopeTooltip, - isOpenDelayed: isOpenDelayed, - delayDuration: delayDuration, - onOpen: $iVrL9$react.useCallback(() => { - window.clearTimeout(skipDelayTimerRef.current); - setIsOpenDelayed(false); - }, []), - onClose: $iVrL9$react.useCallback(() => { - window.clearTimeout(skipDelayTimerRef.current); - skipDelayTimerRef.current = window.setTimeout(() => setIsOpenDelayed(true), skipDelayDuration); - }, [skipDelayDuration]), - isPointerInTransitRef: isPointerInTransitRef, - onPointerInTransitChange: $iVrL9$react.useCallback(inTransit => { - isPointerInTransitRef.current = inTransit; - }, []), - disableHoverableContent: disableHoverableContent - }, children); -}; -/*#__PURE__*/ -Object.assign($c34afbc43c90cc6f$export$f78649fb9ca566b8, { - displayName: $c34afbc43c90cc6f$var$PROVIDER_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * Tooltip - * -----------------------------------------------------------------------------------------------*/ -const $c34afbc43c90cc6f$var$TOOLTIP_NAME = 'Tooltip'; -const [$c34afbc43c90cc6f$var$TooltipContextProvider, $c34afbc43c90cc6f$var$useTooltipContext] = $c34afbc43c90cc6f$var$createTooltipContext($c34afbc43c90cc6f$var$TOOLTIP_NAME); -const $c34afbc43c90cc6f$export$28c660c63b792dea = props => { - const { - __scopeTooltip: __scopeTooltip, - children: children, - open: openProp, - defaultOpen = false, - onOpenChange: onOpenChange, - disableHoverableContent: disableHoverableContentProp, - delayDuration: delayDurationProp - } = props; - const providerContext = $c34afbc43c90cc6f$var$useTooltipProviderContext($c34afbc43c90cc6f$var$TOOLTIP_NAME, props.__scopeTooltip); - const popperScope = $c34afbc43c90cc6f$var$usePopperScope(__scopeTooltip); - const [trigger, setTrigger] = $iVrL9$react.useState(null); - const contentId = $iVrL9$radixuireactid.useId(); - const openTimerRef = $iVrL9$react.useRef(0); - const disableHoverableContent = disableHoverableContentProp !== null && disableHoverableContentProp !== void 0 ? disableHoverableContentProp : providerContext.disableHoverableContent; - const delayDuration = delayDurationProp !== null && delayDurationProp !== void 0 ? delayDurationProp : providerContext.delayDuration; - const wasOpenDelayedRef = $iVrL9$react.useRef(false); - const [open1 = false, setOpen] = $iVrL9$radixuireactusecontrollablestate.useControllableState({ - prop: openProp, - defaultProp: defaultOpen, - onChange: open => { - if (open) { - providerContext.onOpen(); // as `onChange` is called within a lifecycle method we - // avoid dispatching via `dispatchDiscreteCustomEvent`. - document.dispatchEvent(new CustomEvent($c34afbc43c90cc6f$var$TOOLTIP_OPEN)); - } else providerContext.onClose(); - onOpenChange === null || onOpenChange === void 0 || onOpenChange(open); - } - }); - const stateAttribute = $iVrL9$react.useMemo(() => { - return open1 ? wasOpenDelayedRef.current ? 'delayed-open' : 'instant-open' : 'closed'; - }, [open1]); - const handleOpen = $iVrL9$react.useCallback(() => { - window.clearTimeout(openTimerRef.current); - wasOpenDelayedRef.current = false; - setOpen(true); - }, [setOpen]); - const handleClose = $iVrL9$react.useCallback(() => { - window.clearTimeout(openTimerRef.current); - setOpen(false); - }, [setOpen]); - const handleDelayedOpen = $iVrL9$react.useCallback(() => { - window.clearTimeout(openTimerRef.current); - openTimerRef.current = window.setTimeout(() => { - wasOpenDelayedRef.current = true; - setOpen(true); - }, delayDuration); - }, [delayDuration, setOpen]); - $iVrL9$react.useEffect(() => { - return () => window.clearTimeout(openTimerRef.current); - }, []); - return /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactpopper.Root, popperScope, /*#__PURE__*/$iVrL9$react.createElement($c34afbc43c90cc6f$var$TooltipContextProvider, { - scope: __scopeTooltip, - contentId: contentId, - open: open1, - stateAttribute: stateAttribute, - trigger: trigger, - onTriggerChange: setTrigger, - onTriggerEnter: $iVrL9$react.useCallback(() => { - if (providerContext.isOpenDelayed) handleDelayedOpen();else handleOpen(); - }, [providerContext.isOpenDelayed, handleDelayedOpen, handleOpen]), - onTriggerLeave: $iVrL9$react.useCallback(() => { - if (disableHoverableContent) handleClose();else - // Clear the timer in case the pointer leaves the trigger before the tooltip is opened. - window.clearTimeout(openTimerRef.current); - }, [handleClose, disableHoverableContent]), - onOpen: handleOpen, - onClose: handleClose, - disableHoverableContent: disableHoverableContent - }, children)); -}; -/*#__PURE__*/ -Object.assign($c34afbc43c90cc6f$export$28c660c63b792dea, { - displayName: $c34afbc43c90cc6f$var$TOOLTIP_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * TooltipTrigger - * -----------------------------------------------------------------------------------------------*/ -const $c34afbc43c90cc6f$var$TRIGGER_NAME = 'TooltipTrigger'; -const $c34afbc43c90cc6f$export$8c610744efcf8a1d = /*#__PURE__*/$iVrL9$react.forwardRef((props, forwardedRef) => { - const { - __scopeTooltip: __scopeTooltip, - ...triggerProps - } = props; - const context = $c34afbc43c90cc6f$var$useTooltipContext($c34afbc43c90cc6f$var$TRIGGER_NAME, __scopeTooltip); - const providerContext = $c34afbc43c90cc6f$var$useTooltipProviderContext($c34afbc43c90cc6f$var$TRIGGER_NAME, __scopeTooltip); - const popperScope = $c34afbc43c90cc6f$var$usePopperScope(__scopeTooltip); - const ref = $iVrL9$react.useRef(null); - const composedRefs = $iVrL9$radixuireactcomposerefs.useComposedRefs(forwardedRef, ref, context.onTriggerChange); - const isPointerDownRef = $iVrL9$react.useRef(false); - const hasPointerMoveOpenedRef = $iVrL9$react.useRef(false); - const handlePointerUp = $iVrL9$react.useCallback(() => isPointerDownRef.current = false, []); - $iVrL9$react.useEffect(() => { - return () => document.removeEventListener('pointerup', handlePointerUp); - }, [handlePointerUp]); - return /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactpopper.Anchor, $parcel$interopDefault($iVrL9$babelruntimehelpersextends)({ - asChild: true - }, popperScope), /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactprimitive.Primitive.button, $parcel$interopDefault($iVrL9$babelruntimehelpersextends)({ - // We purposefully avoid adding `type=button` here because tooltip triggers are also - // commonly anchors and the anchor `type` attribute signifies MIME type. - "aria-describedby": context.open ? context.contentId : undefined, - "data-state": context.stateAttribute - }, triggerProps, { - ref: composedRefs, - onPointerMove: $iVrL9$radixuiprimitive.composeEventHandlers(props.onPointerMove, event => { - if (event.pointerType === 'touch') return; - if (!hasPointerMoveOpenedRef.current && !providerContext.isPointerInTransitRef.current) { - context.onTriggerEnter(); - hasPointerMoveOpenedRef.current = true; - } - }), - onPointerLeave: $iVrL9$radixuiprimitive.composeEventHandlers(props.onPointerLeave, () => { - context.onTriggerLeave(); - hasPointerMoveOpenedRef.current = false; - }), - onPointerDown: $iVrL9$radixuiprimitive.composeEventHandlers(props.onPointerDown, () => { - isPointerDownRef.current = true; - document.addEventListener('pointerup', handlePointerUp, { - once: true - }); - }), - onFocus: $iVrL9$radixuiprimitive.composeEventHandlers(props.onFocus, () => { - if (!isPointerDownRef.current) context.onOpen(); - }), - onBlur: $iVrL9$radixuiprimitive.composeEventHandlers(props.onBlur, context.onClose), - onClick: $iVrL9$radixuiprimitive.composeEventHandlers(props.onClick, context.onClose) - }))); -}); -/*#__PURE__*/ -Object.assign($c34afbc43c90cc6f$export$8c610744efcf8a1d, { - displayName: $c34afbc43c90cc6f$var$TRIGGER_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * TooltipPortal - * -----------------------------------------------------------------------------------------------*/ -const $c34afbc43c90cc6f$var$PORTAL_NAME = 'TooltipPortal'; -const [$c34afbc43c90cc6f$var$PortalProvider, $c34afbc43c90cc6f$var$usePortalContext] = $c34afbc43c90cc6f$var$createTooltipContext($c34afbc43c90cc6f$var$PORTAL_NAME, { - forceMount: undefined -}); -const $c34afbc43c90cc6f$export$7b36b8f925ab7497 = props => { - const { - __scopeTooltip: __scopeTooltip, - forceMount: forceMount, - children: children, - container: container - } = props; - const context = $c34afbc43c90cc6f$var$useTooltipContext($c34afbc43c90cc6f$var$PORTAL_NAME, __scopeTooltip); - return /*#__PURE__*/$iVrL9$react.createElement($c34afbc43c90cc6f$var$PortalProvider, { - scope: __scopeTooltip, - forceMount: forceMount - }, /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactpresence.Presence, { - present: forceMount || context.open - }, /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactportal.Portal, { - asChild: true, - container: container - }, children))); -}; -/*#__PURE__*/ -Object.assign($c34afbc43c90cc6f$export$7b36b8f925ab7497, { - displayName: $c34afbc43c90cc6f$var$PORTAL_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * TooltipContent - * -----------------------------------------------------------------------------------------------*/ -const $c34afbc43c90cc6f$var$CONTENT_NAME = 'TooltipContent'; -const $c34afbc43c90cc6f$export$e9003e2be37ec060 = /*#__PURE__*/$iVrL9$react.forwardRef((props, forwardedRef) => { - const portalContext = $c34afbc43c90cc6f$var$usePortalContext($c34afbc43c90cc6f$var$CONTENT_NAME, props.__scopeTooltip); - const { - forceMount = portalContext.forceMount, - side = 'top', - ...contentProps - } = props; - const context = $c34afbc43c90cc6f$var$useTooltipContext($c34afbc43c90cc6f$var$CONTENT_NAME, props.__scopeTooltip); - return /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactpresence.Presence, { - present: forceMount || context.open - }, context.disableHoverableContent ? /*#__PURE__*/$iVrL9$react.createElement($c34afbc43c90cc6f$var$TooltipContentImpl, $parcel$interopDefault($iVrL9$babelruntimehelpersextends)({ - side: side - }, contentProps, { - ref: forwardedRef - })) : /*#__PURE__*/$iVrL9$react.createElement($c34afbc43c90cc6f$var$TooltipContentHoverable, $parcel$interopDefault($iVrL9$babelruntimehelpersextends)({ - side: side - }, contentProps, { - ref: forwardedRef - }))); -}); -const $c34afbc43c90cc6f$var$TooltipContentHoverable = /*#__PURE__*/$iVrL9$react.forwardRef((props, forwardedRef) => { - const context = $c34afbc43c90cc6f$var$useTooltipContext($c34afbc43c90cc6f$var$CONTENT_NAME, props.__scopeTooltip); - const providerContext = $c34afbc43c90cc6f$var$useTooltipProviderContext($c34afbc43c90cc6f$var$CONTENT_NAME, props.__scopeTooltip); - const ref = $iVrL9$react.useRef(null); - const composedRefs = $iVrL9$radixuireactcomposerefs.useComposedRefs(forwardedRef, ref); - const [pointerGraceArea, setPointerGraceArea] = $iVrL9$react.useState(null); - const { - trigger: trigger, - onClose: onClose - } = context; - const content = ref.current; - const { - onPointerInTransitChange: onPointerInTransitChange - } = providerContext; - const handleRemoveGraceArea = $iVrL9$react.useCallback(() => { - setPointerGraceArea(null); - onPointerInTransitChange(false); - }, [onPointerInTransitChange]); - const handleCreateGraceArea = $iVrL9$react.useCallback((event, hoverTarget) => { - const currentTarget = event.currentTarget; - const exitPoint = { - x: event.clientX, - y: event.clientY - }; - const exitSide = $c34afbc43c90cc6f$var$getExitSideFromRect(exitPoint, currentTarget.getBoundingClientRect()); - const paddedExitPoints = $c34afbc43c90cc6f$var$getPaddedExitPoints(exitPoint, exitSide); - const hoverTargetPoints = $c34afbc43c90cc6f$var$getPointsFromRect(hoverTarget.getBoundingClientRect()); - const graceArea = $c34afbc43c90cc6f$var$getHull([...paddedExitPoints, ...hoverTargetPoints]); - setPointerGraceArea(graceArea); - onPointerInTransitChange(true); - }, [onPointerInTransitChange]); - $iVrL9$react.useEffect(() => { - return () => handleRemoveGraceArea(); - }, [handleRemoveGraceArea]); - $iVrL9$react.useEffect(() => { - if (trigger && content) { - const handleTriggerLeave = event => handleCreateGraceArea(event, content); - const handleContentLeave = event => handleCreateGraceArea(event, trigger); - trigger.addEventListener('pointerleave', handleTriggerLeave); - content.addEventListener('pointerleave', handleContentLeave); - return () => { - trigger.removeEventListener('pointerleave', handleTriggerLeave); - content.removeEventListener('pointerleave', handleContentLeave); - }; - } - }, [trigger, content, handleCreateGraceArea, handleRemoveGraceArea]); - $iVrL9$react.useEffect(() => { - if (pointerGraceArea) { - const handleTrackPointerGrace = event => { - const target = event.target; - const pointerPosition = { - x: event.clientX, - y: event.clientY - }; - const hasEnteredTarget = (trigger === null || trigger === void 0 ? void 0 : trigger.contains(target)) || (content === null || content === void 0 ? void 0 : content.contains(target)); - const isPointerOutsideGraceArea = !$c34afbc43c90cc6f$var$isPointInPolygon(pointerPosition, pointerGraceArea); - if (hasEnteredTarget) handleRemoveGraceArea();else if (isPointerOutsideGraceArea) { - handleRemoveGraceArea(); - onClose(); - } - }; - document.addEventListener('pointermove', handleTrackPointerGrace); - return () => document.removeEventListener('pointermove', handleTrackPointerGrace); - } - }, [trigger, content, pointerGraceArea, onClose, handleRemoveGraceArea]); - return /*#__PURE__*/$iVrL9$react.createElement($c34afbc43c90cc6f$var$TooltipContentImpl, $parcel$interopDefault($iVrL9$babelruntimehelpersextends)({}, props, { - ref: composedRefs - })); -}); -const [$c34afbc43c90cc6f$var$VisuallyHiddenContentContextProvider, $c34afbc43c90cc6f$var$useVisuallyHiddenContentContext] = $c34afbc43c90cc6f$var$createTooltipContext($c34afbc43c90cc6f$var$TOOLTIP_NAME, { - isInside: false -}); -const $c34afbc43c90cc6f$var$TooltipContentImpl = /*#__PURE__*/$iVrL9$react.forwardRef((props, forwardedRef) => { - const { - __scopeTooltip: __scopeTooltip, - children: children, - 'aria-label': ariaLabel, - onEscapeKeyDown: onEscapeKeyDown, - onPointerDownOutside: onPointerDownOutside, - ...contentProps - } = props; - const context = $c34afbc43c90cc6f$var$useTooltipContext($c34afbc43c90cc6f$var$CONTENT_NAME, __scopeTooltip); - const popperScope = $c34afbc43c90cc6f$var$usePopperScope(__scopeTooltip); - const { - onClose: onClose - } = context; // Close this tooltip if another one opens - $iVrL9$react.useEffect(() => { - document.addEventListener($c34afbc43c90cc6f$var$TOOLTIP_OPEN, onClose); - return () => document.removeEventListener($c34afbc43c90cc6f$var$TOOLTIP_OPEN, onClose); - }, [onClose]); // Close the tooltip if the trigger is scrolled - $iVrL9$react.useEffect(() => { - if (context.trigger) { - const handleScroll = event => { - const target = event.target; - if (target !== null && target !== void 0 && target.contains(context.trigger)) onClose(); - }; - window.addEventListener('scroll', handleScroll, { - capture: true - }); - return () => window.removeEventListener('scroll', handleScroll, { - capture: true - }); - } - }, [context.trigger, onClose]); - return /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactdismissablelayer.DismissableLayer, { - asChild: true, - disableOutsidePointerEvents: false, - onEscapeKeyDown: onEscapeKeyDown, - onPointerDownOutside: onPointerDownOutside, - onFocusOutside: event => event.preventDefault(), - onDismiss: onClose - }, /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactpopper.Content, $parcel$interopDefault($iVrL9$babelruntimehelpersextends)({ - "data-state": context.stateAttribute - }, popperScope, contentProps, { - ref: forwardedRef, - style: { - ...contentProps.style, - '--radix-tooltip-content-transform-origin': 'var(--radix-popper-transform-origin)', - '--radix-tooltip-content-available-width': 'var(--radix-popper-available-width)', - '--radix-tooltip-content-available-height': 'var(--radix-popper-available-height)', - '--radix-tooltip-trigger-width': 'var(--radix-popper-anchor-width)', - '--radix-tooltip-trigger-height': 'var(--radix-popper-anchor-height)' - } - }), /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactslot.Slottable, null, children), /*#__PURE__*/$iVrL9$react.createElement($c34afbc43c90cc6f$var$VisuallyHiddenContentContextProvider, { - scope: __scopeTooltip, - isInside: true - }, /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactvisuallyhidden.Root, { - id: context.contentId, - role: "tooltip" - }, ariaLabel || children)))); -}); -/*#__PURE__*/ -Object.assign($c34afbc43c90cc6f$export$e9003e2be37ec060, { - displayName: $c34afbc43c90cc6f$var$CONTENT_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * TooltipArrow - * -----------------------------------------------------------------------------------------------*/ -const $c34afbc43c90cc6f$var$ARROW_NAME = 'TooltipArrow'; -const $c34afbc43c90cc6f$export$c27ee0ad710f7559 = /*#__PURE__*/$iVrL9$react.forwardRef((props, forwardedRef) => { - const { - __scopeTooltip: __scopeTooltip, - ...arrowProps - } = props; - const popperScope = $c34afbc43c90cc6f$var$usePopperScope(__scopeTooltip); - const visuallyHiddenContentContext = $c34afbc43c90cc6f$var$useVisuallyHiddenContentContext($c34afbc43c90cc6f$var$ARROW_NAME, __scopeTooltip); // if the arrow is inside the `VisuallyHidden`, we don't want to render it all to - // prevent issues in positioning the arrow due to the duplicate - return visuallyHiddenContentContext.isInside ? null : /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactpopper.Arrow, $parcel$interopDefault($iVrL9$babelruntimehelpersextends)({}, popperScope, arrowProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($c34afbc43c90cc6f$export$c27ee0ad710f7559, { - displayName: $c34afbc43c90cc6f$var$ARROW_NAME -}); -/* -----------------------------------------------------------------------------------------------*/ -function $c34afbc43c90cc6f$var$getExitSideFromRect(point, rect) { - const top = Math.abs(rect.top - point.y); - const bottom = Math.abs(rect.bottom - point.y); - const right = Math.abs(rect.right - point.x); - const left = Math.abs(rect.left - point.x); - switch (Math.min(top, bottom, right, left)) { - case left: - return 'left'; - case right: - return 'right'; - case top: - return 'top'; - case bottom: - return 'bottom'; - default: - throw new Error('unreachable'); - } -} -function $c34afbc43c90cc6f$var$getPaddedExitPoints(exitPoint, exitSide, padding = 5) { - const paddedExitPoints = []; - switch (exitSide) { - case 'top': - paddedExitPoints.push({ - x: exitPoint.x - padding, - y: exitPoint.y + padding - }, { - x: exitPoint.x + padding, - y: exitPoint.y + padding - }); - break; - case 'bottom': - paddedExitPoints.push({ - x: exitPoint.x - padding, - y: exitPoint.y - padding - }, { - x: exitPoint.x + padding, - y: exitPoint.y - padding - }); - break; - case 'left': - paddedExitPoints.push({ - x: exitPoint.x + padding, - y: exitPoint.y - padding - }, { - x: exitPoint.x + padding, - y: exitPoint.y + padding - }); - break; - case 'right': - paddedExitPoints.push({ - x: exitPoint.x - padding, - y: exitPoint.y - padding - }, { - x: exitPoint.x - padding, - y: exitPoint.y + padding - }); - break; - } - return paddedExitPoints; -} -function $c34afbc43c90cc6f$var$getPointsFromRect(rect) { - const { - top: top, - right: right, - bottom: bottom, - left: left - } = rect; - return [{ - x: left, - y: top - }, { - x: right, - y: top - }, { - x: right, - y: bottom - }, { - x: left, - y: bottom - }]; -} // Determine if a point is inside of a polygon. -// Based on https://github.com/substack/point-in-polygon -function $c34afbc43c90cc6f$var$isPointInPolygon(point, polygon) { - const { - x: x, - y: y - } = point; - let inside = false; - for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { - const xi = polygon[i].x; - const yi = polygon[i].y; - const xj = polygon[j].x; - const yj = polygon[j].y; // prettier-ignore - const intersect = yi > y !== yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi; - if (intersect) inside = !inside; - } - return inside; -} // Returns a new array of points representing the convex hull of the given set of points. -// https://www.nayuki.io/page/convex-hull-algorithm -function $c34afbc43c90cc6f$var$getHull(points) { - const newPoints = points.slice(); - newPoints.sort((a, b) => { - if (a.x < b.x) return -1;else if (a.x > b.x) return 1;else if (a.y < b.y) return -1;else if (a.y > b.y) return 1;else return 0; - }); - return $c34afbc43c90cc6f$var$getHullPresorted(newPoints); -} // Returns the convex hull, assuming that each points[i] <= points[i + 1]. Runs in O(n) time. -function $c34afbc43c90cc6f$var$getHullPresorted(points) { - if (points.length <= 1) return points.slice(); - const upperHull = []; - for (let i = 0; i < points.length; i++) { - const p = points[i]; - while (upperHull.length >= 2) { - const q = upperHull[upperHull.length - 1]; - const r = upperHull[upperHull.length - 2]; - if ((q.x - r.x) * (p.y - r.y) >= (q.y - r.y) * (p.x - r.x)) upperHull.pop();else break; - } - upperHull.push(p); - } - upperHull.pop(); - const lowerHull = []; - for (let i1 = points.length - 1; i1 >= 0; i1--) { - const p = points[i1]; - while (lowerHull.length >= 2) { - const q = lowerHull[lowerHull.length - 1]; - const r = lowerHull[lowerHull.length - 2]; - if ((q.x - r.x) * (p.y - r.y) >= (q.y - r.y) * (p.x - r.x)) lowerHull.pop();else break; - } - lowerHull.push(p); - } - lowerHull.pop(); - if (upperHull.length === 1 && lowerHull.length === 1 && upperHull[0].x === lowerHull[0].x && upperHull[0].y === lowerHull[0].y) return upperHull;else return upperHull.concat(lowerHull); -} -const $c34afbc43c90cc6f$export$2881499e37b75b9a = $c34afbc43c90cc6f$export$f78649fb9ca566b8; -const $c34afbc43c90cc6f$export$be92b6f5f03c0fe9 = $c34afbc43c90cc6f$export$28c660c63b792dea; -const $c34afbc43c90cc6f$export$41fb9f06171c75f4 = $c34afbc43c90cc6f$export$8c610744efcf8a1d; -const $c34afbc43c90cc6f$export$602eac185826482c = $c34afbc43c90cc6f$export$7b36b8f925ab7497; -const $c34afbc43c90cc6f$export$7c6e2c02157bb7d2 = $c34afbc43c90cc6f$export$e9003e2be37ec060; -const $c34afbc43c90cc6f$export$21b07c8f274aebd5 = $c34afbc43c90cc6f$export$c27ee0ad710f7559; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js": -/*!****************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js ***! - \****************************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var $92muK$react = __webpack_require__(/*! react */ "react"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -$parcel$export(module.exports, "useCallbackRef", () => $28e03942f763e819$export$25bec8c6f54ee79a); - -/** - * A custom hook that converts a callback to a ref to avoid triggering re-renders when passed as a - * prop or avoid re-executing effects when passed as a dependency - */ -function $28e03942f763e819$export$25bec8c6f54ee79a(callback) { - const callbackRef = $92muK$react.useRef(callback); - $92muK$react.useEffect(() => { - callbackRef.current = callback; - }); // https://github.com/facebook/react/issues/19240 - return $92muK$react.useMemo(() => (...args) => { - var _callbackRef$current; - return (_callbackRef$current = callbackRef.current) === null || _callbackRef$current === void 0 ? void 0 : _callbackRef$current.call(callbackRef, ...args); - }, []); -} - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js": -/*!**********************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js ***! - \**********************************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var $ijazI$react = __webpack_require__(/*! react */ "react"); -var $ijazI$radixuireactusecallbackref = __webpack_require__(/*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -$parcel$export(module.exports, "useControllableState", () => $b84d42d44371bff7$export$6f32135080cb4c3); -function $b84d42d44371bff7$export$6f32135080cb4c3({ - prop: prop, - defaultProp: defaultProp, - onChange = () => {} -}) { - const [uncontrolledProp, setUncontrolledProp] = $b84d42d44371bff7$var$useUncontrolledState({ - defaultProp: defaultProp, - onChange: onChange - }); - const isControlled = prop !== undefined; - const value1 = isControlled ? prop : uncontrolledProp; - const handleChange = $ijazI$radixuireactusecallbackref.useCallbackRef(onChange); - const setValue = $ijazI$react.useCallback(nextValue => { - if (isControlled) { - const setter = nextValue; - const value = typeof nextValue === 'function' ? setter(prop) : nextValue; - if (value !== prop) handleChange(value); - } else setUncontrolledProp(nextValue); - }, [isControlled, prop, setUncontrolledProp, handleChange]); - return [value1, setValue]; -} -function $b84d42d44371bff7$var$useUncontrolledState({ - defaultProp: defaultProp, - onChange: onChange -}) { - const uncontrolledState = $ijazI$react.useState(defaultProp); - const [value] = uncontrolledState; - const prevValueRef = $ijazI$react.useRef(value); - const handleChange = $ijazI$radixuireactusecallbackref.useCallbackRef(onChange); - $ijazI$react.useEffect(() => { - if (prevValueRef.current !== value) { - handleChange(value); - prevValueRef.current = value; - } - }, [value, prevValueRef, handleChange]); - return uncontrolledState; -} - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-use-escape-keydown/dist/index.js": -/*!******************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-use-escape-keydown/dist/index.js ***! - \******************************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var $b0gz3$react = __webpack_require__(/*! react */ "react"); -var $b0gz3$radixuireactusecallbackref = __webpack_require__(/*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -$parcel$export(module.exports, "useEscapeKeydown", () => $24c84e9f83c4454f$export$3a72a57244d6e765); - -/** - * Listens for when the escape key is down - */ -function $24c84e9f83c4454f$export$3a72a57244d6e765(onEscapeKeyDownProp, ownerDocument = globalThis === null || globalThis === void 0 ? void 0 : globalThis.document) { - const onEscapeKeyDown = $b0gz3$radixuireactusecallbackref.useCallbackRef(onEscapeKeyDownProp); - $b0gz3$react.useEffect(() => { - const handleKeyDown = event => { - if (event.key === 'Escape') onEscapeKeyDown(event); - }; - ownerDocument.addEventListener('keydown', handleKeyDown); - return () => ownerDocument.removeEventListener('keydown', handleKeyDown); - }, [onEscapeKeyDown, ownerDocument]); -} - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js": -/*!*****************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js ***! - \*****************************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var $caHyQ$react = __webpack_require__(/*! react */ "react"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -$parcel$export(module.exports, "useLayoutEffect", () => $ca21affb0542a8a4$export$e5c5a5f917a5871c); - -/** - * On the server, React emits a warning when calling `useLayoutEffect`. - * This is because neither `useLayoutEffect` nor `useEffect` run on the server. - * We use this safe version which suppresses the warning by replacing it with a noop on the server. - * - * See: https://reactjs.org/docs/hooks-reference.html#uselayouteffect - */ -const $ca21affb0542a8a4$export$e5c5a5f917a5871c = Boolean(globalThis === null || globalThis === void 0 ? void 0 : globalThis.document) ? $caHyQ$react.useLayoutEffect : () => {}; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-use-size/dist/index.js": -/*!********************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-use-size/dist/index.js ***! - \********************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var $ksDzM$react = __webpack_require__(/*! react */ "react"); -var $ksDzM$radixuireactuselayouteffect = __webpack_require__(/*! @radix-ui/react-use-layout-effect */ "../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -$parcel$export(module.exports, "useSize", () => $d2c1d285af17635b$export$1ab7ae714698c4b8); -function $d2c1d285af17635b$export$1ab7ae714698c4b8(element) { - const [size, setSize] = $ksDzM$react.useState(undefined); - $ksDzM$radixuireactuselayouteffect.useLayoutEffect(() => { - if (element) { - // provide size as early as possible - setSize({ - width: element.offsetWidth, - height: element.offsetHeight - }); - const resizeObserver = new ResizeObserver(entries => { - if (!Array.isArray(entries)) return; - // Since we only observe the one element, we don't need to loop over the - // array - if (!entries.length) return; - const entry = entries[0]; - let width; - let height; - if ('borderBoxSize' in entry) { - const borderSizeEntry = entry['borderBoxSize']; // iron out differences between browsers - const borderSize = Array.isArray(borderSizeEntry) ? borderSizeEntry[0] : borderSizeEntry; - width = borderSize['inlineSize']; - height = borderSize['blockSize']; - } else { - // for browsers that don't support `borderBoxSize` - // we calculate it ourselves to get the correct border box. - width = element.offsetWidth; - height = element.offsetHeight; - } - setSize({ - width: width, - height: height - }); - }); - resizeObserver.observe(element, { - box: 'border-box' - }); - return () => resizeObserver.unobserve(element); - } else - // We only want to reset to `undefined` when the element becomes `null`, - // not if it changes to another element. - setSize(undefined); - }, [element]); - return size; -} - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-visually-hidden/dist/index.js": -/*!***************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-visually-hidden/dist/index.js ***! - \***************************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var $awrN2$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); -var $awrN2$react = __webpack_require__(/*! react */ "react"); -var $awrN2$radixuireactprimitive = __webpack_require__(/*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "VisuallyHidden", () => $685371e9c20848e2$export$439d29a4e110a164); -$parcel$export(module.exports, "Root", () => $685371e9c20848e2$export$be92b6f5f03c0fe9); - -/* ------------------------------------------------------------------------------------------------- - * VisuallyHidden - * -----------------------------------------------------------------------------------------------*/ -const $685371e9c20848e2$var$NAME = 'VisuallyHidden'; -const $685371e9c20848e2$export$439d29a4e110a164 = /*#__PURE__*/$awrN2$react.forwardRef((props, forwardedRef) => { - return /*#__PURE__*/$awrN2$react.createElement($awrN2$radixuireactprimitive.Primitive.span, $parcel$interopDefault($awrN2$babelruntimehelpersextends)({}, props, { - ref: forwardedRef, - style: { - // See: https://github.com/twbs/bootstrap/blob/master/scss/mixins/_screen-reader.scss - position: 'absolute', - border: 0, - width: 1, - height: 1, - padding: 0, - margin: -1, - overflow: 'hidden', - clip: 'rect(0, 0, 0, 0)', - whiteSpace: 'nowrap', - wordWrap: 'normal', - ...props.style - } - })); -}); -/*#__PURE__*/ -Object.assign($685371e9c20848e2$export$439d29a4e110a164, { - displayName: $685371e9c20848e2$var$NAME -}); -/* -----------------------------------------------------------------------------------------------*/ -const $685371e9c20848e2$export$be92b6f5f03c0fe9 = $685371e9c20848e2$export$439d29a4e110a164; - -/***/ }), - -/***/ "../../../node_modules/aria-hidden/dist/es2015/index.js": -/*!**************************************************************!*\ - !*** ../../../node_modules/aria-hidden/dist/es2015/index.js ***! - \**************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.suppressOthers = exports.supportsInert = exports.inertOthers = exports.hideOthers = void 0; -var getDefaultParent = function (originalTarget) { - if (typeof document === 'undefined') { - return null; - } - var sampleTarget = Array.isArray(originalTarget) ? originalTarget[0] : originalTarget; - return sampleTarget.ownerDocument.body; -}; -var counterMap = new WeakMap(); -var uncontrolledNodes = new WeakMap(); -var markerMap = {}; -var lockCount = 0; -var unwrapHost = function (node) { - return node && (node.host || unwrapHost(node.parentNode)); -}; -var correctTargets = function (parent, targets) { - return targets.map(function (target) { - if (parent.contains(target)) { - return target; - } - var correctedTarget = unwrapHost(target); - if (correctedTarget && parent.contains(correctedTarget)) { - return correctedTarget; - } - console.error('aria-hidden', target, 'in not contained inside', parent, '. Doing nothing'); - return null; - }).filter(function (x) { - return Boolean(x); - }); -}; -/** - * Marks everything except given node(or nodes) as aria-hidden - * @param {Element | Element[]} originalTarget - elements to keep on the page - * @param [parentNode] - top element, defaults to document.body - * @param {String} [markerName] - a special attribute to mark every node - * @param {String} [controlAttribute] - html Attribute to control - * @return {Undo} undo command - */ -var applyAttributeToOthers = function (originalTarget, parentNode, markerName, controlAttribute) { - var targets = correctTargets(parentNode, Array.isArray(originalTarget) ? originalTarget : [originalTarget]); - if (!markerMap[markerName]) { - markerMap[markerName] = new WeakMap(); - } - var markerCounter = markerMap[markerName]; - var hiddenNodes = []; - var elementsToKeep = new Set(); - var elementsToStop = new Set(targets); - var keep = function (el) { - if (!el || elementsToKeep.has(el)) { - return; - } - elementsToKeep.add(el); - keep(el.parentNode); - }; - targets.forEach(keep); - var deep = function (parent) { - if (!parent || elementsToStop.has(parent)) { - return; - } - Array.prototype.forEach.call(parent.children, function (node) { - if (elementsToKeep.has(node)) { - deep(node); - } else { - var attr = node.getAttribute(controlAttribute); - var alreadyHidden = attr !== null && attr !== 'false'; - var counterValue = (counterMap.get(node) || 0) + 1; - var markerValue = (markerCounter.get(node) || 0) + 1; - counterMap.set(node, counterValue); - markerCounter.set(node, markerValue); - hiddenNodes.push(node); - if (counterValue === 1 && alreadyHidden) { - uncontrolledNodes.set(node, true); - } - if (markerValue === 1) { - node.setAttribute(markerName, 'true'); - } - if (!alreadyHidden) { - node.setAttribute(controlAttribute, 'true'); - } - } - }); - }; - deep(parentNode); - elementsToKeep.clear(); - lockCount++; - return function () { - hiddenNodes.forEach(function (node) { - var counterValue = counterMap.get(node) - 1; - var markerValue = markerCounter.get(node) - 1; - counterMap.set(node, counterValue); - markerCounter.set(node, markerValue); - if (!counterValue) { - if (!uncontrolledNodes.has(node)) { - node.removeAttribute(controlAttribute); - } - uncontrolledNodes.delete(node); - } - if (!markerValue) { - node.removeAttribute(markerName); - } - }); - lockCount--; - if (!lockCount) { - // clear - counterMap = new WeakMap(); - counterMap = new WeakMap(); - uncontrolledNodes = new WeakMap(); - markerMap = {}; - } - }; -}; -/** - * Marks everything except given node(or nodes) as aria-hidden - * @param {Element | Element[]} originalTarget - elements to keep on the page - * @param [parentNode] - top element, defaults to document.body - * @param {String} [markerName] - a special attribute to mark every node - * @return {Undo} undo command - */ -var hideOthers = function (originalTarget, parentNode, markerName) { - if (markerName === void 0) { - markerName = 'data-aria-hidden'; - } - var targets = Array.from(Array.isArray(originalTarget) ? originalTarget : [originalTarget]); - var activeParentNode = parentNode || getDefaultParent(originalTarget); - if (!activeParentNode) { - return function () { - return null; - }; - } - // we should not hide ariaLive elements - https://github.com/theKashey/aria-hidden/issues/10 - targets.push.apply(targets, Array.from(activeParentNode.querySelectorAll('[aria-live]'))); - return applyAttributeToOthers(targets, activeParentNode, markerName, 'aria-hidden'); -}; -/** - * Marks everything except given node(or nodes) as inert - * @param {Element | Element[]} originalTarget - elements to keep on the page - * @param [parentNode] - top element, defaults to document.body - * @param {String} [markerName] - a special attribute to mark every node - * @return {Undo} undo command - */ -exports.hideOthers = hideOthers; -var inertOthers = function (originalTarget, parentNode, markerName) { - if (markerName === void 0) { - markerName = 'data-inert-ed'; - } - var activeParentNode = parentNode || getDefaultParent(originalTarget); - if (!activeParentNode) { - return function () { - return null; - }; - } - return applyAttributeToOthers(originalTarget, activeParentNode, markerName, 'inert'); -}; -/** - * @returns if current browser supports inert - */ -exports.inertOthers = inertOthers; -var supportsInert = function () { - return typeof HTMLElement !== 'undefined' && HTMLElement.prototype.hasOwnProperty('inert'); -}; -/** - * Automatic function to "suppress" DOM elements - _hide_ or _inert_ in the best possible way - * @param {Element | Element[]} originalTarget - elements to keep on the page - * @param [parentNode] - top element, defaults to document.body - * @param {String} [markerName] - a special attribute to mark every node - * @return {Undo} undo command - */ -exports.supportsInert = supportsInert; -var suppressOthers = function (originalTarget, parentNode, markerName) { - if (markerName === void 0) { - markerName = 'data-suppressed'; - } - return (supportsInert() ? inertOthers : hideOthers)(originalTarget, parentNode, markerName); -}; -exports.suppressOthers = suppressOthers; - -/***/ }), - -/***/ "../../../node_modules/clsx/dist/clsx.m.js": -/*!*************************************************!*\ - !*** ../../../node_modules/clsx/dist/clsx.m.js ***! - \*************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.clsx = clsx; -exports["default"] = void 0; -function r(e) { - var t, - f, - n = ""; - if ("string" == typeof e || "number" == typeof e) n += e;else if ("object" == typeof e) if (Array.isArray(e)) for (t = 0; t < e.length; t++) e[t] && (f = r(e[t])) && (n && (n += " "), n += f);else for (t in e) e[t] && (n && (n += " "), n += t); - return n; -} -function clsx() { - for (var e, t, f = 0, n = ""; f < arguments.length;) (e = arguments[f++]) && (t = r(e)) && (n && (n += " "), n += t); - return n; -} -var _default = exports["default"] = clsx; - -/***/ }), - -/***/ "../../../node_modules/codemirror/addon/comment/comment.js": -/*!*****************************************************************!*\ - !*** ../../../node_modules/codemirror/addon/comment/comment.js ***! - \*****************************************************************/ -/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function (mod) { - if (true) - // CommonJS - mod(__webpack_require__(/*! ../../lib/codemirror */ "../../../node_modules/codemirror/lib/codemirror.js"));else {} -})(function (CodeMirror) { - "use strict"; - - var noOptions = {}; - var nonWS = /[^\s\u00a0]/; - var Pos = CodeMirror.Pos, - cmp = CodeMirror.cmpPos; - function firstNonWS(str) { - var found = str.search(nonWS); - return found == -1 ? 0 : found; - } - CodeMirror.commands.toggleComment = function (cm) { - cm.toggleComment(); - }; - CodeMirror.defineExtension("toggleComment", function (options) { - if (!options) options = noOptions; - var cm = this; - var minLine = Infinity, - ranges = this.listSelections(), - mode = null; - for (var i = ranges.length - 1; i >= 0; i--) { - var from = ranges[i].from(), - to = ranges[i].to(); - if (from.line >= minLine) continue; - if (to.line >= minLine) to = Pos(minLine, 0); - minLine = from.line; - if (mode == null) { - if (cm.uncomment(from, to, options)) mode = "un";else { - cm.lineComment(from, to, options); - mode = "line"; - } - } else if (mode == "un") { - cm.uncomment(from, to, options); - } else { - cm.lineComment(from, to, options); - } - } - }); - - // Rough heuristic to try and detect lines that are part of multi-line string - function probablyInsideString(cm, pos, line) { - return /\bstring\b/.test(cm.getTokenTypeAt(Pos(pos.line, 0))) && !/^[\'\"\`]/.test(line); - } - function getMode(cm, pos) { - var mode = cm.getMode(); - return mode.useInnerComments === false || !mode.innerMode ? mode : cm.getModeAt(pos); - } - CodeMirror.defineExtension("lineComment", function (from, to, options) { - if (!options) options = noOptions; - var self = this, - mode = getMode(self, from); - var firstLine = self.getLine(from.line); - if (firstLine == null || probablyInsideString(self, from, firstLine)) return; - var commentString = options.lineComment || mode.lineComment; - if (!commentString) { - if (options.blockCommentStart || mode.blockCommentStart) { - options.fullLines = true; - self.blockComment(from, to, options); - } - return; - } - var end = Math.min(to.ch != 0 || to.line == from.line ? to.line + 1 : to.line, self.lastLine() + 1); - var pad = options.padding == null ? " " : options.padding; - var blankLines = options.commentBlankLines || from.line == to.line; - self.operation(function () { - if (options.indent) { - var baseString = null; - for (var i = from.line; i < end; ++i) { - var line = self.getLine(i); - var whitespace = line.slice(0, firstNonWS(line)); - if (baseString == null || baseString.length > whitespace.length) { - baseString = whitespace; - } - } - for (var i = from.line; i < end; ++i) { - var line = self.getLine(i), - cut = baseString.length; - if (!blankLines && !nonWS.test(line)) continue; - if (line.slice(0, cut) != baseString) cut = firstNonWS(line); - self.replaceRange(baseString + commentString + pad, Pos(i, 0), Pos(i, cut)); - } - } else { - for (var i = from.line; i < end; ++i) { - if (blankLines || nonWS.test(self.getLine(i))) self.replaceRange(commentString + pad, Pos(i, 0)); - } - } - }); - }); - CodeMirror.defineExtension("blockComment", function (from, to, options) { - if (!options) options = noOptions; - var self = this, - mode = getMode(self, from); - var startString = options.blockCommentStart || mode.blockCommentStart; - var endString = options.blockCommentEnd || mode.blockCommentEnd; - if (!startString || !endString) { - if ((options.lineComment || mode.lineComment) && options.fullLines != false) self.lineComment(from, to, options); - return; - } - if (/\bcomment\b/.test(self.getTokenTypeAt(Pos(from.line, 0)))) return; - var end = Math.min(to.line, self.lastLine()); - if (end != from.line && to.ch == 0 && nonWS.test(self.getLine(end))) --end; - var pad = options.padding == null ? " " : options.padding; - if (from.line > end) return; - self.operation(function () { - if (options.fullLines != false) { - var lastLineHasText = nonWS.test(self.getLine(end)); - self.replaceRange(pad + endString, Pos(end)); - self.replaceRange(startString + pad, Pos(from.line, 0)); - var lead = options.blockCommentLead || mode.blockCommentLead; - if (lead != null) for (var i = from.line + 1; i <= end; ++i) if (i != end || lastLineHasText) self.replaceRange(lead + pad, Pos(i, 0)); - } else { - var atCursor = cmp(self.getCursor("to"), to) == 0, - empty = !self.somethingSelected(); - self.replaceRange(endString, to); - if (atCursor) self.setSelection(empty ? to : self.getCursor("from"), to); - self.replaceRange(startString, from); - } - }); - }); - CodeMirror.defineExtension("uncomment", function (from, to, options) { - if (!options) options = noOptions; - var self = this, - mode = getMode(self, from); - var end = Math.min(to.ch != 0 || to.line == from.line ? to.line : to.line - 1, self.lastLine()), - start = Math.min(from.line, end); - - // Try finding line comments - var lineString = options.lineComment || mode.lineComment, - lines = []; - var pad = options.padding == null ? " " : options.padding, - didSomething; - lineComment: { - if (!lineString) break lineComment; - for (var i = start; i <= end; ++i) { - var line = self.getLine(i); - var found = line.indexOf(lineString); - if (found > -1 && !/comment/.test(self.getTokenTypeAt(Pos(i, found + 1)))) found = -1; - if (found == -1 && nonWS.test(line)) break lineComment; - if (found > -1 && nonWS.test(line.slice(0, found))) break lineComment; - lines.push(line); - } - self.operation(function () { - for (var i = start; i <= end; ++i) { - var line = lines[i - start]; - var pos = line.indexOf(lineString), - endPos = pos + lineString.length; - if (pos < 0) continue; - if (line.slice(endPos, endPos + pad.length) == pad) endPos += pad.length; - didSomething = true; - self.replaceRange("", Pos(i, pos), Pos(i, endPos)); - } - }); - if (didSomething) return true; - } - - // Try block comments - var startString = options.blockCommentStart || mode.blockCommentStart; - var endString = options.blockCommentEnd || mode.blockCommentEnd; - if (!startString || !endString) return false; - var lead = options.blockCommentLead || mode.blockCommentLead; - var startLine = self.getLine(start), - open = startLine.indexOf(startString); - if (open == -1) return false; - var endLine = end == start ? startLine : self.getLine(end); - var close = endLine.indexOf(endString, end == start ? open + startString.length : 0); - var insideStart = Pos(start, open + 1), - insideEnd = Pos(end, close + 1); - if (close == -1 || !/comment/.test(self.getTokenTypeAt(insideStart)) || !/comment/.test(self.getTokenTypeAt(insideEnd)) || self.getRange(insideStart, insideEnd, "\n").indexOf(endString) > -1) return false; - - // Avoid killing block comments completely outside the selection. - // Positions of the last startString before the start of the selection, and the first endString after it. - var lastStart = startLine.lastIndexOf(startString, from.ch); - var firstEnd = lastStart == -1 ? -1 : startLine.slice(0, from.ch).indexOf(endString, lastStart + startString.length); - if (lastStart != -1 && firstEnd != -1 && firstEnd + endString.length != from.ch) return false; - // Positions of the first endString after the end of the selection, and the last startString before it. - firstEnd = endLine.indexOf(endString, to.ch); - var almostLastStart = endLine.slice(to.ch).lastIndexOf(startString, firstEnd - to.ch); - lastStart = firstEnd == -1 || almostLastStart == -1 ? -1 : to.ch + almostLastStart; - if (firstEnd != -1 && lastStart != -1 && lastStart != to.ch) return false; - self.operation(function () { - self.replaceRange("", Pos(end, close - (pad && endLine.slice(close - pad.length, close) == pad ? pad.length : 0)), Pos(end, close + endString.length)); - var openEnd = open + startString.length; - if (pad && startLine.slice(openEnd, openEnd + pad.length) == pad) openEnd += pad.length; - self.replaceRange("", Pos(start, open), Pos(start, openEnd)); - if (lead) for (var i = start + 1; i <= end; ++i) { - var line = self.getLine(i), - found = line.indexOf(lead); - if (found == -1 || nonWS.test(line.slice(0, found))) continue; - var foundEnd = found + lead.length; - if (pad && line.slice(foundEnd, foundEnd + pad.length) == pad) foundEnd += pad.length; - self.replaceRange("", Pos(i, found), Pos(i, foundEnd)); - } - }); - return true; - }); -}); - -/***/ }), - -/***/ "../../../node_modules/codemirror/addon/dialog/dialog.js": -/*!***************************************************************!*\ - !*** ../../../node_modules/codemirror/addon/dialog/dialog.js ***! - \***************************************************************/ -/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -// Open simple dialogs on top of an editor. Relies on dialog.css. - -(function (mod) { - if (true) - // CommonJS - mod(__webpack_require__(/*! ../../lib/codemirror */ "../../../node_modules/codemirror/lib/codemirror.js"));else {} -})(function (CodeMirror) { - function dialogDiv(cm, template, bottom) { - var wrap = cm.getWrapperElement(); - var dialog; - dialog = wrap.appendChild(document.createElement("div")); - if (bottom) dialog.className = "CodeMirror-dialog CodeMirror-dialog-bottom";else dialog.className = "CodeMirror-dialog CodeMirror-dialog-top"; - if (typeof template == "string") { - dialog.innerHTML = template; - } else { - // Assuming it's a detached DOM element. - dialog.appendChild(template); - } - CodeMirror.addClass(wrap, 'dialog-opened'); - return dialog; - } - function closeNotification(cm, newVal) { - if (cm.state.currentNotificationClose) cm.state.currentNotificationClose(); - cm.state.currentNotificationClose = newVal; - } - CodeMirror.defineExtension("openDialog", function (template, callback, options) { - if (!options) options = {}; - closeNotification(this, null); - var dialog = dialogDiv(this, template, options.bottom); - var closed = false, - me = this; - function close(newVal) { - if (typeof newVal == 'string') { - inp.value = newVal; - } else { - if (closed) return; - closed = true; - CodeMirror.rmClass(dialog.parentNode, 'dialog-opened'); - dialog.parentNode.removeChild(dialog); - me.focus(); - if (options.onClose) options.onClose(dialog); - } - } - var inp = dialog.getElementsByTagName("input")[0], - button; - if (inp) { - inp.focus(); - if (options.value) { - inp.value = options.value; - if (options.selectValueOnOpen !== false) { - inp.select(); - } - } - if (options.onInput) CodeMirror.on(inp, "input", function (e) { - options.onInput(e, inp.value, close); - }); - if (options.onKeyUp) CodeMirror.on(inp, "keyup", function (e) { - options.onKeyUp(e, inp.value, close); - }); - CodeMirror.on(inp, "keydown", function (e) { - if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { - return; - } - if (e.keyCode == 27 || options.closeOnEnter !== false && e.keyCode == 13) { - inp.blur(); - CodeMirror.e_stop(e); - close(); - } - if (e.keyCode == 13) callback(inp.value, e); - }); - if (options.closeOnBlur !== false) CodeMirror.on(dialog, "focusout", function (evt) { - if (evt.relatedTarget !== null) close(); - }); - } else if (button = dialog.getElementsByTagName("button")[0]) { - CodeMirror.on(button, "click", function () { - close(); - me.focus(); - }); - if (options.closeOnBlur !== false) CodeMirror.on(button, "blur", close); - button.focus(); - } - return close; - }); - CodeMirror.defineExtension("openConfirm", function (template, callbacks, options) { - closeNotification(this, null); - var dialog = dialogDiv(this, template, options && options.bottom); - var buttons = dialog.getElementsByTagName("button"); - var closed = false, - me = this, - blurring = 1; - function close() { - if (closed) return; - closed = true; - CodeMirror.rmClass(dialog.parentNode, 'dialog-opened'); - dialog.parentNode.removeChild(dialog); - me.focus(); - } - buttons[0].focus(); - for (var i = 0; i < buttons.length; ++i) { - var b = buttons[i]; - (function (callback) { - CodeMirror.on(b, "click", function (e) { - CodeMirror.e_preventDefault(e); - close(); - if (callback) callback(me); - }); - })(callbacks[i]); - CodeMirror.on(b, "blur", function () { - --blurring; - setTimeout(function () { - if (blurring <= 0) close(); - }, 200); - }); - CodeMirror.on(b, "focus", function () { - ++blurring; - }); - } - }); - - /* - * openNotification - * Opens a notification, that can be closed with an optional timer - * (default 5000ms timer) and always closes on click. + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. * - * If a notification is opened while another is opened, it will close the - * currently opened one and open the new one immediately. - */ - CodeMirror.defineExtension("openNotification", function (template, options) { - closeNotification(this, close); - var dialog = dialogDiv(this, template, options && options.bottom); - var closed = false, - doneTimer; - var duration = options && typeof options.duration !== "undefined" ? options.duration : 5000; - function close() { - if (closed) return; - closed = true; - clearTimeout(doneTimer); - CodeMirror.rmClass(dialog.parentNode, 'dialog-opened'); - dialog.parentNode.removeChild(dialog); - } - CodeMirror.on(dialog, 'click', function (e) { - CodeMirror.e_preventDefault(e); - close(); - }); - if (duration) doneTimer = setTimeout(close, duration); - return close; - }); -}); - -/***/ }), - -/***/ "../../../node_modules/codemirror/addon/edit/closebrackets.js": -/*!********************************************************************!*\ - !*** ../../../node_modules/codemirror/addon/edit/closebrackets.js ***! - \********************************************************************/ -/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function (mod) { - if (true) - // CommonJS - mod(__webpack_require__(/*! ../../lib/codemirror */ "../../../node_modules/codemirror/lib/codemirror.js"));else {} -})(function (CodeMirror) { - var defaults = { - pairs: "()[]{}''\"\"", - closeBefore: ")]}'\":;>", - triples: "", - explode: "[]{}" - }; - var Pos = CodeMirror.Pos; - CodeMirror.defineOption("autoCloseBrackets", false, function (cm, val, old) { - if (old && old != CodeMirror.Init) { - cm.removeKeyMap(keyMap); - cm.state.closeBrackets = null; - } - if (val) { - ensureBound(getOption(val, "pairs")); - cm.state.closeBrackets = val; - cm.addKeyMap(keyMap); - } - }); - function getOption(conf, name) { - if (name == "pairs" && typeof conf == "string") return conf; - if (typeof conf == "object" && conf[name] != null) return conf[name]; - return defaults[name]; - } - var keyMap = { - Backspace: handleBackspace, - Enter: handleEnter - }; - function ensureBound(chars) { - for (var i = 0; i < chars.length; i++) { - var ch = chars.charAt(i), - key = "'" + ch + "'"; - if (!keyMap[key]) keyMap[key] = handler(ch); - } - } - ensureBound(defaults.pairs + "`"); - function handler(ch) { - return function (cm) { - return handleChar(cm, ch); - }; - } - function getConfig(cm) { - var deflt = cm.state.closeBrackets; - if (!deflt || deflt.override) return deflt; - var mode = cm.getModeAt(cm.getCursor()); - return mode.closeBrackets || deflt; - } - function handleBackspace(cm) { - var conf = getConfig(cm); - if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass; - var pairs = getOption(conf, "pairs"); - var ranges = cm.listSelections(); - for (var i = 0; i < ranges.length; i++) { - if (!ranges[i].empty()) return CodeMirror.Pass; - var around = charsAround(cm, ranges[i].head); - if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass; - } - for (var i = ranges.length - 1; i >= 0; i--) { - var cur = ranges[i].head; - cm.replaceRange("", Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1), "+delete"); - } - } - function handleEnter(cm) { - var conf = getConfig(cm); - var explode = conf && getOption(conf, "explode"); - if (!explode || cm.getOption("disableInput")) return CodeMirror.Pass; - var ranges = cm.listSelections(); - for (var i = 0; i < ranges.length; i++) { - if (!ranges[i].empty()) return CodeMirror.Pass; - var around = charsAround(cm, ranges[i].head); - if (!around || explode.indexOf(around) % 2 != 0) return CodeMirror.Pass; - } - cm.operation(function () { - var linesep = cm.lineSeparator() || "\n"; - cm.replaceSelection(linesep + linesep, null); - moveSel(cm, -1); - ranges = cm.listSelections(); - for (var i = 0; i < ranges.length; i++) { - var line = ranges[i].head.line; - cm.indentLine(line, null, true); - cm.indentLine(line + 1, null, true); - } - }); - } - function moveSel(cm, dir) { - var newRanges = [], - ranges = cm.listSelections(), - primary = 0; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - if (range.head == cm.getCursor()) primary = i; - var pos = range.head.ch || dir > 0 ? { - line: range.head.line, - ch: range.head.ch + dir - } : { - line: range.head.line - 1 - }; - newRanges.push({ - anchor: pos, - head: pos - }); - } - cm.setSelections(newRanges, primary); - } - function contractSelection(sel) { - var inverted = CodeMirror.cmpPos(sel.anchor, sel.head) > 0; - return { - anchor: new Pos(sel.anchor.line, sel.anchor.ch + (inverted ? -1 : 1)), - head: new Pos(sel.head.line, sel.head.ch + (inverted ? 1 : -1)) - }; - } - function handleChar(cm, ch) { - var conf = getConfig(cm); - if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass; - var pairs = getOption(conf, "pairs"); - var pos = pairs.indexOf(ch); - if (pos == -1) return CodeMirror.Pass; - var closeBefore = getOption(conf, "closeBefore"); - var triples = getOption(conf, "triples"); - var identical = pairs.charAt(pos + 1) == ch; - var ranges = cm.listSelections(); - var opening = pos % 2 == 0; - var type; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i], - cur = range.head, - curType; - var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1)); - if (opening && !range.empty()) { - curType = "surround"; - } else if ((identical || !opening) && next == ch) { - if (identical && stringStartsAfter(cm, cur)) curType = "both";else if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch) curType = "skipThree";else curType = "skip"; - } else if (identical && cur.ch > 1 && triples.indexOf(ch) >= 0 && cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch) { - if (cur.ch > 2 && /\bstring/.test(cm.getTokenTypeAt(Pos(cur.line, cur.ch - 2)))) return CodeMirror.Pass; - curType = "addFour"; - } else if (identical) { - var prev = cur.ch == 0 ? " " : cm.getRange(Pos(cur.line, cur.ch - 1), cur); - if (!CodeMirror.isWordChar(next) && prev != ch && !CodeMirror.isWordChar(prev)) curType = "both";else return CodeMirror.Pass; - } else if (opening && (next.length === 0 || /\s/.test(next) || closeBefore.indexOf(next) > -1)) { - curType = "both"; - } else { - return CodeMirror.Pass; - } - if (!type) type = curType;else if (type != curType) return CodeMirror.Pass; - } - var left = pos % 2 ? pairs.charAt(pos - 1) : ch; - var right = pos % 2 ? ch : pairs.charAt(pos + 1); - cm.operation(function () { - if (type == "skip") { - moveSel(cm, 1); - } else if (type == "skipThree") { - moveSel(cm, 3); - } else if (type == "surround") { - var sels = cm.getSelections(); - for (var i = 0; i < sels.length; i++) sels[i] = left + sels[i] + right; - cm.replaceSelections(sels, "around"); - sels = cm.listSelections().slice(); - for (var i = 0; i < sels.length; i++) sels[i] = contractSelection(sels[i]); - cm.setSelections(sels); - } else if (type == "both") { - cm.replaceSelection(left + right, null); - cm.triggerElectric(left + right); - moveSel(cm, -1); - } else if (type == "addFour") { - cm.replaceSelection(left + left + left + left, "before"); - moveSel(cm, 1); - } - }); - } - function charsAround(cm, pos) { - var str = cm.getRange(Pos(pos.line, pos.ch - 1), Pos(pos.line, pos.ch + 1)); - return str.length == 2 ? str : null; - } - function stringStartsAfter(cm, pos) { - var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1)); - return /\bstring/.test(token.type) && token.start == pos.ch && (pos.ch == 0 || !/\bstring/.test(cm.getTokenTypeAt(pos))); - } -}); - -/***/ }), - -/***/ "../../../node_modules/codemirror/addon/edit/matchbrackets.js": -/*!********************************************************************!*\ - !*** ../../../node_modules/codemirror/addon/edit/matchbrackets.js ***! - \********************************************************************/ -/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function (mod) { - if (true) - // CommonJS - mod(__webpack_require__(/*! ../../lib/codemirror */ "../../../node_modules/codemirror/lib/codemirror.js"));else {} -})(function (CodeMirror) { - var ie_lt8 = /MSIE \d/.test(navigator.userAgent) && (document.documentMode == null || document.documentMode < 8); - var Pos = CodeMirror.Pos; - var matching = { - "(": ")>", - ")": "(<", - "[": "]>", - "]": "[<", - "{": "}>", - "}": "{<", - "<": ">>", - ">": "<<" - }; - function bracketRegex(config) { - return config && config.bracketRegex || /[(){}[\]]/; - } - function findMatchingBracket(cm, where, config) { - var line = cm.getLineHandle(where.line), - pos = where.ch - 1; - var afterCursor = config && config.afterCursor; - if (afterCursor == null) afterCursor = /(^| )cm-fat-cursor($| )/.test(cm.getWrapperElement().className); - var re = bracketRegex(config); - - // A cursor is defined as between two characters, but in in vim command mode - // (i.e. not insert mode), the cursor is visually represented as a - // highlighted box on top of the 2nd character. Otherwise, we allow matches - // from before or after the cursor. - var match = !afterCursor && pos >= 0 && re.test(line.text.charAt(pos)) && matching[line.text.charAt(pos)] || re.test(line.text.charAt(pos + 1)) && matching[line.text.charAt(++pos)]; - if (!match) return null; - var dir = match.charAt(1) == ">" ? 1 : -1; - if (config && config.strict && dir > 0 != (pos == where.ch)) return null; - var style = cm.getTokenTypeAt(Pos(where.line, pos + 1)); - var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style, config); - if (found == null) return null; - return { - from: Pos(where.line, pos), - to: found && found.pos, - match: found && found.ch == match.charAt(0), - forward: dir > 0 - }; - } - - // bracketRegex is used to specify which type of bracket to scan - // should be a regexp, e.g. /[[\]]/ - // - // Note: If "where" is on an open bracket, then this bracket is ignored. - // - // Returns false when no bracket was found, null when it reached - // maxScanLines and gave up - function scanForBracket(cm, where, dir, style, config) { - var maxScanLen = config && config.maxScanLineLength || 10000; - var maxScanLines = config && config.maxScanLines || 1000; - var stack = []; - var re = bracketRegex(config); - var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1) : Math.max(cm.firstLine() - 1, where.line - maxScanLines); - for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) { - var line = cm.getLine(lineNo); - if (!line) continue; - var pos = dir > 0 ? 0 : line.length - 1, - end = dir > 0 ? line.length : -1; - if (line.length > maxScanLen) continue; - if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0); - for (; pos != end; pos += dir) { - var ch = line.charAt(pos); - if (re.test(ch) && (style === undefined || (cm.getTokenTypeAt(Pos(lineNo, pos + 1)) || "") == (style || ""))) { - var match = matching[ch]; - if (match && match.charAt(1) == ">" == dir > 0) stack.push(ch);else if (!stack.length) return { - pos: Pos(lineNo, pos), - ch: ch - };else stack.pop(); - } - } - } - return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null; - } - function matchBrackets(cm, autoclear, config) { - // Disable brace matching in long lines, since it'll cause hugely slow updates - var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000, - highlightNonMatching = config && config.highlightNonMatching; - var marks = [], - ranges = cm.listSelections(); - for (var i = 0; i < ranges.length; i++) { - var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, config); - if (match && (match.match || highlightNonMatching !== false) && cm.getLine(match.from.line).length <= maxHighlightLen) { - var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket"; - marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), { - className: style - })); - if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen) marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), { - className: style - })); - } - } - if (marks.length) { - // Kludge to work around the IE bug from issue #1193, where text - // input stops going to the textarea whenever this fires. - if (ie_lt8 && cm.state.focused) cm.focus(); - var clear = function () { - cm.operation(function () { - for (var i = 0; i < marks.length; i++) marks[i].clear(); - }); - }; - if (autoclear) setTimeout(clear, 800);else return clear; - } - } - function doMatchBrackets(cm) { - cm.operation(function () { - if (cm.state.matchBrackets.currentlyHighlighted) { - cm.state.matchBrackets.currentlyHighlighted(); - cm.state.matchBrackets.currentlyHighlighted = null; - } - cm.state.matchBrackets.currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets); - }); - } - function clearHighlighted(cm) { - if (cm.state.matchBrackets && cm.state.matchBrackets.currentlyHighlighted) { - cm.state.matchBrackets.currentlyHighlighted(); - cm.state.matchBrackets.currentlyHighlighted = null; - } - } - CodeMirror.defineOption("matchBrackets", false, function (cm, val, old) { - if (old && old != CodeMirror.Init) { - cm.off("cursorActivity", doMatchBrackets); - cm.off("focus", doMatchBrackets); - cm.off("blur", clearHighlighted); - clearHighlighted(cm); - } - if (val) { - cm.state.matchBrackets = typeof val == "object" ? val : {}; - cm.on("cursorActivity", doMatchBrackets); - cm.on("focus", doMatchBrackets); - cm.on("blur", clearHighlighted); - } - }); - CodeMirror.defineExtension("matchBrackets", function () { - matchBrackets(this, true); - }); - CodeMirror.defineExtension("findMatchingBracket", function (pos, config, oldConfig) { - // Backwards-compatibility kludge - if (oldConfig || typeof config == "boolean") { - if (!oldConfig) { - config = config ? { - strict: true - } : null; - } else { - oldConfig.strict = config; - config = oldConfig; - } - } - return findMatchingBracket(this, pos, config); - }); - CodeMirror.defineExtension("scanForBracket", function (pos, dir, style, config) { - return scanForBracket(this, pos, dir, style, config); - }); -}); - -/***/ }), - -/***/ "../../../node_modules/codemirror/addon/fold/brace-fold.js": -/*!*****************************************************************!*\ - !*** ../../../node_modules/codemirror/addon/fold/brace-fold.js ***! - \*****************************************************************/ -/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function (mod) { - if (true) - // CommonJS - mod(__webpack_require__(/*! ../../lib/codemirror */ "../../../node_modules/codemirror/lib/codemirror.js"));else {} -})(function (CodeMirror) { - "use strict"; - - function bracketFolding(pairs) { - return function (cm, start) { - var line = start.line, - lineText = cm.getLine(line); - function findOpening(pair) { - var tokenType; - for (var at = start.ch, pass = 0;;) { - var found = at <= 0 ? -1 : lineText.lastIndexOf(pair[0], at - 1); - if (found == -1) { - if (pass == 1) break; - pass = 1; - at = lineText.length; - continue; - } - if (pass == 1 && found < start.ch) break; - tokenType = cm.getTokenTypeAt(CodeMirror.Pos(line, found + 1)); - if (!/^(comment|string)/.test(tokenType)) return { - ch: found + 1, - tokenType: tokenType, - pair: pair - }; - at = found - 1; - } - } - function findRange(found) { - var count = 1, - lastLine = cm.lastLine(), - end, - startCh = found.ch, - endCh; - outer: for (var i = line; i <= lastLine; ++i) { - var text = cm.getLine(i), - pos = i == line ? startCh : 0; - for (;;) { - var nextOpen = text.indexOf(found.pair[0], pos), - nextClose = text.indexOf(found.pair[1], pos); - if (nextOpen < 0) nextOpen = text.length; - if (nextClose < 0) nextClose = text.length; - pos = Math.min(nextOpen, nextClose); - if (pos == text.length) break; - if (cm.getTokenTypeAt(CodeMirror.Pos(i, pos + 1)) == found.tokenType) { - if (pos == nextOpen) ++count;else if (! --count) { - end = i; - endCh = pos; - break outer; - } - } - ++pos; - } - } - if (end == null || line == end) return null; - return { - from: CodeMirror.Pos(line, startCh), - to: CodeMirror.Pos(end, endCh) - }; - } - var found = []; - for (var i = 0; i < pairs.length; i++) { - var open = findOpening(pairs[i]); - if (open) found.push(open); - } - found.sort(function (a, b) { - return a.ch - b.ch; - }); - for (var i = 0; i < found.length; i++) { - var range = findRange(found[i]); - if (range) return range; - } - return null; - }; - } - CodeMirror.registerHelper("fold", "brace", bracketFolding([["{", "}"], ["[", "]"]])); - CodeMirror.registerHelper("fold", "brace-paren", bracketFolding([["{", "}"], ["[", "]"], ["(", ")"]])); - CodeMirror.registerHelper("fold", "import", function (cm, start) { - function hasImport(line) { - if (line < cm.firstLine() || line > cm.lastLine()) return null; - var start = cm.getTokenAt(CodeMirror.Pos(line, 1)); - if (!/\S/.test(start.string)) start = cm.getTokenAt(CodeMirror.Pos(line, start.end + 1)); - if (start.type != "keyword" || start.string != "import") return null; - // Now find closing semicolon, return its position - for (var i = line, e = Math.min(cm.lastLine(), line + 10); i <= e; ++i) { - var text = cm.getLine(i), - semi = text.indexOf(";"); - if (semi != -1) return { - startCh: start.end, - end: CodeMirror.Pos(i, semi) - }; - } - } - var startLine = start.line, - has = hasImport(startLine), - prev; - if (!has || hasImport(startLine - 1) || (prev = hasImport(startLine - 2)) && prev.end.line == startLine - 1) return null; - for (var end = has.end;;) { - var next = hasImport(end.line + 1); - if (next == null) break; - end = next.end; - } - return { - from: cm.clipPos(CodeMirror.Pos(startLine, has.startCh + 1)), - to: end - }; - }); - CodeMirror.registerHelper("fold", "include", function (cm, start) { - function hasInclude(line) { - if (line < cm.firstLine() || line > cm.lastLine()) return null; - var start = cm.getTokenAt(CodeMirror.Pos(line, 1)); - if (!/\S/.test(start.string)) start = cm.getTokenAt(CodeMirror.Pos(line, start.end + 1)); - if (start.type == "meta" && start.string.slice(0, 8) == "#include") return start.start + 8; - } - var startLine = start.line, - has = hasInclude(startLine); - if (has == null || hasInclude(startLine - 1) != null) return null; - for (var end = startLine;;) { - var next = hasInclude(end + 1); - if (next == null) break; - ++end; - } - return { - from: CodeMirror.Pos(startLine, has + 1), - to: cm.clipPos(CodeMirror.Pos(end)) - }; - }); -}); - -/***/ }), - -/***/ "../../../node_modules/codemirror/addon/fold/foldcode.js": -/*!***************************************************************!*\ - !*** ../../../node_modules/codemirror/addon/fold/foldcode.js ***! - \***************************************************************/ -/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function (mod) { - if (true) - // CommonJS - mod(__webpack_require__(/*! ../../lib/codemirror */ "../../../node_modules/codemirror/lib/codemirror.js"));else {} -})(function (CodeMirror) { - "use strict"; - - function doFold(cm, pos, options, force) { - if (options && options.call) { - var finder = options; - options = null; - } else { - var finder = getOption(cm, options, "rangeFinder"); - } - if (typeof pos == "number") pos = CodeMirror.Pos(pos, 0); - var minSize = getOption(cm, options, "minFoldSize"); - function getRange(allowFolded) { - var range = finder(cm, pos); - if (!range || range.to.line - range.from.line < minSize) return null; - if (force === "fold") return range; - var marks = cm.findMarksAt(range.from); - for (var i = 0; i < marks.length; ++i) { - if (marks[i].__isFold) { - if (!allowFolded) return null; - range.cleared = true; - marks[i].clear(); - } - } - return range; - } - var range = getRange(true); - if (getOption(cm, options, "scanUp")) while (!range && pos.line > cm.firstLine()) { - pos = CodeMirror.Pos(pos.line - 1, 0); - range = getRange(false); - } - if (!range || range.cleared || force === "unfold") return; - var myWidget = makeWidget(cm, options, range); - CodeMirror.on(myWidget, "mousedown", function (e) { - myRange.clear(); - CodeMirror.e_preventDefault(e); - }); - var myRange = cm.markText(range.from, range.to, { - replacedWith: myWidget, - clearOnEnter: getOption(cm, options, "clearOnEnter"), - __isFold: true - }); - myRange.on("clear", function (from, to) { - CodeMirror.signal(cm, "unfold", cm, from, to); - }); - CodeMirror.signal(cm, "fold", cm, range.from, range.to); - } - function makeWidget(cm, options, range) { - var widget = getOption(cm, options, "widget"); - if (typeof widget == "function") { - widget = widget(range.from, range.to); - } - if (typeof widget == "string") { - var text = document.createTextNode(widget); - widget = document.createElement("span"); - widget.appendChild(text); - widget.className = "CodeMirror-foldmarker"; - } else if (widget) { - widget = widget.cloneNode(true); - } - return widget; - } - - // Clumsy backwards-compatible interface - CodeMirror.newFoldFunction = function (rangeFinder, widget) { - return function (cm, pos) { - doFold(cm, pos, { - rangeFinder: rangeFinder, - widget: widget - }); - }; - }; - - // New-style interface - CodeMirror.defineExtension("foldCode", function (pos, options, force) { - doFold(this, pos, options, force); - }); - CodeMirror.defineExtension("isFolded", function (pos) { - var marks = this.findMarksAt(pos); - for (var i = 0; i < marks.length; ++i) if (marks[i].__isFold) return true; - }); - CodeMirror.commands.toggleFold = function (cm) { - cm.foldCode(cm.getCursor()); - }; - CodeMirror.commands.fold = function (cm) { - cm.foldCode(cm.getCursor(), null, "fold"); - }; - CodeMirror.commands.unfold = function (cm) { - cm.foldCode(cm.getCursor(), { - scanUp: false - }, "unfold"); - }; - CodeMirror.commands.foldAll = function (cm) { - cm.operation(function () { - for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++) cm.foldCode(CodeMirror.Pos(i, 0), { - scanUp: false - }, "fold"); - }); - }; - CodeMirror.commands.unfoldAll = function (cm) { - cm.operation(function () { - for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++) cm.foldCode(CodeMirror.Pos(i, 0), { - scanUp: false - }, "unfold"); - }); - }; - CodeMirror.registerHelper("fold", "combine", function () { - var funcs = Array.prototype.slice.call(arguments, 0); - return function (cm, start) { - for (var i = 0; i < funcs.length; ++i) { - var found = funcs[i](cm, start); - if (found) return found; - } - }; - }); - CodeMirror.registerHelper("fold", "auto", function (cm, start) { - var helpers = cm.getHelpers(start, "fold"); - for (var i = 0; i < helpers.length; i++) { - var cur = helpers[i](cm, start); - if (cur) return cur; - } - }); - var defaultOptions = { - rangeFinder: CodeMirror.fold.auto, - widget: "\u2194", - minFoldSize: 0, - scanUp: false, - clearOnEnter: true - }; - CodeMirror.defineOption("foldOptions", null); - function getOption(cm, options, name) { - if (options && options[name] !== undefined) return options[name]; - var editorOptions = cm.options.foldOptions; - if (editorOptions && editorOptions[name] !== undefined) return editorOptions[name]; - return defaultOptions[name]; - } - CodeMirror.defineExtension("foldOption", function (options, name) { - return getOption(this, options, name); - }); -}); - -/***/ }), - -/***/ "../../../node_modules/codemirror/addon/fold/foldgutter.js": -/*!*****************************************************************!*\ - !*** ../../../node_modules/codemirror/addon/fold/foldgutter.js ***! - \*****************************************************************/ -/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function (mod) { - if (true) - // CommonJS - mod(__webpack_require__(/*! ../../lib/codemirror */ "../../../node_modules/codemirror/lib/codemirror.js"), __webpack_require__(/*! ./foldcode */ "../../../node_modules/codemirror/addon/fold/foldcode.js"));else {} -})(function (CodeMirror) { - "use strict"; - - CodeMirror.defineOption("foldGutter", false, function (cm, val, old) { - if (old && old != CodeMirror.Init) { - cm.clearGutter(cm.state.foldGutter.options.gutter); - cm.state.foldGutter = null; - cm.off("gutterClick", onGutterClick); - cm.off("changes", onChange); - cm.off("viewportChange", onViewportChange); - cm.off("fold", onFold); - cm.off("unfold", onFold); - cm.off("swapDoc", onChange); - } - if (val) { - cm.state.foldGutter = new State(parseOptions(val)); - updateInViewport(cm); - cm.on("gutterClick", onGutterClick); - cm.on("changes", onChange); - cm.on("viewportChange", onViewportChange); - cm.on("fold", onFold); - cm.on("unfold", onFold); - cm.on("swapDoc", onChange); - } - }); - var Pos = CodeMirror.Pos; - function State(options) { - this.options = options; - this.from = this.to = 0; - } - function parseOptions(opts) { - if (opts === true) opts = {}; - if (opts.gutter == null) opts.gutter = "CodeMirror-foldgutter"; - if (opts.indicatorOpen == null) opts.indicatorOpen = "CodeMirror-foldgutter-open"; - if (opts.indicatorFolded == null) opts.indicatorFolded = "CodeMirror-foldgutter-folded"; - return opts; - } - function isFolded(cm, line) { - var marks = cm.findMarks(Pos(line, 0), Pos(line + 1, 0)); - for (var i = 0; i < marks.length; ++i) { - if (marks[i].__isFold) { - var fromPos = marks[i].find(-1); - if (fromPos && fromPos.line === line) return marks[i]; - } - } - } - function marker(spec) { - if (typeof spec == "string") { - var elt = document.createElement("div"); - elt.className = spec + " CodeMirror-guttermarker-subtle"; - return elt; - } else { - return spec.cloneNode(true); - } - } - function updateFoldInfo(cm, from, to) { - var opts = cm.state.foldGutter.options, - cur = from - 1; - var minSize = cm.foldOption(opts, "minFoldSize"); - var func = cm.foldOption(opts, "rangeFinder"); - // we can reuse the built-in indicator element if its className matches the new state - var clsFolded = typeof opts.indicatorFolded == "string" && classTest(opts.indicatorFolded); - var clsOpen = typeof opts.indicatorOpen == "string" && classTest(opts.indicatorOpen); - cm.eachLine(from, to, function (line) { - ++cur; - var mark = null; - var old = line.gutterMarkers; - if (old) old = old[opts.gutter]; - if (isFolded(cm, cur)) { - if (clsFolded && old && clsFolded.test(old.className)) return; - mark = marker(opts.indicatorFolded); - } else { - var pos = Pos(cur, 0); - var range = func && func(cm, pos); - if (range && range.to.line - range.from.line >= minSize) { - if (clsOpen && old && clsOpen.test(old.className)) return; - mark = marker(opts.indicatorOpen); - } - } - if (!mark && !old) return; - cm.setGutterMarker(line, opts.gutter, mark); - }); - } - - // copied from CodeMirror/src/util/dom.js - function classTest(cls) { - return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); - } - function updateInViewport(cm) { - var vp = cm.getViewport(), - state = cm.state.foldGutter; - if (!state) return; - cm.operation(function () { - updateFoldInfo(cm, vp.from, vp.to); - }); - state.from = vp.from; - state.to = vp.to; - } - function onGutterClick(cm, line, gutter) { - var state = cm.state.foldGutter; - if (!state) return; - var opts = state.options; - if (gutter != opts.gutter) return; - var folded = isFolded(cm, line); - if (folded) folded.clear();else cm.foldCode(Pos(line, 0), opts); - } - function onChange(cm) { - var state = cm.state.foldGutter; - if (!state) return; - var opts = state.options; - state.from = state.to = 0; - clearTimeout(state.changeUpdate); - state.changeUpdate = setTimeout(function () { - updateInViewport(cm); - }, opts.foldOnChangeTimeSpan || 600); - } - function onViewportChange(cm) { - var state = cm.state.foldGutter; - if (!state) return; - var opts = state.options; - clearTimeout(state.changeUpdate); - state.changeUpdate = setTimeout(function () { - var vp = cm.getViewport(); - if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) { - updateInViewport(cm); - } else { - cm.operation(function () { - if (vp.from < state.from) { - updateFoldInfo(cm, vp.from, state.from); - state.from = vp.from; - } - if (vp.to > state.to) { - updateFoldInfo(cm, state.to, vp.to); - state.to = vp.to; - } - }); - } - }, opts.updateViewportTimeSpan || 400); - } - function onFold(cm, from) { - var state = cm.state.foldGutter; - if (!state) return; - var line = from.line; - if (line >= state.from && line < state.to) updateFoldInfo(cm, line, line + 1); - } -}); - -/***/ }), - -/***/ "../../../node_modules/codemirror/addon/hint/show-hint.js": -/*!****************************************************************!*\ - !*** ../../../node_modules/codemirror/addon/hint/show-hint.js ***! - \****************************************************************/ -/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -// declare global: DOMRect - -(function (mod) { - if (true) - // CommonJS - mod(__webpack_require__(/*! ../../lib/codemirror */ "../../../node_modules/codemirror/lib/codemirror.js"));else {} -})(function (CodeMirror) { - "use strict"; - - var HINT_ELEMENT_CLASS = "CodeMirror-hint"; - var ACTIVE_HINT_ELEMENT_CLASS = "CodeMirror-hint-active"; - - // This is the old interface, kept around for now to stay - // backwards-compatible. - CodeMirror.showHint = function (cm, getHints, options) { - if (!getHints) return cm.showHint(options); - if (options && options.async) getHints.async = true; - var newOpts = { - hint: getHints - }; - if (options) for (var prop in options) newOpts[prop] = options[prop]; - return cm.showHint(newOpts); - }; - CodeMirror.defineExtension("showHint", function (options) { - options = parseOptions(this, this.getCursor("start"), options); - var selections = this.listSelections(); - if (selections.length > 1) return; - // By default, don't allow completion when something is selected. - // A hint function can have a `supportsSelection` property to - // indicate that it can handle selections. - if (this.somethingSelected()) { - if (!options.hint.supportsSelection) return; - // Don't try with cross-line selections - for (var i = 0; i < selections.length; i++) if (selections[i].head.line != selections[i].anchor.line) return; - } - if (this.state.completionActive) this.state.completionActive.close(); - var completion = this.state.completionActive = new Completion(this, options); - if (!completion.options.hint) return; - CodeMirror.signal(this, "startCompletion", this); - completion.update(true); - }); - CodeMirror.defineExtension("closeHint", function () { - if (this.state.completionActive) this.state.completionActive.close(); - }); - function Completion(cm, options) { - this.cm = cm; - this.options = options; - this.widget = null; - this.debounce = 0; - this.tick = 0; - this.startPos = this.cm.getCursor("start"); - this.startLen = this.cm.getLine(this.startPos.line).length - this.cm.getSelection().length; - if (this.options.updateOnCursorActivity) { - var self = this; - cm.on("cursorActivity", this.activityFunc = function () { - self.cursorActivity(); - }); - } - } - var requestAnimationFrame = window.requestAnimationFrame || function (fn) { - return setTimeout(fn, 1000 / 60); - }; - var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout; - Completion.prototype = { - close: function () { - if (!this.active()) return; - this.cm.state.completionActive = null; - this.tick = null; - if (this.options.updateOnCursorActivity) { - this.cm.off("cursorActivity", this.activityFunc); - } - if (this.widget && this.data) CodeMirror.signal(this.data, "close"); - if (this.widget) this.widget.close(); - CodeMirror.signal(this.cm, "endCompletion", this.cm); - }, - active: function () { - return this.cm.state.completionActive == this; - }, - pick: function (data, i) { - var completion = data.list[i], - self = this; - this.cm.operation(function () { - if (completion.hint) completion.hint(self.cm, data, completion);else self.cm.replaceRange(getText(completion), completion.from || data.from, completion.to || data.to, "complete"); - CodeMirror.signal(data, "pick", completion); - self.cm.scrollIntoView(); - }); - if (this.options.closeOnPick) { - this.close(); - } - }, - cursorActivity: function () { - if (this.debounce) { - cancelAnimationFrame(this.debounce); - this.debounce = 0; - } - var identStart = this.startPos; - if (this.data) { - identStart = this.data.from; - } - var pos = this.cm.getCursor(), - line = this.cm.getLine(pos.line); - if (pos.line != this.startPos.line || line.length - pos.ch != this.startLen - this.startPos.ch || pos.ch < identStart.ch || this.cm.somethingSelected() || !pos.ch || this.options.closeCharacters.test(line.charAt(pos.ch - 1))) { - this.close(); - } else { - var self = this; - this.debounce = requestAnimationFrame(function () { - self.update(); - }); - if (this.widget) this.widget.disable(); - } - }, - update: function (first) { - if (this.tick == null) return; - var self = this, - myTick = ++this.tick; - fetchHints(this.options.hint, this.cm, this.options, function (data) { - if (self.tick == myTick) self.finishUpdate(data, first); - }); - }, - finishUpdate: function (data, first) { - if (this.data) CodeMirror.signal(this.data, "update"); - var picked = this.widget && this.widget.picked || first && this.options.completeSingle; - if (this.widget) this.widget.close(); - this.data = data; - if (data && data.list.length) { - if (picked && data.list.length == 1) { - this.pick(data, 0); - } else { - this.widget = new Widget(this, data); - CodeMirror.signal(data, "shown"); - } - } - } - }; - function parseOptions(cm, pos, options) { - var editor = cm.options.hintOptions; - var out = {}; - for (var prop in defaultOptions) out[prop] = defaultOptions[prop]; - if (editor) for (var prop in editor) if (editor[prop] !== undefined) out[prop] = editor[prop]; - if (options) for (var prop in options) if (options[prop] !== undefined) out[prop] = options[prop]; - if (out.hint.resolve) out.hint = out.hint.resolve(cm, pos); - return out; - } - function getText(completion) { - if (typeof completion == "string") return completion;else return completion.text; - } - function buildKeyMap(completion, handle) { - var baseMap = { - Up: function () { - handle.moveFocus(-1); - }, - Down: function () { - handle.moveFocus(1); - }, - PageUp: function () { - handle.moveFocus(-handle.menuSize() + 1, true); - }, - PageDown: function () { - handle.moveFocus(handle.menuSize() - 1, true); - }, - Home: function () { - handle.setFocus(0); - }, - End: function () { - handle.setFocus(handle.length - 1); - }, - Enter: handle.pick, - Tab: handle.pick, - Esc: handle.close - }; - var mac = /Mac/.test(navigator.platform); - if (mac) { - baseMap["Ctrl-P"] = function () { - handle.moveFocus(-1); - }; - baseMap["Ctrl-N"] = function () { - handle.moveFocus(1); - }; - } - var custom = completion.options.customKeys; - var ourMap = custom ? {} : baseMap; - function addBinding(key, val) { - var bound; - if (typeof val != "string") bound = function (cm) { - return val(cm, handle); - }; - // This mechanism is deprecated - else if (baseMap.hasOwnProperty(val)) bound = baseMap[val];else bound = val; - ourMap[key] = bound; - } - if (custom) for (var key in custom) if (custom.hasOwnProperty(key)) addBinding(key, custom[key]); - var extra = completion.options.extraKeys; - if (extra) for (var key in extra) if (extra.hasOwnProperty(key)) addBinding(key, extra[key]); - return ourMap; - } - function getHintElement(hintsElement, el) { - while (el && el != hintsElement) { - if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement) return el; - el = el.parentNode; - } - } - function Widget(completion, data) { - this.id = "cm-complete-" + Math.floor(Math.random(1e6)); - this.completion = completion; - this.data = data; - this.picked = false; - var widget = this, - cm = completion.cm; - var ownerDocument = cm.getInputField().ownerDocument; - var parentWindow = ownerDocument.defaultView || ownerDocument.parentWindow; - var hints = this.hints = ownerDocument.createElement("ul"); - hints.setAttribute("role", "listbox"); - hints.setAttribute("aria-expanded", "true"); - hints.id = this.id; - var theme = completion.cm.options.theme; - hints.className = "CodeMirror-hints " + theme; - this.selectedHint = data.selectedHint || 0; - var completions = data.list; - for (var i = 0; i < completions.length; ++i) { - var elt = hints.appendChild(ownerDocument.createElement("li")), - cur = completions[i]; - var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS); - if (cur.className != null) className = cur.className + " " + className; - elt.className = className; - if (i == this.selectedHint) elt.setAttribute("aria-selected", "true"); - elt.id = this.id + "-" + i; - elt.setAttribute("role", "option"); - if (cur.render) cur.render(elt, data, cur);else elt.appendChild(ownerDocument.createTextNode(cur.displayText || getText(cur))); - elt.hintId = i; - } - var container = completion.options.container || ownerDocument.body; - var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null); - var left = pos.left, - top = pos.bottom, - below = true; - var offsetLeft = 0, - offsetTop = 0; - if (container !== ownerDocument.body) { - // We offset the cursor position because left and top are relative to the offsetParent's top left corner. - var isContainerPositioned = ['absolute', 'relative', 'fixed'].indexOf(parentWindow.getComputedStyle(container).position) !== -1; - var offsetParent = isContainerPositioned ? container : container.offsetParent; - var offsetParentPosition = offsetParent.getBoundingClientRect(); - var bodyPosition = ownerDocument.body.getBoundingClientRect(); - offsetLeft = offsetParentPosition.left - bodyPosition.left - offsetParent.scrollLeft; - offsetTop = offsetParentPosition.top - bodyPosition.top - offsetParent.scrollTop; - } - hints.style.left = left - offsetLeft + "px"; - hints.style.top = top - offsetTop + "px"; - - // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor. - var winW = parentWindow.innerWidth || Math.max(ownerDocument.body.offsetWidth, ownerDocument.documentElement.offsetWidth); - var winH = parentWindow.innerHeight || Math.max(ownerDocument.body.offsetHeight, ownerDocument.documentElement.offsetHeight); - container.appendChild(hints); - cm.getInputField().setAttribute("aria-autocomplete", "list"); - cm.getInputField().setAttribute("aria-owns", this.id); - cm.getInputField().setAttribute("aria-activedescendant", this.id + "-" + this.selectedHint); - var box = completion.options.moveOnOverlap ? hints.getBoundingClientRect() : new DOMRect(); - var scrolls = completion.options.paddingForScrollbar ? hints.scrollHeight > hints.clientHeight + 1 : false; - - // Compute in the timeout to avoid reflow on init - var startScroll; - setTimeout(function () { - startScroll = cm.getScrollInfo(); - }); - var overlapY = box.bottom - winH; - if (overlapY > 0) { - var height = box.bottom - box.top, - curTop = pos.top - (pos.bottom - box.top); - if (curTop - height > 0) { - // Fits above cursor - hints.style.top = (top = pos.top - height - offsetTop) + "px"; - below = false; - } else if (height > winH) { - hints.style.height = winH - 5 + "px"; - hints.style.top = (top = pos.bottom - box.top - offsetTop) + "px"; - var cursor = cm.getCursor(); - if (data.from.ch != cursor.ch) { - pos = cm.cursorCoords(cursor); - hints.style.left = (left = pos.left - offsetLeft) + "px"; - box = hints.getBoundingClientRect(); - } - } - } - var overlapX = box.right - winW; - if (scrolls) overlapX += cm.display.nativeBarWidth; - if (overlapX > 0) { - if (box.right - box.left > winW) { - hints.style.width = winW - 5 + "px"; - overlapX -= box.right - box.left - winW; - } - hints.style.left = (left = pos.left - overlapX - offsetLeft) + "px"; - } - if (scrolls) for (var node = hints.firstChild; node; node = node.nextSibling) node.style.paddingRight = cm.display.nativeBarWidth + "px"; - cm.addKeyMap(this.keyMap = buildKeyMap(completion, { - moveFocus: function (n, avoidWrap) { - widget.changeActive(widget.selectedHint + n, avoidWrap); - }, - setFocus: function (n) { - widget.changeActive(n); - }, - menuSize: function () { - return widget.screenAmount(); - }, - length: completions.length, - close: function () { - completion.close(); - }, - pick: function () { - widget.pick(); - }, - data: data - })); - if (completion.options.closeOnUnfocus) { - var closingOnBlur; - cm.on("blur", this.onBlur = function () { - closingOnBlur = setTimeout(function () { - completion.close(); - }, 100); - }); - cm.on("focus", this.onFocus = function () { - clearTimeout(closingOnBlur); - }); - } - cm.on("scroll", this.onScroll = function () { - var curScroll = cm.getScrollInfo(), - editor = cm.getWrapperElement().getBoundingClientRect(); - if (!startScroll) startScroll = cm.getScrollInfo(); - var newTop = top + startScroll.top - curScroll.top; - var point = newTop - (parentWindow.pageYOffset || (ownerDocument.documentElement || ownerDocument.body).scrollTop); - if (!below) point += hints.offsetHeight; - if (point <= editor.top || point >= editor.bottom) return completion.close(); - hints.style.top = newTop + "px"; - hints.style.left = left + startScroll.left - curScroll.left + "px"; - }); - CodeMirror.on(hints, "dblclick", function (e) { - var t = getHintElement(hints, e.target || e.srcElement); - if (t && t.hintId != null) { - widget.changeActive(t.hintId); - widget.pick(); - } - }); - CodeMirror.on(hints, "click", function (e) { - var t = getHintElement(hints, e.target || e.srcElement); - if (t && t.hintId != null) { - widget.changeActive(t.hintId); - if (completion.options.completeOnSingleClick) widget.pick(); - } - }); - CodeMirror.on(hints, "mousedown", function () { - setTimeout(function () { - cm.focus(); - }, 20); - }); - - // The first hint doesn't need to be scrolled to on init - var selectedHintRange = this.getSelectedHintRange(); - if (selectedHintRange.from !== 0 || selectedHintRange.to !== 0) { - this.scrollToActive(); - } - CodeMirror.signal(data, "select", completions[this.selectedHint], hints.childNodes[this.selectedHint]); - return true; - } - Widget.prototype = { - close: function () { - if (this.completion.widget != this) return; - this.completion.widget = null; - if (this.hints.parentNode) this.hints.parentNode.removeChild(this.hints); - this.completion.cm.removeKeyMap(this.keyMap); - var input = this.completion.cm.getInputField(); - input.removeAttribute("aria-activedescendant"); - input.removeAttribute("aria-owns"); - var cm = this.completion.cm; - if (this.completion.options.closeOnUnfocus) { - cm.off("blur", this.onBlur); - cm.off("focus", this.onFocus); - } - cm.off("scroll", this.onScroll); - }, - disable: function () { - this.completion.cm.removeKeyMap(this.keyMap); - var widget = this; - this.keyMap = { - Enter: function () { - widget.picked = true; - } - }; - this.completion.cm.addKeyMap(this.keyMap); - }, - pick: function () { - this.completion.pick(this.data, this.selectedHint); - }, - changeActive: function (i, avoidWrap) { - if (i >= this.data.list.length) i = avoidWrap ? this.data.list.length - 1 : 0;else if (i < 0) i = avoidWrap ? 0 : this.data.list.length - 1; - if (this.selectedHint == i) return; - var node = this.hints.childNodes[this.selectedHint]; - if (node) { - node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, ""); - node.removeAttribute("aria-selected"); - } - node = this.hints.childNodes[this.selectedHint = i]; - node.className += " " + ACTIVE_HINT_ELEMENT_CLASS; - node.setAttribute("aria-selected", "true"); - this.completion.cm.getInputField().setAttribute("aria-activedescendant", node.id); - this.scrollToActive(); - CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node); - }, - scrollToActive: function () { - var selectedHintRange = this.getSelectedHintRange(); - var node1 = this.hints.childNodes[selectedHintRange.from]; - var node2 = this.hints.childNodes[selectedHintRange.to]; - var firstNode = this.hints.firstChild; - if (node1.offsetTop < this.hints.scrollTop) this.hints.scrollTop = node1.offsetTop - firstNode.offsetTop;else if (node2.offsetTop + node2.offsetHeight > this.hints.scrollTop + this.hints.clientHeight) this.hints.scrollTop = node2.offsetTop + node2.offsetHeight - this.hints.clientHeight + firstNode.offsetTop; - }, - screenAmount: function () { - return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1; - }, - getSelectedHintRange: function () { - var margin = this.completion.options.scrollMargin || 0; - return { - from: Math.max(0, this.selectedHint - margin), - to: Math.min(this.data.list.length - 1, this.selectedHint + margin) - }; - } - }; - function applicableHelpers(cm, helpers) { - if (!cm.somethingSelected()) return helpers; - var result = []; - for (var i = 0; i < helpers.length; i++) if (helpers[i].supportsSelection) result.push(helpers[i]); - return result; - } - function fetchHints(hint, cm, options, callback) { - if (hint.async) { - hint(cm, callback, options); - } else { - var result = hint(cm, options); - if (result && result.then) result.then(callback);else callback(result); - } - } - function resolveAutoHints(cm, pos) { - var helpers = cm.getHelpers(pos, "hint"), - words; - if (helpers.length) { - var resolved = function (cm, callback, options) { - var app = applicableHelpers(cm, helpers); - function run(i) { - if (i == app.length) return callback(null); - fetchHints(app[i], cm, options, function (result) { - if (result && result.list.length > 0) callback(result);else run(i + 1); - }); - } - run(0); - }; - resolved.async = true; - resolved.supportsSelection = true; - return resolved; - } else if (words = cm.getHelper(cm.getCursor(), "hintWords")) { - return function (cm) { - return CodeMirror.hint.fromList(cm, { - words: words - }); - }; - } else if (CodeMirror.hint.anyword) { - return function (cm, options) { - return CodeMirror.hint.anyword(cm, options); - }; - } else { - return function () {}; - } - } - CodeMirror.registerHelper("hint", "auto", { - resolve: resolveAutoHints - }); - CodeMirror.registerHelper("hint", "fromList", function (cm, options) { - var cur = cm.getCursor(), - token = cm.getTokenAt(cur); - var term, - from = CodeMirror.Pos(cur.line, token.start), - to = cur; - if (token.start < cur.ch && /\w/.test(token.string.charAt(cur.ch - token.start - 1))) { - term = token.string.substr(0, cur.ch - token.start); - } else { - term = ""; - from = cur; - } - var found = []; - for (var i = 0; i < options.words.length; i++) { - var word = options.words[i]; - if (word.slice(0, term.length) == term) found.push(word); - } - if (found.length) return { - list: found, - from: from, - to: to - }; - }); - CodeMirror.commands.autocomplete = CodeMirror.showHint; - var defaultOptions = { - hint: CodeMirror.hint.auto, - completeSingle: true, - alignWithWord: true, - closeCharacters: /[\s()\[\]{};:>,]/, - closeOnPick: true, - closeOnUnfocus: true, - updateOnCursorActivity: true, - completeOnSingleClick: true, - container: null, - customKeys: null, - extraKeys: null, - paddingForScrollbar: true, - moveOnOverlap: true - }; - CodeMirror.defineOption("hintOptions", null); -}); - -/***/ }), - -/***/ "../../../node_modules/codemirror/addon/lint/lint.js": -/*!***********************************************************!*\ - !*** ../../../node_modules/codemirror/addon/lint/lint.js ***! - \***********************************************************/ -/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function (mod) { - if (true) - // CommonJS - mod(__webpack_require__(/*! ../../lib/codemirror */ "../../../node_modules/codemirror/lib/codemirror.js"));else {} -})(function (CodeMirror) { - "use strict"; - - var GUTTER_ID = "CodeMirror-lint-markers"; - var LINT_LINE_ID = "CodeMirror-lint-line-"; - function showTooltip(cm, e, content) { - var tt = document.createElement("div"); - tt.className = "CodeMirror-lint-tooltip cm-s-" + cm.options.theme; - tt.appendChild(content.cloneNode(true)); - if (cm.state.lint.options.selfContain) cm.getWrapperElement().appendChild(tt);else document.body.appendChild(tt); - function position(e) { - if (!tt.parentNode) return CodeMirror.off(document, "mousemove", position); - tt.style.top = Math.max(0, e.clientY - tt.offsetHeight - 5) + "px"; - tt.style.left = e.clientX + 5 + "px"; - } - CodeMirror.on(document, "mousemove", position); - position(e); - if (tt.style.opacity != null) tt.style.opacity = 1; - return tt; - } - function rm(elt) { - if (elt.parentNode) elt.parentNode.removeChild(elt); - } - function hideTooltip(tt) { - if (!tt.parentNode) return; - if (tt.style.opacity == null) rm(tt); - tt.style.opacity = 0; - setTimeout(function () { - rm(tt); - }, 600); - } - function showTooltipFor(cm, e, content, node) { - var tooltip = showTooltip(cm, e, content); - function hide() { - CodeMirror.off(node, "mouseout", hide); - if (tooltip) { - hideTooltip(tooltip); - tooltip = null; - } - } - var poll = setInterval(function () { - if (tooltip) for (var n = node;; n = n.parentNode) { - if (n && n.nodeType == 11) n = n.host; - if (n == document.body) return; - if (!n) { - hide(); - break; - } - } - if (!tooltip) return clearInterval(poll); - }, 400); - CodeMirror.on(node, "mouseout", hide); - } - function LintState(cm, conf, hasGutter) { - this.marked = []; - if (conf instanceof Function) conf = { - getAnnotations: conf - }; - if (!conf || conf === true) conf = {}; - this.options = {}; - this.linterOptions = conf.options || {}; - for (var prop in defaults) this.options[prop] = defaults[prop]; - for (var prop in conf) { - if (defaults.hasOwnProperty(prop)) { - if (conf[prop] != null) this.options[prop] = conf[prop]; - } else if (!conf.options) { - this.linterOptions[prop] = conf[prop]; - } - } - this.timeout = null; - this.hasGutter = hasGutter; - this.onMouseOver = function (e) { - onMouseOver(cm, e); - }; - this.waitingFor = 0; - } - var defaults = { - highlightLines: false, - tooltips: true, - delay: 500, - lintOnChange: true, - getAnnotations: null, - async: false, - selfContain: null, - formatAnnotation: null, - onUpdateLinting: null - }; - function clearMarks(cm) { - var state = cm.state.lint; - if (state.hasGutter) cm.clearGutter(GUTTER_ID); - if (state.options.highlightLines) clearErrorLines(cm); - for (var i = 0; i < state.marked.length; ++i) state.marked[i].clear(); - state.marked.length = 0; - } - function clearErrorLines(cm) { - cm.eachLine(function (line) { - var has = line.wrapClass && /\bCodeMirror-lint-line-\w+\b/.exec(line.wrapClass); - if (has) cm.removeLineClass(line, "wrap", has[0]); - }); - } - function makeMarker(cm, labels, severity, multiple, tooltips) { - var marker = document.createElement("div"), - inner = marker; - marker.className = "CodeMirror-lint-marker CodeMirror-lint-marker-" + severity; - if (multiple) { - inner = marker.appendChild(document.createElement("div")); - inner.className = "CodeMirror-lint-marker CodeMirror-lint-marker-multiple"; - } - if (tooltips != false) CodeMirror.on(inner, "mouseover", function (e) { - showTooltipFor(cm, e, labels, inner); - }); - return marker; - } - function getMaxSeverity(a, b) { - if (a == "error") return a;else return b; - } - function groupByLine(annotations) { - var lines = []; - for (var i = 0; i < annotations.length; ++i) { - var ann = annotations[i], - line = ann.from.line; - (lines[line] || (lines[line] = [])).push(ann); - } - return lines; - } - function annotationTooltip(ann) { - var severity = ann.severity; - if (!severity) severity = "error"; - var tip = document.createElement("div"); - tip.className = "CodeMirror-lint-message CodeMirror-lint-message-" + severity; - if (typeof ann.messageHTML != 'undefined') { - tip.innerHTML = ann.messageHTML; - } else { - tip.appendChild(document.createTextNode(ann.message)); - } - return tip; - } - function lintAsync(cm, getAnnotations) { - var state = cm.state.lint; - var id = ++state.waitingFor; - function abort() { - id = -1; - cm.off("change", abort); - } - cm.on("change", abort); - getAnnotations(cm.getValue(), function (annotations, arg2) { - cm.off("change", abort); - if (state.waitingFor != id) return; - if (arg2 && annotations instanceof CodeMirror) annotations = arg2; - cm.operation(function () { - updateLinting(cm, annotations); - }); - }, state.linterOptions, cm); - } - function startLinting(cm) { - var state = cm.state.lint; - if (!state) return; - var options = state.options; - /* - * Passing rules in `options` property prevents JSHint (and other linters) from complaining - * about unrecognized rules like `onUpdateLinting`, `delay`, `lintOnChange`, etc. - */ - var getAnnotations = options.getAnnotations || cm.getHelper(CodeMirror.Pos(0, 0), "lint"); - if (!getAnnotations) return; - if (options.async || getAnnotations.async) { - lintAsync(cm, getAnnotations); - } else { - var annotations = getAnnotations(cm.getValue(), state.linterOptions, cm); - if (!annotations) return; - if (annotations.then) annotations.then(function (issues) { - cm.operation(function () { - updateLinting(cm, issues); - }); - });else cm.operation(function () { - updateLinting(cm, annotations); - }); - } - } - function updateLinting(cm, annotationsNotSorted) { - var state = cm.state.lint; - if (!state) return; - var options = state.options; - clearMarks(cm); - var annotations = groupByLine(annotationsNotSorted); - for (var line = 0; line < annotations.length; ++line) { - var anns = annotations[line]; - if (!anns) continue; - - // filter out duplicate messages - var message = []; - anns = anns.filter(function (item) { - return message.indexOf(item.message) > -1 ? false : message.push(item.message); - }); - var maxSeverity = null; - var tipLabel = state.hasGutter && document.createDocumentFragment(); - for (var i = 0; i < anns.length; ++i) { - var ann = anns[i]; - var severity = ann.severity; - if (!severity) severity = "error"; - maxSeverity = getMaxSeverity(maxSeverity, severity); - if (options.formatAnnotation) ann = options.formatAnnotation(ann); - if (state.hasGutter) tipLabel.appendChild(annotationTooltip(ann)); - if (ann.to) state.marked.push(cm.markText(ann.from, ann.to, { - className: "CodeMirror-lint-mark CodeMirror-lint-mark-" + severity, - __annotation: ann - })); - } - // use original annotations[line] to show multiple messages - if (state.hasGutter) cm.setGutterMarker(line, GUTTER_ID, makeMarker(cm, tipLabel, maxSeverity, annotations[line].length > 1, options.tooltips)); - if (options.highlightLines) cm.addLineClass(line, "wrap", LINT_LINE_ID + maxSeverity); - } - if (options.onUpdateLinting) options.onUpdateLinting(annotationsNotSorted, annotations, cm); - } - function onChange(cm) { - var state = cm.state.lint; - if (!state) return; - clearTimeout(state.timeout); - state.timeout = setTimeout(function () { - startLinting(cm); - }, state.options.delay); - } - function popupTooltips(cm, annotations, e) { - var target = e.target || e.srcElement; - var tooltip = document.createDocumentFragment(); - for (var i = 0; i < annotations.length; i++) { - var ann = annotations[i]; - tooltip.appendChild(annotationTooltip(ann)); - } - showTooltipFor(cm, e, tooltip, target); - } - function onMouseOver(cm, e) { - var target = e.target || e.srcElement; - if (!/\bCodeMirror-lint-mark-/.test(target.className)) return; - var box = target.getBoundingClientRect(), - x = (box.left + box.right) / 2, - y = (box.top + box.bottom) / 2; - var spans = cm.findMarksAt(cm.coordsChar({ - left: x, - top: y - }, "client")); - var annotations = []; - for (var i = 0; i < spans.length; ++i) { - var ann = spans[i].__annotation; - if (ann) annotations.push(ann); - } - if (annotations.length) popupTooltips(cm, annotations, e); - } - CodeMirror.defineOption("lint", false, function (cm, val, old) { - if (old && old != CodeMirror.Init) { - clearMarks(cm); - if (cm.state.lint.options.lintOnChange !== false) cm.off("change", onChange); - CodeMirror.off(cm.getWrapperElement(), "mouseover", cm.state.lint.onMouseOver); - clearTimeout(cm.state.lint.timeout); - delete cm.state.lint; - } - if (val) { - var gutters = cm.getOption("gutters"), - hasLintGutter = false; - for (var i = 0; i < gutters.length; ++i) if (gutters[i] == GUTTER_ID) hasLintGutter = true; - var state = cm.state.lint = new LintState(cm, val, hasLintGutter); - if (state.options.lintOnChange) cm.on("change", onChange); - if (state.options.tooltips != false && state.options.tooltips != "gutter") CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver); - startLinting(cm); - } - }); - CodeMirror.defineExtension("performLint", function () { - startLinting(this); - }); -}); - -/***/ }), - -/***/ "../../../node_modules/codemirror/addon/search/jump-to-line.js": -/*!*********************************************************************!*\ - !*** ../../../node_modules/codemirror/addon/search/jump-to-line.js ***! - \*********************************************************************/ -/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -// Defines jumpToLine command. Uses dialog.js if present. - -(function (mod) { - if (true) - // CommonJS - mod(__webpack_require__(/*! ../../lib/codemirror */ "../../../node_modules/codemirror/lib/codemirror.js"), __webpack_require__(/*! ../dialog/dialog */ "../../../node_modules/codemirror/addon/dialog/dialog.js"));else {} -})(function (CodeMirror) { - "use strict"; - - // default search panel location - CodeMirror.defineOption("search", { - bottom: false - }); - function dialog(cm, text, shortText, deflt, f) { - if (cm.openDialog) cm.openDialog(text, f, { - value: deflt, - selectValueOnOpen: true, - bottom: cm.options.search.bottom - });else f(prompt(shortText, deflt)); - } - function getJumpDialog(cm) { - return cm.phrase("Jump to line:") + ' ' + cm.phrase("(Use line:column or scroll% syntax)") + ''; - } - function interpretLine(cm, string) { - var num = Number(string); - if (/^[-+]/.test(string)) return cm.getCursor().line + num;else return num - 1; - } - CodeMirror.commands.jumpToLine = function (cm) { - var cur = cm.getCursor(); - dialog(cm, getJumpDialog(cm), cm.phrase("Jump to line:"), cur.line + 1 + ":" + cur.ch, function (posStr) { - if (!posStr) return; - var match; - if (match = /^\s*([\+\-]?\d+)\s*\:\s*(\d+)\s*$/.exec(posStr)) { - cm.setCursor(interpretLine(cm, match[1]), Number(match[2])); - } else if (match = /^\s*([\+\-]?\d+(\.\d+)?)\%\s*/.exec(posStr)) { - var line = Math.round(cm.lineCount() * Number(match[1]) / 100); - if (/^[-+]/.test(match[1])) line = cur.line + line + 1; - cm.setCursor(line - 1, cur.ch); - } else if (match = /^\s*\:?\s*([\+\-]?\d+)\s*/.exec(posStr)) { - cm.setCursor(interpretLine(cm, match[1]), cur.ch); - } - }); - }; - CodeMirror.keyMap["default"]["Alt-G"] = "jumpToLine"; -}); - -/***/ }), - -/***/ "../../../node_modules/codemirror/addon/search/search.js": -/*!***************************************************************!*\ - !*** ../../../node_modules/codemirror/addon/search/search.js ***! - \***************************************************************/ -/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -// Define search commands. Depends on dialog.js or another -// implementation of the openDialog method. - -// Replace works a little oddly -- it will do the replace on the next -// Ctrl-G (or whatever is bound to findNext) press. You prevent a -// replace by making sure the match is no longer selected when hitting -// Ctrl-G. - -(function (mod) { - if (true) - // CommonJS - mod(__webpack_require__(/*! ../../lib/codemirror */ "../../../node_modules/codemirror/lib/codemirror.js"), __webpack_require__(/*! ./searchcursor */ "../../../node_modules/codemirror/addon/search/searchcursor.js"), __webpack_require__(/*! ../dialog/dialog */ "../../../node_modules/codemirror/addon/dialog/dialog.js"));else {} -})(function (CodeMirror) { - "use strict"; - - // default search panel location - CodeMirror.defineOption("search", { - bottom: false - }); - function searchOverlay(query, caseInsensitive) { - if (typeof query == "string") query = new RegExp(query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), caseInsensitive ? "gi" : "g");else if (!query.global) query = new RegExp(query.source, query.ignoreCase ? "gi" : "g"); - return { - token: function (stream) { - query.lastIndex = stream.pos; - var match = query.exec(stream.string); - if (match && match.index == stream.pos) { - stream.pos += match[0].length || 1; - return "searching"; - } else if (match) { - stream.pos = match.index; - } else { - stream.skipToEnd(); - } - } - }; - } - function SearchState() { - this.posFrom = this.posTo = this.lastQuery = this.query = null; - this.overlay = null; - } - function getSearchState(cm) { - return cm.state.search || (cm.state.search = new SearchState()); - } - function queryCaseInsensitive(query) { - return typeof query == "string" && query == query.toLowerCase(); - } - function getSearchCursor(cm, query, pos) { - // Heuristic: if the query string is all lowercase, do a case insensitive search. - return cm.getSearchCursor(query, pos, { - caseFold: queryCaseInsensitive(query), - multiline: true - }); - } - function persistentDialog(cm, text, deflt, onEnter, onKeyDown) { - cm.openDialog(text, onEnter, { - value: deflt, - selectValueOnOpen: true, - closeOnEnter: false, - onClose: function () { - clearSearch(cm); - }, - onKeyDown: onKeyDown, - bottom: cm.options.search.bottom - }); - } - function dialog(cm, text, shortText, deflt, f) { - if (cm.openDialog) cm.openDialog(text, f, { - value: deflt, - selectValueOnOpen: true, - bottom: cm.options.search.bottom - });else f(prompt(shortText, deflt)); - } - function confirmDialog(cm, text, shortText, fs) { - if (cm.openConfirm) cm.openConfirm(text, fs);else if (confirm(shortText)) fs[0](); - } - function parseString(string) { - return string.replace(/\\([nrt\\])/g, function (match, ch) { - if (ch == "n") return "\n"; - if (ch == "r") return "\r"; - if (ch == "t") return "\t"; - if (ch == "\\") return "\\"; - return match; - }); - } - function parseQuery(query) { - var isRE = query.match(/^\/(.*)\/([a-z]*)$/); - if (isRE) { - try { - query = new RegExp(isRE[1], isRE[2].indexOf("i") == -1 ? "" : "i"); - } catch (e) {} // Not a regular expression after all, do a string search - } else { - query = parseString(query); - } - if (typeof query == "string" ? query == "" : query.test("")) query = /x^/; - return query; - } - function startSearch(cm, state, query) { - state.queryText = query; - state.query = parseQuery(query); - cm.removeOverlay(state.overlay, queryCaseInsensitive(state.query)); - state.overlay = searchOverlay(state.query, queryCaseInsensitive(state.query)); - cm.addOverlay(state.overlay); - if (cm.showMatchesOnScrollbar) { - if (state.annotate) { - state.annotate.clear(); - state.annotate = null; - } - state.annotate = cm.showMatchesOnScrollbar(state.query, queryCaseInsensitive(state.query)); - } - } - function doSearch(cm, rev, persistent, immediate) { - var state = getSearchState(cm); - if (state.query) return findNext(cm, rev); - var q = cm.getSelection() || state.lastQuery; - if (q instanceof RegExp && q.source == "x^") q = null; - if (persistent && cm.openDialog) { - var hiding = null; - var searchNext = function (query, event) { - CodeMirror.e_stop(event); - if (!query) return; - if (query != state.queryText) { - startSearch(cm, state, query); - state.posFrom = state.posTo = cm.getCursor(); - } - if (hiding) hiding.style.opacity = 1; - findNext(cm, event.shiftKey, function (_, to) { - var dialog; - if (to.line < 3 && document.querySelector && (dialog = cm.display.wrapper.querySelector(".CodeMirror-dialog")) && dialog.getBoundingClientRect().bottom - 4 > cm.cursorCoords(to, "window").top) (hiding = dialog).style.opacity = .4; - }); - }; - persistentDialog(cm, getQueryDialog(cm), q, searchNext, function (event, query) { - var keyName = CodeMirror.keyName(event); - var extra = cm.getOption('extraKeys'), - cmd = extra && extra[keyName] || CodeMirror.keyMap[cm.getOption("keyMap")][keyName]; - if (cmd == "findNext" || cmd == "findPrev" || cmd == "findPersistentNext" || cmd == "findPersistentPrev") { - CodeMirror.e_stop(event); - startSearch(cm, getSearchState(cm), query); - cm.execCommand(cmd); - } else if (cmd == "find" || cmd == "findPersistent") { - CodeMirror.e_stop(event); - searchNext(query, event); - } - }); - if (immediate && q) { - startSearch(cm, state, q); - findNext(cm, rev); - } - } else { - dialog(cm, getQueryDialog(cm), "Search for:", q, function (query) { - if (query && !state.query) cm.operation(function () { - startSearch(cm, state, query); - state.posFrom = state.posTo = cm.getCursor(); - findNext(cm, rev); - }); - }); - } - } - function findNext(cm, rev, callback) { - cm.operation(function () { - var state = getSearchState(cm); - var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo); - if (!cursor.find(rev)) { - cursor = getSearchCursor(cm, state.query, rev ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm.firstLine(), 0)); - if (!cursor.find(rev)) return; - } - cm.setSelection(cursor.from(), cursor.to()); - cm.scrollIntoView({ - from: cursor.from(), - to: cursor.to() - }, 20); - state.posFrom = cursor.from(); - state.posTo = cursor.to(); - if (callback) callback(cursor.from(), cursor.to()); - }); - } - function clearSearch(cm) { - cm.operation(function () { - var state = getSearchState(cm); - state.lastQuery = state.query; - if (!state.query) return; - state.query = state.queryText = null; - cm.removeOverlay(state.overlay); - if (state.annotate) { - state.annotate.clear(); - state.annotate = null; - } - }); - } - function el(tag, attrs) { - var element = tag ? document.createElement(tag) : document.createDocumentFragment(); - for (var key in attrs) { - element[key] = attrs[key]; - } - for (var i = 2; i < arguments.length; i++) { - var child = arguments[i]; - element.appendChild(typeof child == "string" ? document.createTextNode(child) : child); - } - return element; - } - function getQueryDialog(cm) { - return el("", null, el("span", { - className: "CodeMirror-search-label" - }, cm.phrase("Search:")), " ", el("input", { - type: "text", - "style": "width: 10em", - className: "CodeMirror-search-field" - }), " ", el("span", { - style: "color: #888", - className: "CodeMirror-search-hint" - }, cm.phrase("(Use /re/ syntax for regexp search)"))); - } - function getReplaceQueryDialog(cm) { - return el("", null, " ", el("input", { - type: "text", - "style": "width: 10em", - className: "CodeMirror-search-field" - }), " ", el("span", { - style: "color: #888", - className: "CodeMirror-search-hint" - }, cm.phrase("(Use /re/ syntax for regexp search)"))); - } - function getReplacementQueryDialog(cm) { - return el("", null, el("span", { - className: "CodeMirror-search-label" - }, cm.phrase("With:")), " ", el("input", { - type: "text", - "style": "width: 10em", - className: "CodeMirror-search-field" - })); - } - function getDoReplaceConfirm(cm) { - return el("", null, el("span", { - className: "CodeMirror-search-label" - }, cm.phrase("Replace?")), " ", el("button", {}, cm.phrase("Yes")), " ", el("button", {}, cm.phrase("No")), " ", el("button", {}, cm.phrase("All")), " ", el("button", {}, cm.phrase("Stop"))); - } - function replaceAll(cm, query, text) { - cm.operation(function () { - for (var cursor = getSearchCursor(cm, query); cursor.findNext();) { - if (typeof query != "string") { - var match = cm.getRange(cursor.from(), cursor.to()).match(query); - cursor.replace(text.replace(/\$(\d)/g, function (_, i) { - return match[i]; - })); - } else cursor.replace(text); - } - }); - } - function replace(cm, all) { - if (cm.getOption("readOnly")) return; - var query = cm.getSelection() || getSearchState(cm).lastQuery; - var dialogText = all ? cm.phrase("Replace all:") : cm.phrase("Replace:"); - var fragment = el("", null, el("span", { - className: "CodeMirror-search-label" - }, dialogText), getReplaceQueryDialog(cm)); - dialog(cm, fragment, dialogText, query, function (query) { - if (!query) return; - query = parseQuery(query); - dialog(cm, getReplacementQueryDialog(cm), cm.phrase("Replace with:"), "", function (text) { - text = parseString(text); - if (all) { - replaceAll(cm, query, text); - } else { - clearSearch(cm); - var cursor = getSearchCursor(cm, query, cm.getCursor("from")); - var advance = function () { - var start = cursor.from(), - match; - if (!(match = cursor.findNext())) { - cursor = getSearchCursor(cm, query); - if (!(match = cursor.findNext()) || start && cursor.from().line == start.line && cursor.from().ch == start.ch) return; - } - cm.setSelection(cursor.from(), cursor.to()); - cm.scrollIntoView({ - from: cursor.from(), - to: cursor.to() - }); - confirmDialog(cm, getDoReplaceConfirm(cm), cm.phrase("Replace?"), [function () { - doReplace(match); - }, advance, function () { - replaceAll(cm, query, text); - }]); - }; - var doReplace = function (match) { - cursor.replace(typeof query == "string" ? text : text.replace(/\$(\d)/g, function (_, i) { - return match[i]; - })); - advance(); - }; - advance(); - } - }); - }); - } - CodeMirror.commands.find = function (cm) { - clearSearch(cm); - doSearch(cm); - }; - CodeMirror.commands.findPersistent = function (cm) { - clearSearch(cm); - doSearch(cm, false, true); - }; - CodeMirror.commands.findPersistentNext = function (cm) { - doSearch(cm, false, true, true); - }; - CodeMirror.commands.findPersistentPrev = function (cm) { - doSearch(cm, true, true, true); - }; - CodeMirror.commands.findNext = doSearch; - CodeMirror.commands.findPrev = function (cm) { - doSearch(cm, true); - }; - CodeMirror.commands.clearSearch = clearSearch; - CodeMirror.commands.replace = replace; - CodeMirror.commands.replaceAll = function (cm) { - replace(cm, true); - }; -}); - -/***/ }), - -/***/ "../../../node_modules/codemirror/addon/search/searchcursor.js": -/*!*********************************************************************!*\ - !*** ../../../node_modules/codemirror/addon/search/searchcursor.js ***! - \*********************************************************************/ -/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function (mod) { - if (true) - // CommonJS - mod(__webpack_require__(/*! ../../lib/codemirror */ "../../../node_modules/codemirror/lib/codemirror.js"));else {} -})(function (CodeMirror) { - "use strict"; - - var Pos = CodeMirror.Pos; - function regexpFlags(regexp) { - var flags = regexp.flags; - return flags != null ? flags : (regexp.ignoreCase ? "i" : "") + (regexp.global ? "g" : "") + (regexp.multiline ? "m" : ""); - } - function ensureFlags(regexp, flags) { - var current = regexpFlags(regexp), - target = current; - for (var i = 0; i < flags.length; i++) if (target.indexOf(flags.charAt(i)) == -1) target += flags.charAt(i); - return current == target ? regexp : new RegExp(regexp.source, target); - } - function maybeMultiline(regexp) { - return /\\s|\\n|\n|\\W|\\D|\[\^/.test(regexp.source); - } - function searchRegexpForward(doc, regexp, start) { - regexp = ensureFlags(regexp, "g"); - for (var line = start.line, ch = start.ch, last = doc.lastLine(); line <= last; line++, ch = 0) { - regexp.lastIndex = ch; - var string = doc.getLine(line), - match = regexp.exec(string); - if (match) return { - from: Pos(line, match.index), - to: Pos(line, match.index + match[0].length), - match: match - }; - } - } - function searchRegexpForwardMultiline(doc, regexp, start) { - if (!maybeMultiline(regexp)) return searchRegexpForward(doc, regexp, start); - regexp = ensureFlags(regexp, "gm"); - var string, - chunk = 1; - for (var line = start.line, last = doc.lastLine(); line <= last;) { - // This grows the search buffer in exponentially-sized chunks - // between matches, so that nearby matches are fast and don't - // require concatenating the whole document (in case we're - // searching for something that has tons of matches), but at the - // same time, the amount of retries is limited. - for (var i = 0; i < chunk; i++) { - if (line > last) break; - var curLine = doc.getLine(line++); - string = string == null ? curLine : string + "\n" + curLine; - } - chunk = chunk * 2; - regexp.lastIndex = start.ch; - var match = regexp.exec(string); - if (match) { - var before = string.slice(0, match.index).split("\n"), - inside = match[0].split("\n"); - var startLine = start.line + before.length - 1, - startCh = before[before.length - 1].length; - return { - from: Pos(startLine, startCh), - to: Pos(startLine + inside.length - 1, inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length), - match: match - }; - } - } - } - function lastMatchIn(string, regexp, endMargin) { - var match, - from = 0; - while (from <= string.length) { - regexp.lastIndex = from; - var newMatch = regexp.exec(string); - if (!newMatch) break; - var end = newMatch.index + newMatch[0].length; - if (end > string.length - endMargin) break; - if (!match || end > match.index + match[0].length) match = newMatch; - from = newMatch.index + 1; - } - return match; - } - function searchRegexpBackward(doc, regexp, start) { - regexp = ensureFlags(regexp, "g"); - for (var line = start.line, ch = start.ch, first = doc.firstLine(); line >= first; line--, ch = -1) { - var string = doc.getLine(line); - var match = lastMatchIn(string, regexp, ch < 0 ? 0 : string.length - ch); - if (match) return { - from: Pos(line, match.index), - to: Pos(line, match.index + match[0].length), - match: match - }; - } - } - function searchRegexpBackwardMultiline(doc, regexp, start) { - if (!maybeMultiline(regexp)) return searchRegexpBackward(doc, regexp, start); - regexp = ensureFlags(regexp, "gm"); - var string, - chunkSize = 1, - endMargin = doc.getLine(start.line).length - start.ch; - for (var line = start.line, first = doc.firstLine(); line >= first;) { - for (var i = 0; i < chunkSize && line >= first; i++) { - var curLine = doc.getLine(line--); - string = string == null ? curLine : curLine + "\n" + string; - } - chunkSize *= 2; - var match = lastMatchIn(string, regexp, endMargin); - if (match) { - var before = string.slice(0, match.index).split("\n"), - inside = match[0].split("\n"); - var startLine = line + before.length, - startCh = before[before.length - 1].length; - return { - from: Pos(startLine, startCh), - to: Pos(startLine + inside.length - 1, inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length), - match: match - }; - } - } - } - var doFold, noFold; - if (String.prototype.normalize) { - doFold = function (str) { - return str.normalize("NFD").toLowerCase(); - }; - noFold = function (str) { - return str.normalize("NFD"); - }; - } else { - doFold = function (str) { - return str.toLowerCase(); - }; - noFold = function (str) { - return str; - }; - } - - // Maps a position in a case-folded line back to a position in the original line - // (compensating for codepoints increasing in number during folding) - function adjustPos(orig, folded, pos, foldFunc) { - if (orig.length == folded.length) return pos; - for (var min = 0, max = pos + Math.max(0, orig.length - folded.length);;) { - if (min == max) return min; - var mid = min + max >> 1; - var len = foldFunc(orig.slice(0, mid)).length; - if (len == pos) return mid;else if (len > pos) max = mid;else min = mid + 1; - } - } - function searchStringForward(doc, query, start, caseFold) { - // Empty string would match anything and never progress, so we - // define it to match nothing instead. - if (!query.length) return null; - var fold = caseFold ? doFold : noFold; - var lines = fold(query).split(/\r|\n\r?/); - search: for (var line = start.line, ch = start.ch, last = doc.lastLine() + 1 - lines.length; line <= last; line++, ch = 0) { - var orig = doc.getLine(line).slice(ch), - string = fold(orig); - if (lines.length == 1) { - var found = string.indexOf(lines[0]); - if (found == -1) continue search; - var start = adjustPos(orig, string, found, fold) + ch; - return { - from: Pos(line, adjustPos(orig, string, found, fold) + ch), - to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold) + ch) - }; - } else { - var cutFrom = string.length - lines[0].length; - if (string.slice(cutFrom) != lines[0]) continue search; - for (var i = 1; i < lines.length - 1; i++) if (fold(doc.getLine(line + i)) != lines[i]) continue search; - var end = doc.getLine(line + lines.length - 1), - endString = fold(end), - lastLine = lines[lines.length - 1]; - if (endString.slice(0, lastLine.length) != lastLine) continue search; - return { - from: Pos(line, adjustPos(orig, string, cutFrom, fold) + ch), - to: Pos(line + lines.length - 1, adjustPos(end, endString, lastLine.length, fold)) - }; - } - } - } - function searchStringBackward(doc, query, start, caseFold) { - if (!query.length) return null; - var fold = caseFold ? doFold : noFold; - var lines = fold(query).split(/\r|\n\r?/); - search: for (var line = start.line, ch = start.ch, first = doc.firstLine() - 1 + lines.length; line >= first; line--, ch = -1) { - var orig = doc.getLine(line); - if (ch > -1) orig = orig.slice(0, ch); - var string = fold(orig); - if (lines.length == 1) { - var found = string.lastIndexOf(lines[0]); - if (found == -1) continue search; - return { - from: Pos(line, adjustPos(orig, string, found, fold)), - to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold)) - }; - } else { - var lastLine = lines[lines.length - 1]; - if (string.slice(0, lastLine.length) != lastLine) continue search; - for (var i = 1, start = line - lines.length + 1; i < lines.length - 1; i++) if (fold(doc.getLine(start + i)) != lines[i]) continue search; - var top = doc.getLine(line + 1 - lines.length), - topString = fold(top); - if (topString.slice(topString.length - lines[0].length) != lines[0]) continue search; - return { - from: Pos(line + 1 - lines.length, adjustPos(top, topString, top.length - lines[0].length, fold)), - to: Pos(line, adjustPos(orig, string, lastLine.length, fold)) - }; - } - } - } - function SearchCursor(doc, query, pos, options) { - this.atOccurrence = false; - this.afterEmptyMatch = false; - this.doc = doc; - pos = pos ? doc.clipPos(pos) : Pos(0, 0); - this.pos = { - from: pos, - to: pos - }; - var caseFold; - if (typeof options == "object") { - caseFold = options.caseFold; - } else { - // Backwards compat for when caseFold was the 4th argument - caseFold = options; - options = null; - } - if (typeof query == "string") { - if (caseFold == null) caseFold = false; - this.matches = function (reverse, pos) { - return (reverse ? searchStringBackward : searchStringForward)(doc, query, pos, caseFold); - }; - } else { - query = ensureFlags(query, "gm"); - if (!options || options.multiline !== false) this.matches = function (reverse, pos) { - return (reverse ? searchRegexpBackwardMultiline : searchRegexpForwardMultiline)(doc, query, pos); - };else this.matches = function (reverse, pos) { - return (reverse ? searchRegexpBackward : searchRegexpForward)(doc, query, pos); - }; - } - } - SearchCursor.prototype = { - findNext: function () { - return this.find(false); - }, - findPrevious: function () { - return this.find(true); - }, - find: function (reverse) { - var head = this.doc.clipPos(reverse ? this.pos.from : this.pos.to); - if (this.afterEmptyMatch && this.atOccurrence) { - // do not return the same 0 width match twice - head = Pos(head.line, head.ch); - if (reverse) { - head.ch--; - if (head.ch < 0) { - head.line--; - head.ch = (this.doc.getLine(head.line) || "").length; - } - } else { - head.ch++; - if (head.ch > (this.doc.getLine(head.line) || "").length) { - head.ch = 0; - head.line++; - } - } - if (CodeMirror.cmpPos(head, this.doc.clipPos(head)) != 0) { - return this.atOccurrence = false; - } - } - var result = this.matches(reverse, head); - this.afterEmptyMatch = result && CodeMirror.cmpPos(result.from, result.to) == 0; - if (result) { - this.pos = result; - this.atOccurrence = true; - return this.pos.match || true; - } else { - var end = Pos(reverse ? this.doc.firstLine() : this.doc.lastLine() + 1, 0); - this.pos = { - from: end, - to: end - }; - return this.atOccurrence = false; - } - }, - from: function () { - if (this.atOccurrence) return this.pos.from; - }, - to: function () { - if (this.atOccurrence) return this.pos.to; - }, - replace: function (newText, origin) { - if (!this.atOccurrence) return; - var lines = CodeMirror.splitLines(newText); - this.doc.replaceRange(lines, this.pos.from, this.pos.to, origin); - this.pos.to = Pos(this.pos.from.line + lines.length - 1, lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0)); - } - }; - CodeMirror.defineExtension("getSearchCursor", function (query, pos, caseFold) { - return new SearchCursor(this.doc, query, pos, caseFold); - }); - CodeMirror.defineDocExtension("getSearchCursor", function (query, pos, caseFold) { - return new SearchCursor(this, query, pos, caseFold); - }); - CodeMirror.defineExtension("selectMatches", function (query, caseFold) { - var ranges = []; - var cur = this.getSearchCursor(query, this.getCursor("from"), caseFold); - while (cur.findNext()) { - if (CodeMirror.cmpPos(cur.to(), this.getCursor("to")) > 0) break; - ranges.push({ - anchor: cur.from(), - head: cur.to() - }); - } - if (ranges.length) this.setSelections(ranges, 0); - }); -}); - -/***/ }), - -/***/ "../../../node_modules/codemirror/keymap/sublime.js": -/*!**********************************************************!*\ - !*** ../../../node_modules/codemirror/keymap/sublime.js ***! - \**********************************************************/ -/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -// A rough approximation of Sublime Text's keybindings -// Depends on addon/search/searchcursor.js and optionally addon/dialog/dialogs.js - -(function (mod) { - if (true) - // CommonJS - mod(__webpack_require__(/*! ../lib/codemirror */ "../../../node_modules/codemirror/lib/codemirror.js"), __webpack_require__(/*! ../addon/search/searchcursor */ "../../../node_modules/codemirror/addon/search/searchcursor.js"), __webpack_require__(/*! ../addon/edit/matchbrackets */ "../../../node_modules/codemirror/addon/edit/matchbrackets.js"));else {} -})(function (CodeMirror) { - "use strict"; - - var cmds = CodeMirror.commands; - var Pos = CodeMirror.Pos; - - // This is not exactly Sublime's algorithm. I couldn't make heads or tails of that. - function findPosSubword(doc, start, dir) { - if (dir < 0 && start.ch == 0) return doc.clipPos(Pos(start.line - 1)); - var line = doc.getLine(start.line); - if (dir > 0 && start.ch >= line.length) return doc.clipPos(Pos(start.line + 1, 0)); - var state = "start", - type, - startPos = start.ch; - for (var pos = startPos, e = dir < 0 ? 0 : line.length, i = 0; pos != e; pos += dir, i++) { - var next = line.charAt(dir < 0 ? pos - 1 : pos); - var cat = next != "_" && CodeMirror.isWordChar(next) ? "w" : "o"; - if (cat == "w" && next.toUpperCase() == next) cat = "W"; - if (state == "start") { - if (cat != "o") { - state = "in"; - type = cat; - } else startPos = pos + dir; - } else if (state == "in") { - if (type != cat) { - if (type == "w" && cat == "W" && dir < 0) pos--; - if (type == "W" && cat == "w" && dir > 0) { - // From uppercase to lowercase - if (pos == startPos + 1) { - type = "w"; - continue; - } else pos--; - } - break; - } - } - } - return Pos(start.line, pos); - } - function moveSubword(cm, dir) { - cm.extendSelectionsBy(function (range) { - if (cm.display.shift || cm.doc.extend || range.empty()) return findPosSubword(cm.doc, range.head, dir);else return dir < 0 ? range.from() : range.to(); - }); - } - cmds.goSubwordLeft = function (cm) { - moveSubword(cm, -1); - }; - cmds.goSubwordRight = function (cm) { - moveSubword(cm, 1); - }; - cmds.scrollLineUp = function (cm) { - var info = cm.getScrollInfo(); - if (!cm.somethingSelected()) { - var visibleBottomLine = cm.lineAtHeight(info.top + info.clientHeight, "local"); - if (cm.getCursor().line >= visibleBottomLine) cm.execCommand("goLineUp"); - } - cm.scrollTo(null, info.top - cm.defaultTextHeight()); - }; - cmds.scrollLineDown = function (cm) { - var info = cm.getScrollInfo(); - if (!cm.somethingSelected()) { - var visibleTopLine = cm.lineAtHeight(info.top, "local") + 1; - if (cm.getCursor().line <= visibleTopLine) cm.execCommand("goLineDown"); - } - cm.scrollTo(null, info.top + cm.defaultTextHeight()); - }; - cmds.splitSelectionByLine = function (cm) { - var ranges = cm.listSelections(), - lineRanges = []; - for (var i = 0; i < ranges.length; i++) { - var from = ranges[i].from(), - to = ranges[i].to(); - for (var line = from.line; line <= to.line; ++line) if (!(to.line > from.line && line == to.line && to.ch == 0)) lineRanges.push({ - anchor: line == from.line ? from : Pos(line, 0), - head: line == to.line ? to : Pos(line) - }); - } - cm.setSelections(lineRanges, 0); - }; - cmds.singleSelectionTop = function (cm) { - var range = cm.listSelections()[0]; - cm.setSelection(range.anchor, range.head, { - scroll: false - }); - }; - cmds.selectLine = function (cm) { - var ranges = cm.listSelections(), - extended = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - extended.push({ - anchor: Pos(range.from().line, 0), - head: Pos(range.to().line + 1, 0) - }); - } - cm.setSelections(extended); - }; - function insertLine(cm, above) { - if (cm.isReadOnly()) return CodeMirror.Pass; - cm.operation(function () { - var len = cm.listSelections().length, - newSelection = [], - last = -1; - for (var i = 0; i < len; i++) { - var head = cm.listSelections()[i].head; - if (head.line <= last) continue; - var at = Pos(head.line + (above ? 0 : 1), 0); - cm.replaceRange("\n", at, null, "+insertLine"); - cm.indentLine(at.line, null, true); - newSelection.push({ - head: at, - anchor: at - }); - last = head.line + 1; - } - cm.setSelections(newSelection); - }); - cm.execCommand("indentAuto"); - } - cmds.insertLineAfter = function (cm) { - return insertLine(cm, false); - }; - cmds.insertLineBefore = function (cm) { - return insertLine(cm, true); - }; - function wordAt(cm, pos) { - var start = pos.ch, - end = start, - line = cm.getLine(pos.line); - while (start && CodeMirror.isWordChar(line.charAt(start - 1))) --start; - while (end < line.length && CodeMirror.isWordChar(line.charAt(end))) ++end; - return { - from: Pos(pos.line, start), - to: Pos(pos.line, end), - word: line.slice(start, end) - }; - } - cmds.selectNextOccurrence = function (cm) { - var from = cm.getCursor("from"), - to = cm.getCursor("to"); - var fullWord = cm.state.sublimeFindFullWord == cm.doc.sel; - if (CodeMirror.cmpPos(from, to) == 0) { - var word = wordAt(cm, from); - if (!word.word) return; - cm.setSelection(word.from, word.to); - fullWord = true; - } else { - var text = cm.getRange(from, to); - var query = fullWord ? new RegExp("\\b" + text + "\\b") : text; - var cur = cm.getSearchCursor(query, to); - var found = cur.findNext(); - if (!found) { - cur = cm.getSearchCursor(query, Pos(cm.firstLine(), 0)); - found = cur.findNext(); - } - if (!found || isSelectedRange(cm.listSelections(), cur.from(), cur.to())) return; - cm.addSelection(cur.from(), cur.to()); - } - if (fullWord) cm.state.sublimeFindFullWord = cm.doc.sel; - }; - cmds.skipAndSelectNextOccurrence = function (cm) { - var prevAnchor = cm.getCursor("anchor"), - prevHead = cm.getCursor("head"); - cmds.selectNextOccurrence(cm); - if (CodeMirror.cmpPos(prevAnchor, prevHead) != 0) { - cm.doc.setSelections(cm.doc.listSelections().filter(function (sel) { - return sel.anchor != prevAnchor || sel.head != prevHead; - })); - } - }; - function addCursorToSelection(cm, dir) { - var ranges = cm.listSelections(), - newRanges = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - var newAnchor = cm.findPosV(range.anchor, dir, "line", range.anchor.goalColumn); - var newHead = cm.findPosV(range.head, dir, "line", range.head.goalColumn); - newAnchor.goalColumn = range.anchor.goalColumn != null ? range.anchor.goalColumn : cm.cursorCoords(range.anchor, "div").left; - newHead.goalColumn = range.head.goalColumn != null ? range.head.goalColumn : cm.cursorCoords(range.head, "div").left; - var newRange = { - anchor: newAnchor, - head: newHead - }; - newRanges.push(range); - newRanges.push(newRange); - } - cm.setSelections(newRanges); - } - cmds.addCursorToPrevLine = function (cm) { - addCursorToSelection(cm, -1); - }; - cmds.addCursorToNextLine = function (cm) { - addCursorToSelection(cm, 1); - }; - function isSelectedRange(ranges, from, to) { - for (var i = 0; i < ranges.length; i++) if (CodeMirror.cmpPos(ranges[i].from(), from) == 0 && CodeMirror.cmpPos(ranges[i].to(), to) == 0) return true; - return false; - } - var mirror = "(){}[]"; - function selectBetweenBrackets(cm) { - var ranges = cm.listSelections(), - newRanges = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i], - pos = range.head, - opening = cm.scanForBracket(pos, -1); - if (!opening) return false; - for (;;) { - var closing = cm.scanForBracket(pos, 1); - if (!closing) return false; - if (closing.ch == mirror.charAt(mirror.indexOf(opening.ch) + 1)) { - var startPos = Pos(opening.pos.line, opening.pos.ch + 1); - if (CodeMirror.cmpPos(startPos, range.from()) == 0 && CodeMirror.cmpPos(closing.pos, range.to()) == 0) { - opening = cm.scanForBracket(opening.pos, -1); - if (!opening) return false; - } else { - newRanges.push({ - anchor: startPos, - head: closing.pos - }); - break; - } - } - pos = Pos(closing.pos.line, closing.pos.ch + 1); - } - } - cm.setSelections(newRanges); - return true; - } - cmds.selectScope = function (cm) { - selectBetweenBrackets(cm) || cm.execCommand("selectAll"); - }; - cmds.selectBetweenBrackets = function (cm) { - if (!selectBetweenBrackets(cm)) return CodeMirror.Pass; - }; - function puncType(type) { - return !type ? null : /\bpunctuation\b/.test(type) ? type : undefined; - } - cmds.goToBracket = function (cm) { - cm.extendSelectionsBy(function (range) { - var next = cm.scanForBracket(range.head, 1, puncType(cm.getTokenTypeAt(range.head))); - if (next && CodeMirror.cmpPos(next.pos, range.head) != 0) return next.pos; - var prev = cm.scanForBracket(range.head, -1, puncType(cm.getTokenTypeAt(Pos(range.head.line, range.head.ch + 1)))); - return prev && Pos(prev.pos.line, prev.pos.ch + 1) || range.head; - }); - }; - cmds.swapLineUp = function (cm) { - if (cm.isReadOnly()) return CodeMirror.Pass; - var ranges = cm.listSelections(), - linesToMove = [], - at = cm.firstLine() - 1, - newSels = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i], - from = range.from().line - 1, - to = range.to().line; - newSels.push({ - anchor: Pos(range.anchor.line - 1, range.anchor.ch), - head: Pos(range.head.line - 1, range.head.ch) - }); - if (range.to().ch == 0 && !range.empty()) --to; - if (from > at) linesToMove.push(from, to);else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to; - at = to; - } - cm.operation(function () { - for (var i = 0; i < linesToMove.length; i += 2) { - var from = linesToMove[i], - to = linesToMove[i + 1]; - var line = cm.getLine(from); - cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine"); - if (to > cm.lastLine()) cm.replaceRange("\n" + line, Pos(cm.lastLine()), null, "+swapLine");else cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine"); - } - cm.setSelections(newSels); - cm.scrollIntoView(); - }); - }; - cmds.swapLineDown = function (cm) { - if (cm.isReadOnly()) return CodeMirror.Pass; - var ranges = cm.listSelections(), - linesToMove = [], - at = cm.lastLine() + 1; - for (var i = ranges.length - 1; i >= 0; i--) { - var range = ranges[i], - from = range.to().line + 1, - to = range.from().line; - if (range.to().ch == 0 && !range.empty()) from--; - if (from < at) linesToMove.push(from, to);else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to; - at = to; - } - cm.operation(function () { - for (var i = linesToMove.length - 2; i >= 0; i -= 2) { - var from = linesToMove[i], - to = linesToMove[i + 1]; - var line = cm.getLine(from); - if (from == cm.lastLine()) cm.replaceRange("", Pos(from - 1), Pos(from), "+swapLine");else cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine"); - cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine"); - } - cm.scrollIntoView(); - }); - }; - cmds.toggleCommentIndented = function (cm) { - cm.toggleComment({ - indent: true - }); - }; - cmds.joinLines = function (cm) { - var ranges = cm.listSelections(), - joined = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i], - from = range.from(); - var start = from.line, - end = range.to().line; - while (i < ranges.length - 1 && ranges[i + 1].from().line == end) end = ranges[++i].to().line; - joined.push({ - start: start, - end: end, - anchor: !range.empty() && from - }); - } - cm.operation(function () { - var offset = 0, - ranges = []; - for (var i = 0; i < joined.length; i++) { - var obj = joined[i]; - var anchor = obj.anchor && Pos(obj.anchor.line - offset, obj.anchor.ch), - head; - for (var line = obj.start; line <= obj.end; line++) { - var actual = line - offset; - if (line == obj.end) head = Pos(actual, cm.getLine(actual).length + 1); - if (actual < cm.lastLine()) { - cm.replaceRange(" ", Pos(actual), Pos(actual + 1, /^\s*/.exec(cm.getLine(actual + 1))[0].length)); - ++offset; - } - } - ranges.push({ - anchor: anchor || head, - head: head - }); - } - cm.setSelections(ranges, 0); - }); - }; - cmds.duplicateLine = function (cm) { - cm.operation(function () { - var rangeCount = cm.listSelections().length; - for (var i = 0; i < rangeCount; i++) { - var range = cm.listSelections()[i]; - if (range.empty()) cm.replaceRange(cm.getLine(range.head.line) + "\n", Pos(range.head.line, 0));else cm.replaceRange(cm.getRange(range.from(), range.to()), range.from()); - } - cm.scrollIntoView(); - }); - }; - function sortLines(cm, caseSensitive, direction) { - if (cm.isReadOnly()) return CodeMirror.Pass; - var ranges = cm.listSelections(), - toSort = [], - selected; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - if (range.empty()) continue; - var from = range.from().line, - to = range.to().line; - while (i < ranges.length - 1 && ranges[i + 1].from().line == to) to = ranges[++i].to().line; - if (!ranges[i].to().ch) to--; - toSort.push(from, to); - } - if (toSort.length) selected = true;else toSort.push(cm.firstLine(), cm.lastLine()); - cm.operation(function () { - var ranges = []; - for (var i = 0; i < toSort.length; i += 2) { - var from = toSort[i], - to = toSort[i + 1]; - var start = Pos(from, 0), - end = Pos(to); - var lines = cm.getRange(start, end, false); - if (caseSensitive) lines.sort(function (a, b) { - return a < b ? -direction : a == b ? 0 : direction; - });else lines.sort(function (a, b) { - var au = a.toUpperCase(), - bu = b.toUpperCase(); - if (au != bu) { - a = au; - b = bu; - } - return a < b ? -direction : a == b ? 0 : direction; - }); - cm.replaceRange(lines, start, end); - if (selected) ranges.push({ - anchor: start, - head: Pos(to + 1, 0) - }); - } - if (selected) cm.setSelections(ranges, 0); - }); - } - cmds.sortLines = function (cm) { - sortLines(cm, true, 1); - }; - cmds.reverseSortLines = function (cm) { - sortLines(cm, true, -1); - }; - cmds.sortLinesInsensitive = function (cm) { - sortLines(cm, false, 1); - }; - cmds.reverseSortLinesInsensitive = function (cm) { - sortLines(cm, false, -1); - }; - cmds.nextBookmark = function (cm) { - var marks = cm.state.sublimeBookmarks; - if (marks) while (marks.length) { - var current = marks.shift(); - var found = current.find(); - if (found) { - marks.push(current); - return cm.setSelection(found.from, found.to); - } - } - }; - cmds.prevBookmark = function (cm) { - var marks = cm.state.sublimeBookmarks; - if (marks) while (marks.length) { - marks.unshift(marks.pop()); - var found = marks[marks.length - 1].find(); - if (!found) marks.pop();else return cm.setSelection(found.from, found.to); - } - }; - cmds.toggleBookmark = function (cm) { - var ranges = cm.listSelections(); - var marks = cm.state.sublimeBookmarks || (cm.state.sublimeBookmarks = []); - for (var i = 0; i < ranges.length; i++) { - var from = ranges[i].from(), - to = ranges[i].to(); - var found = ranges[i].empty() ? cm.findMarksAt(from) : cm.findMarks(from, to); - for (var j = 0; j < found.length; j++) { - if (found[j].sublimeBookmark) { - found[j].clear(); - for (var k = 0; k < marks.length; k++) if (marks[k] == found[j]) marks.splice(k--, 1); - break; - } - } - if (j == found.length) marks.push(cm.markText(from, to, { - sublimeBookmark: true, - clearWhenEmpty: false - })); - } - }; - cmds.clearBookmarks = function (cm) { - var marks = cm.state.sublimeBookmarks; - if (marks) for (var i = 0; i < marks.length; i++) marks[i].clear(); - marks.length = 0; - }; - cmds.selectBookmarks = function (cm) { - var marks = cm.state.sublimeBookmarks, - ranges = []; - if (marks) for (var i = 0; i < marks.length; i++) { - var found = marks[i].find(); - if (!found) marks.splice(i--, 0);else ranges.push({ - anchor: found.from, - head: found.to - }); - } - if (ranges.length) cm.setSelections(ranges, 0); - }; - function modifyWordOrSelection(cm, mod) { - cm.operation(function () { - var ranges = cm.listSelections(), - indices = [], - replacements = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - if (range.empty()) { - indices.push(i); - replacements.push(""); - } else replacements.push(mod(cm.getRange(range.from(), range.to()))); - } - cm.replaceSelections(replacements, "around", "case"); - for (var i = indices.length - 1, at; i >= 0; i--) { - var range = ranges[indices[i]]; - if (at && CodeMirror.cmpPos(range.head, at) > 0) continue; - var word = wordAt(cm, range.head); - at = word.from; - cm.replaceRange(mod(word.word), word.from, word.to); - } - }); - } - cmds.smartBackspace = function (cm) { - if (cm.somethingSelected()) return CodeMirror.Pass; - cm.operation(function () { - var cursors = cm.listSelections(); - var indentUnit = cm.getOption("indentUnit"); - for (var i = cursors.length - 1; i >= 0; i--) { - var cursor = cursors[i].head; - var toStartOfLine = cm.getRange({ - line: cursor.line, - ch: 0 - }, cursor); - var column = CodeMirror.countColumn(toStartOfLine, null, cm.getOption("tabSize")); - - // Delete by one character by default - var deletePos = cm.findPosH(cursor, -1, "char", false); - if (toStartOfLine && !/\S/.test(toStartOfLine) && column % indentUnit == 0) { - var prevIndent = new Pos(cursor.line, CodeMirror.findColumn(toStartOfLine, column - indentUnit, indentUnit)); - - // Smart delete only if we found a valid prevIndent location - if (prevIndent.ch != cursor.ch) deletePos = prevIndent; - } - cm.replaceRange("", deletePos, cursor, "+delete"); - } - }); - }; - cmds.delLineRight = function (cm) { - cm.operation(function () { - var ranges = cm.listSelections(); - for (var i = ranges.length - 1; i >= 0; i--) cm.replaceRange("", ranges[i].anchor, Pos(ranges[i].to().line), "+delete"); - cm.scrollIntoView(); - }); - }; - cmds.upcaseAtCursor = function (cm) { - modifyWordOrSelection(cm, function (str) { - return str.toUpperCase(); - }); - }; - cmds.downcaseAtCursor = function (cm) { - modifyWordOrSelection(cm, function (str) { - return str.toLowerCase(); - }); - }; - cmds.setSublimeMark = function (cm) { - if (cm.state.sublimeMark) cm.state.sublimeMark.clear(); - cm.state.sublimeMark = cm.setBookmark(cm.getCursor()); - }; - cmds.selectToSublimeMark = function (cm) { - var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); - if (found) cm.setSelection(cm.getCursor(), found); - }; - cmds.deleteToSublimeMark = function (cm) { - var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); - if (found) { - var from = cm.getCursor(), - to = found; - if (CodeMirror.cmpPos(from, to) > 0) { - var tmp = to; - to = from; - from = tmp; - } - cm.state.sublimeKilled = cm.getRange(from, to); - cm.replaceRange("", from, to); - } - }; - cmds.swapWithSublimeMark = function (cm) { - var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); - if (found) { - cm.state.sublimeMark.clear(); - cm.state.sublimeMark = cm.setBookmark(cm.getCursor()); - cm.setCursor(found); - } - }; - cmds.sublimeYank = function (cm) { - if (cm.state.sublimeKilled != null) cm.replaceSelection(cm.state.sublimeKilled, null, "paste"); - }; - cmds.showInCenter = function (cm) { - var pos = cm.cursorCoords(null, "local"); - cm.scrollTo(null, (pos.top + pos.bottom) / 2 - cm.getScrollInfo().clientHeight / 2); - }; - function getTarget(cm) { - var from = cm.getCursor("from"), - to = cm.getCursor("to"); - if (CodeMirror.cmpPos(from, to) == 0) { - var word = wordAt(cm, from); - if (!word.word) return; - from = word.from; - to = word.to; - } - return { - from: from, - to: to, - query: cm.getRange(from, to), - word: word - }; - } - function findAndGoTo(cm, forward) { - var target = getTarget(cm); - if (!target) return; - var query = target.query; - var cur = cm.getSearchCursor(query, forward ? target.to : target.from); - if (forward ? cur.findNext() : cur.findPrevious()) { - cm.setSelection(cur.from(), cur.to()); - } else { - cur = cm.getSearchCursor(query, forward ? Pos(cm.firstLine(), 0) : cm.clipPos(Pos(cm.lastLine()))); - if (forward ? cur.findNext() : cur.findPrevious()) cm.setSelection(cur.from(), cur.to());else if (target.word) cm.setSelection(target.from, target.to); - } - } - ; - cmds.findUnder = function (cm) { - findAndGoTo(cm, true); - }; - cmds.findUnderPrevious = function (cm) { - findAndGoTo(cm, false); - }; - cmds.findAllUnder = function (cm) { - var target = getTarget(cm); - if (!target) return; - var cur = cm.getSearchCursor(target.query); - var matches = []; - var primaryIndex = -1; - while (cur.findNext()) { - matches.push({ - anchor: cur.from(), - head: cur.to() - }); - if (cur.from().line <= target.from.line && cur.from().ch <= target.from.ch) primaryIndex++; - } - cm.setSelections(matches, primaryIndex); - }; - var keyMap = CodeMirror.keyMap; - keyMap.macSublime = { - "Cmd-Left": "goLineStartSmart", - "Shift-Tab": "indentLess", - "Shift-Ctrl-K": "deleteLine", - "Alt-Q": "wrapLines", - "Ctrl-Left": "goSubwordLeft", - "Ctrl-Right": "goSubwordRight", - "Ctrl-Alt-Up": "scrollLineUp", - "Ctrl-Alt-Down": "scrollLineDown", - "Cmd-L": "selectLine", - "Shift-Cmd-L": "splitSelectionByLine", - "Esc": "singleSelectionTop", - "Cmd-Enter": "insertLineAfter", - "Shift-Cmd-Enter": "insertLineBefore", - "Cmd-D": "selectNextOccurrence", - "Shift-Cmd-Space": "selectScope", - "Shift-Cmd-M": "selectBetweenBrackets", - "Cmd-M": "goToBracket", - "Cmd-Ctrl-Up": "swapLineUp", - "Cmd-Ctrl-Down": "swapLineDown", - "Cmd-/": "toggleCommentIndented", - "Cmd-J": "joinLines", - "Shift-Cmd-D": "duplicateLine", - "F5": "sortLines", - "Shift-F5": "reverseSortLines", - "Cmd-F5": "sortLinesInsensitive", - "Shift-Cmd-F5": "reverseSortLinesInsensitive", - "F2": "nextBookmark", - "Shift-F2": "prevBookmark", - "Cmd-F2": "toggleBookmark", - "Shift-Cmd-F2": "clearBookmarks", - "Alt-F2": "selectBookmarks", - "Backspace": "smartBackspace", - "Cmd-K Cmd-D": "skipAndSelectNextOccurrence", - "Cmd-K Cmd-K": "delLineRight", - "Cmd-K Cmd-U": "upcaseAtCursor", - "Cmd-K Cmd-L": "downcaseAtCursor", - "Cmd-K Cmd-Space": "setSublimeMark", - "Cmd-K Cmd-A": "selectToSublimeMark", - "Cmd-K Cmd-W": "deleteToSublimeMark", - "Cmd-K Cmd-X": "swapWithSublimeMark", - "Cmd-K Cmd-Y": "sublimeYank", - "Cmd-K Cmd-C": "showInCenter", - "Cmd-K Cmd-G": "clearBookmarks", - "Cmd-K Cmd-Backspace": "delLineLeft", - "Cmd-K Cmd-1": "foldAll", - "Cmd-K Cmd-0": "unfoldAll", - "Cmd-K Cmd-J": "unfoldAll", - "Ctrl-Shift-Up": "addCursorToPrevLine", - "Ctrl-Shift-Down": "addCursorToNextLine", - "Cmd-F3": "findUnder", - "Shift-Cmd-F3": "findUnderPrevious", - "Alt-F3": "findAllUnder", - "Shift-Cmd-[": "fold", - "Shift-Cmd-]": "unfold", - "Cmd-I": "findIncremental", - "Shift-Cmd-I": "findIncrementalReverse", - "Cmd-H": "replace", - "F3": "findNext", - "Shift-F3": "findPrev", - "fallthrough": "macDefault" - }; - CodeMirror.normalizeKeyMap(keyMap.macSublime); - keyMap.pcSublime = { - "Shift-Tab": "indentLess", - "Shift-Ctrl-K": "deleteLine", - "Alt-Q": "wrapLines", - "Ctrl-T": "transposeChars", - "Alt-Left": "goSubwordLeft", - "Alt-Right": "goSubwordRight", - "Ctrl-Up": "scrollLineUp", - "Ctrl-Down": "scrollLineDown", - "Ctrl-L": "selectLine", - "Shift-Ctrl-L": "splitSelectionByLine", - "Esc": "singleSelectionTop", - "Ctrl-Enter": "insertLineAfter", - "Shift-Ctrl-Enter": "insertLineBefore", - "Ctrl-D": "selectNextOccurrence", - "Shift-Ctrl-Space": "selectScope", - "Shift-Ctrl-M": "selectBetweenBrackets", - "Ctrl-M": "goToBracket", - "Shift-Ctrl-Up": "swapLineUp", - "Shift-Ctrl-Down": "swapLineDown", - "Ctrl-/": "toggleCommentIndented", - "Ctrl-J": "joinLines", - "Shift-Ctrl-D": "duplicateLine", - "F9": "sortLines", - "Shift-F9": "reverseSortLines", - "Ctrl-F9": "sortLinesInsensitive", - "Shift-Ctrl-F9": "reverseSortLinesInsensitive", - "F2": "nextBookmark", - "Shift-F2": "prevBookmark", - "Ctrl-F2": "toggleBookmark", - "Shift-Ctrl-F2": "clearBookmarks", - "Alt-F2": "selectBookmarks", - "Backspace": "smartBackspace", - "Ctrl-K Ctrl-D": "skipAndSelectNextOccurrence", - "Ctrl-K Ctrl-K": "delLineRight", - "Ctrl-K Ctrl-U": "upcaseAtCursor", - "Ctrl-K Ctrl-L": "downcaseAtCursor", - "Ctrl-K Ctrl-Space": "setSublimeMark", - "Ctrl-K Ctrl-A": "selectToSublimeMark", - "Ctrl-K Ctrl-W": "deleteToSublimeMark", - "Ctrl-K Ctrl-X": "swapWithSublimeMark", - "Ctrl-K Ctrl-Y": "sublimeYank", - "Ctrl-K Ctrl-C": "showInCenter", - "Ctrl-K Ctrl-G": "clearBookmarks", - "Ctrl-K Ctrl-Backspace": "delLineLeft", - "Ctrl-K Ctrl-1": "foldAll", - "Ctrl-K Ctrl-0": "unfoldAll", - "Ctrl-K Ctrl-J": "unfoldAll", - "Ctrl-Alt-Up": "addCursorToPrevLine", - "Ctrl-Alt-Down": "addCursorToNextLine", - "Ctrl-F3": "findUnder", - "Shift-Ctrl-F3": "findUnderPrevious", - "Alt-F3": "findAllUnder", - "Shift-Ctrl-[": "fold", - "Shift-Ctrl-]": "unfold", - "Ctrl-I": "findIncremental", - "Shift-Ctrl-I": "findIncrementalReverse", - "Ctrl-H": "replace", - "F3": "findNext", - "Shift-F3": "findPrev", - "fallthrough": "pcDefault" - }; - CodeMirror.normalizeKeyMap(keyMap.pcSublime); - var mac = keyMap.default == keyMap.macDefault; - keyMap.sublime = mac ? keyMap.macSublime : keyMap.pcSublime; -}); - -/***/ }), - -/***/ "../../../node_modules/codemirror/lib/codemirror.js": -/*!**********************************************************!*\ - !*** ../../../node_modules/codemirror/lib/codemirror.js ***! - \**********************************************************/ -/***/ (function(module) { - -"use strict"; - - -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -// This is CodeMirror (https://codemirror.net), a code editor -// implemented in JavaScript on top of the browser's DOM. -// -// You can find some technical background for some of the code below -// at http://marijnhaverbeke.nl/blog/#cm-internals . - -(function (global, factory) { - true ? module.exports = factory() : 0; -})(void 0, function () { - 'use strict'; - - // Kludges for bugs and behavior differences that can't be feature - // detected are enabled based on userAgent etc sniffing. - var userAgent = navigator.userAgent; - var platform = navigator.platform; - var gecko = /gecko\/\d/i.test(userAgent); - var ie_upto10 = /MSIE \d/.test(userAgent); - var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent); - var edge = /Edge\/(\d+)/.exec(userAgent); - var ie = ie_upto10 || ie_11up || edge; - var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]); - var webkit = !edge && /WebKit\//.test(userAgent); - var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent); - var chrome = !edge && /Chrome\//.test(userAgent); - var presto = /Opera\//.test(userAgent); - var safari = /Apple Computer/.test(navigator.vendor); - var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent); - var phantom = /PhantomJS/.test(userAgent); - var ios = safari && (/Mobile\/\w+/.test(userAgent) || navigator.maxTouchPoints > 2); - var android = /Android/.test(userAgent); - // This is woefully incomplete. Suggestions for alternative methods welcome. - var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent); - var mac = ios || /Mac/.test(platform); - var chromeOS = /\bCrOS\b/.test(userAgent); - var windows = /win/i.test(platform); - var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/); - if (presto_version) { - presto_version = Number(presto_version[1]); - } - if (presto_version && presto_version >= 15) { - presto = false; - webkit = true; - } - // Some browsers use the wrong event properties to signal cmd/ctrl on OS X - var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); - var captureRightClick = gecko || ie && ie_version >= 9; - function classTest(cls) { - return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); - } - var rmClass = function (node, cls) { - var current = node.className; - var match = classTest(cls).exec(current); - if (match) { - var after = current.slice(match.index + match[0].length); - node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); - } - }; - function removeChildren(e) { - for (var count = e.childNodes.length; count > 0; --count) { - e.removeChild(e.firstChild); - } - return e; - } - function removeChildrenAndAdd(parent, e) { - return removeChildren(parent).appendChild(e); - } - function elt(tag, content, className, style) { - var e = document.createElement(tag); - if (className) { - e.className = className; - } - if (style) { - e.style.cssText = style; - } - if (typeof content == "string") { - e.appendChild(document.createTextNode(content)); - } else if (content) { - for (var i = 0; i < content.length; ++i) { - e.appendChild(content[i]); - } - } - return e; - } - // wrapper for elt, which removes the elt from the accessibility tree - function eltP(tag, content, className, style) { - var e = elt(tag, content, className, style); - e.setAttribute("role", "presentation"); - return e; - } - var range; - if (document.createRange) { - range = function (node, start, end, endNode) { - var r = document.createRange(); - r.setEnd(endNode || node, end); - r.setStart(node, start); - return r; - }; - } else { - range = function (node, start, end) { - var r = document.body.createTextRange(); - try { - r.moveToElementText(node.parentNode); - } catch (e) { - return r; - } - r.collapse(true); - r.moveEnd("character", end); - r.moveStart("character", start); - return r; - }; - } - function contains(parent, child) { - if (child.nodeType == 3) - // Android browser always returns false when child is a textnode - { - child = child.parentNode; - } - if (parent.contains) { - return parent.contains(child); - } - do { - if (child.nodeType == 11) { - child = child.host; - } - if (child == parent) { - return true; - } - } while (child = child.parentNode); - } - function activeElt() { - // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement. - // IE < 10 will throw when accessed while the page is loading or in an iframe. - // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable. - var activeElement; - try { - activeElement = document.activeElement; - } catch (e) { - activeElement = document.body || null; - } - while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) { - activeElement = activeElement.shadowRoot.activeElement; - } - return activeElement; - } - function addClass(node, cls) { - var current = node.className; - if (!classTest(cls).test(current)) { - node.className += (current ? " " : "") + cls; - } - } - function joinClasses(a, b) { - var as = a.split(" "); - for (var i = 0; i < as.length; i++) { - if (as[i] && !classTest(as[i]).test(b)) { - b += " " + as[i]; - } - } - return b; - } - var selectInput = function (node) { - node.select(); - }; - if (ios) - // Mobile Safari apparently has a bug where select() is broken. - { - selectInput = function (node) { - node.selectionStart = 0; - node.selectionEnd = node.value.length; - }; - } else if (ie) - // Suppress mysterious IE10 errors - { - selectInput = function (node) { - try { - node.select(); - } catch (_e) {} - }; - } - function bind(f) { - var args = Array.prototype.slice.call(arguments, 1); - return function () { - return f.apply(null, args); - }; - } - function copyObj(obj, target, overwrite) { - if (!target) { - target = {}; - } - for (var prop in obj) { - if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) { - target[prop] = obj[prop]; - } - } - return target; - } - - // Counts the column offset in a string, taking tabs into account. - // Used mostly to find indentation. - function countColumn(string, end, tabSize, startIndex, startValue) { - if (end == null) { - end = string.search(/[^\s\u00a0]/); - if (end == -1) { - end = string.length; - } - } - for (var i = startIndex || 0, n = startValue || 0;;) { - var nextTab = string.indexOf("\t", i); - if (nextTab < 0 || nextTab >= end) { - return n + (end - i); - } - n += nextTab - i; - n += tabSize - n % tabSize; - i = nextTab + 1; - } - } - var Delayed = function () { - this.id = null; - this.f = null; - this.time = 0; - this.handler = bind(this.onTimeout, this); - }; - Delayed.prototype.onTimeout = function (self) { - self.id = 0; - if (self.time <= +new Date()) { - self.f(); - } else { - setTimeout(self.handler, self.time - +new Date()); - } - }; - Delayed.prototype.set = function (ms, f) { - this.f = f; - var time = +new Date() + ms; - if (!this.id || time < this.time) { - clearTimeout(this.id); - this.id = setTimeout(this.handler, ms); - this.time = time; - } - }; - function indexOf(array, elt) { - for (var i = 0; i < array.length; ++i) { - if (array[i] == elt) { - return i; - } - } - return -1; - } - - // Number of pixels added to scroller and sizer to hide scrollbar - var scrollerGap = 50; - - // Returned or thrown by various protocols to signal 'I'm not - // handling this'. - var Pass = { - toString: function () { - return "CodeMirror.Pass"; - } - }; - - // Reused option objects for setSelection & friends - var sel_dontScroll = { - scroll: false - }, - sel_mouse = { - origin: "*mouse" - }, - sel_move = { - origin: "+move" - }; - - // The inverse of countColumn -- find the offset that corresponds to - // a particular column. - function findColumn(string, goal, tabSize) { - for (var pos = 0, col = 0;;) { - var nextTab = string.indexOf("\t", pos); - if (nextTab == -1) { - nextTab = string.length; - } - var skipped = nextTab - pos; - if (nextTab == string.length || col + skipped >= goal) { - return pos + Math.min(skipped, goal - col); - } - col += nextTab - pos; - col += tabSize - col % tabSize; - pos = nextTab + 1; - if (col >= goal) { - return pos; - } - } - } - var spaceStrs = [""]; - function spaceStr(n) { - while (spaceStrs.length <= n) { - spaceStrs.push(lst(spaceStrs) + " "); - } - return spaceStrs[n]; - } - function lst(arr) { - return arr[arr.length - 1]; - } - function map(array, f) { - var out = []; - for (var i = 0; i < array.length; i++) { - out[i] = f(array[i], i); - } - return out; - } - function insertSorted(array, value, score) { - var pos = 0, - priority = score(value); - while (pos < array.length && score(array[pos]) <= priority) { - pos++; - } - array.splice(pos, 0, value); - } - function nothing() {} - function createObj(base, props) { - var inst; - if (Object.create) { - inst = Object.create(base); - } else { - nothing.prototype = base; - inst = new nothing(); - } - if (props) { - copyObj(props, inst); - } - return inst; - } - var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; - function isWordCharBasic(ch) { - return /\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); - } - function isWordChar(ch, helper) { - if (!helper) { - return isWordCharBasic(ch); - } - if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { - return true; - } - return helper.test(ch); - } - function isEmpty(obj) { - for (var n in obj) { - if (obj.hasOwnProperty(n) && obj[n]) { - return false; - } - } - return true; - } - - // Extending unicode characters. A series of a non-extending char + - // any number of extending chars is treated as a single unit as far - // as editing and measuring is concerned. This is not fully correct, - // since some scripts/fonts/browsers also treat other configurations - // of code points as a group. - var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; - function isExtendingChar(ch) { - return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); - } - - // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range. - function skipExtendingChars(str, pos, dir) { - while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { - pos += dir; - } - return pos; - } - - // Returns the value from the range [`from`; `to`] that satisfies - // `pred` and is closest to `from`. Assumes that at least `to` - // satisfies `pred`. Supports `from` being greater than `to`. - function findFirst(pred, from, to) { - // At any point we are certain `to` satisfies `pred`, don't know - // whether `from` does. - var dir = from > to ? -1 : 1; - for (;;) { - if (from == to) { - return from; - } - var midF = (from + to) / 2, - mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF); - if (mid == from) { - return pred(mid) ? from : to; - } - if (pred(mid)) { - to = mid; - } else { - from = mid + dir; - } - } - } - - // BIDI HELPERS - - function iterateBidiSections(order, from, to, f) { - if (!order) { - return f(from, to, "ltr", 0); - } - var found = false; - for (var i = 0; i < order.length; ++i) { - var part = order[i]; - if (part.from < to && part.to > from || from == to && part.to == from) { - f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i); - found = true; - } - } - if (!found) { - f(from, to, "ltr"); - } - } - var bidiOther = null; - function getBidiPartAt(order, ch, sticky) { - var found; - bidiOther = null; - for (var i = 0; i < order.length; ++i) { - var cur = order[i]; - if (cur.from < ch && cur.to > ch) { - return i; - } - if (cur.to == ch) { - if (cur.from != cur.to && sticky == "before") { - found = i; - } else { - bidiOther = i; - } - } - if (cur.from == ch) { - if (cur.from != cur.to && sticky != "before") { - found = i; - } else { - bidiOther = i; - } - } - } - return found != null ? found : bidiOther; - } - - // Bidirectional ordering algorithm - // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm - // that this (partially) implements. - - // One-char codes used for character types: - // L (L): Left-to-Right - // R (R): Right-to-Left - // r (AL): Right-to-Left Arabic - // 1 (EN): European Number - // + (ES): European Number Separator - // % (ET): European Number Terminator - // n (AN): Arabic Number - // , (CS): Common Number Separator - // m (NSM): Non-Spacing Mark - // b (BN): Boundary Neutral - // s (B): Paragraph Separator - // t (S): Segment Separator - // w (WS): Whitespace - // N (ON): Other Neutrals - - // Returns null if characters are ordered as they appear - // (left-to-right), or an array of sections ({from, to, level} - // objects) in the order in which they occur visually. - var bidiOrdering = function () { - // Character types for codepoints 0 to 0xff - var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; - // Character types for codepoints 0x600 to 0x6f9 - var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111"; - function charType(code) { - if (code <= 0xf7) { - return lowTypes.charAt(code); - } else if (0x590 <= code && code <= 0x5f4) { - return "R"; - } else if (0x600 <= code && code <= 0x6f9) { - return arabicTypes.charAt(code - 0x600); - } else if (0x6ee <= code && code <= 0x8ac) { - return "r"; - } else if (0x2000 <= code && code <= 0x200b) { - return "w"; - } else if (code == 0x200c) { - return "b"; - } else { - return "L"; - } - } - var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; - var isNeutral = /[stwN]/, - isStrong = /[LRr]/, - countsAsLeft = /[Lb1n]/, - countsAsNum = /[1n]/; - function BidiSpan(level, from, to) { - this.level = level; - this.from = from; - this.to = to; - } - return function (str, direction) { - var outerType = direction == "ltr" ? "L" : "R"; - if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { - return false; - } - var len = str.length, - types = []; - for (var i = 0; i < len; ++i) { - types.push(charType(str.charCodeAt(i))); - } - - // W1. Examine each non-spacing mark (NSM) in the level run, and - // change the type of the NSM to the type of the previous - // character. If the NSM is at the start of the level run, it will - // get the type of sor. - for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) { - var type = types[i$1]; - if (type == "m") { - types[i$1] = prev; - } else { - prev = type; - } - } - - // W2. Search backwards from each instance of a European number - // until the first strong type (R, L, AL, or sor) is found. If an - // AL is found, change the type of the European number to Arabic - // number. - // W3. Change all ALs to R. - for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) { - var type$1 = types[i$2]; - if (type$1 == "1" && cur == "r") { - types[i$2] = "n"; - } else if (isStrong.test(type$1)) { - cur = type$1; - if (type$1 == "r") { - types[i$2] = "R"; - } - } - } - - // W4. A single European separator between two European numbers - // changes to a European number. A single common separator between - // two numbers of the same type changes to that type. - for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) { - var type$2 = types[i$3]; - if (type$2 == "+" && prev$1 == "1" && types[i$3 + 1] == "1") { - types[i$3] = "1"; - } else if (type$2 == "," && prev$1 == types[i$3 + 1] && (prev$1 == "1" || prev$1 == "n")) { - types[i$3] = prev$1; - } - prev$1 = type$2; - } - - // W5. A sequence of European terminators adjacent to European - // numbers changes to all European numbers. - // W6. Otherwise, separators and terminators change to Other - // Neutral. - for (var i$4 = 0; i$4 < len; ++i$4) { - var type$3 = types[i$4]; - if (type$3 == ",") { - types[i$4] = "N"; - } else if (type$3 == "%") { - var end = void 0; - for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {} - var replace = i$4 && types[i$4 - 1] == "!" || end < len && types[end] == "1" ? "1" : "N"; - for (var j = i$4; j < end; ++j) { - types[j] = replace; - } - i$4 = end - 1; - } - } - - // W7. Search backwards from each instance of a European number - // until the first strong type (R, L, or sor) is found. If an L is - // found, then change the type of the European number to L. - for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) { - var type$4 = types[i$5]; - if (cur$1 == "L" && type$4 == "1") { - types[i$5] = "L"; - } else if (isStrong.test(type$4)) { - cur$1 = type$4; - } - } - - // N1. A sequence of neutrals takes the direction of the - // surrounding strong text if the text on both sides has the same - // direction. European and Arabic numbers act as if they were R in - // terms of their influence on neutrals. Start-of-level-run (sor) - // and end-of-level-run (eor) are used at level run boundaries. - // N2. Any remaining neutrals take the embedding direction. - for (var i$6 = 0; i$6 < len; ++i$6) { - if (isNeutral.test(types[i$6])) { - var end$1 = void 0; - for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {} - var before = (i$6 ? types[i$6 - 1] : outerType) == "L"; - var after = (end$1 < len ? types[end$1] : outerType) == "L"; - var replace$1 = before == after ? before ? "L" : "R" : outerType; - for (var j$1 = i$6; j$1 < end$1; ++j$1) { - types[j$1] = replace$1; - } - i$6 = end$1 - 1; - } - } - - // Here we depart from the documented algorithm, in order to avoid - // building up an actual levels array. Since there are only three - // levels (0, 1, 2) in an implementation that doesn't take - // explicit embedding into account, we can build up the order on - // the fly, without following the level-based algorithm. - var order = [], - m; - for (var i$7 = 0; i$7 < len;) { - if (countsAsLeft.test(types[i$7])) { - var start = i$7; - for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {} - order.push(new BidiSpan(0, start, i$7)); - } else { - var pos = i$7, - at = order.length, - isRTL = direction == "rtl" ? 1 : 0; - for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {} - for (var j$2 = pos; j$2 < i$7;) { - if (countsAsNum.test(types[j$2])) { - if (pos < j$2) { - order.splice(at, 0, new BidiSpan(1, pos, j$2)); - at += isRTL; - } - var nstart = j$2; - for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {} - order.splice(at, 0, new BidiSpan(2, nstart, j$2)); - at += isRTL; - pos = j$2; - } else { - ++j$2; - } - } - if (pos < i$7) { - order.splice(at, 0, new BidiSpan(1, pos, i$7)); - } - } - } - if (direction == "ltr") { - if (order[0].level == 1 && (m = str.match(/^\s+/))) { - order[0].from = m[0].length; - order.unshift(new BidiSpan(0, 0, m[0].length)); - } - if (lst(order).level == 1 && (m = str.match(/\s+$/))) { - lst(order).to -= m[0].length; - order.push(new BidiSpan(0, len - m[0].length, len)); - } - } - return direction == "rtl" ? order.reverse() : order; - }; - }(); - - // Get the bidi ordering for the given line (and cache it). Returns - // false for lines that are fully left-to-right, and an array of - // BidiSpan objects otherwise. - function getOrder(line, direction) { - var order = line.order; - if (order == null) { - order = line.order = bidiOrdering(line.text, direction); - } - return order; - } - - // EVENT HANDLING - - // Lightweight event framework. on/off also work on DOM nodes, - // registering native DOM handlers. - - var noHandlers = []; - var on = function (emitter, type, f) { - if (emitter.addEventListener) { - emitter.addEventListener(type, f, false); - } else if (emitter.attachEvent) { - emitter.attachEvent("on" + type, f); - } else { - var map = emitter._handlers || (emitter._handlers = {}); - map[type] = (map[type] || noHandlers).concat(f); - } - }; - function getHandlers(emitter, type) { - return emitter._handlers && emitter._handlers[type] || noHandlers; - } - function off(emitter, type, f) { - if (emitter.removeEventListener) { - emitter.removeEventListener(type, f, false); - } else if (emitter.detachEvent) { - emitter.detachEvent("on" + type, f); - } else { - var map = emitter._handlers, - arr = map && map[type]; - if (arr) { - var index = indexOf(arr, f); - if (index > -1) { - map[type] = arr.slice(0, index).concat(arr.slice(index + 1)); - } - } - } - } - function signal(emitter, type /*, values...*/) { - var handlers = getHandlers(emitter, type); - if (!handlers.length) { - return; - } - var args = Array.prototype.slice.call(arguments, 2); - for (var i = 0; i < handlers.length; ++i) { - handlers[i].apply(null, args); - } - } - - // The DOM events that CodeMirror handles can be overridden by - // registering a (non-DOM) handler on the editor for the event name, - // and preventDefault-ing the event in that handler. - function signalDOMEvent(cm, e, override) { - if (typeof e == "string") { - e = { - type: e, - preventDefault: function () { - this.defaultPrevented = true; - } - }; - } - signal(cm, override || e.type, cm, e); - return e_defaultPrevented(e) || e.codemirrorIgnore; - } - function signalCursorActivity(cm) { - var arr = cm._handlers && cm._handlers.cursorActivity; - if (!arr) { - return; - } - var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); - for (var i = 0; i < arr.length; ++i) { - if (indexOf(set, arr[i]) == -1) { - set.push(arr[i]); - } - } - } - function hasHandler(emitter, type) { - return getHandlers(emitter, type).length > 0; - } - - // Add on and off methods to a constructor's prototype, to make - // registering events on such objects more convenient. - function eventMixin(ctor) { - ctor.prototype.on = function (type, f) { - on(this, type, f); - }; - ctor.prototype.off = function (type, f) { - off(this, type, f); - }; - } - - // Due to the fact that we still support jurassic IE versions, some - // compatibility wrappers are needed. - - function e_preventDefault(e) { - if (e.preventDefault) { - e.preventDefault(); - } else { - e.returnValue = false; - } - } - function e_stopPropagation(e) { - if (e.stopPropagation) { - e.stopPropagation(); - } else { - e.cancelBubble = true; - } - } - function e_defaultPrevented(e) { - return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false; - } - function e_stop(e) { - e_preventDefault(e); - e_stopPropagation(e); - } - function e_target(e) { - return e.target || e.srcElement; - } - function e_button(e) { - var b = e.which; - if (b == null) { - if (e.button & 1) { - b = 1; - } else if (e.button & 2) { - b = 3; - } else if (e.button & 4) { - b = 2; - } - } - if (mac && e.ctrlKey && b == 1) { - b = 3; - } - return b; - } - - // Detect drag-and-drop - var dragAndDrop = function () { - // There is *some* kind of drag-and-drop support in IE6-8, but I - // couldn't get it to work yet. - if (ie && ie_version < 9) { - return false; - } - var div = elt('div'); - return "draggable" in div || "dragDrop" in div; - }(); - var zwspSupported; - function zeroWidthElement(measure) { - if (zwspSupported == null) { - var test = elt("span", "\u200b"); - removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); - if (measure.firstChild.offsetHeight != 0) { - zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); - } - } - var node = zwspSupported ? elt("span", "\u200b") : elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); - node.setAttribute("cm-text", ""); - return node; - } - - // Feature-detect IE's crummy client rect reporting for bidi text - var badBidiRects; - function hasBadBidiRects(measure) { - if (badBidiRects != null) { - return badBidiRects; - } - var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")); - var r0 = range(txt, 0, 1).getBoundingClientRect(); - var r1 = range(txt, 1, 2).getBoundingClientRect(); - removeChildren(measure); - if (!r0 || r0.left == r0.right) { - return false; - } // Safari returns null in some cases (#2780) - return badBidiRects = r1.right - r0.right < 3; - } - - // See if "".split is the broken IE version, if so, provide an - // alternative way to split lines. - var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) { - var pos = 0, - result = [], - l = string.length; - while (pos <= l) { - var nl = string.indexOf("\n", pos); - if (nl == -1) { - nl = string.length; - } - var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); - var rt = line.indexOf("\r"); - if (rt != -1) { - result.push(line.slice(0, rt)); - pos += rt + 1; - } else { - result.push(line); - pos = nl + 1; - } - } - return result; - } : function (string) { - return string.split(/\r\n?|\n/); - }; - var hasSelection = window.getSelection ? function (te) { - try { - return te.selectionStart != te.selectionEnd; - } catch (e) { - return false; - } - } : function (te) { - var range; - try { - range = te.ownerDocument.selection.createRange(); - } catch (e) {} - if (!range || range.parentElement() != te) { - return false; - } - return range.compareEndPoints("StartToEnd", range) != 0; - }; - var hasCopyEvent = function () { - var e = elt("div"); - if ("oncopy" in e) { - return true; - } - e.setAttribute("oncopy", "return;"); - return typeof e.oncopy == "function"; - }(); - var badZoomedRects = null; - function hasBadZoomedRects(measure) { - if (badZoomedRects != null) { - return badZoomedRects; - } - var node = removeChildrenAndAdd(measure, elt("span", "x")); - var normal = node.getBoundingClientRect(); - var fromRange = range(node, 0, 1).getBoundingClientRect(); - return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1; - } - - // Known modes, by name and by MIME - var modes = {}, - mimeModes = {}; - - // Extra arguments are stored as the mode's dependencies, which is - // used by (legacy) mechanisms like loadmode.js to automatically - // load a mode. (Preferred mechanism is the require/define calls.) - function defineMode(name, mode) { - if (arguments.length > 2) { - mode.dependencies = Array.prototype.slice.call(arguments, 2); - } - modes[name] = mode; - } - function defineMIME(mime, spec) { - mimeModes[mime] = spec; - } - - // Given a MIME type, a {name, ...options} config object, or a name - // string, return a mode config object. - function resolveMode(spec) { - if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { - spec = mimeModes[spec]; - } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { - var found = mimeModes[spec.name]; - if (typeof found == "string") { - found = { - name: found - }; - } - spec = createObj(found, spec); - spec.name = found.name; - } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { - return resolveMode("application/xml"); - } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) { - return resolveMode("application/json"); - } - if (typeof spec == "string") { - return { - name: spec - }; - } else { - return spec || { - name: "null" - }; - } - } - - // Given a mode spec (anything that resolveMode accepts), find and - // initialize an actual mode object. - function getMode(options, spec) { - spec = resolveMode(spec); - var mfactory = modes[spec.name]; - if (!mfactory) { - return getMode(options, "text/plain"); - } - var modeObj = mfactory(options, spec); - if (modeExtensions.hasOwnProperty(spec.name)) { - var exts = modeExtensions[spec.name]; - for (var prop in exts) { - if (!exts.hasOwnProperty(prop)) { - continue; - } - if (modeObj.hasOwnProperty(prop)) { - modeObj["_" + prop] = modeObj[prop]; - } - modeObj[prop] = exts[prop]; - } - } - modeObj.name = spec.name; - if (spec.helperType) { - modeObj.helperType = spec.helperType; - } - if (spec.modeProps) { - for (var prop$1 in spec.modeProps) { - modeObj[prop$1] = spec.modeProps[prop$1]; - } - } - return modeObj; - } - - // This can be used to attach properties to mode objects from - // outside the actual mode definition. - var modeExtensions = {}; - function extendMode(mode, properties) { - var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : modeExtensions[mode] = {}; - copyObj(properties, exts); - } - function copyState(mode, state) { - if (state === true) { - return state; - } - if (mode.copyState) { - return mode.copyState(state); - } - var nstate = {}; - for (var n in state) { - var val = state[n]; - if (val instanceof Array) { - val = val.concat([]); - } - nstate[n] = val; - } - return nstate; - } - - // Given a mode and a state (for that mode), find the inner mode and - // state at the position that the state refers to. - function innerMode(mode, state) { - var info; - while (mode.innerMode) { - info = mode.innerMode(state); - if (!info || info.mode == mode) { - break; - } - state = info.state; - mode = info.mode; - } - return info || { - mode: mode, - state: state - }; - } - function startState(mode, a1, a2) { - return mode.startState ? mode.startState(a1, a2) : true; - } - - // STRING STREAM - - // Fed to the mode parsers, provides helper functions to make - // parsers more succinct. - - var StringStream = function (string, tabSize, lineOracle) { - this.pos = this.start = 0; - this.string = string; - this.tabSize = tabSize || 8; - this.lastColumnPos = this.lastColumnValue = 0; - this.lineStart = 0; - this.lineOracle = lineOracle; - }; - StringStream.prototype.eol = function () { - return this.pos >= this.string.length; - }; - StringStream.prototype.sol = function () { - return this.pos == this.lineStart; - }; - StringStream.prototype.peek = function () { - return this.string.charAt(this.pos) || undefined; - }; - StringStream.prototype.next = function () { - if (this.pos < this.string.length) { - return this.string.charAt(this.pos++); - } - }; - StringStream.prototype.eat = function (match) { - var ch = this.string.charAt(this.pos); - var ok; - if (typeof match == "string") { - ok = ch == match; - } else { - ok = ch && (match.test ? match.test(ch) : match(ch)); - } - if (ok) { - ++this.pos; - return ch; - } - }; - StringStream.prototype.eatWhile = function (match) { - var start = this.pos; - while (this.eat(match)) {} - return this.pos > start; - }; - StringStream.prototype.eatSpace = function () { - var start = this.pos; - while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { - ++this.pos; - } - return this.pos > start; - }; - StringStream.prototype.skipToEnd = function () { - this.pos = this.string.length; - }; - StringStream.prototype.skipTo = function (ch) { - var found = this.string.indexOf(ch, this.pos); - if (found > -1) { - this.pos = found; - return true; - } - }; - StringStream.prototype.backUp = function (n) { - this.pos -= n; - }; - StringStream.prototype.column = function () { - if (this.lastColumnPos < this.start) { - this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); - this.lastColumnPos = this.start; - } - return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); - }; - StringStream.prototype.indentation = function () { - return countColumn(this.string, null, this.tabSize) - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); - }; - StringStream.prototype.match = function (pattern, consume, caseInsensitive) { - if (typeof pattern == "string") { - var cased = function (str) { - return caseInsensitive ? str.toLowerCase() : str; - }; - var substr = this.string.substr(this.pos, pattern.length); - if (cased(substr) == cased(pattern)) { - if (consume !== false) { - this.pos += pattern.length; - } - return true; - } - } else { - var match = this.string.slice(this.pos).match(pattern); - if (match && match.index > 0) { - return null; - } - if (match && consume !== false) { - this.pos += match[0].length; - } - return match; - } - }; - StringStream.prototype.current = function () { - return this.string.slice(this.start, this.pos); - }; - StringStream.prototype.hideFirstChars = function (n, inner) { - this.lineStart += n; - try { - return inner(); - } finally { - this.lineStart -= n; - } - }; - StringStream.prototype.lookAhead = function (n) { - var oracle = this.lineOracle; - return oracle && oracle.lookAhead(n); - }; - StringStream.prototype.baseToken = function () { - var oracle = this.lineOracle; - return oracle && oracle.baseToken(this.pos); - }; - - // Find the line object corresponding to the given line number. - function getLine(doc, n) { - n -= doc.first; - if (n < 0 || n >= doc.size) { - throw new Error("There is no line " + (n + doc.first) + " in the document."); - } - var chunk = doc; - while (!chunk.lines) { - for (var i = 0;; ++i) { - var child = chunk.children[i], - sz = child.chunkSize(); - if (n < sz) { - chunk = child; - break; - } - n -= sz; - } - } - return chunk.lines[n]; - } - - // Get the part of a document between two positions, as an array of - // strings. - function getBetween(doc, start, end) { - var out = [], - n = start.line; - doc.iter(start.line, end.line + 1, function (line) { - var text = line.text; - if (n == end.line) { - text = text.slice(0, end.ch); - } - if (n == start.line) { - text = text.slice(start.ch); - } - out.push(text); - ++n; - }); - return out; - } - // Get the lines between from and to, as array of strings. - function getLines(doc, from, to) { - var out = []; - doc.iter(from, to, function (line) { - out.push(line.text); - }); // iter aborts when callback returns truthy value - return out; - } - - // Update the height of a line, propagating the height change - // upwards to parent nodes. - function updateLineHeight(line, height) { - var diff = height - line.height; - if (diff) { - for (var n = line; n; n = n.parent) { - n.height += diff; - } - } - } - - // Given a line object, find its line number by walking up through - // its parent links. - function lineNo(line) { - if (line.parent == null) { - return null; - } - var cur = line.parent, - no = indexOf(cur.lines, line); - for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { - for (var i = 0;; ++i) { - if (chunk.children[i] == cur) { - break; - } - no += chunk.children[i].chunkSize(); - } - } - return no + cur.first; - } - - // Find the line at the given vertical position, using the height - // information in the document tree. - function lineAtHeight(chunk, h) { - var n = chunk.first; - outer: do { - for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) { - var child = chunk.children[i$1], - ch = child.height; - if (h < ch) { - chunk = child; - continue outer; - } - h -= ch; - n += child.chunkSize(); - } - return n; - } while (!chunk.lines); - var i = 0; - for (; i < chunk.lines.length; ++i) { - var line = chunk.lines[i], - lh = line.height; - if (h < lh) { - break; - } - h -= lh; - } - return n + i; - } - function isLine(doc, l) { - return l >= doc.first && l < doc.first + doc.size; - } - function lineNumberFor(options, i) { - return String(options.lineNumberFormatter(i + options.firstLineNumber)); - } - - // A Pos instance represents a position within the text. - function Pos(line, ch, sticky) { - if (sticky === void 0) sticky = null; - if (!(this instanceof Pos)) { - return new Pos(line, ch, sticky); - } - this.line = line; - this.ch = ch; - this.sticky = sticky; - } - - // Compare two positions, return 0 if they are the same, a negative - // number when a is less, and a positive number otherwise. - function cmp(a, b) { - return a.line - b.line || a.ch - b.ch; - } - function equalCursorPos(a, b) { - return a.sticky == b.sticky && cmp(a, b) == 0; - } - function copyPos(x) { - return Pos(x.line, x.ch); - } - function maxPos(a, b) { - return cmp(a, b) < 0 ? b : a; - } - function minPos(a, b) { - return cmp(a, b) < 0 ? a : b; - } - - // Most of the external API clips given positions to make sure they - // actually exist within the document. - function clipLine(doc, n) { - return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1)); - } - function clipPos(doc, pos) { - if (pos.line < doc.first) { - return Pos(doc.first, 0); - } - var last = doc.first + doc.size - 1; - if (pos.line > last) { - return Pos(last, getLine(doc, last).text.length); - } - return clipToLen(pos, getLine(doc, pos.line).text.length); - } - function clipToLen(pos, linelen) { - var ch = pos.ch; - if (ch == null || ch > linelen) { - return Pos(pos.line, linelen); - } else if (ch < 0) { - return Pos(pos.line, 0); - } else { - return pos; - } - } - function clipPosArray(doc, array) { - var out = []; - for (var i = 0; i < array.length; i++) { - out[i] = clipPos(doc, array[i]); - } - return out; - } - var SavedContext = function (state, lookAhead) { - this.state = state; - this.lookAhead = lookAhead; - }; - var Context = function (doc, state, line, lookAhead) { - this.state = state; - this.doc = doc; - this.line = line; - this.maxLookAhead = lookAhead || 0; - this.baseTokens = null; - this.baseTokenPos = 1; - }; - Context.prototype.lookAhead = function (n) { - var line = this.doc.getLine(this.line + n); - if (line != null && n > this.maxLookAhead) { - this.maxLookAhead = n; - } - return line; - }; - Context.prototype.baseToken = function (n) { - if (!this.baseTokens) { - return null; - } - while (this.baseTokens[this.baseTokenPos] <= n) { - this.baseTokenPos += 2; - } - var type = this.baseTokens[this.baseTokenPos + 1]; - return { - type: type && type.replace(/( |^)overlay .*/, ""), - size: this.baseTokens[this.baseTokenPos] - n - }; - }; - Context.prototype.nextLine = function () { - this.line++; - if (this.maxLookAhead > 0) { - this.maxLookAhead--; - } - }; - Context.fromSaved = function (doc, saved, line) { - if (saved instanceof SavedContext) { - return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead); - } else { - return new Context(doc, copyState(doc.mode, saved), line); - } - }; - Context.prototype.save = function (copy) { - var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state; - return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state; - }; - - // Compute a style array (an array starting with a mode generation - // -- for invalidation -- followed by pairs of end positions and - // style strings), which is used to highlight the tokens on the - // line. - function highlightLine(cm, line, context, forceToEnd) { - // A styles array always starts with a number identifying the - // mode/overlays that it is based on (for easy invalidation). - var st = [cm.state.modeGen], - lineClasses = {}; - // Compute the base array of styles - runMode(cm, line.text, cm.doc.mode, context, function (end, style) { - return st.push(end, style); - }, lineClasses, forceToEnd); - var state = context.state; - - // Run overlays, adjust style array. - var loop = function (o) { - context.baseTokens = st; - var overlay = cm.state.overlays[o], - i = 1, - at = 0; - context.state = true; - runMode(cm, line.text, overlay.mode, context, function (end, style) { - var start = i; - // Ensure there's a token end at the current position, and that i points at it - while (at < end) { - var i_end = st[i]; - if (i_end > end) { - st.splice(i, 1, end, st[i + 1], i_end); - } - i += 2; - at = Math.min(end, i_end); - } - if (!style) { - return; - } - if (overlay.opaque) { - st.splice(start, i - start, end, "overlay " + style); - i = start + 2; - } else { - for (; start < i; start += 2) { - var cur = st[start + 1]; - st[start + 1] = (cur ? cur + " " : "") + "overlay " + style; - } - } - }, lineClasses); - context.state = state; - context.baseTokens = null; - context.baseTokenPos = 1; - }; - for (var o = 0; o < cm.state.overlays.length; ++o) loop(o); - return { - styles: st, - classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null - }; - } - function getLineStyles(cm, line, updateFrontier) { - if (!line.styles || line.styles[0] != cm.state.modeGen) { - var context = getContextBefore(cm, lineNo(line)); - var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state); - var result = highlightLine(cm, line, context); - if (resetState) { - context.state = resetState; - } - line.stateAfter = context.save(!resetState); - line.styles = result.styles; - if (result.classes) { - line.styleClasses = result.classes; - } else if (line.styleClasses) { - line.styleClasses = null; - } - if (updateFrontier === cm.doc.highlightFrontier) { - cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); - } - } - return line.styles; - } - function getContextBefore(cm, n, precise) { - var doc = cm.doc, - display = cm.display; - if (!doc.mode.startState) { - return new Context(doc, true, n); - } - var start = findStartLine(cm, n, precise); - var saved = start > doc.first && getLine(doc, start - 1).stateAfter; - var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start); - doc.iter(start, n, function (line) { - processLine(cm, line.text, context); - var pos = context.line; - line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null; - context.nextLine(); - }); - if (precise) { - doc.modeFrontier = context.line; - } - return context; - } - - // Lightweight form of highlight -- proceed over this line and - // update state, but don't save a style array. Used for lines that - // aren't currently visible. - function processLine(cm, text, context, startAt) { - var mode = cm.doc.mode; - var stream = new StringStream(text, cm.options.tabSize, context); - stream.start = stream.pos = startAt || 0; - if (text == "") { - callBlankLine(mode, context.state); - } - while (!stream.eol()) { - readToken(mode, stream, context.state); - stream.start = stream.pos; - } - } - function callBlankLine(mode, state) { - if (mode.blankLine) { - return mode.blankLine(state); - } - if (!mode.innerMode) { - return; - } - var inner = innerMode(mode, state); - if (inner.mode.blankLine) { - return inner.mode.blankLine(inner.state); - } - } - function readToken(mode, stream, state, inner) { - for (var i = 0; i < 10; i++) { - if (inner) { - inner[0] = innerMode(mode, state).mode; - } - var style = mode.token(stream, state); - if (stream.pos > stream.start) { - return style; - } - } - throw new Error("Mode " + mode.name + " failed to advance stream."); - } - var Token = function (stream, type, state) { - this.start = stream.start; - this.end = stream.pos; - this.string = stream.current(); - this.type = type || null; - this.state = state; - }; - - // Utility for getTokenAt and getLineTokens - function takeToken(cm, pos, precise, asArray) { - var doc = cm.doc, - mode = doc.mode, - style; - pos = clipPos(doc, pos); - var line = getLine(doc, pos.line), - context = getContextBefore(cm, pos.line, precise); - var stream = new StringStream(line.text, cm.options.tabSize, context), - tokens; - if (asArray) { - tokens = []; - } - while ((asArray || stream.pos < pos.ch) && !stream.eol()) { - stream.start = stream.pos; - style = readToken(mode, stream, context.state); - if (asArray) { - tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); - } - } - return asArray ? tokens : new Token(stream, style, context.state); - } - function extractLineClasses(type, output) { - if (type) { - for (;;) { - var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); - if (!lineClass) { - break; - } - type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); - var prop = lineClass[1] ? "bgClass" : "textClass"; - if (output[prop] == null) { - output[prop] = lineClass[2]; - } else if (!new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)").test(output[prop])) { - output[prop] += " " + lineClass[2]; - } - } - } - return type; - } - - // Run the given mode's parser over a line, calling f for each token. - function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) { - var flattenSpans = mode.flattenSpans; - if (flattenSpans == null) { - flattenSpans = cm.options.flattenSpans; - } - var curStart = 0, - curStyle = null; - var stream = new StringStream(text, cm.options.tabSize, context), - style; - var inner = cm.options.addModeClass && [null]; - if (text == "") { - extractLineClasses(callBlankLine(mode, context.state), lineClasses); - } - while (!stream.eol()) { - if (stream.pos > cm.options.maxHighlightLength) { - flattenSpans = false; - if (forceToEnd) { - processLine(cm, text, context, stream.pos); - } - stream.pos = text.length; - style = null; - } else { - style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses); - } - if (inner) { - var mName = inner[0].name; - if (mName) { - style = "m-" + (style ? mName + " " + style : mName); - } - } - if (!flattenSpans || curStyle != style) { - while (curStart < stream.start) { - curStart = Math.min(stream.start, curStart + 5000); - f(curStart, curStyle); - } - curStyle = style; - } - stream.start = stream.pos; - } - while (curStart < stream.pos) { - // Webkit seems to refuse to render text nodes longer than 57444 - // characters, and returns inaccurate measurements in nodes - // starting around 5000 chars. - var pos = Math.min(stream.pos, curStart + 5000); - f(pos, curStyle); - curStart = pos; - } - } - - // Finds the line to start with when starting a parse. Tries to - // find a line with a stateAfter, so that it can start with a - // valid state. If that fails, it returns the line with the - // smallest indentation, which tends to need the least context to - // parse correctly. - function findStartLine(cm, n, precise) { - var minindent, - minline, - doc = cm.doc; - var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); - for (var search = n; search > lim; --search) { - if (search <= doc.first) { - return doc.first; - } - var line = getLine(doc, search - 1), - after = line.stateAfter; - if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier)) { - return search; - } - var indented = countColumn(line.text, null, cm.options.tabSize); - if (minline == null || minindent > indented) { - minline = search - 1; - minindent = indented; - } - } - return minline; - } - function retreatFrontier(doc, n) { - doc.modeFrontier = Math.min(doc.modeFrontier, n); - if (doc.highlightFrontier < n - 10) { - return; - } - var start = doc.first; - for (var line = n - 1; line > start; line--) { - var saved = getLine(doc, line).stateAfter; - // change is on 3 - // state on line 1 looked ahead 2 -- so saw 3 - // test 1 + 2 < 3 should cover this - if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) { - start = line + 1; - break; - } - } - doc.highlightFrontier = Math.min(doc.highlightFrontier, start); - } - - // Optimize some code when these features are not used. - var sawReadOnlySpans = false, - sawCollapsedSpans = false; - function seeReadOnlySpans() { - sawReadOnlySpans = true; - } - function seeCollapsedSpans() { - sawCollapsedSpans = true; - } - - // TEXTMARKER SPANS - - function MarkedSpan(marker, from, to) { - this.marker = marker; - this.from = from; - this.to = to; - } - - // Search an array of spans for a span matching the given marker. - function getMarkedSpanFor(spans, marker) { - if (spans) { - for (var i = 0; i < spans.length; ++i) { - var span = spans[i]; - if (span.marker == marker) { - return span; - } - } - } - } - - // Remove a span from an array, returning undefined if no spans are - // left (we don't store arrays for lines without spans). - function removeMarkedSpan(spans, span) { - var r; - for (var i = 0; i < spans.length; ++i) { - if (spans[i] != span) { - (r || (r = [])).push(spans[i]); - } - } - return r; - } - - // Add a span to a line. - function addMarkedSpan(line, span, op) { - var inThisOp = op && window.WeakSet && (op.markedSpans || (op.markedSpans = new WeakSet())); - if (inThisOp && line.markedSpans && inThisOp.has(line.markedSpans)) { - line.markedSpans.push(span); - } else { - line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; - if (inThisOp) { - inThisOp.add(line.markedSpans); - } - } - span.marker.attachLine(line); - } - - // Used for the algorithm that adjusts markers for a change in the - // document. These functions cut an array of spans at a given - // character position, returning an array of remaining chunks (or - // undefined if nothing remains). - function markedSpansBefore(old, startCh, isInsert) { - var nw; - if (old) { - for (var i = 0; i < old.length; ++i) { - var span = old[i], - marker = span.marker; - var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); - if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { - var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); - (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); - } - } - } - return nw; - } - function markedSpansAfter(old, endCh, isInsert) { - var nw; - if (old) { - for (var i = 0; i < old.length; ++i) { - var span = old[i], - marker = span.marker; - var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); - if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { - var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); - (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, span.to == null ? null : span.to - endCh)); - } - } - } - return nw; - } - - // Given a change object, compute the new set of marker spans that - // cover the line in which the change took place. Removes spans - // entirely within the change, reconnects spans belonging to the - // same marker that appear on both sides of the change, and cuts off - // spans partially within the change. Returns an array of span - // arrays with one element for each line in (after) the change. - function stretchSpansOverChange(doc, change) { - if (change.full) { - return null; - } - var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; - var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; - if (!oldFirst && !oldLast) { - return null; - } - var startCh = change.from.ch, - endCh = change.to.ch, - isInsert = cmp(change.from, change.to) == 0; - // Get the spans that 'stick out' on both sides - var first = markedSpansBefore(oldFirst, startCh, isInsert); - var last = markedSpansAfter(oldLast, endCh, isInsert); - - // Next, merge those two ends - var sameLine = change.text.length == 1, - offset = lst(change.text).length + (sameLine ? startCh : 0); - if (first) { - // Fix up .to properties of first - for (var i = 0; i < first.length; ++i) { - var span = first[i]; - if (span.to == null) { - var found = getMarkedSpanFor(last, span.marker); - if (!found) { - span.to = startCh; - } else if (sameLine) { - span.to = found.to == null ? null : found.to + offset; - } - } - } - } - if (last) { - // Fix up .from in last (or move them into first in case of sameLine) - for (var i$1 = 0; i$1 < last.length; ++i$1) { - var span$1 = last[i$1]; - if (span$1.to != null) { - span$1.to += offset; - } - if (span$1.from == null) { - var found$1 = getMarkedSpanFor(first, span$1.marker); - if (!found$1) { - span$1.from = offset; - if (sameLine) { - (first || (first = [])).push(span$1); - } - } - } else { - span$1.from += offset; - if (sameLine) { - (first || (first = [])).push(span$1); - } - } - } - } - // Make sure we didn't create any zero-length spans - if (first) { - first = clearEmptySpans(first); - } - if (last && last != first) { - last = clearEmptySpans(last); - } - var newMarkers = [first]; - if (!sameLine) { - // Fill gap with whole-line-spans - var gap = change.text.length - 2, - gapMarkers; - if (gap > 0 && first) { - for (var i$2 = 0; i$2 < first.length; ++i$2) { - if (first[i$2].to == null) { - (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); - } - } - } - for (var i$3 = 0; i$3 < gap; ++i$3) { - newMarkers.push(gapMarkers); - } - newMarkers.push(last); - } - return newMarkers; - } - - // Remove spans that are empty and don't have a clearWhenEmpty - // option of false. - function clearEmptySpans(spans) { - for (var i = 0; i < spans.length; ++i) { - var span = spans[i]; - if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) { - spans.splice(i--, 1); - } - } - if (!spans.length) { - return null; - } - return spans; - } - - // Used to 'clip' out readOnly ranges when making a change. - function removeReadOnlyRanges(doc, from, to) { - var markers = null; - doc.iter(from.line, to.line + 1, function (line) { - if (line.markedSpans) { - for (var i = 0; i < line.markedSpans.length; ++i) { - var mark = line.markedSpans[i].marker; - if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) { - (markers || (markers = [])).push(mark); - } - } - } - }); - if (!markers) { - return null; - } - var parts = [{ - from: from, - to: to - }]; - for (var i = 0; i < markers.length; ++i) { - var mk = markers[i], - m = mk.find(0); - for (var j = 0; j < parts.length; ++j) { - var p = parts[j]; - if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { - continue; - } - var newParts = [j, 1], - dfrom = cmp(p.from, m.from), - dto = cmp(p.to, m.to); - if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) { - newParts.push({ - from: p.from, - to: m.from - }); - } - if (dto > 0 || !mk.inclusiveRight && !dto) { - newParts.push({ - from: m.to, - to: p.to - }); - } - parts.splice.apply(parts, newParts); - j += newParts.length - 3; - } - } - return parts; - } - - // Connect or disconnect spans from a line. - function detachMarkedSpans(line) { - var spans = line.markedSpans; - if (!spans) { - return; - } - for (var i = 0; i < spans.length; ++i) { - spans[i].marker.detachLine(line); - } - line.markedSpans = null; - } - function attachMarkedSpans(line, spans) { - if (!spans) { - return; - } - for (var i = 0; i < spans.length; ++i) { - spans[i].marker.attachLine(line); - } - line.markedSpans = spans; - } - - // Helpers used when computing which overlapping collapsed span - // counts as the larger one. - function extraLeft(marker) { - return marker.inclusiveLeft ? -1 : 0; - } - function extraRight(marker) { - return marker.inclusiveRight ? 1 : 0; - } - - // Returns a number indicating which of two overlapping collapsed - // spans is larger (and thus includes the other). Falls back to - // comparing ids when the spans cover exactly the same range. - function compareCollapsedMarkers(a, b) { - var lenDiff = a.lines.length - b.lines.length; - if (lenDiff != 0) { - return lenDiff; - } - var aPos = a.find(), - bPos = b.find(); - var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); - if (fromCmp) { - return -fromCmp; - } - var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); - if (toCmp) { - return toCmp; - } - return b.id - a.id; - } - - // Find out whether a line ends or starts in a collapsed span. If - // so, return the marker for that span. - function collapsedSpanAtSide(line, start) { - var sps = sawCollapsedSpans && line.markedSpans, - found; - if (sps) { - for (var sp = void 0, i = 0; i < sps.length; ++i) { - sp = sps[i]; - if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { - found = sp.marker; - } - } - } - return found; - } - function collapsedSpanAtStart(line) { - return collapsedSpanAtSide(line, true); - } - function collapsedSpanAtEnd(line) { - return collapsedSpanAtSide(line, false); - } - function collapsedSpanAround(line, ch) { - var sps = sawCollapsedSpans && line.markedSpans, - found; - if (sps) { - for (var i = 0; i < sps.length; ++i) { - var sp = sps[i]; - if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { - found = sp.marker; - } - } - } - return found; - } - - // Test whether there exists a collapsed span that partially - // overlaps (covers the start or end, but not both) of a new span. - // Such overlap is not allowed. - function conflictingCollapsedRange(doc, lineNo, from, to, marker) { - var line = getLine(doc, lineNo); - var sps = sawCollapsedSpans && line.markedSpans; - if (sps) { - for (var i = 0; i < sps.length; ++i) { - var sp = sps[i]; - if (!sp.marker.collapsed) { - continue; - } - var found = sp.marker.find(0); - var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); - var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); - if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { - continue; - } - if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) { - return true; - } - } - } - } - - // A visual line is a line as drawn on the screen. Folding, for - // example, can cause multiple logical lines to appear on the same - // visual line. This finds the start of the visual line that the - // given line is part of (usually that is the line itself). - function visualLine(line) { - var merged; - while (merged = collapsedSpanAtStart(line)) { - line = merged.find(-1, true).line; - } - return line; - } - function visualLineEnd(line) { - var merged; - while (merged = collapsedSpanAtEnd(line)) { - line = merged.find(1, true).line; - } - return line; - } - - // Returns an array of logical lines that continue the visual line - // started by the argument, or undefined if there are no such lines. - function visualLineContinued(line) { - var merged, lines; - while (merged = collapsedSpanAtEnd(line)) { - line = merged.find(1, true).line; - (lines || (lines = [])).push(line); - } - return lines; - } - - // Get the line number of the start of the visual line that the - // given line number is part of. - function visualLineNo(doc, lineN) { - var line = getLine(doc, lineN), - vis = visualLine(line); - if (line == vis) { - return lineN; - } - return lineNo(vis); - } - - // Get the line number of the start of the next visual line after - // the given line. - function visualLineEndNo(doc, lineN) { - if (lineN > doc.lastLine()) { - return lineN; - } - var line = getLine(doc, lineN), - merged; - if (!lineIsHidden(doc, line)) { - return lineN; - } - while (merged = collapsedSpanAtEnd(line)) { - line = merged.find(1, true).line; - } - return lineNo(line) + 1; - } - - // Compute whether a line is hidden. Lines count as hidden when they - // are part of a visual line that starts with another line, or when - // they are entirely covered by collapsed, non-widget span. - function lineIsHidden(doc, line) { - var sps = sawCollapsedSpans && line.markedSpans; - if (sps) { - for (var sp = void 0, i = 0; i < sps.length; ++i) { - sp = sps[i]; - if (!sp.marker.collapsed) { - continue; - } - if (sp.from == null) { - return true; - } - if (sp.marker.widgetNode) { - continue; - } - if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) { - return true; - } - } - } - } - function lineIsHiddenInner(doc, line, span) { - if (span.to == null) { - var end = span.marker.find(1, true); - return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)); - } - if (span.marker.inclusiveRight && span.to == line.text.length) { - return true; - } - for (var sp = void 0, i = 0; i < line.markedSpans.length; ++i) { - sp = line.markedSpans[i]; - if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && (sp.to == null || sp.to != span.from) && (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && lineIsHiddenInner(doc, line, sp)) { - return true; - } - } - } - - // Find the height above the given line. - function heightAtLine(lineObj) { - lineObj = visualLine(lineObj); - var h = 0, - chunk = lineObj.parent; - for (var i = 0; i < chunk.lines.length; ++i) { - var line = chunk.lines[i]; - if (line == lineObj) { - break; - } else { - h += line.height; - } - } - for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { - for (var i$1 = 0; i$1 < p.children.length; ++i$1) { - var cur = p.children[i$1]; - if (cur == chunk) { - break; - } else { - h += cur.height; - } - } - } - return h; - } - - // Compute the character length of a line, taking into account - // collapsed ranges (see markText) that might hide parts, and join - // other lines onto it. - function lineLength(line) { - if (line.height == 0) { - return 0; - } - var len = line.text.length, - merged, - cur = line; - while (merged = collapsedSpanAtStart(cur)) { - var found = merged.find(0, true); - cur = found.from.line; - len += found.from.ch - found.to.ch; - } - cur = line; - while (merged = collapsedSpanAtEnd(cur)) { - var found$1 = merged.find(0, true); - len -= cur.text.length - found$1.from.ch; - cur = found$1.to.line; - len += cur.text.length - found$1.to.ch; - } - return len; - } - - // Find the longest line in the document. - function findMaxLine(cm) { - var d = cm.display, - doc = cm.doc; - d.maxLine = getLine(doc, doc.first); - d.maxLineLength = lineLength(d.maxLine); - d.maxLineChanged = true; - doc.iter(function (line) { - var len = lineLength(line); - if (len > d.maxLineLength) { - d.maxLineLength = len; - d.maxLine = line; - } - }); - } - - // LINE DATA STRUCTURE - - // Line objects. These hold state related to a line, including - // highlighting info (the styles array). - var Line = function (text, markedSpans, estimateHeight) { - this.text = text; - attachMarkedSpans(this, markedSpans); - this.height = estimateHeight ? estimateHeight(this) : 1; - }; - Line.prototype.lineNo = function () { - return lineNo(this); - }; - eventMixin(Line); - - // Change the content (text, markers) of a line. Automatically - // invalidates cached information and tries to re-estimate the - // line's height. - function updateLine(line, text, markedSpans, estimateHeight) { - line.text = text; - if (line.stateAfter) { - line.stateAfter = null; - } - if (line.styles) { - line.styles = null; - } - if (line.order != null) { - line.order = null; - } - detachMarkedSpans(line); - attachMarkedSpans(line, markedSpans); - var estHeight = estimateHeight ? estimateHeight(line) : 1; - if (estHeight != line.height) { - updateLineHeight(line, estHeight); - } - } - - // Detach a line from the document tree and its markers. - function cleanUpLine(line) { - line.parent = null; - detachMarkedSpans(line); - } - - // Convert a style as returned by a mode (either null, or a string - // containing one or more styles) to a CSS style. This is cached, - // and also looks for line-wide styles. - var styleToClassCache = {}, - styleToClassCacheWithMode = {}; - function interpretTokenStyle(style, options) { - if (!style || /^\s*$/.test(style)) { - return null; - } - var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; - return cache[style] || (cache[style] = style.replace(/\S+/g, "cm-$&")); - } - - // Render the DOM representation of the text of a line. Also builds - // up a 'line map', which points at the DOM nodes that represent - // specific stretches of text, and is used by the measuring code. - // The returned object contains the DOM node, this map, and - // information about line-wide styles that were set by the mode. - function buildLineContent(cm, lineView) { - // The padding-right forces the element to have a 'border', which - // is needed on Webkit to be able to get line-level bounding - // rectangles for it (in measureChar). - var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null); - var builder = { - pre: eltP("pre", [content], "CodeMirror-line"), - content: content, - col: 0, - pos: 0, - cm: cm, - trailingSpace: false, - splitSpaces: cm.getOption("lineWrapping") - }; - lineView.measure = {}; - - // Iterate over the logical lines that make up this visual line. - for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { - var line = i ? lineView.rest[i - 1] : lineView.line, - order = void 0; - builder.pos = 0; - builder.addToken = buildToken; - // Optionally wire in some hacks into the token-rendering - // algorithm, to deal with browser quirks. - if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction))) { - builder.addToken = buildTokenBadBidi(builder.addToken, order); - } - builder.map = []; - var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); - insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); - if (line.styleClasses) { - if (line.styleClasses.bgClass) { - builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); - } - if (line.styleClasses.textClass) { - builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); - } - } - - // Ensure at least a single node is present, for measuring. - if (builder.map.length == 0) { - builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); - } - - // Store the map and a cache object for the current logical line - if (i == 0) { - lineView.measure.map = builder.map; - lineView.measure.cache = {}; - } else { - (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map); - (lineView.measure.caches || (lineView.measure.caches = [])).push({}); - } - } - - // See issue #2901 - if (webkit) { - var last = builder.content.lastChild; - if (/\bcm-tab\b/.test(last.className) || last.querySelector && last.querySelector(".cm-tab")) { - builder.content.className = "cm-tab-wrap-hack"; - } - } - signal(cm, "renderLine", cm, lineView.line, builder.pre); - if (builder.pre.className) { - builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); - } - return builder; - } - function defaultSpecialCharPlaceholder(ch) { - var token = elt("span", "\u2022", "cm-invalidchar"); - token.title = "\\u" + ch.charCodeAt(0).toString(16); - token.setAttribute("aria-label", token.title); - return token; - } - - // Build up the DOM representation for a single token, and add it to - // the line map. Takes care to render special characters separately. - function buildToken(builder, text, style, startStyle, endStyle, css, attributes) { - if (!text) { - return; - } - var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text; - var special = builder.cm.state.specialChars, - mustWrap = false; - var content; - if (!special.test(text)) { - builder.col += text.length; - content = document.createTextNode(displayText); - builder.map.push(builder.pos, builder.pos + text.length, content); - if (ie && ie_version < 9) { - mustWrap = true; - } - builder.pos += text.length; - } else { - content = document.createDocumentFragment(); - var pos = 0; - while (true) { - special.lastIndex = pos; - var m = special.exec(text); - var skipped = m ? m.index - pos : text.length - pos; - if (skipped) { - var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); - if (ie && ie_version < 9) { - content.appendChild(elt("span", [txt])); - } else { - content.appendChild(txt); - } - builder.map.push(builder.pos, builder.pos + skipped, txt); - builder.col += skipped; - builder.pos += skipped; - } - if (!m) { - break; - } - pos += skipped + 1; - var txt$1 = void 0; - if (m[0] == "\t") { - var tabSize = builder.cm.options.tabSize, - tabWidth = tabSize - builder.col % tabSize; - txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); - txt$1.setAttribute("role", "presentation"); - txt$1.setAttribute("cm-text", "\t"); - builder.col += tabWidth; - } else if (m[0] == "\r" || m[0] == "\n") { - txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar")); - txt$1.setAttribute("cm-text", m[0]); - builder.col += 1; - } else { - txt$1 = builder.cm.options.specialCharPlaceholder(m[0]); - txt$1.setAttribute("cm-text", m[0]); - if (ie && ie_version < 9) { - content.appendChild(elt("span", [txt$1])); - } else { - content.appendChild(txt$1); - } - builder.col += 1; - } - builder.map.push(builder.pos, builder.pos + 1, txt$1); - builder.pos++; - } - } - builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32; - if (style || startStyle || endStyle || mustWrap || css || attributes) { - var fullStyle = style || ""; - if (startStyle) { - fullStyle += startStyle; - } - if (endStyle) { - fullStyle += endStyle; - } - var token = elt("span", [content], fullStyle, css); - if (attributes) { - for (var attr in attributes) { - if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class") { - token.setAttribute(attr, attributes[attr]); - } - } - } - return builder.content.appendChild(token); - } - builder.content.appendChild(content); - } - - // Change some spaces to NBSP to prevent the browser from collapsing - // trailing spaces at the end of a line when rendering text (issue #1362). - function splitSpaces(text, trailingBefore) { - if (text.length > 1 && !/ /.test(text)) { - return text; - } - var spaceBefore = trailingBefore, - result = ""; - for (var i = 0; i < text.length; i++) { - var ch = text.charAt(i); - if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32)) { - ch = "\u00a0"; - } - result += ch; - spaceBefore = ch == " "; - } - return result; - } - - // Work around nonsense dimensions being reported for stretches of - // right-to-left text. - function buildTokenBadBidi(inner, order) { - return function (builder, text, style, startStyle, endStyle, css, attributes) { - style = style ? style + " cm-force-border" : "cm-force-border"; - var start = builder.pos, - end = start + text.length; - for (;;) { - // Find the part that overlaps with the start of this text - var part = void 0; - for (var i = 0; i < order.length; i++) { - part = order[i]; - if (part.to > start && part.from <= start) { - break; - } - } - if (part.to >= end) { - return inner(builder, text, style, startStyle, endStyle, css, attributes); - } - inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes); - startStyle = null; - text = text.slice(part.to - start); - start = part.to; - } - }; - } - function buildCollapsedSpan(builder, size, marker, ignoreWidget) { - var widget = !ignoreWidget && marker.widgetNode; - if (widget) { - builder.map.push(builder.pos, builder.pos + size, widget); - } - if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { - if (!widget) { - widget = builder.content.appendChild(document.createElement("span")); - } - widget.setAttribute("cm-marker", marker.id); - } - if (widget) { - builder.cm.display.input.setUneditable(widget); - builder.content.appendChild(widget); - } - builder.pos += size; - builder.trailingSpace = false; - } - - // Outputs a number of spans to make up a line, taking highlighting - // and marked text into account. - function insertLineContent(line, builder, styles) { - var spans = line.markedSpans, - allText = line.text, - at = 0; - if (!spans) { - for (var i$1 = 1; i$1 < styles.length; i$1 += 2) { - builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1 + 1], builder.cm.options)); - } - return; - } - var len = allText.length, - pos = 0, - i = 1, - text = "", - style, - css; - var nextChange = 0, - spanStyle, - spanEndStyle, - spanStartStyle, - collapsed, - attributes; - for (;;) { - if (nextChange == pos) { - // Update current marker set - spanStyle = spanEndStyle = spanStartStyle = css = ""; - attributes = null; - collapsed = null; - nextChange = Infinity; - var foundBookmarks = [], - endStyles = void 0; - for (var j = 0; j < spans.length; ++j) { - var sp = spans[j], - m = sp.marker; - if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { - foundBookmarks.push(m); - } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { - if (sp.to != null && sp.to != pos && nextChange > sp.to) { - nextChange = sp.to; - spanEndStyle = ""; - } - if (m.className) { - spanStyle += " " + m.className; - } - if (m.css) { - css = (css ? css + ";" : "") + m.css; - } - if (m.startStyle && sp.from == pos) { - spanStartStyle += " " + m.startStyle; - } - if (m.endStyle && sp.to == nextChange) { - (endStyles || (endStyles = [])).push(m.endStyle, sp.to); - } - // support for the old title property - // https://github.com/codemirror/CodeMirror/pull/5673 - if (m.title) { - (attributes || (attributes = {})).title = m.title; - } - if (m.attributes) { - for (var attr in m.attributes) { - (attributes || (attributes = {}))[attr] = m.attributes[attr]; - } - } - if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) { - collapsed = sp; - } - } else if (sp.from > pos && nextChange > sp.from) { - nextChange = sp.from; - } - } - if (endStyles) { - for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) { - if (endStyles[j$1 + 1] == nextChange) { - spanEndStyle += " " + endStyles[j$1]; - } - } - } - if (!collapsed || collapsed.from == pos) { - for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2) { - buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); - } - } - if (collapsed && (collapsed.from || 0) == pos) { - buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, collapsed.marker, collapsed.from == null); - if (collapsed.to == null) { - return; - } - if (collapsed.to == pos) { - collapsed = false; - } - } - } - if (pos >= len) { - break; - } - var upto = Math.min(len, nextChange); - while (true) { - if (text) { - var end = pos + text.length; - if (!collapsed) { - var tokenText = end > upto ? text.slice(0, upto - pos) : text; - builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes); - } - if (end >= upto) { - text = text.slice(upto - pos); - pos = upto; - break; - } - pos = end; - spanStartStyle = ""; - } - text = allText.slice(at, at = styles[i++]); - style = interpretTokenStyle(styles[i++], builder.cm.options); - } - } - } - - // These objects are used to represent the visible (currently drawn) - // part of the document. A LineView may correspond to multiple - // logical lines, if those are connected by collapsed ranges. - function LineView(doc, line, lineN) { - // The starting line - this.line = line; - // Continuing lines, if any - this.rest = visualLineContinued(line); - // Number of logical lines in this visual line - this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; - this.node = this.text = null; - this.hidden = lineIsHidden(doc, line); - } - - // Create a range of LineView objects for the given lines. - function buildViewArray(cm, from, to) { - var array = [], - nextPos; - for (var pos = from; pos < to; pos = nextPos) { - var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); - nextPos = pos + view.size; - array.push(view); - } - return array; - } - var operationGroup = null; - function pushOperation(op) { - if (operationGroup) { - operationGroup.ops.push(op); - } else { - op.ownsGroup = operationGroup = { - ops: [op], - delayedCallbacks: [] - }; - } - } - function fireCallbacksForOps(group) { - // Calls delayed callbacks and cursorActivity handlers until no - // new ones appear - var callbacks = group.delayedCallbacks, - i = 0; - do { - for (; i < callbacks.length; i++) { - callbacks[i].call(null); - } - for (var j = 0; j < group.ops.length; j++) { - var op = group.ops[j]; - if (op.cursorActivityHandlers) { - while (op.cursorActivityCalled < op.cursorActivityHandlers.length) { - op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); - } - } - } - } while (i < callbacks.length); - } - function finishOperation(op, endCb) { - var group = op.ownsGroup; - if (!group) { - return; - } - try { - fireCallbacksForOps(group); - } finally { - operationGroup = null; - endCb(group); - } - } - var orphanDelayedCallbacks = null; - - // Often, we want to signal events at a point where we are in the - // middle of some work, but don't want the handler to start calling - // other methods on the editor, which might be in an inconsistent - // state or simply not expect any other events to happen. - // signalLater looks whether there are any handlers, and schedules - // them to be executed when the last operation ends, or, if no - // operation is active, when a timeout fires. - function signalLater(emitter, type /*, values...*/) { - var arr = getHandlers(emitter, type); - if (!arr.length) { - return; - } - var args = Array.prototype.slice.call(arguments, 2), - list; - if (operationGroup) { - list = operationGroup.delayedCallbacks; - } else if (orphanDelayedCallbacks) { - list = orphanDelayedCallbacks; - } else { - list = orphanDelayedCallbacks = []; - setTimeout(fireOrphanDelayed, 0); - } - var loop = function (i) { - list.push(function () { - return arr[i].apply(null, args); - }); - }; - for (var i = 0; i < arr.length; ++i) loop(i); - } - function fireOrphanDelayed() { - var delayed = orphanDelayedCallbacks; - orphanDelayedCallbacks = null; - for (var i = 0; i < delayed.length; ++i) { - delayed[i](); - } - } - - // When an aspect of a line changes, a string is added to - // lineView.changes. This updates the relevant part of the line's - // DOM structure. - function updateLineForChanges(cm, lineView, lineN, dims) { - for (var j = 0; j < lineView.changes.length; j++) { - var type = lineView.changes[j]; - if (type == "text") { - updateLineText(cm, lineView); - } else if (type == "gutter") { - updateLineGutter(cm, lineView, lineN, dims); - } else if (type == "class") { - updateLineClasses(cm, lineView); - } else if (type == "widget") { - updateLineWidgets(cm, lineView, dims); - } - } - lineView.changes = null; - } - - // Lines with gutter elements, widgets or a background class need to - // be wrapped, and have the extra elements added to the wrapper div - function ensureLineWrapped(lineView) { - if (lineView.node == lineView.text) { - lineView.node = elt("div", null, null, "position: relative"); - if (lineView.text.parentNode) { - lineView.text.parentNode.replaceChild(lineView.node, lineView.text); - } - lineView.node.appendChild(lineView.text); - if (ie && ie_version < 8) { - lineView.node.style.zIndex = 2; - } - } - return lineView.node; - } - function updateLineBackground(cm, lineView) { - var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; - if (cls) { - cls += " CodeMirror-linebackground"; - } - if (lineView.background) { - if (cls) { - lineView.background.className = cls; - } else { - lineView.background.parentNode.removeChild(lineView.background); - lineView.background = null; - } - } else if (cls) { - var wrap = ensureLineWrapped(lineView); - lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); - cm.display.input.setUneditable(lineView.background); - } - } - - // Wrapper around buildLineContent which will reuse the structure - // in display.externalMeasured when possible. - function getLineContent(cm, lineView) { - var ext = cm.display.externalMeasured; - if (ext && ext.line == lineView.line) { - cm.display.externalMeasured = null; - lineView.measure = ext.measure; - return ext.built; - } - return buildLineContent(cm, lineView); - } - - // Redraw the line's text. Interacts with the background and text - // classes because the mode may output tokens that influence these - // classes. - function updateLineText(cm, lineView) { - var cls = lineView.text.className; - var built = getLineContent(cm, lineView); - if (lineView.text == lineView.node) { - lineView.node = built.pre; - } - lineView.text.parentNode.replaceChild(built.pre, lineView.text); - lineView.text = built.pre; - if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { - lineView.bgClass = built.bgClass; - lineView.textClass = built.textClass; - updateLineClasses(cm, lineView); - } else if (cls) { - lineView.text.className = cls; - } - } - function updateLineClasses(cm, lineView) { - updateLineBackground(cm, lineView); - if (lineView.line.wrapClass) { - ensureLineWrapped(lineView).className = lineView.line.wrapClass; - } else if (lineView.node != lineView.text) { - lineView.node.className = ""; - } - var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; - lineView.text.className = textClass || ""; - } - function updateLineGutter(cm, lineView, lineN, dims) { - if (lineView.gutter) { - lineView.node.removeChild(lineView.gutter); - lineView.gutter = null; - } - if (lineView.gutterBackground) { - lineView.node.removeChild(lineView.gutterBackground); - lineView.gutterBackground = null; - } - if (lineView.line.gutterClass) { - var wrap = ensureLineWrapped(lineView); - lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + dims.gutterTotalWidth + "px"); - cm.display.input.setUneditable(lineView.gutterBackground); - wrap.insertBefore(lineView.gutterBackground, lineView.text); - } - var markers = lineView.line.gutterMarkers; - if (cm.options.lineNumbers || markers) { - var wrap$1 = ensureLineWrapped(lineView); - var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"); - gutterWrap.setAttribute("aria-hidden", "true"); - cm.display.input.setUneditable(gutterWrap); - wrap$1.insertBefore(gutterWrap, lineView.text); - if (lineView.line.gutterClass) { - gutterWrap.className += " " + lineView.line.gutterClass; - } - if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) { - lineView.lineNumber = gutterWrap.appendChild(elt("div", lineNumberFor(cm.options, lineN), "CodeMirror-linenumber CodeMirror-gutter-elt", "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " + cm.display.lineNumInnerWidth + "px")); - } - if (markers) { - for (var k = 0; k < cm.display.gutterSpecs.length; ++k) { - var id = cm.display.gutterSpecs[k].className, - found = markers.hasOwnProperty(id) && markers[id]; - if (found) { - gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px")); - } - } - } - } - } - function updateLineWidgets(cm, lineView, dims) { - if (lineView.alignable) { - lineView.alignable = null; - } - var isWidget = classTest("CodeMirror-linewidget"); - for (var node = lineView.node.firstChild, next = void 0; node; node = next) { - next = node.nextSibling; - if (isWidget.test(node.className)) { - lineView.node.removeChild(node); - } - } - insertLineWidgets(cm, lineView, dims); - } - - // Build a line's DOM representation from scratch - function buildLineElement(cm, lineView, lineN, dims) { - var built = getLineContent(cm, lineView); - lineView.text = lineView.node = built.pre; - if (built.bgClass) { - lineView.bgClass = built.bgClass; - } - if (built.textClass) { - lineView.textClass = built.textClass; - } - updateLineClasses(cm, lineView); - updateLineGutter(cm, lineView, lineN, dims); - insertLineWidgets(cm, lineView, dims); - return lineView.node; - } - - // A lineView may contain multiple logical lines (when merged by - // collapsed spans). The widgets for all of them need to be drawn. - function insertLineWidgets(cm, lineView, dims) { - insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); - if (lineView.rest) { - for (var i = 0; i < lineView.rest.length; i++) { - insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); - } - } - } - function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { - if (!line.widgets) { - return; - } - var wrap = ensureLineWrapped(lineView); - for (var i = 0, ws = line.widgets; i < ws.length; ++i) { - var widget = ws[i], - node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : "")); - if (!widget.handleMouseEvents) { - node.setAttribute("cm-ignore-events", "true"); - } - positionLineWidget(widget, node, lineView, dims); - cm.display.input.setUneditable(node); - if (allowAbove && widget.above) { - wrap.insertBefore(node, lineView.gutter || lineView.text); - } else { - wrap.appendChild(node); - } - signalLater(widget, "redraw"); - } - } - function positionLineWidget(widget, node, lineView, dims) { - if (widget.noHScroll) { - (lineView.alignable || (lineView.alignable = [])).push(node); - var width = dims.wrapperWidth; - node.style.left = dims.fixedPos + "px"; - if (!widget.coverGutter) { - width -= dims.gutterTotalWidth; - node.style.paddingLeft = dims.gutterTotalWidth + "px"; - } - node.style.width = width + "px"; - } - if (widget.coverGutter) { - node.style.zIndex = 5; - node.style.position = "relative"; - if (!widget.noHScroll) { - node.style.marginLeft = -dims.gutterTotalWidth + "px"; - } - } - } - function widgetHeight(widget) { - if (widget.height != null) { - return widget.height; - } - var cm = widget.doc.cm; - if (!cm) { - return 0; - } - if (!contains(document.body, widget.node)) { - var parentStyle = "position: relative;"; - if (widget.coverGutter) { - parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; - } - if (widget.noHScroll) { - parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; - } - removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); - } - return widget.height = widget.node.parentNode.offsetHeight; - } - - // Return true when the given mouse event happened in a widget - function eventInWidget(display, e) { - for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { - if (!n || n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true" || n.parentNode == display.sizer && n != display.mover) { - return true; - } - } - } - - // POSITION MEASUREMENT - - function paddingTop(display) { - return display.lineSpace.offsetTop; - } - function paddingVert(display) { - return display.mover.offsetHeight - display.lineSpace.offsetHeight; - } - function paddingH(display) { - if (display.cachedPaddingH) { - return display.cachedPaddingH; - } - var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like")); - var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; - var data = { - left: parseInt(style.paddingLeft), - right: parseInt(style.paddingRight) - }; - if (!isNaN(data.left) && !isNaN(data.right)) { - display.cachedPaddingH = data; - } - return data; - } - function scrollGap(cm) { - return scrollerGap - cm.display.nativeBarWidth; - } - function displayWidth(cm) { - return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth; - } - function displayHeight(cm) { - return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight; - } - - // Ensure the lineView.wrapping.heights array is populated. This is - // an array of bottom offsets for the lines that make up a drawn - // line. When lineWrapping is on, there might be more than one - // height. - function ensureLineHeights(cm, lineView, rect) { - var wrapping = cm.options.lineWrapping; - var curWidth = wrapping && displayWidth(cm); - if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { - var heights = lineView.measure.heights = []; - if (wrapping) { - lineView.measure.width = curWidth; - var rects = lineView.text.firstChild.getClientRects(); - for (var i = 0; i < rects.length - 1; i++) { - var cur = rects[i], - next = rects[i + 1]; - if (Math.abs(cur.bottom - next.bottom) > 2) { - heights.push((cur.bottom + next.top) / 2 - rect.top); - } - } - } - heights.push(rect.bottom - rect.top); - } - } - - // Find a line map (mapping character offsets to text nodes) and a - // measurement cache for the given line number. (A line view might - // contain multiple lines when collapsed ranges are present.) - function mapFromLineView(lineView, line, lineN) { - if (lineView.line == line) { - return { - map: lineView.measure.map, - cache: lineView.measure.cache - }; - } - if (lineView.rest) { - for (var i = 0; i < lineView.rest.length; i++) { - if (lineView.rest[i] == line) { - return { - map: lineView.measure.maps[i], - cache: lineView.measure.caches[i] - }; - } - } - for (var i$1 = 0; i$1 < lineView.rest.length; i$1++) { - if (lineNo(lineView.rest[i$1]) > lineN) { - return { - map: lineView.measure.maps[i$1], - cache: lineView.measure.caches[i$1], - before: true - }; - } - } - } - } - - // Render a line into the hidden node display.externalMeasured. Used - // when measurement is needed for a line that's not in the viewport. - function updateExternalMeasurement(cm, line) { - line = visualLine(line); - var lineN = lineNo(line); - var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); - view.lineN = lineN; - var built = view.built = buildLineContent(cm, view); - view.text = built.pre; - removeChildrenAndAdd(cm.display.lineMeasure, built.pre); - return view; - } - - // Get a {top, bottom, left, right} box (in line-local coordinates) - // for a given character. - function measureChar(cm, line, ch, bias) { - return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias); - } - - // Find a line view that corresponds to the given line number. - function findViewForLine(cm, lineN) { - if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) { - return cm.display.view[findViewIndex(cm, lineN)]; - } - var ext = cm.display.externalMeasured; - if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) { - return ext; - } - } - - // Measurement can be split in two steps, the set-up work that - // applies to the whole line, and the measurement of the actual - // character. Functions like coordsChar, that need to do a lot of - // measurements in a row, can thus ensure that the set-up work is - // only done once. - function prepareMeasureForLine(cm, line) { - var lineN = lineNo(line); - var view = findViewForLine(cm, lineN); - if (view && !view.text) { - view = null; - } else if (view && view.changes) { - updateLineForChanges(cm, view, lineN, getDimensions(cm)); - cm.curOp.forceUpdate = true; - } - if (!view) { - view = updateExternalMeasurement(cm, line); - } - var info = mapFromLineView(view, line, lineN); - return { - line: line, - view: view, - rect: null, - map: info.map, - cache: info.cache, - before: info.before, - hasHeights: false - }; - } - - // Given a prepared measurement object, measures the position of an - // actual character (or fetches it from the cache). - function measureCharPrepared(cm, prepared, ch, bias, varHeight) { - if (prepared.before) { - ch = -1; - } - var key = ch + (bias || ""), - found; - if (prepared.cache.hasOwnProperty(key)) { - found = prepared.cache[key]; - } else { - if (!prepared.rect) { - prepared.rect = prepared.view.text.getBoundingClientRect(); - } - if (!prepared.hasHeights) { - ensureLineHeights(cm, prepared.view, prepared.rect); - prepared.hasHeights = true; - } - found = measureCharInner(cm, prepared, ch, bias); - if (!found.bogus) { - prepared.cache[key] = found; - } - } - return { - left: found.left, - right: found.right, - top: varHeight ? found.rtop : found.top, - bottom: varHeight ? found.rbottom : found.bottom - }; - } - var nullRect = { - left: 0, - right: 0, - top: 0, - bottom: 0 - }; - function nodeAndOffsetInLineMap(map, ch, bias) { - var node, start, end, collapse, mStart, mEnd; - // First, search the line map for the text node corresponding to, - // or closest to, the target character. - for (var i = 0; i < map.length; i += 3) { - mStart = map[i]; - mEnd = map[i + 1]; - if (ch < mStart) { - start = 0; - end = 1; - collapse = "left"; - } else if (ch < mEnd) { - start = ch - mStart; - end = start + 1; - } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) { - end = mEnd - mStart; - start = end - 1; - if (ch >= mEnd) { - collapse = "right"; - } - } - if (start != null) { - node = map[i + 2]; - if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) { - collapse = bias; - } - if (bias == "left" && start == 0) { - while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) { - node = map[(i -= 3) + 2]; - collapse = "left"; - } - } - if (bias == "right" && start == mEnd - mStart) { - while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) { - node = map[(i += 3) + 2]; - collapse = "right"; - } - } - break; - } - } - return { - node: node, - start: start, - end: end, - collapse: collapse, - coverStart: mStart, - coverEnd: mEnd - }; - } - function getUsefulRect(rects, bias) { - var rect = nullRect; - if (bias == "left") { - for (var i = 0; i < rects.length; i++) { - if ((rect = rects[i]).left != rect.right) { - break; - } - } - } else { - for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) { - if ((rect = rects[i$1]).left != rect.right) { - break; - } - } - } - return rect; - } - function measureCharInner(cm, prepared, ch, bias) { - var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); - var node = place.node, - start = place.start, - end = place.end, - collapse = place.collapse; - var rect; - if (node.nodeType == 3) { - // If it is a text node, use a range to retrieve the coordinates. - for (var i$1 = 0; i$1 < 4; i$1++) { - // Retry a maximum of 4 times when nonsense rectangles are returned - while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { - --start; - } - while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { - ++end; - } - if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) { - rect = node.parentNode.getBoundingClientRect(); - } else { - rect = getUsefulRect(range(node, start, end).getClientRects(), bias); - } - if (rect.left || rect.right || start == 0) { - break; - } - end = start; - start = start - 1; - collapse = "right"; - } - if (ie && ie_version < 11) { - rect = maybeUpdateRectForZooming(cm.display.measure, rect); - } - } else { - // If it is a widget, simply get the box for the whole widget. - if (start > 0) { - collapse = bias = "right"; - } - var rects; - if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) { - rect = rects[bias == "right" ? rects.length - 1 : 0]; - } else { - rect = node.getBoundingClientRect(); - } - } - if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { - var rSpan = node.parentNode.getClientRects()[0]; - if (rSpan) { - rect = { - left: rSpan.left, - right: rSpan.left + charWidth(cm.display), - top: rSpan.top, - bottom: rSpan.bottom - }; - } else { - rect = nullRect; - } - } - var rtop = rect.top - prepared.rect.top, - rbot = rect.bottom - prepared.rect.top; - var mid = (rtop + rbot) / 2; - var heights = prepared.view.measure.heights; - var i = 0; - for (; i < heights.length - 1; i++) { - if (mid < heights[i]) { - break; - } - } - var top = i ? heights[i - 1] : 0, - bot = heights[i]; - var result = { - left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, - right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, - top: top, - bottom: bot - }; - if (!rect.left && !rect.right) { - result.bogus = true; - } - if (!cm.options.singleCursorHeightPerLine) { - result.rtop = rtop; - result.rbottom = rbot; - } - return result; - } - - // Work around problem with bounding client rects on ranges being - // returned incorrectly when zoomed on IE10 and below. - function maybeUpdateRectForZooming(measure, rect) { - if (!window.screen || screen.logicalXDPI == null || screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) { - return rect; - } - var scaleX = screen.logicalXDPI / screen.deviceXDPI; - var scaleY = screen.logicalYDPI / screen.deviceYDPI; - return { - left: rect.left * scaleX, - right: rect.right * scaleX, - top: rect.top * scaleY, - bottom: rect.bottom * scaleY - }; - } - function clearLineMeasurementCacheFor(lineView) { - if (lineView.measure) { - lineView.measure.cache = {}; - lineView.measure.heights = null; - if (lineView.rest) { - for (var i = 0; i < lineView.rest.length; i++) { - lineView.measure.caches[i] = {}; - } - } - } - } - function clearLineMeasurementCache(cm) { - cm.display.externalMeasure = null; - removeChildren(cm.display.lineMeasure); - for (var i = 0; i < cm.display.view.length; i++) { - clearLineMeasurementCacheFor(cm.display.view[i]); - } - } - function clearCaches(cm) { - clearLineMeasurementCache(cm); - cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; - if (!cm.options.lineWrapping) { - cm.display.maxLineChanged = true; - } - cm.display.lineNumChars = null; - } - function pageScrollX() { - // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206 - // which causes page_Offset and bounding client rects to use - // different reference viewports and invalidate our calculations. - if (chrome && android) { - return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)); - } - return window.pageXOffset || (document.documentElement || document.body).scrollLeft; - } - function pageScrollY() { - if (chrome && android) { - return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)); - } - return window.pageYOffset || (document.documentElement || document.body).scrollTop; - } - function widgetTopHeight(lineObj) { - var ref = visualLine(lineObj); - var widgets = ref.widgets; - var height = 0; - if (widgets) { - for (var i = 0; i < widgets.length; ++i) { - if (widgets[i].above) { - height += widgetHeight(widgets[i]); - } - } - } - return height; - } - - // Converts a {top, bottom, left, right} box from line-local - // coordinates into another coordinate system. Context may be one of - // "line", "div" (display.lineDiv), "local"./null (editor), "window", - // or "page". - function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) { - if (!includeWidgets) { - var height = widgetTopHeight(lineObj); - rect.top += height; - rect.bottom += height; - } - if (context == "line") { - return rect; - } - if (!context) { - context = "local"; - } - var yOff = heightAtLine(lineObj); - if (context == "local") { - yOff += paddingTop(cm.display); - } else { - yOff -= cm.display.viewOffset; - } - if (context == "page" || context == "window") { - var lOff = cm.display.lineSpace.getBoundingClientRect(); - yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); - var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); - rect.left += xOff; - rect.right += xOff; - } - rect.top += yOff; - rect.bottom += yOff; - return rect; - } - - // Coverts a box from "div" coords to another coordinate system. - // Context may be "window", "page", "div", or "local"./null. - function fromCoordSystem(cm, coords, context) { - if (context == "div") { - return coords; - } - var left = coords.left, - top = coords.top; - // First move into "page" coordinate system - if (context == "page") { - left -= pageScrollX(); - top -= pageScrollY(); - } else if (context == "local" || !context) { - var localBox = cm.display.sizer.getBoundingClientRect(); - left += localBox.left; - top += localBox.top; - } - var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); - return { - left: left - lineSpaceBox.left, - top: top - lineSpaceBox.top - }; - } - function charCoords(cm, pos, context, lineObj, bias) { - if (!lineObj) { - lineObj = getLine(cm.doc, pos.line); - } - return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context); - } - - // Returns a box for a given cursor position, which may have an - // 'other' property containing the position of the secondary cursor - // on a bidi boundary. - // A cursor Pos(line, char, "before") is on the same visual line as `char - 1` - // and after `char - 1` in writing order of `char - 1` - // A cursor Pos(line, char, "after") is on the same visual line as `char` - // and before `char` in writing order of `char` - // Examples (upper-case letters are RTL, lower-case are LTR): - // Pos(0, 1, ...) - // before after - // ab a|b a|b - // aB a|B aB| - // Ab |Ab A|b - // AB B|A B|A - // Every position after the last character on a line is considered to stick - // to the last character on the line. - function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { - lineObj = lineObj || getLine(cm.doc, pos.line); - if (!preparedMeasure) { - preparedMeasure = prepareMeasureForLine(cm, lineObj); - } - function get(ch, right) { - var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight); - if (right) { - m.left = m.right; - } else { - m.right = m.left; - } - return intoCoordSystem(cm, lineObj, m, context); - } - var order = getOrder(lineObj, cm.doc.direction), - ch = pos.ch, - sticky = pos.sticky; - if (ch >= lineObj.text.length) { - ch = lineObj.text.length; - sticky = "before"; - } else if (ch <= 0) { - ch = 0; - sticky = "after"; - } - if (!order) { - return get(sticky == "before" ? ch - 1 : ch, sticky == "before"); - } - function getBidi(ch, partPos, invert) { - var part = order[partPos], - right = part.level == 1; - return get(invert ? ch - 1 : ch, right != invert); - } - var partPos = getBidiPartAt(order, ch, sticky); - var other = bidiOther; - var val = getBidi(ch, partPos, sticky == "before"); - if (other != null) { - val.other = getBidi(ch, other, sticky != "before"); - } - return val; - } - - // Used to cheaply estimate the coordinates for a position. Used for - // intermediate scroll updates. - function estimateCoords(cm, pos) { - var left = 0; - pos = clipPos(cm.doc, pos); - if (!cm.options.lineWrapping) { - left = charWidth(cm.display) * pos.ch; - } - var lineObj = getLine(cm.doc, pos.line); - var top = heightAtLine(lineObj) + paddingTop(cm.display); - return { - left: left, - right: left, - top: top, - bottom: top + lineObj.height - }; - } - - // Positions returned by coordsChar contain some extra information. - // xRel is the relative x position of the input coordinates compared - // to the found position (so xRel > 0 means the coordinates are to - // the right of the character position, for example). When outside - // is true, that means the coordinates lie outside the line's - // vertical range. - function PosWithInfo(line, ch, sticky, outside, xRel) { - var pos = Pos(line, ch, sticky); - pos.xRel = xRel; - if (outside) { - pos.outside = outside; - } - return pos; - } - - // Compute the character position closest to the given coordinates. - // Input must be lineSpace-local ("div" coordinate system). - function coordsChar(cm, x, y) { - var doc = cm.doc; - y += cm.display.viewOffset; - if (y < 0) { - return PosWithInfo(doc.first, 0, null, -1, -1); - } - var lineN = lineAtHeight(doc, y), - last = doc.first + doc.size - 1; - if (lineN > last) { - return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1); - } - if (x < 0) { - x = 0; - } - var lineObj = getLine(doc, lineN); - for (;;) { - var found = coordsCharInner(cm, lineObj, lineN, x, y); - var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0)); - if (!collapsed) { - return found; - } - var rangeEnd = collapsed.find(1); - if (rangeEnd.line == lineN) { - return rangeEnd; - } - lineObj = getLine(doc, lineN = rangeEnd.line); - } - } - function wrappedLineExtent(cm, lineObj, preparedMeasure, y) { - y -= widgetTopHeight(lineObj); - var end = lineObj.text.length; - var begin = findFirst(function (ch) { - return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; - }, end, 0); - end = findFirst(function (ch) { - return measureCharPrepared(cm, preparedMeasure, ch).top > y; - }, begin, end); - return { - begin: begin, - end: end - }; - } - function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) { - if (!preparedMeasure) { - preparedMeasure = prepareMeasureForLine(cm, lineObj); - } - var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top; - return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop); - } - - // Returns true if the given side of a box is after the given - // coordinates, in top-to-bottom, left-to-right order. - function boxIsAfter(box, x, y, left) { - return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x; - } - function coordsCharInner(cm, lineObj, lineNo, x, y) { - // Move y into line-local coordinate space - y -= heightAtLine(lineObj); - var preparedMeasure = prepareMeasureForLine(cm, lineObj); - // When directly calling `measureCharPrepared`, we have to adjust - // for the widgets at this line. - var widgetHeight = widgetTopHeight(lineObj); - var begin = 0, - end = lineObj.text.length, - ltr = true; - var order = getOrder(lineObj, cm.doc.direction); - // If the line isn't plain left-to-right text, first figure out - // which bidi section the coordinates fall into. - if (order) { - var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)(cm, lineObj, lineNo, preparedMeasure, order, x, y); - ltr = part.level != 1; - // The awkward -1 offsets are needed because findFirst (called - // on these below) will treat its first bound as inclusive, - // second as exclusive, but we want to actually address the - // characters in the part's range - begin = ltr ? part.from : part.to - 1; - end = ltr ? part.to : part.from - 1; - } - - // A binary search to find the first character whose bounding box - // starts after the coordinates. If we run across any whose box wrap - // the coordinates, store that. - var chAround = null, - boxAround = null; - var ch = findFirst(function (ch) { - var box = measureCharPrepared(cm, preparedMeasure, ch); - box.top += widgetHeight; - box.bottom += widgetHeight; - if (!boxIsAfter(box, x, y, false)) { - return false; - } - if (box.top <= y && box.left <= x) { - chAround = ch; - boxAround = box; - } - return true; - }, begin, end); - var baseX, - sticky, - outside = false; - // If a box around the coordinates was found, use that - if (boxAround) { - // Distinguish coordinates nearer to the left or right side of the box - var atLeft = x - boxAround.left < boxAround.right - x, - atStart = atLeft == ltr; - ch = chAround + (atStart ? 0 : 1); - sticky = atStart ? "after" : "before"; - baseX = atLeft ? boxAround.left : boxAround.right; - } else { - // (Adjust for extended bound, if necessary.) - if (!ltr && (ch == end || ch == begin)) { - ch++; - } - // To determine which side to associate with, get the box to the - // left of the character and compare it's vertical position to the - // coordinates - sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" : measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y == ltr ? "after" : "before"; - // Now get accurate coordinates for this place, in order to get a - // base X position - var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure); - baseX = coords.left; - outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0; - } - ch = skipExtendingChars(lineObj.text, ch, 1); - return PosWithInfo(lineNo, ch, sticky, outside, x - baseX); - } - function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) { - // Bidi parts are sorted left-to-right, and in a non-line-wrapping - // situation, we can take this ordering to correspond to the visual - // ordering. This finds the first part whose end is after the given - // coordinates. - var index = findFirst(function (i) { - var part = order[i], - ltr = part.level != 1; - return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"), "line", lineObj, preparedMeasure), x, y, true); - }, 0, order.length - 1); - var part = order[index]; - // If this isn't the first part, the part's start is also after - // the coordinates, and the coordinates aren't on the same line as - // that start, move one part back. - if (index > 0) { - var ltr = part.level != 1; - var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"), "line", lineObj, preparedMeasure); - if (boxIsAfter(start, x, y, true) && start.top > y) { - part = order[index - 1]; - } - } - return part; - } - function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) { - // In a wrapped line, rtl text on wrapping boundaries can do things - // that don't correspond to the ordering in our `order` array at - // all, so a binary search doesn't work, and we want to return a - // part that only spans one line so that the binary search in - // coordsCharInner is safe. As such, we first find the extent of the - // wrapped line, and then do a flat search in which we discard any - // spans that aren't on the line. - var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y); - var begin = ref.begin; - var end = ref.end; - if (/\s/.test(lineObj.text.charAt(end - 1))) { - end--; - } - var part = null, - closestDist = null; - for (var i = 0; i < order.length; i++) { - var p = order[i]; - if (p.from >= end || p.to <= begin) { - continue; - } - var ltr = p.level != 1; - var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right; - // Weigh against spans ending before this, so that they are only - // picked if nothing ends after - var dist = endX < x ? x - endX + 1e9 : endX - x; - if (!part || closestDist > dist) { - part = p; - closestDist = dist; - } - } - if (!part) { - part = order[order.length - 1]; - } - // Clip the part to the wrapped line. - if (part.from < begin) { - part = { - from: begin, - to: part.to, - level: part.level - }; - } - if (part.to > end) { - part = { - from: part.from, - to: end, - level: part.level - }; - } - return part; - } - var measureText; - // Compute the default text height. - function textHeight(display) { - if (display.cachedTextHeight != null) { - return display.cachedTextHeight; - } - if (measureText == null) { - measureText = elt("pre", null, "CodeMirror-line-like"); - // Measure a bunch of lines, for browsers that compute - // fractional heights. - for (var i = 0; i < 49; ++i) { - measureText.appendChild(document.createTextNode("x")); - measureText.appendChild(elt("br")); - } - measureText.appendChild(document.createTextNode("x")); - } - removeChildrenAndAdd(display.measure, measureText); - var height = measureText.offsetHeight / 50; - if (height > 3) { - display.cachedTextHeight = height; - } - removeChildren(display.measure); - return height || 1; - } - - // Compute the default character width. - function charWidth(display) { - if (display.cachedCharWidth != null) { - return display.cachedCharWidth; - } - var anchor = elt("span", "xxxxxxxxxx"); - var pre = elt("pre", [anchor], "CodeMirror-line-like"); - removeChildrenAndAdd(display.measure, pre); - var rect = anchor.getBoundingClientRect(), - width = (rect.right - rect.left) / 10; - if (width > 2) { - display.cachedCharWidth = width; - } - return width || 10; - } - - // Do a bulk-read of the DOM positions and sizes needed to draw the - // view, so that we don't interleave reading and writing to the DOM. - function getDimensions(cm) { - var d = cm.display, - left = {}, - width = {}; - var gutterLeft = d.gutters.clientLeft; - for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { - var id = cm.display.gutterSpecs[i].className; - left[id] = n.offsetLeft + n.clientLeft + gutterLeft; - width[id] = n.clientWidth; - } - return { - fixedPos: compensateForHScroll(d), - gutterTotalWidth: d.gutters.offsetWidth, - gutterLeft: left, - gutterWidth: width, - wrapperWidth: d.wrapper.clientWidth - }; - } - - // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, - // but using getBoundingClientRect to get a sub-pixel-accurate - // result. - function compensateForHScroll(display) { - return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left; - } - - // Returns a function that estimates the height of a line, to use as - // first approximation until the line becomes visible (and is thus - // properly measurable). - function estimateHeight(cm) { - var th = textHeight(cm.display), - wrapping = cm.options.lineWrapping; - var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); - return function (line) { - if (lineIsHidden(cm.doc, line)) { - return 0; - } - var widgetsHeight = 0; - if (line.widgets) { - for (var i = 0; i < line.widgets.length; i++) { - if (line.widgets[i].height) { - widgetsHeight += line.widgets[i].height; - } - } - } - if (wrapping) { - return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th; - } else { - return widgetsHeight + th; - } - }; - } - function estimateLineHeights(cm) { - var doc = cm.doc, - est = estimateHeight(cm); - doc.iter(function (line) { - var estHeight = est(line); - if (estHeight != line.height) { - updateLineHeight(line, estHeight); - } - }); - } - - // Given a mouse event, find the corresponding position. If liberal - // is false, it checks whether a gutter or scrollbar was clicked, - // and returns null if it was. forRect is used by rectangular - // selections, and tries to estimate a character position even for - // coordinates beyond the right of the text. - function posFromMouse(cm, e, liberal, forRect) { - var display = cm.display; - if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { - return null; - } - var x, - y, - space = display.lineSpace.getBoundingClientRect(); - // Fails unpredictably on IE[67] when mouse is dragged around quickly. - try { - x = e.clientX - space.left; - y = e.clientY - space.top; - } catch (e$1) { - return null; - } - var coords = coordsChar(cm, x, y), - line; - if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { - var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; - coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); - } - return coords; - } - - // Find the view element corresponding to a given line. Return null - // when the line isn't visible. - function findViewIndex(cm, n) { - if (n >= cm.display.viewTo) { - return null; - } - n -= cm.display.viewFrom; - if (n < 0) { - return null; - } - var view = cm.display.view; - for (var i = 0; i < view.length; i++) { - n -= view[i].size; - if (n < 0) { - return i; - } - } - } - - // Updates the display.view data structure for a given change to the - // document. From and to are in pre-change coordinates. Lendiff is - // the amount of lines added or subtracted by the change. This is - // used for changes that span multiple lines, or change the way - // lines are divided into visual lines. regLineChange (below) - // registers single-line changes. - function regChange(cm, from, to, lendiff) { - if (from == null) { - from = cm.doc.first; - } - if (to == null) { - to = cm.doc.first + cm.doc.size; - } - if (!lendiff) { - lendiff = 0; - } - var display = cm.display; - if (lendiff && to < display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers > from)) { - display.updateLineNumbers = from; - } - cm.curOp.viewChanged = true; - if (from >= display.viewTo) { - // Change after - if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) { - resetView(cm); - } - } else if (to <= display.viewFrom) { - // Change before - if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { - resetView(cm); - } else { - display.viewFrom += lendiff; - display.viewTo += lendiff; - } - } else if (from <= display.viewFrom && to >= display.viewTo) { - // Full overlap - resetView(cm); - } else if (from <= display.viewFrom) { - // Top overlap - var cut = viewCuttingPoint(cm, to, to + lendiff, 1); - if (cut) { - display.view = display.view.slice(cut.index); - display.viewFrom = cut.lineN; - display.viewTo += lendiff; - } else { - resetView(cm); - } - } else if (to >= display.viewTo) { - // Bottom overlap - var cut$1 = viewCuttingPoint(cm, from, from, -1); - if (cut$1) { - display.view = display.view.slice(0, cut$1.index); - display.viewTo = cut$1.lineN; - } else { - resetView(cm); - } - } else { - // Gap in the middle - var cutTop = viewCuttingPoint(cm, from, from, -1); - var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); - if (cutTop && cutBot) { - display.view = display.view.slice(0, cutTop.index).concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)).concat(display.view.slice(cutBot.index)); - display.viewTo += lendiff; - } else { - resetView(cm); - } - } - var ext = display.externalMeasured; - if (ext) { - if (to < ext.lineN) { - ext.lineN += lendiff; - } else if (from < ext.lineN + ext.size) { - display.externalMeasured = null; - } - } - } - - // Register a change to a single line. Type must be one of "text", - // "gutter", "class", "widget" - function regLineChange(cm, line, type) { - cm.curOp.viewChanged = true; - var display = cm.display, - ext = cm.display.externalMeasured; - if (ext && line >= ext.lineN && line < ext.lineN + ext.size) { - display.externalMeasured = null; - } - if (line < display.viewFrom || line >= display.viewTo) { - return; - } - var lineView = display.view[findViewIndex(cm, line)]; - if (lineView.node == null) { - return; - } - var arr = lineView.changes || (lineView.changes = []); - if (indexOf(arr, type) == -1) { - arr.push(type); - } - } - - // Clear the view. - function resetView(cm) { - cm.display.viewFrom = cm.display.viewTo = cm.doc.first; - cm.display.view = []; - cm.display.viewOffset = 0; - } - function viewCuttingPoint(cm, oldN, newN, dir) { - var index = findViewIndex(cm, oldN), - diff, - view = cm.display.view; - if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) { - return { - index: index, - lineN: newN - }; - } - var n = cm.display.viewFrom; - for (var i = 0; i < index; i++) { - n += view[i].size; - } - if (n != oldN) { - if (dir > 0) { - if (index == view.length - 1) { - return null; - } - diff = n + view[index].size - oldN; - index++; - } else { - diff = n - oldN; - } - oldN += diff; - newN += diff; - } - while (visualLineNo(cm.doc, newN) != newN) { - if (index == (dir < 0 ? 0 : view.length - 1)) { - return null; - } - newN += dir * view[index - (dir < 0 ? 1 : 0)].size; - index += dir; - } - return { - index: index, - lineN: newN - }; - } - - // Force the view to cover a given range, adding empty view element - // or clipping off existing ones as needed. - function adjustView(cm, from, to) { - var display = cm.display, - view = display.view; - if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { - display.view = buildViewArray(cm, from, to); - display.viewFrom = from; - } else { - if (display.viewFrom > from) { - display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); - } else if (display.viewFrom < from) { - display.view = display.view.slice(findViewIndex(cm, from)); - } - display.viewFrom = from; - if (display.viewTo < to) { - display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); - } else if (display.viewTo > to) { - display.view = display.view.slice(0, findViewIndex(cm, to)); - } - } - display.viewTo = to; - } - - // Count the number of lines in the view whose DOM representation is - // out of date (or nonexistent). - function countDirtyView(cm) { - var view = cm.display.view, - dirty = 0; - for (var i = 0; i < view.length; i++) { - var lineView = view[i]; - if (!lineView.hidden && (!lineView.node || lineView.changes)) { - ++dirty; - } - } - return dirty; - } - function updateSelection(cm) { - cm.display.input.showSelection(cm.display.input.prepareSelection()); - } - function prepareSelection(cm, primary) { - if (primary === void 0) primary = true; - var doc = cm.doc, - result = {}; - var curFragment = result.cursors = document.createDocumentFragment(); - var selFragment = result.selection = document.createDocumentFragment(); - var customCursor = cm.options.$customCursor; - if (customCursor) { - primary = true; - } - for (var i = 0; i < doc.sel.ranges.length; i++) { - if (!primary && i == doc.sel.primIndex) { - continue; - } - var range = doc.sel.ranges[i]; - if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { - continue; - } - var collapsed = range.empty(); - if (customCursor) { - var head = customCursor(cm, range); - if (head) { - drawSelectionCursor(cm, head, curFragment); - } - } else if (collapsed || cm.options.showCursorWhenSelecting) { - drawSelectionCursor(cm, range.head, curFragment); - } - if (!collapsed) { - drawSelectionRange(cm, range, selFragment); - } - } - return result; - } - - // Draws a cursor for the given range - function drawSelectionCursor(cm, head, output) { - var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine); - var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); - cursor.style.left = pos.left + "px"; - cursor.style.top = pos.top + "px"; - cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; - if (/\bcm-fat-cursor\b/.test(cm.getWrapperElement().className)) { - var charPos = charCoords(cm, head, "div", null, null); - var width = charPos.right - charPos.left; - cursor.style.width = (width > 0 ? width : cm.defaultCharWidth()) + "px"; - } - if (pos.other) { - // Secondary cursor, shown when on a 'jump' in bi-directional text - var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")); - otherCursor.style.display = ""; - otherCursor.style.left = pos.other.left + "px"; - otherCursor.style.top = pos.other.top + "px"; - otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; - } - } - function cmpCoords(a, b) { - return a.top - b.top || a.left - b.left; - } - - // Draws the given range as a highlighted selection - function drawSelectionRange(cm, range, output) { - var display = cm.display, - doc = cm.doc; - var fragment = document.createDocumentFragment(); - var padding = paddingH(cm.display), - leftSide = padding.left; - var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; - var docLTR = doc.direction == "ltr"; - function add(left, top, width, bottom) { - if (top < 0) { - top = 0; - } - top = Math.round(top); - bottom = Math.round(bottom); - fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px")); - } - function drawForLine(line, fromArg, toArg) { - var lineObj = getLine(doc, line); - var lineLen = lineObj.text.length; - var start, end; - function coords(ch, bias) { - return charCoords(cm, Pos(line, ch), "div", lineObj, bias); - } - function wrapX(pos, dir, side) { - var extent = wrappedLineExtentChar(cm, lineObj, null, pos); - var prop = dir == "ltr" == (side == "after") ? "left" : "right"; - var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1); - return coords(ch, prop)[prop]; - } - var order = getOrder(lineObj, doc.direction); - iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) { - var ltr = dir == "ltr"; - var fromPos = coords(from, ltr ? "left" : "right"); - var toPos = coords(to - 1, ltr ? "right" : "left"); - var openStart = fromArg == null && from == 0, - openEnd = toArg == null && to == lineLen; - var first = i == 0, - last = !order || i == order.length - 1; - if (toPos.top - fromPos.top <= 3) { - // Single line - var openLeft = (docLTR ? openStart : openEnd) && first; - var openRight = (docLTR ? openEnd : openStart) && last; - var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left; - var right = openRight ? rightSide : (ltr ? toPos : fromPos).right; - add(left, fromPos.top, right - left, fromPos.bottom); - } else { - // Multiple lines - var topLeft, topRight, botLeft, botRight; - if (ltr) { - topLeft = docLTR && openStart && first ? leftSide : fromPos.left; - topRight = docLTR ? rightSide : wrapX(from, dir, "before"); - botLeft = docLTR ? leftSide : wrapX(to, dir, "after"); - botRight = docLTR && openEnd && last ? rightSide : toPos.right; - } else { - topLeft = !docLTR ? leftSide : wrapX(from, dir, "before"); - topRight = !docLTR && openStart && first ? rightSide : fromPos.right; - botLeft = !docLTR && openEnd && last ? leftSide : toPos.left; - botRight = !docLTR ? rightSide : wrapX(to, dir, "after"); - } - add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom); - if (fromPos.bottom < toPos.top) { - add(leftSide, fromPos.bottom, null, toPos.top); - } - add(botLeft, toPos.top, botRight - botLeft, toPos.bottom); - } - if (!start || cmpCoords(fromPos, start) < 0) { - start = fromPos; - } - if (cmpCoords(toPos, start) < 0) { - start = toPos; - } - if (!end || cmpCoords(fromPos, end) < 0) { - end = fromPos; - } - if (cmpCoords(toPos, end) < 0) { - end = toPos; - } - }); - return { - start: start, - end: end - }; - } - var sFrom = range.from(), - sTo = range.to(); - if (sFrom.line == sTo.line) { - drawForLine(sFrom.line, sFrom.ch, sTo.ch); - } else { - var fromLine = getLine(doc, sFrom.line), - toLine = getLine(doc, sTo.line); - var singleVLine = visualLine(fromLine) == visualLine(toLine); - var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; - var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; - if (singleVLine) { - if (leftEnd.top < rightStart.top - 2) { - add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); - add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); - } else { - add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); - } - } - if (leftEnd.bottom < rightStart.top) { - add(leftSide, leftEnd.bottom, null, rightStart.top); - } - } - output.appendChild(fragment); - } - - // Cursor-blinking - function restartBlink(cm) { - if (!cm.state.focused) { - return; - } - var display = cm.display; - clearInterval(display.blinker); - var on = true; - display.cursorDiv.style.visibility = ""; - if (cm.options.cursorBlinkRate > 0) { - display.blinker = setInterval(function () { - if (!cm.hasFocus()) { - onBlur(cm); - } - display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; - }, cm.options.cursorBlinkRate); - } else if (cm.options.cursorBlinkRate < 0) { - display.cursorDiv.style.visibility = "hidden"; - } - } - function ensureFocus(cm) { - if (!cm.hasFocus()) { - cm.display.input.focus(); - if (!cm.state.focused) { - onFocus(cm); - } - } - } - function delayBlurEvent(cm) { - cm.state.delayingBlurEvent = true; - setTimeout(function () { - if (cm.state.delayingBlurEvent) { - cm.state.delayingBlurEvent = false; - if (cm.state.focused) { - onBlur(cm); - } - } - }, 100); - } - function onFocus(cm, e) { - if (cm.state.delayingBlurEvent && !cm.state.draggingText) { - cm.state.delayingBlurEvent = false; - } - if (cm.options.readOnly == "nocursor") { - return; - } - if (!cm.state.focused) { - signal(cm, "focus", cm, e); - cm.state.focused = true; - addClass(cm.display.wrapper, "CodeMirror-focused"); - // This test prevents this from firing when a context - // menu is closed (since the input reset would kill the - // select-all detection hack) - if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { - cm.display.input.reset(); - if (webkit) { - setTimeout(function () { - return cm.display.input.reset(true); - }, 20); - } // Issue #1730 - } - cm.display.input.receivedFocus(); - } - restartBlink(cm); - } - function onBlur(cm, e) { - if (cm.state.delayingBlurEvent) { - return; - } - if (cm.state.focused) { - signal(cm, "blur", cm, e); - cm.state.focused = false; - rmClass(cm.display.wrapper, "CodeMirror-focused"); - } - clearInterval(cm.display.blinker); - setTimeout(function () { - if (!cm.state.focused) { - cm.display.shift = false; - } - }, 150); - } - - // Read the actual heights of the rendered lines, and update their - // stored heights to match. - function updateHeightsInViewport(cm) { - var display = cm.display; - var prevBottom = display.lineDiv.offsetTop; - var viewTop = Math.max(0, display.scroller.getBoundingClientRect().top); - var oldHeight = display.lineDiv.getBoundingClientRect().top; - var mustScroll = 0; - for (var i = 0; i < display.view.length; i++) { - var cur = display.view[i], - wrapping = cm.options.lineWrapping; - var height = void 0, - width = 0; - if (cur.hidden) { - continue; - } - oldHeight += cur.line.height; - if (ie && ie_version < 8) { - var bot = cur.node.offsetTop + cur.node.offsetHeight; - height = bot - prevBottom; - prevBottom = bot; - } else { - var box = cur.node.getBoundingClientRect(); - height = box.bottom - box.top; - // Check that lines don't extend past the right of the current - // editor width - if (!wrapping && cur.text.firstChild) { - width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; - } - } - var diff = cur.line.height - height; - if (diff > .005 || diff < -.005) { - if (oldHeight < viewTop) { - mustScroll -= diff; - } - updateLineHeight(cur.line, height); - updateWidgetHeight(cur.line); - if (cur.rest) { - for (var j = 0; j < cur.rest.length; j++) { - updateWidgetHeight(cur.rest[j]); - } - } - } - if (width > cm.display.sizerWidth) { - var chWidth = Math.ceil(width / charWidth(cm.display)); - if (chWidth > cm.display.maxLineLength) { - cm.display.maxLineLength = chWidth; - cm.display.maxLine = cur.line; - cm.display.maxLineChanged = true; - } - } - } - if (Math.abs(mustScroll) > 2) { - display.scroller.scrollTop += mustScroll; - } - } - - // Read and store the height of line widgets associated with the - // given line. - function updateWidgetHeight(line) { - if (line.widgets) { - for (var i = 0; i < line.widgets.length; ++i) { - var w = line.widgets[i], - parent = w.node.parentNode; - if (parent) { - w.height = parent.offsetHeight; - } - } - } - } - - // Compute the lines that are visible in a given viewport (defaults - // the the current scroll position). viewport may contain top, - // height, and ensure (see op.scrollToPos) properties. - function visibleLines(display, doc, viewport) { - var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; - top = Math.floor(top - paddingTop(display)); - var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; - var from = lineAtHeight(doc, top), - to = lineAtHeight(doc, bottom); - // Ensure is a {from: {line, ch}, to: {line, ch}} object, and - // forces those lines into the viewport (if possible). - if (viewport && viewport.ensure) { - var ensureFrom = viewport.ensure.from.line, - ensureTo = viewport.ensure.to.line; - if (ensureFrom < from) { - from = ensureFrom; - to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); - } else if (Math.min(ensureTo, doc.lastLine()) >= to) { - from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); - to = ensureTo; - } - } - return { - from: from, - to: Math.max(to, from + 1) - }; - } - - // SCROLLING THINGS INTO VIEW - - // If an editor sits on the top or bottom of the window, partially - // scrolled out of view, this ensures that the cursor is visible. - function maybeScrollWindow(cm, rect) { - if (signalDOMEvent(cm, "scrollCursorIntoView")) { - return; - } - var display = cm.display, - box = display.sizer.getBoundingClientRect(), - doScroll = null; - if (rect.top + box.top < 0) { - doScroll = true; - } else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { - doScroll = false; - } - if (doScroll != null && !phantom) { - var scrollNode = elt("div", "\u200b", null, "position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + rect.left + "px; width: " + Math.max(2, rect.right - rect.left) + "px;"); - cm.display.lineSpace.appendChild(scrollNode); - scrollNode.scrollIntoView(doScroll); - cm.display.lineSpace.removeChild(scrollNode); - } - } - - // Scroll a given position into view (immediately), verifying that - // it actually became visible (as line heights are accurately - // measured, the position of something may 'drift' during drawing). - function scrollPosIntoView(cm, pos, end, margin) { - if (margin == null) { - margin = 0; - } - var rect; - if (!cm.options.lineWrapping && pos == end) { - // Set pos and end to the cursor positions around the character pos sticks to - // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch - // If pos == Pos(_, 0, "before"), pos and end are unchanged - end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos; - pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos; - } - for (var limit = 0; limit < 5; limit++) { - var changed = false; - var coords = cursorCoords(cm, pos); - var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); - rect = { - left: Math.min(coords.left, endCoords.left), - top: Math.min(coords.top, endCoords.top) - margin, - right: Math.max(coords.left, endCoords.left), - bottom: Math.max(coords.bottom, endCoords.bottom) + margin - }; - var scrollPos = calculateScrollPos(cm, rect); - var startTop = cm.doc.scrollTop, - startLeft = cm.doc.scrollLeft; - if (scrollPos.scrollTop != null) { - updateScrollTop(cm, scrollPos.scrollTop); - if (Math.abs(cm.doc.scrollTop - startTop) > 1) { - changed = true; - } - } - if (scrollPos.scrollLeft != null) { - setScrollLeft(cm, scrollPos.scrollLeft); - if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { - changed = true; - } - } - if (!changed) { - break; - } - } - return rect; - } - - // Scroll a given set of coordinates into view (immediately). - function scrollIntoView(cm, rect) { - var scrollPos = calculateScrollPos(cm, rect); - if (scrollPos.scrollTop != null) { - updateScrollTop(cm, scrollPos.scrollTop); - } - if (scrollPos.scrollLeft != null) { - setScrollLeft(cm, scrollPos.scrollLeft); - } - } - - // Calculate a new scroll position needed to scroll the given - // rectangle into view. Returns an object with scrollTop and - // scrollLeft properties. When these are undefined, the - // vertical/horizontal position does not need to be adjusted. - function calculateScrollPos(cm, rect) { - var display = cm.display, - snapMargin = textHeight(cm.display); - if (rect.top < 0) { - rect.top = 0; - } - var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; - var screen = displayHeight(cm), - result = {}; - if (rect.bottom - rect.top > screen) { - rect.bottom = rect.top + screen; - } - var docBottom = cm.doc.height + paddingVert(display); - var atTop = rect.top < snapMargin, - atBottom = rect.bottom > docBottom - snapMargin; - if (rect.top < screentop) { - result.scrollTop = atTop ? 0 : rect.top; - } else if (rect.bottom > screentop + screen) { - var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen); - if (newTop != screentop) { - result.scrollTop = newTop; - } - } - var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth; - var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace; - var screenw = displayWidth(cm) - display.gutters.offsetWidth; - var tooWide = rect.right - rect.left > screenw; - if (tooWide) { - rect.right = rect.left + screenw; - } - if (rect.left < 10) { - result.scrollLeft = 0; - } else if (rect.left < screenleft) { - result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10)); - } else if (rect.right > screenw + screenleft - 3) { - result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; - } - return result; - } - - // Store a relative adjustment to the scroll position in the current - // operation (to be applied when the operation finishes). - function addToScrollTop(cm, top) { - if (top == null) { - return; - } - resolveScrollToPos(cm); - cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; - } - - // Make sure that at the end of the operation the current cursor is - // shown. - function ensureCursorVisible(cm) { - resolveScrollToPos(cm); - var cur = cm.getCursor(); - cm.curOp.scrollToPos = { - from: cur, - to: cur, - margin: cm.options.cursorScrollMargin - }; - } - function scrollToCoords(cm, x, y) { - if (x != null || y != null) { - resolveScrollToPos(cm); - } - if (x != null) { - cm.curOp.scrollLeft = x; - } - if (y != null) { - cm.curOp.scrollTop = y; - } - } - function scrollToRange(cm, range) { - resolveScrollToPos(cm); - cm.curOp.scrollToPos = range; - } - - // When an operation has its scrollToPos property set, and another - // scroll action is applied before the end of the operation, this - // 'simulates' scrolling that position into view in a cheap way, so - // that the effect of intermediate scroll commands is not ignored. - function resolveScrollToPos(cm) { - var range = cm.curOp.scrollToPos; - if (range) { - cm.curOp.scrollToPos = null; - var from = estimateCoords(cm, range.from), - to = estimateCoords(cm, range.to); - scrollToCoordsRange(cm, from, to, range.margin); - } - } - function scrollToCoordsRange(cm, from, to, margin) { - var sPos = calculateScrollPos(cm, { - left: Math.min(from.left, to.left), - top: Math.min(from.top, to.top) - margin, - right: Math.max(from.right, to.right), - bottom: Math.max(from.bottom, to.bottom) + margin - }); - scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop); - } - - // Sync the scrollable area and scrollbars, ensure the viewport - // covers the visible area. - function updateScrollTop(cm, val) { - if (Math.abs(cm.doc.scrollTop - val) < 2) { - return; - } - if (!gecko) { - updateDisplaySimple(cm, { - top: val - }); - } - setScrollTop(cm, val, true); - if (gecko) { - updateDisplaySimple(cm); - } - startWorker(cm, 100); - } - function setScrollTop(cm, val, forceScroll) { - val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val)); - if (cm.display.scroller.scrollTop == val && !forceScroll) { - return; - } - cm.doc.scrollTop = val; - cm.display.scrollbars.setScrollTop(val); - if (cm.display.scroller.scrollTop != val) { - cm.display.scroller.scrollTop = val; - } - } - - // Sync scroller and scrollbar, ensure the gutter elements are - // aligned. - function setScrollLeft(cm, val, isScroller, forceScroll) { - val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth)); - if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { - return; - } - cm.doc.scrollLeft = val; - alignHorizontally(cm); - if (cm.display.scroller.scrollLeft != val) { - cm.display.scroller.scrollLeft = val; - } - cm.display.scrollbars.setScrollLeft(val); - } - - // SCROLLBARS - - // Prepare DOM reads needed to update the scrollbars. Done in one - // shot to minimize update/measure roundtrips. - function measureForScrollbars(cm) { - var d = cm.display, - gutterW = d.gutters.offsetWidth; - var docH = Math.round(cm.doc.height + paddingVert(cm.display)); - return { - clientHeight: d.scroller.clientHeight, - viewHeight: d.wrapper.clientHeight, - scrollWidth: d.scroller.scrollWidth, - clientWidth: d.scroller.clientWidth, - viewWidth: d.wrapper.clientWidth, - barLeft: cm.options.fixedGutter ? gutterW : 0, - docHeight: docH, - scrollHeight: docH + scrollGap(cm) + d.barHeight, - nativeBarWidth: d.nativeBarWidth, - gutterWidth: gutterW - }; - } - var NativeScrollbars = function (place, scroll, cm) { - this.cm = cm; - var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); - var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); - vert.tabIndex = horiz.tabIndex = -1; - place(vert); - place(horiz); - on(vert, "scroll", function () { - if (vert.clientHeight) { - scroll(vert.scrollTop, "vertical"); - } - }); - on(horiz, "scroll", function () { - if (horiz.clientWidth) { - scroll(horiz.scrollLeft, "horizontal"); - } - }); - this.checkedZeroWidth = false; - // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). - if (ie && ie_version < 8) { - this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; - } - }; - NativeScrollbars.prototype.update = function (measure) { - var needsH = measure.scrollWidth > measure.clientWidth + 1; - var needsV = measure.scrollHeight > measure.clientHeight + 1; - var sWidth = measure.nativeBarWidth; - if (needsV) { - this.vert.style.display = "block"; - this.vert.style.bottom = needsH ? sWidth + "px" : "0"; - var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); - // A bug in IE8 can cause this value to be negative, so guard it. - this.vert.firstChild.style.height = Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; - } else { - this.vert.scrollTop = 0; - this.vert.style.display = ""; - this.vert.firstChild.style.height = "0"; - } - if (needsH) { - this.horiz.style.display = "block"; - this.horiz.style.right = needsV ? sWidth + "px" : "0"; - this.horiz.style.left = measure.barLeft + "px"; - var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); - this.horiz.firstChild.style.width = Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; - } else { - this.horiz.style.display = ""; - this.horiz.firstChild.style.width = "0"; - } - if (!this.checkedZeroWidth && measure.clientHeight > 0) { - if (sWidth == 0) { - this.zeroWidthHack(); - } - this.checkedZeroWidth = true; - } - return { - right: needsV ? sWidth : 0, - bottom: needsH ? sWidth : 0 - }; - }; - NativeScrollbars.prototype.setScrollLeft = function (pos) { - if (this.horiz.scrollLeft != pos) { - this.horiz.scrollLeft = pos; - } - if (this.disableHoriz) { - this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); - } - }; - NativeScrollbars.prototype.setScrollTop = function (pos) { - if (this.vert.scrollTop != pos) { - this.vert.scrollTop = pos; - } - if (this.disableVert) { - this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); - } - }; - NativeScrollbars.prototype.zeroWidthHack = function () { - var w = mac && !mac_geMountainLion ? "12px" : "18px"; - this.horiz.style.height = this.vert.style.width = w; - this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"; - this.disableHoriz = new Delayed(); - this.disableVert = new Delayed(); - }; - NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) { - bar.style.pointerEvents = "auto"; - function maybeDisable() { - // To find out whether the scrollbar is still visible, we - // check whether the element under the pixel in the bottom - // right corner of the scrollbar box is the scrollbar box - // itself (when the bar is still visible) or its filler child - // (when the bar is hidden). If it is still visible, we keep - // it enabled, if it's hidden, we disable pointer events. - var box = bar.getBoundingClientRect(); - var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2) : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1); - if (elt != bar) { - bar.style.pointerEvents = "none"; - } else { - delay.set(1000, maybeDisable); - } - } - delay.set(1000, maybeDisable); - }; - NativeScrollbars.prototype.clear = function () { - var parent = this.horiz.parentNode; - parent.removeChild(this.horiz); - parent.removeChild(this.vert); - }; - var NullScrollbars = function () {}; - NullScrollbars.prototype.update = function () { - return { - bottom: 0, - right: 0 - }; - }; - NullScrollbars.prototype.setScrollLeft = function () {}; - NullScrollbars.prototype.setScrollTop = function () {}; - NullScrollbars.prototype.clear = function () {}; - function updateScrollbars(cm, measure) { - if (!measure) { - measure = measureForScrollbars(cm); - } - var startWidth = cm.display.barWidth, - startHeight = cm.display.barHeight; - updateScrollbarsInner(cm, measure); - for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { - if (startWidth != cm.display.barWidth && cm.options.lineWrapping) { - updateHeightsInViewport(cm); - } - updateScrollbarsInner(cm, measureForScrollbars(cm)); - startWidth = cm.display.barWidth; - startHeight = cm.display.barHeight; - } - } - - // Re-synchronize the fake scrollbars with the actual size of the - // content. - function updateScrollbarsInner(cm, measure) { - var d = cm.display; - var sizes = d.scrollbars.update(measure); - d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; - d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; - d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"; - if (sizes.right && sizes.bottom) { - d.scrollbarFiller.style.display = "block"; - d.scrollbarFiller.style.height = sizes.bottom + "px"; - d.scrollbarFiller.style.width = sizes.right + "px"; - } else { - d.scrollbarFiller.style.display = ""; - } - if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { - d.gutterFiller.style.display = "block"; - d.gutterFiller.style.height = sizes.bottom + "px"; - d.gutterFiller.style.width = measure.gutterWidth + "px"; - } else { - d.gutterFiller.style.display = ""; - } - } - var scrollbarModel = { - "native": NativeScrollbars, - "null": NullScrollbars - }; - function initScrollbars(cm) { - if (cm.display.scrollbars) { - cm.display.scrollbars.clear(); - if (cm.display.scrollbars.addClass) { - rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); - } - } - cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) { - cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); - // Prevent clicks in the scrollbars from killing focus - on(node, "mousedown", function () { - if (cm.state.focused) { - setTimeout(function () { - return cm.display.input.focus(); - }, 0); - } - }); - node.setAttribute("cm-not-content", "true"); - }, function (pos, axis) { - if (axis == "horizontal") { - setScrollLeft(cm, pos); - } else { - updateScrollTop(cm, pos); - } - }, cm); - if (cm.display.scrollbars.addClass) { - addClass(cm.display.wrapper, cm.display.scrollbars.addClass); - } - } - - // Operations are used to wrap a series of changes to the editor - // state in such a way that each change won't have to update the - // cursor and display (which would be awkward, slow, and - // error-prone). Instead, display updates are batched and then all - // combined and executed at once. - - var nextOpId = 0; - // Start a new operation. - function startOperation(cm) { - cm.curOp = { - cm: cm, - viewChanged: false, - // Flag that indicates that lines might need to be redrawn - startHeight: cm.doc.height, - // Used to detect need to update scrollbar - forceUpdate: false, - // Used to force a redraw - updateInput: 0, - // Whether to reset the input textarea - typing: false, - // Whether this reset should be careful to leave existing text (for compositing) - changeObjs: null, - // Accumulated changes, for firing change events - cursorActivityHandlers: null, - // Set of handlers to fire cursorActivity on - cursorActivityCalled: 0, - // Tracks which cursorActivity handlers have been called already - selectionChanged: false, - // Whether the selection needs to be redrawn - updateMaxLine: false, - // Set when the widest line needs to be determined anew - scrollLeft: null, - scrollTop: null, - // Intermediate scroll position, not pushed to DOM yet - scrollToPos: null, - // Used to scroll to a specific position - focus: false, - id: ++nextOpId, - // Unique ID - markArrays: null // Used by addMarkedSpan - }; - pushOperation(cm.curOp); - } - - // Finish an operation, updating the display and signalling delayed events - function endOperation(cm) { - var op = cm.curOp; - if (op) { - finishOperation(op, function (group) { - for (var i = 0; i < group.ops.length; i++) { - group.ops[i].cm.curOp = null; - } - endOperations(group); - }); - } - } - - // The DOM updates done when an operation finishes are batched so - // that the minimum number of relayouts are required. - function endOperations(group) { - var ops = group.ops; - for (var i = 0; i < ops.length; i++) - // Read DOM - { - endOperation_R1(ops[i]); - } - for (var i$1 = 0; i$1 < ops.length; i$1++) - // Write DOM (maybe) - { - endOperation_W1(ops[i$1]); - } - for (var i$2 = 0; i$2 < ops.length; i$2++) - // Read DOM - { - endOperation_R2(ops[i$2]); - } - for (var i$3 = 0; i$3 < ops.length; i$3++) - // Write DOM (maybe) - { - endOperation_W2(ops[i$3]); - } - for (var i$4 = 0; i$4 < ops.length; i$4++) - // Read DOM - { - endOperation_finish(ops[i$4]); - } - } - function endOperation_R1(op) { - var cm = op.cm, - display = cm.display; - maybeClipScrollbars(cm); - if (op.updateMaxLine) { - findMaxLine(cm); - } - op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || op.scrollToPos.to.line >= display.viewTo) || display.maxLineChanged && cm.options.lineWrapping; - op.update = op.mustUpdate && new DisplayUpdate(cm, op.mustUpdate && { - top: op.scrollTop, - ensure: op.scrollToPos - }, op.forceUpdate); - } - function endOperation_W1(op) { - op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); - } - function endOperation_R2(op) { - var cm = op.cm, - display = cm.display; - if (op.updatedDisplay) { - updateHeightsInViewport(cm); - } - op.barMeasure = measureForScrollbars(cm); - - // If the max line changed since it was last measured, measure it, - // and ensure the document's width matches it. - // updateDisplay_W2 will use these properties to do the actual resizing - if (display.maxLineChanged && !cm.options.lineWrapping) { - op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; - cm.display.sizerWidth = op.adjustWidthTo; - op.barMeasure.scrollWidth = Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); - op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); - } - if (op.updatedDisplay || op.selectionChanged) { - op.preparedSelection = display.input.prepareSelection(); - } - } - function endOperation_W2(op) { - var cm = op.cm; - if (op.adjustWidthTo != null) { - cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; - if (op.maxScrollLeft < cm.doc.scrollLeft) { - setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); - } - cm.display.maxLineChanged = false; - } - var takeFocus = op.focus && op.focus == activeElt(); - if (op.preparedSelection) { - cm.display.input.showSelection(op.preparedSelection, takeFocus); - } - if (op.updatedDisplay || op.startHeight != cm.doc.height) { - updateScrollbars(cm, op.barMeasure); - } - if (op.updatedDisplay) { - setDocumentHeight(cm, op.barMeasure); - } - if (op.selectionChanged) { - restartBlink(cm); - } - if (cm.state.focused && op.updateInput) { - cm.display.input.reset(op.typing); - } - if (takeFocus) { - ensureFocus(op.cm); - } - } - function endOperation_finish(op) { - var cm = op.cm, - display = cm.display, - doc = cm.doc; - if (op.updatedDisplay) { - postUpdateDisplay(cm, op.update); - } - - // Abort mouse wheel delta measurement, when scrolling explicitly - if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) { - display.wheelStartX = display.wheelStartY = null; - } - - // Propagate the scroll position to the actual DOM scroller - if (op.scrollTop != null) { - setScrollTop(cm, op.scrollTop, op.forceScroll); - } - if (op.scrollLeft != null) { - setScrollLeft(cm, op.scrollLeft, true, true); - } - // If we need to scroll a specific position into view, do so. - if (op.scrollToPos) { - var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); - maybeScrollWindow(cm, rect); - } - - // Fire events for markers that are hidden/unidden by editing or - // undoing - var hidden = op.maybeHiddenMarkers, - unhidden = op.maybeUnhiddenMarkers; - if (hidden) { - for (var i = 0; i < hidden.length; ++i) { - if (!hidden[i].lines.length) { - signal(hidden[i], "hide"); - } - } - } - if (unhidden) { - for (var i$1 = 0; i$1 < unhidden.length; ++i$1) { - if (unhidden[i$1].lines.length) { - signal(unhidden[i$1], "unhide"); - } - } - } - if (display.wrapper.offsetHeight) { - doc.scrollTop = cm.display.scroller.scrollTop; - } - - // Fire change events, and delayed event handlers - if (op.changeObjs) { - signal(cm, "changes", cm, op.changeObjs); - } - if (op.update) { - op.update.finish(); - } - } - - // Run the given function in an operation - function runInOp(cm, f) { - if (cm.curOp) { - return f(); - } - startOperation(cm); - try { - return f(); - } finally { - endOperation(cm); - } - } - // Wraps a function in an operation. Returns the wrapped function. - function operation(cm, f) { - return function () { - if (cm.curOp) { - return f.apply(cm, arguments); - } - startOperation(cm); - try { - return f.apply(cm, arguments); - } finally { - endOperation(cm); - } - }; - } - // Used to add methods to editor and doc instances, wrapping them in - // operations. - function methodOp(f) { - return function () { - if (this.curOp) { - return f.apply(this, arguments); - } - startOperation(this); - try { - return f.apply(this, arguments); - } finally { - endOperation(this); - } - }; - } - function docMethodOp(f) { - return function () { - var cm = this.cm; - if (!cm || cm.curOp) { - return f.apply(this, arguments); - } - startOperation(cm); - try { - return f.apply(this, arguments); - } finally { - endOperation(cm); - } - }; - } - - // HIGHLIGHT WORKER - - function startWorker(cm, time) { - if (cm.doc.highlightFrontier < cm.display.viewTo) { - cm.state.highlight.set(time, bind(highlightWorker, cm)); - } - } - function highlightWorker(cm) { - var doc = cm.doc; - if (doc.highlightFrontier >= cm.display.viewTo) { - return; - } - var end = +new Date() + cm.options.workTime; - var context = getContextBefore(cm, doc.highlightFrontier); - var changedLines = []; - doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) { - if (context.line >= cm.display.viewFrom) { - // Visible - var oldStyles = line.styles; - var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null; - var highlighted = highlightLine(cm, line, context, true); - if (resetState) { - context.state = resetState; - } - line.styles = highlighted.styles; - var oldCls = line.styleClasses, - newCls = highlighted.classes; - if (newCls) { - line.styleClasses = newCls; - } else if (oldCls) { - line.styleClasses = null; - } - var ischange = !oldStyles || oldStyles.length != line.styles.length || oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); - for (var i = 0; !ischange && i < oldStyles.length; ++i) { - ischange = oldStyles[i] != line.styles[i]; - } - if (ischange) { - changedLines.push(context.line); - } - line.stateAfter = context.save(); - context.nextLine(); - } else { - if (line.text.length <= cm.options.maxHighlightLength) { - processLine(cm, line.text, context); - } - line.stateAfter = context.line % 5 == 0 ? context.save() : null; - context.nextLine(); - } - if (+new Date() > end) { - startWorker(cm, cm.options.workDelay); - return true; - } - }); - doc.highlightFrontier = context.line; - doc.modeFrontier = Math.max(doc.modeFrontier, context.line); - if (changedLines.length) { - runInOp(cm, function () { - for (var i = 0; i < changedLines.length; i++) { - regLineChange(cm, changedLines[i], "text"); - } - }); - } - } - - // DISPLAY DRAWING - - var DisplayUpdate = function (cm, viewport, force) { - var display = cm.display; - this.viewport = viewport; - // Store some values that we'll need later (but don't want to force a relayout for) - this.visible = visibleLines(display, cm.doc, viewport); - this.editorIsHidden = !display.wrapper.offsetWidth; - this.wrapperHeight = display.wrapper.clientHeight; - this.wrapperWidth = display.wrapper.clientWidth; - this.oldDisplayWidth = displayWidth(cm); - this.force = force; - this.dims = getDimensions(cm); - this.events = []; - }; - DisplayUpdate.prototype.signal = function (emitter, type) { - if (hasHandler(emitter, type)) { - this.events.push(arguments); - } - }; - DisplayUpdate.prototype.finish = function () { - for (var i = 0; i < this.events.length; i++) { - signal.apply(null, this.events[i]); - } - }; - function maybeClipScrollbars(cm) { - var display = cm.display; - if (!display.scrollbarsClipped && display.scroller.offsetWidth) { - display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; - display.heightForcer.style.height = scrollGap(cm) + "px"; - display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; - display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; - display.scrollbarsClipped = true; - } - } - function selectionSnapshot(cm) { - if (cm.hasFocus()) { - return null; - } - var active = activeElt(); - if (!active || !contains(cm.display.lineDiv, active)) { - return null; - } - var result = { - activeElt: active - }; - if (window.getSelection) { - var sel = window.getSelection(); - if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) { - result.anchorNode = sel.anchorNode; - result.anchorOffset = sel.anchorOffset; - result.focusNode = sel.focusNode; - result.focusOffset = sel.focusOffset; - } - } - return result; - } - function restoreSelection(snapshot) { - if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { - return; - } - snapshot.activeElt.focus(); - if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) && snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) { - var sel = window.getSelection(), - range = document.createRange(); - range.setEnd(snapshot.anchorNode, snapshot.anchorOffset); - range.collapse(false); - sel.removeAllRanges(); - sel.addRange(range); - sel.extend(snapshot.focusNode, snapshot.focusOffset); - } - } - - // Does the actual updating of the line display. Bails out - // (returning false) when there is nothing to be done and forced is - // false. - function updateDisplayIfNeeded(cm, update) { - var display = cm.display, - doc = cm.doc; - if (update.editorIsHidden) { - resetView(cm); - return false; - } - - // Bail out if the visible area is already rendered and nothing changed. - if (!update.force && update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && display.renderedView == display.view && countDirtyView(cm) == 0) { - return false; - } - if (maybeUpdateLineNumberWidth(cm)) { - resetView(cm); - update.dims = getDimensions(cm); - } - - // Compute a suitable new viewport (from & to) - var end = doc.first + doc.size; - var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); - var to = Math.min(end, update.visible.to + cm.options.viewportMargin); - if (display.viewFrom < from && from - display.viewFrom < 20) { - from = Math.max(doc.first, display.viewFrom); - } - if (display.viewTo > to && display.viewTo - to < 20) { - to = Math.min(end, display.viewTo); - } - if (sawCollapsedSpans) { - from = visualLineNo(cm.doc, from); - to = visualLineEndNo(cm.doc, to); - } - var different = from != display.viewFrom || to != display.viewTo || display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; - adjustView(cm, from, to); - display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); - // Position the mover div to align with the current scroll position - cm.display.mover.style.top = display.viewOffset + "px"; - var toUpdate = countDirtyView(cm); - if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) { - return false; - } - - // For big changes, we hide the enclosing element during the - // update, since that speeds up the operations on most browsers. - var selSnapshot = selectionSnapshot(cm); - if (toUpdate > 4) { - display.lineDiv.style.display = "none"; - } - patchDisplay(cm, display.updateLineNumbers, update.dims); - if (toUpdate > 4) { - display.lineDiv.style.display = ""; - } - display.renderedView = display.view; - // There might have been a widget with a focused element that got - // hidden or updated, if so re-focus it. - restoreSelection(selSnapshot); - - // Prevent selection and cursors from interfering with the scroll - // width and height. - removeChildren(display.cursorDiv); - removeChildren(display.selectionDiv); - display.gutters.style.height = display.sizer.style.minHeight = 0; - if (different) { - display.lastWrapHeight = update.wrapperHeight; - display.lastWrapWidth = update.wrapperWidth; - startWorker(cm, 400); - } - display.updateLineNumbers = null; - return true; - } - function postUpdateDisplay(cm, update) { - var viewport = update.viewport; - for (var first = true;; first = false) { - if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { - // Clip forced viewport to actual scrollable area. - if (viewport && viewport.top != null) { - viewport = { - top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top) - }; - } - // Updated line heights might result in the drawn area not - // actually covering the viewport. Keep looping until it does. - update.visible = visibleLines(cm.display, cm.doc, viewport); - if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) { - break; - } - } else if (first) { - update.visible = visibleLines(cm.display, cm.doc, viewport); - } - if (!updateDisplayIfNeeded(cm, update)) { - break; - } - updateHeightsInViewport(cm); - var barMeasure = measureForScrollbars(cm); - updateSelection(cm); - updateScrollbars(cm, barMeasure); - setDocumentHeight(cm, barMeasure); - update.force = false; - } - update.signal(cm, "update", cm); - if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { - update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); - cm.display.reportedViewFrom = cm.display.viewFrom; - cm.display.reportedViewTo = cm.display.viewTo; - } - } - function updateDisplaySimple(cm, viewport) { - var update = new DisplayUpdate(cm, viewport); - if (updateDisplayIfNeeded(cm, update)) { - updateHeightsInViewport(cm); - postUpdateDisplay(cm, update); - var barMeasure = measureForScrollbars(cm); - updateSelection(cm); - updateScrollbars(cm, barMeasure); - setDocumentHeight(cm, barMeasure); - update.finish(); - } - } - - // Sync the actual display DOM structure with display.view, removing - // nodes for lines that are no longer in view, and creating the ones - // that are not there yet, and updating the ones that are out of - // date. - function patchDisplay(cm, updateNumbersFrom, dims) { - var display = cm.display, - lineNumbers = cm.options.lineNumbers; - var container = display.lineDiv, - cur = container.firstChild; - function rm(node) { - var next = node.nextSibling; - // Works around a throw-scroll bug in OS X Webkit - if (webkit && mac && cm.display.currentWheelTarget == node) { - node.style.display = "none"; - } else { - node.parentNode.removeChild(node); - } - return next; - } - var view = display.view, - lineN = display.viewFrom; - // Loop over the elements in the view, syncing cur (the DOM nodes - // in display.lineDiv) with the view as we go. - for (var i = 0; i < view.length; i++) { - var lineView = view[i]; - if (lineView.hidden) ;else if (!lineView.node || lineView.node.parentNode != container) { - // Not drawn yet - var node = buildLineElement(cm, lineView, lineN, dims); - container.insertBefore(node, cur); - } else { - // Already drawn - while (cur != lineView.node) { - cur = rm(cur); - } - var updateNumber = lineNumbers && updateNumbersFrom != null && updateNumbersFrom <= lineN && lineView.lineNumber; - if (lineView.changes) { - if (indexOf(lineView.changes, "gutter") > -1) { - updateNumber = false; - } - updateLineForChanges(cm, lineView, lineN, dims); - } - if (updateNumber) { - removeChildren(lineView.lineNumber); - lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); - } - cur = lineView.node.nextSibling; - } - lineN += lineView.size; - } - while (cur) { - cur = rm(cur); - } - } - function updateGutterSpace(display) { - var width = display.gutters.offsetWidth; - display.sizer.style.marginLeft = width + "px"; - // Send an event to consumers responding to changes in gutter width. - signalLater(display, "gutterChanged", display); - } - function setDocumentHeight(cm, measure) { - cm.display.sizer.style.minHeight = measure.docHeight + "px"; - cm.display.heightForcer.style.top = measure.docHeight + "px"; - cm.display.gutters.style.height = measure.docHeight + cm.display.barHeight + scrollGap(cm) + "px"; - } - - // Re-align line numbers and gutter marks to compensate for - // horizontal scrolling. - function alignHorizontally(cm) { - var display = cm.display, - view = display.view; - if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { - return; - } - var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; - var gutterW = display.gutters.offsetWidth, - left = comp + "px"; - for (var i = 0; i < view.length; i++) { - if (!view[i].hidden) { - if (cm.options.fixedGutter) { - if (view[i].gutter) { - view[i].gutter.style.left = left; - } - if (view[i].gutterBackground) { - view[i].gutterBackground.style.left = left; - } - } - var align = view[i].alignable; - if (align) { - for (var j = 0; j < align.length; j++) { - align[j].style.left = left; - } - } - } - } - if (cm.options.fixedGutter) { - display.gutters.style.left = comp + gutterW + "px"; - } - } - - // Used to ensure that the line number gutter is still the right - // size for the current document size. Returns true when an update - // is needed. - function maybeUpdateLineNumberWidth(cm) { - if (!cm.options.lineNumbers) { - return false; - } - var doc = cm.doc, - last = lineNumberFor(cm.options, doc.first + doc.size - 1), - display = cm.display; - if (last.length != display.lineNumChars) { - var test = display.measure.appendChild(elt("div", [elt("div", last)], "CodeMirror-linenumber CodeMirror-gutter-elt")); - var innerW = test.firstChild.offsetWidth, - padding = test.offsetWidth - innerW; - display.lineGutter.style.width = ""; - display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; - display.lineNumWidth = display.lineNumInnerWidth + padding; - display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; - display.lineGutter.style.width = display.lineNumWidth + "px"; - updateGutterSpace(cm.display); - return true; - } - return false; - } - function getGutters(gutters, lineNumbers) { - var result = [], - sawLineNumbers = false; - for (var i = 0; i < gutters.length; i++) { - var name = gutters[i], - style = null; - if (typeof name != "string") { - style = name.style; - name = name.className; - } - if (name == "CodeMirror-linenumbers") { - if (!lineNumbers) { - continue; - } else { - sawLineNumbers = true; - } - } - result.push({ - className: name, - style: style - }); - } - if (lineNumbers && !sawLineNumbers) { - result.push({ - className: "CodeMirror-linenumbers", - style: null - }); - } - return result; - } - - // Rebuild the gutter elements, ensure the margin to the left of the - // code matches their width. - function renderGutters(display) { - var gutters = display.gutters, - specs = display.gutterSpecs; - removeChildren(gutters); - display.lineGutter = null; - for (var i = 0; i < specs.length; ++i) { - var ref = specs[i]; - var className = ref.className; - var style = ref.style; - var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className)); - if (style) { - gElt.style.cssText = style; - } - if (className == "CodeMirror-linenumbers") { - display.lineGutter = gElt; - gElt.style.width = (display.lineNumWidth || 1) + "px"; - } - } - gutters.style.display = specs.length ? "" : "none"; - updateGutterSpace(display); - } - function updateGutters(cm) { - renderGutters(cm.display); - regChange(cm); - alignHorizontally(cm); - } - - // The display handles the DOM integration, both for input reading - // and content drawing. It holds references to DOM nodes and - // display-related state. - - function Display(place, doc, input, options) { - var d = this; - this.input = input; - - // Covers bottom-right square when both scrollbars are present. - d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); - d.scrollbarFiller.setAttribute("cm-not-content", "true"); - // Covers bottom of gutter when coverGutterNextToScrollbar is on - // and h scrollbar is present. - d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); - d.gutterFiller.setAttribute("cm-not-content", "true"); - // Will contain the actual code, positioned to cover the viewport. - d.lineDiv = eltP("div", null, "CodeMirror-code"); - // Elements are added to these to represent selection and cursors. - d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); - d.cursorDiv = elt("div", null, "CodeMirror-cursors"); - // A visibility: hidden element used to find the size of things. - d.measure = elt("div", null, "CodeMirror-measure"); - // When lines outside of the viewport are measured, they are drawn in this. - d.lineMeasure = elt("div", null, "CodeMirror-measure"); - // Wraps everything that needs to exist inside the vertically-padded coordinate system - d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], null, "position: relative; outline: none"); - var lines = eltP("div", [d.lineSpace], "CodeMirror-lines"); - // Moved around its parent to cover visible view. - d.mover = elt("div", [lines], null, "position: relative"); - // Set to the height of the document, allowing scrolling. - d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); - d.sizerWidth = null; - // Behavior of elts with overflow: auto and padding is - // inconsistent across browsers. This is used to ensure the - // scrollable area is big enough. - d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); - // Will contain the gutters, if any. - d.gutters = elt("div", null, "CodeMirror-gutters"); - d.lineGutter = null; - // Actual scrollable element. - d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); - d.scroller.setAttribute("tabIndex", "-1"); - // The element in which the editor lives. - d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); - - // This attribute is respected by automatic translation systems such as Google Translate, - // and may also be respected by tools used by human translators. - d.wrapper.setAttribute('translate', 'no'); - - // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) - if (ie && ie_version < 8) { - d.gutters.style.zIndex = -1; - d.scroller.style.paddingRight = 0; - } - if (!webkit && !(gecko && mobile)) { - d.scroller.draggable = true; - } - if (place) { - if (place.appendChild) { - place.appendChild(d.wrapper); - } else { - place(d.wrapper); - } - } - - // Current rendered range (may be bigger than the view window). - d.viewFrom = d.viewTo = doc.first; - d.reportedViewFrom = d.reportedViewTo = doc.first; - // Information about the rendered lines. - d.view = []; - d.renderedView = null; - // Holds info about a single rendered line when it was rendered - // for measurement, while not in view. - d.externalMeasured = null; - // Empty space (in pixels) above the view - d.viewOffset = 0; - d.lastWrapHeight = d.lastWrapWidth = 0; - d.updateLineNumbers = null; - d.nativeBarWidth = d.barHeight = d.barWidth = 0; - d.scrollbarsClipped = false; - - // Used to only resize the line number gutter when necessary (when - // the amount of lines crosses a boundary that makes its width change) - d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; - // Set to true when a non-horizontal-scrolling line widget is - // added. As an optimization, line widget aligning is skipped when - // this is false. - d.alignWidgets = false; - d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; - - // Tracks the maximum line length so that the horizontal scrollbar - // can be kept static when scrolling. - d.maxLine = null; - d.maxLineLength = 0; - d.maxLineChanged = false; - - // Used for measuring wheel scrolling granularity - d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; - - // True when shift is held down. - d.shift = false; - - // Used to track whether anything happened since the context menu - // was opened. - d.selForContextMenu = null; - d.activeTouch = null; - d.gutterSpecs = getGutters(options.gutters, options.lineNumbers); - renderGutters(d); - input.init(d); - } - - // Since the delta values reported on mouse wheel events are - // unstandardized between browsers and even browser versions, and - // generally horribly unpredictable, this code starts by measuring - // the scroll effect that the first few mouse wheel events have, - // and, from that, detects the way it can convert deltas to pixel - // offsets afterwards. - // - // The reason we want to know the amount a wheel event will scroll - // is that it gives us a chance to update the display before the - // actual scrolling happens, reducing flickering. - - var wheelSamples = 0, - wheelPixelsPerUnit = null; - // Fill in a browser-detected starting value on browsers where we - // know one. These don't have to be accurate -- the result of them - // being wrong would just be a slight flicker on the first wheel - // scroll (if it is large enough). - if (ie) { - wheelPixelsPerUnit = -.53; - } else if (gecko) { - wheelPixelsPerUnit = 15; - } else if (chrome) { - wheelPixelsPerUnit = -.7; - } else if (safari) { - wheelPixelsPerUnit = -1 / 3; - } - function wheelEventDelta(e) { - var dx = e.wheelDeltaX, - dy = e.wheelDeltaY; - if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { - dx = e.detail; - } - if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { - dy = e.detail; - } else if (dy == null) { - dy = e.wheelDelta; - } - return { - x: dx, - y: dy - }; - } - function wheelEventPixels(e) { - var delta = wheelEventDelta(e); - delta.x *= wheelPixelsPerUnit; - delta.y *= wheelPixelsPerUnit; - return delta; - } - function onScrollWheel(cm, e) { - var delta = wheelEventDelta(e), - dx = delta.x, - dy = delta.y; - var pixelsPerUnit = wheelPixelsPerUnit; - if (e.deltaMode === 0) { - dx = e.deltaX; - dy = e.deltaY; - pixelsPerUnit = 1; - } - var display = cm.display, - scroll = display.scroller; - // Quit if there's nothing to scroll here - var canScrollX = scroll.scrollWidth > scroll.clientWidth; - var canScrollY = scroll.scrollHeight > scroll.clientHeight; - if (!(dx && canScrollX || dy && canScrollY)) { - return; - } - - // Webkit browsers on OS X abort momentum scrolls when the target - // of the scroll event is removed from the scrollable element. - // This hack (see related code in patchDisplay) makes sure the - // element is kept around. - if (dy && mac && webkit) { - outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { - for (var i = 0; i < view.length; i++) { - if (view[i].node == cur) { - cm.display.currentWheelTarget = cur; - break outer; - } - } - } - } - - // On some browsers, horizontal scrolling will cause redraws to - // happen before the gutter has been realigned, causing it to - // wriggle around in a most unseemly way. When we have an - // estimated pixels/delta value, we just handle horizontal - // scrolling entirely here. It'll be slightly off from native, but - // better than glitching out. - if (dx && !gecko && !presto && pixelsPerUnit != null) { - if (dy && canScrollY) { - updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * pixelsPerUnit)); - } - setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * pixelsPerUnit)); - // Only prevent default scrolling if vertical scrolling is - // actually possible. Otherwise, it causes vertical scroll - // jitter on OSX trackpads when deltaX is small and deltaY - // is large (issue #3579) - if (!dy || dy && canScrollY) { - e_preventDefault(e); - } - display.wheelStartX = null; // Abort measurement, if in progress - return; - } - - // 'Project' the visible viewport to cover the area that is being - // scrolled into view (if we know enough to estimate it). - if (dy && pixelsPerUnit != null) { - var pixels = dy * pixelsPerUnit; - var top = cm.doc.scrollTop, - bot = top + display.wrapper.clientHeight; - if (pixels < 0) { - top = Math.max(0, top + pixels - 50); - } else { - bot = Math.min(cm.doc.height, bot + pixels + 50); - } - updateDisplaySimple(cm, { - top: top, - bottom: bot - }); - } - if (wheelSamples < 20 && e.deltaMode !== 0) { - if (display.wheelStartX == null) { - display.wheelStartX = scroll.scrollLeft; - display.wheelStartY = scroll.scrollTop; - display.wheelDX = dx; - display.wheelDY = dy; - setTimeout(function () { - if (display.wheelStartX == null) { - return; - } - var movedX = scroll.scrollLeft - display.wheelStartX; - var movedY = scroll.scrollTop - display.wheelStartY; - var sample = movedY && display.wheelDY && movedY / display.wheelDY || movedX && display.wheelDX && movedX / display.wheelDX; - display.wheelStartX = display.wheelStartY = null; - if (!sample) { - return; - } - wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); - ++wheelSamples; - }, 200); - } else { - display.wheelDX += dx; - display.wheelDY += dy; - } - } - } - - // Selection objects are immutable. A new one is created every time - // the selection changes. A selection is one or more non-overlapping - // (and non-touching) ranges, sorted, and an integer that indicates - // which one is the primary selection (the one that's scrolled into - // view, that getCursor returns, etc). - var Selection = function (ranges, primIndex) { - this.ranges = ranges; - this.primIndex = primIndex; - }; - Selection.prototype.primary = function () { - return this.ranges[this.primIndex]; - }; - Selection.prototype.equals = function (other) { - if (other == this) { - return true; - } - if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { - return false; - } - for (var i = 0; i < this.ranges.length; i++) { - var here = this.ranges[i], - there = other.ranges[i]; - if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { - return false; - } - } - return true; - }; - Selection.prototype.deepCopy = function () { - var out = []; - for (var i = 0; i < this.ranges.length; i++) { - out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); - } - return new Selection(out, this.primIndex); - }; - Selection.prototype.somethingSelected = function () { - for (var i = 0; i < this.ranges.length; i++) { - if (!this.ranges[i].empty()) { - return true; - } - } - return false; - }; - Selection.prototype.contains = function (pos, end) { - if (!end) { - end = pos; - } - for (var i = 0; i < this.ranges.length; i++) { - var range = this.ranges[i]; - if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) { - return i; - } - } - return -1; - }; - var Range = function (anchor, head) { - this.anchor = anchor; - this.head = head; - }; - Range.prototype.from = function () { - return minPos(this.anchor, this.head); - }; - Range.prototype.to = function () { - return maxPos(this.anchor, this.head); - }; - Range.prototype.empty = function () { - return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch; - }; - - // Take an unsorted, potentially overlapping set of ranges, and - // build a selection out of it. 'Consumes' ranges array (modifying - // it). - function normalizeSelection(cm, ranges, primIndex) { - var mayTouch = cm && cm.options.selectionsMayTouch; - var prim = ranges[primIndex]; - ranges.sort(function (a, b) { - return cmp(a.from(), b.from()); - }); - primIndex = indexOf(ranges, prim); - for (var i = 1; i < ranges.length; i++) { - var cur = ranges[i], - prev = ranges[i - 1]; - var diff = cmp(prev.to(), cur.from()); - if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) { - var from = minPos(prev.from(), cur.from()), - to = maxPos(prev.to(), cur.to()); - var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; - if (i <= primIndex) { - --primIndex; - } - ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); - } - } - return new Selection(ranges, primIndex); - } - function simpleSelection(anchor, head) { - return new Selection([new Range(anchor, head || anchor)], 0); - } - - // Compute the position of the end of a change (its 'to' property - // refers to the pre-change end). - function changeEnd(change) { - if (!change.text) { - return change.to; - } - return Pos(change.from.line + change.text.length - 1, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)); - } - - // Adjust a position to refer to the post-change position of the - // same text, or the end of the change if the change covers it. - function adjustForChange(pos, change) { - if (cmp(pos, change.from) < 0) { - return pos; - } - if (cmp(pos, change.to) <= 0) { - return changeEnd(change); - } - var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, - ch = pos.ch; - if (pos.line == change.to.line) { - ch += changeEnd(change).ch - change.to.ch; - } - return Pos(line, ch); - } - function computeSelAfterChange(doc, change) { - var out = []; - for (var i = 0; i < doc.sel.ranges.length; i++) { - var range = doc.sel.ranges[i]; - out.push(new Range(adjustForChange(range.anchor, change), adjustForChange(range.head, change))); - } - return normalizeSelection(doc.cm, out, doc.sel.primIndex); - } - function offsetPos(pos, old, nw) { - if (pos.line == old.line) { - return Pos(nw.line, pos.ch - old.ch + nw.ch); - } else { - return Pos(nw.line + (pos.line - old.line), pos.ch); - } - } - - // Used by replaceSelections to allow moving the selection to the - // start or around the replaced test. Hint may be "start" or "around". - function computeReplacedSel(doc, changes, hint) { - var out = []; - var oldPrev = Pos(doc.first, 0), - newPrev = oldPrev; - for (var i = 0; i < changes.length; i++) { - var change = changes[i]; - var from = offsetPos(change.from, oldPrev, newPrev); - var to = offsetPos(changeEnd(change), oldPrev, newPrev); - oldPrev = change.to; - newPrev = to; - if (hint == "around") { - var range = doc.sel.ranges[i], - inv = cmp(range.head, range.anchor) < 0; - out[i] = new Range(inv ? to : from, inv ? from : to); - } else { - out[i] = new Range(from, from); - } - } - return new Selection(out, doc.sel.primIndex); - } - - // Used to get the editor into a consistent state again when options change. - - function loadMode(cm) { - cm.doc.mode = getMode(cm.options, cm.doc.modeOption); - resetModeState(cm); - } - function resetModeState(cm) { - cm.doc.iter(function (line) { - if (line.stateAfter) { - line.stateAfter = null; - } - if (line.styles) { - line.styles = null; - } - }); - cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first; - startWorker(cm, 100); - cm.state.modeGen++; - if (cm.curOp) { - regChange(cm); - } - } - - // DOCUMENT DATA STRUCTURE - - // By default, updates that start and end at the beginning of a line - // are treated specially, in order to make the association of line - // widgets and marker elements with the text behave more intuitive. - function isWholeLineUpdate(doc, change) { - return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && (!doc.cm || doc.cm.options.wholeLineUpdateBefore); - } - - // Perform a change on the document data structure. - function updateDoc(doc, change, markedSpans, estimateHeight) { - function spansFor(n) { - return markedSpans ? markedSpans[n] : null; - } - function update(line, text, spans) { - updateLine(line, text, spans, estimateHeight); - signalLater(line, "change", line, change); - } - function linesFor(start, end) { - var result = []; - for (var i = start; i < end; ++i) { - result.push(new Line(text[i], spansFor(i), estimateHeight)); - } - return result; - } - var from = change.from, - to = change.to, - text = change.text; - var firstLine = getLine(doc, from.line), - lastLine = getLine(doc, to.line); - var lastText = lst(text), - lastSpans = spansFor(text.length - 1), - nlines = to.line - from.line; - - // Adjust the line structure - if (change.full) { - doc.insert(0, linesFor(0, text.length)); - doc.remove(text.length, doc.size - text.length); - } else if (isWholeLineUpdate(doc, change)) { - // This is a whole-line replace. Treated specially to make - // sure line objects move the way they are supposed to. - var added = linesFor(0, text.length - 1); - update(lastLine, lastLine.text, lastSpans); - if (nlines) { - doc.remove(from.line, nlines); - } - if (added.length) { - doc.insert(from.line, added); - } - } else if (firstLine == lastLine) { - if (text.length == 1) { - update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); - } else { - var added$1 = linesFor(1, text.length - 1); - added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight)); - update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); - doc.insert(from.line + 1, added$1); - } - } else if (text.length == 1) { - update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); - doc.remove(from.line + 1, nlines); - } else { - update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); - update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); - var added$2 = linesFor(1, text.length - 1); - if (nlines > 1) { - doc.remove(from.line + 1, nlines - 1); - } - doc.insert(from.line + 1, added$2); - } - signalLater(doc, "change", doc, change); - } - - // Call f for all linked documents. - function linkedDocs(doc, f, sharedHistOnly) { - function propagate(doc, skip, sharedHist) { - if (doc.linked) { - for (var i = 0; i < doc.linked.length; ++i) { - var rel = doc.linked[i]; - if (rel.doc == skip) { - continue; - } - var shared = sharedHist && rel.sharedHist; - if (sharedHistOnly && !shared) { - continue; - } - f(rel.doc, shared); - propagate(rel.doc, doc, shared); - } - } - } - propagate(doc, null, true); - } - - // Attach a document to an editor. - function attachDoc(cm, doc) { - if (doc.cm) { - throw new Error("This document is already in use."); - } - cm.doc = doc; - doc.cm = cm; - estimateLineHeights(cm); - loadMode(cm); - setDirectionClass(cm); - cm.options.direction = doc.direction; - if (!cm.options.lineWrapping) { - findMaxLine(cm); - } - cm.options.mode = doc.modeOption; - regChange(cm); - } - function setDirectionClass(cm) { - (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl"); - } - function directionChanged(cm) { - runInOp(cm, function () { - setDirectionClass(cm); - regChange(cm); - }); - } - function History(prev) { - // Arrays of change events and selections. Doing something adds an - // event to done and clears undo. Undoing moves events from done - // to undone, redoing moves them in the other direction. - this.done = []; - this.undone = []; - this.undoDepth = prev ? prev.undoDepth : Infinity; - // Used to track when changes can be merged into a single undo - // event - this.lastModTime = this.lastSelTime = 0; - this.lastOp = this.lastSelOp = null; - this.lastOrigin = this.lastSelOrigin = null; - // Used by the isClean() method - this.generation = this.maxGeneration = prev ? prev.maxGeneration : 1; - } - - // Create a history change event from an updateDoc-style change - // object. - function historyChangeFromChange(doc, change) { - var histChange = { - from: copyPos(change.from), - to: changeEnd(change), - text: getBetween(doc, change.from, change.to) - }; - attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); - linkedDocs(doc, function (doc) { - return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); - }, true); - return histChange; - } - - // Pop all selection events off the end of a history array. Stop at - // a change event. - function clearSelectionEvents(array) { - while (array.length) { - var last = lst(array); - if (last.ranges) { - array.pop(); - } else { - break; - } - } - } - - // Find the top change event in the history. Pop off selection - // events that are in the way. - function lastChangeEvent(hist, force) { - if (force) { - clearSelectionEvents(hist.done); - return lst(hist.done); - } else if (hist.done.length && !lst(hist.done).ranges) { - return lst(hist.done); - } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { - hist.done.pop(); - return lst(hist.done); - } - } - - // Register a change in the history. Merges changes that are within - // a single operation, or are close together with an origin that - // allows merging (starting with "+") into a single event. - function addChangeToHistory(doc, change, selAfter, opId) { - var hist = doc.history; - hist.undone.length = 0; - var time = +new Date(), - cur; - var last; - if ((hist.lastOp == opId || hist.lastOrigin == change.origin && change.origin && (change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500) || change.origin.charAt(0) == "*")) && (cur = lastChangeEvent(hist, hist.lastOp == opId))) { - // Merge this change into the last event - last = lst(cur.changes); - if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { - // Optimized case for simple insertion -- don't want to add - // new changesets for every character typed - last.to = changeEnd(change); - } else { - // Add new sub-event - cur.changes.push(historyChangeFromChange(doc, change)); - } - } else { - // Can not be merged, start a new event. - var before = lst(hist.done); - if (!before || !before.ranges) { - pushSelectionToHistory(doc.sel, hist.done); - } - cur = { - changes: [historyChangeFromChange(doc, change)], - generation: hist.generation - }; - hist.done.push(cur); - while (hist.done.length > hist.undoDepth) { - hist.done.shift(); - if (!hist.done[0].ranges) { - hist.done.shift(); - } - } - } - hist.done.push(selAfter); - hist.generation = ++hist.maxGeneration; - hist.lastModTime = hist.lastSelTime = time; - hist.lastOp = hist.lastSelOp = opId; - hist.lastOrigin = hist.lastSelOrigin = change.origin; - if (!last) { - signal(doc, "historyAdded"); - } - } - function selectionEventCanBeMerged(doc, origin, prev, sel) { - var ch = origin.charAt(0); - return ch == "*" || ch == "+" && prev.ranges.length == sel.ranges.length && prev.somethingSelected() == sel.somethingSelected() && new Date() - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500); - } - - // Called whenever the selection changes, sets the new selection as - // the pending selection in the history, and pushes the old pending - // selection into the 'done' array when it was significantly - // different (in number of selected ranges, emptiness, or time). - function addSelectionToHistory(doc, sel, opId, options) { - var hist = doc.history, - origin = options && options.origin; - - // A new event is started when the previous origin does not match - // the current, or the origins don't allow matching. Origins - // starting with * are always merged, those starting with + are - // merged when similar and close together in time. - if (opId == hist.lastSelOp || origin && hist.lastSelOrigin == origin && (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))) { - hist.done[hist.done.length - 1] = sel; - } else { - pushSelectionToHistory(sel, hist.done); - } - hist.lastSelTime = +new Date(); - hist.lastSelOrigin = origin; - hist.lastSelOp = opId; - if (options && options.clearRedo !== false) { - clearSelectionEvents(hist.undone); - } - } - function pushSelectionToHistory(sel, dest) { - var top = lst(dest); - if (!(top && top.ranges && top.equals(sel))) { - dest.push(sel); - } - } - - // Used to store marked span information in the history. - function attachLocalSpans(doc, change, from, to) { - var existing = change["spans_" + doc.id], - n = 0; - doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) { - if (line.markedSpans) { - (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; - } - ++n; - }); - } - - // When un/re-doing restores text containing marked spans, those - // that have been explicitly cleared should not be restored. - function removeClearedSpans(spans) { - if (!spans) { - return null; - } - var out; - for (var i = 0; i < spans.length; ++i) { - if (spans[i].marker.explicitlyCleared) { - if (!out) { - out = spans.slice(0, i); - } - } else if (out) { - out.push(spans[i]); - } - } - return !out ? spans : out.length ? out : null; - } - - // Retrieve and filter the old marked spans stored in a change event. - function getOldSpans(doc, change) { - var found = change["spans_" + doc.id]; - if (!found) { - return null; - } - var nw = []; - for (var i = 0; i < change.text.length; ++i) { - nw.push(removeClearedSpans(found[i])); - } - return nw; - } - - // Used for un/re-doing changes from the history. Combines the - // result of computing the existing spans with the set of spans that - // existed in the history (so that deleting around a span and then - // undoing brings back the span). - function mergeOldSpans(doc, change) { - var old = getOldSpans(doc, change); - var stretched = stretchSpansOverChange(doc, change); - if (!old) { - return stretched; - } - if (!stretched) { - return old; - } - for (var i = 0; i < old.length; ++i) { - var oldCur = old[i], - stretchCur = stretched[i]; - if (oldCur && stretchCur) { - spans: for (var j = 0; j < stretchCur.length; ++j) { - var span = stretchCur[j]; - for (var k = 0; k < oldCur.length; ++k) { - if (oldCur[k].marker == span.marker) { - continue spans; - } - } - oldCur.push(span); - } - } else if (stretchCur) { - old[i] = stretchCur; - } - } - return old; - } - - // Used both to provide a JSON-safe object in .getHistory, and, when - // detaching a document, to split the history in two - function copyHistoryArray(events, newGroup, instantiateSel) { - var copy = []; - for (var i = 0; i < events.length; ++i) { - var event = events[i]; - if (event.ranges) { - copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); - continue; - } - var changes = event.changes, - newChanges = []; - copy.push({ - changes: newChanges - }); - for (var j = 0; j < changes.length; ++j) { - var change = changes[j], - m = void 0; - newChanges.push({ - from: change.from, - to: change.to, - text: change.text - }); - if (newGroup) { - for (var prop in change) { - if (m = prop.match(/^spans_(\d+)$/)) { - if (indexOf(newGroup, Number(m[1])) > -1) { - lst(newChanges)[prop] = change[prop]; - delete change[prop]; - } - } - } - } - } - } - return copy; - } - - // The 'scroll' parameter given to many of these indicated whether - // the new cursor position should be scrolled into view after - // modifying the selection. - - // If shift is held or the extend flag is set, extends a range to - // include a given position (and optionally a second position). - // Otherwise, simply returns the range between the given positions. - // Used for cursor motion and such. - function extendRange(range, head, other, extend) { - if (extend) { - var anchor = range.anchor; - if (other) { - var posBefore = cmp(head, anchor) < 0; - if (posBefore != cmp(other, anchor) < 0) { - anchor = head; - head = other; - } else if (posBefore != cmp(head, other) < 0) { - head = other; - } - } - return new Range(anchor, head); - } else { - return new Range(other || head, head); - } - } - - // Extend the primary selection range, discard the rest. - function extendSelection(doc, head, other, options, extend) { - if (extend == null) { - extend = doc.cm && (doc.cm.display.shift || doc.extend); - } - setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options); - } - - // Extend all selections (pos is an array of selections with length - // equal the number of selections) - function extendSelections(doc, heads, options) { - var out = []; - var extend = doc.cm && (doc.cm.display.shift || doc.extend); - for (var i = 0; i < doc.sel.ranges.length; i++) { - out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); - } - var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex); - setSelection(doc, newSel, options); - } - - // Updates a single range in the selection. - function replaceOneSelection(doc, i, range, options) { - var ranges = doc.sel.ranges.slice(0); - ranges[i] = range; - setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options); - } - - // Reset the selection to a single range. - function setSimpleSelection(doc, anchor, head, options) { - setSelection(doc, simpleSelection(anchor, head), options); - } - - // Give beforeSelectionChange handlers a change to influence a - // selection update. - function filterSelectionChange(doc, sel, options) { - var obj = { - ranges: sel.ranges, - update: function (ranges) { - this.ranges = []; - for (var i = 0; i < ranges.length; i++) { - this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), clipPos(doc, ranges[i].head)); - } - }, - origin: options && options.origin - }; - signal(doc, "beforeSelectionChange", doc, obj); - if (doc.cm) { - signal(doc.cm, "beforeSelectionChange", doc.cm, obj); - } - if (obj.ranges != sel.ranges) { - return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1); - } else { - return sel; - } - } - function setSelectionReplaceHistory(doc, sel, options) { - var done = doc.history.done, - last = lst(done); - if (last && last.ranges) { - done[done.length - 1] = sel; - setSelectionNoUndo(doc, sel, options); - } else { - setSelection(doc, sel, options); - } - } - - // Set a new selection. - function setSelection(doc, sel, options) { - setSelectionNoUndo(doc, sel, options); - addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); - } - function setSelectionNoUndo(doc, sel, options) { - if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) { - sel = filterSelectionChange(doc, sel, options); - } - var bias = options && options.bias || (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); - setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); - if (!(options && options.scroll === false) && doc.cm && doc.cm.getOption("readOnly") != "nocursor") { - ensureCursorVisible(doc.cm); - } - } - function setSelectionInner(doc, sel) { - if (sel.equals(doc.sel)) { - return; - } - doc.sel = sel; - if (doc.cm) { - doc.cm.curOp.updateInput = 1; - doc.cm.curOp.selectionChanged = true; - signalCursorActivity(doc.cm); - } - signalLater(doc, "cursorActivity", doc); - } - - // Verify that the selection does not partially select any atomic - // marked ranges. - function reCheckSelection(doc) { - setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false)); - } - - // Return a selection that does not partially select any atomic - // ranges. - function skipAtomicInSelection(doc, sel, bias, mayClear) { - var out; - for (var i = 0; i < sel.ranges.length; i++) { - var range = sel.ranges[i]; - var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]; - var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear); - var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear); - if (out || newAnchor != range.anchor || newHead != range.head) { - if (!out) { - out = sel.ranges.slice(0, i); - } - out[i] = new Range(newAnchor, newHead); - } - } - return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel; - } - function skipAtomicInner(doc, pos, oldPos, dir, mayClear) { - var line = getLine(doc, pos.line); - if (line.markedSpans) { - for (var i = 0; i < line.markedSpans.length; ++i) { - var sp = line.markedSpans[i], - m = sp.marker; - - // Determine if we should prevent the cursor being placed to the left/right of an atomic marker - // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it - // is with selectLeft/Right - var preventCursorLeft = "selectLeft" in m ? !m.selectLeft : m.inclusiveLeft; - var preventCursorRight = "selectRight" in m ? !m.selectRight : m.inclusiveRight; - if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) { - if (mayClear) { - signal(m, "beforeCursorEnter"); - if (m.explicitlyCleared) { - if (!line.markedSpans) { - break; - } else { - --i; - continue; - } - } - } - if (!m.atomic) { - continue; - } - if (oldPos) { - var near = m.find(dir < 0 ? 1 : -1), - diff = void 0; - if (dir < 0 ? preventCursorRight : preventCursorLeft) { - near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); - } - if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) { - return skipAtomicInner(doc, near, pos, dir, mayClear); - } - } - var far = m.find(dir < 0 ? -1 : 1); - if (dir < 0 ? preventCursorLeft : preventCursorRight) { - far = movePos(doc, far, dir, far.line == pos.line ? line : null); - } - return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null; - } - } - } - return pos; - } - - // Ensure a given position is not inside an atomic range. - function skipAtomic(doc, pos, oldPos, bias, mayClear) { - var dir = bias || 1; - var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || !mayClear && skipAtomicInner(doc, pos, oldPos, dir, true) || skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || !mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true); - if (!found) { - doc.cantEdit = true; - return Pos(doc.first, 0); - } - return found; - } - function movePos(doc, pos, dir, line) { - if (dir < 0 && pos.ch == 0) { - if (pos.line > doc.first) { - return clipPos(doc, Pos(pos.line - 1)); - } else { - return null; - } - } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) { - if (pos.line < doc.first + doc.size - 1) { - return Pos(pos.line + 1, 0); - } else { - return null; - } - } else { - return new Pos(pos.line, pos.ch + dir); - } - } - function selectAll(cm) { - cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll); - } - - // UPDATING - - // Allow "beforeChange" event handlers to influence a change - function filterChange(doc, change, update) { - var obj = { - canceled: false, - from: change.from, - to: change.to, - text: change.text, - origin: change.origin, - cancel: function () { - return obj.canceled = true; - } - }; - if (update) { - obj.update = function (from, to, text, origin) { - if (from) { - obj.from = clipPos(doc, from); - } - if (to) { - obj.to = clipPos(doc, to); - } - if (text) { - obj.text = text; - } - if (origin !== undefined) { - obj.origin = origin; - } - }; - } - signal(doc, "beforeChange", doc, obj); - if (doc.cm) { - signal(doc.cm, "beforeChange", doc.cm, obj); - } - if (obj.canceled) { - if (doc.cm) { - doc.cm.curOp.updateInput = 2; - } - return null; - } - return { - from: obj.from, - to: obj.to, - text: obj.text, - origin: obj.origin - }; - } - - // Apply a change to a document, and add it to the document's - // history, and propagating it to all linked documents. - function makeChange(doc, change, ignoreReadOnly) { - if (doc.cm) { - if (!doc.cm.curOp) { - return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly); - } - if (doc.cm.state.suppressEdits) { - return; - } - } - if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { - change = filterChange(doc, change, true); - if (!change) { - return; - } - } - - // Possibly split or suppress the update based on the presence - // of read-only spans in its range. - var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); - if (split) { - for (var i = split.length - 1; i >= 0; --i) { - makeChangeInner(doc, { - from: split[i].from, - to: split[i].to, - text: i ? [""] : change.text, - origin: change.origin - }); - } - } else { - makeChangeInner(doc, change); - } - } - function makeChangeInner(doc, change) { - if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { - return; - } - var selAfter = computeSelAfterChange(doc, change); - addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); - makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); - var rebased = []; - linkedDocs(doc, function (doc, sharedHist) { - if (!sharedHist && indexOf(rebased, doc.history) == -1) { - rebaseHist(doc.history, change); - rebased.push(doc.history); - } - makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); - }); - } - - // Revert a change stored in a document's history. - function makeChangeFromHistory(doc, type, allowSelectionOnly) { - var suppress = doc.cm && doc.cm.state.suppressEdits; - if (suppress && !allowSelectionOnly) { - return; - } - var hist = doc.history, - event, - selAfter = doc.sel; - var source = type == "undo" ? hist.done : hist.undone, - dest = type == "undo" ? hist.undone : hist.done; - - // Verify that there is a useable event (so that ctrl-z won't - // needlessly clear selection events) - var i = 0; - for (; i < source.length; i++) { - event = source[i]; - if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) { - break; - } - } - if (i == source.length) { - return; - } - hist.lastOrigin = hist.lastSelOrigin = null; - for (;;) { - event = source.pop(); - if (event.ranges) { - pushSelectionToHistory(event, dest); - if (allowSelectionOnly && !event.equals(doc.sel)) { - setSelection(doc, event, { - clearRedo: false - }); - return; - } - selAfter = event; - } else if (suppress) { - source.push(event); - return; - } else { - break; - } - } - - // Build up a reverse change object to add to the opposite history - // stack (redo when undoing, and vice versa). - var antiChanges = []; - pushSelectionToHistory(selAfter, dest); - dest.push({ - changes: antiChanges, - generation: hist.generation - }); - hist.generation = event.generation || ++hist.maxGeneration; - var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); - var loop = function (i) { - var change = event.changes[i]; - change.origin = type; - if (filter && !filterChange(doc, change, false)) { - source.length = 0; - return {}; - } - antiChanges.push(historyChangeFromChange(doc, change)); - var after = i ? computeSelAfterChange(doc, change) : lst(source); - makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); - if (!i && doc.cm) { - doc.cm.scrollIntoView({ - from: change.from, - to: changeEnd(change) - }); - } - var rebased = []; - - // Propagate to the linked documents - linkedDocs(doc, function (doc, sharedHist) { - if (!sharedHist && indexOf(rebased, doc.history) == -1) { - rebaseHist(doc.history, change); - rebased.push(doc.history); - } - makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); - }); - }; - for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) { - var returned = loop(i$1); - if (returned) return returned.v; - } - } - - // Sub-views need their line numbers shifted when text is added - // above or below them in the parent document. - function shiftDoc(doc, distance) { - if (distance == 0) { - return; - } - doc.first += distance; - doc.sel = new Selection(map(doc.sel.ranges, function (range) { - return new Range(Pos(range.anchor.line + distance, range.anchor.ch), Pos(range.head.line + distance, range.head.ch)); - }), doc.sel.primIndex); - if (doc.cm) { - regChange(doc.cm, doc.first, doc.first - distance, distance); - for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) { - regLineChange(doc.cm, l, "gutter"); - } - } - } - - // More lower-level change function, handling only a single document - // (not linked ones). - function makeChangeSingleDoc(doc, change, selAfter, spans) { - if (doc.cm && !doc.cm.curOp) { - return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans); - } - if (change.to.line < doc.first) { - shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); - return; - } - if (change.from.line > doc.lastLine()) { - return; - } - - // Clip the change to the size of this doc - if (change.from.line < doc.first) { - var shift = change.text.length - 1 - (doc.first - change.from.line); - shiftDoc(doc, shift); - change = { - from: Pos(doc.first, 0), - to: Pos(change.to.line + shift, change.to.ch), - text: [lst(change.text)], - origin: change.origin - }; - } - var last = doc.lastLine(); - if (change.to.line > last) { - change = { - from: change.from, - to: Pos(last, getLine(doc, last).text.length), - text: [change.text[0]], - origin: change.origin - }; - } - change.removed = getBetween(doc, change.from, change.to); - if (!selAfter) { - selAfter = computeSelAfterChange(doc, change); - } - if (doc.cm) { - makeChangeSingleDocInEditor(doc.cm, change, spans); - } else { - updateDoc(doc, change, spans); - } - setSelectionNoUndo(doc, selAfter, sel_dontScroll); - if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0))) { - doc.cantEdit = false; - } - } - - // Handle the interaction of a change to a document with the editor - // that this document is part of. - function makeChangeSingleDocInEditor(cm, change, spans) { - var doc = cm.doc, - display = cm.display, - from = change.from, - to = change.to; - var recomputeMaxLength = false, - checkWidthStart = from.line; - if (!cm.options.lineWrapping) { - checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); - doc.iter(checkWidthStart, to.line + 1, function (line) { - if (line == display.maxLine) { - recomputeMaxLength = true; - return true; - } - }); - } - if (doc.sel.contains(change.from, change.to) > -1) { - signalCursorActivity(cm); - } - updateDoc(doc, change, spans, estimateHeight(cm)); - if (!cm.options.lineWrapping) { - doc.iter(checkWidthStart, from.line + change.text.length, function (line) { - var len = lineLength(line); - if (len > display.maxLineLength) { - display.maxLine = line; - display.maxLineLength = len; - display.maxLineChanged = true; - recomputeMaxLength = false; - } - }); - if (recomputeMaxLength) { - cm.curOp.updateMaxLine = true; - } - } - retreatFrontier(doc, from.line); - startWorker(cm, 400); - var lendiff = change.text.length - (to.line - from.line) - 1; - // Remember that these lines changed, for updating the display - if (change.full) { - regChange(cm); - } else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) { - regLineChange(cm, from.line, "text"); - } else { - regChange(cm, from.line, to.line + 1, lendiff); - } - var changesHandler = hasHandler(cm, "changes"), - changeHandler = hasHandler(cm, "change"); - if (changeHandler || changesHandler) { - var obj = { - from: from, - to: to, - text: change.text, - removed: change.removed, - origin: change.origin - }; - if (changeHandler) { - signalLater(cm, "change", cm, obj); - } - if (changesHandler) { - (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); - } - } - cm.display.selForContextMenu = null; - } - function replaceRange(doc, code, from, to, origin) { - var assign; - if (!to) { - to = from; - } - if (cmp(to, from) < 0) { - assign = [to, from], from = assign[0], to = assign[1]; - } - if (typeof code == "string") { - code = doc.splitLines(code); - } - makeChange(doc, { - from: from, - to: to, - text: code, - origin: origin - }); - } - - // Rebasing/resetting history to deal with externally-sourced changes - - function rebaseHistSelSingle(pos, from, to, diff) { - if (to < pos.line) { - pos.line += diff; - } else if (from < pos.line) { - pos.line = from; - pos.ch = 0; - } - } - - // Tries to rebase an array of history events given a change in the - // document. If the change touches the same lines as the event, the - // event, and everything 'behind' it, is discarded. If the change is - // before the event, the event's positions are updated. Uses a - // copy-on-write scheme for the positions, to avoid having to - // reallocate them all on every rebase, but also avoid problems with - // shared position objects being unsafely updated. - function rebaseHistArray(array, from, to, diff) { - for (var i = 0; i < array.length; ++i) { - var sub = array[i], - ok = true; - if (sub.ranges) { - if (!sub.copied) { - sub = array[i] = sub.deepCopy(); - sub.copied = true; - } - for (var j = 0; j < sub.ranges.length; j++) { - rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); - rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); - } - continue; - } - for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) { - var cur = sub.changes[j$1]; - if (to < cur.from.line) { - cur.from = Pos(cur.from.line + diff, cur.from.ch); - cur.to = Pos(cur.to.line + diff, cur.to.ch); - } else if (from <= cur.to.line) { - ok = false; - break; - } - } - if (!ok) { - array.splice(0, i + 1); - i = 0; - } - } - } - function rebaseHist(hist, change) { - var from = change.from.line, - to = change.to.line, - diff = change.text.length - (to - from) - 1; - rebaseHistArray(hist.done, from, to, diff); - rebaseHistArray(hist.undone, from, to, diff); - } - - // Utility for applying a change to a line by handle or number, - // returning the number and optionally registering the line as - // changed. - function changeLine(doc, handle, changeType, op) { - var no = handle, - line = handle; - if (typeof handle == "number") { - line = getLine(doc, clipLine(doc, handle)); - } else { - no = lineNo(handle); - } - if (no == null) { - return null; - } - if (op(line, no) && doc.cm) { - regLineChange(doc.cm, no, changeType); - } - return line; - } - - // The document is represented as a BTree consisting of leaves, with - // chunk of lines in them, and branches, with up to ten leaves or - // other branch nodes below them. The top node is always a branch - // node, and is the document object itself (meaning it has - // additional methods and properties). - // - // All nodes have parent links. The tree is used both to go from - // line numbers to line objects, and to go from objects to numbers. - // It also indexes by height, and is used to convert between height - // and line object, and to find the total height of the document. - // - // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html - - function LeafChunk(lines) { - this.lines = lines; - this.parent = null; - var height = 0; - for (var i = 0; i < lines.length; ++i) { - lines[i].parent = this; - height += lines[i].height; - } - this.height = height; - } - LeafChunk.prototype = { - chunkSize: function () { - return this.lines.length; - }, - // Remove the n lines at offset 'at'. - removeInner: function (at, n) { - for (var i = at, e = at + n; i < e; ++i) { - var line = this.lines[i]; - this.height -= line.height; - cleanUpLine(line); - signalLater(line, "delete"); - } - this.lines.splice(at, n); - }, - // Helper used to collapse a small branch into a single leaf. - collapse: function (lines) { - lines.push.apply(lines, this.lines); - }, - // Insert the given array of lines at offset 'at', count them as - // having the given height. - insertInner: function (at, lines, height) { - this.height += height; - this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); - for (var i = 0; i < lines.length; ++i) { - lines[i].parent = this; - } - }, - // Used to iterate over a part of the tree. - iterN: function (at, n, op) { - for (var e = at + n; at < e; ++at) { - if (op(this.lines[at])) { - return true; - } - } - } - }; - function BranchChunk(children) { - this.children = children; - var size = 0, - height = 0; - for (var i = 0; i < children.length; ++i) { - var ch = children[i]; - size += ch.chunkSize(); - height += ch.height; - ch.parent = this; - } - this.size = size; - this.height = height; - this.parent = null; - } - BranchChunk.prototype = { - chunkSize: function () { - return this.size; - }, - removeInner: function (at, n) { - this.size -= n; - for (var i = 0; i < this.children.length; ++i) { - var child = this.children[i], - sz = child.chunkSize(); - if (at < sz) { - var rm = Math.min(n, sz - at), - oldHeight = child.height; - child.removeInner(at, rm); - this.height -= oldHeight - child.height; - if (sz == rm) { - this.children.splice(i--, 1); - child.parent = null; - } - if ((n -= rm) == 0) { - break; - } - at = 0; - } else { - at -= sz; - } - } - // If the result is smaller than 25 lines, ensure that it is a - // single leaf node. - if (this.size - n < 25 && (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { - var lines = []; - this.collapse(lines); - this.children = [new LeafChunk(lines)]; - this.children[0].parent = this; - } - }, - collapse: function (lines) { - for (var i = 0; i < this.children.length; ++i) { - this.children[i].collapse(lines); - } - }, - insertInner: function (at, lines, height) { - this.size += lines.length; - this.height += height; - for (var i = 0; i < this.children.length; ++i) { - var child = this.children[i], - sz = child.chunkSize(); - if (at <= sz) { - child.insertInner(at, lines, height); - if (child.lines && child.lines.length > 50) { - // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced. - // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest. - var remaining = child.lines.length % 25 + 25; - for (var pos = remaining; pos < child.lines.length;) { - var leaf = new LeafChunk(child.lines.slice(pos, pos += 25)); - child.height -= leaf.height; - this.children.splice(++i, 0, leaf); - leaf.parent = this; - } - child.lines = child.lines.slice(0, remaining); - this.maybeSpill(); - } - break; - } - at -= sz; - } - }, - // When a node has grown, check whether it should be split. - maybeSpill: function () { - if (this.children.length <= 10) { - return; - } - var me = this; - do { - var spilled = me.children.splice(me.children.length - 5, 5); - var sibling = new BranchChunk(spilled); - if (!me.parent) { - // Become the parent node - var copy = new BranchChunk(me.children); - copy.parent = me; - me.children = [copy, sibling]; - me = copy; - } else { - me.size -= sibling.size; - me.height -= sibling.height; - var myIndex = indexOf(me.parent.children, me); - me.parent.children.splice(myIndex + 1, 0, sibling); - } - sibling.parent = me.parent; - } while (me.children.length > 10); - me.parent.maybeSpill(); - }, - iterN: function (at, n, op) { - for (var i = 0; i < this.children.length; ++i) { - var child = this.children[i], - sz = child.chunkSize(); - if (at < sz) { - var used = Math.min(n, sz - at); - if (child.iterN(at, used, op)) { - return true; - } - if ((n -= used) == 0) { - break; - } - at = 0; - } else { - at -= sz; - } - } - } - }; - - // Line widgets are block elements displayed above or below a line. - - var LineWidget = function (doc, node, options) { - if (options) { - for (var opt in options) { - if (options.hasOwnProperty(opt)) { - this[opt] = options[opt]; - } - } - } - this.doc = doc; - this.node = node; - }; - LineWidget.prototype.clear = function () { - var cm = this.doc.cm, - ws = this.line.widgets, - line = this.line, - no = lineNo(line); - if (no == null || !ws) { - return; - } - for (var i = 0; i < ws.length; ++i) { - if (ws[i] == this) { - ws.splice(i--, 1); - } - } - if (!ws.length) { - line.widgets = null; - } - var height = widgetHeight(this); - updateLineHeight(line, Math.max(0, line.height - height)); - if (cm) { - runInOp(cm, function () { - adjustScrollWhenAboveVisible(cm, line, -height); - regLineChange(cm, no, "widget"); - }); - signalLater(cm, "lineWidgetCleared", cm, this, no); - } - }; - LineWidget.prototype.changed = function () { - var this$1 = this; - var oldH = this.height, - cm = this.doc.cm, - line = this.line; - this.height = null; - var diff = widgetHeight(this) - oldH; - if (!diff) { - return; - } - if (!lineIsHidden(this.doc, line)) { - updateLineHeight(line, line.height + diff); - } - if (cm) { - runInOp(cm, function () { - cm.curOp.forceUpdate = true; - adjustScrollWhenAboveVisible(cm, line, diff); - signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line)); - }); - } - }; - eventMixin(LineWidget); - function adjustScrollWhenAboveVisible(cm, line, diff) { - if (heightAtLine(line) < (cm.curOp && cm.curOp.scrollTop || cm.doc.scrollTop)) { - addToScrollTop(cm, diff); - } - } - function addLineWidget(doc, handle, node, options) { - var widget = new LineWidget(doc, node, options); - var cm = doc.cm; - if (cm && widget.noHScroll) { - cm.display.alignWidgets = true; - } - changeLine(doc, handle, "widget", function (line) { - var widgets = line.widgets || (line.widgets = []); - if (widget.insertAt == null) { - widgets.push(widget); - } else { - widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget); - } - widget.line = line; - if (cm && !lineIsHidden(doc, line)) { - var aboveVisible = heightAtLine(line) < doc.scrollTop; - updateLineHeight(line, line.height + widgetHeight(widget)); - if (aboveVisible) { - addToScrollTop(cm, widget.height); - } - cm.curOp.forceUpdate = true; - } - return true; - }); - if (cm) { - signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); - } - return widget; - } - - // TEXTMARKERS - - // Created with markText and setBookmark methods. A TextMarker is a - // handle that can be used to clear or find a marked position in the - // document. Line objects hold arrays (markedSpans) containing - // {from, to, marker} object pointing to such marker objects, and - // indicating that such a marker is present on that line. Multiple - // lines may point to the same marker when it spans across lines. - // The spans will have null for their from/to properties when the - // marker continues beyond the start/end of the line. Markers have - // links back to the lines they currently touch. - - // Collapsed markers have unique ids, in order to be able to order - // them, which is needed for uniquely determining an outer marker - // when they overlap (they may nest, but not partially overlap). - var nextMarkerId = 0; - var TextMarker = function (doc, type) { - this.lines = []; - this.type = type; - this.doc = doc; - this.id = ++nextMarkerId; - }; - - // Clear the marker. - TextMarker.prototype.clear = function () { - if (this.explicitlyCleared) { - return; - } - var cm = this.doc.cm, - withOp = cm && !cm.curOp; - if (withOp) { - startOperation(cm); - } - if (hasHandler(this, "clear")) { - var found = this.find(); - if (found) { - signalLater(this, "clear", found.from, found.to); - } - } - var min = null, - max = null; - for (var i = 0; i < this.lines.length; ++i) { - var line = this.lines[i]; - var span = getMarkedSpanFor(line.markedSpans, this); - if (cm && !this.collapsed) { - regLineChange(cm, lineNo(line), "text"); - } else if (cm) { - if (span.to != null) { - max = lineNo(line); - } - if (span.from != null) { - min = lineNo(line); - } - } - line.markedSpans = removeMarkedSpan(line.markedSpans, span); - if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) { - updateLineHeight(line, textHeight(cm.display)); - } - } - if (cm && this.collapsed && !cm.options.lineWrapping) { - for (var i$1 = 0; i$1 < this.lines.length; ++i$1) { - var visual = visualLine(this.lines[i$1]), - len = lineLength(visual); - if (len > cm.display.maxLineLength) { - cm.display.maxLine = visual; - cm.display.maxLineLength = len; - cm.display.maxLineChanged = true; - } - } - } - if (min != null && cm && this.collapsed) { - regChange(cm, min, max + 1); - } - this.lines.length = 0; - this.explicitlyCleared = true; - if (this.atomic && this.doc.cantEdit) { - this.doc.cantEdit = false; - if (cm) { - reCheckSelection(cm.doc); - } - } - if (cm) { - signalLater(cm, "markerCleared", cm, this, min, max); - } - if (withOp) { - endOperation(cm); - } - if (this.parent) { - this.parent.clear(); - } - }; - - // Find the position of the marker in the document. Returns a {from, - // to} object by default. Side can be passed to get a specific side - // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the - // Pos objects returned contain a line object, rather than a line - // number (used to prevent looking up the same line twice). - TextMarker.prototype.find = function (side, lineObj) { - if (side == null && this.type == "bookmark") { - side = 1; - } - var from, to; - for (var i = 0; i < this.lines.length; ++i) { - var line = this.lines[i]; - var span = getMarkedSpanFor(line.markedSpans, this); - if (span.from != null) { - from = Pos(lineObj ? line : lineNo(line), span.from); - if (side == -1) { - return from; - } - } - if (span.to != null) { - to = Pos(lineObj ? line : lineNo(line), span.to); - if (side == 1) { - return to; - } - } - } - return from && { - from: from, - to: to - }; - }; - - // Signals that the marker's widget changed, and surrounding layout - // should be recomputed. - TextMarker.prototype.changed = function () { - var this$1 = this; - var pos = this.find(-1, true), - widget = this, - cm = this.doc.cm; - if (!pos || !cm) { - return; - } - runInOp(cm, function () { - var line = pos.line, - lineN = lineNo(pos.line); - var view = findViewForLine(cm, lineN); - if (view) { - clearLineMeasurementCacheFor(view); - cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; - } - cm.curOp.updateMaxLine = true; - if (!lineIsHidden(widget.doc, line) && widget.height != null) { - var oldHeight = widget.height; - widget.height = null; - var dHeight = widgetHeight(widget) - oldHeight; - if (dHeight) { - updateLineHeight(line, line.height + dHeight); - } - } - signalLater(cm, "markerChanged", cm, this$1); - }); - }; - TextMarker.prototype.attachLine = function (line) { - if (!this.lines.length && this.doc.cm) { - var op = this.doc.cm.curOp; - if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) { - (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); - } - } - this.lines.push(line); - }; - TextMarker.prototype.detachLine = function (line) { - this.lines.splice(indexOf(this.lines, line), 1); - if (!this.lines.length && this.doc.cm) { - var op = this.doc.cm.curOp; - (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); - } - }; - eventMixin(TextMarker); - - // Create a marker, wire it up to the right lines, and - function markText(doc, from, to, options, type) { - // Shared markers (across linked documents) are handled separately - // (markTextShared will call out to this again, once per - // document). - if (options && options.shared) { - return markTextShared(doc, from, to, options, type); - } - // Ensure we are in an operation. - if (doc.cm && !doc.cm.curOp) { - return operation(doc.cm, markText)(doc, from, to, options, type); - } - var marker = new TextMarker(doc, type), - diff = cmp(from, to); - if (options) { - copyObj(options, marker, false); - } - // Don't connect empty markers unless clearWhenEmpty is false - if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) { - return marker; - } - if (marker.replacedWith) { - // Showing up as a widget implies collapsed (widget replaces text) - marker.collapsed = true; - marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget"); - if (!options.handleMouseEvents) { - marker.widgetNode.setAttribute("cm-ignore-events", "true"); - } - if (options.insertLeft) { - marker.widgetNode.insertLeft = true; - } - } - if (marker.collapsed) { - if (conflictingCollapsedRange(doc, from.line, from, to, marker) || from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) { - throw new Error("Inserting collapsed marker partially overlapping an existing one"); - } - seeCollapsedSpans(); - } - if (marker.addToHistory) { - addChangeToHistory(doc, { - from: from, - to: to, - origin: "markText" - }, doc.sel, NaN); - } - var curLine = from.line, - cm = doc.cm, - updateMaxLine; - doc.iter(curLine, to.line + 1, function (line) { - if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) { - updateMaxLine = true; - } - if (marker.collapsed && curLine != from.line) { - updateLineHeight(line, 0); - } - addMarkedSpan(line, new MarkedSpan(marker, curLine == from.line ? from.ch : null, curLine == to.line ? to.ch : null), doc.cm && doc.cm.curOp); - ++curLine; - }); - // lineIsHidden depends on the presence of the spans, so needs a second pass - if (marker.collapsed) { - doc.iter(from.line, to.line + 1, function (line) { - if (lineIsHidden(doc, line)) { - updateLineHeight(line, 0); - } - }); - } - if (marker.clearOnEnter) { - on(marker, "beforeCursorEnter", function () { - return marker.clear(); - }); - } - if (marker.readOnly) { - seeReadOnlySpans(); - if (doc.history.done.length || doc.history.undone.length) { - doc.clearHistory(); - } - } - if (marker.collapsed) { - marker.id = ++nextMarkerId; - marker.atomic = true; - } - if (cm) { - // Sync editor state - if (updateMaxLine) { - cm.curOp.updateMaxLine = true; - } - if (marker.collapsed) { - regChange(cm, from.line, to.line + 1); - } else if (marker.className || marker.startStyle || marker.endStyle || marker.css || marker.attributes || marker.title) { - for (var i = from.line; i <= to.line; i++) { - regLineChange(cm, i, "text"); - } - } - if (marker.atomic) { - reCheckSelection(cm.doc); - } - signalLater(cm, "markerAdded", cm, marker); - } - return marker; - } - - // SHARED TEXTMARKERS - - // A shared marker spans multiple linked documents. It is - // implemented as a meta-marker-object controlling multiple normal - // markers. - var SharedTextMarker = function (markers, primary) { - this.markers = markers; - this.primary = primary; - for (var i = 0; i < markers.length; ++i) { - markers[i].parent = this; - } - }; - SharedTextMarker.prototype.clear = function () { - if (this.explicitlyCleared) { - return; - } - this.explicitlyCleared = true; - for (var i = 0; i < this.markers.length; ++i) { - this.markers[i].clear(); - } - signalLater(this, "clear"); - }; - SharedTextMarker.prototype.find = function (side, lineObj) { - return this.primary.find(side, lineObj); - }; - eventMixin(SharedTextMarker); - function markTextShared(doc, from, to, options, type) { - options = copyObj(options); - options.shared = false; - var markers = [markText(doc, from, to, options, type)], - primary = markers[0]; - var widget = options.widgetNode; - linkedDocs(doc, function (doc) { - if (widget) { - options.widgetNode = widget.cloneNode(true); - } - markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); - for (var i = 0; i < doc.linked.length; ++i) { - if (doc.linked[i].isParent) { - return; - } - } - primary = lst(markers); - }); - return new SharedTextMarker(markers, primary); - } - function findSharedMarkers(doc) { - return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { - return m.parent; - }); - } - function copySharedMarkers(doc, markers) { - for (var i = 0; i < markers.length; i++) { - var marker = markers[i], - pos = marker.find(); - var mFrom = doc.clipPos(pos.from), - mTo = doc.clipPos(pos.to); - if (cmp(mFrom, mTo)) { - var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); - marker.markers.push(subMark); - subMark.parent = marker; - } - } - } - function detachSharedMarkers(markers) { - var loop = function (i) { - var marker = markers[i], - linked = [marker.primary.doc]; - linkedDocs(marker.primary.doc, function (d) { - return linked.push(d); - }); - for (var j = 0; j < marker.markers.length; j++) { - var subMarker = marker.markers[j]; - if (indexOf(linked, subMarker.doc) == -1) { - subMarker.parent = null; - marker.markers.splice(j--, 1); - } - } - }; - for (var i = 0; i < markers.length; i++) loop(i); - } - var nextDocId = 0; - var Doc = function (text, mode, firstLine, lineSep, direction) { - if (!(this instanceof Doc)) { - return new Doc(text, mode, firstLine, lineSep, direction); - } - if (firstLine == null) { - firstLine = 0; - } - BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); - this.first = firstLine; - this.scrollTop = this.scrollLeft = 0; - this.cantEdit = false; - this.cleanGeneration = 1; - this.modeFrontier = this.highlightFrontier = firstLine; - var start = Pos(firstLine, 0); - this.sel = simpleSelection(start); - this.history = new History(null); - this.id = ++nextDocId; - this.modeOption = mode; - this.lineSep = lineSep; - this.direction = direction == "rtl" ? "rtl" : "ltr"; - this.extend = false; - if (typeof text == "string") { - text = this.splitLines(text); - } - updateDoc(this, { - from: start, - to: start, - text: text - }); - setSelection(this, simpleSelection(start), sel_dontScroll); - }; - Doc.prototype = createObj(BranchChunk.prototype, { - constructor: Doc, - // Iterate over the document. Supports two forms -- with only one - // argument, it calls that for each line in the document. With - // three, it iterates over the range given by the first two (with - // the second being non-inclusive). - iter: function (from, to, op) { - if (op) { - this.iterN(from - this.first, to - from, op); - } else { - this.iterN(this.first, this.first + this.size, from); - } - }, - // Non-public interface for adding and removing lines. - insert: function (at, lines) { - var height = 0; - for (var i = 0; i < lines.length; ++i) { - height += lines[i].height; - } - this.insertInner(at - this.first, lines, height); - }, - remove: function (at, n) { - this.removeInner(at - this.first, n); - }, - // From here, the methods are part of the public interface. Most - // are also available from CodeMirror (editor) instances. - - getValue: function (lineSep) { - var lines = getLines(this, this.first, this.first + this.size); - if (lineSep === false) { - return lines; - } - return lines.join(lineSep || this.lineSeparator()); - }, - setValue: docMethodOp(function (code) { - var top = Pos(this.first, 0), - last = this.first + this.size - 1; - makeChange(this, { - from: top, - to: Pos(last, getLine(this, last).text.length), - text: this.splitLines(code), - origin: "setValue", - full: true - }, true); - if (this.cm) { - scrollToCoords(this.cm, 0, 0); - } - setSelection(this, simpleSelection(top), sel_dontScroll); - }), - replaceRange: function (code, from, to, origin) { - from = clipPos(this, from); - to = to ? clipPos(this, to) : from; - replaceRange(this, code, from, to, origin); - }, - getRange: function (from, to, lineSep) { - var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); - if (lineSep === false) { - return lines; - } - if (lineSep === '') { - return lines.join(''); - } - return lines.join(lineSep || this.lineSeparator()); - }, - getLine: function (line) { - var l = this.getLineHandle(line); - return l && l.text; - }, - getLineHandle: function (line) { - if (isLine(this, line)) { - return getLine(this, line); - } - }, - getLineNumber: function (line) { - return lineNo(line); - }, - getLineHandleVisualStart: function (line) { - if (typeof line == "number") { - line = getLine(this, line); - } - return visualLine(line); - }, - lineCount: function () { - return this.size; - }, - firstLine: function () { - return this.first; - }, - lastLine: function () { - return this.first + this.size - 1; - }, - clipPos: function (pos) { - return clipPos(this, pos); - }, - getCursor: function (start) { - var range = this.sel.primary(), - pos; - if (start == null || start == "head") { - pos = range.head; - } else if (start == "anchor") { - pos = range.anchor; - } else if (start == "end" || start == "to" || start === false) { - pos = range.to(); - } else { - pos = range.from(); - } - return pos; - }, - listSelections: function () { - return this.sel.ranges; - }, - somethingSelected: function () { - return this.sel.somethingSelected(); - }, - setCursor: docMethodOp(function (line, ch, options) { - setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); - }), - setSelection: docMethodOp(function (anchor, head, options) { - setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); - }), - extendSelection: docMethodOp(function (head, other, options) { - extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); - }), - extendSelections: docMethodOp(function (heads, options) { - extendSelections(this, clipPosArray(this, heads), options); - }), - extendSelectionsBy: docMethodOp(function (f, options) { - var heads = map(this.sel.ranges, f); - extendSelections(this, clipPosArray(this, heads), options); - }), - setSelections: docMethodOp(function (ranges, primary, options) { - if (!ranges.length) { - return; - } - var out = []; - for (var i = 0; i < ranges.length; i++) { - out[i] = new Range(clipPos(this, ranges[i].anchor), clipPos(this, ranges[i].head || ranges[i].anchor)); - } - if (primary == null) { - primary = Math.min(ranges.length - 1, this.sel.primIndex); - } - setSelection(this, normalizeSelection(this.cm, out, primary), options); - }), - addSelection: docMethodOp(function (anchor, head, options) { - var ranges = this.sel.ranges.slice(0); - ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); - setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options); - }), - getSelection: function (lineSep) { - var ranges = this.sel.ranges, - lines; - for (var i = 0; i < ranges.length; i++) { - var sel = getBetween(this, ranges[i].from(), ranges[i].to()); - lines = lines ? lines.concat(sel) : sel; - } - if (lineSep === false) { - return lines; - } else { - return lines.join(lineSep || this.lineSeparator()); - } - }, - getSelections: function (lineSep) { - var parts = [], - ranges = this.sel.ranges; - for (var i = 0; i < ranges.length; i++) { - var sel = getBetween(this, ranges[i].from(), ranges[i].to()); - if (lineSep !== false) { - sel = sel.join(lineSep || this.lineSeparator()); - } - parts[i] = sel; - } - return parts; - }, - replaceSelection: function (code, collapse, origin) { - var dup = []; - for (var i = 0; i < this.sel.ranges.length; i++) { - dup[i] = code; - } - this.replaceSelections(dup, collapse, origin || "+input"); - }, - replaceSelections: docMethodOp(function (code, collapse, origin) { - var changes = [], - sel = this.sel; - for (var i = 0; i < sel.ranges.length; i++) { - var range = sel.ranges[i]; - changes[i] = { - from: range.from(), - to: range.to(), - text: this.splitLines(code[i]), - origin: origin - }; - } - var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); - for (var i$1 = changes.length - 1; i$1 >= 0; i$1--) { - makeChange(this, changes[i$1]); - } - if (newSel) { - setSelectionReplaceHistory(this, newSel); - } else if (this.cm) { - ensureCursorVisible(this.cm); - } - }), - undo: docMethodOp(function () { - makeChangeFromHistory(this, "undo"); - }), - redo: docMethodOp(function () { - makeChangeFromHistory(this, "redo"); - }), - undoSelection: docMethodOp(function () { - makeChangeFromHistory(this, "undo", true); - }), - redoSelection: docMethodOp(function () { - makeChangeFromHistory(this, "redo", true); - }), - setExtending: function (val) { - this.extend = val; - }, - getExtending: function () { - return this.extend; - }, - historySize: function () { - var hist = this.history, - done = 0, - undone = 0; - for (var i = 0; i < hist.done.length; i++) { - if (!hist.done[i].ranges) { - ++done; - } - } - for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { - if (!hist.undone[i$1].ranges) { - ++undone; - } - } - return { - undo: done, - redo: undone - }; - }, - clearHistory: function () { - var this$1 = this; - this.history = new History(this.history); - linkedDocs(this, function (doc) { - return doc.history = this$1.history; - }, true); - }, - markClean: function () { - this.cleanGeneration = this.changeGeneration(true); - }, - changeGeneration: function (forceSplit) { - if (forceSplit) { - this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; - } - return this.history.generation; - }, - isClean: function (gen) { - return this.history.generation == (gen || this.cleanGeneration); - }, - getHistory: function () { - return { - done: copyHistoryArray(this.history.done), - undone: copyHistoryArray(this.history.undone) - }; - }, - setHistory: function (histData) { - var hist = this.history = new History(this.history); - hist.done = copyHistoryArray(histData.done.slice(0), null, true); - hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); - }, - setGutterMarker: docMethodOp(function (line, gutterID, value) { - return changeLine(this, line, "gutter", function (line) { - var markers = line.gutterMarkers || (line.gutterMarkers = {}); - markers[gutterID] = value; - if (!value && isEmpty(markers)) { - line.gutterMarkers = null; - } - return true; - }); - }), - clearGutter: docMethodOp(function (gutterID) { - var this$1 = this; - this.iter(function (line) { - if (line.gutterMarkers && line.gutterMarkers[gutterID]) { - changeLine(this$1, line, "gutter", function () { - line.gutterMarkers[gutterID] = null; - if (isEmpty(line.gutterMarkers)) { - line.gutterMarkers = null; - } - return true; - }); - } - }); - }), - lineInfo: function (line) { - var n; - if (typeof line == "number") { - if (!isLine(this, line)) { - return null; - } - n = line; - line = getLine(this, line); - if (!line) { - return null; - } - } else { - n = lineNo(line); - if (n == null) { - return null; - } - } - return { - line: n, - handle: line, - text: line.text, - gutterMarkers: line.gutterMarkers, - textClass: line.textClass, - bgClass: line.bgClass, - wrapClass: line.wrapClass, - widgets: line.widgets - }; - }, - addLineClass: docMethodOp(function (handle, where, cls) { - return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { - var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass"; - if (!line[prop]) { - line[prop] = cls; - } else if (classTest(cls).test(line[prop])) { - return false; - } else { - line[prop] += " " + cls; - } - return true; - }); - }), - removeLineClass: docMethodOp(function (handle, where, cls) { - return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { - var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass"; - var cur = line[prop]; - if (!cur) { - return false; - } else if (cls == null) { - line[prop] = null; - } else { - var found = cur.match(classTest(cls)); - if (!found) { - return false; - } - var end = found.index + found[0].length; - line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; - } - return true; - }); - }), - addLineWidget: docMethodOp(function (handle, node, options) { - return addLineWidget(this, handle, node, options); - }), - removeLineWidget: function (widget) { - widget.clear(); - }, - markText: function (from, to, options) { - return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range"); - }, - setBookmark: function (pos, options) { - var realOpts = { - replacedWith: options && (options.nodeType == null ? options.widget : options), - insertLeft: options && options.insertLeft, - clearWhenEmpty: false, - shared: options && options.shared, - handleMouseEvents: options && options.handleMouseEvents - }; - pos = clipPos(this, pos); - return markText(this, pos, pos, realOpts, "bookmark"); - }, - findMarksAt: function (pos) { - pos = clipPos(this, pos); - var markers = [], - spans = getLine(this, pos.line).markedSpans; - if (spans) { - for (var i = 0; i < spans.length; ++i) { - var span = spans[i]; - if ((span.from == null || span.from <= pos.ch) && (span.to == null || span.to >= pos.ch)) { - markers.push(span.marker.parent || span.marker); - } - } - } - return markers; - }, - findMarks: function (from, to, filter) { - from = clipPos(this, from); - to = clipPos(this, to); - var found = [], - lineNo = from.line; - this.iter(from.line, to.line + 1, function (line) { - var spans = line.markedSpans; - if (spans) { - for (var i = 0; i < spans.length; i++) { - var span = spans[i]; - if (!(span.to != null && lineNo == from.line && from.ch >= span.to || span.from == null && lineNo != from.line || span.from != null && lineNo == to.line && span.from >= to.ch) && (!filter || filter(span.marker))) { - found.push(span.marker.parent || span.marker); - } - } - } - ++lineNo; - }); - return found; - }, - getAllMarks: function () { - var markers = []; - this.iter(function (line) { - var sps = line.markedSpans; - if (sps) { - for (var i = 0; i < sps.length; ++i) { - if (sps[i].from != null) { - markers.push(sps[i].marker); - } - } - } - }); - return markers; - }, - posFromIndex: function (off) { - var ch, - lineNo = this.first, - sepSize = this.lineSeparator().length; - this.iter(function (line) { - var sz = line.text.length + sepSize; - if (sz > off) { - ch = off; - return true; - } - off -= sz; - ++lineNo; - }); - return clipPos(this, Pos(lineNo, ch)); - }, - indexFromPos: function (coords) { - coords = clipPos(this, coords); - var index = coords.ch; - if (coords.line < this.first || coords.ch < 0) { - return 0; - } - var sepSize = this.lineSeparator().length; - this.iter(this.first, coords.line, function (line) { - // iter aborts when callback returns a truthy value - index += line.text.length + sepSize; - }); - return index; - }, - copy: function (copyHistory) { - var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first, this.lineSep, this.direction); - doc.scrollTop = this.scrollTop; - doc.scrollLeft = this.scrollLeft; - doc.sel = this.sel; - doc.extend = false; - if (copyHistory) { - doc.history.undoDepth = this.history.undoDepth; - doc.setHistory(this.getHistory()); - } - return doc; - }, - linkedDoc: function (options) { - if (!options) { - options = {}; - } - var from = this.first, - to = this.first + this.size; - if (options.from != null && options.from > from) { - from = options.from; - } - if (options.to != null && options.to < to) { - to = options.to; - } - var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction); - if (options.sharedHist) { - copy.history = this.history; - } - (this.linked || (this.linked = [])).push({ - doc: copy, - sharedHist: options.sharedHist - }); - copy.linked = [{ - doc: this, - isParent: true, - sharedHist: options.sharedHist - }]; - copySharedMarkers(copy, findSharedMarkers(this)); - return copy; - }, - unlinkDoc: function (other) { - if (other instanceof CodeMirror) { - other = other.doc; - } - if (this.linked) { - for (var i = 0; i < this.linked.length; ++i) { - var link = this.linked[i]; - if (link.doc != other) { - continue; - } - this.linked.splice(i, 1); - other.unlinkDoc(this); - detachSharedMarkers(findSharedMarkers(this)); - break; - } - } - // If the histories were shared, split them again - if (other.history == this.history) { - var splitIds = [other.id]; - linkedDocs(other, function (doc) { - return splitIds.push(doc.id); - }, true); - other.history = new History(null); - other.history.done = copyHistoryArray(this.history.done, splitIds); - other.history.undone = copyHistoryArray(this.history.undone, splitIds); - } - }, - iterLinkedDocs: function (f) { - linkedDocs(this, f); - }, - getMode: function () { - return this.mode; - }, - getEditor: function () { - return this.cm; - }, - splitLines: function (str) { - if (this.lineSep) { - return str.split(this.lineSep); - } - return splitLinesAuto(str); - }, - lineSeparator: function () { - return this.lineSep || "\n"; - }, - setDirection: docMethodOp(function (dir) { - if (dir != "rtl") { - dir = "ltr"; - } - if (dir == this.direction) { - return; - } - this.direction = dir; - this.iter(function (line) { - return line.order = null; - }); - if (this.cm) { - directionChanged(this.cm); - } - }) - }); - - // Public alias. - Doc.prototype.eachLine = Doc.prototype.iter; - - // Kludge to work around strange IE behavior where it'll sometimes - // re-fire a series of drag-related events right after the drop (#1551) - var lastDrop = 0; - function onDrop(e) { - var cm = this; - clearDragCursor(cm); - if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { - return; - } - e_preventDefault(e); - if (ie) { - lastDrop = +new Date(); - } - var pos = posFromMouse(cm, e, true), - files = e.dataTransfer.files; - if (!pos || cm.isReadOnly()) { - return; - } - // Might be a file drop, in which case we simply extract the text - // and insert it. - if (files && files.length && window.FileReader && window.File) { - var n = files.length, - text = Array(n), - read = 0; - var markAsReadAndPasteIfAllFilesAreRead = function () { - if (++read == n) { - operation(cm, function () { - pos = clipPos(cm.doc, pos); - var change = { - from: pos, - to: pos, - text: cm.doc.splitLines(text.filter(function (t) { - return t != null; - }).join(cm.doc.lineSeparator())), - origin: "paste" - }; - makeChange(cm.doc, change); - setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change)))); - })(); - } - }; - var readTextFromFile = function (file, i) { - if (cm.options.allowDropFileTypes && indexOf(cm.options.allowDropFileTypes, file.type) == -1) { - markAsReadAndPasteIfAllFilesAreRead(); - return; - } - var reader = new FileReader(); - reader.onerror = function () { - return markAsReadAndPasteIfAllFilesAreRead(); - }; - reader.onload = function () { - var content = reader.result; - if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { - markAsReadAndPasteIfAllFilesAreRead(); - return; - } - text[i] = content; - markAsReadAndPasteIfAllFilesAreRead(); - }; - reader.readAsText(file); - }; - for (var i = 0; i < files.length; i++) { - readTextFromFile(files[i], i); - } - } else { - // Normal drop - // Don't do a replace if the drop happened inside of the selected text. - if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { - cm.state.draggingText(e); - // Ensure the editor is re-focused - setTimeout(function () { - return cm.display.input.focus(); - }, 20); - return; - } - try { - var text$1 = e.dataTransfer.getData("Text"); - if (text$1) { - var selected; - if (cm.state.draggingText && !cm.state.draggingText.copy) { - selected = cm.listSelections(); - } - setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); - if (selected) { - for (var i$1 = 0; i$1 < selected.length; ++i$1) { - replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); - } - } - cm.replaceSelection(text$1, "around", "paste"); - cm.display.input.focus(); - } - } catch (e$1) {} - } - } - function onDragStart(cm, e) { - if (ie && (!cm.state.draggingText || +new Date() - lastDrop < 100)) { - e_stop(e); - return; - } - if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { - return; - } - e.dataTransfer.setData("Text", cm.getSelection()); - e.dataTransfer.effectAllowed = "copyMove"; - - // Use dummy image instead of default browsers image. - // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. - if (e.dataTransfer.setDragImage && !safari) { - var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); - img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; - if (presto) { - img.width = img.height = 1; - cm.display.wrapper.appendChild(img); - // Force a relayout, or Opera won't use our image for some obscure reason - img._top = img.offsetTop; - } - e.dataTransfer.setDragImage(img, 0, 0); - if (presto) { - img.parentNode.removeChild(img); - } - } - } - function onDragOver(cm, e) { - var pos = posFromMouse(cm, e); - if (!pos) { - return; - } - var frag = document.createDocumentFragment(); - drawSelectionCursor(cm, pos, frag); - if (!cm.display.dragCursor) { - cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors"); - cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv); - } - removeChildrenAndAdd(cm.display.dragCursor, frag); - } - function clearDragCursor(cm) { - if (cm.display.dragCursor) { - cm.display.lineSpace.removeChild(cm.display.dragCursor); - cm.display.dragCursor = null; - } - } - - // These must be handled carefully, because naively registering a - // handler for each editor will cause the editors to never be - // garbage collected. - - function forEachCodeMirror(f) { - if (!document.getElementsByClassName) { - return; - } - var byClass = document.getElementsByClassName("CodeMirror"), - editors = []; - for (var i = 0; i < byClass.length; i++) { - var cm = byClass[i].CodeMirror; - if (cm) { - editors.push(cm); - } - } - if (editors.length) { - editors[0].operation(function () { - for (var i = 0; i < editors.length; i++) { - f(editors[i]); - } - }); - } - } - var globalsRegistered = false; - function ensureGlobalHandlers() { - if (globalsRegistered) { - return; - } - registerGlobalHandlers(); - globalsRegistered = true; - } - function registerGlobalHandlers() { - // When the window resizes, we need to refresh active editors. - var resizeTimer; - on(window, "resize", function () { - if (resizeTimer == null) { - resizeTimer = setTimeout(function () { - resizeTimer = null; - forEachCodeMirror(onResize); - }, 100); - } - }); - // When the window loses focus, we want to show the editor as blurred - on(window, "blur", function () { - return forEachCodeMirror(onBlur); - }); - } - // Called when the window resizes - function onResize(cm) { - var d = cm.display; - // Might be a text scaling operation, clear size caches. - d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; - d.scrollbarsClipped = false; - cm.setSize(); - } - var keyNames = { - 3: "Pause", - 8: "Backspace", - 9: "Tab", - 13: "Enter", - 16: "Shift", - 17: "Ctrl", - 18: "Alt", - 19: "Pause", - 20: "CapsLock", - 27: "Esc", - 32: "Space", - 33: "PageUp", - 34: "PageDown", - 35: "End", - 36: "Home", - 37: "Left", - 38: "Up", - 39: "Right", - 40: "Down", - 44: "PrintScrn", - 45: "Insert", - 46: "Delete", - 59: ";", - 61: "=", - 91: "Mod", - 92: "Mod", - 93: "Mod", - 106: "*", - 107: "=", - 109: "-", - 110: ".", - 111: "/", - 145: "ScrollLock", - 173: "-", - 186: ";", - 187: "=", - 188: ",", - 189: "-", - 190: ".", - 191: "/", - 192: "`", - 219: "[", - 220: "\\", - 221: "]", - 222: "'", - 224: "Mod", - 63232: "Up", - 63233: "Down", - 63234: "Left", - 63235: "Right", - 63272: "Delete", - 63273: "Home", - 63275: "End", - 63276: "PageUp", - 63277: "PageDown", - 63302: "Insert" - }; - - // Number keys - for (var i = 0; i < 10; i++) { - keyNames[i + 48] = keyNames[i + 96] = String(i); - } - // Alphabetic keys - for (var i$1 = 65; i$1 <= 90; i$1++) { - keyNames[i$1] = String.fromCharCode(i$1); - } - // Function keys - for (var i$2 = 1; i$2 <= 12; i$2++) { - keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; - } - var keyMap = {}; - keyMap.basic = { - "Left": "goCharLeft", - "Right": "goCharRight", - "Up": "goLineUp", - "Down": "goLineDown", - "End": "goLineEnd", - "Home": "goLineStartSmart", - "PageUp": "goPageUp", - "PageDown": "goPageDown", - "Delete": "delCharAfter", - "Backspace": "delCharBefore", - "Shift-Backspace": "delCharBefore", - "Tab": "defaultTab", - "Shift-Tab": "indentAuto", - "Enter": "newlineAndIndent", - "Insert": "toggleOverwrite", - "Esc": "singleSelection" - }; - // Note that the save and find-related commands aren't defined by - // default. User code or addons can define them. Unknown commands - // are simply ignored. - keyMap.pcDefault = { - "Ctrl-A": "selectAll", - "Ctrl-D": "deleteLine", - "Ctrl-Z": "undo", - "Shift-Ctrl-Z": "redo", - "Ctrl-Y": "redo", - "Ctrl-Home": "goDocStart", - "Ctrl-End": "goDocEnd", - "Ctrl-Up": "goLineUp", - "Ctrl-Down": "goLineDown", - "Ctrl-Left": "goGroupLeft", - "Ctrl-Right": "goGroupRight", - "Alt-Left": "goLineStart", - "Alt-Right": "goLineEnd", - "Ctrl-Backspace": "delGroupBefore", - "Ctrl-Delete": "delGroupAfter", - "Ctrl-S": "save", - "Ctrl-F": "find", - "Ctrl-G": "findNext", - "Shift-Ctrl-G": "findPrev", - "Shift-Ctrl-F": "replace", - "Shift-Ctrl-R": "replaceAll", - "Ctrl-[": "indentLess", - "Ctrl-]": "indentMore", - "Ctrl-U": "undoSelection", - "Shift-Ctrl-U": "redoSelection", - "Alt-U": "redoSelection", - "fallthrough": "basic" - }; - // Very basic readline/emacs-style bindings, which are standard on Mac. - keyMap.emacsy = { - "Ctrl-F": "goCharRight", - "Ctrl-B": "goCharLeft", - "Ctrl-P": "goLineUp", - "Ctrl-N": "goLineDown", - "Ctrl-A": "goLineStart", - "Ctrl-E": "goLineEnd", - "Ctrl-V": "goPageDown", - "Shift-Ctrl-V": "goPageUp", - "Ctrl-D": "delCharAfter", - "Ctrl-H": "delCharBefore", - "Alt-Backspace": "delWordBefore", - "Ctrl-K": "killLine", - "Ctrl-T": "transposeChars", - "Ctrl-O": "openLine" - }; - keyMap.macDefault = { - "Cmd-A": "selectAll", - "Cmd-D": "deleteLine", - "Cmd-Z": "undo", - "Shift-Cmd-Z": "redo", - "Cmd-Y": "redo", - "Cmd-Home": "goDocStart", - "Cmd-Up": "goDocStart", - "Cmd-End": "goDocEnd", - "Cmd-Down": "goDocEnd", - "Alt-Left": "goGroupLeft", - "Alt-Right": "goGroupRight", - "Cmd-Left": "goLineLeft", - "Cmd-Right": "goLineRight", - "Alt-Backspace": "delGroupBefore", - "Ctrl-Alt-Backspace": "delGroupAfter", - "Alt-Delete": "delGroupAfter", - "Cmd-S": "save", - "Cmd-F": "find", - "Cmd-G": "findNext", - "Shift-Cmd-G": "findPrev", - "Cmd-Alt-F": "replace", - "Shift-Cmd-Alt-F": "replaceAll", - "Cmd-[": "indentLess", - "Cmd-]": "indentMore", - "Cmd-Backspace": "delWrappedLineLeft", - "Cmd-Delete": "delWrappedLineRight", - "Cmd-U": "undoSelection", - "Shift-Cmd-U": "redoSelection", - "Ctrl-Up": "goDocStart", - "Ctrl-Down": "goDocEnd", - "fallthrough": ["basic", "emacsy"] - }; - keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; - - // KEYMAP DISPATCH - - function normalizeKeyName(name) { - var parts = name.split(/-(?!$)/); - name = parts[parts.length - 1]; - var alt, ctrl, shift, cmd; - for (var i = 0; i < parts.length - 1; i++) { - var mod = parts[i]; - if (/^(cmd|meta|m)$/i.test(mod)) { - cmd = true; - } else if (/^a(lt)?$/i.test(mod)) { - alt = true; - } else if (/^(c|ctrl|control)$/i.test(mod)) { - ctrl = true; - } else if (/^s(hift)?$/i.test(mod)) { - shift = true; - } else { - throw new Error("Unrecognized modifier name: " + mod); - } - } - if (alt) { - name = "Alt-" + name; - } - if (ctrl) { - name = "Ctrl-" + name; - } - if (cmd) { - name = "Cmd-" + name; - } - if (shift) { - name = "Shift-" + name; - } - return name; - } - - // This is a kludge to keep keymaps mostly working as raw objects - // (backwards compatibility) while at the same time support features - // like normalization and multi-stroke key bindings. It compiles a - // new normalized keymap, and then updates the old object to reflect - // this. - function normalizeKeyMap(keymap) { - var copy = {}; - for (var keyname in keymap) { - if (keymap.hasOwnProperty(keyname)) { - var value = keymap[keyname]; - if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { - continue; - } - if (value == "...") { - delete keymap[keyname]; - continue; - } - var keys = map(keyname.split(" "), normalizeKeyName); - for (var i = 0; i < keys.length; i++) { - var val = void 0, - name = void 0; - if (i == keys.length - 1) { - name = keys.join(" "); - val = value; - } else { - name = keys.slice(0, i + 1).join(" "); - val = "..."; - } - var prev = copy[name]; - if (!prev) { - copy[name] = val; - } else if (prev != val) { - throw new Error("Inconsistent bindings for " + name); - } - } - delete keymap[keyname]; - } - } - for (var prop in copy) { - keymap[prop] = copy[prop]; - } - return keymap; - } - function lookupKey(key, map, handle, context) { - map = getKeyMap(map); - var found = map.call ? map.call(key, context) : map[key]; - if (found === false) { - return "nothing"; - } - if (found === "...") { - return "multi"; - } - if (found != null && handle(found)) { - return "handled"; - } - if (map.fallthrough) { - if (Object.prototype.toString.call(map.fallthrough) != "[object Array]") { - return lookupKey(key, map.fallthrough, handle, context); - } - for (var i = 0; i < map.fallthrough.length; i++) { - var result = lookupKey(key, map.fallthrough[i], handle, context); - if (result) { - return result; - } - } - } - } - - // Modifier key presses don't count as 'real' key presses for the - // purpose of keymap fallthrough. - function isModifierKey(value) { - var name = typeof value == "string" ? value : keyNames[value.keyCode]; - return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; - } - function addModifierNames(name, event, noShift) { - var base = name; - if (event.altKey && base != "Alt") { - name = "Alt-" + name; - } - if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { - name = "Ctrl-" + name; - } - if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") { - name = "Cmd-" + name; - } - if (!noShift && event.shiftKey && base != "Shift") { - name = "Shift-" + name; - } - return name; - } - - // Look up the name of a key as indicated by an event object. - function keyName(event, noShift) { - if (presto && event.keyCode == 34 && event["char"]) { - return false; - } - var name = keyNames[event.keyCode]; - if (name == null || event.altGraphKey) { - return false; - } - // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause, - // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+) - if (event.keyCode == 3 && event.code) { - name = event.code; - } - return addModifierNames(name, event, noShift); - } - function getKeyMap(val) { - return typeof val == "string" ? keyMap[val] : val; - } - - // Helper for deleting text near the selection(s), used to implement - // backspace, delete, and similar functionality. - function deleteNearSelection(cm, compute) { - var ranges = cm.doc.sel.ranges, - kill = []; - // Build up a set of ranges to kill first, merging overlapping - // ranges. - for (var i = 0; i < ranges.length; i++) { - var toKill = compute(ranges[i]); - while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { - var replaced = kill.pop(); - if (cmp(replaced.from, toKill.from) < 0) { - toKill.from = replaced.from; - break; - } - } - kill.push(toKill); - } - // Next, remove those actual ranges. - runInOp(cm, function () { - for (var i = kill.length - 1; i >= 0; i--) { - replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); - } - ensureCursorVisible(cm); - }); - } - function moveCharLogically(line, ch, dir) { - var target = skipExtendingChars(line.text, ch + dir, dir); - return target < 0 || target > line.text.length ? null : target; - } - function moveLogically(line, start, dir) { - var ch = moveCharLogically(line, start.ch, dir); - return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before"); - } - function endOfLine(visually, cm, lineObj, lineNo, dir) { - if (visually) { - if (cm.doc.direction == "rtl") { - dir = -dir; - } - var order = getOrder(lineObj, cm.doc.direction); - if (order) { - var part = dir < 0 ? lst(order) : order[0]; - var moveInStorageOrder = dir < 0 == (part.level == 1); - var sticky = moveInStorageOrder ? "after" : "before"; - var ch; - // With a wrapped rtl chunk (possibly spanning multiple bidi parts), - // it could be that the last bidi part is not on the last visual line, - // since visual lines contain content order-consecutive chunks. - // Thus, in rtl, we are looking for the first (content-order) character - // in the rtl chunk that is on the last line (that is, the same line - // as the last (content-order) character). - if (part.level > 0 || cm.doc.direction == "rtl") { - var prep = prepareMeasureForLine(cm, lineObj); - ch = dir < 0 ? lineObj.text.length - 1 : 0; - var targetTop = measureCharPrepared(cm, prep, ch).top; - ch = findFirst(function (ch) { - return measureCharPrepared(cm, prep, ch).top == targetTop; - }, dir < 0 == (part.level == 1) ? part.from : part.to - 1, ch); - if (sticky == "before") { - ch = moveCharLogically(lineObj, ch, 1); - } - } else { - ch = dir < 0 ? part.to : part.from; - } - return new Pos(lineNo, ch, sticky); - } - } - return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after"); - } - function moveVisually(cm, line, start, dir) { - var bidi = getOrder(line, cm.doc.direction); - if (!bidi) { - return moveLogically(line, start, dir); - } - if (start.ch >= line.text.length) { - start.ch = line.text.length; - start.sticky = "before"; - } else if (start.ch <= 0) { - start.ch = 0; - start.sticky = "after"; - } - var partPos = getBidiPartAt(bidi, start.ch, start.sticky), - part = bidi[partPos]; - if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) { - // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines, - // nothing interesting happens. - return moveLogically(line, start, dir); - } - var mv = function (pos, dir) { - return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); - }; - var prep; - var getWrappedLineExtent = function (ch) { - if (!cm.options.lineWrapping) { - return { - begin: 0, - end: line.text.length - }; - } - prep = prep || prepareMeasureForLine(cm, line); - return wrappedLineExtentChar(cm, line, prep, ch); - }; - var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch); - if (cm.doc.direction == "rtl" || part.level == 1) { - var moveInStorageOrder = part.level == 1 == dir < 0; - var ch = mv(start, moveInStorageOrder ? 1 : -1); - if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) { - // Case 2: We move within an rtl part or in an rtl editor on the same visual line - var sticky = moveInStorageOrder ? "before" : "after"; - return new Pos(start.line, ch, sticky); - } - } - - // Case 3: Could not move within this bidi part in this visual line, so leave - // the current bidi part - - var searchInVisualLine = function (partPos, dir, wrappedLineExtent) { - var getRes = function (ch, moveInStorageOrder) { - return moveInStorageOrder ? new Pos(start.line, mv(ch, 1), "before") : new Pos(start.line, ch, "after"); - }; - for (; partPos >= 0 && partPos < bidi.length; partPos += dir) { - var part = bidi[partPos]; - var moveInStorageOrder = dir > 0 == (part.level != 1); - var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1); - if (part.from <= ch && ch < part.to) { - return getRes(ch, moveInStorageOrder); - } - ch = moveInStorageOrder ? part.from : mv(part.to, -1); - if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { - return getRes(ch, moveInStorageOrder); - } - } - }; - - // Case 3a: Look for other bidi parts on the same visual line - var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent); - if (res) { - return res; - } - - // Case 3b: Look for other bidi parts on the next visual line - var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1); - if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) { - res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh)); - if (res) { - return res; - } - } - - // Case 4: Nowhere to move - return null; - } - - // Commands are parameter-less actions that can be performed on an - // editor, mostly used for keybindings. - var commands = { - selectAll: selectAll, - singleSelection: function (cm) { - return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); - }, - killLine: function (cm) { - return deleteNearSelection(cm, function (range) { - if (range.empty()) { - var len = getLine(cm.doc, range.head.line).text.length; - if (range.head.ch == len && range.head.line < cm.lastLine()) { - return { - from: range.head, - to: Pos(range.head.line + 1, 0) - }; - } else { - return { - from: range.head, - to: Pos(range.head.line, len) - }; - } - } else { - return { - from: range.from(), - to: range.to() - }; - } - }); - }, - deleteLine: function (cm) { - return deleteNearSelection(cm, function (range) { - return { - from: Pos(range.from().line, 0), - to: clipPos(cm.doc, Pos(range.to().line + 1, 0)) - }; - }); - }, - delLineLeft: function (cm) { - return deleteNearSelection(cm, function (range) { - return { - from: Pos(range.from().line, 0), - to: range.from() - }; - }); - }, - delWrappedLineLeft: function (cm) { - return deleteNearSelection(cm, function (range) { - var top = cm.charCoords(range.head, "div").top + 5; - var leftPos = cm.coordsChar({ - left: 0, - top: top - }, "div"); - return { - from: leftPos, - to: range.from() - }; - }); - }, - delWrappedLineRight: function (cm) { - return deleteNearSelection(cm, function (range) { - var top = cm.charCoords(range.head, "div").top + 5; - var rightPos = cm.coordsChar({ - left: cm.display.lineDiv.offsetWidth + 100, - top: top - }, "div"); - return { - from: range.from(), - to: rightPos - }; - }); - }, - undo: function (cm) { - return cm.undo(); - }, - redo: function (cm) { - return cm.redo(); - }, - undoSelection: function (cm) { - return cm.undoSelection(); - }, - redoSelection: function (cm) { - return cm.redoSelection(); - }, - goDocStart: function (cm) { - return cm.extendSelection(Pos(cm.firstLine(), 0)); - }, - goDocEnd: function (cm) { - return cm.extendSelection(Pos(cm.lastLine())); - }, - goLineStart: function (cm) { - return cm.extendSelectionsBy(function (range) { - return lineStart(cm, range.head.line); - }, { - origin: "+move", - bias: 1 - }); - }, - goLineStartSmart: function (cm) { - return cm.extendSelectionsBy(function (range) { - return lineStartSmart(cm, range.head); - }, { - origin: "+move", - bias: 1 - }); - }, - goLineEnd: function (cm) { - return cm.extendSelectionsBy(function (range) { - return lineEnd(cm, range.head.line); - }, { - origin: "+move", - bias: -1 - }); - }, - goLineRight: function (cm) { - return cm.extendSelectionsBy(function (range) { - var top = cm.cursorCoords(range.head, "div").top + 5; - return cm.coordsChar({ - left: cm.display.lineDiv.offsetWidth + 100, - top: top - }, "div"); - }, sel_move); - }, - goLineLeft: function (cm) { - return cm.extendSelectionsBy(function (range) { - var top = cm.cursorCoords(range.head, "div").top + 5; - return cm.coordsChar({ - left: 0, - top: top - }, "div"); - }, sel_move); - }, - goLineLeftSmart: function (cm) { - return cm.extendSelectionsBy(function (range) { - var top = cm.cursorCoords(range.head, "div").top + 5; - var pos = cm.coordsChar({ - left: 0, - top: top - }, "div"); - if (pos.ch < cm.getLine(pos.line).search(/\S/)) { - return lineStartSmart(cm, range.head); - } - return pos; - }, sel_move); - }, - goLineUp: function (cm) { - return cm.moveV(-1, "line"); - }, - goLineDown: function (cm) { - return cm.moveV(1, "line"); - }, - goPageUp: function (cm) { - return cm.moveV(-1, "page"); - }, - goPageDown: function (cm) { - return cm.moveV(1, "page"); - }, - goCharLeft: function (cm) { - return cm.moveH(-1, "char"); - }, - goCharRight: function (cm) { - return cm.moveH(1, "char"); - }, - goColumnLeft: function (cm) { - return cm.moveH(-1, "column"); - }, - goColumnRight: function (cm) { - return cm.moveH(1, "column"); - }, - goWordLeft: function (cm) { - return cm.moveH(-1, "word"); - }, - goGroupRight: function (cm) { - return cm.moveH(1, "group"); - }, - goGroupLeft: function (cm) { - return cm.moveH(-1, "group"); - }, - goWordRight: function (cm) { - return cm.moveH(1, "word"); - }, - delCharBefore: function (cm) { - return cm.deleteH(-1, "codepoint"); - }, - delCharAfter: function (cm) { - return cm.deleteH(1, "char"); - }, - delWordBefore: function (cm) { - return cm.deleteH(-1, "word"); - }, - delWordAfter: function (cm) { - return cm.deleteH(1, "word"); - }, - delGroupBefore: function (cm) { - return cm.deleteH(-1, "group"); - }, - delGroupAfter: function (cm) { - return cm.deleteH(1, "group"); - }, - indentAuto: function (cm) { - return cm.indentSelection("smart"); - }, - indentMore: function (cm) { - return cm.indentSelection("add"); - }, - indentLess: function (cm) { - return cm.indentSelection("subtract"); - }, - insertTab: function (cm) { - return cm.replaceSelection("\t"); - }, - insertSoftTab: function (cm) { - var spaces = [], - ranges = cm.listSelections(), - tabSize = cm.options.tabSize; - for (var i = 0; i < ranges.length; i++) { - var pos = ranges[i].from(); - var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); - spaces.push(spaceStr(tabSize - col % tabSize)); - } - cm.replaceSelections(spaces); - }, - defaultTab: function (cm) { - if (cm.somethingSelected()) { - cm.indentSelection("add"); - } else { - cm.execCommand("insertTab"); - } - }, - // Swap the two chars left and right of each selection's head. - // Move cursor behind the two swapped characters afterwards. - // - // Doesn't consider line feeds a character. - // Doesn't scan more than one line above to find a character. - // Doesn't do anything on an empty line. - // Doesn't do anything with non-empty selections. - transposeChars: function (cm) { - return runInOp(cm, function () { - var ranges = cm.listSelections(), - newSel = []; - for (var i = 0; i < ranges.length; i++) { - if (!ranges[i].empty()) { - continue; - } - var cur = ranges[i].head, - line = getLine(cm.doc, cur.line).text; - if (line) { - if (cur.ch == line.length) { - cur = new Pos(cur.line, cur.ch - 1); - } - if (cur.ch > 0) { - cur = new Pos(cur.line, cur.ch + 1); - cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), Pos(cur.line, cur.ch - 2), cur, "+transpose"); - } else if (cur.line > cm.doc.first) { - var prev = getLine(cm.doc, cur.line - 1).text; - if (prev) { - cur = new Pos(cur.line, 1); - cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + prev.charAt(prev.length - 1), Pos(cur.line - 1, prev.length - 1), cur, "+transpose"); - } - } - } - newSel.push(new Range(cur, cur)); - } - cm.setSelections(newSel); - }); - }, - newlineAndIndent: function (cm) { - return runInOp(cm, function () { - var sels = cm.listSelections(); - for (var i = sels.length - 1; i >= 0; i--) { - cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); - } - sels = cm.listSelections(); - for (var i$1 = 0; i$1 < sels.length; i$1++) { - cm.indentLine(sels[i$1].from().line, null, true); - } - ensureCursorVisible(cm); - }); - }, - openLine: function (cm) { - return cm.replaceSelection("\n", "start"); - }, - toggleOverwrite: function (cm) { - return cm.toggleOverwrite(); - } - }; - function lineStart(cm, lineN) { - var line = getLine(cm.doc, lineN); - var visual = visualLine(line); - if (visual != line) { - lineN = lineNo(visual); - } - return endOfLine(true, cm, visual, lineN, 1); - } - function lineEnd(cm, lineN) { - var line = getLine(cm.doc, lineN); - var visual = visualLineEnd(line); - if (visual != line) { - lineN = lineNo(visual); - } - return endOfLine(true, cm, line, lineN, -1); - } - function lineStartSmart(cm, pos) { - var start = lineStart(cm, pos.line); - var line = getLine(cm.doc, start.line); - var order = getOrder(line, cm.doc.direction); - if (!order || order[0].level == 0) { - var firstNonWS = Math.max(start.ch, line.text.search(/\S/)); - var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; - return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky); - } - return start; - } - - // Run a handler that was bound to a key. - function doHandleBinding(cm, bound, dropShift) { - if (typeof bound == "string") { - bound = commands[bound]; - if (!bound) { - return false; - } - } - // Ensure previous input has been read, so that the handler sees a - // consistent view of the document - cm.display.input.ensurePolled(); - var prevShift = cm.display.shift, - done = false; - try { - if (cm.isReadOnly()) { - cm.state.suppressEdits = true; - } - if (dropShift) { - cm.display.shift = false; - } - done = bound(cm) != Pass; - } finally { - cm.display.shift = prevShift; - cm.state.suppressEdits = false; - } - return done; - } - function lookupKeyForEditor(cm, name, handle) { - for (var i = 0; i < cm.state.keyMaps.length; i++) { - var result = lookupKey(name, cm.state.keyMaps[i], handle, cm); - if (result) { - return result; - } - } - return cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm) || lookupKey(name, cm.options.keyMap, handle, cm); - } - - // Note that, despite the name, this function is also used to check - // for bound mouse clicks. - - var stopSeq = new Delayed(); - function dispatchKey(cm, name, e, handle) { - var seq = cm.state.keySeq; - if (seq) { - if (isModifierKey(name)) { - return "handled"; - } - if (/\'$/.test(name)) { - cm.state.keySeq = null; - } else { - stopSeq.set(50, function () { - if (cm.state.keySeq == seq) { - cm.state.keySeq = null; - cm.display.input.reset(); - } - }); - } - if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { - return true; - } - } - return dispatchKeyInner(cm, name, e, handle); - } - function dispatchKeyInner(cm, name, e, handle) { - var result = lookupKeyForEditor(cm, name, handle); - if (result == "multi") { - cm.state.keySeq = name; - } - if (result == "handled") { - signalLater(cm, "keyHandled", cm, name, e); - } - if (result == "handled" || result == "multi") { - e_preventDefault(e); - restartBlink(cm); - } - return !!result; - } - - // Handle a key from the keydown event. - function handleKeyBinding(cm, e) { - var name = keyName(e, true); - if (!name) { - return false; - } - if (e.shiftKey && !cm.state.keySeq) { - // First try to resolve full name (including 'Shift-'). Failing - // that, see if there is a cursor-motion command (starting with - // 'go') bound to the keyname without 'Shift-'. - return dispatchKey(cm, "Shift-" + name, e, function (b) { - return doHandleBinding(cm, b, true); - }) || dispatchKey(cm, name, e, function (b) { - if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) { - return doHandleBinding(cm, b); - } - }); - } else { - return dispatchKey(cm, name, e, function (b) { - return doHandleBinding(cm, b); - }); - } - } - - // Handle a key from the keypress event - function handleCharBinding(cm, e, ch) { - return dispatchKey(cm, "'" + ch + "'", e, function (b) { - return doHandleBinding(cm, b, true); - }); - } - var lastStoppedKey = null; - function onKeyDown(e) { - var cm = this; - if (e.target && e.target != cm.display.input.getField()) { - return; - } - cm.curOp.focus = activeElt(); - if (signalDOMEvent(cm, e)) { - return; - } - // IE does strange things with escape. - if (ie && ie_version < 11 && e.keyCode == 27) { - e.returnValue = false; - } - var code = e.keyCode; - cm.display.shift = code == 16 || e.shiftKey; - var handled = handleKeyBinding(cm, e); - if (presto) { - lastStoppedKey = handled ? code : null; - // Opera has no cut event... we try to at least catch the key combo - if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) { - cm.replaceSelection("", null, "cut"); - } - } - if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand) { - document.execCommand("cut"); - } - - // Turn mouse into crosshair when Alt is held on Mac. - if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) { - showCrossHair(cm); - } - } - function showCrossHair(cm) { - var lineDiv = cm.display.lineDiv; - addClass(lineDiv, "CodeMirror-crosshair"); - function up(e) { - if (e.keyCode == 18 || !e.altKey) { - rmClass(lineDiv, "CodeMirror-crosshair"); - off(document, "keyup", up); - off(document, "mouseover", up); - } - } - on(document, "keyup", up); - on(document, "mouseover", up); - } - function onKeyUp(e) { - if (e.keyCode == 16) { - this.doc.sel.shift = false; - } - signalDOMEvent(this, e); - } - function onKeyPress(e) { - var cm = this; - if (e.target && e.target != cm.display.input.getField()) { - return; - } - if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { - return; - } - var keyCode = e.keyCode, - charCode = e.charCode; - if (presto && keyCode == lastStoppedKey) { - lastStoppedKey = null; - e_preventDefault(e); - return; - } - if (presto && (!e.which || e.which < 10) && handleKeyBinding(cm, e)) { - return; - } - var ch = String.fromCharCode(charCode == null ? keyCode : charCode); - // Some browsers fire keypress events for backspace - if (ch == "\x08") { - return; - } - if (handleCharBinding(cm, e, ch)) { - return; - } - cm.display.input.onKeyPress(e); - } - var DOUBLECLICK_DELAY = 400; - var PastClick = function (time, pos, button) { - this.time = time; - this.pos = pos; - this.button = button; - }; - PastClick.prototype.compare = function (time, pos, button) { - return this.time + DOUBLECLICK_DELAY > time && cmp(pos, this.pos) == 0 && button == this.button; - }; - var lastClick, lastDoubleClick; - function clickRepeat(pos, button) { - var now = +new Date(); - if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) { - lastClick = lastDoubleClick = null; - return "triple"; - } else if (lastClick && lastClick.compare(now, pos, button)) { - lastDoubleClick = new PastClick(now, pos, button); - lastClick = null; - return "double"; - } else { - lastClick = new PastClick(now, pos, button); - lastDoubleClick = null; - return "single"; - } - } - - // A mouse down can be a single click, double click, triple click, - // start of selection drag, start of text drag, new cursor - // (ctrl-click), rectangle drag (alt-drag), or xwin - // middle-click-paste. Or it might be a click on something we should - // not interfere with, such as a scrollbar or widget. - function onMouseDown(e) { - var cm = this, - display = cm.display; - if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { - return; - } - display.input.ensurePolled(); - display.shift = e.shiftKey; - if (eventInWidget(display, e)) { - if (!webkit) { - // Briefly turn off draggability, to allow widgets to do - // normal dragging things. - display.scroller.draggable = false; - setTimeout(function () { - return display.scroller.draggable = true; - }, 100); - } - return; - } - if (clickInGutter(cm, e)) { - return; - } - var pos = posFromMouse(cm, e), - button = e_button(e), - repeat = pos ? clickRepeat(pos, button) : "single"; - window.focus(); - - // #3261: make sure, that we're not starting a second selection - if (button == 1 && cm.state.selectingText) { - cm.state.selectingText(e); - } - if (pos && handleMappedButton(cm, button, pos, repeat, e)) { - return; - } - if (button == 1) { - if (pos) { - leftButtonDown(cm, pos, repeat, e); - } else if (e_target(e) == display.scroller) { - e_preventDefault(e); - } - } else if (button == 2) { - if (pos) { - extendSelection(cm.doc, pos); - } - setTimeout(function () { - return display.input.focus(); - }, 20); - } else if (button == 3) { - if (captureRightClick) { - cm.display.input.onContextMenu(e); - } else { - delayBlurEvent(cm); - } - } - } - function handleMappedButton(cm, button, pos, repeat, event) { - var name = "Click"; - if (repeat == "double") { - name = "Double" + name; - } else if (repeat == "triple") { - name = "Triple" + name; - } - name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name; - return dispatchKey(cm, addModifierNames(name, event), event, function (bound) { - if (typeof bound == "string") { - bound = commands[bound]; - } - if (!bound) { - return false; - } - var done = false; - try { - if (cm.isReadOnly()) { - cm.state.suppressEdits = true; - } - done = bound(cm, pos) != Pass; - } finally { - cm.state.suppressEdits = false; - } - return done; - }); - } - function configureMouse(cm, repeat, event) { - var option = cm.getOption("configureMouse"); - var value = option ? option(cm, repeat, event) : {}; - if (value.unit == null) { - var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey; - value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line"; - } - if (value.extend == null || cm.doc.extend) { - value.extend = cm.doc.extend || event.shiftKey; - } - if (value.addNew == null) { - value.addNew = mac ? event.metaKey : event.ctrlKey; - } - if (value.moveOnDrag == null) { - value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); - } - return value; - } - function leftButtonDown(cm, pos, repeat, event) { - if (ie) { - setTimeout(bind(ensureFocus, cm), 0); - } else { - cm.curOp.focus = activeElt(); - } - var behavior = configureMouse(cm, repeat, event); - var sel = cm.doc.sel, - contained; - if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && repeat == "single" && (contained = sel.contains(pos)) > -1 && (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) && (cmp(contained.to(), pos) > 0 || pos.xRel < 0)) { - leftButtonStartDrag(cm, event, pos, behavior); - } else { - leftButtonSelect(cm, event, pos, behavior); - } - } - - // Start a text drag. When it ends, see if any dragging actually - // happen, and treat as a click if it didn't. - function leftButtonStartDrag(cm, event, pos, behavior) { - var display = cm.display, - moved = false; - var dragEnd = operation(cm, function (e) { - if (webkit) { - display.scroller.draggable = false; - } - cm.state.draggingText = false; - if (cm.state.delayingBlurEvent) { - if (cm.hasFocus()) { - cm.state.delayingBlurEvent = false; - } else { - delayBlurEvent(cm); - } - } - off(display.wrapper.ownerDocument, "mouseup", dragEnd); - off(display.wrapper.ownerDocument, "mousemove", mouseMove); - off(display.scroller, "dragstart", dragStart); - off(display.scroller, "drop", dragEnd); - if (!moved) { - e_preventDefault(e); - if (!behavior.addNew) { - extendSelection(cm.doc, pos, null, null, behavior.extend); - } - // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) - if (webkit && !safari || ie && ie_version == 9) { - setTimeout(function () { - display.wrapper.ownerDocument.body.focus({ - preventScroll: true - }); - display.input.focus(); - }, 20); - } else { - display.input.focus(); - } - } - }); - var mouseMove = function (e2) { - moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10; - }; - var dragStart = function () { - return moved = true; - }; - // Let the drag handler handle this. - if (webkit) { - display.scroller.draggable = true; - } - cm.state.draggingText = dragEnd; - dragEnd.copy = !behavior.moveOnDrag; - on(display.wrapper.ownerDocument, "mouseup", dragEnd); - on(display.wrapper.ownerDocument, "mousemove", mouseMove); - on(display.scroller, "dragstart", dragStart); - on(display.scroller, "drop", dragEnd); - cm.state.delayingBlurEvent = true; - setTimeout(function () { - return display.input.focus(); - }, 20); - // IE's approach to draggable - if (display.scroller.dragDrop) { - display.scroller.dragDrop(); - } - } - function rangeForUnit(cm, pos, unit) { - if (unit == "char") { - return new Range(pos, pos); - } - if (unit == "word") { - return cm.findWordAt(pos); - } - if (unit == "line") { - return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); - } - var result = unit(cm, pos); - return new Range(result.from, result.to); - } - - // Normal selection, as opposed to text dragging. - function leftButtonSelect(cm, event, start, behavior) { - if (ie) { - delayBlurEvent(cm); - } - var display = cm.display, - doc = cm.doc; - e_preventDefault(event); - var ourRange, - ourIndex, - startSel = doc.sel, - ranges = startSel.ranges; - if (behavior.addNew && !behavior.extend) { - ourIndex = doc.sel.contains(start); - if (ourIndex > -1) { - ourRange = ranges[ourIndex]; - } else { - ourRange = new Range(start, start); - } - } else { - ourRange = doc.sel.primary(); - ourIndex = doc.sel.primIndex; - } - if (behavior.unit == "rectangle") { - if (!behavior.addNew) { - ourRange = new Range(start, start); - } - start = posFromMouse(cm, event, true, true); - ourIndex = -1; - } else { - var range = rangeForUnit(cm, start, behavior.unit); - if (behavior.extend) { - ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend); - } else { - ourRange = range; - } - } - if (!behavior.addNew) { - ourIndex = 0; - setSelection(doc, new Selection([ourRange], 0), sel_mouse); - startSel = doc.sel; - } else if (ourIndex == -1) { - ourIndex = ranges.length; - setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex), { - scroll: false, - origin: "*mouse" - }); - } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) { - setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), { - scroll: false, - origin: "*mouse" - }); - startSel = doc.sel; - } else { - replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); - } - var lastPos = start; - function extendTo(pos) { - if (cmp(lastPos, pos) == 0) { - return; - } - lastPos = pos; - if (behavior.unit == "rectangle") { - var ranges = [], - tabSize = cm.options.tabSize; - var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); - var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); - var left = Math.min(startCol, posCol), - right = Math.max(startCol, posCol); - for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); line <= end; line++) { - var text = getLine(doc, line).text, - leftPos = findColumn(text, left, tabSize); - if (left == right) { - ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); - } else if (text.length > leftPos) { - ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); - } - } - if (!ranges.length) { - ranges.push(new Range(start, start)); - } - setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), { - origin: "*mouse", - scroll: false - }); - cm.scrollIntoView(pos); - } else { - var oldRange = ourRange; - var range = rangeForUnit(cm, pos, behavior.unit); - var anchor = oldRange.anchor, - head; - if (cmp(range.anchor, anchor) > 0) { - head = range.head; - anchor = minPos(oldRange.from(), range.anchor); - } else { - head = range.anchor; - anchor = maxPos(oldRange.to(), range.head); - } - var ranges$1 = startSel.ranges.slice(0); - ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head)); - setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse); - } - } - var editorSize = display.wrapper.getBoundingClientRect(); - // Used to ensure timeout re-tries don't fire when another extend - // happened in the meantime (clearTimeout isn't reliable -- at - // least on Chrome, the timeouts still happen even when cleared, - // if the clear happens after their scheduled firing time). - var counter = 0; - function extend(e) { - var curCount = ++counter; - var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle"); - if (!cur) { - return; - } - if (cmp(cur, lastPos) != 0) { - cm.curOp.focus = activeElt(); - extendTo(cur); - var visible = visibleLines(display, doc); - if (cur.line >= visible.to || cur.line < visible.from) { - setTimeout(operation(cm, function () { - if (counter == curCount) { - extend(e); - } - }), 150); - } - } else { - var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; - if (outside) { - setTimeout(operation(cm, function () { - if (counter != curCount) { - return; - } - display.scroller.scrollTop += outside; - extend(e); - }), 50); - } - } - } - function done(e) { - cm.state.selectingText = false; - counter = Infinity; - // If e is null or undefined we interpret this as someone trying - // to explicitly cancel the selection rather than the user - // letting go of the mouse button. - if (e) { - e_preventDefault(e); - display.input.focus(); - } - off(display.wrapper.ownerDocument, "mousemove", move); - off(display.wrapper.ownerDocument, "mouseup", up); - doc.history.lastSelOrigin = null; - } - var move = operation(cm, function (e) { - if (e.buttons === 0 || !e_button(e)) { - done(e); - } else { - extend(e); - } - }); - var up = operation(cm, done); - cm.state.selectingText = up; - on(display.wrapper.ownerDocument, "mousemove", move); - on(display.wrapper.ownerDocument, "mouseup", up); - } - - // Used when mouse-selecting to adjust the anchor to the proper side - // of a bidi jump depending on the visual position of the head. - function bidiSimplify(cm, range) { - var anchor = range.anchor; - var head = range.head; - var anchorLine = getLine(cm.doc, anchor.line); - if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { - return range; - } - var order = getOrder(anchorLine); - if (!order) { - return range; - } - var index = getBidiPartAt(order, anchor.ch, anchor.sticky), - part = order[index]; - if (part.from != anchor.ch && part.to != anchor.ch) { - return range; - } - var boundary = index + (part.from == anchor.ch == (part.level != 1) ? 0 : 1); - if (boundary == 0 || boundary == order.length) { - return range; - } - - // Compute the relative visual position of the head compared to the - // anchor (<0 is to the left, >0 to the right) - var leftSide; - if (head.line != anchor.line) { - leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0; - } else { - var headIndex = getBidiPartAt(order, head.ch, head.sticky); - var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1); - if (headIndex == boundary - 1 || headIndex == boundary) { - leftSide = dir < 0; - } else { - leftSide = dir > 0; - } - } - var usePart = order[boundary + (leftSide ? -1 : 0)]; - var from = leftSide == (usePart.level == 1); - var ch = from ? usePart.from : usePart.to, - sticky = from ? "after" : "before"; - return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head); - } - - // Determines whether an event happened in the gutter, and fires the - // handlers for the corresponding event. - function gutterEvent(cm, e, type, prevent) { - var mX, mY; - if (e.touches) { - mX = e.touches[0].clientX; - mY = e.touches[0].clientY; - } else { - try { - mX = e.clientX; - mY = e.clientY; - } catch (e$1) { - return false; - } - } - if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { - return false; - } - if (prevent) { - e_preventDefault(e); - } - var display = cm.display; - var lineBox = display.lineDiv.getBoundingClientRect(); - if (mY > lineBox.bottom || !hasHandler(cm, type)) { - return e_defaultPrevented(e); - } - mY -= lineBox.top - display.viewOffset; - for (var i = 0; i < cm.display.gutterSpecs.length; ++i) { - var g = display.gutters.childNodes[i]; - if (g && g.getBoundingClientRect().right >= mX) { - var line = lineAtHeight(cm.doc, mY); - var gutter = cm.display.gutterSpecs[i]; - signal(cm, type, cm, line, gutter.className, e); - return e_defaultPrevented(e); - } - } - } - function clickInGutter(cm, e) { - return gutterEvent(cm, e, "gutterClick", true); - } - - // CONTEXT MENU HANDLING - - // To make the context menu work, we need to briefly unhide the - // textarea (making it as unobtrusive as possible) to let the - // right-click take effect on it. - function onContextMenu(cm, e) { - if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { - return; - } - if (signalDOMEvent(cm, e, "contextmenu")) { - return; - } - if (!captureRightClick) { - cm.display.input.onContextMenu(e); - } - } - function contextMenuInGutter(cm, e) { - if (!hasHandler(cm, "gutterContextMenu")) { - return false; - } - return gutterEvent(cm, e, "gutterContextMenu", false); - } - function themeChanged(cm) { - cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); - clearCaches(cm); - } - var Init = { - toString: function () { - return "CodeMirror.Init"; - } - }; - var defaults = {}; - var optionHandlers = {}; - function defineOptions(CodeMirror) { - var optionHandlers = CodeMirror.optionHandlers; - function option(name, deflt, handle, notOnInit) { - CodeMirror.defaults[name] = deflt; - if (handle) { - optionHandlers[name] = notOnInit ? function (cm, val, old) { - if (old != Init) { - handle(cm, val, old); - } - } : handle; - } - } - CodeMirror.defineOption = option; - - // Passed to option handlers when there is no old value. - CodeMirror.Init = Init; - - // These two are, on init, called from the constructor because they - // have to be initialized before the editor can start at all. - option("value", "", function (cm, val) { - return cm.setValue(val); - }, true); - option("mode", null, function (cm, val) { - cm.doc.modeOption = val; - loadMode(cm); - }, true); - option("indentUnit", 2, loadMode, true); - option("indentWithTabs", false); - option("smartIndent", true); - option("tabSize", 4, function (cm) { - resetModeState(cm); - clearCaches(cm); - regChange(cm); - }, true); - option("lineSeparator", null, function (cm, val) { - cm.doc.lineSep = val; - if (!val) { - return; - } - var newBreaks = [], - lineNo = cm.doc.first; - cm.doc.iter(function (line) { - for (var pos = 0;;) { - var found = line.text.indexOf(val, pos); - if (found == -1) { - break; - } - pos = found + val.length; - newBreaks.push(Pos(lineNo, found)); - } - lineNo++; - }); - for (var i = newBreaks.length - 1; i >= 0; i--) { - replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); - } - }); - option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) { - cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); - if (old != Init) { - cm.refresh(); - } - }); - option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { - return cm.refresh(); - }, true); - option("electricChars", true); - option("inputStyle", mobile ? "contenteditable" : "textarea", function () { - throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME - }, true); - option("spellcheck", false, function (cm, val) { - return cm.getInputField().spellcheck = val; - }, true); - option("autocorrect", false, function (cm, val) { - return cm.getInputField().autocorrect = val; - }, true); - option("autocapitalize", false, function (cm, val) { - return cm.getInputField().autocapitalize = val; - }, true); - option("rtlMoveVisually", !windows); - option("wholeLineUpdateBefore", true); - option("theme", "default", function (cm) { - themeChanged(cm); - updateGutters(cm); - }, true); - option("keyMap", "default", function (cm, val, old) { - var next = getKeyMap(val); - var prev = old != Init && getKeyMap(old); - if (prev && prev.detach) { - prev.detach(cm, next); - } - if (next.attach) { - next.attach(cm, prev || null); - } - }); - option("extraKeys", null); - option("configureMouse", null); - option("lineWrapping", false, wrappingChanged, true); - option("gutters", [], function (cm, val) { - cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers); - updateGutters(cm); - }, true); - option("fixedGutter", true, function (cm, val) { - cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; - cm.refresh(); - }, true); - option("coverGutterNextToScrollbar", false, function (cm) { - return updateScrollbars(cm); - }, true); - option("scrollbarStyle", "native", function (cm) { - initScrollbars(cm); - updateScrollbars(cm); - cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); - cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); - }, true); - option("lineNumbers", false, function (cm, val) { - cm.display.gutterSpecs = getGutters(cm.options.gutters, val); - updateGutters(cm); - }, true); - option("firstLineNumber", 1, updateGutters, true); - option("lineNumberFormatter", function (integer) { - return integer; - }, updateGutters, true); - option("showCursorWhenSelecting", false, updateSelection, true); - option("resetSelectionOnContextMenu", true); - option("lineWiseCopyCut", true); - option("pasteLinesPerSelection", true); - option("selectionsMayTouch", false); - option("readOnly", false, function (cm, val) { - if (val == "nocursor") { - onBlur(cm); - cm.display.input.blur(); - } - cm.display.input.readOnlyChanged(val); - }); - option("screenReaderLabel", null, function (cm, val) { - val = val === '' ? null : val; - cm.display.input.screenReaderLabelChanged(val); - }); - option("disableInput", false, function (cm, val) { - if (!val) { - cm.display.input.reset(); - } - }, true); - option("dragDrop", true, dragDropChanged); - option("allowDropFileTypes", null); - option("cursorBlinkRate", 530); - option("cursorScrollMargin", 0); - option("cursorHeight", 1, updateSelection, true); - option("singleCursorHeightPerLine", true, updateSelection, true); - option("workTime", 100); - option("workDelay", 100); - option("flattenSpans", true, resetModeState, true); - option("addModeClass", false, resetModeState, true); - option("pollInterval", 100); - option("undoDepth", 200, function (cm, val) { - return cm.doc.history.undoDepth = val; - }); - option("historyEventDelay", 1250); - option("viewportMargin", 10, function (cm) { - return cm.refresh(); - }, true); - option("maxHighlightLength", 10000, resetModeState, true); - option("moveInputWithCursor", true, function (cm, val) { - if (!val) { - cm.display.input.resetPosition(); - } - }); - option("tabindex", null, function (cm, val) { - return cm.display.input.getField().tabIndex = val || ""; - }); - option("autofocus", null); - option("direction", "ltr", function (cm, val) { - return cm.doc.setDirection(val); - }, true); - option("phrases", null); - } - function dragDropChanged(cm, value, old) { - var wasOn = old && old != Init; - if (!value != !wasOn) { - var funcs = cm.display.dragFunctions; - var toggle = value ? on : off; - toggle(cm.display.scroller, "dragstart", funcs.start); - toggle(cm.display.scroller, "dragenter", funcs.enter); - toggle(cm.display.scroller, "dragover", funcs.over); - toggle(cm.display.scroller, "dragleave", funcs.leave); - toggle(cm.display.scroller, "drop", funcs.drop); - } - } - function wrappingChanged(cm) { - if (cm.options.lineWrapping) { - addClass(cm.display.wrapper, "CodeMirror-wrap"); - cm.display.sizer.style.minWidth = ""; - cm.display.sizerWidth = null; - } else { - rmClass(cm.display.wrapper, "CodeMirror-wrap"); - findMaxLine(cm); - } - estimateLineHeights(cm); - regChange(cm); - clearCaches(cm); - setTimeout(function () { - return updateScrollbars(cm); - }, 100); - } - - // A CodeMirror instance represents an editor. This is the object - // that user code is usually dealing with. - - function CodeMirror(place, options) { - var this$1 = this; - if (!(this instanceof CodeMirror)) { - return new CodeMirror(place, options); - } - this.options = options = options ? copyObj(options) : {}; - // Determine effective options based on given values and defaults. - copyObj(defaults, options, false); - var doc = options.value; - if (typeof doc == "string") { - doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); - } else if (options.mode) { - doc.modeOption = options.mode; - } - this.doc = doc; - var input = new CodeMirror.inputStyles[options.inputStyle](this); - var display = this.display = new Display(place, doc, input, options); - display.wrapper.CodeMirror = this; - themeChanged(this); - if (options.lineWrapping) { - this.display.wrapper.className += " CodeMirror-wrap"; - } - initScrollbars(this); - this.state = { - keyMaps: [], - // stores maps added by addKeyMap - overlays: [], - // highlighting overlays, as added by addOverlay - modeGen: 0, - // bumped when mode/overlay changes, used to invalidate highlighting info - overwrite: false, - delayingBlurEvent: false, - focused: false, - suppressEdits: false, - // used to disable editing during key handlers when in readOnly mode - pasteIncoming: -1, - cutIncoming: -1, - // help recognize paste/cut edits in input.poll - selectingText: false, - draggingText: false, - highlight: new Delayed(), - // stores highlight worker timeout - keySeq: null, - // Unfinished key sequence - specialChars: null - }; - if (options.autofocus && !mobile) { - display.input.focus(); - } - - // Override magic textarea content restore that IE sometimes does - // on our hidden textarea on reload - if (ie && ie_version < 11) { - setTimeout(function () { - return this$1.display.input.reset(true); - }, 20); - } - registerEventHandlers(this); - ensureGlobalHandlers(); - startOperation(this); - this.curOp.forceUpdate = true; - attachDoc(this, doc); - if (options.autofocus && !mobile || this.hasFocus()) { - setTimeout(function () { - if (this$1.hasFocus() && !this$1.state.focused) { - onFocus(this$1); - } - }, 20); - } else { - onBlur(this); - } - for (var opt in optionHandlers) { - if (optionHandlers.hasOwnProperty(opt)) { - optionHandlers[opt](this, options[opt], Init); - } - } - maybeUpdateLineNumberWidth(this); - if (options.finishInit) { - options.finishInit(this); - } - for (var i = 0; i < initHooks.length; ++i) { - initHooks[i](this); - } - endOperation(this); - // Suppress optimizelegibility in Webkit, since it breaks text - // measuring on line wrapping boundaries. - if (webkit && options.lineWrapping && getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") { - display.lineDiv.style.textRendering = "auto"; - } - } - - // The default configuration options. - CodeMirror.defaults = defaults; - // Functions to run when options are changed. - CodeMirror.optionHandlers = optionHandlers; - - // Attach the necessary event handlers when initializing the editor - function registerEventHandlers(cm) { - var d = cm.display; - on(d.scroller, "mousedown", operation(cm, onMouseDown)); - // Older IE's will not fire a second mousedown for a double click - if (ie && ie_version < 11) { - on(d.scroller, "dblclick", operation(cm, function (e) { - if (signalDOMEvent(cm, e)) { - return; - } - var pos = posFromMouse(cm, e); - if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { - return; - } - e_preventDefault(e); - var word = cm.findWordAt(pos); - extendSelection(cm.doc, word.anchor, word.head); - })); - } else { - on(d.scroller, "dblclick", function (e) { - return signalDOMEvent(cm, e) || e_preventDefault(e); - }); - } - // Some browsers fire contextmenu *after* opening the menu, at - // which point we can't mess with it anymore. Context menu is - // handled in onMouseDown for these browsers. - on(d.scroller, "contextmenu", function (e) { - return onContextMenu(cm, e); - }); - on(d.input.getField(), "contextmenu", function (e) { - if (!d.scroller.contains(e.target)) { - onContextMenu(cm, e); - } - }); - - // Used to suppress mouse event handling when a touch happens - var touchFinished, - prevTouch = { - end: 0 - }; - function finishTouch() { - if (d.activeTouch) { - touchFinished = setTimeout(function () { - return d.activeTouch = null; - }, 1000); - prevTouch = d.activeTouch; - prevTouch.end = +new Date(); - } - } - function isMouseLikeTouchEvent(e) { - if (e.touches.length != 1) { - return false; - } - var touch = e.touches[0]; - return touch.radiusX <= 1 && touch.radiusY <= 1; - } - function farAway(touch, other) { - if (other.left == null) { - return true; - } - var dx = other.left - touch.left, - dy = other.top - touch.top; - return dx * dx + dy * dy > 20 * 20; - } - on(d.scroller, "touchstart", function (e) { - if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) { - d.input.ensurePolled(); - clearTimeout(touchFinished); - var now = +new Date(); - d.activeTouch = { - start: now, - moved: false, - prev: now - prevTouch.end <= 300 ? prevTouch : null - }; - if (e.touches.length == 1) { - d.activeTouch.left = e.touches[0].pageX; - d.activeTouch.top = e.touches[0].pageY; - } - } - }); - on(d.scroller, "touchmove", function () { - if (d.activeTouch) { - d.activeTouch.moved = true; - } - }); - on(d.scroller, "touchend", function (e) { - var touch = d.activeTouch; - if (touch && !eventInWidget(d, e) && touch.left != null && !touch.moved && new Date() - touch.start < 300) { - var pos = cm.coordsChar(d.activeTouch, "page"), - range; - if (!touch.prev || farAway(touch, touch.prev)) - // Single tap - { - range = new Range(pos, pos); - } else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) - // Double tap - { - range = cm.findWordAt(pos); - } else - // Triple tap - { - range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); - } - cm.setSelection(range.anchor, range.head); - cm.focus(); - e_preventDefault(e); - } - finishTouch(); - }); - on(d.scroller, "touchcancel", finishTouch); - - // Sync scrolling between fake scrollbars and real scrollable - // area, ensure viewport is updated when scrolling. - on(d.scroller, "scroll", function () { - if (d.scroller.clientHeight) { - updateScrollTop(cm, d.scroller.scrollTop); - setScrollLeft(cm, d.scroller.scrollLeft, true); - signal(cm, "scroll", cm); - } - }); - - // Listen to wheel events in order to try and update the viewport on time. - on(d.scroller, "mousewheel", function (e) { - return onScrollWheel(cm, e); - }); - on(d.scroller, "DOMMouseScroll", function (e) { - return onScrollWheel(cm, e); - }); - - // Prevent wrapper from ever scrolling - on(d.wrapper, "scroll", function () { - return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; - }); - d.dragFunctions = { - enter: function (e) { - if (!signalDOMEvent(cm, e)) { - e_stop(e); - } - }, - over: function (e) { - if (!signalDOMEvent(cm, e)) { - onDragOver(cm, e); - e_stop(e); - } - }, - start: function (e) { - return onDragStart(cm, e); - }, - drop: operation(cm, onDrop), - leave: function (e) { - if (!signalDOMEvent(cm, e)) { - clearDragCursor(cm); - } - } - }; - var inp = d.input.getField(); - on(inp, "keyup", function (e) { - return onKeyUp.call(cm, e); - }); - on(inp, "keydown", operation(cm, onKeyDown)); - on(inp, "keypress", operation(cm, onKeyPress)); - on(inp, "focus", function (e) { - return onFocus(cm, e); - }); - on(inp, "blur", function (e) { - return onBlur(cm, e); - }); - } - var initHooks = []; - CodeMirror.defineInitHook = function (f) { - return initHooks.push(f); - }; - - // Indent the given line. The how parameter can be "smart", - // "add"/null, "subtract", or "prev". When aggressive is false - // (typically set to true for forced single-line indents), empty - // lines are not indented, and places where the mode returns Pass - // are left alone. - function indentLine(cm, n, how, aggressive) { - var doc = cm.doc, - state; - if (how == null) { - how = "add"; - } - if (how == "smart") { - // Fall back to "prev" when the mode doesn't have an indentation - // method. - if (!doc.mode.indent) { - how = "prev"; - } else { - state = getContextBefore(cm, n).state; - } - } - var tabSize = cm.options.tabSize; - var line = getLine(doc, n), - curSpace = countColumn(line.text, null, tabSize); - if (line.stateAfter) { - line.stateAfter = null; - } - var curSpaceString = line.text.match(/^\s*/)[0], - indentation; - if (!aggressive && !/\S/.test(line.text)) { - indentation = 0; - how = "not"; - } else if (how == "smart") { - indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); - if (indentation == Pass || indentation > 150) { - if (!aggressive) { - return; - } - how = "prev"; - } - } - if (how == "prev") { - if (n > doc.first) { - indentation = countColumn(getLine(doc, n - 1).text, null, tabSize); - } else { - indentation = 0; - } - } else if (how == "add") { - indentation = curSpace + cm.options.indentUnit; - } else if (how == "subtract") { - indentation = curSpace - cm.options.indentUnit; - } else if (typeof how == "number") { - indentation = curSpace + how; - } - indentation = Math.max(0, indentation); - var indentString = "", - pos = 0; - if (cm.options.indentWithTabs) { - for (var i = Math.floor(indentation / tabSize); i; --i) { - pos += tabSize; - indentString += "\t"; - } - } - if (pos < indentation) { - indentString += spaceStr(indentation - pos); - } - if (indentString != curSpaceString) { - replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); - line.stateAfter = null; - return true; - } else { - // Ensure that, if the cursor was in the whitespace at the start - // of the line, it is moved to the end of that space. - for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) { - var range = doc.sel.ranges[i$1]; - if (range.head.line == n && range.head.ch < curSpaceString.length) { - var pos$1 = Pos(n, curSpaceString.length); - replaceOneSelection(doc, i$1, new Range(pos$1, pos$1)); - break; - } - } - } - } - - // This will be set to a {lineWise: bool, text: [string]} object, so - // that, when pasting, we know what kind of selections the copied - // text was made out of. - var lastCopied = null; - function setLastCopied(newLastCopied) { - lastCopied = newLastCopied; - } - function applyTextInput(cm, inserted, deleted, sel, origin) { - var doc = cm.doc; - cm.display.shift = false; - if (!sel) { - sel = doc.sel; - } - var recent = +new Date() - 200; - var paste = origin == "paste" || cm.state.pasteIncoming > recent; - var textLines = splitLinesAuto(inserted), - multiPaste = null; - // When pasting N lines into N selections, insert one line per selection - if (paste && sel.ranges.length > 1) { - if (lastCopied && lastCopied.text.join("\n") == inserted) { - if (sel.ranges.length % lastCopied.text.length == 0) { - multiPaste = []; - for (var i = 0; i < lastCopied.text.length; i++) { - multiPaste.push(doc.splitLines(lastCopied.text[i])); - } - } - } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) { - multiPaste = map(textLines, function (l) { - return [l]; - }); - } - } - var updateInput = cm.curOp.updateInput; - // Normal behavior is to insert the new text into every selection - for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) { - var range = sel.ranges[i$1]; - var from = range.from(), - to = range.to(); - if (range.empty()) { - if (deleted && deleted > 0) - // Handle deletion - { - from = Pos(from.line, from.ch - deleted); - } else if (cm.state.overwrite && !paste) - // Handle overwrite - { - to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); - } else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n")) { - from = to = Pos(from.line, 0); - } - } - var changeEvent = { - from: from, - to: to, - text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines, - origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input") - }; - makeChange(cm.doc, changeEvent); - signalLater(cm, "inputRead", cm, changeEvent); - } - if (inserted && !paste) { - triggerElectric(cm, inserted); - } - ensureCursorVisible(cm); - if (cm.curOp.updateInput < 2) { - cm.curOp.updateInput = updateInput; - } - cm.curOp.typing = true; - cm.state.pasteIncoming = cm.state.cutIncoming = -1; - } - function handlePaste(e, cm) { - var pasted = e.clipboardData && e.clipboardData.getData("Text"); - if (pasted) { - e.preventDefault(); - if (!cm.isReadOnly() && !cm.options.disableInput) { - runInOp(cm, function () { - return applyTextInput(cm, pasted, 0, null, "paste"); - }); - } - return true; - } - } - function triggerElectric(cm, inserted) { - // When an 'electric' character is inserted, immediately trigger a reindent - if (!cm.options.electricChars || !cm.options.smartIndent) { - return; - } - var sel = cm.doc.sel; - for (var i = sel.ranges.length - 1; i >= 0; i--) { - var range = sel.ranges[i]; - if (range.head.ch > 100 || i && sel.ranges[i - 1].head.line == range.head.line) { - continue; - } - var mode = cm.getModeAt(range.head); - var indented = false; - if (mode.electricChars) { - for (var j = 0; j < mode.electricChars.length; j++) { - if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { - indented = indentLine(cm, range.head.line, "smart"); - break; - } - } - } else if (mode.electricInput) { - if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch))) { - indented = indentLine(cm, range.head.line, "smart"); - } - } - if (indented) { - signalLater(cm, "electricInput", cm, range.head.line); - } - } - } - function copyableRanges(cm) { - var text = [], - ranges = []; - for (var i = 0; i < cm.doc.sel.ranges.length; i++) { - var line = cm.doc.sel.ranges[i].head.line; - var lineRange = { - anchor: Pos(line, 0), - head: Pos(line + 1, 0) - }; - ranges.push(lineRange); - text.push(cm.getRange(lineRange.anchor, lineRange.head)); - } - return { - text: text, - ranges: ranges - }; - } - function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) { - field.setAttribute("autocorrect", autocorrect ? "" : "off"); - field.setAttribute("autocapitalize", autocapitalize ? "" : "off"); - field.setAttribute("spellcheck", !!spellcheck); - } - function hiddenTextarea() { - var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; min-height: 1em; outline: none"); - var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); - // The textarea is kept positioned near the cursor to prevent the - // fact that it'll be scrolled into view on input from scrolling - // our fake cursor out of view. On webkit, when wrap=off, paste is - // very slow. So make the area wide instead. - if (webkit) { - te.style.width = "1000px"; - } else { - te.setAttribute("wrap", "off"); - } - // If border: 0; -- iOS fails to open keyboard (issue #1287) - if (ios) { - te.style.border = "1px solid black"; - } - disableBrowserMagic(te); - return div; - } - - // The publicly visible API. Note that methodOp(f) means - // 'wrap f in an operation, performed on its `this` parameter'. - - // This is not the complete set of editor methods. Most of the - // methods defined on the Doc type are also injected into - // CodeMirror.prototype, for backwards compatibility and - // convenience. - - function addEditorMethods(CodeMirror) { - var optionHandlers = CodeMirror.optionHandlers; - var helpers = CodeMirror.helpers = {}; - CodeMirror.prototype = { - constructor: CodeMirror, - focus: function () { - window.focus(); - this.display.input.focus(); - }, - setOption: function (option, value) { - var options = this.options, - old = options[option]; - if (options[option] == value && option != "mode") { - return; - } - options[option] = value; - if (optionHandlers.hasOwnProperty(option)) { - operation(this, optionHandlers[option])(this, value, old); - } - signal(this, "optionChange", this, option); - }, - getOption: function (option) { - return this.options[option]; - }, - getDoc: function () { - return this.doc; - }, - addKeyMap: function (map, bottom) { - this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map)); - }, - removeKeyMap: function (map) { - var maps = this.state.keyMaps; - for (var i = 0; i < maps.length; ++i) { - if (maps[i] == map || maps[i].name == map) { - maps.splice(i, 1); - return true; - } - } - }, - addOverlay: methodOp(function (spec, options) { - var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); - if (mode.startState) { - throw new Error("Overlays may not be stateful."); - } - insertSorted(this.state.overlays, { - mode: mode, - modeSpec: spec, - opaque: options && options.opaque, - priority: options && options.priority || 0 - }, function (overlay) { - return overlay.priority; - }); - this.state.modeGen++; - regChange(this); - }), - removeOverlay: methodOp(function (spec) { - var overlays = this.state.overlays; - for (var i = 0; i < overlays.length; ++i) { - var cur = overlays[i].modeSpec; - if (cur == spec || typeof spec == "string" && cur.name == spec) { - overlays.splice(i, 1); - this.state.modeGen++; - regChange(this); - return; - } - } - }), - indentLine: methodOp(function (n, dir, aggressive) { - if (typeof dir != "string" && typeof dir != "number") { - if (dir == null) { - dir = this.options.smartIndent ? "smart" : "prev"; - } else { - dir = dir ? "add" : "subtract"; - } - } - if (isLine(this.doc, n)) { - indentLine(this, n, dir, aggressive); - } - }), - indentSelection: methodOp(function (how) { - var ranges = this.doc.sel.ranges, - end = -1; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - if (!range.empty()) { - var from = range.from(), - to = range.to(); - var start = Math.max(end, from.line); - end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; - for (var j = start; j < end; ++j) { - indentLine(this, j, how); - } - var newRanges = this.doc.sel.ranges; - if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) { - replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); - } - } else if (range.head.line > end) { - indentLine(this, range.head.line, how, true); - end = range.head.line; - if (i == this.doc.sel.primIndex) { - ensureCursorVisible(this); - } - } - } - }), - // Fetch the parser token for a given character. Useful for hacks - // that want to inspect the mode state (say, for completion). - getTokenAt: function (pos, precise) { - return takeToken(this, pos, precise); - }, - getLineTokens: function (line, precise) { - return takeToken(this, Pos(line), precise, true); - }, - getTokenTypeAt: function (pos) { - pos = clipPos(this.doc, pos); - var styles = getLineStyles(this, getLine(this.doc, pos.line)); - var before = 0, - after = (styles.length - 1) / 2, - ch = pos.ch; - var type; - if (ch == 0) { - type = styles[2]; - } else { - for (;;) { - var mid = before + after >> 1; - if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { - after = mid; - } else if (styles[mid * 2 + 1] < ch) { - before = mid + 1; - } else { - type = styles[mid * 2 + 2]; - break; - } - } - } - var cut = type ? type.indexOf("overlay ") : -1; - return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1); - }, - getModeAt: function (pos) { - var mode = this.doc.mode; - if (!mode.innerMode) { - return mode; - } - return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode; - }, - getHelper: function (pos, type) { - return this.getHelpers(pos, type)[0]; - }, - getHelpers: function (pos, type) { - var found = []; - if (!helpers.hasOwnProperty(type)) { - return found; - } - var help = helpers[type], - mode = this.getModeAt(pos); - if (typeof mode[type] == "string") { - if (help[mode[type]]) { - found.push(help[mode[type]]); - } - } else if (mode[type]) { - for (var i = 0; i < mode[type].length; i++) { - var val = help[mode[type][i]]; - if (val) { - found.push(val); - } - } - } else if (mode.helperType && help[mode.helperType]) { - found.push(help[mode.helperType]); - } else if (help[mode.name]) { - found.push(help[mode.name]); - } - for (var i$1 = 0; i$1 < help._global.length; i$1++) { - var cur = help._global[i$1]; - if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) { - found.push(cur.val); - } - } - return found; - }, - getStateAfter: function (line, precise) { - var doc = this.doc; - line = clipLine(doc, line == null ? doc.first + doc.size - 1 : line); - return getContextBefore(this, line + 1, precise).state; - }, - cursorCoords: function (start, mode) { - var pos, - range = this.doc.sel.primary(); - if (start == null) { - pos = range.head; - } else if (typeof start == "object") { - pos = clipPos(this.doc, start); - } else { - pos = start ? range.from() : range.to(); - } - return cursorCoords(this, pos, mode || "page"); - }, - charCoords: function (pos, mode) { - return charCoords(this, clipPos(this.doc, pos), mode || "page"); - }, - coordsChar: function (coords, mode) { - coords = fromCoordSystem(this, coords, mode || "page"); - return coordsChar(this, coords.left, coords.top); - }, - lineAtHeight: function (height, mode) { - height = fromCoordSystem(this, { - top: height, - left: 0 - }, mode || "page").top; - return lineAtHeight(this.doc, height + this.display.viewOffset); - }, - heightAtLine: function (line, mode, includeWidgets) { - var end = false, - lineObj; - if (typeof line == "number") { - var last = this.doc.first + this.doc.size - 1; - if (line < this.doc.first) { - line = this.doc.first; - } else if (line > last) { - line = last; - end = true; - } - lineObj = getLine(this.doc, line); - } else { - lineObj = line; - } - return intoCoordSystem(this, lineObj, { - top: 0, - left: 0 - }, mode || "page", includeWidgets || end).top + (end ? this.doc.height - heightAtLine(lineObj) : 0); - }, - defaultTextHeight: function () { - return textHeight(this.display); - }, - defaultCharWidth: function () { - return charWidth(this.display); - }, - getViewport: function () { - return { - from: this.display.viewFrom, - to: this.display.viewTo - }; - }, - addWidget: function (pos, node, scroll, vert, horiz) { - var display = this.display; - pos = cursorCoords(this, clipPos(this.doc, pos)); - var top = pos.bottom, - left = pos.left; - node.style.position = "absolute"; - node.setAttribute("cm-ignore-events", "true"); - this.display.input.setUneditable(node); - display.sizer.appendChild(node); - if (vert == "over") { - top = pos.top; - } else if (vert == "above" || vert == "near") { - var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), - hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); - // Default to positioning above (if specified and possible); otherwise default to positioning below - if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) { - top = pos.top - node.offsetHeight; - } else if (pos.bottom + node.offsetHeight <= vspace) { - top = pos.bottom; - } - if (left + node.offsetWidth > hspace) { - left = hspace - node.offsetWidth; - } - } - node.style.top = top + "px"; - node.style.left = node.style.right = ""; - if (horiz == "right") { - left = display.sizer.clientWidth - node.offsetWidth; - node.style.right = "0px"; - } else { - if (horiz == "left") { - left = 0; - } else if (horiz == "middle") { - left = (display.sizer.clientWidth - node.offsetWidth) / 2; - } - node.style.left = left + "px"; - } - if (scroll) { - scrollIntoView(this, { - left: left, - top: top, - right: left + node.offsetWidth, - bottom: top + node.offsetHeight - }); - } - }, - triggerOnKeyDown: methodOp(onKeyDown), - triggerOnKeyPress: methodOp(onKeyPress), - triggerOnKeyUp: onKeyUp, - triggerOnMouseDown: methodOp(onMouseDown), - execCommand: function (cmd) { - if (commands.hasOwnProperty(cmd)) { - return commands[cmd].call(null, this); - } - }, - triggerElectric: methodOp(function (text) { - triggerElectric(this, text); - }), - findPosH: function (from, amount, unit, visually) { - var dir = 1; - if (amount < 0) { - dir = -1; - amount = -amount; - } - var cur = clipPos(this.doc, from); - for (var i = 0; i < amount; ++i) { - cur = findPosH(this.doc, cur, dir, unit, visually); - if (cur.hitSide) { - break; - } - } - return cur; - }, - moveH: methodOp(function (dir, unit) { - var this$1 = this; - this.extendSelectionsBy(function (range) { - if (this$1.display.shift || this$1.doc.extend || range.empty()) { - return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually); - } else { - return dir < 0 ? range.from() : range.to(); - } - }, sel_move); - }), - deleteH: methodOp(function (dir, unit) { - var sel = this.doc.sel, - doc = this.doc; - if (sel.somethingSelected()) { - doc.replaceSelection("", null, "+delete"); - } else { - deleteNearSelection(this, function (range) { - var other = findPosH(doc, range.head, dir, unit, false); - return dir < 0 ? { - from: other, - to: range.head - } : { - from: range.head, - to: other - }; - }); - } - }), - findPosV: function (from, amount, unit, goalColumn) { - var dir = 1, - x = goalColumn; - if (amount < 0) { - dir = -1; - amount = -amount; - } - var cur = clipPos(this.doc, from); - for (var i = 0; i < amount; ++i) { - var coords = cursorCoords(this, cur, "div"); - if (x == null) { - x = coords.left; - } else { - coords.left = x; - } - cur = findPosV(this, coords, dir, unit); - if (cur.hitSide) { - break; - } - } - return cur; - }, - moveV: methodOp(function (dir, unit) { - var this$1 = this; - var doc = this.doc, - goals = []; - var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected(); - doc.extendSelectionsBy(function (range) { - if (collapse) { - return dir < 0 ? range.from() : range.to(); - } - var headPos = cursorCoords(this$1, range.head, "div"); - if (range.goalColumn != null) { - headPos.left = range.goalColumn; - } - goals.push(headPos.left); - var pos = findPosV(this$1, headPos, dir, unit); - if (unit == "page" && range == doc.sel.primary()) { - addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); - } - return pos; - }, sel_move); - if (goals.length) { - for (var i = 0; i < doc.sel.ranges.length; i++) { - doc.sel.ranges[i].goalColumn = goals[i]; - } - } - }), - // Find the word at the given position (as returned by coordsChar). - findWordAt: function (pos) { - var doc = this.doc, - line = getLine(doc, pos.line).text; - var start = pos.ch, - end = pos.ch; - if (line) { - var helper = this.getHelper(pos, "wordChars"); - if ((pos.sticky == "before" || end == line.length) && start) { - --start; - } else { - ++end; - } - var startChar = line.charAt(start); - var check = isWordChar(startChar, helper) ? function (ch) { - return isWordChar(ch, helper); - } : /\s/.test(startChar) ? function (ch) { - return /\s/.test(ch); - } : function (ch) { - return !/\s/.test(ch) && !isWordChar(ch); - }; - while (start > 0 && check(line.charAt(start - 1))) { - --start; - } - while (end < line.length && check(line.charAt(end))) { - ++end; - } - } - return new Range(Pos(pos.line, start), Pos(pos.line, end)); - }, - toggleOverwrite: function (value) { - if (value != null && value == this.state.overwrite) { - return; - } - if (this.state.overwrite = !this.state.overwrite) { - addClass(this.display.cursorDiv, "CodeMirror-overwrite"); - } else { - rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); - } - signal(this, "overwriteToggle", this, this.state.overwrite); - }, - hasFocus: function () { - return this.display.input.getField() == activeElt(); - }, - isReadOnly: function () { - return !!(this.options.readOnly || this.doc.cantEdit); - }, - scrollTo: methodOp(function (x, y) { - scrollToCoords(this, x, y); - }), - getScrollInfo: function () { - var scroller = this.display.scroller; - return { - left: scroller.scrollLeft, - top: scroller.scrollTop, - height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, - width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, - clientHeight: displayHeight(this), - clientWidth: displayWidth(this) - }; - }, - scrollIntoView: methodOp(function (range, margin) { - if (range == null) { - range = { - from: this.doc.sel.primary().head, - to: null - }; - if (margin == null) { - margin = this.options.cursorScrollMargin; - } - } else if (typeof range == "number") { - range = { - from: Pos(range, 0), - to: null - }; - } else if (range.from == null) { - range = { - from: range, - to: null - }; - } - if (!range.to) { - range.to = range.from; - } - range.margin = margin || 0; - if (range.from.line != null) { - scrollToRange(this, range); - } else { - scrollToCoordsRange(this, range.from, range.to, range.margin); - } - }), - setSize: methodOp(function (width, height) { - var this$1 = this; - var interpret = function (val) { - return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; - }; - if (width != null) { - this.display.wrapper.style.width = interpret(width); - } - if (height != null) { - this.display.wrapper.style.height = interpret(height); - } - if (this.options.lineWrapping) { - clearLineMeasurementCache(this); - } - var lineNo = this.display.viewFrom; - this.doc.iter(lineNo, this.display.viewTo, function (line) { - if (line.widgets) { - for (var i = 0; i < line.widgets.length; i++) { - if (line.widgets[i].noHScroll) { - regLineChange(this$1, lineNo, "widget"); - break; - } - } - } - ++lineNo; - }); - this.curOp.forceUpdate = true; - signal(this, "refresh", this); - }), - operation: function (f) { - return runInOp(this, f); - }, - startOperation: function () { - return startOperation(this); - }, - endOperation: function () { - return endOperation(this); - }, - refresh: methodOp(function () { - var oldHeight = this.display.cachedTextHeight; - regChange(this); - this.curOp.forceUpdate = true; - clearCaches(this); - scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop); - updateGutterSpace(this.display); - if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping) { - estimateLineHeights(this); - } - signal(this, "refresh", this); - }), - swapDoc: methodOp(function (doc) { - var old = this.doc; - old.cm = null; - // Cancel the current text selection if any (#5821) - if (this.state.selectingText) { - this.state.selectingText(); - } - attachDoc(this, doc); - clearCaches(this); - this.display.input.reset(); - scrollToCoords(this, doc.scrollLeft, doc.scrollTop); - this.curOp.forceScroll = true; - signalLater(this, "swapDoc", this, old); - return old; - }), - phrase: function (phraseText) { - var phrases = this.options.phrases; - return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText; - }, - getInputField: function () { - return this.display.input.getField(); - }, - getWrapperElement: function () { - return this.display.wrapper; - }, - getScrollerElement: function () { - return this.display.scroller; - }, - getGutterElement: function () { - return this.display.gutters; - } - }; - eventMixin(CodeMirror); - CodeMirror.registerHelper = function (type, name, value) { - if (!helpers.hasOwnProperty(type)) { - helpers[type] = CodeMirror[type] = { - _global: [] - }; - } - helpers[type][name] = value; - }; - CodeMirror.registerGlobalHelper = function (type, name, predicate, value) { - CodeMirror.registerHelper(type, name, value); - helpers[type]._global.push({ - pred: predicate, - val: value - }); - }; - } - - // Used for horizontal relative motion. Dir is -1 or 1 (left or - // right), unit can be "codepoint", "char", "column" (like char, but - // doesn't cross line boundaries), "word" (across next word), or - // "group" (to the start of next group of word or - // non-word-non-whitespace chars). The visually param controls - // whether, in right-to-left text, direction 1 means to move towards - // the next index in the string, or towards the character to the right - // of the current position. The resulting position will have a - // hitSide=true property if it reached the end of the document. - function findPosH(doc, pos, dir, unit, visually) { - var oldPos = pos; - var origDir = dir; - var lineObj = getLine(doc, pos.line); - var lineDir = visually && doc.direction == "rtl" ? -dir : dir; - function findNextLine() { - var l = pos.line + lineDir; - if (l < doc.first || l >= doc.first + doc.size) { - return false; - } - pos = new Pos(l, pos.ch, pos.sticky); - return lineObj = getLine(doc, l); - } - function moveOnce(boundToLine) { - var next; - if (unit == "codepoint") { - var ch = lineObj.text.charCodeAt(pos.ch + (dir > 0 ? 0 : -1)); - if (isNaN(ch)) { - next = null; - } else { - var astral = dir > 0 ? ch >= 0xD800 && ch < 0xDC00 : ch >= 0xDC00 && ch < 0xDFFF; - next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir); - } - } else if (visually) { - next = moveVisually(doc.cm, lineObj, pos, dir); - } else { - next = moveLogically(lineObj, pos, dir); - } - if (next == null) { - if (!boundToLine && findNextLine()) { - pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); - } else { - return false; - } - } else { - pos = next; - } - return true; - } - if (unit == "char" || unit == "codepoint") { - moveOnce(); - } else if (unit == "column") { - moveOnce(true); - } else if (unit == "word" || unit == "group") { - var sawType = null, - group = unit == "group"; - var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); - for (var first = true;; first = false) { - if (dir < 0 && !moveOnce(!first)) { - break; - } - var cur = lineObj.text.charAt(pos.ch) || "\n"; - var type = isWordChar(cur, helper) ? "w" : group && cur == "\n" ? "n" : !group || /\s/.test(cur) ? null : "p"; - if (group && !first && !type) { - type = "s"; - } - if (sawType && sawType != type) { - if (dir < 0) { - dir = 1; - moveOnce(); - pos.sticky = "after"; - } - break; - } - if (type) { - sawType = type; - } - if (dir > 0 && !moveOnce(!first)) { - break; - } - } - } - var result = skipAtomic(doc, pos, oldPos, origDir, true); - if (equalCursorPos(oldPos, result)) { - result.hitSide = true; - } - return result; - } - - // For relative vertical movement. Dir may be -1 or 1. Unit can be - // "page" or "line". The resulting position will have a hitSide=true - // property if it reached the end of the document. - function findPosV(cm, pos, dir, unit) { - var doc = cm.doc, - x = pos.left, - y; - if (unit == "page") { - var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); - var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3); - y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount; - } else if (unit == "line") { - y = dir > 0 ? pos.bottom + 3 : pos.top - 3; - } - var target; - for (;;) { - target = coordsChar(cm, x, y); - if (!target.outside) { - break; - } - if (dir < 0 ? y <= 0 : y >= doc.height) { - target.hitSide = true; - break; - } - y += dir * 5; - } - return target; - } - - // CONTENTEDITABLE INPUT STYLE - - var ContentEditableInput = function (cm) { - this.cm = cm; - this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; - this.polling = new Delayed(); - this.composing = null; - this.gracePeriod = false; - this.readDOMTimeout = null; - }; - ContentEditableInput.prototype.init = function (display) { - var this$1 = this; - var input = this, - cm = input.cm; - var div = input.div = display.lineDiv; - div.contentEditable = true; - disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize); - function belongsToInput(e) { - for (var t = e.target; t; t = t.parentNode) { - if (t == div) { - return true; - } - if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { - break; - } - } - return false; - } - on(div, "paste", function (e) { - if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { - return; - } - // IE doesn't fire input events, so we schedule a read for the pasted content in this way - if (ie_version <= 11) { - setTimeout(operation(cm, function () { - return this$1.updateFromDOM(); - }), 20); - } - }); - on(div, "compositionstart", function (e) { - this$1.composing = { - data: e.data, - done: false - }; - }); - on(div, "compositionupdate", function (e) { - if (!this$1.composing) { - this$1.composing = { - data: e.data, - done: false - }; - } - }); - on(div, "compositionend", function (e) { - if (this$1.composing) { - if (e.data != this$1.composing.data) { - this$1.readFromDOMSoon(); - } - this$1.composing.done = true; - } - }); - on(div, "touchstart", function () { - return input.forceCompositionEnd(); - }); - on(div, "input", function () { - if (!this$1.composing) { - this$1.readFromDOMSoon(); - } - }); - function onCopyCut(e) { - if (!belongsToInput(e) || signalDOMEvent(cm, e)) { - return; - } - if (cm.somethingSelected()) { - setLastCopied({ - lineWise: false, - text: cm.getSelections() - }); - if (e.type == "cut") { - cm.replaceSelection("", null, "cut"); - } - } else if (!cm.options.lineWiseCopyCut) { - return; - } else { - var ranges = copyableRanges(cm); - setLastCopied({ - lineWise: true, - text: ranges.text - }); - if (e.type == "cut") { - cm.operation(function () { - cm.setSelections(ranges.ranges, 0, sel_dontScroll); - cm.replaceSelection("", null, "cut"); - }); - } - } - if (e.clipboardData) { - e.clipboardData.clearData(); - var content = lastCopied.text.join("\n"); - // iOS exposes the clipboard API, but seems to discard content inserted into it - e.clipboardData.setData("Text", content); - if (e.clipboardData.getData("Text") == content) { - e.preventDefault(); - return; - } - } - // Old-fashioned briefly-focus-a-textarea hack - var kludge = hiddenTextarea(), - te = kludge.firstChild; - cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); - te.value = lastCopied.text.join("\n"); - var hadFocus = activeElt(); - selectInput(te); - setTimeout(function () { - cm.display.lineSpace.removeChild(kludge); - hadFocus.focus(); - if (hadFocus == div) { - input.showPrimarySelection(); - } - }, 50); - } - on(div, "copy", onCopyCut); - on(div, "cut", onCopyCut); - }; - ContentEditableInput.prototype.screenReaderLabelChanged = function (label) { - // Label for screenreaders, accessibility - if (label) { - this.div.setAttribute('aria-label', label); - } else { - this.div.removeAttribute('aria-label'); - } - }; - ContentEditableInput.prototype.prepareSelection = function () { - var result = prepareSelection(this.cm, false); - result.focus = activeElt() == this.div; - return result; - }; - ContentEditableInput.prototype.showSelection = function (info, takeFocus) { - if (!info || !this.cm.display.view.length) { - return; - } - if (info.focus || takeFocus) { - this.showPrimarySelection(); - } - this.showMultipleSelections(info); - }; - ContentEditableInput.prototype.getSelection = function () { - return this.cm.display.wrapper.ownerDocument.getSelection(); - }; - ContentEditableInput.prototype.showPrimarySelection = function () { - var sel = this.getSelection(), - cm = this.cm, - prim = cm.doc.sel.primary(); - var from = prim.from(), - to = prim.to(); - if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) { - sel.removeAllRanges(); - return; - } - var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); - var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset); - if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && cmp(minPos(curAnchor, curFocus), from) == 0 && cmp(maxPos(curAnchor, curFocus), to) == 0) { - return; - } - var view = cm.display.view; - var start = from.line >= cm.display.viewFrom && posToDOM(cm, from) || { - node: view[0].measure.map[2], - offset: 0 - }; - var end = to.line < cm.display.viewTo && posToDOM(cm, to); - if (!end) { - var measure = view[view.length - 1].measure; - var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; - end = { - node: map[map.length - 1], - offset: map[map.length - 2] - map[map.length - 3] - }; - } - if (!start || !end) { - sel.removeAllRanges(); - return; - } - var old = sel.rangeCount && sel.getRangeAt(0), - rng; - try { - rng = range(start.node, start.offset, end.offset, end.node); - } catch (e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible - if (rng) { - if (!gecko && cm.state.focused) { - sel.collapse(start.node, start.offset); - if (!rng.collapsed) { - sel.removeAllRanges(); - sel.addRange(rng); - } - } else { - sel.removeAllRanges(); - sel.addRange(rng); - } - if (old && sel.anchorNode == null) { - sel.addRange(old); - } else if (gecko) { - this.startGracePeriod(); - } - } - this.rememberSelection(); - }; - ContentEditableInput.prototype.startGracePeriod = function () { - var this$1 = this; - clearTimeout(this.gracePeriod); - this.gracePeriod = setTimeout(function () { - this$1.gracePeriod = false; - if (this$1.selectionChanged()) { - this$1.cm.operation(function () { - return this$1.cm.curOp.selectionChanged = true; - }); - } - }, 20); - }; - ContentEditableInput.prototype.showMultipleSelections = function (info) { - removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); - removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); - }; - ContentEditableInput.prototype.rememberSelection = function () { - var sel = this.getSelection(); - this.lastAnchorNode = sel.anchorNode; - this.lastAnchorOffset = sel.anchorOffset; - this.lastFocusNode = sel.focusNode; - this.lastFocusOffset = sel.focusOffset; - }; - ContentEditableInput.prototype.selectionInEditor = function () { - var sel = this.getSelection(); - if (!sel.rangeCount) { - return false; - } - var node = sel.getRangeAt(0).commonAncestorContainer; - return contains(this.div, node); - }; - ContentEditableInput.prototype.focus = function () { - if (this.cm.options.readOnly != "nocursor") { - if (!this.selectionInEditor() || activeElt() != this.div) { - this.showSelection(this.prepareSelection(), true); - } - this.div.focus(); - } - }; - ContentEditableInput.prototype.blur = function () { - this.div.blur(); - }; - ContentEditableInput.prototype.getField = function () { - return this.div; - }; - ContentEditableInput.prototype.supportsTouch = function () { - return true; - }; - ContentEditableInput.prototype.receivedFocus = function () { - var this$1 = this; - var input = this; - if (this.selectionInEditor()) { - setTimeout(function () { - return this$1.pollSelection(); - }, 20); - } else { - runInOp(this.cm, function () { - return input.cm.curOp.selectionChanged = true; - }); - } - function poll() { - if (input.cm.state.focused) { - input.pollSelection(); - input.polling.set(input.cm.options.pollInterval, poll); - } - } - this.polling.set(this.cm.options.pollInterval, poll); - }; - ContentEditableInput.prototype.selectionChanged = function () { - var sel = this.getSelection(); - return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset; - }; - ContentEditableInput.prototype.pollSelection = function () { - if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { - return; - } - var sel = this.getSelection(), - cm = this.cm; - // On Android Chrome (version 56, at least), backspacing into an - // uneditable block element will put the cursor in that element, - // and then, because it's not editable, hide the virtual keyboard. - // Because Android doesn't allow us to actually detect backspace - // presses in a sane way, this code checks for when that happens - // and simulates a backspace press in this case. - if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) { - this.cm.triggerOnKeyDown({ - type: "keydown", - keyCode: 8, - preventDefault: Math.abs - }); - this.blur(); - this.focus(); - return; - } - if (this.composing) { - return; - } - this.rememberSelection(); - var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); - var head = domToPos(cm, sel.focusNode, sel.focusOffset); - if (anchor && head) { - runInOp(cm, function () { - setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); - if (anchor.bad || head.bad) { - cm.curOp.selectionChanged = true; - } - }); - } - }; - ContentEditableInput.prototype.pollContent = function () { - if (this.readDOMTimeout != null) { - clearTimeout(this.readDOMTimeout); - this.readDOMTimeout = null; - } - var cm = this.cm, - display = cm.display, - sel = cm.doc.sel.primary(); - var from = sel.from(), - to = sel.to(); - if (from.ch == 0 && from.line > cm.firstLine()) { - from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); - } - if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine()) { - to = Pos(to.line + 1, 0); - } - if (from.line < display.viewFrom || to.line > display.viewTo - 1) { - return false; - } - var fromIndex, fromLine, fromNode; - if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { - fromLine = lineNo(display.view[0].line); - fromNode = display.view[0].node; - } else { - fromLine = lineNo(display.view[fromIndex].line); - fromNode = display.view[fromIndex - 1].node.nextSibling; - } - var toIndex = findViewIndex(cm, to.line); - var toLine, toNode; - if (toIndex == display.view.length - 1) { - toLine = display.viewTo - 1; - toNode = display.lineDiv.lastChild; - } else { - toLine = lineNo(display.view[toIndex + 1].line) - 1; - toNode = display.view[toIndex + 1].node.previousSibling; - } - if (!fromNode) { - return false; - } - var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); - var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); - while (newText.length > 1 && oldText.length > 1) { - if (lst(newText) == lst(oldText)) { - newText.pop(); - oldText.pop(); - toLine--; - } else if (newText[0] == oldText[0]) { - newText.shift(); - oldText.shift(); - fromLine++; - } else { - break; - } - } - var cutFront = 0, - cutEnd = 0; - var newTop = newText[0], - oldTop = oldText[0], - maxCutFront = Math.min(newTop.length, oldTop.length); - while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) { - ++cutFront; - } - var newBot = lst(newText), - oldBot = lst(oldText); - var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), oldBot.length - (oldText.length == 1 ? cutFront : 0)); - while (cutEnd < maxCutEnd && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { - ++cutEnd; - } - // Try to move start of change to start of selection if ambiguous - if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) { - while (cutFront && cutFront > from.ch && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { - cutFront--; - cutEnd++; - } - } - newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, ""); - newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, ""); - var chFrom = Pos(fromLine, cutFront); - var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); - if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { - replaceRange(cm.doc, newText, chFrom, chTo, "+input"); - return true; - } - }; - ContentEditableInput.prototype.ensurePolled = function () { - this.forceCompositionEnd(); - }; - ContentEditableInput.prototype.reset = function () { - this.forceCompositionEnd(); - }; - ContentEditableInput.prototype.forceCompositionEnd = function () { - if (!this.composing) { - return; - } - clearTimeout(this.readDOMTimeout); - this.composing = null; - this.updateFromDOM(); - this.div.blur(); - this.div.focus(); - }; - ContentEditableInput.prototype.readFromDOMSoon = function () { - var this$1 = this; - if (this.readDOMTimeout != null) { - return; - } - this.readDOMTimeout = setTimeout(function () { - this$1.readDOMTimeout = null; - if (this$1.composing) { - if (this$1.composing.done) { - this$1.composing = null; - } else { - return; - } - } - this$1.updateFromDOM(); - }, 80); - }; - ContentEditableInput.prototype.updateFromDOM = function () { - var this$1 = this; - if (this.cm.isReadOnly() || !this.pollContent()) { - runInOp(this.cm, function () { - return regChange(this$1.cm); - }); - } - }; - ContentEditableInput.prototype.setUneditable = function (node) { - node.contentEditable = "false"; - }; - ContentEditableInput.prototype.onKeyPress = function (e) { - if (e.charCode == 0 || this.composing) { - return; - } - e.preventDefault(); - if (!this.cm.isReadOnly()) { - operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); - } - }; - ContentEditableInput.prototype.readOnlyChanged = function (val) { - this.div.contentEditable = String(val != "nocursor"); - }; - ContentEditableInput.prototype.onContextMenu = function () {}; - ContentEditableInput.prototype.resetPosition = function () {}; - ContentEditableInput.prototype.needsContentAttribute = true; - function posToDOM(cm, pos) { - var view = findViewForLine(cm, pos.line); - if (!view || view.hidden) { - return null; - } - var line = getLine(cm.doc, pos.line); - var info = mapFromLineView(view, line, pos.line); - var order = getOrder(line, cm.doc.direction), - side = "left"; - if (order) { - var partPos = getBidiPartAt(order, pos.ch); - side = partPos % 2 ? "right" : "left"; - } - var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); - result.offset = result.collapse == "right" ? result.end : result.start; - return result; - } - function isInGutter(node) { - for (var scan = node; scan; scan = scan.parentNode) { - if (/CodeMirror-gutter-wrapper/.test(scan.className)) { - return true; - } - } - return false; - } - function badPos(pos, bad) { - if (bad) { - pos.bad = true; - } - return pos; - } - function domTextBetween(cm, from, to, fromLine, toLine) { - var text = "", - closing = false, - lineSep = cm.doc.lineSeparator(), - extraLinebreak = false; - function recognizeMarker(id) { - return function (marker) { - return marker.id == id; - }; - } - function close() { - if (closing) { - text += lineSep; - if (extraLinebreak) { - text += lineSep; - } - closing = extraLinebreak = false; - } - } - function addText(str) { - if (str) { - close(); - text += str; - } - } - function walk(node) { - if (node.nodeType == 1) { - var cmText = node.getAttribute("cm-text"); - if (cmText) { - addText(cmText); - return; - } - var markerID = node.getAttribute("cm-marker"), - range; - if (markerID) { - var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); - if (found.length && (range = found[0].find(0))) { - addText(getBetween(cm.doc, range.from, range.to).join(lineSep)); - } - return; - } - if (node.getAttribute("contenteditable") == "false") { - return; - } - var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName); - if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { - return; - } - if (isBlock) { - close(); - } - for (var i = 0; i < node.childNodes.length; i++) { - walk(node.childNodes[i]); - } - if (/^(pre|p)$/i.test(node.nodeName)) { - extraLinebreak = true; - } - if (isBlock) { - closing = true; - } - } else if (node.nodeType == 3) { - addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " ")); - } - } - for (;;) { - walk(from); - if (from == to) { - break; - } - from = from.nextSibling; - extraLinebreak = false; - } - return text; - } - function domToPos(cm, node, offset) { - var lineNode; - if (node == cm.display.lineDiv) { - lineNode = cm.display.lineDiv.childNodes[offset]; - if (!lineNode) { - return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true); - } - node = null; - offset = 0; - } else { - for (lineNode = node;; lineNode = lineNode.parentNode) { - if (!lineNode || lineNode == cm.display.lineDiv) { - return null; - } - if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { - break; - } - } - } - for (var i = 0; i < cm.display.view.length; i++) { - var lineView = cm.display.view[i]; - if (lineView.node == lineNode) { - return locateNodeInLineView(lineView, node, offset); - } - } - } - function locateNodeInLineView(lineView, node, offset) { - var wrapper = lineView.text.firstChild, - bad = false; - if (!node || !contains(wrapper, node)) { - return badPos(Pos(lineNo(lineView.line), 0), true); - } - if (node == wrapper) { - bad = true; - node = wrapper.childNodes[offset]; - offset = 0; - if (!node) { - var line = lineView.rest ? lst(lineView.rest) : lineView.line; - return badPos(Pos(lineNo(line), line.text.length), bad); - } - } - var textNode = node.nodeType == 3 ? node : null, - topNode = node; - if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { - textNode = node.firstChild; - if (offset) { - offset = textNode.nodeValue.length; - } - } - while (topNode.parentNode != wrapper) { - topNode = topNode.parentNode; - } - var measure = lineView.measure, - maps = measure.maps; - function find(textNode, topNode, offset) { - for (var i = -1; i < (maps ? maps.length : 0); i++) { - var map = i < 0 ? measure.map : maps[i]; - for (var j = 0; j < map.length; j += 3) { - var curNode = map[j + 2]; - if (curNode == textNode || curNode == topNode) { - var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]); - var ch = map[j] + offset; - if (offset < 0 || curNode != textNode) { - ch = map[j + (offset ? 1 : 0)]; - } - return Pos(line, ch); - } - } - } - } - var found = find(textNode, topNode, offset); - if (found) { - return badPos(found, bad); - } - - // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems - for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { - found = find(after, after.firstChild, 0); - if (found) { - return badPos(Pos(found.line, found.ch - dist), bad); - } else { - dist += after.textContent.length; - } - } - for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) { - found = find(before, before.firstChild, -1); - if (found) { - return badPos(Pos(found.line, found.ch + dist$1), bad); - } else { - dist$1 += before.textContent.length; - } - } - } - - // TEXTAREA INPUT STYLE - - var TextareaInput = function (cm) { - this.cm = cm; - // See input.poll and input.reset - this.prevInput = ""; - - // Flag that indicates whether we expect input to appear real soon - // now (after some event like 'keypress' or 'input') and are - // polling intensively. - this.pollingFast = false; - // Self-resetting timeout for the poller - this.polling = new Delayed(); - // Used to work around IE issue with selection being forgotten when focus moves away from textarea - this.hasSelection = false; - this.composing = null; - }; - TextareaInput.prototype.init = function (display) { - var this$1 = this; - var input = this, - cm = this.cm; - this.createField(display); - var te = this.textarea; - display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild); - - // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) - if (ios) { - te.style.width = "0px"; - } - on(te, "input", function () { - if (ie && ie_version >= 9 && this$1.hasSelection) { - this$1.hasSelection = null; - } - input.poll(); - }); - on(te, "paste", function (e) { - if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { - return; - } - cm.state.pasteIncoming = +new Date(); - input.fastPoll(); - }); - function prepareCopyCut(e) { - if (signalDOMEvent(cm, e)) { - return; - } - if (cm.somethingSelected()) { - setLastCopied({ - lineWise: false, - text: cm.getSelections() - }); - } else if (!cm.options.lineWiseCopyCut) { - return; - } else { - var ranges = copyableRanges(cm); - setLastCopied({ - lineWise: true, - text: ranges.text - }); - if (e.type == "cut") { - cm.setSelections(ranges.ranges, null, sel_dontScroll); - } else { - input.prevInput = ""; - te.value = ranges.text.join("\n"); - selectInput(te); - } - } - if (e.type == "cut") { - cm.state.cutIncoming = +new Date(); - } - } - on(te, "cut", prepareCopyCut); - on(te, "copy", prepareCopyCut); - on(display.scroller, "paste", function (e) { - if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { - return; - } - if (!te.dispatchEvent) { - cm.state.pasteIncoming = +new Date(); - input.focus(); - return; - } - - // Pass the `paste` event to the textarea so it's handled by its event listener. - var event = new Event("paste"); - event.clipboardData = e.clipboardData; - te.dispatchEvent(event); - }); - - // Prevent normal selection in the editor (we handle our own) - on(display.lineSpace, "selectstart", function (e) { - if (!eventInWidget(display, e)) { - e_preventDefault(e); - } - }); - on(te, "compositionstart", function () { - var start = cm.getCursor("from"); - if (input.composing) { - input.composing.range.clear(); - } - input.composing = { - start: start, - range: cm.markText(start, cm.getCursor("to"), { - className: "CodeMirror-composing" - }) - }; - }); - on(te, "compositionend", function () { - if (input.composing) { - input.poll(); - input.composing.range.clear(); - input.composing = null; - } - }); - }; - TextareaInput.prototype.createField = function (_display) { - // Wraps and hides input textarea - this.wrapper = hiddenTextarea(); - // The semihidden textarea that is focused when the editor is - // focused, and receives input. - this.textarea = this.wrapper.firstChild; - }; - TextareaInput.prototype.screenReaderLabelChanged = function (label) { - // Label for screenreaders, accessibility - if (label) { - this.textarea.setAttribute('aria-label', label); - } else { - this.textarea.removeAttribute('aria-label'); - } - }; - TextareaInput.prototype.prepareSelection = function () { - // Redraw the selection and/or cursor - var cm = this.cm, - display = cm.display, - doc = cm.doc; - var result = prepareSelection(cm); - - // Move the hidden textarea near the cursor to prevent scrolling artifacts - if (cm.options.moveInputWithCursor) { - var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); - var wrapOff = display.wrapper.getBoundingClientRect(), - lineOff = display.lineDiv.getBoundingClientRect(); - result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, headPos.top + lineOff.top - wrapOff.top)); - result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, headPos.left + lineOff.left - wrapOff.left)); - } - return result; - }; - TextareaInput.prototype.showSelection = function (drawn) { - var cm = this.cm, - display = cm.display; - removeChildrenAndAdd(display.cursorDiv, drawn.cursors); - removeChildrenAndAdd(display.selectionDiv, drawn.selection); - if (drawn.teTop != null) { - this.wrapper.style.top = drawn.teTop + "px"; - this.wrapper.style.left = drawn.teLeft + "px"; - } - }; - - // Reset the input to correspond to the selection (or to be empty, - // when not typing and nothing is selected) - TextareaInput.prototype.reset = function (typing) { - if (this.contextMenuPending || this.composing) { - return; - } - var cm = this.cm; - if (cm.somethingSelected()) { - this.prevInput = ""; - var content = cm.getSelection(); - this.textarea.value = content; - if (cm.state.focused) { - selectInput(this.textarea); - } - if (ie && ie_version >= 9) { - this.hasSelection = content; - } - } else if (!typing) { - this.prevInput = this.textarea.value = ""; - if (ie && ie_version >= 9) { - this.hasSelection = null; - } - } - }; - TextareaInput.prototype.getField = function () { - return this.textarea; - }; - TextareaInput.prototype.supportsTouch = function () { - return false; - }; - TextareaInput.prototype.focus = function () { - if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { - try { - this.textarea.focus(); - } catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM - } - }; - TextareaInput.prototype.blur = function () { - this.textarea.blur(); - }; - TextareaInput.prototype.resetPosition = function () { - this.wrapper.style.top = this.wrapper.style.left = 0; - }; - TextareaInput.prototype.receivedFocus = function () { - this.slowPoll(); - }; - - // Poll for input changes, using the normal rate of polling. This - // runs as long as the editor is focused. - TextareaInput.prototype.slowPoll = function () { - var this$1 = this; - if (this.pollingFast) { - return; - } - this.polling.set(this.cm.options.pollInterval, function () { - this$1.poll(); - if (this$1.cm.state.focused) { - this$1.slowPoll(); - } - }); - }; - - // When an event has just come in that is likely to add or change - // something in the input textarea, we poll faster, to ensure that - // the change appears on the screen quickly. - TextareaInput.prototype.fastPoll = function () { - var missed = false, - input = this; - input.pollingFast = true; - function p() { - var changed = input.poll(); - if (!changed && !missed) { - missed = true; - input.polling.set(60, p); - } else { - input.pollingFast = false; - input.slowPoll(); - } - } - input.polling.set(20, p); - }; - - // Read input from the textarea, and update the document to match. - // When something is selected, it is present in the textarea, and - // selected (unless it is huge, in which case a placeholder is - // used). When nothing is selected, the cursor sits after previously - // seen text (can be empty), which is stored in prevInput (we must - // not reset the textarea when typing, because that breaks IME). - TextareaInput.prototype.poll = function () { - var this$1 = this; - var cm = this.cm, - input = this.textarea, - prevInput = this.prevInput; - // Since this is called a *lot*, try to bail out as cheaply as - // possible when it is clear that nothing happened. hasSelection - // will be the case when there is a lot of text in the textarea, - // in which case reading its value would be expensive. - if (this.contextMenuPending || !cm.state.focused || hasSelection(input) && !prevInput && !this.composing || cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) { - return false; - } - var text = input.value; - // If nothing changed, bail. - if (text == prevInput && !cm.somethingSelected()) { - return false; - } - // Work around nonsensical selection resetting in IE9/10, and - // inexplicable appearance of private area unicode characters on - // some key combos in Mac (#2689). - if (ie && ie_version >= 9 && this.hasSelection === text || mac && /[\uf700-\uf7ff]/.test(text)) { - cm.display.input.reset(); - return false; - } - if (cm.doc.sel == cm.display.selForContextMenu) { - var first = text.charCodeAt(0); - if (first == 0x200b && !prevInput) { - prevInput = "\u200b"; - } - if (first == 0x21da) { - this.reset(); - return this.cm.execCommand("undo"); - } - } - // Find the part of the input that is actually new - var same = 0, - l = Math.min(prevInput.length, text.length); - while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { - ++same; - } - runInOp(cm, function () { - applyTextInput(cm, text.slice(same), prevInput.length - same, null, this$1.composing ? "*compose" : null); - - // Don't leave long text in the textarea, since it makes further polling slow - if (text.length > 1000 || text.indexOf("\n") > -1) { - input.value = this$1.prevInput = ""; - } else { - this$1.prevInput = text; - } - if (this$1.composing) { - this$1.composing.range.clear(); - this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"), { - className: "CodeMirror-composing" - }); - } - }); - return true; - }; - TextareaInput.prototype.ensurePolled = function () { - if (this.pollingFast && this.poll()) { - this.pollingFast = false; - } - }; - TextareaInput.prototype.onKeyPress = function () { - if (ie && ie_version >= 9) { - this.hasSelection = null; - } - this.fastPoll(); - }; - TextareaInput.prototype.onContextMenu = function (e) { - var input = this, - cm = input.cm, - display = cm.display, - te = input.textarea; - if (input.contextMenuPending) { - input.contextMenuPending(); - } - var pos = posFromMouse(cm, e), - scrollPos = display.scroller.scrollTop; - if (!pos || presto) { - return; - } // Opera is difficult. - - // Reset the current text selection only if the click is done outside of the selection - // and 'resetSelectionOnContextMenu' option is true. - var reset = cm.options.resetSelectionOnContextMenu; - if (reset && cm.doc.sel.contains(pos) == -1) { - operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); - } - var oldCSS = te.style.cssText, - oldWrapperCSS = input.wrapper.style.cssText; - var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect(); - input.wrapper.style.cssText = "position: static"; - te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; - var oldScrollY; - if (webkit) { - oldScrollY = window.scrollY; - } // Work around Chrome issue (#2712) - display.input.focus(); - if (webkit) { - window.scrollTo(null, oldScrollY); - } - display.input.reset(); - // Adds "Select all" to context menu in FF - if (!cm.somethingSelected()) { - te.value = input.prevInput = " "; - } - input.contextMenuPending = rehide; - display.selForContextMenu = cm.doc.sel; - clearTimeout(display.detectingSelectAll); - - // Select-all will be greyed out if there's nothing to select, so - // this adds a zero-width space so that we can later check whether - // it got selected. - function prepareSelectAllHack() { - if (te.selectionStart != null) { - var selected = cm.somethingSelected(); - var extval = "\u200b" + (selected ? te.value : ""); - te.value = "\u21da"; // Used to catch context-menu undo - te.value = extval; - input.prevInput = selected ? "" : "\u200b"; - te.selectionStart = 1; - te.selectionEnd = extval.length; - // Re-set this, in case some other handler touched the - // selection in the meantime. - display.selForContextMenu = cm.doc.sel; - } - } - function rehide() { - if (input.contextMenuPending != rehide) { - return; - } - input.contextMenuPending = false; - input.wrapper.style.cssText = oldWrapperCSS; - te.style.cssText = oldCSS; - if (ie && ie_version < 9) { - display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); - } - - // Try to detect the user choosing select-all - if (te.selectionStart != null) { - if (!ie || ie && ie_version < 9) { - prepareSelectAllHack(); - } - var i = 0, - poll = function () { - if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && te.selectionEnd > 0 && input.prevInput == "\u200b") { - operation(cm, selectAll)(cm); - } else if (i++ < 10) { - display.detectingSelectAll = setTimeout(poll, 500); - } else { - display.selForContextMenu = null; - display.input.reset(); - } - }; - display.detectingSelectAll = setTimeout(poll, 200); - } - } - if (ie && ie_version >= 9) { - prepareSelectAllHack(); - } - if (captureRightClick) { - e_stop(e); - var mouseup = function () { - off(window, "mouseup", mouseup); - setTimeout(rehide, 20); - }; - on(window, "mouseup", mouseup); - } else { - setTimeout(rehide, 50); - } - }; - TextareaInput.prototype.readOnlyChanged = function (val) { - if (!val) { - this.reset(); - } - this.textarea.disabled = val == "nocursor"; - this.textarea.readOnly = !!val; - }; - TextareaInput.prototype.setUneditable = function () {}; - TextareaInput.prototype.needsContentAttribute = false; - function fromTextArea(textarea, options) { - options = options ? copyObj(options) : {}; - options.value = textarea.value; - if (!options.tabindex && textarea.tabIndex) { - options.tabindex = textarea.tabIndex; - } - if (!options.placeholder && textarea.placeholder) { - options.placeholder = textarea.placeholder; - } - // Set autofocus to true if this textarea is focused, or if it has - // autofocus and no other element is focused. - if (options.autofocus == null) { - var hasFocus = activeElt(); - options.autofocus = hasFocus == textarea || textarea.getAttribute("autofocus") != null && hasFocus == document.body; - } - function save() { - textarea.value = cm.getValue(); - } - var realSubmit; - if (textarea.form) { - on(textarea.form, "submit", save); - // Deplorable hack to make the submit method do the right thing. - if (!options.leaveSubmitMethodAlone) { - var form = textarea.form; - realSubmit = form.submit; - try { - var wrappedSubmit = form.submit = function () { - save(); - form.submit = realSubmit; - form.submit(); - form.submit = wrappedSubmit; - }; - } catch (e) {} - } - } - options.finishInit = function (cm) { - cm.save = save; - cm.getTextArea = function () { - return textarea; - }; - cm.toTextArea = function () { - cm.toTextArea = isNaN; // Prevent this from being ran twice - save(); - textarea.parentNode.removeChild(cm.getWrapperElement()); - textarea.style.display = ""; - if (textarea.form) { - off(textarea.form, "submit", save); - if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function") { - textarea.form.submit = realSubmit; - } - } - }; - }; - textarea.style.display = "none"; - var cm = CodeMirror(function (node) { - return textarea.parentNode.insertBefore(node, textarea.nextSibling); - }, options); - return cm; - } - function addLegacyProps(CodeMirror) { - CodeMirror.off = off; - CodeMirror.on = on; - CodeMirror.wheelEventPixels = wheelEventPixels; - CodeMirror.Doc = Doc; - CodeMirror.splitLines = splitLinesAuto; - CodeMirror.countColumn = countColumn; - CodeMirror.findColumn = findColumn; - CodeMirror.isWordChar = isWordCharBasic; - CodeMirror.Pass = Pass; - CodeMirror.signal = signal; - CodeMirror.Line = Line; - CodeMirror.changeEnd = changeEnd; - CodeMirror.scrollbarModel = scrollbarModel; - CodeMirror.Pos = Pos; - CodeMirror.cmpPos = cmp; - CodeMirror.modes = modes; - CodeMirror.mimeModes = mimeModes; - CodeMirror.resolveMode = resolveMode; - CodeMirror.getMode = getMode; - CodeMirror.modeExtensions = modeExtensions; - CodeMirror.extendMode = extendMode; - CodeMirror.copyState = copyState; - CodeMirror.startState = startState; - CodeMirror.innerMode = innerMode; - CodeMirror.commands = commands; - CodeMirror.keyMap = keyMap; - CodeMirror.keyName = keyName; - CodeMirror.isModifierKey = isModifierKey; - CodeMirror.lookupKey = lookupKey; - CodeMirror.normalizeKeyMap = normalizeKeyMap; - CodeMirror.StringStream = StringStream; - CodeMirror.SharedTextMarker = SharedTextMarker; - CodeMirror.TextMarker = TextMarker; - CodeMirror.LineWidget = LineWidget; - CodeMirror.e_preventDefault = e_preventDefault; - CodeMirror.e_stopPropagation = e_stopPropagation; - CodeMirror.e_stop = e_stop; - CodeMirror.addClass = addClass; - CodeMirror.contains = contains; - CodeMirror.rmClass = rmClass; - CodeMirror.keyNames = keyNames; - } - - // EDITOR CONSTRUCTOR - - defineOptions(CodeMirror); - addEditorMethods(CodeMirror); - - // Set up methods on CodeMirror's prototype to redirect to the editor's document. - var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); - for (var prop in Doc.prototype) { - if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) { - CodeMirror.prototype[prop] = function (method) { - return function () { - return method.apply(this.doc, arguments); - }; - }(Doc.prototype[prop]); - } - } - eventMixin(Doc); - CodeMirror.inputStyles = { - "textarea": TextareaInput, - "contenteditable": ContentEditableInput - }; - - // Extra arguments are stored as the mode's dependencies, which is - // used by (legacy) mechanisms like loadmode.js to automatically - // load a mode. (Preferred mechanism is the require/define calls.) - CodeMirror.defineMode = function (name /*, mode, …*/) { - if (!CodeMirror.defaults.mode && name != "null") { - CodeMirror.defaults.mode = name; - } - defineMode.apply(this, arguments); - }; - CodeMirror.defineMIME = defineMIME; - - // Minimal default mode. - CodeMirror.defineMode("null", function () { - return { - token: function (stream) { - return stream.skipToEnd(); - } - }; - }); - CodeMirror.defineMIME("text/plain", "null"); - - // EXTENSIONS - - CodeMirror.defineExtension = function (name, func) { - CodeMirror.prototype[name] = func; - }; - CodeMirror.defineDocExtension = function (name, func) { - Doc.prototype[name] = func; - }; - CodeMirror.fromTextArea = fromTextArea; - addLegacyProps(CodeMirror); - CodeMirror.version = "5.65.3"; - return CodeMirror; -}); - -/***/ }), - -/***/ "../../../node_modules/codemirror/mode/javascript/javascript.js": -/*!**********************************************************************!*\ - !*** ../../../node_modules/codemirror/mode/javascript/javascript.js ***! - \**********************************************************************/ -/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function (mod) { - if (true) - // CommonJS - mod(__webpack_require__(/*! ../../lib/codemirror */ "../../../node_modules/codemirror/lib/codemirror.js"));else {} -})(function (CodeMirror) { - "use strict"; - - CodeMirror.defineMode("javascript", function (config, parserConfig) { - var indentUnit = config.indentUnit; - var statementIndent = parserConfig.statementIndent; - var jsonldMode = parserConfig.jsonld; - var jsonMode = parserConfig.json || jsonldMode; - var trackScope = parserConfig.trackScope !== false; - var isTS = parserConfig.typescript; - var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/; - - // Tokenizer - - var keywords = function () { - function kw(type) { - return { - type: type, - style: "keyword" - }; - } - var A = kw("keyword a"), - B = kw("keyword b"), - C = kw("keyword c"), - D = kw("keyword d"); - var operator = kw("operator"), - atom = { - type: "atom", - style: "atom" - }; - return { - "if": kw("if"), - "while": A, - "with": A, - "else": B, - "do": B, - "try": B, - "finally": B, - "return": D, - "break": D, - "continue": D, - "new": kw("new"), - "delete": C, - "void": C, - "throw": C, - "debugger": kw("debugger"), - "var": kw("var"), - "const": kw("var"), - "let": kw("var"), - "function": kw("function"), - "catch": kw("catch"), - "for": kw("for"), - "switch": kw("switch"), - "case": kw("case"), - "default": kw("default"), - "in": operator, - "typeof": operator, - "instanceof": operator, - "true": atom, - "false": atom, - "null": atom, - "undefined": atom, - "NaN": atom, - "Infinity": atom, - "this": kw("this"), - "class": kw("class"), - "super": kw("atom"), - "yield": C, - "export": kw("export"), - "import": kw("import"), - "extends": C, - "await": C - }; - }(); - var isOperatorChar = /[+\-*&%=<>!?|~^@]/; - var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; - function readRegexp(stream) { - var escaped = false, - next, - inSet = false; - while ((next = stream.next()) != null) { - if (!escaped) { - if (next == "/" && !inSet) return; - if (next == "[") inSet = true;else if (inSet && next == "]") inSet = false; - } - escaped = !escaped && next == "\\"; - } - } - - // Used as scratch variables to communicate multiple values without - // consing up tons of objects. - var type, content; - function ret(tp, style, cont) { - type = tp; - content = cont; - return style; - } - function tokenBase(stream, state) { - var ch = stream.next(); - if (ch == '"' || ch == "'") { - state.tokenize = tokenString(ch); - return state.tokenize(stream, state); - } else if (ch == "." && stream.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/)) { - return ret("number", "number"); - } else if (ch == "." && stream.match("..")) { - return ret("spread", "meta"); - } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { - return ret(ch); - } else if (ch == "=" && stream.eat(">")) { - return ret("=>", "operator"); - } else if (ch == "0" && stream.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/)) { - return ret("number", "number"); - } else if (/\d/.test(ch)) { - stream.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/); - return ret("number", "number"); - } else if (ch == "/") { - if (stream.eat("*")) { - state.tokenize = tokenComment; - return tokenComment(stream, state); - } else if (stream.eat("/")) { - stream.skipToEnd(); - return ret("comment", "comment"); - } else if (expressionAllowed(stream, state, 1)) { - readRegexp(stream); - stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/); - return ret("regexp", "string-2"); - } else { - stream.eat("="); - return ret("operator", "operator", stream.current()); - } - } else if (ch == "`") { - state.tokenize = tokenQuasi; - return tokenQuasi(stream, state); - } else if (ch == "#" && stream.peek() == "!") { - stream.skipToEnd(); - return ret("meta", "meta"); - } else if (ch == "#" && stream.eatWhile(wordRE)) { - return ret("variable", "property"); - } else if (ch == "<" && stream.match("!--") || ch == "-" && stream.match("->") && !/\S/.test(stream.string.slice(0, stream.start))) { - stream.skipToEnd(); - return ret("comment", "comment"); - } else if (isOperatorChar.test(ch)) { - if (ch != ">" || !state.lexical || state.lexical.type != ">") { - if (stream.eat("=")) { - if (ch == "!" || ch == "=") stream.eat("="); - } else if (/[<>*+\-|&?]/.test(ch)) { - stream.eat(ch); - if (ch == ">") stream.eat(ch); - } - } - if (ch == "?" && stream.eat(".")) return ret("."); - return ret("operator", "operator", stream.current()); - } else if (wordRE.test(ch)) { - stream.eatWhile(wordRE); - var word = stream.current(); - if (state.lastType != ".") { - if (keywords.propertyIsEnumerable(word)) { - var kw = keywords[word]; - return ret(kw.type, kw.style, word); - } - if (word == "async" && stream.match(/^(\s|\/\*([^*]|\*(?!\/))*?\*\/)*[\[\(\w]/, false)) return ret("async", "keyword", word); - } - return ret("variable", "variable", word); - } - } - function tokenString(quote) { - return function (stream, state) { - var escaped = false, - next; - if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)) { - state.tokenize = tokenBase; - return ret("jsonld-keyword", "meta"); - } - while ((next = stream.next()) != null) { - if (next == quote && !escaped) break; - escaped = !escaped && next == "\\"; - } - if (!escaped) state.tokenize = tokenBase; - return ret("string", "string"); - }; - } - function tokenComment(stream, state) { - var maybeEnd = false, - ch; - while (ch = stream.next()) { - if (ch == "/" && maybeEnd) { - state.tokenize = tokenBase; - break; - } - maybeEnd = ch == "*"; - } - return ret("comment", "comment"); - } - function tokenQuasi(stream, state) { - var escaped = false, - next; - while ((next = stream.next()) != null) { - if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) { - state.tokenize = tokenBase; - break; - } - escaped = !escaped && next == "\\"; - } - return ret("quasi", "string-2", stream.current()); - } - var brackets = "([{}])"; - // This is a crude lookahead trick to try and notice that we're - // parsing the argument patterns for a fat-arrow function before we - // actually hit the arrow token. It only works if the arrow is on - // the same line as the arguments and there's no strange noise - // (comments) in between. Fallback is to only notice when we hit the - // arrow, and not declare the arguments as locals for the arrow - // body. - function findFatArrow(stream, state) { - if (state.fatArrowAt) state.fatArrowAt = null; - var arrow = stream.string.indexOf("=>", stream.start); - if (arrow < 0) return; - if (isTS) { - // Try to skip TypeScript return type declarations after the arguments - var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow)); - if (m) arrow = m.index; - } - var depth = 0, - sawSomething = false; - for (var pos = arrow - 1; pos >= 0; --pos) { - var ch = stream.string.charAt(pos); - var bracket = brackets.indexOf(ch); - if (bracket >= 0 && bracket < 3) { - if (!depth) { - ++pos; - break; - } - if (--depth == 0) { - if (ch == "(") sawSomething = true; - break; - } - } else if (bracket >= 3 && bracket < 6) { - ++depth; - } else if (wordRE.test(ch)) { - sawSomething = true; - } else if (/["'\/`]/.test(ch)) { - for (;; --pos) { - if (pos == 0) return; - var next = stream.string.charAt(pos - 1); - if (next == ch && stream.string.charAt(pos - 2) != "\\") { - pos--; - break; - } - } - } else if (sawSomething && !depth) { - ++pos; - break; - } - } - if (sawSomething && !depth) state.fatArrowAt = pos; - } - - // Parser - - var atomicTypes = { - "atom": true, - "number": true, - "variable": true, - "string": true, - "regexp": true, - "this": true, - "import": true, - "jsonld-keyword": true - }; - function JSLexical(indented, column, type, align, prev, info) { - this.indented = indented; - this.column = column; - this.type = type; - this.prev = prev; - this.info = info; - if (align != null) this.align = align; - } - function inScope(state, varname) { - if (!trackScope) return false; - for (var v = state.localVars; v; v = v.next) if (v.name == varname) return true; - for (var cx = state.context; cx; cx = cx.prev) { - for (var v = cx.vars; v; v = v.next) if (v.name == varname) return true; - } - } - function parseJS(state, style, type, content, stream) { - var cc = state.cc; - // Communicate our context to the combinators. - // (Less wasteful than consing up a hundred closures on every call.) - cx.state = state; - cx.stream = stream; - cx.marked = null, cx.cc = cc; - cx.style = style; - if (!state.lexical.hasOwnProperty("align")) state.lexical.align = true; - while (true) { - var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; - if (combinator(type, content)) { - while (cc.length && cc[cc.length - 1].lex) cc.pop()(); - if (cx.marked) return cx.marked; - if (type == "variable" && inScope(state, content)) return "variable-2"; - return style; - } - } - } - - // Combinator utils - - var cx = { - state: null, - column: null, - marked: null, - cc: null - }; - function pass() { - for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); - } - function cont() { - pass.apply(null, arguments); - return true; - } - function inList(name, list) { - for (var v = list; v; v = v.next) if (v.name == name) return true; - return false; - } - function register(varname) { - var state = cx.state; - cx.marked = "def"; - if (!trackScope) return; - if (state.context) { - if (state.lexical.info == "var" && state.context && state.context.block) { - // FIXME function decls are also not block scoped - var newContext = registerVarScoped(varname, state.context); - if (newContext != null) { - state.context = newContext; - return; - } - } else if (!inList(varname, state.localVars)) { - state.localVars = new Var(varname, state.localVars); - return; - } - } - // Fall through means this is global - if (parserConfig.globalVars && !inList(varname, state.globalVars)) state.globalVars = new Var(varname, state.globalVars); - } - function registerVarScoped(varname, context) { - if (!context) { - return null; - } else if (context.block) { - var inner = registerVarScoped(varname, context.prev); - if (!inner) return null; - if (inner == context.prev) return context; - return new Context(inner, context.vars, true); - } else if (inList(varname, context.vars)) { - return context; - } else { - return new Context(context.prev, new Var(varname, context.vars), false); - } - } - function isModifier(name) { - return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly"; - } - - // Combinators - - function Context(prev, vars, block) { - this.prev = prev; - this.vars = vars; - this.block = block; - } - function Var(name, next) { - this.name = name; - this.next = next; - } - var defaultVars = new Var("this", new Var("arguments", null)); - function pushcontext() { - cx.state.context = new Context(cx.state.context, cx.state.localVars, false); - cx.state.localVars = defaultVars; - } - function pushblockcontext() { - cx.state.context = new Context(cx.state.context, cx.state.localVars, true); - cx.state.localVars = null; - } - pushcontext.lex = pushblockcontext.lex = true; - function popcontext() { - cx.state.localVars = cx.state.context.vars; - cx.state.context = cx.state.context.prev; - } - popcontext.lex = true; - function pushlex(type, info) { - var result = function () { - var state = cx.state, - indent = state.indented; - if (state.lexical.type == "stat") indent = state.lexical.indented;else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev) indent = outer.indented; - state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info); - }; - result.lex = true; - return result; - } - function poplex() { - var state = cx.state; - if (state.lexical.prev) { - if (state.lexical.type == ")") state.indented = state.lexical.indented; - state.lexical = state.lexical.prev; - } - } - poplex.lex = true; - function expect(wanted) { - function exp(type) { - if (type == wanted) return cont();else if (wanted == ";" || type == "}" || type == ")" || type == "]") return pass();else return cont(exp); - } - ; - return exp; - } - function statement(type, value) { - if (type == "var") return cont(pushlex("vardef", value), vardef, expect(";"), poplex); - if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex); - if (type == "keyword b") return cont(pushlex("form"), statement, poplex); - if (type == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex); - if (type == "debugger") return cont(expect(";")); - if (type == "{") return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext); - if (type == ";") return cont(); - if (type == "if") { - if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex) cx.state.cc.pop()(); - return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse); - } - if (type == "function") return cont(functiondef); - if (type == "for") return cont(pushlex("form"), pushblockcontext, forspec, statement, popcontext, poplex); - if (type == "class" || isTS && value == "interface") { - cx.marked = "keyword"; - return cont(pushlex("form", type == "class" ? type : value), className, poplex); - } - if (type == "variable") { - if (isTS && value == "declare") { - cx.marked = "keyword"; - return cont(statement); - } else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) { - cx.marked = "keyword"; - if (value == "enum") return cont(enumdef);else if (value == "type") return cont(typename, expect("operator"), typeexpr, expect(";"));else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex); - } else if (isTS && value == "namespace") { - cx.marked = "keyword"; - return cont(pushlex("form"), expression, statement, poplex); - } else if (isTS && value == "abstract") { - cx.marked = "keyword"; - return cont(statement); - } else { - return cont(pushlex("stat"), maybelabel); - } - } - if (type == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), pushblockcontext, block, poplex, poplex, popcontext); - if (type == "case") return cont(expression, expect(":")); - if (type == "default") return cont(expect(":")); - if (type == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext); - if (type == "export") return cont(pushlex("stat"), afterExport, poplex); - if (type == "import") return cont(pushlex("stat"), afterImport, poplex); - if (type == "async") return cont(statement); - if (value == "@") return cont(expression, statement); - return pass(pushlex("stat"), expression, expect(";"), poplex); - } - function maybeCatchBinding(type) { - if (type == "(") return cont(funarg, expect(")")); - } - function expression(type, value) { - return expressionInner(type, value, false); - } - function expressionNoComma(type, value) { - return expressionInner(type, value, true); - } - function parenExpr(type) { - if (type != "(") return pass(); - return cont(pushlex(")"), maybeexpression, expect(")"), poplex); - } - function expressionInner(type, value, noComma) { - if (cx.state.fatArrowAt == cx.stream.start) { - var body = noComma ? arrowBodyNoComma : arrowBody; - if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext);else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext); - } - var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; - if (atomicTypes.hasOwnProperty(type)) return cont(maybeop); - if (type == "function") return cont(functiondef, maybeop); - if (type == "class" || isTS && value == "interface") { - cx.marked = "keyword"; - return cont(pushlex("form"), classExpression, poplex); - } - if (type == "keyword c" || type == "async") return cont(noComma ? expressionNoComma : expression); - if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop); - if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression); - if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop); - if (type == "{") return contCommasep(objprop, "}", null, maybeop); - if (type == "quasi") return pass(quasi, maybeop); - if (type == "new") return cont(maybeTarget(noComma)); - return cont(); - } - function maybeexpression(type) { - if (type.match(/[;\}\)\],]/)) return pass(); - return pass(expression); - } - function maybeoperatorComma(type, value) { - if (type == ",") return cont(maybeexpression); - return maybeoperatorNoComma(type, value, false); - } - function maybeoperatorNoComma(type, value, noComma) { - var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; - var expr = noComma == false ? expression : expressionNoComma; - if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); - if (type == "operator") { - if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me); - if (isTS && value == "<" && cx.stream.match(/^([^<>]|<[^<>]*>)*>\s*\(/, false)) return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me); - if (value == "?") return cont(expression, expect(":"), expr); - return cont(expr); - } - if (type == "quasi") { - return pass(quasi, me); - } - if (type == ";") return; - if (type == "(") return contCommasep(expressionNoComma, ")", "call", me); - if (type == ".") return cont(property, me); - if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); - if (isTS && value == "as") { - cx.marked = "keyword"; - return cont(typeexpr, me); - } - if (type == "regexp") { - cx.state.lastType = cx.marked = "operator"; - cx.stream.backUp(cx.stream.pos - cx.stream.start - 1); - return cont(expr); - } - } - function quasi(type, value) { - if (type != "quasi") return pass(); - if (value.slice(value.length - 2) != "${") return cont(quasi); - return cont(maybeexpression, continueQuasi); - } - function continueQuasi(type) { - if (type == "}") { - cx.marked = "string-2"; - cx.state.tokenize = tokenQuasi; - return cont(quasi); - } - } - function arrowBody(type) { - findFatArrow(cx.stream, cx.state); - return pass(type == "{" ? statement : expression); - } - function arrowBodyNoComma(type) { - findFatArrow(cx.stream, cx.state); - return pass(type == "{" ? statement : expressionNoComma); - } - function maybeTarget(noComma) { - return function (type) { - if (type == ".") return cont(noComma ? targetNoComma : target);else if (type == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma);else return pass(noComma ? expressionNoComma : expression); - }; - } - function target(_, value) { - if (value == "target") { - cx.marked = "keyword"; - return cont(maybeoperatorComma); - } - } - function targetNoComma(_, value) { - if (value == "target") { - cx.marked = "keyword"; - return cont(maybeoperatorNoComma); - } - } - function maybelabel(type) { - if (type == ":") return cont(poplex, statement); - return pass(maybeoperatorComma, expect(";"), poplex); - } - function property(type) { - if (type == "variable") { - cx.marked = "property"; - return cont(); - } - } - function objprop(type, value) { - if (type == "async") { - cx.marked = "property"; - return cont(objprop); - } else if (type == "variable" || cx.style == "keyword") { - cx.marked = "property"; - if (value == "get" || value == "set") return cont(getterSetter); - var m; // Work around fat-arrow-detection complication for detecting typescript typed arrow params - if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false))) cx.state.fatArrowAt = cx.stream.pos + m[0].length; - return cont(afterprop); - } else if (type == "number" || type == "string") { - cx.marked = jsonldMode ? "property" : cx.style + " property"; - return cont(afterprop); - } else if (type == "jsonld-keyword") { - return cont(afterprop); - } else if (isTS && isModifier(value)) { - cx.marked = "keyword"; - return cont(objprop); - } else if (type == "[") { - return cont(expression, maybetype, expect("]"), afterprop); - } else if (type == "spread") { - return cont(expressionNoComma, afterprop); - } else if (value == "*") { - cx.marked = "keyword"; - return cont(objprop); - } else if (type == ":") { - return pass(afterprop); - } - } - function getterSetter(type) { - if (type != "variable") return pass(afterprop); - cx.marked = "property"; - return cont(functiondef); - } - function afterprop(type) { - if (type == ":") return cont(expressionNoComma); - if (type == "(") return pass(functiondef); - } - function commasep(what, end, sep) { - function proceed(type, value) { - if (sep ? sep.indexOf(type) > -1 : type == ",") { - var lex = cx.state.lexical; - if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; - return cont(function (type, value) { - if (type == end || value == end) return pass(); - return pass(what); - }, proceed); - } - if (type == end || value == end) return cont(); - if (sep && sep.indexOf(";") > -1) return pass(what); - return cont(expect(end)); - } - return function (type, value) { - if (type == end || value == end) return cont(); - return pass(what, proceed); - }; - } - function contCommasep(what, end, info) { - for (var i = 3; i < arguments.length; i++) cx.cc.push(arguments[i]); - return cont(pushlex(end, info), commasep(what, end), poplex); - } - function block(type) { - if (type == "}") return cont(); - return pass(statement, block); - } - function maybetype(type, value) { - if (isTS) { - if (type == ":") return cont(typeexpr); - if (value == "?") return cont(maybetype); - } - } - function maybetypeOrIn(type, value) { - if (isTS && (type == ":" || value == "in")) return cont(typeexpr); - } - function mayberettype(type) { - if (isTS && type == ":") { - if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr);else return cont(typeexpr); - } - } - function isKW(_, value) { - if (value == "is") { - cx.marked = "keyword"; - return cont(); - } - } - function typeexpr(type, value) { - if (value == "keyof" || value == "typeof" || value == "infer" || value == "readonly") { - cx.marked = "keyword"; - return cont(value == "typeof" ? expressionNoComma : typeexpr); - } - if (type == "variable" || value == "void") { - cx.marked = "type"; - return cont(afterType); - } - if (value == "|" || value == "&") return cont(typeexpr); - if (type == "string" || type == "number" || type == "atom") return cont(afterType); - if (type == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType); - if (type == "{") return cont(pushlex("}"), typeprops, poplex, afterType); - if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType, afterType); - if (type == "<") return cont(commasep(typeexpr, ">"), typeexpr); - if (type == "quasi") { - return pass(quasiType, afterType); - } - } - function maybeReturnType(type) { - if (type == "=>") return cont(typeexpr); - } - function typeprops(type) { - if (type.match(/[\}\)\]]/)) return cont(); - if (type == "," || type == ";") return cont(typeprops); - return pass(typeprop, typeprops); - } - function typeprop(type, value) { - if (type == "variable" || cx.style == "keyword") { - cx.marked = "property"; - return cont(typeprop); - } else if (value == "?" || type == "number" || type == "string") { - return cont(typeprop); - } else if (type == ":") { - return cont(typeexpr); - } else if (type == "[") { - return cont(expect("variable"), maybetypeOrIn, expect("]"), typeprop); - } else if (type == "(") { - return pass(functiondecl, typeprop); - } else if (!type.match(/[;\}\)\],]/)) { - return cont(); - } - } - function quasiType(type, value) { - if (type != "quasi") return pass(); - if (value.slice(value.length - 2) != "${") return cont(quasiType); - return cont(typeexpr, continueQuasiType); - } - function continueQuasiType(type) { - if (type == "}") { - cx.marked = "string-2"; - cx.state.tokenize = tokenQuasi; - return cont(quasiType); - } - } - function typearg(type, value) { - if (type == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg); - if (type == ":") return cont(typeexpr); - if (type == "spread") return cont(typearg); - return pass(typeexpr); - } - function afterType(type, value) { - if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType); - if (value == "|" || type == "." || value == "&") return cont(typeexpr); - if (type == "[") return cont(typeexpr, expect("]"), afterType); - if (value == "extends" || value == "implements") { - cx.marked = "keyword"; - return cont(typeexpr); - } - if (value == "?") return cont(typeexpr, expect(":"), typeexpr); - } - function maybeTypeArgs(_, value) { - if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType); - } - function typeparam() { - return pass(typeexpr, maybeTypeDefault); - } - function maybeTypeDefault(_, value) { - if (value == "=") return cont(typeexpr); - } - function vardef(_, value) { - if (value == "enum") { - cx.marked = "keyword"; - return cont(enumdef); - } - return pass(pattern, maybetype, maybeAssign, vardefCont); - } - function pattern(type, value) { - if (isTS && isModifier(value)) { - cx.marked = "keyword"; - return cont(pattern); - } - if (type == "variable") { - register(value); - return cont(); - } - if (type == "spread") return cont(pattern); - if (type == "[") return contCommasep(eltpattern, "]"); - if (type == "{") return contCommasep(proppattern, "}"); - } - function proppattern(type, value) { - if (type == "variable" && !cx.stream.match(/^\s*:/, false)) { - register(value); - return cont(maybeAssign); - } - if (type == "variable") cx.marked = "property"; - if (type == "spread") return cont(pattern); - if (type == "}") return pass(); - if (type == "[") return cont(expression, expect(']'), expect(':'), proppattern); - return cont(expect(":"), pattern, maybeAssign); - } - function eltpattern() { - return pass(pattern, maybeAssign); - } - function maybeAssign(_type, value) { - if (value == "=") return cont(expressionNoComma); - } - function vardefCont(type) { - if (type == ",") return cont(vardef); - } - function maybeelse(type, value) { - if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex); - } - function forspec(type, value) { - if (value == "await") return cont(forspec); - if (type == "(") return cont(pushlex(")"), forspec1, poplex); - } - function forspec1(type) { - if (type == "var") return cont(vardef, forspec2); - if (type == "variable") return cont(forspec2); - return pass(forspec2); - } - function forspec2(type, value) { - if (type == ")") return cont(); - if (type == ";") return cont(forspec2); - if (value == "in" || value == "of") { - cx.marked = "keyword"; - return cont(expression, forspec2); - } - return pass(expression, forspec2); - } - function functiondef(type, value) { - if (value == "*") { - cx.marked = "keyword"; - return cont(functiondef); - } - if (type == "variable") { - register(value); - return cont(functiondef); - } - if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext); - if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef); - } - function functiondecl(type, value) { - if (value == "*") { - cx.marked = "keyword"; - return cont(functiondecl); - } - if (type == "variable") { - register(value); - return cont(functiondecl); - } - if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, popcontext); - if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondecl); - } - function typename(type, value) { - if (type == "keyword" || type == "variable") { - cx.marked = "type"; - return cont(typename); - } else if (value == "<") { - return cont(pushlex(">"), commasep(typeparam, ">"), poplex); - } - } - function funarg(type, value) { - if (value == "@") cont(expression, funarg); - if (type == "spread") return cont(funarg); - if (isTS && isModifier(value)) { - cx.marked = "keyword"; - return cont(funarg); - } - if (isTS && type == "this") return cont(maybetype, maybeAssign); - return pass(pattern, maybetype, maybeAssign); - } - function classExpression(type, value) { - // Class expressions may have an optional name. - if (type == "variable") return className(type, value); - return classNameAfter(type, value); - } - function className(type, value) { - if (type == "variable") { - register(value); - return cont(classNameAfter); - } - } - function classNameAfter(type, value) { - if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter); - if (value == "extends" || value == "implements" || isTS && type == ",") { - if (value == "implements") cx.marked = "keyword"; - return cont(isTS ? typeexpr : expression, classNameAfter); - } - if (type == "{") return cont(pushlex("}"), classBody, poplex); - } - function classBody(type, value) { - if (type == "async" || type == "variable" && (value == "static" || value == "get" || value == "set" || isTS && isModifier(value)) && cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false)) { - cx.marked = "keyword"; - return cont(classBody); - } - if (type == "variable" || cx.style == "keyword") { - cx.marked = "property"; - return cont(classfield, classBody); - } - if (type == "number" || type == "string") return cont(classfield, classBody); - if (type == "[") return cont(expression, maybetype, expect("]"), classfield, classBody); - if (value == "*") { - cx.marked = "keyword"; - return cont(classBody); - } - if (isTS && type == "(") return pass(functiondecl, classBody); - if (type == ";" || type == ",") return cont(classBody); - if (type == "}") return cont(); - if (value == "@") return cont(expression, classBody); - } - function classfield(type, value) { - if (value == "!") return cont(classfield); - if (value == "?") return cont(classfield); - if (type == ":") return cont(typeexpr, maybeAssign); - if (value == "=") return cont(expressionNoComma); - var context = cx.state.lexical.prev, - isInterface = context && context.info == "interface"; - return pass(isInterface ? functiondecl : functiondef); - } - function afterExport(type, value) { - if (value == "*") { - cx.marked = "keyword"; - return cont(maybeFrom, expect(";")); - } - if (value == "default") { - cx.marked = "keyword"; - return cont(expression, expect(";")); - } - if (type == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";")); - return pass(statement); - } - function exportField(type, value) { - if (value == "as") { - cx.marked = "keyword"; - return cont(expect("variable")); - } - if (type == "variable") return pass(expressionNoComma, exportField); - } - function afterImport(type) { - if (type == "string") return cont(); - if (type == "(") return pass(expression); - if (type == ".") return pass(maybeoperatorComma); - return pass(importSpec, maybeMoreImports, maybeFrom); - } - function importSpec(type, value) { - if (type == "{") return contCommasep(importSpec, "}"); - if (type == "variable") register(value); - if (value == "*") cx.marked = "keyword"; - return cont(maybeAs); - } - function maybeMoreImports(type) { - if (type == ",") return cont(importSpec, maybeMoreImports); - } - function maybeAs(_type, value) { - if (value == "as") { - cx.marked = "keyword"; - return cont(importSpec); - } - } - function maybeFrom(_type, value) { - if (value == "from") { - cx.marked = "keyword"; - return cont(expression); - } - } - function arrayLiteral(type) { - if (type == "]") return cont(); - return pass(commasep(expressionNoComma, "]")); - } - function enumdef() { - return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex); - } - function enummember() { - return pass(pattern, maybeAssign); - } - function isContinuedStatement(state, textAfter) { - return state.lastType == "operator" || state.lastType == "," || isOperatorChar.test(textAfter.charAt(0)) || /[,.]/.test(textAfter.charAt(0)); - } - function expressionAllowed(stream, state, backUp) { - return state.tokenize == tokenBase && /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) || state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))); - } - - // Interface - - return { - startState: function (basecolumn) { - var state = { - tokenize: tokenBase, - lastType: "sof", - cc: [], - lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), - localVars: parserConfig.localVars, - context: parserConfig.localVars && new Context(null, null, false), - indented: basecolumn || 0 - }; - if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") state.globalVars = parserConfig.globalVars; - return state; - }, - token: function (stream, state) { - if (stream.sol()) { - if (!state.lexical.hasOwnProperty("align")) state.lexical.align = false; - state.indented = stream.indentation(); - findFatArrow(stream, state); - } - if (state.tokenize != tokenComment && stream.eatSpace()) return null; - var style = state.tokenize(stream, state); - if (type == "comment") return style; - state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; - return parseJS(state, style, type, content, stream); - }, - indent: function (state, textAfter) { - if (state.tokenize == tokenComment || state.tokenize == tokenQuasi) return CodeMirror.Pass; - if (state.tokenize != tokenBase) return 0; - var firstChar = textAfter && textAfter.charAt(0), - lexical = state.lexical, - top; - // Kludge to prevent 'maybelse' from blocking lexical scope pops - if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) { - var c = state.cc[i]; - if (c == poplex) lexical = lexical.prev;else if (c != maybeelse && c != popcontext) break; - } - while ((lexical.type == "stat" || lexical.type == "form") && (firstChar == "}" || (top = state.cc[state.cc.length - 1]) && (top == maybeoperatorComma || top == maybeoperatorNoComma) && !/^[,\.=+\-*:?[\(]/.test(textAfter))) lexical = lexical.prev; - if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") lexical = lexical.prev; - var type = lexical.type, - closing = firstChar == type; - if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0);else if (type == "form" && firstChar == "{") return lexical.indented;else if (type == "form") return lexical.indented + indentUnit;else if (type == "stat") return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);else if (lexical.align) return lexical.column + (closing ? 0 : 1);else return lexical.indented + (closing ? 0 : indentUnit); - }, - electricInput: /^\s*(?:case .*?:|default:|\{|\})$/, - blockCommentStart: jsonMode ? null : "/*", - blockCommentEnd: jsonMode ? null : "*/", - blockCommentContinue: jsonMode ? null : " * ", - lineComment: jsonMode ? null : "//", - fold: "brace", - closeBrackets: "()[]{}''\"\"``", - helperType: jsonMode ? "json" : "javascript", - jsonldMode: jsonldMode, - jsonMode: jsonMode, - expressionAllowed: expressionAllowed, - skipExpression: function (state) { - parseJS(state, "atom", "atom", "true", new CodeMirror.StringStream("", 2, null)); - } - }; - }); - CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/); - CodeMirror.defineMIME("text/javascript", "javascript"); - CodeMirror.defineMIME("text/ecmascript", "javascript"); - CodeMirror.defineMIME("application/javascript", "javascript"); - CodeMirror.defineMIME("application/x-javascript", "javascript"); - CodeMirror.defineMIME("application/ecmascript", "javascript"); - CodeMirror.defineMIME("application/json", { - name: "javascript", - json: true - }); - CodeMirror.defineMIME("application/x-json", { - name: "javascript", - json: true - }); - CodeMirror.defineMIME("application/manifest+json", { - name: "javascript", - json: true - }); - CodeMirror.defineMIME("application/ld+json", { - name: "javascript", - jsonld: true - }); - CodeMirror.defineMIME("text/typescript", { - name: "javascript", - typescript: true - }); - CodeMirror.defineMIME("application/typescript", { - name: "javascript", - typescript: true - }); -}); - -/***/ }), - -/***/ "../../../node_modules/copy-to-clipboard/index.js": -/*!********************************************************!*\ - !*** ../../../node_modules/copy-to-clipboard/index.js ***! - \********************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var deselectCurrent = __webpack_require__(/*! toggle-selection */ "../../../node_modules/toggle-selection/index.js"); -var clipboardToIE11Formatting = { - "text/plain": "Text", - "text/html": "Url", - "default": "Text" -}; -var defaultMessage = "Copy to clipboard: #{key}, Enter"; -function format(message) { - var copyKey = (/mac os x/i.test(navigator.userAgent) ? "⌘" : "Ctrl") + "+C"; - return message.replace(/#{\s*key\s*}/g, copyKey); -} -function copy(text, options) { - var debug, - message, - reselectPrevious, - range, - selection, - mark, - success = false; - if (!options) { - options = {}; - } - debug = options.debug || false; - try { - reselectPrevious = deselectCurrent(); - range = document.createRange(); - selection = document.getSelection(); - mark = document.createElement("span"); - mark.textContent = text; - // avoid screen readers from reading out loud the text - mark.ariaHidden = "true"; - // reset user styles for span element - mark.style.all = "unset"; - // prevents scrolling to the end of the page - mark.style.position = "fixed"; - mark.style.top = 0; - mark.style.clip = "rect(0, 0, 0, 0)"; - // used to preserve spaces and line breaks - mark.style.whiteSpace = "pre"; - // do not inherit user-select (it may be `none`) - mark.style.webkitUserSelect = "text"; - mark.style.MozUserSelect = "text"; - mark.style.msUserSelect = "text"; - mark.style.userSelect = "text"; - mark.addEventListener("copy", function (e) { - e.stopPropagation(); - if (options.format) { - e.preventDefault(); - if (typeof e.clipboardData === "undefined") { - // IE 11 - debug && console.warn("unable to use e.clipboardData"); - debug && console.warn("trying IE specific stuff"); - window.clipboardData.clearData(); - var format = clipboardToIE11Formatting[options.format] || clipboardToIE11Formatting["default"]; - window.clipboardData.setData(format, text); - } else { - // all other browsers - e.clipboardData.clearData(); - e.clipboardData.setData(options.format, text); - } - } - if (options.onCopy) { - e.preventDefault(); - options.onCopy(e.clipboardData); - } - }); - document.body.appendChild(mark); - range.selectNodeContents(mark); - selection.addRange(range); - var successful = document.execCommand("copy"); - if (!successful) { - throw new Error("copy command was unsuccessful"); - } - success = true; - } catch (err) { - debug && console.error("unable to copy using execCommand: ", err); - debug && console.warn("trying IE specific stuff"); - try { - window.clipboardData.setData(options.format || "text", text); - options.onCopy && options.onCopy(window.clipboardData); - success = true; - } catch (err) { - debug && console.error("unable to copy using clipboardData: ", err); - debug && console.error("falling back to prompt"); - message = format("message" in options ? options.message : defaultMessage); - window.prompt(message, text); - } - } finally { - if (selection) { - if (typeof selection.removeRange == "function") { - selection.removeRange(range); - } else { - selection.removeAllRanges(); - } - } - if (mark) { - document.body.removeChild(mark); - } - reselectPrevious(); - } - return success; -} -module.exports = copy; - -/***/ }), - -/***/ "../../../node_modules/detect-node-es/esm/browser.js": -/*!***********************************************************!*\ - !*** ../../../node_modules/detect-node-es/esm/browser.js ***! - \***********************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isNode = void 0; -const isNode = exports.isNode = false; - -/***/ }), - -/***/ "../../../node_modules/entities/lib/decode.js": -/*!****************************************************!*\ - !*** ../../../node_modules/entities/lib/decode.js ***! - \****************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -var __createBinding = void 0 && (void 0).__createBinding || (Object.create ? function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { - enumerable: true, - get: function () { - return m[k]; - } - }; - } - Object.defineProperty(o, k2, desc); -} : function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -}); -var __setModuleDefault = void 0 && (void 0).__setModuleDefault || (Object.create ? function (o, v) { - Object.defineProperty(o, "default", { - enumerable: true, - value: v - }); -} : function (o, v) { - o["default"] = v; -}); -var __importStar = void 0 && (void 0).__importStar || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = void 0 && (void 0).__importDefault || function (mod) { - return mod && mod.__esModule ? mod : { - "default": mod - }; -}; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.decodeXML = exports.decodeHTMLStrict = exports.decodeHTMLAttribute = exports.decodeHTML = exports.determineBranch = exports.EntityDecoder = exports.DecodingMode = exports.BinTrieFlags = exports.fromCodePoint = exports.replaceCodePoint = exports.decodeCodePoint = exports.xmlDecodeTree = exports.htmlDecodeTree = void 0; -var decode_data_html_js_1 = __importDefault(__webpack_require__(/*! ./generated/decode-data-html.js */ "../../../node_modules/entities/lib/generated/decode-data-html.js")); -exports.htmlDecodeTree = decode_data_html_js_1.default; -var decode_data_xml_js_1 = __importDefault(__webpack_require__(/*! ./generated/decode-data-xml.js */ "../../../node_modules/entities/lib/generated/decode-data-xml.js")); -exports.xmlDecodeTree = decode_data_xml_js_1.default; -var decode_codepoint_js_1 = __importStar(__webpack_require__(/*! ./decode_codepoint.js */ "../../../node_modules/entities/lib/decode_codepoint.js")); -exports.decodeCodePoint = decode_codepoint_js_1.default; -var decode_codepoint_js_2 = __webpack_require__(/*! ./decode_codepoint.js */ "../../../node_modules/entities/lib/decode_codepoint.js"); -Object.defineProperty(exports, "replaceCodePoint", ({ - enumerable: true, - get: function () { - return decode_codepoint_js_2.replaceCodePoint; - } -})); -Object.defineProperty(exports, "fromCodePoint", ({ - enumerable: true, - get: function () { - return decode_codepoint_js_2.fromCodePoint; - } -})); -var CharCodes; -(function (CharCodes) { - CharCodes[CharCodes["NUM"] = 35] = "NUM"; - CharCodes[CharCodes["SEMI"] = 59] = "SEMI"; - CharCodes[CharCodes["EQUALS"] = 61] = "EQUALS"; - CharCodes[CharCodes["ZERO"] = 48] = "ZERO"; - CharCodes[CharCodes["NINE"] = 57] = "NINE"; - CharCodes[CharCodes["LOWER_A"] = 97] = "LOWER_A"; - CharCodes[CharCodes["LOWER_F"] = 102] = "LOWER_F"; - CharCodes[CharCodes["LOWER_X"] = 120] = "LOWER_X"; - CharCodes[CharCodes["LOWER_Z"] = 122] = "LOWER_Z"; - CharCodes[CharCodes["UPPER_A"] = 65] = "UPPER_A"; - CharCodes[CharCodes["UPPER_F"] = 70] = "UPPER_F"; - CharCodes[CharCodes["UPPER_Z"] = 90] = "UPPER_Z"; -})(CharCodes || (CharCodes = {})); -/** Bit that needs to be set to convert an upper case ASCII character to lower case */ -var TO_LOWER_BIT = 32; -var BinTrieFlags; -(function (BinTrieFlags) { - BinTrieFlags[BinTrieFlags["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH"; - BinTrieFlags[BinTrieFlags["BRANCH_LENGTH"] = 16256] = "BRANCH_LENGTH"; - BinTrieFlags[BinTrieFlags["JUMP_TABLE"] = 127] = "JUMP_TABLE"; -})(BinTrieFlags = exports.BinTrieFlags || (exports.BinTrieFlags = {})); -function isNumber(code) { - return code >= CharCodes.ZERO && code <= CharCodes.NINE; -} -function isHexadecimalCharacter(code) { - return code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_F || code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_F; -} -function isAsciiAlphaNumeric(code) { - return code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_Z || code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_Z || isNumber(code); -} -/** - * Checks if the given character is a valid end character for an entity in an attribute. - * - * Attribute values that aren't terminated properly aren't parsed, and shouldn't lead to a parser error. - * See the example in https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state - */ -function isEntityInAttributeInvalidEnd(code) { - return code === CharCodes.EQUALS || isAsciiAlphaNumeric(code); -} -var EntityDecoderState; -(function (EntityDecoderState) { - EntityDecoderState[EntityDecoderState["EntityStart"] = 0] = "EntityStart"; - EntityDecoderState[EntityDecoderState["NumericStart"] = 1] = "NumericStart"; - EntityDecoderState[EntityDecoderState["NumericDecimal"] = 2] = "NumericDecimal"; - EntityDecoderState[EntityDecoderState["NumericHex"] = 3] = "NumericHex"; - EntityDecoderState[EntityDecoderState["NamedEntity"] = 4] = "NamedEntity"; -})(EntityDecoderState || (EntityDecoderState = {})); -var DecodingMode; -(function (DecodingMode) { - /** Entities in text nodes that can end with any character. */ - DecodingMode[DecodingMode["Legacy"] = 0] = "Legacy"; - /** Only allow entities terminated with a semicolon. */ - DecodingMode[DecodingMode["Strict"] = 1] = "Strict"; - /** Entities in attributes have limitations on ending characters. */ - DecodingMode[DecodingMode["Attribute"] = 2] = "Attribute"; -})(DecodingMode = exports.DecodingMode || (exports.DecodingMode = {})); -/** - * Token decoder with support of writing partial entities. - */ -var EntityDecoder = /** @class */function () { - function EntityDecoder( /** The tree used to decode entities. */ - decodeTree, - /** - * The function that is called when a codepoint is decoded. - * - * For multi-byte named entities, this will be called multiple times, - * with the second codepoint, and the same `consumed` value. - * - * @param codepoint The decoded codepoint. - * @param consumed The number of bytes consumed by the decoder. - */ - emitCodePoint, /** An object that is used to produce errors. */ - errors) { - this.decodeTree = decodeTree; - this.emitCodePoint = emitCodePoint; - this.errors = errors; - /** The current state of the decoder. */ - this.state = EntityDecoderState.EntityStart; - /** Characters that were consumed while parsing an entity. */ - this.consumed = 1; - /** - * The result of the entity. - * - * Either the result index of a numeric entity, or the codepoint of a - * numeric entity. - */ - this.result = 0; - /** The current index in the decode tree. */ - this.treeIndex = 0; - /** The number of characters that were consumed in excess. */ - this.excess = 1; - /** The mode in which the decoder is operating. */ - this.decodeMode = DecodingMode.Strict; - } - /** Resets the instance to make it reusable. */ - EntityDecoder.prototype.startEntity = function (decodeMode) { - this.decodeMode = decodeMode; - this.state = EntityDecoderState.EntityStart; - this.result = 0; - this.treeIndex = 0; - this.excess = 1; - this.consumed = 1; - }; - /** - * Write an entity to the decoder. This can be called multiple times with partial entities. - * If the entity is incomplete, the decoder will return -1. - * - * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the - * entity is incomplete, and resume when the next string is written. - * - * @param string The string containing the entity (or a continuation of the entity). - * @param offset The offset at which the entity begins. Should be 0 if this is not the first call. - * @returns The number of characters that were consumed, or -1 if the entity is incomplete. - */ - EntityDecoder.prototype.write = function (str, offset) { - switch (this.state) { - case EntityDecoderState.EntityStart: - { - if (str.charCodeAt(offset) === CharCodes.NUM) { - this.state = EntityDecoderState.NumericStart; - this.consumed += 1; - return this.stateNumericStart(str, offset + 1); - } - this.state = EntityDecoderState.NamedEntity; - return this.stateNamedEntity(str, offset); - } - case EntityDecoderState.NumericStart: - { - return this.stateNumericStart(str, offset); - } - case EntityDecoderState.NumericDecimal: - { - return this.stateNumericDecimal(str, offset); - } - case EntityDecoderState.NumericHex: - { - return this.stateNumericHex(str, offset); - } - case EntityDecoderState.NamedEntity: - { - return this.stateNamedEntity(str, offset); - } - } - }; - /** - * Switches between the numeric decimal and hexadecimal states. - * - * Equivalent to the `Numeric character reference state` in the HTML spec. - * - * @param str The string containing the entity (or a continuation of the entity). - * @param offset The current offset. - * @returns The number of characters that were consumed, or -1 if the entity is incomplete. - */ - EntityDecoder.prototype.stateNumericStart = function (str, offset) { - if (offset >= str.length) { - return -1; - } - if ((str.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) { - this.state = EntityDecoderState.NumericHex; - this.consumed += 1; - return this.stateNumericHex(str, offset + 1); - } - this.state = EntityDecoderState.NumericDecimal; - return this.stateNumericDecimal(str, offset); - }; - EntityDecoder.prototype.addToNumericResult = function (str, start, end, base) { - if (start !== end) { - var digitCount = end - start; - this.result = this.result * Math.pow(base, digitCount) + parseInt(str.substr(start, digitCount), base); - this.consumed += digitCount; - } - }; - /** - * Parses a hexadecimal numeric entity. - * - * Equivalent to the `Hexademical character reference state` in the HTML spec. - * - * @param str The string containing the entity (or a continuation of the entity). - * @param offset The current offset. - * @returns The number of characters that were consumed, or -1 if the entity is incomplete. - */ - EntityDecoder.prototype.stateNumericHex = function (str, offset) { - var startIdx = offset; - while (offset < str.length) { - var char = str.charCodeAt(offset); - if (isNumber(char) || isHexadecimalCharacter(char)) { - offset += 1; - } else { - this.addToNumericResult(str, startIdx, offset, 16); - return this.emitNumericEntity(char, 3); - } - } - this.addToNumericResult(str, startIdx, offset, 16); - return -1; - }; - /** - * Parses a decimal numeric entity. - * - * Equivalent to the `Decimal character reference state` in the HTML spec. - * - * @param str The string containing the entity (or a continuation of the entity). - * @param offset The current offset. - * @returns The number of characters that were consumed, or -1 if the entity is incomplete. - */ - EntityDecoder.prototype.stateNumericDecimal = function (str, offset) { - var startIdx = offset; - while (offset < str.length) { - var char = str.charCodeAt(offset); - if (isNumber(char)) { - offset += 1; - } else { - this.addToNumericResult(str, startIdx, offset, 10); - return this.emitNumericEntity(char, 2); - } - } - this.addToNumericResult(str, startIdx, offset, 10); - return -1; - }; - /** - * Validate and emit a numeric entity. - * - * Implements the logic from the `Hexademical character reference start - * state` and `Numeric character reference end state` in the HTML spec. - * - * @param lastCp The last code point of the entity. Used to see if the - * entity was terminated with a semicolon. - * @param expectedLength The minimum number of characters that should be - * consumed. Used to validate that at least one digit - * was consumed. - * @returns The number of characters that were consumed. - */ - EntityDecoder.prototype.emitNumericEntity = function (lastCp, expectedLength) { - var _a; - // Ensure we consumed at least one digit. - if (this.consumed <= expectedLength) { - (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed); - return 0; - } - // Figure out if this is a legit end of the entity - if (lastCp === CharCodes.SEMI) { - this.consumed += 1; - } else if (this.decodeMode === DecodingMode.Strict) { - return 0; - } - this.emitCodePoint((0, decode_codepoint_js_1.replaceCodePoint)(this.result), this.consumed); - if (this.errors) { - if (lastCp !== CharCodes.SEMI) { - this.errors.missingSemicolonAfterCharacterReference(); - } - this.errors.validateNumericCharacterReference(this.result); - } - return this.consumed; - }; - /** - * Parses a named entity. - * - * Equivalent to the `Named character reference state` in the HTML spec. - * - * @param str The string containing the entity (or a continuation of the entity). - * @param offset The current offset. - * @returns The number of characters that were consumed, or -1 if the entity is incomplete. - */ - EntityDecoder.prototype.stateNamedEntity = function (str, offset) { - var decodeTree = this.decodeTree; - var current = decodeTree[this.treeIndex]; - // The mask is the number of bytes of the value, including the current byte. - var valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14; - for (; offset < str.length; offset++, this.excess++) { - var char = str.charCodeAt(offset); - this.treeIndex = determineBranch(decodeTree, current, this.treeIndex + Math.max(1, valueLength), char); - if (this.treeIndex < 0) { - return this.result === 0 || - // If we are parsing an attribute - this.decodeMode === DecodingMode.Attribute && ( - // We shouldn't have consumed any characters after the entity, - valueLength === 0 || - // And there should be no invalid characters. - isEntityInAttributeInvalidEnd(char)) ? 0 : this.emitNotTerminatedNamedEntity(); - } - current = decodeTree[this.treeIndex]; - valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14; - // If the branch is a value, store it and continue - if (valueLength !== 0) { - // If the entity is terminated by a semicolon, we are done. - if (char === CharCodes.SEMI) { - return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess); - } - // If we encounter a non-terminated (legacy) entity while parsing strictly, then ignore it. - if (this.decodeMode !== DecodingMode.Strict) { - this.result = this.treeIndex; - this.consumed += this.excess; - this.excess = 0; - } - } - } - return -1; - }; - /** - * Emit a named entity that was not terminated with a semicolon. - * - * @returns The number of characters consumed. - */ - EntityDecoder.prototype.emitNotTerminatedNamedEntity = function () { - var _a; - var _b = this, - result = _b.result, - decodeTree = _b.decodeTree; - var valueLength = (decodeTree[result] & BinTrieFlags.VALUE_LENGTH) >> 14; - this.emitNamedEntityData(result, valueLength, this.consumed); - (_a = this.errors) === null || _a === void 0 ? void 0 : _a.missingSemicolonAfterCharacterReference(); - return this.consumed; - }; - /** - * Emit a named entity. - * - * @param result The index of the entity in the decode tree. - * @param valueLength The number of bytes in the entity. - * @param consumed The number of characters consumed. - * - * @returns The number of characters consumed. - */ - EntityDecoder.prototype.emitNamedEntityData = function (result, valueLength, consumed) { - var decodeTree = this.decodeTree; - this.emitCodePoint(valueLength === 1 ? decodeTree[result] & ~BinTrieFlags.VALUE_LENGTH : decodeTree[result + 1], consumed); - if (valueLength === 3) { - // For multi-byte values, we need to emit the second byte. - this.emitCodePoint(decodeTree[result + 2], consumed); - } - return consumed; - }; - /** - * Signal to the parser that the end of the input was reached. - * - * Remaining data will be emitted and relevant errors will be produced. - * - * @returns The number of characters consumed. - */ - EntityDecoder.prototype.end = function () { - var _a; - switch (this.state) { - case EntityDecoderState.NamedEntity: - { - // Emit a named entity if we have one. - return this.result !== 0 && (this.decodeMode !== DecodingMode.Attribute || this.result === this.treeIndex) ? this.emitNotTerminatedNamedEntity() : 0; - } - // Otherwise, emit a numeric entity if we have one. - case EntityDecoderState.NumericDecimal: - { - return this.emitNumericEntity(0, 2); - } - case EntityDecoderState.NumericHex: - { - return this.emitNumericEntity(0, 3); - } - case EntityDecoderState.NumericStart: - { - (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed); - return 0; - } - case EntityDecoderState.EntityStart: - { - // Return 0 if we have no entity. - return 0; - } - } - }; - return EntityDecoder; -}(); -exports.EntityDecoder = EntityDecoder; -/** - * Creates a function that decodes entities in a string. - * - * @param decodeTree The decode tree. - * @returns A function that decodes entities in a string. - */ -function getDecoder(decodeTree) { - var ret = ""; - var decoder = new EntityDecoder(decodeTree, function (str) { - return ret += (0, decode_codepoint_js_1.fromCodePoint)(str); - }); - return function decodeWithTrie(str, decodeMode) { - var lastIndex = 0; - var offset = 0; - while ((offset = str.indexOf("&", offset)) >= 0) { - ret += str.slice(lastIndex, offset); - decoder.startEntity(decodeMode); - var len = decoder.write(str, - // Skip the "&" - offset + 1); - if (len < 0) { - lastIndex = offset + decoder.end(); - break; - } - lastIndex = offset + len; - // If `len` is 0, skip the current `&` and continue. - offset = len === 0 ? lastIndex + 1 : lastIndex; - } - var result = ret + str.slice(lastIndex); - // Make sure we don't keep a reference to the final string. - ret = ""; - return result; - }; -} -/** - * Determines the branch of the current node that is taken given the current - * character. This function is used to traverse the trie. - * - * @param decodeTree The trie. - * @param current The current node. - * @param nodeIdx The index right after the current node and its value. - * @param char The current character. - * @returns The index of the next node, or -1 if no branch is taken. - */ -function determineBranch(decodeTree, current, nodeIdx, char) { - var branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7; - var jumpOffset = current & BinTrieFlags.JUMP_TABLE; - // Case 1: Single branch encoded in jump offset - if (branchCount === 0) { - return jumpOffset !== 0 && char === jumpOffset ? nodeIdx : -1; - } - // Case 2: Multiple branches encoded in jump table - if (jumpOffset) { - var value = char - jumpOffset; - return value < 0 || value >= branchCount ? -1 : decodeTree[nodeIdx + value] - 1; - } - // Case 3: Multiple branches encoded in dictionary - // Binary search for the character. - var lo = nodeIdx; - var hi = lo + branchCount - 1; - while (lo <= hi) { - var mid = lo + hi >>> 1; - var midVal = decodeTree[mid]; - if (midVal < char) { - lo = mid + 1; - } else if (midVal > char) { - hi = mid - 1; - } else { - return decodeTree[mid + branchCount]; - } - } - return -1; -} -exports.determineBranch = determineBranch; -var htmlDecoder = getDecoder(decode_data_html_js_1.default); -var xmlDecoder = getDecoder(decode_data_xml_js_1.default); -/** - * Decodes an HTML string. - * - * @param str The string to decode. - * @param mode The decoding mode. - * @returns The decoded string. - */ -function decodeHTML(str, mode) { - if (mode === void 0) { - mode = DecodingMode.Legacy; - } - return htmlDecoder(str, mode); -} -exports.decodeHTML = decodeHTML; -/** - * Decodes an HTML string in an attribute. - * - * @param str The string to decode. - * @returns The decoded string. - */ -function decodeHTMLAttribute(str) { - return htmlDecoder(str, DecodingMode.Attribute); -} -exports.decodeHTMLAttribute = decodeHTMLAttribute; -/** - * Decodes an HTML string, requiring all entities to be terminated by a semicolon. - * - * @param str The string to decode. - * @returns The decoded string. - */ -function decodeHTMLStrict(str) { - return htmlDecoder(str, DecodingMode.Strict); -} -exports.decodeHTMLStrict = decodeHTMLStrict; -/** - * Decodes an XML string, requiring all entities to be terminated by a semicolon. - * - * @param str The string to decode. - * @returns The decoded string. - */ -function decodeXML(str) { - return xmlDecoder(str, DecodingMode.Strict); -} -exports.decodeXML = decodeXML; - -/***/ }), - -/***/ "../../../node_modules/entities/lib/decode_codepoint.js": -/*!**************************************************************!*\ - !*** ../../../node_modules/entities/lib/decode_codepoint.js ***! - \**************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -// Adapted from https://github.com/mathiasbynens/he/blob/36afe179392226cf1b6ccdb16ebbb7a5a844d93a/src/he.js#L106-L134 -var _a; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.replaceCodePoint = exports.fromCodePoint = void 0; -var decodeMap = new Map([[0, 65533], -// C1 Unicode control character reference replacements -[128, 8364], [130, 8218], [131, 402], [132, 8222], [133, 8230], [134, 8224], [135, 8225], [136, 710], [137, 8240], [138, 352], [139, 8249], [140, 338], [142, 381], [145, 8216], [146, 8217], [147, 8220], [148, 8221], [149, 8226], [150, 8211], [151, 8212], [152, 732], [153, 8482], [154, 353], [155, 8250], [156, 339], [158, 382], [159, 376]]); -/** - * Polyfill for `String.fromCodePoint`. It is used to create a string from a Unicode code point. - */ -exports.fromCodePoint = -// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, node/no-unsupported-features/es-builtins -(_a = String.fromCodePoint) !== null && _a !== void 0 ? _a : function (codePoint) { - var output = ""; - if (codePoint > 0xffff) { - codePoint -= 0x10000; - output += String.fromCharCode(codePoint >>> 10 & 0x3ff | 0xd800); - codePoint = 0xdc00 | codePoint & 0x3ff; - } - output += String.fromCharCode(codePoint); - return output; -}; -/** - * Replace the given code point with a replacement character if it is a - * surrogate or is outside the valid range. Otherwise return the code - * point unchanged. - */ -function replaceCodePoint(codePoint) { - var _a; - if (codePoint >= 0xd800 && codePoint <= 0xdfff || codePoint > 0x10ffff) { - return 0xfffd; - } - return (_a = decodeMap.get(codePoint)) !== null && _a !== void 0 ? _a : codePoint; -} -exports.replaceCodePoint = replaceCodePoint; -/** - * Replace the code point if relevant, then convert it to a string. - * - * @deprecated Use `fromCodePoint(replaceCodePoint(codePoint))` instead. - * @param codePoint The code point to decode. - * @returns The decoded code point. - */ -function decodeCodePoint(codePoint) { - return (0, exports.fromCodePoint)(replaceCodePoint(codePoint)); -} -exports["default"] = decodeCodePoint; - -/***/ }), - -/***/ "../../../node_modules/entities/lib/encode.js": -/*!****************************************************!*\ - !*** ../../../node_modules/entities/lib/encode.js ***! - \****************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -var __importDefault = void 0 && (void 0).__importDefault || function (mod) { - return mod && mod.__esModule ? mod : { - "default": mod - }; -}; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.encodeNonAsciiHTML = exports.encodeHTML = void 0; -var encode_html_js_1 = __importDefault(__webpack_require__(/*! ./generated/encode-html.js */ "../../../node_modules/entities/lib/generated/encode-html.js")); -var escape_js_1 = __webpack_require__(/*! ./escape.js */ "../../../node_modules/entities/lib/escape.js"); -var htmlReplacer = /[\t\n!-,./:-@[-`\f{-}$\x80-\uFFFF]/g; -/** - * Encodes all characters in the input using HTML entities. This includes - * characters that are valid ASCII characters in HTML documents, such as `#`. - * - * To get a more compact output, consider using the `encodeNonAsciiHTML` - * function, which will only encode characters that are not valid in HTML - * documents, as well as non-ASCII characters. - * - * If a character has no equivalent entity, a numeric hexadecimal reference - * (eg. `ü`) will be used. - */ -function encodeHTML(data) { - return encodeHTMLTrieRe(htmlReplacer, data); -} -exports.encodeHTML = encodeHTML; -/** - * Encodes all non-ASCII characters, as well as characters not valid in HTML - * documents using HTML entities. This function will not encode characters that - * are valid in HTML documents, such as `#`. - * - * If a character has no equivalent entity, a numeric hexadecimal reference - * (eg. `ü`) will be used. - */ -function encodeNonAsciiHTML(data) { - return encodeHTMLTrieRe(escape_js_1.xmlReplacer, data); -} -exports.encodeNonAsciiHTML = encodeNonAsciiHTML; -function encodeHTMLTrieRe(regExp, str) { - var ret = ""; - var lastIdx = 0; - var match; - while ((match = regExp.exec(str)) !== null) { - var i = match.index; - ret += str.substring(lastIdx, i); - var char = str.charCodeAt(i); - var next = encode_html_js_1.default.get(char); - if (typeof next === "object") { - // We are in a branch. Try to match the next char. - if (i + 1 < str.length) { - var nextChar = str.charCodeAt(i + 1); - var value = typeof next.n === "number" ? next.n === nextChar ? next.o : undefined : next.n.get(nextChar); - if (value !== undefined) { - ret += value; - lastIdx = regExp.lastIndex += 1; - continue; - } - } - next = next.v; - } - // We might have a tree node without a value; skip and use a numeric entity. - if (next !== undefined) { - ret += next; - lastIdx = i + 1; - } else { - var cp = (0, escape_js_1.getCodePoint)(str, i); - ret += "&#x".concat(cp.toString(16), ";"); - // Increase by 1 if we have a surrogate pair - lastIdx = regExp.lastIndex += Number(cp !== char); - } - } - return ret + str.substr(lastIdx); -} - -/***/ }), - -/***/ "../../../node_modules/entities/lib/escape.js": -/*!****************************************************!*\ - !*** ../../../node_modules/entities/lib/escape.js ***! - \****************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.escapeText = exports.escapeAttribute = exports.escapeUTF8 = exports.escape = exports.encodeXML = exports.getCodePoint = exports.xmlReplacer = void 0; -exports.xmlReplacer = /["&'<>$\x80-\uFFFF]/g; -var xmlCodeMap = new Map([[34, """], [38, "&"], [39, "'"], [60, "<"], [62, ">"]]); -// For compatibility with node < 4, we wrap `codePointAt` -exports.getCodePoint = -// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -String.prototype.codePointAt != null ? function (str, index) { - return str.codePointAt(index); -} : -// http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae -function (c, index) { - return (c.charCodeAt(index) & 0xfc00) === 0xd800 ? (c.charCodeAt(index) - 0xd800) * 0x400 + c.charCodeAt(index + 1) - 0xdc00 + 0x10000 : c.charCodeAt(index); -}; -/** - * Encodes all non-ASCII characters, as well as characters not valid in XML - * documents using XML entities. - * - * If a character has no equivalent entity, a - * numeric hexadecimal reference (eg. `ü`) will be used. - */ -function encodeXML(str) { - var ret = ""; - var lastIdx = 0; - var match; - while ((match = exports.xmlReplacer.exec(str)) !== null) { - var i = match.index; - var char = str.charCodeAt(i); - var next = xmlCodeMap.get(char); - if (next !== undefined) { - ret += str.substring(lastIdx, i) + next; - lastIdx = i + 1; - } else { - ret += "".concat(str.substring(lastIdx, i), "&#x").concat((0, exports.getCodePoint)(str, i).toString(16), ";"); - // Increase by 1 if we have a surrogate pair - lastIdx = exports.xmlReplacer.lastIndex += Number((char & 0xfc00) === 0xd800); - } - } - return ret + str.substr(lastIdx); -} -exports.encodeXML = encodeXML; -/** - * Encodes all non-ASCII characters, as well as characters not valid in XML - * documents using numeric hexadecimal reference (eg. `ü`). - * - * Have a look at `escapeUTF8` if you want a more concise output at the expense - * of reduced transportability. - * - * @param data String to escape. - */ -exports.escape = encodeXML; -/** - * Creates a function that escapes all characters matched by the given regular - * expression using the given map of characters to escape to their entities. - * - * @param regex Regular expression to match characters to escape. - * @param map Map of characters to escape to their entities. - * - * @returns Function that escapes all characters matched by the given regular - * expression using the given map of characters to escape to their entities. - */ -function getEscaper(regex, map) { - return function escape(data) { - var match; - var lastIdx = 0; - var result = ""; - while (match = regex.exec(data)) { - if (lastIdx !== match.index) { - result += data.substring(lastIdx, match.index); - } - // We know that this character will be in the map. - result += map.get(match[0].charCodeAt(0)); - // Every match will be of length 1 - lastIdx = match.index + 1; - } - return result + data.substring(lastIdx); - }; -} -/** - * Encodes all characters not valid in XML documents using XML entities. - * - * Note that the output will be character-set dependent. - * - * @param data String to escape. - */ -exports.escapeUTF8 = getEscaper(/[&<>'"]/g, xmlCodeMap); -/** - * Encodes all characters that have to be escaped in HTML attributes, - * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. - * - * @param data String to escape. - */ -exports.escapeAttribute = getEscaper(/["&\u00A0]/g, new Map([[34, """], [38, "&"], [160, " "]])); -/** - * Encodes all characters that have to be escaped in HTML text, - * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. - * - * @param data String to escape. - */ -exports.escapeText = getEscaper(/[&<>\u00A0]/g, new Map([[38, "&"], [60, "<"], [62, ">"], [160, " "]])); - -/***/ }), - -/***/ "../../../node_modules/entities/lib/generated/decode-data-html.js": -/*!************************************************************************!*\ - !*** ../../../node_modules/entities/lib/generated/decode-data-html.js ***! - \************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -// Generated using scripts/write-decode-map.ts -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = new Uint16Array( -// prettier-ignore -"\u1d41<\xd5\u0131\u028a\u049d\u057b\u05d0\u0675\u06de\u07a2\u07d6\u080f\u0a4a\u0a91\u0da1\u0e6d\u0f09\u0f26\u10ca\u1228\u12e1\u1415\u149d\u14c3\u14df\u1525\0\0\0\0\0\0\u156b\u16cd\u198d\u1c12\u1ddd\u1f7e\u2060\u21b0\u228d\u23c0\u23fb\u2442\u2824\u2912\u2d08\u2e48\u2fce\u3016\u32ba\u3639\u37ac\u38fe\u3a28\u3a71\u3ae0\u3b2e\u0800EMabcfglmnoprstu\\bfms\x7f\x84\x8b\x90\x95\x98\xa6\xb3\xb9\xc8\xcflig\u803b\xc6\u40c6P\u803b&\u4026cute\u803b\xc1\u40c1reve;\u4102\u0100iyx}rc\u803b\xc2\u40c2;\u4410r;\uc000\ud835\udd04rave\u803b\xc0\u40c0pha;\u4391acr;\u4100d;\u6a53\u0100gp\x9d\xa1on;\u4104f;\uc000\ud835\udd38plyFunction;\u6061ing\u803b\xc5\u40c5\u0100cs\xbe\xc3r;\uc000\ud835\udc9cign;\u6254ilde\u803b\xc3\u40c3ml\u803b\xc4\u40c4\u0400aceforsu\xe5\xfb\xfe\u0117\u011c\u0122\u0127\u012a\u0100cr\xea\xf2kslash;\u6216\u0176\xf6\xf8;\u6ae7ed;\u6306y;\u4411\u0180crt\u0105\u010b\u0114ause;\u6235noullis;\u612ca;\u4392r;\uc000\ud835\udd05pf;\uc000\ud835\udd39eve;\u42d8c\xf2\u0113mpeq;\u624e\u0700HOacdefhilorsu\u014d\u0151\u0156\u0180\u019e\u01a2\u01b5\u01b7\u01ba\u01dc\u0215\u0273\u0278\u027ecy;\u4427PY\u803b\xa9\u40a9\u0180cpy\u015d\u0162\u017aute;\u4106\u0100;i\u0167\u0168\u62d2talDifferentialD;\u6145leys;\u612d\u0200aeio\u0189\u018e\u0194\u0198ron;\u410cdil\u803b\xc7\u40c7rc;\u4108nint;\u6230ot;\u410a\u0100dn\u01a7\u01adilla;\u40b8terDot;\u40b7\xf2\u017fi;\u43a7rcle\u0200DMPT\u01c7\u01cb\u01d1\u01d6ot;\u6299inus;\u6296lus;\u6295imes;\u6297o\u0100cs\u01e2\u01f8kwiseContourIntegral;\u6232eCurly\u0100DQ\u0203\u020foubleQuote;\u601duote;\u6019\u0200lnpu\u021e\u0228\u0247\u0255on\u0100;e\u0225\u0226\u6237;\u6a74\u0180git\u022f\u0236\u023aruent;\u6261nt;\u622fourIntegral;\u622e\u0100fr\u024c\u024e;\u6102oduct;\u6210nterClockwiseContourIntegral;\u6233oss;\u6a2fcr;\uc000\ud835\udc9ep\u0100;C\u0284\u0285\u62d3ap;\u624d\u0580DJSZacefios\u02a0\u02ac\u02b0\u02b4\u02b8\u02cb\u02d7\u02e1\u02e6\u0333\u048d\u0100;o\u0179\u02a5trahd;\u6911cy;\u4402cy;\u4405cy;\u440f\u0180grs\u02bf\u02c4\u02c7ger;\u6021r;\u61a1hv;\u6ae4\u0100ay\u02d0\u02d5ron;\u410e;\u4414l\u0100;t\u02dd\u02de\u6207a;\u4394r;\uc000\ud835\udd07\u0100af\u02eb\u0327\u0100cm\u02f0\u0322ritical\u0200ADGT\u0300\u0306\u0316\u031ccute;\u40b4o\u0174\u030b\u030d;\u42d9bleAcute;\u42ddrave;\u4060ilde;\u42dcond;\u62c4ferentialD;\u6146\u0470\u033d\0\0\0\u0342\u0354\0\u0405f;\uc000\ud835\udd3b\u0180;DE\u0348\u0349\u034d\u40a8ot;\u60dcqual;\u6250ble\u0300CDLRUV\u0363\u0372\u0382\u03cf\u03e2\u03f8ontourIntegra\xec\u0239o\u0274\u0379\0\0\u037b\xbb\u0349nArrow;\u61d3\u0100eo\u0387\u03a4ft\u0180ART\u0390\u0396\u03a1rrow;\u61d0ightArrow;\u61d4e\xe5\u02cang\u0100LR\u03ab\u03c4eft\u0100AR\u03b3\u03b9rrow;\u67f8ightArrow;\u67faightArrow;\u67f9ight\u0100AT\u03d8\u03derrow;\u61d2ee;\u62a8p\u0241\u03e9\0\0\u03efrrow;\u61d1ownArrow;\u61d5erticalBar;\u6225n\u0300ABLRTa\u0412\u042a\u0430\u045e\u047f\u037crrow\u0180;BU\u041d\u041e\u0422\u6193ar;\u6913pArrow;\u61f5reve;\u4311eft\u02d2\u043a\0\u0446\0\u0450ightVector;\u6950eeVector;\u695eector\u0100;B\u0459\u045a\u61bdar;\u6956ight\u01d4\u0467\0\u0471eeVector;\u695fector\u0100;B\u047a\u047b\u61c1ar;\u6957ee\u0100;A\u0486\u0487\u62a4rrow;\u61a7\u0100ct\u0492\u0497r;\uc000\ud835\udc9frok;\u4110\u0800NTacdfglmopqstux\u04bd\u04c0\u04c4\u04cb\u04de\u04e2\u04e7\u04ee\u04f5\u0521\u052f\u0536\u0552\u055d\u0560\u0565G;\u414aH\u803b\xd0\u40d0cute\u803b\xc9\u40c9\u0180aiy\u04d2\u04d7\u04dcron;\u411arc\u803b\xca\u40ca;\u442dot;\u4116r;\uc000\ud835\udd08rave\u803b\xc8\u40c8ement;\u6208\u0100ap\u04fa\u04fecr;\u4112ty\u0253\u0506\0\0\u0512mallSquare;\u65fberySmallSquare;\u65ab\u0100gp\u0526\u052aon;\u4118f;\uc000\ud835\udd3csilon;\u4395u\u0100ai\u053c\u0549l\u0100;T\u0542\u0543\u6a75ilde;\u6242librium;\u61cc\u0100ci\u0557\u055ar;\u6130m;\u6a73a;\u4397ml\u803b\xcb\u40cb\u0100ip\u056a\u056fsts;\u6203onentialE;\u6147\u0280cfios\u0585\u0588\u058d\u05b2\u05ccy;\u4424r;\uc000\ud835\udd09lled\u0253\u0597\0\0\u05a3mallSquare;\u65fcerySmallSquare;\u65aa\u0370\u05ba\0\u05bf\0\0\u05c4f;\uc000\ud835\udd3dAll;\u6200riertrf;\u6131c\xf2\u05cb\u0600JTabcdfgorst\u05e8\u05ec\u05ef\u05fa\u0600\u0612\u0616\u061b\u061d\u0623\u066c\u0672cy;\u4403\u803b>\u403emma\u0100;d\u05f7\u05f8\u4393;\u43dcreve;\u411e\u0180eiy\u0607\u060c\u0610dil;\u4122rc;\u411c;\u4413ot;\u4120r;\uc000\ud835\udd0a;\u62d9pf;\uc000\ud835\udd3eeater\u0300EFGLST\u0635\u0644\u064e\u0656\u065b\u0666qual\u0100;L\u063e\u063f\u6265ess;\u62dbullEqual;\u6267reater;\u6aa2ess;\u6277lantEqual;\u6a7eilde;\u6273cr;\uc000\ud835\udca2;\u626b\u0400Aacfiosu\u0685\u068b\u0696\u069b\u069e\u06aa\u06be\u06caRDcy;\u442a\u0100ct\u0690\u0694ek;\u42c7;\u405eirc;\u4124r;\u610clbertSpace;\u610b\u01f0\u06af\0\u06b2f;\u610dizontalLine;\u6500\u0100ct\u06c3\u06c5\xf2\u06a9rok;\u4126mp\u0144\u06d0\u06d8ownHum\xf0\u012fqual;\u624f\u0700EJOacdfgmnostu\u06fa\u06fe\u0703\u0707\u070e\u071a\u071e\u0721\u0728\u0744\u0778\u078b\u078f\u0795cy;\u4415lig;\u4132cy;\u4401cute\u803b\xcd\u40cd\u0100iy\u0713\u0718rc\u803b\xce\u40ce;\u4418ot;\u4130r;\u6111rave\u803b\xcc\u40cc\u0180;ap\u0720\u072f\u073f\u0100cg\u0734\u0737r;\u412ainaryI;\u6148lie\xf3\u03dd\u01f4\u0749\0\u0762\u0100;e\u074d\u074e\u622c\u0100gr\u0753\u0758ral;\u622bsection;\u62c2isible\u0100CT\u076c\u0772omma;\u6063imes;\u6062\u0180gpt\u077f\u0783\u0788on;\u412ef;\uc000\ud835\udd40a;\u4399cr;\u6110ilde;\u4128\u01eb\u079a\0\u079ecy;\u4406l\u803b\xcf\u40cf\u0280cfosu\u07ac\u07b7\u07bc\u07c2\u07d0\u0100iy\u07b1\u07b5rc;\u4134;\u4419r;\uc000\ud835\udd0dpf;\uc000\ud835\udd41\u01e3\u07c7\0\u07ccr;\uc000\ud835\udca5rcy;\u4408kcy;\u4404\u0380HJacfos\u07e4\u07e8\u07ec\u07f1\u07fd\u0802\u0808cy;\u4425cy;\u440cppa;\u439a\u0100ey\u07f6\u07fbdil;\u4136;\u441ar;\uc000\ud835\udd0epf;\uc000\ud835\udd42cr;\uc000\ud835\udca6\u0580JTaceflmost\u0825\u0829\u082c\u0850\u0863\u09b3\u09b8\u09c7\u09cd\u0a37\u0a47cy;\u4409\u803b<\u403c\u0280cmnpr\u0837\u083c\u0841\u0844\u084dute;\u4139bda;\u439bg;\u67ealacetrf;\u6112r;\u619e\u0180aey\u0857\u085c\u0861ron;\u413ddil;\u413b;\u441b\u0100fs\u0868\u0970t\u0500ACDFRTUVar\u087e\u08a9\u08b1\u08e0\u08e6\u08fc\u092f\u095b\u0390\u096a\u0100nr\u0883\u088fgleBracket;\u67e8row\u0180;BR\u0899\u089a\u089e\u6190ar;\u61e4ightArrow;\u61c6eiling;\u6308o\u01f5\u08b7\0\u08c3bleBracket;\u67e6n\u01d4\u08c8\0\u08d2eeVector;\u6961ector\u0100;B\u08db\u08dc\u61c3ar;\u6959loor;\u630aight\u0100AV\u08ef\u08f5rrow;\u6194ector;\u694e\u0100er\u0901\u0917e\u0180;AV\u0909\u090a\u0910\u62a3rrow;\u61a4ector;\u695aiangle\u0180;BE\u0924\u0925\u0929\u62b2ar;\u69cfqual;\u62b4p\u0180DTV\u0937\u0942\u094cownVector;\u6951eeVector;\u6960ector\u0100;B\u0956\u0957\u61bfar;\u6958ector\u0100;B\u0965\u0966\u61bcar;\u6952ight\xe1\u039cs\u0300EFGLST\u097e\u098b\u0995\u099d\u09a2\u09adqualGreater;\u62daullEqual;\u6266reater;\u6276ess;\u6aa1lantEqual;\u6a7dilde;\u6272r;\uc000\ud835\udd0f\u0100;e\u09bd\u09be\u62d8ftarrow;\u61daidot;\u413f\u0180npw\u09d4\u0a16\u0a1bg\u0200LRlr\u09de\u09f7\u0a02\u0a10eft\u0100AR\u09e6\u09ecrrow;\u67f5ightArrow;\u67f7ightArrow;\u67f6eft\u0100ar\u03b3\u0a0aight\xe1\u03bfight\xe1\u03caf;\uc000\ud835\udd43er\u0100LR\u0a22\u0a2ceftArrow;\u6199ightArrow;\u6198\u0180cht\u0a3e\u0a40\u0a42\xf2\u084c;\u61b0rok;\u4141;\u626a\u0400acefiosu\u0a5a\u0a5d\u0a60\u0a77\u0a7c\u0a85\u0a8b\u0a8ep;\u6905y;\u441c\u0100dl\u0a65\u0a6fiumSpace;\u605flintrf;\u6133r;\uc000\ud835\udd10nusPlus;\u6213pf;\uc000\ud835\udd44c\xf2\u0a76;\u439c\u0480Jacefostu\u0aa3\u0aa7\u0aad\u0ac0\u0b14\u0b19\u0d91\u0d97\u0d9ecy;\u440acute;\u4143\u0180aey\u0ab4\u0ab9\u0aberon;\u4147dil;\u4145;\u441d\u0180gsw\u0ac7\u0af0\u0b0eative\u0180MTV\u0ad3\u0adf\u0ae8ediumSpace;\u600bhi\u0100cn\u0ae6\u0ad8\xeb\u0ad9eryThi\xee\u0ad9ted\u0100GL\u0af8\u0b06reaterGreate\xf2\u0673essLes\xf3\u0a48Line;\u400ar;\uc000\ud835\udd11\u0200Bnpt\u0b22\u0b28\u0b37\u0b3areak;\u6060BreakingSpace;\u40a0f;\u6115\u0680;CDEGHLNPRSTV\u0b55\u0b56\u0b6a\u0b7c\u0ba1\u0beb\u0c04\u0c5e\u0c84\u0ca6\u0cd8\u0d61\u0d85\u6aec\u0100ou\u0b5b\u0b64ngruent;\u6262pCap;\u626doubleVerticalBar;\u6226\u0180lqx\u0b83\u0b8a\u0b9bement;\u6209ual\u0100;T\u0b92\u0b93\u6260ilde;\uc000\u2242\u0338ists;\u6204reater\u0380;EFGLST\u0bb6\u0bb7\u0bbd\u0bc9\u0bd3\u0bd8\u0be5\u626fqual;\u6271ullEqual;\uc000\u2267\u0338reater;\uc000\u226b\u0338ess;\u6279lantEqual;\uc000\u2a7e\u0338ilde;\u6275ump\u0144\u0bf2\u0bfdownHump;\uc000\u224e\u0338qual;\uc000\u224f\u0338e\u0100fs\u0c0a\u0c27tTriangle\u0180;BE\u0c1a\u0c1b\u0c21\u62eaar;\uc000\u29cf\u0338qual;\u62ecs\u0300;EGLST\u0c35\u0c36\u0c3c\u0c44\u0c4b\u0c58\u626equal;\u6270reater;\u6278ess;\uc000\u226a\u0338lantEqual;\uc000\u2a7d\u0338ilde;\u6274ested\u0100GL\u0c68\u0c79reaterGreater;\uc000\u2aa2\u0338essLess;\uc000\u2aa1\u0338recedes\u0180;ES\u0c92\u0c93\u0c9b\u6280qual;\uc000\u2aaf\u0338lantEqual;\u62e0\u0100ei\u0cab\u0cb9verseElement;\u620cghtTriangle\u0180;BE\u0ccb\u0ccc\u0cd2\u62ebar;\uc000\u29d0\u0338qual;\u62ed\u0100qu\u0cdd\u0d0cuareSu\u0100bp\u0ce8\u0cf9set\u0100;E\u0cf0\u0cf3\uc000\u228f\u0338qual;\u62e2erset\u0100;E\u0d03\u0d06\uc000\u2290\u0338qual;\u62e3\u0180bcp\u0d13\u0d24\u0d4eset\u0100;E\u0d1b\u0d1e\uc000\u2282\u20d2qual;\u6288ceeds\u0200;EST\u0d32\u0d33\u0d3b\u0d46\u6281qual;\uc000\u2ab0\u0338lantEqual;\u62e1ilde;\uc000\u227f\u0338erset\u0100;E\u0d58\u0d5b\uc000\u2283\u20d2qual;\u6289ilde\u0200;EFT\u0d6e\u0d6f\u0d75\u0d7f\u6241qual;\u6244ullEqual;\u6247ilde;\u6249erticalBar;\u6224cr;\uc000\ud835\udca9ilde\u803b\xd1\u40d1;\u439d\u0700Eacdfgmoprstuv\u0dbd\u0dc2\u0dc9\u0dd5\u0ddb\u0de0\u0de7\u0dfc\u0e02\u0e20\u0e22\u0e32\u0e3f\u0e44lig;\u4152cute\u803b\xd3\u40d3\u0100iy\u0dce\u0dd3rc\u803b\xd4\u40d4;\u441eblac;\u4150r;\uc000\ud835\udd12rave\u803b\xd2\u40d2\u0180aei\u0dee\u0df2\u0df6cr;\u414cga;\u43a9cron;\u439fpf;\uc000\ud835\udd46enCurly\u0100DQ\u0e0e\u0e1aoubleQuote;\u601cuote;\u6018;\u6a54\u0100cl\u0e27\u0e2cr;\uc000\ud835\udcaaash\u803b\xd8\u40d8i\u016c\u0e37\u0e3cde\u803b\xd5\u40d5es;\u6a37ml\u803b\xd6\u40d6er\u0100BP\u0e4b\u0e60\u0100ar\u0e50\u0e53r;\u603eac\u0100ek\u0e5a\u0e5c;\u63deet;\u63b4arenthesis;\u63dc\u0480acfhilors\u0e7f\u0e87\u0e8a\u0e8f\u0e92\u0e94\u0e9d\u0eb0\u0efcrtialD;\u6202y;\u441fr;\uc000\ud835\udd13i;\u43a6;\u43a0usMinus;\u40b1\u0100ip\u0ea2\u0eadncareplan\xe5\u069df;\u6119\u0200;eio\u0eb9\u0eba\u0ee0\u0ee4\u6abbcedes\u0200;EST\u0ec8\u0ec9\u0ecf\u0eda\u627aqual;\u6aaflantEqual;\u627cilde;\u627eme;\u6033\u0100dp\u0ee9\u0eeeuct;\u620fortion\u0100;a\u0225\u0ef9l;\u621d\u0100ci\u0f01\u0f06r;\uc000\ud835\udcab;\u43a8\u0200Ufos\u0f11\u0f16\u0f1b\u0f1fOT\u803b\"\u4022r;\uc000\ud835\udd14pf;\u611acr;\uc000\ud835\udcac\u0600BEacefhiorsu\u0f3e\u0f43\u0f47\u0f60\u0f73\u0fa7\u0faa\u0fad\u1096\u10a9\u10b4\u10bearr;\u6910G\u803b\xae\u40ae\u0180cnr\u0f4e\u0f53\u0f56ute;\u4154g;\u67ebr\u0100;t\u0f5c\u0f5d\u61a0l;\u6916\u0180aey\u0f67\u0f6c\u0f71ron;\u4158dil;\u4156;\u4420\u0100;v\u0f78\u0f79\u611cerse\u0100EU\u0f82\u0f99\u0100lq\u0f87\u0f8eement;\u620builibrium;\u61cbpEquilibrium;\u696fr\xbb\u0f79o;\u43a1ght\u0400ACDFTUVa\u0fc1\u0feb\u0ff3\u1022\u1028\u105b\u1087\u03d8\u0100nr\u0fc6\u0fd2gleBracket;\u67e9row\u0180;BL\u0fdc\u0fdd\u0fe1\u6192ar;\u61e5eftArrow;\u61c4eiling;\u6309o\u01f5\u0ff9\0\u1005bleBracket;\u67e7n\u01d4\u100a\0\u1014eeVector;\u695dector\u0100;B\u101d\u101e\u61c2ar;\u6955loor;\u630b\u0100er\u102d\u1043e\u0180;AV\u1035\u1036\u103c\u62a2rrow;\u61a6ector;\u695biangle\u0180;BE\u1050\u1051\u1055\u62b3ar;\u69d0qual;\u62b5p\u0180DTV\u1063\u106e\u1078ownVector;\u694feeVector;\u695cector\u0100;B\u1082\u1083\u61bear;\u6954ector\u0100;B\u1091\u1092\u61c0ar;\u6953\u0100pu\u109b\u109ef;\u611dndImplies;\u6970ightarrow;\u61db\u0100ch\u10b9\u10bcr;\u611b;\u61b1leDelayed;\u69f4\u0680HOacfhimoqstu\u10e4\u10f1\u10f7\u10fd\u1119\u111e\u1151\u1156\u1161\u1167\u11b5\u11bb\u11bf\u0100Cc\u10e9\u10eeHcy;\u4429y;\u4428FTcy;\u442ccute;\u415a\u0280;aeiy\u1108\u1109\u110e\u1113\u1117\u6abcron;\u4160dil;\u415erc;\u415c;\u4421r;\uc000\ud835\udd16ort\u0200DLRU\u112a\u1134\u113e\u1149ownArrow\xbb\u041eeftArrow\xbb\u089aightArrow\xbb\u0fddpArrow;\u6191gma;\u43a3allCircle;\u6218pf;\uc000\ud835\udd4a\u0272\u116d\0\0\u1170t;\u621aare\u0200;ISU\u117b\u117c\u1189\u11af\u65a1ntersection;\u6293u\u0100bp\u118f\u119eset\u0100;E\u1197\u1198\u628fqual;\u6291erset\u0100;E\u11a8\u11a9\u6290qual;\u6292nion;\u6294cr;\uc000\ud835\udcaear;\u62c6\u0200bcmp\u11c8\u11db\u1209\u120b\u0100;s\u11cd\u11ce\u62d0et\u0100;E\u11cd\u11d5qual;\u6286\u0100ch\u11e0\u1205eeds\u0200;EST\u11ed\u11ee\u11f4\u11ff\u627bqual;\u6ab0lantEqual;\u627dilde;\u627fTh\xe1\u0f8c;\u6211\u0180;es\u1212\u1213\u1223\u62d1rset\u0100;E\u121c\u121d\u6283qual;\u6287et\xbb\u1213\u0580HRSacfhiors\u123e\u1244\u1249\u1255\u125e\u1271\u1276\u129f\u12c2\u12c8\u12d1ORN\u803b\xde\u40deADE;\u6122\u0100Hc\u124e\u1252cy;\u440by;\u4426\u0100bu\u125a\u125c;\u4009;\u43a4\u0180aey\u1265\u126a\u126fron;\u4164dil;\u4162;\u4422r;\uc000\ud835\udd17\u0100ei\u127b\u1289\u01f2\u1280\0\u1287efore;\u6234a;\u4398\u0100cn\u128e\u1298kSpace;\uc000\u205f\u200aSpace;\u6009lde\u0200;EFT\u12ab\u12ac\u12b2\u12bc\u623cqual;\u6243ullEqual;\u6245ilde;\u6248pf;\uc000\ud835\udd4bipleDot;\u60db\u0100ct\u12d6\u12dbr;\uc000\ud835\udcafrok;\u4166\u0ae1\u12f7\u130e\u131a\u1326\0\u132c\u1331\0\0\0\0\0\u1338\u133d\u1377\u1385\0\u13ff\u1404\u140a\u1410\u0100cr\u12fb\u1301ute\u803b\xda\u40dar\u0100;o\u1307\u1308\u619fcir;\u6949r\u01e3\u1313\0\u1316y;\u440eve;\u416c\u0100iy\u131e\u1323rc\u803b\xdb\u40db;\u4423blac;\u4170r;\uc000\ud835\udd18rave\u803b\xd9\u40d9acr;\u416a\u0100di\u1341\u1369er\u0100BP\u1348\u135d\u0100ar\u134d\u1350r;\u405fac\u0100ek\u1357\u1359;\u63dfet;\u63b5arenthesis;\u63ddon\u0100;P\u1370\u1371\u62c3lus;\u628e\u0100gp\u137b\u137fon;\u4172f;\uc000\ud835\udd4c\u0400ADETadps\u1395\u13ae\u13b8\u13c4\u03e8\u13d2\u13d7\u13f3rrow\u0180;BD\u1150\u13a0\u13a4ar;\u6912ownArrow;\u61c5ownArrow;\u6195quilibrium;\u696eee\u0100;A\u13cb\u13cc\u62a5rrow;\u61a5own\xe1\u03f3er\u0100LR\u13de\u13e8eftArrow;\u6196ightArrow;\u6197i\u0100;l\u13f9\u13fa\u43d2on;\u43a5ing;\u416ecr;\uc000\ud835\udcb0ilde;\u4168ml\u803b\xdc\u40dc\u0480Dbcdefosv\u1427\u142c\u1430\u1433\u143e\u1485\u148a\u1490\u1496ash;\u62abar;\u6aeby;\u4412ash\u0100;l\u143b\u143c\u62a9;\u6ae6\u0100er\u1443\u1445;\u62c1\u0180bty\u144c\u1450\u147aar;\u6016\u0100;i\u144f\u1455cal\u0200BLST\u1461\u1465\u146a\u1474ar;\u6223ine;\u407ceparator;\u6758ilde;\u6240ThinSpace;\u600ar;\uc000\ud835\udd19pf;\uc000\ud835\udd4dcr;\uc000\ud835\udcb1dash;\u62aa\u0280cefos\u14a7\u14ac\u14b1\u14b6\u14bcirc;\u4174dge;\u62c0r;\uc000\ud835\udd1apf;\uc000\ud835\udd4ecr;\uc000\ud835\udcb2\u0200fios\u14cb\u14d0\u14d2\u14d8r;\uc000\ud835\udd1b;\u439epf;\uc000\ud835\udd4fcr;\uc000\ud835\udcb3\u0480AIUacfosu\u14f1\u14f5\u14f9\u14fd\u1504\u150f\u1514\u151a\u1520cy;\u442fcy;\u4407cy;\u442ecute\u803b\xdd\u40dd\u0100iy\u1509\u150drc;\u4176;\u442br;\uc000\ud835\udd1cpf;\uc000\ud835\udd50cr;\uc000\ud835\udcb4ml;\u4178\u0400Hacdefos\u1535\u1539\u153f\u154b\u154f\u155d\u1560\u1564cy;\u4416cute;\u4179\u0100ay\u1544\u1549ron;\u417d;\u4417ot;\u417b\u01f2\u1554\0\u155boWidt\xe8\u0ad9a;\u4396r;\u6128pf;\u6124cr;\uc000\ud835\udcb5\u0be1\u1583\u158a\u1590\0\u15b0\u15b6\u15bf\0\0\0\0\u15c6\u15db\u15eb\u165f\u166d\0\u1695\u169b\u16b2\u16b9\0\u16becute\u803b\xe1\u40e1reve;\u4103\u0300;Ediuy\u159c\u159d\u15a1\u15a3\u15a8\u15ad\u623e;\uc000\u223e\u0333;\u623frc\u803b\xe2\u40e2te\u80bb\xb4\u0306;\u4430lig\u803b\xe6\u40e6\u0100;r\xb2\u15ba;\uc000\ud835\udd1erave\u803b\xe0\u40e0\u0100ep\u15ca\u15d6\u0100fp\u15cf\u15d4sym;\u6135\xe8\u15d3ha;\u43b1\u0100ap\u15dfc\u0100cl\u15e4\u15e7r;\u4101g;\u6a3f\u0264\u15f0\0\0\u160a\u0280;adsv\u15fa\u15fb\u15ff\u1601\u1607\u6227nd;\u6a55;\u6a5clope;\u6a58;\u6a5a\u0380;elmrsz\u1618\u1619\u161b\u161e\u163f\u164f\u1659\u6220;\u69a4e\xbb\u1619sd\u0100;a\u1625\u1626\u6221\u0461\u1630\u1632\u1634\u1636\u1638\u163a\u163c\u163e;\u69a8;\u69a9;\u69aa;\u69ab;\u69ac;\u69ad;\u69ae;\u69aft\u0100;v\u1645\u1646\u621fb\u0100;d\u164c\u164d\u62be;\u699d\u0100pt\u1654\u1657h;\u6222\xbb\xb9arr;\u637c\u0100gp\u1663\u1667on;\u4105f;\uc000\ud835\udd52\u0380;Eaeiop\u12c1\u167b\u167d\u1682\u1684\u1687\u168a;\u6a70cir;\u6a6f;\u624ad;\u624bs;\u4027rox\u0100;e\u12c1\u1692\xf1\u1683ing\u803b\xe5\u40e5\u0180cty\u16a1\u16a6\u16a8r;\uc000\ud835\udcb6;\u402amp\u0100;e\u12c1\u16af\xf1\u0288ilde\u803b\xe3\u40e3ml\u803b\xe4\u40e4\u0100ci\u16c2\u16c8onin\xf4\u0272nt;\u6a11\u0800Nabcdefiklnoprsu\u16ed\u16f1\u1730\u173c\u1743\u1748\u1778\u177d\u17e0\u17e6\u1839\u1850\u170d\u193d\u1948\u1970ot;\u6aed\u0100cr\u16f6\u171ek\u0200ceps\u1700\u1705\u170d\u1713ong;\u624cpsilon;\u43f6rime;\u6035im\u0100;e\u171a\u171b\u623dq;\u62cd\u0176\u1722\u1726ee;\u62bded\u0100;g\u172c\u172d\u6305e\xbb\u172drk\u0100;t\u135c\u1737brk;\u63b6\u0100oy\u1701\u1741;\u4431quo;\u601e\u0280cmprt\u1753\u175b\u1761\u1764\u1768aus\u0100;e\u010a\u0109ptyv;\u69b0s\xe9\u170cno\xf5\u0113\u0180ahw\u176f\u1771\u1773;\u43b2;\u6136een;\u626cr;\uc000\ud835\udd1fg\u0380costuvw\u178d\u179d\u17b3\u17c1\u17d5\u17db\u17de\u0180aiu\u1794\u1796\u179a\xf0\u0760rc;\u65efp\xbb\u1371\u0180dpt\u17a4\u17a8\u17adot;\u6a00lus;\u6a01imes;\u6a02\u0271\u17b9\0\0\u17becup;\u6a06ar;\u6605riangle\u0100du\u17cd\u17d2own;\u65bdp;\u65b3plus;\u6a04e\xe5\u1444\xe5\u14adarow;\u690d\u0180ako\u17ed\u1826\u1835\u0100cn\u17f2\u1823k\u0180lst\u17fa\u05ab\u1802ozenge;\u69ebriangle\u0200;dlr\u1812\u1813\u1818\u181d\u65b4own;\u65beeft;\u65c2ight;\u65b8k;\u6423\u01b1\u182b\0\u1833\u01b2\u182f\0\u1831;\u6592;\u65914;\u6593ck;\u6588\u0100eo\u183e\u184d\u0100;q\u1843\u1846\uc000=\u20e5uiv;\uc000\u2261\u20e5t;\u6310\u0200ptwx\u1859\u185e\u1867\u186cf;\uc000\ud835\udd53\u0100;t\u13cb\u1863om\xbb\u13cctie;\u62c8\u0600DHUVbdhmptuv\u1885\u1896\u18aa\u18bb\u18d7\u18db\u18ec\u18ff\u1905\u190a\u1910\u1921\u0200LRlr\u188e\u1890\u1892\u1894;\u6557;\u6554;\u6556;\u6553\u0280;DUdu\u18a1\u18a2\u18a4\u18a6\u18a8\u6550;\u6566;\u6569;\u6564;\u6567\u0200LRlr\u18b3\u18b5\u18b7\u18b9;\u655d;\u655a;\u655c;\u6559\u0380;HLRhlr\u18ca\u18cb\u18cd\u18cf\u18d1\u18d3\u18d5\u6551;\u656c;\u6563;\u6560;\u656b;\u6562;\u655fox;\u69c9\u0200LRlr\u18e4\u18e6\u18e8\u18ea;\u6555;\u6552;\u6510;\u650c\u0280;DUdu\u06bd\u18f7\u18f9\u18fb\u18fd;\u6565;\u6568;\u652c;\u6534inus;\u629flus;\u629eimes;\u62a0\u0200LRlr\u1919\u191b\u191d\u191f;\u655b;\u6558;\u6518;\u6514\u0380;HLRhlr\u1930\u1931\u1933\u1935\u1937\u1939\u193b\u6502;\u656a;\u6561;\u655e;\u653c;\u6524;\u651c\u0100ev\u0123\u1942bar\u803b\xa6\u40a6\u0200ceio\u1951\u1956\u195a\u1960r;\uc000\ud835\udcb7mi;\u604fm\u0100;e\u171a\u171cl\u0180;bh\u1968\u1969\u196b\u405c;\u69c5sub;\u67c8\u016c\u1974\u197el\u0100;e\u1979\u197a\u6022t\xbb\u197ap\u0180;Ee\u012f\u1985\u1987;\u6aae\u0100;q\u06dc\u06db\u0ce1\u19a7\0\u19e8\u1a11\u1a15\u1a32\0\u1a37\u1a50\0\0\u1ab4\0\0\u1ac1\0\0\u1b21\u1b2e\u1b4d\u1b52\0\u1bfd\0\u1c0c\u0180cpr\u19ad\u19b2\u19ddute;\u4107\u0300;abcds\u19bf\u19c0\u19c4\u19ca\u19d5\u19d9\u6229nd;\u6a44rcup;\u6a49\u0100au\u19cf\u19d2p;\u6a4bp;\u6a47ot;\u6a40;\uc000\u2229\ufe00\u0100eo\u19e2\u19e5t;\u6041\xee\u0693\u0200aeiu\u19f0\u19fb\u1a01\u1a05\u01f0\u19f5\0\u19f8s;\u6a4don;\u410ddil\u803b\xe7\u40e7rc;\u4109ps\u0100;s\u1a0c\u1a0d\u6a4cm;\u6a50ot;\u410b\u0180dmn\u1a1b\u1a20\u1a26il\u80bb\xb8\u01adptyv;\u69b2t\u8100\xa2;e\u1a2d\u1a2e\u40a2r\xe4\u01b2r;\uc000\ud835\udd20\u0180cei\u1a3d\u1a40\u1a4dy;\u4447ck\u0100;m\u1a47\u1a48\u6713ark\xbb\u1a48;\u43c7r\u0380;Ecefms\u1a5f\u1a60\u1a62\u1a6b\u1aa4\u1aaa\u1aae\u65cb;\u69c3\u0180;el\u1a69\u1a6a\u1a6d\u42c6q;\u6257e\u0261\u1a74\0\0\u1a88rrow\u0100lr\u1a7c\u1a81eft;\u61baight;\u61bb\u0280RSacd\u1a92\u1a94\u1a96\u1a9a\u1a9f\xbb\u0f47;\u64c8st;\u629birc;\u629aash;\u629dnint;\u6a10id;\u6aefcir;\u69c2ubs\u0100;u\u1abb\u1abc\u6663it\xbb\u1abc\u02ec\u1ac7\u1ad4\u1afa\0\u1b0aon\u0100;e\u1acd\u1ace\u403a\u0100;q\xc7\xc6\u026d\u1ad9\0\0\u1ae2a\u0100;t\u1ade\u1adf\u402c;\u4040\u0180;fl\u1ae8\u1ae9\u1aeb\u6201\xee\u1160e\u0100mx\u1af1\u1af6ent\xbb\u1ae9e\xf3\u024d\u01e7\u1afe\0\u1b07\u0100;d\u12bb\u1b02ot;\u6a6dn\xf4\u0246\u0180fry\u1b10\u1b14\u1b17;\uc000\ud835\udd54o\xe4\u0254\u8100\xa9;s\u0155\u1b1dr;\u6117\u0100ao\u1b25\u1b29rr;\u61b5ss;\u6717\u0100cu\u1b32\u1b37r;\uc000\ud835\udcb8\u0100bp\u1b3c\u1b44\u0100;e\u1b41\u1b42\u6acf;\u6ad1\u0100;e\u1b49\u1b4a\u6ad0;\u6ad2dot;\u62ef\u0380delprvw\u1b60\u1b6c\u1b77\u1b82\u1bac\u1bd4\u1bf9arr\u0100lr\u1b68\u1b6a;\u6938;\u6935\u0270\u1b72\0\0\u1b75r;\u62dec;\u62dfarr\u0100;p\u1b7f\u1b80\u61b6;\u693d\u0300;bcdos\u1b8f\u1b90\u1b96\u1ba1\u1ba5\u1ba8\u622arcap;\u6a48\u0100au\u1b9b\u1b9ep;\u6a46p;\u6a4aot;\u628dr;\u6a45;\uc000\u222a\ufe00\u0200alrv\u1bb5\u1bbf\u1bde\u1be3rr\u0100;m\u1bbc\u1bbd\u61b7;\u693cy\u0180evw\u1bc7\u1bd4\u1bd8q\u0270\u1bce\0\0\u1bd2re\xe3\u1b73u\xe3\u1b75ee;\u62ceedge;\u62cfen\u803b\xa4\u40a4earrow\u0100lr\u1bee\u1bf3eft\xbb\u1b80ight\xbb\u1bbde\xe4\u1bdd\u0100ci\u1c01\u1c07onin\xf4\u01f7nt;\u6231lcty;\u632d\u0980AHabcdefhijlorstuwz\u1c38\u1c3b\u1c3f\u1c5d\u1c69\u1c75\u1c8a\u1c9e\u1cac\u1cb7\u1cfb\u1cff\u1d0d\u1d7b\u1d91\u1dab\u1dbb\u1dc6\u1dcdr\xf2\u0381ar;\u6965\u0200glrs\u1c48\u1c4d\u1c52\u1c54ger;\u6020eth;\u6138\xf2\u1133h\u0100;v\u1c5a\u1c5b\u6010\xbb\u090a\u016b\u1c61\u1c67arow;\u690fa\xe3\u0315\u0100ay\u1c6e\u1c73ron;\u410f;\u4434\u0180;ao\u0332\u1c7c\u1c84\u0100gr\u02bf\u1c81r;\u61catseq;\u6a77\u0180glm\u1c91\u1c94\u1c98\u803b\xb0\u40b0ta;\u43b4ptyv;\u69b1\u0100ir\u1ca3\u1ca8sht;\u697f;\uc000\ud835\udd21ar\u0100lr\u1cb3\u1cb5\xbb\u08dc\xbb\u101e\u0280aegsv\u1cc2\u0378\u1cd6\u1cdc\u1ce0m\u0180;os\u0326\u1cca\u1cd4nd\u0100;s\u0326\u1cd1uit;\u6666amma;\u43ddin;\u62f2\u0180;io\u1ce7\u1ce8\u1cf8\u40f7de\u8100\xf7;o\u1ce7\u1cf0ntimes;\u62c7n\xf8\u1cf7cy;\u4452c\u026f\u1d06\0\0\u1d0arn;\u631eop;\u630d\u0280lptuw\u1d18\u1d1d\u1d22\u1d49\u1d55lar;\u4024f;\uc000\ud835\udd55\u0280;emps\u030b\u1d2d\u1d37\u1d3d\u1d42q\u0100;d\u0352\u1d33ot;\u6251inus;\u6238lus;\u6214quare;\u62a1blebarwedg\xe5\xfan\u0180adh\u112e\u1d5d\u1d67ownarrow\xf3\u1c83arpoon\u0100lr\u1d72\u1d76ef\xf4\u1cb4igh\xf4\u1cb6\u0162\u1d7f\u1d85karo\xf7\u0f42\u026f\u1d8a\0\0\u1d8ern;\u631fop;\u630c\u0180cot\u1d98\u1da3\u1da6\u0100ry\u1d9d\u1da1;\uc000\ud835\udcb9;\u4455l;\u69f6rok;\u4111\u0100dr\u1db0\u1db4ot;\u62f1i\u0100;f\u1dba\u1816\u65bf\u0100ah\u1dc0\u1dc3r\xf2\u0429a\xf2\u0fa6angle;\u69a6\u0100ci\u1dd2\u1dd5y;\u445fgrarr;\u67ff\u0900Dacdefglmnopqrstux\u1e01\u1e09\u1e19\u1e38\u0578\u1e3c\u1e49\u1e61\u1e7e\u1ea5\u1eaf\u1ebd\u1ee1\u1f2a\u1f37\u1f44\u1f4e\u1f5a\u0100Do\u1e06\u1d34o\xf4\u1c89\u0100cs\u1e0e\u1e14ute\u803b\xe9\u40e9ter;\u6a6e\u0200aioy\u1e22\u1e27\u1e31\u1e36ron;\u411br\u0100;c\u1e2d\u1e2e\u6256\u803b\xea\u40ealon;\u6255;\u444dot;\u4117\u0100Dr\u1e41\u1e45ot;\u6252;\uc000\ud835\udd22\u0180;rs\u1e50\u1e51\u1e57\u6a9aave\u803b\xe8\u40e8\u0100;d\u1e5c\u1e5d\u6a96ot;\u6a98\u0200;ils\u1e6a\u1e6b\u1e72\u1e74\u6a99nters;\u63e7;\u6113\u0100;d\u1e79\u1e7a\u6a95ot;\u6a97\u0180aps\u1e85\u1e89\u1e97cr;\u4113ty\u0180;sv\u1e92\u1e93\u1e95\u6205et\xbb\u1e93p\u01001;\u1e9d\u1ea4\u0133\u1ea1\u1ea3;\u6004;\u6005\u6003\u0100gs\u1eaa\u1eac;\u414bp;\u6002\u0100gp\u1eb4\u1eb8on;\u4119f;\uc000\ud835\udd56\u0180als\u1ec4\u1ece\u1ed2r\u0100;s\u1eca\u1ecb\u62d5l;\u69e3us;\u6a71i\u0180;lv\u1eda\u1edb\u1edf\u43b5on\xbb\u1edb;\u43f5\u0200csuv\u1eea\u1ef3\u1f0b\u1f23\u0100io\u1eef\u1e31rc\xbb\u1e2e\u0269\u1ef9\0\0\u1efb\xed\u0548ant\u0100gl\u1f02\u1f06tr\xbb\u1e5dess\xbb\u1e7a\u0180aei\u1f12\u1f16\u1f1als;\u403dst;\u625fv\u0100;D\u0235\u1f20D;\u6a78parsl;\u69e5\u0100Da\u1f2f\u1f33ot;\u6253rr;\u6971\u0180cdi\u1f3e\u1f41\u1ef8r;\u612fo\xf4\u0352\u0100ah\u1f49\u1f4b;\u43b7\u803b\xf0\u40f0\u0100mr\u1f53\u1f57l\u803b\xeb\u40ebo;\u60ac\u0180cip\u1f61\u1f64\u1f67l;\u4021s\xf4\u056e\u0100eo\u1f6c\u1f74ctatio\xee\u0559nential\xe5\u0579\u09e1\u1f92\0\u1f9e\0\u1fa1\u1fa7\0\0\u1fc6\u1fcc\0\u1fd3\0\u1fe6\u1fea\u2000\0\u2008\u205allingdotse\xf1\u1e44y;\u4444male;\u6640\u0180ilr\u1fad\u1fb3\u1fc1lig;\u8000\ufb03\u0269\u1fb9\0\0\u1fbdg;\u8000\ufb00ig;\u8000\ufb04;\uc000\ud835\udd23lig;\u8000\ufb01lig;\uc000fj\u0180alt\u1fd9\u1fdc\u1fe1t;\u666dig;\u8000\ufb02ns;\u65b1of;\u4192\u01f0\u1fee\0\u1ff3f;\uc000\ud835\udd57\u0100ak\u05bf\u1ff7\u0100;v\u1ffc\u1ffd\u62d4;\u6ad9artint;\u6a0d\u0100ao\u200c\u2055\u0100cs\u2011\u2052\u03b1\u201a\u2030\u2038\u2045\u2048\0\u2050\u03b2\u2022\u2025\u2027\u202a\u202c\0\u202e\u803b\xbd\u40bd;\u6153\u803b\xbc\u40bc;\u6155;\u6159;\u615b\u01b3\u2034\0\u2036;\u6154;\u6156\u02b4\u203e\u2041\0\0\u2043\u803b\xbe\u40be;\u6157;\u615c5;\u6158\u01b6\u204c\0\u204e;\u615a;\u615d8;\u615el;\u6044wn;\u6322cr;\uc000\ud835\udcbb\u0880Eabcdefgijlnorstv\u2082\u2089\u209f\u20a5\u20b0\u20b4\u20f0\u20f5\u20fa\u20ff\u2103\u2112\u2138\u0317\u213e\u2152\u219e\u0100;l\u064d\u2087;\u6a8c\u0180cmp\u2090\u2095\u209dute;\u41f5ma\u0100;d\u209c\u1cda\u43b3;\u6a86reve;\u411f\u0100iy\u20aa\u20aerc;\u411d;\u4433ot;\u4121\u0200;lqs\u063e\u0642\u20bd\u20c9\u0180;qs\u063e\u064c\u20c4lan\xf4\u0665\u0200;cdl\u0665\u20d2\u20d5\u20e5c;\u6aa9ot\u0100;o\u20dc\u20dd\u6a80\u0100;l\u20e2\u20e3\u6a82;\u6a84\u0100;e\u20ea\u20ed\uc000\u22db\ufe00s;\u6a94r;\uc000\ud835\udd24\u0100;g\u0673\u061bmel;\u6137cy;\u4453\u0200;Eaj\u065a\u210c\u210e\u2110;\u6a92;\u6aa5;\u6aa4\u0200Eaes\u211b\u211d\u2129\u2134;\u6269p\u0100;p\u2123\u2124\u6a8arox\xbb\u2124\u0100;q\u212e\u212f\u6a88\u0100;q\u212e\u211bim;\u62e7pf;\uc000\ud835\udd58\u0100ci\u2143\u2146r;\u610am\u0180;el\u066b\u214e\u2150;\u6a8e;\u6a90\u8300>;cdlqr\u05ee\u2160\u216a\u216e\u2173\u2179\u0100ci\u2165\u2167;\u6aa7r;\u6a7aot;\u62d7Par;\u6995uest;\u6a7c\u0280adels\u2184\u216a\u2190\u0656\u219b\u01f0\u2189\0\u218epro\xf8\u209er;\u6978q\u0100lq\u063f\u2196les\xf3\u2088i\xed\u066b\u0100en\u21a3\u21adrtneqq;\uc000\u2269\ufe00\xc5\u21aa\u0500Aabcefkosy\u21c4\u21c7\u21f1\u21f5\u21fa\u2218\u221d\u222f\u2268\u227dr\xf2\u03a0\u0200ilmr\u21d0\u21d4\u21d7\u21dbrs\xf0\u1484f\xbb\u2024il\xf4\u06a9\u0100dr\u21e0\u21e4cy;\u444a\u0180;cw\u08f4\u21eb\u21efir;\u6948;\u61adar;\u610firc;\u4125\u0180alr\u2201\u220e\u2213rts\u0100;u\u2209\u220a\u6665it\xbb\u220alip;\u6026con;\u62b9r;\uc000\ud835\udd25s\u0100ew\u2223\u2229arow;\u6925arow;\u6926\u0280amopr\u223a\u223e\u2243\u225e\u2263rr;\u61fftht;\u623bk\u0100lr\u2249\u2253eftarrow;\u61a9ightarrow;\u61aaf;\uc000\ud835\udd59bar;\u6015\u0180clt\u226f\u2274\u2278r;\uc000\ud835\udcbdas\xe8\u21f4rok;\u4127\u0100bp\u2282\u2287ull;\u6043hen\xbb\u1c5b\u0ae1\u22a3\0\u22aa\0\u22b8\u22c5\u22ce\0\u22d5\u22f3\0\0\u22f8\u2322\u2367\u2362\u237f\0\u2386\u23aa\u23b4cute\u803b\xed\u40ed\u0180;iy\u0771\u22b0\u22b5rc\u803b\xee\u40ee;\u4438\u0100cx\u22bc\u22bfy;\u4435cl\u803b\xa1\u40a1\u0100fr\u039f\u22c9;\uc000\ud835\udd26rave\u803b\xec\u40ec\u0200;ino\u073e\u22dd\u22e9\u22ee\u0100in\u22e2\u22e6nt;\u6a0ct;\u622dfin;\u69dcta;\u6129lig;\u4133\u0180aop\u22fe\u231a\u231d\u0180cgt\u2305\u2308\u2317r;\u412b\u0180elp\u071f\u230f\u2313in\xe5\u078ear\xf4\u0720h;\u4131f;\u62b7ed;\u41b5\u0280;cfot\u04f4\u232c\u2331\u233d\u2341are;\u6105in\u0100;t\u2338\u2339\u621eie;\u69dddo\xf4\u2319\u0280;celp\u0757\u234c\u2350\u235b\u2361al;\u62ba\u0100gr\u2355\u2359er\xf3\u1563\xe3\u234darhk;\u6a17rod;\u6a3c\u0200cgpt\u236f\u2372\u2376\u237by;\u4451on;\u412ff;\uc000\ud835\udd5aa;\u43b9uest\u803b\xbf\u40bf\u0100ci\u238a\u238fr;\uc000\ud835\udcben\u0280;Edsv\u04f4\u239b\u239d\u23a1\u04f3;\u62f9ot;\u62f5\u0100;v\u23a6\u23a7\u62f4;\u62f3\u0100;i\u0777\u23aelde;\u4129\u01eb\u23b8\0\u23bccy;\u4456l\u803b\xef\u40ef\u0300cfmosu\u23cc\u23d7\u23dc\u23e1\u23e7\u23f5\u0100iy\u23d1\u23d5rc;\u4135;\u4439r;\uc000\ud835\udd27ath;\u4237pf;\uc000\ud835\udd5b\u01e3\u23ec\0\u23f1r;\uc000\ud835\udcbfrcy;\u4458kcy;\u4454\u0400acfghjos\u240b\u2416\u2422\u2427\u242d\u2431\u2435\u243bppa\u0100;v\u2413\u2414\u43ba;\u43f0\u0100ey\u241b\u2420dil;\u4137;\u443ar;\uc000\ud835\udd28reen;\u4138cy;\u4445cy;\u445cpf;\uc000\ud835\udd5ccr;\uc000\ud835\udcc0\u0b80ABEHabcdefghjlmnoprstuv\u2470\u2481\u2486\u248d\u2491\u250e\u253d\u255a\u2580\u264e\u265e\u2665\u2679\u267d\u269a\u26b2\u26d8\u275d\u2768\u278b\u27c0\u2801\u2812\u0180art\u2477\u247a\u247cr\xf2\u09c6\xf2\u0395ail;\u691barr;\u690e\u0100;g\u0994\u248b;\u6a8bar;\u6962\u0963\u24a5\0\u24aa\0\u24b1\0\0\0\0\0\u24b5\u24ba\0\u24c6\u24c8\u24cd\0\u24f9ute;\u413amptyv;\u69b4ra\xee\u084cbda;\u43bbg\u0180;dl\u088e\u24c1\u24c3;\u6991\xe5\u088e;\u6a85uo\u803b\xab\u40abr\u0400;bfhlpst\u0899\u24de\u24e6\u24e9\u24eb\u24ee\u24f1\u24f5\u0100;f\u089d\u24e3s;\u691fs;\u691d\xeb\u2252p;\u61abl;\u6939im;\u6973l;\u61a2\u0180;ae\u24ff\u2500\u2504\u6aabil;\u6919\u0100;s\u2509\u250a\u6aad;\uc000\u2aad\ufe00\u0180abr\u2515\u2519\u251drr;\u690crk;\u6772\u0100ak\u2522\u252cc\u0100ek\u2528\u252a;\u407b;\u405b\u0100es\u2531\u2533;\u698bl\u0100du\u2539\u253b;\u698f;\u698d\u0200aeuy\u2546\u254b\u2556\u2558ron;\u413e\u0100di\u2550\u2554il;\u413c\xec\u08b0\xe2\u2529;\u443b\u0200cqrs\u2563\u2566\u256d\u257da;\u6936uo\u0100;r\u0e19\u1746\u0100du\u2572\u2577har;\u6967shar;\u694bh;\u61b2\u0280;fgqs\u258b\u258c\u0989\u25f3\u25ff\u6264t\u0280ahlrt\u2598\u25a4\u25b7\u25c2\u25e8rrow\u0100;t\u0899\u25a1a\xe9\u24f6arpoon\u0100du\u25af\u25b4own\xbb\u045ap\xbb\u0966eftarrows;\u61c7ight\u0180ahs\u25cd\u25d6\u25derrow\u0100;s\u08f4\u08a7arpoon\xf3\u0f98quigarro\xf7\u21f0hreetimes;\u62cb\u0180;qs\u258b\u0993\u25falan\xf4\u09ac\u0280;cdgs\u09ac\u260a\u260d\u261d\u2628c;\u6aa8ot\u0100;o\u2614\u2615\u6a7f\u0100;r\u261a\u261b\u6a81;\u6a83\u0100;e\u2622\u2625\uc000\u22da\ufe00s;\u6a93\u0280adegs\u2633\u2639\u263d\u2649\u264bppro\xf8\u24c6ot;\u62d6q\u0100gq\u2643\u2645\xf4\u0989gt\xf2\u248c\xf4\u099bi\xed\u09b2\u0180ilr\u2655\u08e1\u265asht;\u697c;\uc000\ud835\udd29\u0100;E\u099c\u2663;\u6a91\u0161\u2669\u2676r\u0100du\u25b2\u266e\u0100;l\u0965\u2673;\u696alk;\u6584cy;\u4459\u0280;acht\u0a48\u2688\u268b\u2691\u2696r\xf2\u25c1orne\xf2\u1d08ard;\u696bri;\u65fa\u0100io\u269f\u26a4dot;\u4140ust\u0100;a\u26ac\u26ad\u63b0che\xbb\u26ad\u0200Eaes\u26bb\u26bd\u26c9\u26d4;\u6268p\u0100;p\u26c3\u26c4\u6a89rox\xbb\u26c4\u0100;q\u26ce\u26cf\u6a87\u0100;q\u26ce\u26bbim;\u62e6\u0400abnoptwz\u26e9\u26f4\u26f7\u271a\u272f\u2741\u2747\u2750\u0100nr\u26ee\u26f1g;\u67ecr;\u61fdr\xeb\u08c1g\u0180lmr\u26ff\u270d\u2714eft\u0100ar\u09e6\u2707ight\xe1\u09f2apsto;\u67fcight\xe1\u09fdparrow\u0100lr\u2725\u2729ef\xf4\u24edight;\u61ac\u0180afl\u2736\u2739\u273dr;\u6985;\uc000\ud835\udd5dus;\u6a2dimes;\u6a34\u0161\u274b\u274fst;\u6217\xe1\u134e\u0180;ef\u2757\u2758\u1800\u65cange\xbb\u2758ar\u0100;l\u2764\u2765\u4028t;\u6993\u0280achmt\u2773\u2776\u277c\u2785\u2787r\xf2\u08a8orne\xf2\u1d8car\u0100;d\u0f98\u2783;\u696d;\u600eri;\u62bf\u0300achiqt\u2798\u279d\u0a40\u27a2\u27ae\u27bbquo;\u6039r;\uc000\ud835\udcc1m\u0180;eg\u09b2\u27aa\u27ac;\u6a8d;\u6a8f\u0100bu\u252a\u27b3o\u0100;r\u0e1f\u27b9;\u601arok;\u4142\u8400<;cdhilqr\u082b\u27d2\u2639\u27dc\u27e0\u27e5\u27ea\u27f0\u0100ci\u27d7\u27d9;\u6aa6r;\u6a79re\xe5\u25f2mes;\u62c9arr;\u6976uest;\u6a7b\u0100Pi\u27f5\u27f9ar;\u6996\u0180;ef\u2800\u092d\u181b\u65c3r\u0100du\u2807\u280dshar;\u694ahar;\u6966\u0100en\u2817\u2821rtneqq;\uc000\u2268\ufe00\xc5\u281e\u0700Dacdefhilnopsu\u2840\u2845\u2882\u288e\u2893\u28a0\u28a5\u28a8\u28da\u28e2\u28e4\u0a83\u28f3\u2902Dot;\u623a\u0200clpr\u284e\u2852\u2863\u287dr\u803b\xaf\u40af\u0100et\u2857\u2859;\u6642\u0100;e\u285e\u285f\u6720se\xbb\u285f\u0100;s\u103b\u2868to\u0200;dlu\u103b\u2873\u2877\u287bow\xee\u048cef\xf4\u090f\xf0\u13d1ker;\u65ae\u0100oy\u2887\u288cmma;\u6a29;\u443cash;\u6014asuredangle\xbb\u1626r;\uc000\ud835\udd2ao;\u6127\u0180cdn\u28af\u28b4\u28c9ro\u803b\xb5\u40b5\u0200;acd\u1464\u28bd\u28c0\u28c4s\xf4\u16a7ir;\u6af0ot\u80bb\xb7\u01b5us\u0180;bd\u28d2\u1903\u28d3\u6212\u0100;u\u1d3c\u28d8;\u6a2a\u0163\u28de\u28e1p;\u6adb\xf2\u2212\xf0\u0a81\u0100dp\u28e9\u28eeels;\u62a7f;\uc000\ud835\udd5e\u0100ct\u28f8\u28fdr;\uc000\ud835\udcc2pos\xbb\u159d\u0180;lm\u2909\u290a\u290d\u43bctimap;\u62b8\u0c00GLRVabcdefghijlmoprstuvw\u2942\u2953\u297e\u2989\u2998\u29da\u29e9\u2a15\u2a1a\u2a58\u2a5d\u2a83\u2a95\u2aa4\u2aa8\u2b04\u2b07\u2b44\u2b7f\u2bae\u2c34\u2c67\u2c7c\u2ce9\u0100gt\u2947\u294b;\uc000\u22d9\u0338\u0100;v\u2950\u0bcf\uc000\u226b\u20d2\u0180elt\u295a\u2972\u2976ft\u0100ar\u2961\u2967rrow;\u61cdightarrow;\u61ce;\uc000\u22d8\u0338\u0100;v\u297b\u0c47\uc000\u226a\u20d2ightarrow;\u61cf\u0100Dd\u298e\u2993ash;\u62afash;\u62ae\u0280bcnpt\u29a3\u29a7\u29ac\u29b1\u29ccla\xbb\u02deute;\u4144g;\uc000\u2220\u20d2\u0280;Eiop\u0d84\u29bc\u29c0\u29c5\u29c8;\uc000\u2a70\u0338d;\uc000\u224b\u0338s;\u4149ro\xf8\u0d84ur\u0100;a\u29d3\u29d4\u666el\u0100;s\u29d3\u0b38\u01f3\u29df\0\u29e3p\u80bb\xa0\u0b37mp\u0100;e\u0bf9\u0c00\u0280aeouy\u29f4\u29fe\u2a03\u2a10\u2a13\u01f0\u29f9\0\u29fb;\u6a43on;\u4148dil;\u4146ng\u0100;d\u0d7e\u2a0aot;\uc000\u2a6d\u0338p;\u6a42;\u443dash;\u6013\u0380;Aadqsx\u0b92\u2a29\u2a2d\u2a3b\u2a41\u2a45\u2a50rr;\u61d7r\u0100hr\u2a33\u2a36k;\u6924\u0100;o\u13f2\u13f0ot;\uc000\u2250\u0338ui\xf6\u0b63\u0100ei\u2a4a\u2a4ear;\u6928\xed\u0b98ist\u0100;s\u0ba0\u0b9fr;\uc000\ud835\udd2b\u0200Eest\u0bc5\u2a66\u2a79\u2a7c\u0180;qs\u0bbc\u2a6d\u0be1\u0180;qs\u0bbc\u0bc5\u2a74lan\xf4\u0be2i\xed\u0bea\u0100;r\u0bb6\u2a81\xbb\u0bb7\u0180Aap\u2a8a\u2a8d\u2a91r\xf2\u2971rr;\u61aear;\u6af2\u0180;sv\u0f8d\u2a9c\u0f8c\u0100;d\u2aa1\u2aa2\u62fc;\u62facy;\u445a\u0380AEadest\u2ab7\u2aba\u2abe\u2ac2\u2ac5\u2af6\u2af9r\xf2\u2966;\uc000\u2266\u0338rr;\u619ar;\u6025\u0200;fqs\u0c3b\u2ace\u2ae3\u2aeft\u0100ar\u2ad4\u2ad9rro\xf7\u2ac1ightarro\xf7\u2a90\u0180;qs\u0c3b\u2aba\u2aealan\xf4\u0c55\u0100;s\u0c55\u2af4\xbb\u0c36i\xed\u0c5d\u0100;r\u0c35\u2afei\u0100;e\u0c1a\u0c25i\xe4\u0d90\u0100pt\u2b0c\u2b11f;\uc000\ud835\udd5f\u8180\xac;in\u2b19\u2b1a\u2b36\u40acn\u0200;Edv\u0b89\u2b24\u2b28\u2b2e;\uc000\u22f9\u0338ot;\uc000\u22f5\u0338\u01e1\u0b89\u2b33\u2b35;\u62f7;\u62f6i\u0100;v\u0cb8\u2b3c\u01e1\u0cb8\u2b41\u2b43;\u62fe;\u62fd\u0180aor\u2b4b\u2b63\u2b69r\u0200;ast\u0b7b\u2b55\u2b5a\u2b5flle\xec\u0b7bl;\uc000\u2afd\u20e5;\uc000\u2202\u0338lint;\u6a14\u0180;ce\u0c92\u2b70\u2b73u\xe5\u0ca5\u0100;c\u0c98\u2b78\u0100;e\u0c92\u2b7d\xf1\u0c98\u0200Aait\u2b88\u2b8b\u2b9d\u2ba7r\xf2\u2988rr\u0180;cw\u2b94\u2b95\u2b99\u619b;\uc000\u2933\u0338;\uc000\u219d\u0338ghtarrow\xbb\u2b95ri\u0100;e\u0ccb\u0cd6\u0380chimpqu\u2bbd\u2bcd\u2bd9\u2b04\u0b78\u2be4\u2bef\u0200;cer\u0d32\u2bc6\u0d37\u2bc9u\xe5\u0d45;\uc000\ud835\udcc3ort\u026d\u2b05\0\0\u2bd6ar\xe1\u2b56m\u0100;e\u0d6e\u2bdf\u0100;q\u0d74\u0d73su\u0100bp\u2beb\u2bed\xe5\u0cf8\xe5\u0d0b\u0180bcp\u2bf6\u2c11\u2c19\u0200;Ees\u2bff\u2c00\u0d22\u2c04\u6284;\uc000\u2ac5\u0338et\u0100;e\u0d1b\u2c0bq\u0100;q\u0d23\u2c00c\u0100;e\u0d32\u2c17\xf1\u0d38\u0200;Ees\u2c22\u2c23\u0d5f\u2c27\u6285;\uc000\u2ac6\u0338et\u0100;e\u0d58\u2c2eq\u0100;q\u0d60\u2c23\u0200gilr\u2c3d\u2c3f\u2c45\u2c47\xec\u0bd7lde\u803b\xf1\u40f1\xe7\u0c43iangle\u0100lr\u2c52\u2c5ceft\u0100;e\u0c1a\u2c5a\xf1\u0c26ight\u0100;e\u0ccb\u2c65\xf1\u0cd7\u0100;m\u2c6c\u2c6d\u43bd\u0180;es\u2c74\u2c75\u2c79\u4023ro;\u6116p;\u6007\u0480DHadgilrs\u2c8f\u2c94\u2c99\u2c9e\u2ca3\u2cb0\u2cb6\u2cd3\u2ce3ash;\u62adarr;\u6904p;\uc000\u224d\u20d2ash;\u62ac\u0100et\u2ca8\u2cac;\uc000\u2265\u20d2;\uc000>\u20d2nfin;\u69de\u0180Aet\u2cbd\u2cc1\u2cc5rr;\u6902;\uc000\u2264\u20d2\u0100;r\u2cca\u2ccd\uc000<\u20d2ie;\uc000\u22b4\u20d2\u0100At\u2cd8\u2cdcrr;\u6903rie;\uc000\u22b5\u20d2im;\uc000\u223c\u20d2\u0180Aan\u2cf0\u2cf4\u2d02rr;\u61d6r\u0100hr\u2cfa\u2cfdk;\u6923\u0100;o\u13e7\u13e5ear;\u6927\u1253\u1a95\0\0\0\0\0\0\0\0\0\0\0\0\0\u2d2d\0\u2d38\u2d48\u2d60\u2d65\u2d72\u2d84\u1b07\0\0\u2d8d\u2dab\0\u2dc8\u2dce\0\u2ddc\u2e19\u2e2b\u2e3e\u2e43\u0100cs\u2d31\u1a97ute\u803b\xf3\u40f3\u0100iy\u2d3c\u2d45r\u0100;c\u1a9e\u2d42\u803b\xf4\u40f4;\u443e\u0280abios\u1aa0\u2d52\u2d57\u01c8\u2d5alac;\u4151v;\u6a38old;\u69bclig;\u4153\u0100cr\u2d69\u2d6dir;\u69bf;\uc000\ud835\udd2c\u036f\u2d79\0\0\u2d7c\0\u2d82n;\u42dbave\u803b\xf2\u40f2;\u69c1\u0100bm\u2d88\u0df4ar;\u69b5\u0200acit\u2d95\u2d98\u2da5\u2da8r\xf2\u1a80\u0100ir\u2d9d\u2da0r;\u69beoss;\u69bbn\xe5\u0e52;\u69c0\u0180aei\u2db1\u2db5\u2db9cr;\u414dga;\u43c9\u0180cdn\u2dc0\u2dc5\u01cdron;\u43bf;\u69b6pf;\uc000\ud835\udd60\u0180ael\u2dd4\u2dd7\u01d2r;\u69b7rp;\u69b9\u0380;adiosv\u2dea\u2deb\u2dee\u2e08\u2e0d\u2e10\u2e16\u6228r\xf2\u1a86\u0200;efm\u2df7\u2df8\u2e02\u2e05\u6a5dr\u0100;o\u2dfe\u2dff\u6134f\xbb\u2dff\u803b\xaa\u40aa\u803b\xba\u40bagof;\u62b6r;\u6a56lope;\u6a57;\u6a5b\u0180clo\u2e1f\u2e21\u2e27\xf2\u2e01ash\u803b\xf8\u40f8l;\u6298i\u016c\u2e2f\u2e34de\u803b\xf5\u40f5es\u0100;a\u01db\u2e3as;\u6a36ml\u803b\xf6\u40f6bar;\u633d\u0ae1\u2e5e\0\u2e7d\0\u2e80\u2e9d\0\u2ea2\u2eb9\0\0\u2ecb\u0e9c\0\u2f13\0\0\u2f2b\u2fbc\0\u2fc8r\u0200;ast\u0403\u2e67\u2e72\u0e85\u8100\xb6;l\u2e6d\u2e6e\u40b6le\xec\u0403\u0269\u2e78\0\0\u2e7bm;\u6af3;\u6afdy;\u443fr\u0280cimpt\u2e8b\u2e8f\u2e93\u1865\u2e97nt;\u4025od;\u402eil;\u6030enk;\u6031r;\uc000\ud835\udd2d\u0180imo\u2ea8\u2eb0\u2eb4\u0100;v\u2ead\u2eae\u43c6;\u43d5ma\xf4\u0a76ne;\u660e\u0180;tv\u2ebf\u2ec0\u2ec8\u43c0chfork\xbb\u1ffd;\u43d6\u0100au\u2ecf\u2edfn\u0100ck\u2ed5\u2eddk\u0100;h\u21f4\u2edb;\u610e\xf6\u21f4s\u0480;abcdemst\u2ef3\u2ef4\u1908\u2ef9\u2efd\u2f04\u2f06\u2f0a\u2f0e\u402bcir;\u6a23ir;\u6a22\u0100ou\u1d40\u2f02;\u6a25;\u6a72n\u80bb\xb1\u0e9dim;\u6a26wo;\u6a27\u0180ipu\u2f19\u2f20\u2f25ntint;\u6a15f;\uc000\ud835\udd61nd\u803b\xa3\u40a3\u0500;Eaceinosu\u0ec8\u2f3f\u2f41\u2f44\u2f47\u2f81\u2f89\u2f92\u2f7e\u2fb6;\u6ab3p;\u6ab7u\xe5\u0ed9\u0100;c\u0ece\u2f4c\u0300;acens\u0ec8\u2f59\u2f5f\u2f66\u2f68\u2f7eppro\xf8\u2f43urlye\xf1\u0ed9\xf1\u0ece\u0180aes\u2f6f\u2f76\u2f7approx;\u6ab9qq;\u6ab5im;\u62e8i\xed\u0edfme\u0100;s\u2f88\u0eae\u6032\u0180Eas\u2f78\u2f90\u2f7a\xf0\u2f75\u0180dfp\u0eec\u2f99\u2faf\u0180als\u2fa0\u2fa5\u2faalar;\u632eine;\u6312urf;\u6313\u0100;t\u0efb\u2fb4\xef\u0efbrel;\u62b0\u0100ci\u2fc0\u2fc5r;\uc000\ud835\udcc5;\u43c8ncsp;\u6008\u0300fiopsu\u2fda\u22e2\u2fdf\u2fe5\u2feb\u2ff1r;\uc000\ud835\udd2epf;\uc000\ud835\udd62rime;\u6057cr;\uc000\ud835\udcc6\u0180aeo\u2ff8\u3009\u3013t\u0100ei\u2ffe\u3005rnion\xf3\u06b0nt;\u6a16st\u0100;e\u3010\u3011\u403f\xf1\u1f19\xf4\u0f14\u0a80ABHabcdefhilmnoprstux\u3040\u3051\u3055\u3059\u30e0\u310e\u312b\u3147\u3162\u3172\u318e\u3206\u3215\u3224\u3229\u3258\u326e\u3272\u3290\u32b0\u32b7\u0180art\u3047\u304a\u304cr\xf2\u10b3\xf2\u03ddail;\u691car\xf2\u1c65ar;\u6964\u0380cdenqrt\u3068\u3075\u3078\u307f\u308f\u3094\u30cc\u0100eu\u306d\u3071;\uc000\u223d\u0331te;\u4155i\xe3\u116emptyv;\u69b3g\u0200;del\u0fd1\u3089\u308b\u308d;\u6992;\u69a5\xe5\u0fd1uo\u803b\xbb\u40bbr\u0580;abcfhlpstw\u0fdc\u30ac\u30af\u30b7\u30b9\u30bc\u30be\u30c0\u30c3\u30c7\u30cap;\u6975\u0100;f\u0fe0\u30b4s;\u6920;\u6933s;\u691e\xeb\u225d\xf0\u272el;\u6945im;\u6974l;\u61a3;\u619d\u0100ai\u30d1\u30d5il;\u691ao\u0100;n\u30db\u30dc\u6236al\xf3\u0f1e\u0180abr\u30e7\u30ea\u30eer\xf2\u17e5rk;\u6773\u0100ak\u30f3\u30fdc\u0100ek\u30f9\u30fb;\u407d;\u405d\u0100es\u3102\u3104;\u698cl\u0100du\u310a\u310c;\u698e;\u6990\u0200aeuy\u3117\u311c\u3127\u3129ron;\u4159\u0100di\u3121\u3125il;\u4157\xec\u0ff2\xe2\u30fa;\u4440\u0200clqs\u3134\u3137\u313d\u3144a;\u6937dhar;\u6969uo\u0100;r\u020e\u020dh;\u61b3\u0180acg\u314e\u315f\u0f44l\u0200;ips\u0f78\u3158\u315b\u109cn\xe5\u10bbar\xf4\u0fa9t;\u65ad\u0180ilr\u3169\u1023\u316esht;\u697d;\uc000\ud835\udd2f\u0100ao\u3177\u3186r\u0100du\u317d\u317f\xbb\u047b\u0100;l\u1091\u3184;\u696c\u0100;v\u318b\u318c\u43c1;\u43f1\u0180gns\u3195\u31f9\u31fcht\u0300ahlrst\u31a4\u31b0\u31c2\u31d8\u31e4\u31eerrow\u0100;t\u0fdc\u31ada\xe9\u30c8arpoon\u0100du\u31bb\u31bfow\xee\u317ep\xbb\u1092eft\u0100ah\u31ca\u31d0rrow\xf3\u0feaarpoon\xf3\u0551ightarrows;\u61c9quigarro\xf7\u30cbhreetimes;\u62ccg;\u42daingdotse\xf1\u1f32\u0180ahm\u320d\u3210\u3213r\xf2\u0feaa\xf2\u0551;\u600foust\u0100;a\u321e\u321f\u63b1che\xbb\u321fmid;\u6aee\u0200abpt\u3232\u323d\u3240\u3252\u0100nr\u3237\u323ag;\u67edr;\u61fer\xeb\u1003\u0180afl\u3247\u324a\u324er;\u6986;\uc000\ud835\udd63us;\u6a2eimes;\u6a35\u0100ap\u325d\u3267r\u0100;g\u3263\u3264\u4029t;\u6994olint;\u6a12ar\xf2\u31e3\u0200achq\u327b\u3280\u10bc\u3285quo;\u603ar;\uc000\ud835\udcc7\u0100bu\u30fb\u328ao\u0100;r\u0214\u0213\u0180hir\u3297\u329b\u32a0re\xe5\u31f8mes;\u62cai\u0200;efl\u32aa\u1059\u1821\u32ab\u65b9tri;\u69celuhar;\u6968;\u611e\u0d61\u32d5\u32db\u32df\u332c\u3338\u3371\0\u337a\u33a4\0\0\u33ec\u33f0\0\u3428\u3448\u345a\u34ad\u34b1\u34ca\u34f1\0\u3616\0\0\u3633cute;\u415bqu\xef\u27ba\u0500;Eaceinpsy\u11ed\u32f3\u32f5\u32ff\u3302\u330b\u330f\u331f\u3326\u3329;\u6ab4\u01f0\u32fa\0\u32fc;\u6ab8on;\u4161u\xe5\u11fe\u0100;d\u11f3\u3307il;\u415frc;\u415d\u0180Eas\u3316\u3318\u331b;\u6ab6p;\u6abaim;\u62e9olint;\u6a13i\xed\u1204;\u4441ot\u0180;be\u3334\u1d47\u3335\u62c5;\u6a66\u0380Aacmstx\u3346\u334a\u3357\u335b\u335e\u3363\u336drr;\u61d8r\u0100hr\u3350\u3352\xeb\u2228\u0100;o\u0a36\u0a34t\u803b\xa7\u40a7i;\u403bwar;\u6929m\u0100in\u3369\xf0nu\xf3\xf1t;\u6736r\u0100;o\u3376\u2055\uc000\ud835\udd30\u0200acoy\u3382\u3386\u3391\u33a0rp;\u666f\u0100hy\u338b\u338fcy;\u4449;\u4448rt\u026d\u3399\0\0\u339ci\xe4\u1464ara\xec\u2e6f\u803b\xad\u40ad\u0100gm\u33a8\u33b4ma\u0180;fv\u33b1\u33b2\u33b2\u43c3;\u43c2\u0400;deglnpr\u12ab\u33c5\u33c9\u33ce\u33d6\u33de\u33e1\u33e6ot;\u6a6a\u0100;q\u12b1\u12b0\u0100;E\u33d3\u33d4\u6a9e;\u6aa0\u0100;E\u33db\u33dc\u6a9d;\u6a9fe;\u6246lus;\u6a24arr;\u6972ar\xf2\u113d\u0200aeit\u33f8\u3408\u340f\u3417\u0100ls\u33fd\u3404lsetm\xe9\u336ahp;\u6a33parsl;\u69e4\u0100dl\u1463\u3414e;\u6323\u0100;e\u341c\u341d\u6aaa\u0100;s\u3422\u3423\u6aac;\uc000\u2aac\ufe00\u0180flp\u342e\u3433\u3442tcy;\u444c\u0100;b\u3438\u3439\u402f\u0100;a\u343e\u343f\u69c4r;\u633ff;\uc000\ud835\udd64a\u0100dr\u344d\u0402es\u0100;u\u3454\u3455\u6660it\xbb\u3455\u0180csu\u3460\u3479\u349f\u0100au\u3465\u346fp\u0100;s\u1188\u346b;\uc000\u2293\ufe00p\u0100;s\u11b4\u3475;\uc000\u2294\ufe00u\u0100bp\u347f\u348f\u0180;es\u1197\u119c\u3486et\u0100;e\u1197\u348d\xf1\u119d\u0180;es\u11a8\u11ad\u3496et\u0100;e\u11a8\u349d\xf1\u11ae\u0180;af\u117b\u34a6\u05b0r\u0165\u34ab\u05b1\xbb\u117car\xf2\u1148\u0200cemt\u34b9\u34be\u34c2\u34c5r;\uc000\ud835\udcc8tm\xee\xf1i\xec\u3415ar\xe6\u11be\u0100ar\u34ce\u34d5r\u0100;f\u34d4\u17bf\u6606\u0100an\u34da\u34edight\u0100ep\u34e3\u34eapsilo\xee\u1ee0h\xe9\u2eafs\xbb\u2852\u0280bcmnp\u34fb\u355e\u1209\u358b\u358e\u0480;Edemnprs\u350e\u350f\u3511\u3515\u351e\u3523\u352c\u3531\u3536\u6282;\u6ac5ot;\u6abd\u0100;d\u11da\u351aot;\u6ac3ult;\u6ac1\u0100Ee\u3528\u352a;\u6acb;\u628alus;\u6abfarr;\u6979\u0180eiu\u353d\u3552\u3555t\u0180;en\u350e\u3545\u354bq\u0100;q\u11da\u350feq\u0100;q\u352b\u3528m;\u6ac7\u0100bp\u355a\u355c;\u6ad5;\u6ad3c\u0300;acens\u11ed\u356c\u3572\u3579\u357b\u3326ppro\xf8\u32faurlye\xf1\u11fe\xf1\u11f3\u0180aes\u3582\u3588\u331bppro\xf8\u331aq\xf1\u3317g;\u666a\u0680123;Edehlmnps\u35a9\u35ac\u35af\u121c\u35b2\u35b4\u35c0\u35c9\u35d5\u35da\u35df\u35e8\u35ed\u803b\xb9\u40b9\u803b\xb2\u40b2\u803b\xb3\u40b3;\u6ac6\u0100os\u35b9\u35bct;\u6abeub;\u6ad8\u0100;d\u1222\u35c5ot;\u6ac4s\u0100ou\u35cf\u35d2l;\u67c9b;\u6ad7arr;\u697bult;\u6ac2\u0100Ee\u35e4\u35e6;\u6acc;\u628blus;\u6ac0\u0180eiu\u35f4\u3609\u360ct\u0180;en\u121c\u35fc\u3602q\u0100;q\u1222\u35b2eq\u0100;q\u35e7\u35e4m;\u6ac8\u0100bp\u3611\u3613;\u6ad4;\u6ad6\u0180Aan\u361c\u3620\u362drr;\u61d9r\u0100hr\u3626\u3628\xeb\u222e\u0100;o\u0a2b\u0a29war;\u692alig\u803b\xdf\u40df\u0be1\u3651\u365d\u3660\u12ce\u3673\u3679\0\u367e\u36c2\0\0\0\0\0\u36db\u3703\0\u3709\u376c\0\0\0\u3787\u0272\u3656\0\0\u365bget;\u6316;\u43c4r\xeb\u0e5f\u0180aey\u3666\u366b\u3670ron;\u4165dil;\u4163;\u4442lrec;\u6315r;\uc000\ud835\udd31\u0200eiko\u3686\u369d\u36b5\u36bc\u01f2\u368b\0\u3691e\u01004f\u1284\u1281a\u0180;sv\u3698\u3699\u369b\u43b8ym;\u43d1\u0100cn\u36a2\u36b2k\u0100as\u36a8\u36aeppro\xf8\u12c1im\xbb\u12acs\xf0\u129e\u0100as\u36ba\u36ae\xf0\u12c1rn\u803b\xfe\u40fe\u01ec\u031f\u36c6\u22e7es\u8180\xd7;bd\u36cf\u36d0\u36d8\u40d7\u0100;a\u190f\u36d5r;\u6a31;\u6a30\u0180eps\u36e1\u36e3\u3700\xe1\u2a4d\u0200;bcf\u0486\u36ec\u36f0\u36f4ot;\u6336ir;\u6af1\u0100;o\u36f9\u36fc\uc000\ud835\udd65rk;\u6ada\xe1\u3362rime;\u6034\u0180aip\u370f\u3712\u3764d\xe5\u1248\u0380adempst\u3721\u374d\u3740\u3751\u3757\u375c\u375fngle\u0280;dlqr\u3730\u3731\u3736\u3740\u3742\u65b5own\xbb\u1dbbeft\u0100;e\u2800\u373e\xf1\u092e;\u625cight\u0100;e\u32aa\u374b\xf1\u105aot;\u65ecinus;\u6a3alus;\u6a39b;\u69cdime;\u6a3bezium;\u63e2\u0180cht\u3772\u377d\u3781\u0100ry\u3777\u377b;\uc000\ud835\udcc9;\u4446cy;\u445brok;\u4167\u0100io\u378b\u378ex\xf4\u1777head\u0100lr\u3797\u37a0eftarro\xf7\u084fightarrow\xbb\u0f5d\u0900AHabcdfghlmoprstuw\u37d0\u37d3\u37d7\u37e4\u37f0\u37fc\u380e\u381c\u3823\u3834\u3851\u385d\u386b\u38a9\u38cc\u38d2\u38ea\u38f6r\xf2\u03edar;\u6963\u0100cr\u37dc\u37e2ute\u803b\xfa\u40fa\xf2\u1150r\u01e3\u37ea\0\u37edy;\u445eve;\u416d\u0100iy\u37f5\u37farc\u803b\xfb\u40fb;\u4443\u0180abh\u3803\u3806\u380br\xf2\u13adlac;\u4171a\xf2\u13c3\u0100ir\u3813\u3818sht;\u697e;\uc000\ud835\udd32rave\u803b\xf9\u40f9\u0161\u3827\u3831r\u0100lr\u382c\u382e\xbb\u0957\xbb\u1083lk;\u6580\u0100ct\u3839\u384d\u026f\u383f\0\0\u384arn\u0100;e\u3845\u3846\u631cr\xbb\u3846op;\u630fri;\u65f8\u0100al\u3856\u385acr;\u416b\u80bb\xa8\u0349\u0100gp\u3862\u3866on;\u4173f;\uc000\ud835\udd66\u0300adhlsu\u114b\u3878\u387d\u1372\u3891\u38a0own\xe1\u13b3arpoon\u0100lr\u3888\u388cef\xf4\u382digh\xf4\u382fi\u0180;hl\u3899\u389a\u389c\u43c5\xbb\u13faon\xbb\u389aparrows;\u61c8\u0180cit\u38b0\u38c4\u38c8\u026f\u38b6\0\0\u38c1rn\u0100;e\u38bc\u38bd\u631dr\xbb\u38bdop;\u630eng;\u416fri;\u65f9cr;\uc000\ud835\udcca\u0180dir\u38d9\u38dd\u38e2ot;\u62f0lde;\u4169i\u0100;f\u3730\u38e8\xbb\u1813\u0100am\u38ef\u38f2r\xf2\u38a8l\u803b\xfc\u40fcangle;\u69a7\u0780ABDacdeflnoprsz\u391c\u391f\u3929\u392d\u39b5\u39b8\u39bd\u39df\u39e4\u39e8\u39f3\u39f9\u39fd\u3a01\u3a20r\xf2\u03f7ar\u0100;v\u3926\u3927\u6ae8;\u6ae9as\xe8\u03e1\u0100nr\u3932\u3937grt;\u699c\u0380eknprst\u34e3\u3946\u394b\u3952\u395d\u3964\u3996app\xe1\u2415othin\xe7\u1e96\u0180hir\u34eb\u2ec8\u3959op\xf4\u2fb5\u0100;h\u13b7\u3962\xef\u318d\u0100iu\u3969\u396dgm\xe1\u33b3\u0100bp\u3972\u3984setneq\u0100;q\u397d\u3980\uc000\u228a\ufe00;\uc000\u2acb\ufe00setneq\u0100;q\u398f\u3992\uc000\u228b\ufe00;\uc000\u2acc\ufe00\u0100hr\u399b\u399fet\xe1\u369ciangle\u0100lr\u39aa\u39afeft\xbb\u0925ight\xbb\u1051y;\u4432ash\xbb\u1036\u0180elr\u39c4\u39d2\u39d7\u0180;be\u2dea\u39cb\u39cfar;\u62bbq;\u625alip;\u62ee\u0100bt\u39dc\u1468a\xf2\u1469r;\uc000\ud835\udd33tr\xe9\u39aesu\u0100bp\u39ef\u39f1\xbb\u0d1c\xbb\u0d59pf;\uc000\ud835\udd67ro\xf0\u0efbtr\xe9\u39b4\u0100cu\u3a06\u3a0br;\uc000\ud835\udccb\u0100bp\u3a10\u3a18n\u0100Ee\u3980\u3a16\xbb\u397en\u0100Ee\u3992\u3a1e\xbb\u3990igzag;\u699a\u0380cefoprs\u3a36\u3a3b\u3a56\u3a5b\u3a54\u3a61\u3a6airc;\u4175\u0100di\u3a40\u3a51\u0100bg\u3a45\u3a49ar;\u6a5fe\u0100;q\u15fa\u3a4f;\u6259erp;\u6118r;\uc000\ud835\udd34pf;\uc000\ud835\udd68\u0100;e\u1479\u3a66at\xe8\u1479cr;\uc000\ud835\udccc\u0ae3\u178e\u3a87\0\u3a8b\0\u3a90\u3a9b\0\0\u3a9d\u3aa8\u3aab\u3aaf\0\0\u3ac3\u3ace\0\u3ad8\u17dc\u17dftr\xe9\u17d1r;\uc000\ud835\udd35\u0100Aa\u3a94\u3a97r\xf2\u03c3r\xf2\u09f6;\u43be\u0100Aa\u3aa1\u3aa4r\xf2\u03b8r\xf2\u09eba\xf0\u2713is;\u62fb\u0180dpt\u17a4\u3ab5\u3abe\u0100fl\u3aba\u17a9;\uc000\ud835\udd69im\xe5\u17b2\u0100Aa\u3ac7\u3acar\xf2\u03cer\xf2\u0a01\u0100cq\u3ad2\u17b8r;\uc000\ud835\udccd\u0100pt\u17d6\u3adcr\xe9\u17d4\u0400acefiosu\u3af0\u3afd\u3b08\u3b0c\u3b11\u3b15\u3b1b\u3b21c\u0100uy\u3af6\u3afbte\u803b\xfd\u40fd;\u444f\u0100iy\u3b02\u3b06rc;\u4177;\u444bn\u803b\xa5\u40a5r;\uc000\ud835\udd36cy;\u4457pf;\uc000\ud835\udd6acr;\uc000\ud835\udcce\u0100cm\u3b26\u3b29y;\u444el\u803b\xff\u40ff\u0500acdefhiosw\u3b42\u3b48\u3b54\u3b58\u3b64\u3b69\u3b6d\u3b74\u3b7a\u3b80cute;\u417a\u0100ay\u3b4d\u3b52ron;\u417e;\u4437ot;\u417c\u0100et\u3b5d\u3b61tr\xe6\u155fa;\u43b6r;\uc000\ud835\udd37cy;\u4436grarr;\u61ddpf;\uc000\ud835\udd6bcr;\uc000\ud835\udccf\u0100jn\u3b85\u3b87;\u600dj;\u600c".split("").map(function (c) { - return c.charCodeAt(0); -})); - -/***/ }), - -/***/ "../../../node_modules/entities/lib/generated/decode-data-xml.js": -/*!***********************************************************************!*\ - !*** ../../../node_modules/entities/lib/generated/decode-data-xml.js ***! - \***********************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -// Generated using scripts/write-decode-map.ts -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = new Uint16Array( -// prettier-ignore -"\u0200aglq\t\x15\x18\x1b\u026d\x0f\0\0\x12p;\u4026os;\u4027t;\u403et;\u403cuot;\u4022".split("").map(function (c) { - return c.charCodeAt(0); -})); - -/***/ }), - -/***/ "../../../node_modules/entities/lib/generated/encode-html.js": -/*!*******************************************************************!*\ - !*** ../../../node_modules/entities/lib/generated/encode-html.js ***! - \*******************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - - -// Generated using scripts/write-encode-map.ts -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -function restoreDiff(arr) { - for (var i = 1; i < arr.length; i++) { - arr[i][0] += arr[i - 1][0] + 1; - } - return arr; -} -// prettier-ignore -exports["default"] = new Map( /* #__PURE__ */restoreDiff([[9, " "], [0, " "], [22, "!"], [0, """], [0, "#"], [0, "$"], [0, "%"], [0, "&"], [0, "'"], [0, "("], [0, ")"], [0, "*"], [0, "+"], [0, ","], [1, "."], [0, "/"], [10, ":"], [0, ";"], [0, { - v: "<", - n: 8402, - o: "<⃒" -}], [0, { - v: "=", - n: 8421, - o: "=⃥" -}], [0, { - v: ">", - n: 8402, - o: ">⃒" -}], [0, "?"], [0, "@"], [26, "["], [0, "\"], [0, "]"], [0, "^"], [0, "_"], [0, "`"], [5, { - n: 106, - o: "fj" -}], [20, "{"], [0, "|"], [0, "}"], [34, " "], [0, "¡"], [0, "¢"], [0, "£"], [0, "¤"], [0, "¥"], [0, "¦"], [0, "§"], [0, "¨"], [0, "©"], [0, "ª"], [0, "«"], [0, "¬"], [0, "­"], [0, "®"], [0, "¯"], [0, "°"], [0, "±"], [0, "²"], [0, "³"], [0, "´"], [0, "µ"], [0, "¶"], [0, "·"], [0, "¸"], [0, "¹"], [0, "º"], [0, "»"], [0, "¼"], [0, "½"], [0, "¾"], [0, "¿"], [0, "À"], [0, "Á"], [0, "Â"], [0, "Ã"], [0, "Ä"], [0, "Å"], [0, "Æ"], [0, "Ç"], [0, "È"], [0, "É"], [0, "Ê"], [0, "Ë"], [0, "Ì"], [0, "Í"], [0, "Î"], [0, "Ï"], [0, "Ð"], [0, "Ñ"], [0, "Ò"], [0, "Ó"], [0, "Ô"], [0, "Õ"], [0, "Ö"], [0, "×"], [0, "Ø"], [0, "Ù"], [0, "Ú"], [0, "Û"], [0, "Ü"], [0, "Ý"], [0, "Þ"], [0, "ß"], [0, "à"], [0, "á"], [0, "â"], [0, "ã"], [0, "ä"], [0, "å"], [0, "æ"], [0, "ç"], [0, "è"], [0, "é"], [0, "ê"], [0, "ë"], [0, "ì"], [0, "í"], [0, "î"], [0, "ï"], [0, "ð"], [0, "ñ"], [0, "ò"], [0, "ó"], [0, "ô"], [0, "õ"], [0, "ö"], [0, "÷"], [0, "ø"], [0, "ù"], [0, "ú"], [0, "û"], [0, "ü"], [0, "ý"], [0, "þ"], [0, "ÿ"], [0, "Ā"], [0, "ā"], [0, "Ă"], [0, "ă"], [0, "Ą"], [0, "ą"], [0, "Ć"], [0, "ć"], [0, "Ĉ"], [0, "ĉ"], [0, "Ċ"], [0, "ċ"], [0, "Č"], [0, "č"], [0, "Ď"], [0, "ď"], [0, "Đ"], [0, "đ"], [0, "Ē"], [0, "ē"], [2, "Ė"], [0, "ė"], [0, "Ę"], [0, "ę"], [0, "Ě"], [0, "ě"], [0, "Ĝ"], [0, "ĝ"], [0, "Ğ"], [0, "ğ"], [0, "Ġ"], [0, "ġ"], [0, "Ģ"], [1, "Ĥ"], [0, "ĥ"], [0, "Ħ"], [0, "ħ"], [0, "Ĩ"], [0, "ĩ"], [0, "Ī"], [0, "ī"], [2, "Į"], [0, "į"], [0, "İ"], [0, "ı"], [0, "IJ"], [0, "ij"], [0, "Ĵ"], [0, "ĵ"], [0, "Ķ"], [0, "ķ"], [0, "ĸ"], [0, "Ĺ"], [0, "ĺ"], [0, "Ļ"], [0, "ļ"], [0, "Ľ"], [0, "ľ"], [0, "Ŀ"], [0, "ŀ"], [0, "Ł"], [0, "ł"], [0, "Ń"], [0, "ń"], [0, "Ņ"], [0, "ņ"], [0, "Ň"], [0, "ň"], [0, "ʼn"], [0, "Ŋ"], [0, "ŋ"], [0, "Ō"], [0, "ō"], [2, "Ő"], [0, "ő"], [0, "Œ"], [0, "œ"], [0, "Ŕ"], [0, "ŕ"], [0, "Ŗ"], [0, "ŗ"], [0, "Ř"], [0, "ř"], [0, "Ś"], [0, "ś"], [0, "Ŝ"], [0, "ŝ"], [0, "Ş"], [0, "ş"], [0, "Š"], [0, "š"], [0, "Ţ"], [0, "ţ"], [0, "Ť"], [0, "ť"], [0, "Ŧ"], [0, "ŧ"], [0, "Ũ"], [0, "ũ"], [0, "Ū"], [0, "ū"], [0, "Ŭ"], [0, "ŭ"], [0, "Ů"], [0, "ů"], [0, "Ű"], [0, "ű"], [0, "Ų"], [0, "ų"], [0, "Ŵ"], [0, "ŵ"], [0, "Ŷ"], [0, "ŷ"], [0, "Ÿ"], [0, "Ź"], [0, "ź"], [0, "Ż"], [0, "ż"], [0, "Ž"], [0, "ž"], [19, "ƒ"], [34, "Ƶ"], [63, "ǵ"], [65, "ȷ"], [142, "ˆ"], [0, "ˇ"], [16, "˘"], [0, "˙"], [0, "˚"], [0, "˛"], [0, "˜"], [0, "˝"], [51, "̑"], [127, "Α"], [0, "Β"], [0, "Γ"], [0, "Δ"], [0, "Ε"], [0, "Ζ"], [0, "Η"], [0, "Θ"], [0, "Ι"], [0, "Κ"], [0, "Λ"], [0, "Μ"], [0, "Ν"], [0, "Ξ"], [0, "Ο"], [0, "Π"], [0, "Ρ"], [1, "Σ"], [0, "Τ"], [0, "Υ"], [0, "Φ"], [0, "Χ"], [0, "Ψ"], [0, "Ω"], [7, "α"], [0, "β"], [0, "γ"], [0, "δ"], [0, "ε"], [0, "ζ"], [0, "η"], [0, "θ"], [0, "ι"], [0, "κ"], [0, "λ"], [0, "μ"], [0, "ν"], [0, "ξ"], [0, "ο"], [0, "π"], [0, "ρ"], [0, "ς"], [0, "σ"], [0, "τ"], [0, "υ"], [0, "φ"], [0, "χ"], [0, "ψ"], [0, "ω"], [7, "ϑ"], [0, "ϒ"], [2, "ϕ"], [0, "ϖ"], [5, "Ϝ"], [0, "ϝ"], [18, "ϰ"], [0, "ϱ"], [3, "ϵ"], [0, "϶"], [10, "Ё"], [0, "Ђ"], [0, "Ѓ"], [0, "Є"], [0, "Ѕ"], [0, "І"], [0, "Ї"], [0, "Ј"], [0, "Љ"], [0, "Њ"], [0, "Ћ"], [0, "Ќ"], [1, "Ў"], [0, "Џ"], [0, "А"], [0, "Б"], [0, "В"], [0, "Г"], [0, "Д"], [0, "Е"], [0, "Ж"], [0, "З"], [0, "И"], [0, "Й"], [0, "К"], [0, "Л"], [0, "М"], [0, "Н"], [0, "О"], [0, "П"], [0, "Р"], [0, "С"], [0, "Т"], [0, "У"], [0, "Ф"], [0, "Х"], [0, "Ц"], [0, "Ч"], [0, "Ш"], [0, "Щ"], [0, "Ъ"], [0, "Ы"], [0, "Ь"], [0, "Э"], [0, "Ю"], [0, "Я"], [0, "а"], [0, "б"], [0, "в"], [0, "г"], [0, "д"], [0, "е"], [0, "ж"], [0, "з"], [0, "и"], [0, "й"], [0, "к"], [0, "л"], [0, "м"], [0, "н"], [0, "о"], [0, "п"], [0, "р"], [0, "с"], [0, "т"], [0, "у"], [0, "ф"], [0, "х"], [0, "ц"], [0, "ч"], [0, "ш"], [0, "щ"], [0, "ъ"], [0, "ы"], [0, "ь"], [0, "э"], [0, "ю"], [0, "я"], [1, "ё"], [0, "ђ"], [0, "ѓ"], [0, "є"], [0, "ѕ"], [0, "і"], [0, "ї"], [0, "ј"], [0, "љ"], [0, "њ"], [0, "ћ"], [0, "ќ"], [1, "ў"], [0, "џ"], [7074, " "], [0, " "], [0, " "], [0, " "], [1, " "], [0, " "], [0, " "], [0, " "], [0, "​"], [0, "‌"], [0, "‍"], [0, "‎"], [0, "‏"], [0, "‐"], [2, "–"], [0, "—"], [0, "―"], [0, "‖"], [1, "‘"], [0, "’"], [0, "‚"], [1, "“"], [0, "”"], [0, "„"], [1, "†"], [0, "‡"], [0, "•"], [2, "‥"], [0, "…"], [9, "‰"], [0, "‱"], [0, "′"], [0, "″"], [0, "‴"], [0, "‵"], [3, "‹"], [0, "›"], [3, "‾"], [2, "⁁"], [1, "⁃"], [0, "⁄"], [10, "⁏"], [7, "⁗"], [7, { - v: " ", - n: 8202, - o: "  " -}], [0, "⁠"], [0, "⁡"], [0, "⁢"], [0, "⁣"], [72, "€"], [46, "⃛"], [0, "⃜"], [37, "ℂ"], [2, "℅"], [4, "ℊ"], [0, "ℋ"], [0, "ℌ"], [0, "ℍ"], [0, "ℎ"], [0, "ℏ"], [0, "ℐ"], [0, "ℑ"], [0, "ℒ"], [0, "ℓ"], [1, "ℕ"], [0, "№"], [0, "℗"], [0, "℘"], [0, "ℙ"], [0, "ℚ"], [0, "ℛ"], [0, "ℜ"], [0, "ℝ"], [0, "℞"], [3, "™"], [1, "ℤ"], [2, "℧"], [0, "ℨ"], [0, "℩"], [2, "ℬ"], [0, "ℭ"], [1, "ℯ"], [0, "ℰ"], [0, "ℱ"], [1, "ℳ"], [0, "ℴ"], [0, "ℵ"], [0, "ℶ"], [0, "ℷ"], [0, "ℸ"], [12, "ⅅ"], [0, "ⅆ"], [0, "ⅇ"], [0, "ⅈ"], [10, "⅓"], [0, "⅔"], [0, "⅕"], [0, "⅖"], [0, "⅗"], [0, "⅘"], [0, "⅙"], [0, "⅚"], [0, "⅛"], [0, "⅜"], [0, "⅝"], [0, "⅞"], [49, "←"], [0, "↑"], [0, "→"], [0, "↓"], [0, "↔"], [0, "↕"], [0, "↖"], [0, "↗"], [0, "↘"], [0, "↙"], [0, "↚"], [0, "↛"], [1, { - v: "↝", - n: 824, - o: "↝̸" -}], [0, "↞"], [0, "↟"], [0, "↠"], [0, "↡"], [0, "↢"], [0, "↣"], [0, "↤"], [0, "↥"], [0, "↦"], [0, "↧"], [1, "↩"], [0, "↪"], [0, "↫"], [0, "↬"], [0, "↭"], [0, "↮"], [1, "↰"], [0, "↱"], [0, "↲"], [0, "↳"], [1, "↵"], [0, "↶"], [0, "↷"], [2, "↺"], [0, "↻"], [0, "↼"], [0, "↽"], [0, "↾"], [0, "↿"], [0, "⇀"], [0, "⇁"], [0, "⇂"], [0, "⇃"], [0, "⇄"], [0, "⇅"], [0, "⇆"], [0, "⇇"], [0, "⇈"], [0, "⇉"], [0, "⇊"], [0, "⇋"], [0, "⇌"], [0, "⇍"], [0, "⇎"], [0, "⇏"], [0, "⇐"], [0, "⇑"], [0, "⇒"], [0, "⇓"], [0, "⇔"], [0, "⇕"], [0, "⇖"], [0, "⇗"], [0, "⇘"], [0, "⇙"], [0, "⇚"], [0, "⇛"], [1, "⇝"], [6, "⇤"], [0, "⇥"], [15, "⇵"], [7, "⇽"], [0, "⇾"], [0, "⇿"], [0, "∀"], [0, "∁"], [0, { - v: "∂", - n: 824, - o: "∂̸" -}], [0, "∃"], [0, "∄"], [0, "∅"], [1, "∇"], [0, "∈"], [0, "∉"], [1, "∋"], [0, "∌"], [2, "∏"], [0, "∐"], [0, "∑"], [0, "−"], [0, "∓"], [0, "∔"], [1, "∖"], [0, "∗"], [0, "∘"], [1, "√"], [2, "∝"], [0, "∞"], [0, "∟"], [0, { - v: "∠", - n: 8402, - o: "∠⃒" -}], [0, "∡"], [0, "∢"], [0, "∣"], [0, "∤"], [0, "∥"], [0, "∦"], [0, "∧"], [0, "∨"], [0, { - v: "∩", - n: 65024, - o: "∩︀" -}], [0, { - v: "∪", - n: 65024, - o: "∪︀" -}], [0, "∫"], [0, "∬"], [0, "∭"], [0, "∮"], [0, "∯"], [0, "∰"], [0, "∱"], [0, "∲"], [0, "∳"], [0, "∴"], [0, "∵"], [0, "∶"], [0, "∷"], [0, "∸"], [1, "∺"], [0, "∻"], [0, { - v: "∼", - n: 8402, - o: "∼⃒" -}], [0, { - v: "∽", - n: 817, - o: "∽̱" -}], [0, { - v: "∾", - n: 819, - o: "∾̳" -}], [0, "∿"], [0, "≀"], [0, "≁"], [0, { - v: "≂", - n: 824, - o: "≂̸" -}], [0, "≃"], [0, "≄"], [0, "≅"], [0, "≆"], [0, "≇"], [0, "≈"], [0, "≉"], [0, "≊"], [0, { - v: "≋", - n: 824, - o: "≋̸" -}], [0, "≌"], [0, { - v: "≍", - n: 8402, - o: "≍⃒" -}], [0, { - v: "≎", - n: 824, - o: "≎̸" -}], [0, { - v: "≏", - n: 824, - o: "≏̸" -}], [0, { - v: "≐", - n: 824, - o: "≐̸" -}], [0, "≑"], [0, "≒"], [0, "≓"], [0, "≔"], [0, "≕"], [0, "≖"], [0, "≗"], [1, "≙"], [0, "≚"], [1, "≜"], [2, "≟"], [0, "≠"], [0, { - v: "≡", - n: 8421, - o: "≡⃥" -}], [0, "≢"], [1, { - v: "≤", - n: 8402, - o: "≤⃒" -}], [0, { - v: "≥", - n: 8402, - o: "≥⃒" -}], [0, { - v: "≦", - n: 824, - o: "≦̸" -}], [0, { - v: "≧", - n: 824, - o: "≧̸" -}], [0, { - v: "≨", - n: 65024, - o: "≨︀" -}], [0, { - v: "≩", - n: 65024, - o: "≩︀" -}], [0, { - v: "≪", - n: new Map( /* #__PURE__ */restoreDiff([[824, "≪̸"], [7577, "≪⃒"]])) -}], [0, { - v: "≫", - n: new Map( /* #__PURE__ */restoreDiff([[824, "≫̸"], [7577, "≫⃒"]])) -}], [0, "≬"], [0, "≭"], [0, "≮"], [0, "≯"], [0, "≰"], [0, "≱"], [0, "≲"], [0, "≳"], [0, "≴"], [0, "≵"], [0, "≶"], [0, "≷"], [0, "≸"], [0, "≹"], [0, "≺"], [0, "≻"], [0, "≼"], [0, "≽"], [0, "≾"], [0, { - v: "≿", - n: 824, - o: "≿̸" -}], [0, "⊀"], [0, "⊁"], [0, { - v: "⊂", - n: 8402, - o: "⊂⃒" -}], [0, { - v: "⊃", - n: 8402, - o: "⊃⃒" -}], [0, "⊄"], [0, "⊅"], [0, "⊆"], [0, "⊇"], [0, "⊈"], [0, "⊉"], [0, { - v: "⊊", - n: 65024, - o: "⊊︀" -}], [0, { - v: "⊋", - n: 65024, - o: "⊋︀" -}], [1, "⊍"], [0, "⊎"], [0, { - v: "⊏", - n: 824, - o: "⊏̸" -}], [0, { - v: "⊐", - n: 824, - o: "⊐̸" -}], [0, "⊑"], [0, "⊒"], [0, { - v: "⊓", - n: 65024, - o: "⊓︀" -}], [0, { - v: "⊔", - n: 65024, - o: "⊔︀" -}], [0, "⊕"], [0, "⊖"], [0, "⊗"], [0, "⊘"], [0, "⊙"], [0, "⊚"], [0, "⊛"], [1, "⊝"], [0, "⊞"], [0, "⊟"], [0, "⊠"], [0, "⊡"], [0, "⊢"], [0, "⊣"], [0, "⊤"], [0, "⊥"], [1, "⊧"], [0, "⊨"], [0, "⊩"], [0, "⊪"], [0, "⊫"], [0, "⊬"], [0, "⊭"], [0, "⊮"], [0, "⊯"], [0, "⊰"], [1, "⊲"], [0, "⊳"], [0, { - v: "⊴", - n: 8402, - o: "⊴⃒" -}], [0, { - v: "⊵", - n: 8402, - o: "⊵⃒" -}], [0, "⊶"], [0, "⊷"], [0, "⊸"], [0, "⊹"], [0, "⊺"], [0, "⊻"], [1, "⊽"], [0, "⊾"], [0, "⊿"], [0, "⋀"], [0, "⋁"], [0, "⋂"], [0, "⋃"], [0, "⋄"], [0, "⋅"], [0, "⋆"], [0, "⋇"], [0, "⋈"], [0, "⋉"], [0, "⋊"], [0, "⋋"], [0, "⋌"], [0, "⋍"], [0, "⋎"], [0, "⋏"], [0, "⋐"], [0, "⋑"], [0, "⋒"], [0, "⋓"], [0, "⋔"], [0, "⋕"], [0, "⋖"], [0, "⋗"], [0, { - v: "⋘", - n: 824, - o: "⋘̸" -}], [0, { - v: "⋙", - n: 824, - o: "⋙̸" -}], [0, { - v: "⋚", - n: 65024, - o: "⋚︀" -}], [0, { - v: "⋛", - n: 65024, - o: "⋛︀" -}], [2, "⋞"], [0, "⋟"], [0, "⋠"], [0, "⋡"], [0, "⋢"], [0, "⋣"], [2, "⋦"], [0, "⋧"], [0, "⋨"], [0, "⋩"], [0, "⋪"], [0, "⋫"], [0, "⋬"], [0, "⋭"], [0, "⋮"], [0, "⋯"], [0, "⋰"], [0, "⋱"], [0, "⋲"], [0, "⋳"], [0, "⋴"], [0, { - v: "⋵", - n: 824, - o: "⋵̸" -}], [0, "⋶"], [0, "⋷"], [1, { - v: "⋹", - n: 824, - o: "⋹̸" -}], [0, "⋺"], [0, "⋻"], [0, "⋼"], [0, "⋽"], [0, "⋾"], [6, "⌅"], [0, "⌆"], [1, "⌈"], [0, "⌉"], [0, "⌊"], [0, "⌋"], [0, "⌌"], [0, "⌍"], [0, "⌎"], [0, "⌏"], [0, "⌐"], [1, "⌒"], [0, "⌓"], [1, "⌕"], [0, "⌖"], [5, "⌜"], [0, "⌝"], [0, "⌞"], [0, "⌟"], [2, "⌢"], [0, "⌣"], [9, "⌭"], [0, "⌮"], [7, "⌶"], [6, "⌽"], [1, "⌿"], [60, "⍼"], [51, "⎰"], [0, "⎱"], [2, "⎴"], [0, "⎵"], [0, "⎶"], [37, "⏜"], [0, "⏝"], [0, "⏞"], [0, "⏟"], [2, "⏢"], [4, "⏧"], [59, "␣"], [164, "Ⓢ"], [55, "─"], [1, "│"], [9, "┌"], [3, "┐"], [3, "└"], [3, "┘"], [3, "├"], [7, "┤"], [7, "┬"], [7, "┴"], [7, "┼"], [19, "═"], [0, "║"], [0, "╒"], [0, "╓"], [0, "╔"], [0, "╕"], [0, "╖"], [0, "╗"], [0, "╘"], [0, "╙"], [0, "╚"], [0, "╛"], [0, "╜"], [0, "╝"], [0, "╞"], [0, "╟"], [0, "╠"], [0, "╡"], [0, "╢"], [0, "╣"], [0, "╤"], [0, "╥"], [0, "╦"], [0, "╧"], [0, "╨"], [0, "╩"], [0, "╪"], [0, "╫"], [0, "╬"], [19, "▀"], [3, "▄"], [3, "█"], [8, "░"], [0, "▒"], [0, "▓"], [13, "□"], [8, "▪"], [0, "▫"], [1, "▭"], [0, "▮"], [2, "▱"], [1, "△"], [0, "▴"], [0, "▵"], [2, "▸"], [0, "▹"], [3, "▽"], [0, "▾"], [0, "▿"], [2, "◂"], [0, "◃"], [6, "◊"], [0, "○"], [32, "◬"], [2, "◯"], [8, "◸"], [0, "◹"], [0, "◺"], [0, "◻"], [0, "◼"], [8, "★"], [0, "☆"], [7, "☎"], [49, "♀"], [1, "♂"], [29, "♠"], [2, "♣"], [1, "♥"], [0, "♦"], [3, "♪"], [2, "♭"], [0, "♮"], [0, "♯"], [163, "✓"], [3, "✗"], [8, "✠"], [21, "✶"], [33, "❘"], [25, "❲"], [0, "❳"], [84, "⟈"], [0, "⟉"], [28, "⟦"], [0, "⟧"], [0, "⟨"], [0, "⟩"], [0, "⟪"], [0, "⟫"], [0, "⟬"], [0, "⟭"], [7, "⟵"], [0, "⟶"], [0, "⟷"], [0, "⟸"], [0, "⟹"], [0, "⟺"], [1, "⟼"], [2, "⟿"], [258, "⤂"], [0, "⤃"], [0, "⤄"], [0, "⤅"], [6, "⤌"], [0, "⤍"], [0, "⤎"], [0, "⤏"], [0, "⤐"], [0, "⤑"], [0, "⤒"], [0, "⤓"], [2, "⤖"], [2, "⤙"], [0, "⤚"], [0, "⤛"], [0, "⤜"], [0, "⤝"], [0, "⤞"], [0, "⤟"], [0, "⤠"], [2, "⤣"], [0, "⤤"], [0, "⤥"], [0, "⤦"], [0, "⤧"], [0, "⤨"], [0, "⤩"], [0, "⤪"], [8, { - v: "⤳", - n: 824, - o: "⤳̸" -}], [1, "⤵"], [0, "⤶"], [0, "⤷"], [0, "⤸"], [0, "⤹"], [2, "⤼"], [0, "⤽"], [7, "⥅"], [2, "⥈"], [0, "⥉"], [0, "⥊"], [0, "⥋"], [2, "⥎"], [0, "⥏"], [0, "⥐"], [0, "⥑"], [0, "⥒"], [0, "⥓"], [0, "⥔"], [0, "⥕"], [0, "⥖"], [0, "⥗"], [0, "⥘"], [0, "⥙"], [0, "⥚"], [0, "⥛"], [0, "⥜"], [0, "⥝"], [0, "⥞"], [0, "⥟"], [0, "⥠"], [0, "⥡"], [0, "⥢"], [0, "⥣"], [0, "⥤"], [0, "⥥"], [0, "⥦"], [0, "⥧"], [0, "⥨"], [0, "⥩"], [0, "⥪"], [0, "⥫"], [0, "⥬"], [0, "⥭"], [0, "⥮"], [0, "⥯"], [0, "⥰"], [0, "⥱"], [0, "⥲"], [0, "⥳"], [0, "⥴"], [0, "⥵"], [0, "⥶"], [1, "⥸"], [0, "⥹"], [1, "⥻"], [0, "⥼"], [0, "⥽"], [0, "⥾"], [0, "⥿"], [5, "⦅"], [0, "⦆"], [4, "⦋"], [0, "⦌"], [0, "⦍"], [0, "⦎"], [0, "⦏"], [0, "⦐"], [0, "⦑"], [0, "⦒"], [0, "⦓"], [0, "⦔"], [0, "⦕"], [0, "⦖"], [3, "⦚"], [1, "⦜"], [0, "⦝"], [6, "⦤"], [0, "⦥"], [0, "⦦"], [0, "⦧"], [0, "⦨"], [0, "⦩"], [0, "⦪"], [0, "⦫"], [0, "⦬"], [0, "⦭"], [0, "⦮"], [0, "⦯"], [0, "⦰"], [0, "⦱"], [0, "⦲"], [0, "⦳"], [0, "⦴"], [0, "⦵"], [0, "⦶"], [0, "⦷"], [1, "⦹"], [1, "⦻"], [0, "⦼"], [1, "⦾"], [0, "⦿"], [0, "⧀"], [0, "⧁"], [0, "⧂"], [0, "⧃"], [0, "⧄"], [0, "⧅"], [3, "⧉"], [3, "⧍"], [0, "⧎"], [0, { - v: "⧏", - n: 824, - o: "⧏̸" -}], [0, { - v: "⧐", - n: 824, - o: "⧐̸" -}], [11, "⧜"], [0, "⧝"], [0, "⧞"], [4, "⧣"], [0, "⧤"], [0, "⧥"], [5, "⧫"], [8, "⧴"], [1, "⧶"], [9, "⨀"], [0, "⨁"], [0, "⨂"], [1, "⨄"], [1, "⨆"], [5, "⨌"], [0, "⨍"], [2, "⨐"], [0, "⨑"], [0, "⨒"], [0, "⨓"], [0, "⨔"], [0, "⨕"], [0, "⨖"], [0, "⨗"], [10, "⨢"], [0, "⨣"], [0, "⨤"], [0, "⨥"], [0, "⨦"], [0, "⨧"], [1, "⨩"], [0, "⨪"], [2, "⨭"], [0, "⨮"], [0, "⨯"], [0, "⨰"], [0, "⨱"], [1, "⨳"], [0, "⨴"], [0, "⨵"], [0, "⨶"], [0, "⨷"], [0, "⨸"], [0, "⨹"], [0, "⨺"], [0, "⨻"], [0, "⨼"], [2, "⨿"], [0, "⩀"], [1, "⩂"], [0, "⩃"], [0, "⩄"], [0, "⩅"], [0, "⩆"], [0, "⩇"], [0, "⩈"], [0, "⩉"], [0, "⩊"], [0, "⩋"], [0, "⩌"], [0, "⩍"], [2, "⩐"], [2, "⩓"], [0, "⩔"], [0, "⩕"], [0, "⩖"], [0, "⩗"], [0, "⩘"], [1, "⩚"], [0, "⩛"], [0, "⩜"], [0, "⩝"], [1, "⩟"], [6, "⩦"], [3, "⩪"], [2, { - v: "⩭", - n: 824, - o: "⩭̸" -}], [0, "⩮"], [0, "⩯"], [0, { - v: "⩰", - n: 824, - o: "⩰̸" -}], [0, "⩱"], [0, "⩲"], [0, "⩳"], [0, "⩴"], [0, "⩵"], [1, "⩷"], [0, "⩸"], [0, "⩹"], [0, "⩺"], [0, "⩻"], [0, "⩼"], [0, { - v: "⩽", - n: 824, - o: "⩽̸" -}], [0, { - v: "⩾", - n: 824, - o: "⩾̸" -}], [0, "⩿"], [0, "⪀"], [0, "⪁"], [0, "⪂"], [0, "⪃"], [0, "⪄"], [0, "⪅"], [0, "⪆"], [0, "⪇"], [0, "⪈"], [0, "⪉"], [0, "⪊"], [0, "⪋"], [0, "⪌"], [0, "⪍"], [0, "⪎"], [0, "⪏"], [0, "⪐"], [0, "⪑"], [0, "⪒"], [0, "⪓"], [0, "⪔"], [0, "⪕"], [0, "⪖"], [0, "⪗"], [0, "⪘"], [0, "⪙"], [0, "⪚"], [2, "⪝"], [0, "⪞"], [0, "⪟"], [0, "⪠"], [0, { - v: "⪡", - n: 824, - o: "⪡̸" -}], [0, { - v: "⪢", - n: 824, - o: "⪢̸" -}], [1, "⪤"], [0, "⪥"], [0, "⪦"], [0, "⪧"], [0, "⪨"], [0, "⪩"], [0, "⪪"], [0, "⪫"], [0, { - v: "⪬", - n: 65024, - o: "⪬︀" -}], [0, { - v: "⪭", - n: 65024, - o: "⪭︀" -}], [0, "⪮"], [0, { - v: "⪯", - n: 824, - o: "⪯̸" -}], [0, { - v: "⪰", - n: 824, - o: "⪰̸" -}], [2, "⪳"], [0, "⪴"], [0, "⪵"], [0, "⪶"], [0, "⪷"], [0, "⪸"], [0, "⪹"], [0, "⪺"], [0, "⪻"], [0, "⪼"], [0, "⪽"], [0, "⪾"], [0, "⪿"], [0, "⫀"], [0, "⫁"], [0, "⫂"], [0, "⫃"], [0, "⫄"], [0, { - v: "⫅", - n: 824, - o: "⫅̸" -}], [0, { - v: "⫆", - n: 824, - o: "⫆̸" -}], [0, "⫇"], [0, "⫈"], [2, { - v: "⫋", - n: 65024, - o: "⫋︀" -}], [0, { - v: "⫌", - n: 65024, - o: "⫌︀" -}], [2, "⫏"], [0, "⫐"], [0, "⫑"], [0, "⫒"], [0, "⫓"], [0, "⫔"], [0, "⫕"], [0, "⫖"], [0, "⫗"], [0, "⫘"], [0, "⫙"], [0, "⫚"], [0, "⫛"], [8, "⫤"], [1, "⫦"], [0, "⫧"], [0, "⫨"], [0, "⫩"], [1, "⫫"], [0, "⫬"], [0, "⫭"], [0, "⫮"], [0, "⫯"], [0, "⫰"], [0, "⫱"], [0, "⫲"], [0, "⫳"], [9, { - v: "⫽", - n: 8421, - o: "⫽⃥" -}], [44343, { - n: new Map( /* #__PURE__ */restoreDiff([[56476, "𝒜"], [1, "𝒞"], [0, "𝒟"], [2, "𝒢"], [2, "𝒥"], [0, "𝒦"], [2, "𝒩"], [0, "𝒪"], [0, "𝒫"], [0, "𝒬"], [1, "𝒮"], [0, "𝒯"], [0, "𝒰"], [0, "𝒱"], [0, "𝒲"], [0, "𝒳"], [0, "𝒴"], [0, "𝒵"], [0, "𝒶"], [0, "𝒷"], [0, "𝒸"], [0, "𝒹"], [1, "𝒻"], [1, "𝒽"], [0, "𝒾"], [0, "𝒿"], [0, "𝓀"], [0, "𝓁"], [0, "𝓂"], [0, "𝓃"], [1, "𝓅"], [0, "𝓆"], [0, "𝓇"], [0, "𝓈"], [0, "𝓉"], [0, "𝓊"], [0, "𝓋"], [0, "𝓌"], [0, "𝓍"], [0, "𝓎"], [0, "𝓏"], [52, "𝔄"], [0, "𝔅"], [1, "𝔇"], [0, "𝔈"], [0, "𝔉"], [0, "𝔊"], [2, "𝔍"], [0, "𝔎"], [0, "𝔏"], [0, "𝔐"], [0, "𝔑"], [0, "𝔒"], [0, "𝔓"], [0, "𝔔"], [1, "𝔖"], [0, "𝔗"], [0, "𝔘"], [0, "𝔙"], [0, "𝔚"], [0, "𝔛"], [0, "𝔜"], [1, "𝔞"], [0, "𝔟"], [0, "𝔠"], [0, "𝔡"], [0, "𝔢"], [0, "𝔣"], [0, "𝔤"], [0, "𝔥"], [0, "𝔦"], [0, "𝔧"], [0, "𝔨"], [0, "𝔩"], [0, "𝔪"], [0, "𝔫"], [0, "𝔬"], [0, "𝔭"], [0, "𝔮"], [0, "𝔯"], [0, "𝔰"], [0, "𝔱"], [0, "𝔲"], [0, "𝔳"], [0, "𝔴"], [0, "𝔵"], [0, "𝔶"], [0, "𝔷"], [0, "𝔸"], [0, "𝔹"], [1, "𝔻"], [0, "𝔼"], [0, "𝔽"], [0, "𝔾"], [1, "𝕀"], [0, "𝕁"], [0, "𝕂"], [0, "𝕃"], [0, "𝕄"], [1, "𝕆"], [3, "𝕊"], [0, "𝕋"], [0, "𝕌"], [0, "𝕍"], [0, "𝕎"], [0, "𝕏"], [0, "𝕐"], [1, "𝕒"], [0, "𝕓"], [0, "𝕔"], [0, "𝕕"], [0, "𝕖"], [0, "𝕗"], [0, "𝕘"], [0, "𝕙"], [0, "𝕚"], [0, "𝕛"], [0, "𝕜"], [0, "𝕝"], [0, "𝕞"], [0, "𝕟"], [0, "𝕠"], [0, "𝕡"], [0, "𝕢"], [0, "𝕣"], [0, "𝕤"], [0, "𝕥"], [0, "𝕦"], [0, "𝕧"], [0, "𝕨"], [0, "𝕩"], [0, "𝕪"], [0, "𝕫"]])) -}], [8906, "ff"], [0, "fi"], [0, "fl"], [0, "ffi"], [0, "ffl"]])); - -/***/ }), - -/***/ "../../../node_modules/entities/lib/index.js": -/*!***************************************************!*\ - !*** ../../../node_modules/entities/lib/index.js ***! - \***************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.decodeXMLStrict = exports.decodeHTML5Strict = exports.decodeHTML4Strict = exports.decodeHTML5 = exports.decodeHTML4 = exports.decodeHTMLAttribute = exports.decodeHTMLStrict = exports.decodeHTML = exports.decodeXML = exports.DecodingMode = exports.EntityDecoder = exports.encodeHTML5 = exports.encodeHTML4 = exports.encodeNonAsciiHTML = exports.encodeHTML = exports.escapeText = exports.escapeAttribute = exports.escapeUTF8 = exports.escape = exports.encodeXML = exports.encode = exports.decodeStrict = exports.decode = exports.EncodingMode = exports.EntityLevel = void 0; -var decode_js_1 = __webpack_require__(/*! ./decode.js */ "../../../node_modules/entities/lib/decode.js"); -var encode_js_1 = __webpack_require__(/*! ./encode.js */ "../../../node_modules/entities/lib/encode.js"); -var escape_js_1 = __webpack_require__(/*! ./escape.js */ "../../../node_modules/entities/lib/escape.js"); -/** The level of entities to support. */ -var EntityLevel; -(function (EntityLevel) { - /** Support only XML entities. */ - EntityLevel[EntityLevel["XML"] = 0] = "XML"; - /** Support HTML entities, which are a superset of XML entities. */ - EntityLevel[EntityLevel["HTML"] = 1] = "HTML"; -})(EntityLevel = exports.EntityLevel || (exports.EntityLevel = {})); -var EncodingMode; -(function (EncodingMode) { - /** - * The output is UTF-8 encoded. Only characters that need escaping within - * XML will be escaped. - */ - EncodingMode[EncodingMode["UTF8"] = 0] = "UTF8"; - /** - * The output consists only of ASCII characters. Characters that need - * escaping within HTML, and characters that aren't ASCII characters will - * be escaped. - */ - EncodingMode[EncodingMode["ASCII"] = 1] = "ASCII"; - /** - * Encode all characters that have an equivalent entity, as well as all - * characters that are not ASCII characters. - */ - EncodingMode[EncodingMode["Extensive"] = 2] = "Extensive"; - /** - * Encode all characters that have to be escaped in HTML attributes, - * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. - */ - EncodingMode[EncodingMode["Attribute"] = 3] = "Attribute"; - /** - * Encode all characters that have to be escaped in HTML text, - * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. - */ - EncodingMode[EncodingMode["Text"] = 4] = "Text"; -})(EncodingMode = exports.EncodingMode || (exports.EncodingMode = {})); -/** - * Decodes a string with entities. - * - * @param data String to decode. - * @param options Decoding options. - */ -function decode(data, options) { - if (options === void 0) { - options = EntityLevel.XML; - } - var level = typeof options === "number" ? options : options.level; - if (level === EntityLevel.HTML) { - var mode = typeof options === "object" ? options.mode : undefined; - return (0, decode_js_1.decodeHTML)(data, mode); - } - return (0, decode_js_1.decodeXML)(data); -} -exports.decode = decode; -/** - * Decodes a string with entities. Does not allow missing trailing semicolons for entities. - * - * @param data String to decode. - * @param options Decoding options. - * @deprecated Use `decode` with the `mode` set to `Strict`. - */ -function decodeStrict(data, options) { - var _a; - if (options === void 0) { - options = EntityLevel.XML; - } - var opts = typeof options === "number" ? { - level: options - } : options; - (_a = opts.mode) !== null && _a !== void 0 ? _a : opts.mode = decode_js_1.DecodingMode.Strict; - return decode(data, opts); -} -exports.decodeStrict = decodeStrict; -/** - * Encodes a string with entities. - * - * @param data String to encode. - * @param options Encoding options. - */ -function encode(data, options) { - if (options === void 0) { - options = EntityLevel.XML; - } - var opts = typeof options === "number" ? { - level: options - } : options; - // Mode `UTF8` just escapes XML entities - if (opts.mode === EncodingMode.UTF8) return (0, escape_js_1.escapeUTF8)(data); - if (opts.mode === EncodingMode.Attribute) return (0, escape_js_1.escapeAttribute)(data); - if (opts.mode === EncodingMode.Text) return (0, escape_js_1.escapeText)(data); - if (opts.level === EntityLevel.HTML) { - if (opts.mode === EncodingMode.ASCII) { - return (0, encode_js_1.encodeNonAsciiHTML)(data); - } - return (0, encode_js_1.encodeHTML)(data); - } - // ASCII and Extensive are equivalent - return (0, escape_js_1.encodeXML)(data); -} -exports.encode = encode; -var escape_js_2 = __webpack_require__(/*! ./escape.js */ "../../../node_modules/entities/lib/escape.js"); -Object.defineProperty(exports, "encodeXML", ({ - enumerable: true, - get: function () { - return escape_js_2.encodeXML; - } -})); -Object.defineProperty(exports, "escape", ({ - enumerable: true, - get: function () { - return escape_js_2.escape; - } -})); -Object.defineProperty(exports, "escapeUTF8", ({ - enumerable: true, - get: function () { - return escape_js_2.escapeUTF8; - } -})); -Object.defineProperty(exports, "escapeAttribute", ({ - enumerable: true, - get: function () { - return escape_js_2.escapeAttribute; - } -})); -Object.defineProperty(exports, "escapeText", ({ - enumerable: true, - get: function () { - return escape_js_2.escapeText; - } -})); -var encode_js_2 = __webpack_require__(/*! ./encode.js */ "../../../node_modules/entities/lib/encode.js"); -Object.defineProperty(exports, "encodeHTML", ({ - enumerable: true, - get: function () { - return encode_js_2.encodeHTML; - } -})); -Object.defineProperty(exports, "encodeNonAsciiHTML", ({ - enumerable: true, - get: function () { - return encode_js_2.encodeNonAsciiHTML; - } -})); -// Legacy aliases (deprecated) -Object.defineProperty(exports, "encodeHTML4", ({ - enumerable: true, - get: function () { - return encode_js_2.encodeHTML; - } -})); -Object.defineProperty(exports, "encodeHTML5", ({ - enumerable: true, - get: function () { - return encode_js_2.encodeHTML; - } -})); -var decode_js_2 = __webpack_require__(/*! ./decode.js */ "../../../node_modules/entities/lib/decode.js"); -Object.defineProperty(exports, "EntityDecoder", ({ - enumerable: true, - get: function () { - return decode_js_2.EntityDecoder; - } -})); -Object.defineProperty(exports, "DecodingMode", ({ - enumerable: true, - get: function () { - return decode_js_2.DecodingMode; - } -})); -Object.defineProperty(exports, "decodeXML", ({ - enumerable: true, - get: function () { - return decode_js_2.decodeXML; - } -})); -Object.defineProperty(exports, "decodeHTML", ({ - enumerable: true, - get: function () { - return decode_js_2.decodeHTML; - } -})); -Object.defineProperty(exports, "decodeHTMLStrict", ({ - enumerable: true, - get: function () { - return decode_js_2.decodeHTMLStrict; - } -})); -Object.defineProperty(exports, "decodeHTMLAttribute", ({ - enumerable: true, - get: function () { - return decode_js_2.decodeHTMLAttribute; - } -})); -// Legacy aliases (deprecated) -Object.defineProperty(exports, "decodeHTML4", ({ - enumerable: true, - get: function () { - return decode_js_2.decodeHTML; - } -})); -Object.defineProperty(exports, "decodeHTML5", ({ - enumerable: true, - get: function () { - return decode_js_2.decodeHTML; - } -})); -Object.defineProperty(exports, "decodeHTML4Strict", ({ - enumerable: true, - get: function () { - return decode_js_2.decodeHTMLStrict; - } -})); -Object.defineProperty(exports, "decodeHTML5Strict", ({ - enumerable: true, - get: function () { - return decode_js_2.decodeHTMLStrict; - } -})); -Object.defineProperty(exports, "decodeXMLStrict", ({ - enumerable: true, - get: function () { - return decode_js_2.decodeXML; - } -})); - -/***/ }), - -/***/ "../../../node_modules/framer-motion/dist/cjs/index.js": -/*!*************************************************************!*\ - !*** ../../../node_modules/framer-motion/dist/cjs/index.js ***! - \*************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -var tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); -var React = __webpack_require__(/*! react */ "react"); -var heyListen = __webpack_require__(/*! hey-listen */ "../../../node_modules/hey-listen/dist/hey-listen.es.js"); -var styleValueTypes = __webpack_require__(/*! style-value-types */ "../../../node_modules/style-value-types/dist/valueTypes.cjs.js"); -var popmotion = __webpack_require__(/*! popmotion */ "../../../node_modules/popmotion/dist/popmotion.cjs.js"); -var sync = __webpack_require__(/*! framesync */ "../../../node_modules/framesync/dist/framesync.cjs.js"); -var dom = __webpack_require__(/*! @motionone/dom */ "../../../node_modules/@motionone/dom/dist/index.es.js"); -function _interopDefaultLegacy(e) { - return e && typeof e === 'object' && 'default' in e ? e : { - 'default': e - }; -} -function _interopNamespace(e) { - if (e && e.__esModule) return e; - var n = Object.create(null); - if (e) { - Object.keys(e).forEach(function (k) { - if (k !== 'default') { - var d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: function () { - return e[k]; - } - }); - } - }); - } - n["default"] = e; - return Object.freeze(n); -} -var React__namespace = /*#__PURE__*/_interopNamespace(React); -var React__default = /*#__PURE__*/_interopDefaultLegacy(React); -var sync__default = /*#__PURE__*/_interopDefaultLegacy(sync); - -/** - * Browser-safe usage of process - */ -var defaultEnvironment = "production"; -var env = typeof process === "undefined" || process.env === undefined ? defaultEnvironment : "development" || 0; -var createDefinition = function (propNames) { - return { - isEnabled: function (props) { - return propNames.some(function (name) { - return !!props[name]; - }); - } - }; -}; -var featureDefinitions = { - measureLayout: createDefinition(["layout", "layoutId", "drag"]), - animation: createDefinition(["animate", "exit", "variants", "whileHover", "whileTap", "whileFocus", "whileDrag", "whileInView"]), - exit: createDefinition(["exit"]), - drag: createDefinition(["drag", "dragControls"]), - focus: createDefinition(["whileFocus"]), - hover: createDefinition(["whileHover", "onHoverStart", "onHoverEnd"]), - tap: createDefinition(["whileTap", "onTap", "onTapStart", "onTapCancel"]), - pan: createDefinition(["onPan", "onPanStart", "onPanSessionStart", "onPanEnd"]), - inView: createDefinition(["whileInView", "onViewportEnter", "onViewportLeave"]) -}; -function loadFeatures(features) { - for (var key in features) { - if (features[key] === null) continue; - if (key === "projectionNodeConstructor") { - featureDefinitions.projectionNodeConstructor = features[key]; - } else { - featureDefinitions[key].Component = features[key]; - } - } -} -var LazyContext = React.createContext({ - strict: false -}); -var featureNames = Object.keys(featureDefinitions); -var numFeatures = featureNames.length; -/** - * Load features via renderless components based on the provided MotionProps. - */ -function useFeatures(props, visualElement, preloadedFeatures) { - var features = []; - var lazyContext = React.useContext(LazyContext); - if (!visualElement) return null; - /** - * If we're in development mode, check to make sure we're not rendering a motion component - * as a child of LazyMotion, as this will break the file-size benefits of using it. - */ - if (env !== "production" && preloadedFeatures && lazyContext.strict) { - heyListen.invariant(false, "You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead."); - } - for (var i = 0; i < numFeatures; i++) { - var name_1 = featureNames[i]; - var _a = featureDefinitions[name_1], - isEnabled = _a.isEnabled, - Component = _a.Component; - /** - * It might be possible in the future to use this moment to - * dynamically request functionality. In initial tests this - * was producing a lot of duplication amongst bundles. - */ - if (isEnabled(props) && Component) { - features.push(React__namespace.createElement(Component, tslib.__assign({ - key: name_1 - }, props, { - visualElement: visualElement - }))); - } - } - return features; -} - -/** - * @public - */ -var MotionConfigContext = React.createContext({ - transformPagePoint: function (p) { - return p; - }, - isStatic: false, - reducedMotion: "never" -}); -var MotionContext = React.createContext({}); -function useVisualElementContext() { - return React.useContext(MotionContext).visualElement; -} - -/** - * @public - */ -var PresenceContext = React.createContext(null); -var isBrowser = typeof document !== "undefined"; -var useIsomorphicLayoutEffect = isBrowser ? React.useLayoutEffect : React.useEffect; - -// Does this device prefer reduced motion? Returns `null` server-side. -var prefersReducedMotion = { - current: null -}; -var hasDetected = false; -function initPrefersReducedMotion() { - hasDetected = true; - if (!isBrowser) return; - if (window.matchMedia) { - var motionMediaQuery_1 = window.matchMedia("(prefers-reduced-motion)"); - var setReducedMotionPreferences = function () { - return prefersReducedMotion.current = motionMediaQuery_1.matches; - }; - motionMediaQuery_1.addListener(setReducedMotionPreferences); - setReducedMotionPreferences(); - } else { - prefersReducedMotion.current = false; - } -} -/** - * A hook that returns `true` if we should be using reduced motion based on the current device's Reduced Motion setting. - * - * This can be used to implement changes to your UI based on Reduced Motion. For instance, replacing motion-sickness inducing - * `x`/`y` animations with `opacity`, disabling the autoplay of background videos, or turning off parallax motion. - * - * It will actively respond to changes and re-render your components with the latest setting. - * - * ```jsx - * export function Sidebar({ isOpen }) { - * const shouldReduceMotion = useReducedMotion() - * const closedX = shouldReduceMotion ? 0 : "-100%" - * - * return ( - * - * ) - * } - * ``` - * - * @return boolean - * - * @public - */ -function useReducedMotion() { - /** - * Lazy initialisation of prefersReducedMotion - */ - !hasDetected && initPrefersReducedMotion(); - var _a = tslib.__read(React.useState(prefersReducedMotion.current), 1), - shouldReduceMotion = _a[0]; - /** - * TODO See if people miss automatically updating shouldReduceMotion setting - */ - return shouldReduceMotion; -} -function useReducedMotionConfig() { - var reducedMotionPreference = useReducedMotion(); - var reducedMotion = React.useContext(MotionConfigContext).reducedMotion; - if (reducedMotion === "never") { - return false; - } else if (reducedMotion === "always") { - return true; - } else { - return reducedMotionPreference; - } -} -function useVisualElement(Component, visualState, props, createVisualElement) { - var lazyContext = React.useContext(LazyContext); - var parent = useVisualElementContext(); - var presenceContext = React.useContext(PresenceContext); - var shouldReduceMotion = useReducedMotionConfig(); - var visualElementRef = React.useRef(undefined); - /** - * If we haven't preloaded a renderer, check to see if we have one lazy-loaded - */ - if (!createVisualElement) createVisualElement = lazyContext.renderer; - if (!visualElementRef.current && createVisualElement) { - visualElementRef.current = createVisualElement(Component, { - visualState: visualState, - parent: parent, - props: props, - presenceId: presenceContext === null || presenceContext === void 0 ? void 0 : presenceContext.id, - blockInitialAnimation: (presenceContext === null || presenceContext === void 0 ? void 0 : presenceContext.initial) === false, - shouldReduceMotion: shouldReduceMotion - }); - } - var visualElement = visualElementRef.current; - useIsomorphicLayoutEffect(function () { - visualElement === null || visualElement === void 0 ? void 0 : visualElement.syncRender(); - }); - React.useEffect(function () { - var _a; - (_a = visualElement === null || visualElement === void 0 ? void 0 : visualElement.animationState) === null || _a === void 0 ? void 0 : _a.animateChanges(); - }); - useIsomorphicLayoutEffect(function () { - return function () { - return visualElement === null || visualElement === void 0 ? void 0 : visualElement.notifyUnmount(); - }; - }, []); - return visualElement; -} -function isRefObject(ref) { - return typeof ref === "object" && Object.prototype.hasOwnProperty.call(ref, "current"); -} - -/** - * Creates a ref function that, when called, hydrates the provided - * external ref and VisualElement. - */ -function useMotionRef(visualState, visualElement, externalRef) { - return React.useCallback(function (instance) { - var _a; - instance && ((_a = visualState.mount) === null || _a === void 0 ? void 0 : _a.call(visualState, instance)); - if (visualElement) { - instance ? visualElement.mount(instance) : visualElement.unmount(); - } - if (externalRef) { - if (typeof externalRef === "function") { - externalRef(instance); - } else if (isRefObject(externalRef)) { - externalRef.current = instance; - } - } - }, - /** - * Only pass a new ref callback to React if we've received a visual element - * factory. Otherwise we'll be mounting/remounting every time externalRef - * or other dependencies change. - */ - [visualElement]); -} - -/** - * Decides if the supplied variable is an array of variant labels - */ -function isVariantLabels(v) { - return Array.isArray(v); -} -/** - * Decides if the supplied variable is variant label - */ -function isVariantLabel(v) { - return typeof v === "string" || isVariantLabels(v); -} -/** - * Creates an object containing the latest state of every MotionValue on a VisualElement - */ -function getCurrent(visualElement) { - var current = {}; - visualElement.forEachValue(function (value, key) { - return current[key] = value.get(); - }); - return current; -} -/** - * Creates an object containing the latest velocity of every MotionValue on a VisualElement - */ -function getVelocity$1(visualElement) { - var velocity = {}; - visualElement.forEachValue(function (value, key) { - return velocity[key] = value.getVelocity(); - }); - return velocity; -} -function resolveVariantFromProps(props, definition, custom, currentValues, currentVelocity) { - var _a; - if (currentValues === void 0) { - currentValues = {}; - } - if (currentVelocity === void 0) { - currentVelocity = {}; - } - /** - * If the variant definition is a function, resolve. - */ - if (typeof definition === "function") { - definition = definition(custom !== null && custom !== void 0 ? custom : props.custom, currentValues, currentVelocity); - } - /** - * If the variant definition is a variant label, or - * the function returned a variant label, resolve. - */ - if (typeof definition === "string") { - definition = (_a = props.variants) === null || _a === void 0 ? void 0 : _a[definition]; - } - /** - * At this point we've resolved both functions and variant labels, - * but the resolved variant label might itself have been a function. - * If so, resolve. This can only have returned a valid target object. - */ - if (typeof definition === "function") { - definition = definition(custom !== null && custom !== void 0 ? custom : props.custom, currentValues, currentVelocity); - } - return definition; -} -function resolveVariant(visualElement, definition, custom) { - var props = visualElement.getProps(); - return resolveVariantFromProps(props, definition, custom !== null && custom !== void 0 ? custom : props.custom, getCurrent(visualElement), getVelocity$1(visualElement)); -} -function checkIfControllingVariants(props) { - var _a; - return typeof ((_a = props.animate) === null || _a === void 0 ? void 0 : _a.start) === "function" || isVariantLabel(props.initial) || isVariantLabel(props.animate) || isVariantLabel(props.whileHover) || isVariantLabel(props.whileDrag) || isVariantLabel(props.whileTap) || isVariantLabel(props.whileFocus) || isVariantLabel(props.exit); -} -function checkIfVariantNode(props) { - return Boolean(checkIfControllingVariants(props) || props.variants); -} -function getCurrentTreeVariants(props, context) { - if (checkIfControllingVariants(props)) { - var initial = props.initial, - animate = props.animate; - return { - initial: initial === false || isVariantLabel(initial) ? initial : undefined, - animate: isVariantLabel(animate) ? animate : undefined - }; - } - return props.inherit !== false ? context : {}; -} -function useCreateMotionContext(props) { - var _a = getCurrentTreeVariants(props, React.useContext(MotionContext)), - initial = _a.initial, - animate = _a.animate; - return React.useMemo(function () { - return { - initial: initial, - animate: animate - }; - }, [variantLabelsAsDependency(initial), variantLabelsAsDependency(animate)]); -} -function variantLabelsAsDependency(prop) { - return Array.isArray(prop) ? prop.join(" ") : prop; -} - -/** - * Creates a constant value over the lifecycle of a component. - * - * Even if `useMemo` is provided an empty array as its final argument, it doesn't offer - * a guarantee that it won't re-run for performance reasons later on. By using `useConstant` - * you can ensure that initialisers don't execute twice or more. - */ -function useConstant(init) { - var ref = React.useRef(null); - if (ref.current === null) { - ref.current = init(); - } - return ref.current; -} - -/** - * This should only ever be modified on the client otherwise it'll - * persist through server requests. If we need instanced states we - * could lazy-init via root. - */ -var globalProjectionState = { - /** - * Global flag as to whether the tree has animated since the last time - * we resized the window - */ - hasAnimatedSinceResize: true, - /** - * We set this to true once, on the first update. Any nodes added to the tree beyond that - * update will be given a `data-projection-id` attribute. - */ - hasEverUpdated: false -}; -var id$1 = 1; -function useProjectionId() { - return useConstant(function () { - if (globalProjectionState.hasEverUpdated) { - return id$1++; - } - }); -} -var LayoutGroupContext = React.createContext({}); - -/** - * Internal, exported only for usage in Framer - */ -var SwitchLayoutGroupContext = React.createContext({}); -function useProjection(projectionId, _a, visualElement, ProjectionNodeConstructor) { - var _b; - var layoutId = _a.layoutId, - layout = _a.layout, - drag = _a.drag, - dragConstraints = _a.dragConstraints, - layoutScroll = _a.layoutScroll; - var initialPromotionConfig = React.useContext(SwitchLayoutGroupContext); - if (!ProjectionNodeConstructor || !visualElement || (visualElement === null || visualElement === void 0 ? void 0 : visualElement.projection)) { - return; - } - visualElement.projection = new ProjectionNodeConstructor(projectionId, visualElement.getLatestValues(), (_b = visualElement.parent) === null || _b === void 0 ? void 0 : _b.projection); - visualElement.projection.setOptions({ - layoutId: layoutId, - layout: layout, - alwaysMeasureLayout: Boolean(drag) || dragConstraints && isRefObject(dragConstraints), - visualElement: visualElement, - scheduleRender: function () { - return visualElement.scheduleRender(); - }, - /** - * TODO: Update options in an effect. This could be tricky as it'll be too late - * to update by the time layout animations run. - * We also need to fix this safeToRemove by linking it up to the one returned by usePresence, - * ensuring it gets called if there's no potential layout animations. - * - */ - animationType: typeof layout === "string" ? layout : "both", - initialPromotionConfig: initialPromotionConfig, - layoutScroll: layoutScroll - }); -} -var VisualElementHandler = /** @class */function (_super) { - tslib.__extends(VisualElementHandler, _super); - function VisualElementHandler() { - return _super !== null && _super.apply(this, arguments) || this; - } - /** - * Update visual element props as soon as we know this update is going to be commited. - */ - VisualElementHandler.prototype.getSnapshotBeforeUpdate = function () { - this.updateProps(); - return null; - }; - VisualElementHandler.prototype.componentDidUpdate = function () {}; - VisualElementHandler.prototype.updateProps = function () { - var _a = this.props, - visualElement = _a.visualElement, - props = _a.props; - if (visualElement) visualElement.setProps(props); - }; - VisualElementHandler.prototype.render = function () { - return this.props.children; - }; - return VisualElementHandler; -}(React__default["default"].Component); - -/** - * Create a `motion` component. - * - * This function accepts a Component argument, which can be either a string (ie "div" - * for `motion.div`), or an actual React component. - * - * Alongside this is a config option which provides a way of rendering the provided - * component "offline", or outside the React render cycle. - */ -function createMotionComponent(_a) { - var preloadedFeatures = _a.preloadedFeatures, - createVisualElement = _a.createVisualElement, - projectionNodeConstructor = _a.projectionNodeConstructor, - useRender = _a.useRender, - useVisualState = _a.useVisualState, - Component = _a.Component; - preloadedFeatures && loadFeatures(preloadedFeatures); - function MotionComponent(props, externalRef) { - var layoutId = useLayoutId(props); - props = tslib.__assign(tslib.__assign({}, props), { - layoutId: layoutId - }); - /** - * If we're rendering in a static environment, we only visually update the component - * as a result of a React-rerender rather than interactions or animations. This - * means we don't need to load additional memory structures like VisualElement, - * or any gesture/animation features. - */ - var config = React.useContext(MotionConfigContext); - var features = null; - var context = useCreateMotionContext(props); - /** - * Create a unique projection ID for this component. If a new component is added - * during a layout animation we'll use this to query the DOM and hydrate its ref early, allowing - * us to measure it as soon as any layout effect flushes pending layout animations. - * - * Performance note: It'd be better not to have to search the DOM for these elements. - * For newly-entering components it could be enough to only correct treeScale, in which - * case we could mount in a scale-correction mode. This wouldn't be enough for - * shared element transitions however. Perhaps for those we could revert to a root node - * that gets forceRendered and layout animations are triggered on its layout effect. - */ - var projectionId = config.isStatic ? undefined : useProjectionId(); - /** - * - */ - var visualState = useVisualState(props, config.isStatic); - if (!config.isStatic && isBrowser) { - /** - * Create a VisualElement for this component. A VisualElement provides a common - * interface to renderer-specific APIs (ie DOM/Three.js etc) as well as - * providing a way of rendering to these APIs outside of the React render loop - * for more performant animations and interactions - */ - context.visualElement = useVisualElement(Component, visualState, tslib.__assign(tslib.__assign({}, config), props), createVisualElement); - useProjection(projectionId, props, context.visualElement, projectionNodeConstructor || featureDefinitions.projectionNodeConstructor); - /** - * Load Motion gesture and animation features. These are rendered as renderless - * components so each feature can optionally make use of React lifecycle methods. - */ - features = useFeatures(props, context.visualElement, preloadedFeatures); - } - /** - * The mount order and hierarchy is specific to ensure our element ref - * is hydrated by the time features fire their effects. - */ - return React__namespace.createElement(VisualElementHandler, { - visualElement: context.visualElement, - props: tslib.__assign(tslib.__assign({}, config), props) - }, features, React__namespace.createElement(MotionContext.Provider, { - value: context - }, useRender(Component, props, projectionId, useMotionRef(visualState, context.visualElement, externalRef), visualState, config.isStatic, context.visualElement))); - } - return React.forwardRef(MotionComponent); -} -function useLayoutId(_a) { - var _b; - var layoutId = _a.layoutId; - var layoutGroupId = (_b = React.useContext(LayoutGroupContext)) === null || _b === void 0 ? void 0 : _b.id; - return layoutGroupId && layoutId !== undefined ? layoutGroupId + "-" + layoutId : layoutId; -} - -/** - * Convert any React component into a `motion` component. The provided component - * **must** use `React.forwardRef` to the underlying DOM component you want to animate. - * - * ```jsx - * const Component = React.forwardRef((props, ref) => { - * return
- * }) - * - * const MotionComponent = motion(Component) - * ``` - * - * @public - */ -function createMotionProxy(createConfig) { - function custom(Component, customMotionComponentConfig) { - if (customMotionComponentConfig === void 0) { - customMotionComponentConfig = {}; - } - return createMotionComponent(createConfig(Component, customMotionComponentConfig)); - } - if (typeof Proxy === "undefined") { - return custom; - } - /** - * A cache of generated `motion` components, e.g `motion.div`, `motion.input` etc. - * Rather than generating them anew every render. - */ - var componentCache = new Map(); - return new Proxy(custom, { - /** - * Called when `motion` is referenced with a prop: `motion.div`, `motion.input` etc. - * The prop name is passed through as `key` and we can use that to generate a `motion` - * DOM component with that name. - */ - get: function (_target, key) { - /** - * If this element doesn't exist in the component cache, create it and cache. - */ - if (!componentCache.has(key)) { - componentCache.set(key, custom(key)); - } - return componentCache.get(key); - } - }); -} - -/** - * We keep these listed seperately as we use the lowercase tag names as part - * of the runtime bundle to detect SVG components - */ -var lowercaseSVGElements = ["animate", "circle", "defs", "desc", "ellipse", "g", "image", "line", "filter", "marker", "mask", "metadata", "path", "pattern", "polygon", "polyline", "rect", "stop", "svg", "switch", "symbol", "text", "tspan", "use", "view"]; -function isSVGComponent(Component) { - if ( - /** - * If it's not a string, it's a custom React component. Currently we only support - * HTML custom React components. - */ - typeof Component !== "string" || - /** - * If it contains a dash, the element is a custom HTML webcomponent. - */ - Component.includes("-")) { - return false; - } else if ( - /** - * If it's in our list of lowercase SVG tags, it's an SVG component - */ - lowercaseSVGElements.indexOf(Component) > -1 || - /** - * If it contains a capital letter, it's an SVG component - */ - /[A-Z]/.test(Component)) { - return true; - } - return false; -} -var scaleCorrectors = {}; -function addScaleCorrector(correctors) { - Object.assign(scaleCorrectors, correctors); -} - -/** - * A list of all transformable axes. We'll use this list to generated a version - * of each axes for each transform. - */ -var transformAxes = ["", "X", "Y", "Z"]; -/** - * An ordered array of each transformable value. By default, transform values - * will be sorted to this order. - */ -var order = ["translate", "scale", "rotate", "skew"]; -/** - * Generate a list of every possible transform key. - */ -var transformProps = ["transformPerspective", "x", "y", "z"]; -order.forEach(function (operationKey) { - return transformAxes.forEach(function (axesKey) { - return transformProps.push(operationKey + axesKey); - }); -}); -/** - * A function to use with Array.sort to sort transform keys by their default order. - */ -function sortTransformProps(a, b) { - return transformProps.indexOf(a) - transformProps.indexOf(b); -} -/** - * A quick lookup for transform props. - */ -var transformPropSet = new Set(transformProps); -function isTransformProp(key) { - return transformPropSet.has(key); -} -/** - * A quick lookup for transform origin props - */ -var transformOriginProps = new Set(["originX", "originY", "originZ"]); -function isTransformOriginProp(key) { - return transformOriginProps.has(key); -} -function isForcedMotionValue(key, _a) { - var layout = _a.layout, - layoutId = _a.layoutId; - return isTransformProp(key) || isTransformOriginProp(key) || (layout || layoutId !== undefined) && (!!scaleCorrectors[key] || key === "opacity"); -} -var isMotionValue = function (value) { - return Boolean(value !== null && typeof value === "object" && value.getVelocity); -}; -var translateAlias = { - x: "translateX", - y: "translateY", - z: "translateZ", - transformPerspective: "perspective" -}; -/** - * Build a CSS transform style from individual x/y/scale etc properties. - * - * This outputs with a default order of transforms/scales/rotations, this can be customised by - * providing a transformTemplate function. - */ -function buildTransform(_a, _b, transformIsDefault, transformTemplate) { - var transform = _a.transform, - transformKeys = _a.transformKeys; - var _c = _b.enableHardwareAcceleration, - enableHardwareAcceleration = _c === void 0 ? true : _c, - _d = _b.allowTransformNone, - allowTransformNone = _d === void 0 ? true : _d; - // The transform string we're going to build into. - var transformString = ""; - // Transform keys into their default order - this will determine the output order. - transformKeys.sort(sortTransformProps); - // Track whether the defined transform has a defined z so we don't add a - // second to enable hardware acceleration - var transformHasZ = false; - // Loop over each transform and build them into transformString - var numTransformKeys = transformKeys.length; - for (var i = 0; i < numTransformKeys; i++) { - var key = transformKeys[i]; - transformString += "".concat(translateAlias[key] || key, "(").concat(transform[key], ") "); - if (key === "z") transformHasZ = true; - } - if (!transformHasZ && enableHardwareAcceleration) { - transformString += "translateZ(0)"; - } else { - transformString = transformString.trim(); - } - // If we have a custom `transform` template, pass our transform values and - // generated transformString to that before returning - if (transformTemplate) { - transformString = transformTemplate(transform, transformIsDefault ? "" : transformString); - } else if (allowTransformNone && transformIsDefault) { - transformString = "none"; - } - return transformString; -} -/** - * Build a transformOrigin style. Uses the same defaults as the browser for - * undefined origins. - */ -function buildTransformOrigin(_a) { - var _b = _a.originX, - originX = _b === void 0 ? "50%" : _b, - _c = _a.originY, - originY = _c === void 0 ? "50%" : _c, - _d = _a.originZ, - originZ = _d === void 0 ? 0 : _d; - return "".concat(originX, " ").concat(originY, " ").concat(originZ); -} - -/** - * Returns true if the provided key is a CSS variable - */ -function isCSSVariable$1(key) { - return key.startsWith("--"); -} - -/** - * Provided a value and a ValueType, returns the value as that value type. - */ -var getValueAsType = function (value, type) { - return type && typeof value === "number" ? type.transform(value) : value; -}; -var int = tslib.__assign(tslib.__assign({}, styleValueTypes.number), { - transform: Math.round -}); -var numberValueTypes = { - // Border props - borderWidth: styleValueTypes.px, - borderTopWidth: styleValueTypes.px, - borderRightWidth: styleValueTypes.px, - borderBottomWidth: styleValueTypes.px, - borderLeftWidth: styleValueTypes.px, - borderRadius: styleValueTypes.px, - radius: styleValueTypes.px, - borderTopLeftRadius: styleValueTypes.px, - borderTopRightRadius: styleValueTypes.px, - borderBottomRightRadius: styleValueTypes.px, - borderBottomLeftRadius: styleValueTypes.px, - // Positioning props - width: styleValueTypes.px, - maxWidth: styleValueTypes.px, - height: styleValueTypes.px, - maxHeight: styleValueTypes.px, - size: styleValueTypes.px, - top: styleValueTypes.px, - right: styleValueTypes.px, - bottom: styleValueTypes.px, - left: styleValueTypes.px, - // Spacing props - padding: styleValueTypes.px, - paddingTop: styleValueTypes.px, - paddingRight: styleValueTypes.px, - paddingBottom: styleValueTypes.px, - paddingLeft: styleValueTypes.px, - margin: styleValueTypes.px, - marginTop: styleValueTypes.px, - marginRight: styleValueTypes.px, - marginBottom: styleValueTypes.px, - marginLeft: styleValueTypes.px, - // Transform props - rotate: styleValueTypes.degrees, - rotateX: styleValueTypes.degrees, - rotateY: styleValueTypes.degrees, - rotateZ: styleValueTypes.degrees, - scale: styleValueTypes.scale, - scaleX: styleValueTypes.scale, - scaleY: styleValueTypes.scale, - scaleZ: styleValueTypes.scale, - skew: styleValueTypes.degrees, - skewX: styleValueTypes.degrees, - skewY: styleValueTypes.degrees, - distance: styleValueTypes.px, - translateX: styleValueTypes.px, - translateY: styleValueTypes.px, - translateZ: styleValueTypes.px, - x: styleValueTypes.px, - y: styleValueTypes.px, - z: styleValueTypes.px, - perspective: styleValueTypes.px, - transformPerspective: styleValueTypes.px, - opacity: styleValueTypes.alpha, - originX: styleValueTypes.progressPercentage, - originY: styleValueTypes.progressPercentage, - originZ: styleValueTypes.px, - // Misc - zIndex: int, - // SVG - fillOpacity: styleValueTypes.alpha, - strokeOpacity: styleValueTypes.alpha, - numOctaves: int -}; -function buildHTMLStyles(state, latestValues, options, transformTemplate) { - var _a; - var style = state.style, - vars = state.vars, - transform = state.transform, - transformKeys = state.transformKeys, - transformOrigin = state.transformOrigin; - // Empty the transformKeys array. As we're throwing out refs to its items - // this might not be as cheap as suspected. Maybe using the array as a buffer - // with a manual incrementation would be better. - transformKeys.length = 0; - // Track whether we encounter any transform or transformOrigin values. - var hasTransform = false; - var hasTransformOrigin = false; - // Does the calculated transform essentially equal "none"? - var transformIsNone = true; - /** - * Loop over all our latest animated values and decide whether to handle them - * as a style or CSS variable. - * - * Transforms and transform origins are kept seperately for further processing. - */ - for (var key in latestValues) { - var value = latestValues[key]; - /** - * If this is a CSS variable we don't do any further processing. - */ - if (isCSSVariable$1(key)) { - vars[key] = value; - continue; - } - // Convert the value to its default value type, ie 0 -> "0px" - var valueType = numberValueTypes[key]; - var valueAsType = getValueAsType(value, valueType); - if (isTransformProp(key)) { - // If this is a transform, flag to enable further transform processing - hasTransform = true; - transform[key] = valueAsType; - transformKeys.push(key); - // If we already know we have a non-default transform, early return - if (!transformIsNone) continue; - // Otherwise check to see if this is a default transform - if (value !== ((_a = valueType.default) !== null && _a !== void 0 ? _a : 0)) transformIsNone = false; - } else if (isTransformOriginProp(key)) { - transformOrigin[key] = valueAsType; - // If this is a transform origin, flag and enable further transform-origin processing - hasTransformOrigin = true; - } else { - style[key] = valueAsType; - } - } - if (hasTransform) { - style.transform = buildTransform(state, options, transformIsNone, transformTemplate); - } else if (transformTemplate) { - style.transform = transformTemplate({}, ""); - } else if (!latestValues.transform && style.transform) { - style.transform = "none"; - } - if (hasTransformOrigin) { - style.transformOrigin = buildTransformOrigin(transformOrigin); - } -} -var createHtmlRenderState = function () { - return { - style: {}, - transform: {}, - transformKeys: [], - transformOrigin: {}, - vars: {} - }; -}; -function copyRawValuesOnly(target, source, props) { - for (var key in source) { - if (!isMotionValue(source[key]) && !isForcedMotionValue(key, props)) { - target[key] = source[key]; - } - } -} -function useInitialMotionValues(_a, visualState, isStatic) { - var transformTemplate = _a.transformTemplate; - return React.useMemo(function () { - var state = createHtmlRenderState(); - buildHTMLStyles(state, visualState, { - enableHardwareAcceleration: !isStatic - }, transformTemplate); - var vars = state.vars, - style = state.style; - return tslib.__assign(tslib.__assign({}, vars), style); - }, [visualState]); -} -function useStyle(props, visualState, isStatic) { - var styleProp = props.style || {}; - var style = {}; - /** - * Copy non-Motion Values straight into style - */ - copyRawValuesOnly(style, styleProp, props); - Object.assign(style, useInitialMotionValues(props, visualState, isStatic)); - if (props.transformValues) { - style = props.transformValues(style); - } - return style; -} -function useHTMLProps(props, visualState, isStatic) { - // The `any` isn't ideal but it is the type of createElement props argument - var htmlProps = {}; - var style = useStyle(props, visualState, isStatic); - if (Boolean(props.drag) && props.dragListener !== false) { - // Disable the ghost element when a user drags - htmlProps.draggable = false; - // Disable text selection - style.userSelect = style.WebkitUserSelect = style.WebkitTouchCallout = "none"; - // Disable scrolling on the draggable direction - style.touchAction = props.drag === true ? "none" : "pan-".concat(props.drag === "x" ? "y" : "x"); - } - htmlProps.style = style; - return htmlProps; -} - -/** - * A list of all valid MotionProps. - * - * @privateRemarks - * This doesn't throw if a `MotionProp` name is missing - it should. - */ -var validMotionProps = new Set(["initial", "animate", "exit", "style", "variants", "transition", "transformTemplate", "transformValues", "custom", "inherit", "layout", "layoutId", "layoutDependency", "onLayoutAnimationStart", "onLayoutAnimationComplete", "onLayoutMeasure", "onBeforeLayoutMeasure", "onAnimationStart", "onAnimationComplete", "onUpdate", "onDragStart", "onDrag", "onDragEnd", "onMeasureDragConstraints", "onDirectionLock", "onDragTransitionEnd", "drag", "dragControls", "dragListener", "dragConstraints", "dragDirectionLock", "dragSnapToOrigin", "_dragX", "_dragY", "dragElastic", "dragMomentum", "dragPropagation", "dragTransition", "whileDrag", "onPan", "onPanStart", "onPanEnd", "onPanSessionStart", "onTap", "onTapStart", "onTapCancel", "onHoverStart", "onHoverEnd", "whileFocus", "whileTap", "whileHover", "whileInView", "onViewportEnter", "onViewportLeave", "viewport", "layoutScroll"]); -/** - * Check whether a prop name is a valid `MotionProp` key. - * - * @param key - Name of the property to check - * @returns `true` is key is a valid `MotionProp`. - * - * @public - */ -function isValidMotionProp(key) { - return validMotionProps.has(key); -} -var shouldForward = function (key) { - return !isValidMotionProp(key); -}; -function loadExternalIsValidProp(isValidProp) { - if (!isValidProp) return; - // Explicitly filter our events - shouldForward = function (key) { - return key.startsWith("on") ? !isValidMotionProp(key) : isValidProp(key); - }; -} -/** - * Emotion and Styled Components both allow users to pass through arbitrary props to their components - * to dynamically generate CSS. They both use the `@emotion/is-prop-valid` package to determine which - * of these should be passed to the underlying DOM node. - * - * However, when styling a Motion component `styled(motion.div)`, both packages pass through *all* props - * as it's seen as an arbitrary component rather than a DOM node. Motion only allows arbitrary props - * passed through the `custom` prop so it doesn't *need* the payload or computational overhead of - * `@emotion/is-prop-valid`, however to fix this problem we need to use it. - * - * By making it an optionalDependency we can offer this functionality only in the situations where it's - * actually required. - */ -try { - /** - * We attempt to import this package but require won't be defined in esm environments, in that case - * isPropValid will have to be provided via `MotionContext`. In a 6.0.0 this should probably be removed - * in favour of explicit injection. - */ - loadExternalIsValidProp((__webpack_require__(/*! @emotion/is-prop-valid */ "../../../node_modules/@emotion/is-prop-valid/dist/is-prop-valid.browser.esm.js")["default"])); -} catch (_a) { - // We don't need to actually do anything here - the fallback is the existing `isPropValid`. -} -function filterProps(props, isDom, forwardMotionProps) { - var filteredProps = {}; - for (var key in props) { - if (shouldForward(key) || forwardMotionProps === true && isValidMotionProp(key) || !isDom && !isValidMotionProp(key) || - // If trying to use native HTML drag events, forward drag listeners - props["draggable"] && key.startsWith("onDrag")) { - filteredProps[key] = props[key]; - } - } - return filteredProps; -} -function calcOrigin$1(origin, offset, size) { - return typeof origin === "string" ? origin : styleValueTypes.px.transform(offset + size * origin); -} -/** - * The SVG transform origin defaults are different to CSS and is less intuitive, - * so we use the measured dimensions of the SVG to reconcile these. - */ -function calcSVGTransformOrigin(dimensions, originX, originY) { - var pxOriginX = calcOrigin$1(originX, dimensions.x, dimensions.width); - var pxOriginY = calcOrigin$1(originY, dimensions.y, dimensions.height); - return "".concat(pxOriginX, " ").concat(pxOriginY); -} -var dashKeys = { - offset: "stroke-dashoffset", - array: "stroke-dasharray" -}; -var camelKeys = { - offset: "strokeDashoffset", - array: "strokeDasharray" -}; -/** - * Build SVG path properties. Uses the path's measured length to convert - * our custom pathLength, pathSpacing and pathOffset into stroke-dashoffset - * and stroke-dasharray attributes. - * - * This function is mutative to reduce per-frame GC. - */ -function buildSVGPath(attrs, length, spacing, offset, useDashCase) { - if (spacing === void 0) { - spacing = 1; - } - if (offset === void 0) { - offset = 0; - } - if (useDashCase === void 0) { - useDashCase = true; - } - // Normalise path length by setting SVG attribute pathLength to 1 - attrs.pathLength = 1; - // We use dash case when setting attributes directly to the DOM node and camel case - // when defining props on a React component. - var keys = useDashCase ? dashKeys : camelKeys; - // Build the dash offset - attrs[keys.offset] = styleValueTypes.px.transform(-offset); - // Build the dash array - var pathLength = styleValueTypes.px.transform(length); - var pathSpacing = styleValueTypes.px.transform(spacing); - attrs[keys.array] = "".concat(pathLength, " ").concat(pathSpacing); -} - -/** - * Build SVG visual attrbutes, like cx and style.transform - */ -function buildSVGAttrs(state, _a, options, transformTemplate) { - var attrX = _a.attrX, - attrY = _a.attrY, - originX = _a.originX, - originY = _a.originY, - pathLength = _a.pathLength, - _b = _a.pathSpacing, - pathSpacing = _b === void 0 ? 1 : _b, - _c = _a.pathOffset, - pathOffset = _c === void 0 ? 0 : _c, - // This is object creation, which we try to avoid per-frame. - latest = tslib.__rest(_a, ["attrX", "attrY", "originX", "originY", "pathLength", "pathSpacing", "pathOffset"]); - buildHTMLStyles(state, latest, options, transformTemplate); - state.attrs = state.style; - state.style = {}; - var attrs = state.attrs, - style = state.style, - dimensions = state.dimensions; - /** - * However, we apply transforms as CSS transforms. So if we detect a transform we take it from attrs - * and copy it into style. - */ - if (attrs.transform) { - if (dimensions) style.transform = attrs.transform; - delete attrs.transform; - } - // Parse transformOrigin - if (dimensions && (originX !== undefined || originY !== undefined || style.transform)) { - style.transformOrigin = calcSVGTransformOrigin(dimensions, originX !== undefined ? originX : 0.5, originY !== undefined ? originY : 0.5); - } - // Treat x/y not as shortcuts but as actual attributes - if (attrX !== undefined) attrs.x = attrX; - if (attrY !== undefined) attrs.y = attrY; - // Build SVG path if one has been defined - if (pathLength !== undefined) { - buildSVGPath(attrs, pathLength, pathSpacing, pathOffset, false); - } -} -var createSvgRenderState = function () { - return tslib.__assign(tslib.__assign({}, createHtmlRenderState()), { - attrs: {} - }); -}; -function useSVGProps(props, visualState) { - var visualProps = React.useMemo(function () { - var state = createSvgRenderState(); - buildSVGAttrs(state, visualState, { - enableHardwareAcceleration: false - }, props.transformTemplate); - return tslib.__assign(tslib.__assign({}, state.attrs), { - style: tslib.__assign({}, state.style) - }); - }, [visualState]); - if (props.style) { - var rawStyles = {}; - copyRawValuesOnly(rawStyles, props.style, props); - visualProps.style = tslib.__assign(tslib.__assign({}, rawStyles), visualProps.style); - } - return visualProps; -} -function createUseRender(forwardMotionProps) { - if (forwardMotionProps === void 0) { - forwardMotionProps = false; - } - var useRender = function (Component, props, projectionId, ref, _a, isStatic) { - var latestValues = _a.latestValues; - var useVisualProps = isSVGComponent(Component) ? useSVGProps : useHTMLProps; - var visualProps = useVisualProps(props, latestValues, isStatic); - var filteredProps = filterProps(props, typeof Component === "string", forwardMotionProps); - var elementProps = tslib.__assign(tslib.__assign(tslib.__assign({}, filteredProps), visualProps), { - ref: ref - }); - if (projectionId) { - elementProps["data-projection-id"] = projectionId; - } - return React.createElement(Component, elementProps); - }; - return useRender; -} -var CAMEL_CASE_PATTERN = /([a-z])([A-Z])/g; -var REPLACE_TEMPLATE = "$1-$2"; -/** - * Convert camelCase to dash-case properties. - */ -var camelToDash = function (str) { - return str.replace(CAMEL_CASE_PATTERN, REPLACE_TEMPLATE).toLowerCase(); -}; -function renderHTML(element, _a, styleProp, projection) { - var style = _a.style, - vars = _a.vars; - Object.assign(element.style, style, projection && projection.getProjectionStyles(styleProp)); - // Loop over any CSS variables and assign those. - for (var key in vars) { - element.style.setProperty(key, vars[key]); - } -} - -/** - * A set of attribute names that are always read/written as camel case. - */ -var camelCaseAttributes = new Set(["baseFrequency", "diffuseConstant", "kernelMatrix", "kernelUnitLength", "keySplines", "keyTimes", "limitingConeAngle", "markerHeight", "markerWidth", "numOctaves", "targetX", "targetY", "surfaceScale", "specularConstant", "specularExponent", "stdDeviation", "tableValues", "viewBox", "gradientTransform", "pathLength"]); -function renderSVG(element, renderState, _styleProp, projection) { - renderHTML(element, renderState, undefined, projection); - for (var key in renderState.attrs) { - element.setAttribute(!camelCaseAttributes.has(key) ? camelToDash(key) : key, renderState.attrs[key]); - } -} -function scrapeMotionValuesFromProps$1(props) { - var style = props.style; - var newValues = {}; - for (var key in style) { - if (isMotionValue(style[key]) || isForcedMotionValue(key, props)) { - newValues[key] = style[key]; - } - } - return newValues; -} -function scrapeMotionValuesFromProps(props) { - var newValues = scrapeMotionValuesFromProps$1(props); - for (var key in props) { - if (isMotionValue(props[key])) { - var targetKey = key === "x" || key === "y" ? "attr" + key.toUpperCase() : key; - newValues[targetKey] = props[key]; - } - } - return newValues; -} -function isAnimationControls(v) { - return typeof v === "object" && typeof v.start === "function"; -} -var isKeyframesTarget = function (v) { - return Array.isArray(v); -}; -var isCustomValue = function (v) { - return Boolean(v && typeof v === "object" && v.mix && v.toValue); -}; -var resolveFinalValueInKeyframes = function (v) { - // TODO maybe throw if v.length - 1 is placeholder token? - return isKeyframesTarget(v) ? v[v.length - 1] || 0 : v; -}; - -/** - * If the provided value is a MotionValue, this returns the actual value, otherwise just the value itself - * - * TODO: Remove and move to library - */ -function resolveMotionValue(value) { - var unwrappedValue = isMotionValue(value) ? value.get() : value; - return isCustomValue(unwrappedValue) ? unwrappedValue.toValue() : unwrappedValue; -} -function makeState(_a, props, context, presenceContext) { - var scrapeMotionValuesFromProps = _a.scrapeMotionValuesFromProps, - createRenderState = _a.createRenderState, - onMount = _a.onMount; - var state = { - latestValues: makeLatestValues(props, context, presenceContext, scrapeMotionValuesFromProps), - renderState: createRenderState() - }; - if (onMount) { - state.mount = function (instance) { - return onMount(props, instance, state); - }; - } - return state; -} -var makeUseVisualState = function (config) { - return function (props, isStatic) { - var context = React.useContext(MotionContext); - var presenceContext = React.useContext(PresenceContext); - return isStatic ? makeState(config, props, context, presenceContext) : useConstant(function () { - return makeState(config, props, context, presenceContext); - }); - }; -}; -function makeLatestValues(props, context, presenceContext, scrapeMotionValues) { - var values = {}; - var blockInitialAnimation = (presenceContext === null || presenceContext === void 0 ? void 0 : presenceContext.initial) === false; - var motionValues = scrapeMotionValues(props); - for (var key in motionValues) { - values[key] = resolveMotionValue(motionValues[key]); - } - var initial = props.initial, - animate = props.animate; - var isControllingVariants = checkIfControllingVariants(props); - var isVariantNode = checkIfVariantNode(props); - if (context && isVariantNode && !isControllingVariants && props.inherit !== false) { - initial !== null && initial !== void 0 ? initial : initial = context.initial; - animate !== null && animate !== void 0 ? animate : animate = context.animate; - } - var initialAnimationIsBlocked = blockInitialAnimation || initial === false; - var variantToSet = initialAnimationIsBlocked ? animate : initial; - if (variantToSet && typeof variantToSet !== "boolean" && !isAnimationControls(variantToSet)) { - var list = Array.isArray(variantToSet) ? variantToSet : [variantToSet]; - list.forEach(function (definition) { - var resolved = resolveVariantFromProps(props, definition); - if (!resolved) return; - var transitionEnd = resolved.transitionEnd; - resolved.transition; - var target = tslib.__rest(resolved, ["transitionEnd", "transition"]); - for (var key in target) { - var valueTarget = target[key]; - if (Array.isArray(valueTarget)) { - /** - * Take final keyframe if the initial animation is blocked because - * we want to initialise at the end of that blocked animation. - */ - var index = initialAnimationIsBlocked ? valueTarget.length - 1 : 0; - valueTarget = valueTarget[index]; - } - if (valueTarget !== null) { - values[key] = valueTarget; - } - } - for (var key in transitionEnd) values[key] = transitionEnd[key]; - }); - } - return values; -} -var svgMotionConfig = { - useVisualState: makeUseVisualState({ - scrapeMotionValuesFromProps: scrapeMotionValuesFromProps, - createRenderState: createSvgRenderState, - onMount: function (props, instance, _a) { - var renderState = _a.renderState, - latestValues = _a.latestValues; - try { - renderState.dimensions = typeof instance.getBBox === "function" ? instance.getBBox() : instance.getBoundingClientRect(); - } catch (e) { - // Most likely trying to measure an unrendered element under Firefox - renderState.dimensions = { - x: 0, - y: 0, - width: 0, - height: 0 - }; - } - buildSVGAttrs(renderState, latestValues, { - enableHardwareAcceleration: false - }, props.transformTemplate); - renderSVG(instance, renderState); - } - }) -}; -var htmlMotionConfig = { - useVisualState: makeUseVisualState({ - scrapeMotionValuesFromProps: scrapeMotionValuesFromProps$1, - createRenderState: createHtmlRenderState - }) -}; -function createDomMotionConfig(Component, _a, preloadedFeatures, createVisualElement, projectionNodeConstructor) { - var _b = _a.forwardMotionProps, - forwardMotionProps = _b === void 0 ? false : _b; - var baseConfig = isSVGComponent(Component) ? svgMotionConfig : htmlMotionConfig; - return tslib.__assign(tslib.__assign({}, baseConfig), { - preloadedFeatures: preloadedFeatures, - useRender: createUseRender(forwardMotionProps), - createVisualElement: createVisualElement, - projectionNodeConstructor: projectionNodeConstructor, - Component: Component - }); -} -exports.AnimationType = void 0; -(function (AnimationType) { - AnimationType["Animate"] = "animate"; - AnimationType["Hover"] = "whileHover"; - AnimationType["Tap"] = "whileTap"; - AnimationType["Drag"] = "whileDrag"; - AnimationType["Focus"] = "whileFocus"; - AnimationType["InView"] = "whileInView"; - AnimationType["Exit"] = "exit"; -})(exports.AnimationType || (exports.AnimationType = {})); -function addDomEvent(target, eventName, handler, options) { - if (options === void 0) { - options = { - passive: true - }; - } - target.addEventListener(eventName, handler, options); - return function () { - return target.removeEventListener(eventName, handler); - }; -} -/** - * Attaches an event listener directly to the provided DOM element. - * - * Bypassing React's event system can be desirable, for instance when attaching non-passive - * event handlers. - * - * ```jsx - * const ref = useRef(null) - * - * useDomEvent(ref, 'wheel', onWheel, { passive: false }) - * - * return
- * ``` - * - * @param ref - React.RefObject that's been provided to the element you want to bind the listener to. - * @param eventName - Name of the event you want listen for. - * @param handler - Function to fire when receiving the event. - * @param options - Options to pass to `Event.addEventListener`. - * - * @public - */ -function useDomEvent(ref, eventName, handler, options) { - React.useEffect(function () { - var element = ref.current; - if (handler && element) { - return addDomEvent(element, eventName, handler, options); - } - }, [ref, eventName, handler, options]); -} - -/** - * - * @param props - * @param ref - * @internal - */ -function useFocusGesture(_a) { - var whileFocus = _a.whileFocus, - visualElement = _a.visualElement; - var onFocus = function () { - var _a; - (_a = visualElement.animationState) === null || _a === void 0 ? void 0 : _a.setActive(exports.AnimationType.Focus, true); - }; - var onBlur = function () { - var _a; - (_a = visualElement.animationState) === null || _a === void 0 ? void 0 : _a.setActive(exports.AnimationType.Focus, false); - }; - useDomEvent(visualElement, "focus", whileFocus ? onFocus : undefined); - useDomEvent(visualElement, "blur", whileFocus ? onBlur : undefined); -} -function isMouseEvent(event) { - // PointerEvent inherits from MouseEvent so we can't use a straight instanceof check. - if (typeof PointerEvent !== "undefined" && event instanceof PointerEvent) { - return !!(event.pointerType === "mouse"); - } - return event instanceof MouseEvent; -} -function isTouchEvent(event) { - var hasTouches = !!event.touches; - return hasTouches; -} - -/** - * Filters out events not attached to the primary pointer (currently left mouse button) - * @param eventHandler - */ -function filterPrimaryPointer(eventHandler) { - return function (event) { - var isMouseEvent = event instanceof MouseEvent; - var isPrimaryPointer = !isMouseEvent || isMouseEvent && event.button === 0; - if (isPrimaryPointer) { - eventHandler(event); - } - }; -} -var defaultPagePoint = { - pageX: 0, - pageY: 0 -}; -function pointFromTouch(e, pointType) { - if (pointType === void 0) { - pointType = "page"; - } - var primaryTouch = e.touches[0] || e.changedTouches[0]; - var point = primaryTouch || defaultPagePoint; - return { - x: point[pointType + "X"], - y: point[pointType + "Y"] - }; -} -function pointFromMouse(point, pointType) { - if (pointType === void 0) { - pointType = "page"; - } - return { - x: point[pointType + "X"], - y: point[pointType + "Y"] - }; -} -function extractEventInfo(event, pointType) { - if (pointType === void 0) { - pointType = "page"; - } - return { - point: isTouchEvent(event) ? pointFromTouch(event, pointType) : pointFromMouse(event, pointType) - }; -} -var wrapHandler = function (handler, shouldFilterPrimaryPointer) { - if (shouldFilterPrimaryPointer === void 0) { - shouldFilterPrimaryPointer = false; - } - var listener = function (event) { - return handler(event, extractEventInfo(event)); - }; - return shouldFilterPrimaryPointer ? filterPrimaryPointer(listener) : listener; -}; - -// We check for event support via functions in case they've been mocked by a testing suite. -var supportsPointerEvents = function () { - return isBrowser && window.onpointerdown === null; -}; -var supportsTouchEvents = function () { - return isBrowser && window.ontouchstart === null; -}; -var supportsMouseEvents = function () { - return isBrowser && window.onmousedown === null; -}; -var mouseEventNames = { - pointerdown: "mousedown", - pointermove: "mousemove", - pointerup: "mouseup", - pointercancel: "mousecancel", - pointerover: "mouseover", - pointerout: "mouseout", - pointerenter: "mouseenter", - pointerleave: "mouseleave" -}; -var touchEventNames = { - pointerdown: "touchstart", - pointermove: "touchmove", - pointerup: "touchend", - pointercancel: "touchcancel" -}; -function getPointerEventName(name) { - if (supportsPointerEvents()) { - return name; - } else if (supportsTouchEvents()) { - return touchEventNames[name]; - } else if (supportsMouseEvents()) { - return mouseEventNames[name]; - } - return name; -} -function addPointerEvent(target, eventName, handler, options) { - return addDomEvent(target, getPointerEventName(eventName), wrapHandler(handler, eventName === "pointerdown"), options); -} -function usePointerEvent(ref, eventName, handler, options) { - return useDomEvent(ref, getPointerEventName(eventName), handler && wrapHandler(handler, eventName === "pointerdown"), options); -} -function createLock(name) { - var lock = null; - return function () { - var openLock = function () { - lock = null; - }; - if (lock === null) { - lock = name; - return openLock; - } - return false; - }; -} -var globalHorizontalLock = createLock("dragHorizontal"); -var globalVerticalLock = createLock("dragVertical"); -function getGlobalLock(drag) { - var lock = false; - if (drag === "y") { - lock = globalVerticalLock(); - } else if (drag === "x") { - lock = globalHorizontalLock(); - } else { - var openHorizontal_1 = globalHorizontalLock(); - var openVertical_1 = globalVerticalLock(); - if (openHorizontal_1 && openVertical_1) { - lock = function () { - openHorizontal_1(); - openVertical_1(); - }; - } else { - // Release the locks because we don't use them - if (openHorizontal_1) openHorizontal_1(); - if (openVertical_1) openVertical_1(); - } - } - return lock; -} -function isDragActive() { - // Check the gesture lock - if we get it, it means no drag gesture is active - // and we can safely fire the tap gesture. - var openGestureLock = getGlobalLock(true); - if (!openGestureLock) return true; - openGestureLock(); - return false; -} -function createHoverEvent(visualElement, isActive, callback) { - return function (event, info) { - var _a; - if (!isMouseEvent(event) || isDragActive()) return; - /** - * Ensure we trigger animations before firing event callback - */ - (_a = visualElement.animationState) === null || _a === void 0 ? void 0 : _a.setActive(exports.AnimationType.Hover, isActive); - callback === null || callback === void 0 ? void 0 : callback(event, info); - }; -} -function useHoverGesture(_a) { - var onHoverStart = _a.onHoverStart, - onHoverEnd = _a.onHoverEnd, - whileHover = _a.whileHover, - visualElement = _a.visualElement; - usePointerEvent(visualElement, "pointerenter", onHoverStart || whileHover ? createHoverEvent(visualElement, true, onHoverStart) : undefined, { - passive: !onHoverStart - }); - usePointerEvent(visualElement, "pointerleave", onHoverEnd || whileHover ? createHoverEvent(visualElement, false, onHoverEnd) : undefined, { - passive: !onHoverEnd - }); -} - -/** - * Recursively traverse up the tree to check whether the provided child node - * is the parent or a descendant of it. - * - * @param parent - Element to find - * @param child - Element to test against parent - */ -var isNodeOrChild = function (parent, child) { - if (!child) { - return false; - } else if (parent === child) { - return true; - } else { - return isNodeOrChild(parent, child.parentElement); - } -}; -function useUnmountEffect(callback) { - return React.useEffect(function () { - return function () { - return callback(); - }; - }, []); -} - -/** - * @param handlers - - * @internal - */ -function useTapGesture(_a) { - var onTap = _a.onTap, - onTapStart = _a.onTapStart, - onTapCancel = _a.onTapCancel, - whileTap = _a.whileTap, - visualElement = _a.visualElement; - var hasPressListeners = onTap || onTapStart || onTapCancel || whileTap; - var isPressing = React.useRef(false); - var cancelPointerEndListeners = React.useRef(null); - /** - * Only set listener to passive if there are no external listeners. - */ - var eventOptions = { - passive: !(onTapStart || onTap || onTapCancel || onPointerDown) - }; - function removePointerEndListener() { - var _a; - (_a = cancelPointerEndListeners.current) === null || _a === void 0 ? void 0 : _a.call(cancelPointerEndListeners); - cancelPointerEndListeners.current = null; - } - function checkPointerEnd() { - var _a; - removePointerEndListener(); - isPressing.current = false; - (_a = visualElement.animationState) === null || _a === void 0 ? void 0 : _a.setActive(exports.AnimationType.Tap, false); - return !isDragActive(); - } - function onPointerUp(event, info) { - if (!checkPointerEnd()) return; - /** - * We only count this as a tap gesture if the event.target is the same - * as, or a child of, this component's element - */ - !isNodeOrChild(visualElement.getInstance(), event.target) ? onTapCancel === null || onTapCancel === void 0 ? void 0 : onTapCancel(event, info) : onTap === null || onTap === void 0 ? void 0 : onTap(event, info); - } - function onPointerCancel(event, info) { - if (!checkPointerEnd()) return; - onTapCancel === null || onTapCancel === void 0 ? void 0 : onTapCancel(event, info); - } - function onPointerDown(event, info) { - var _a; - removePointerEndListener(); - if (isPressing.current) return; - isPressing.current = true; - cancelPointerEndListeners.current = popmotion.pipe(addPointerEvent(window, "pointerup", onPointerUp, eventOptions), addPointerEvent(window, "pointercancel", onPointerCancel, eventOptions)); - /** - * Ensure we trigger animations before firing event callback - */ - (_a = visualElement.animationState) === null || _a === void 0 ? void 0 : _a.setActive(exports.AnimationType.Tap, true); - onTapStart === null || onTapStart === void 0 ? void 0 : onTapStart(event, info); - } - usePointerEvent(visualElement, "pointerdown", hasPressListeners ? onPointerDown : undefined, eventOptions); - useUnmountEffect(removePointerEndListener); -} -var warned = new Set(); -function warnOnce(condition, message, element) { - if (condition || warned.has(message)) return; - console.warn(message); - if (element) console.warn(element); - warned.add(message); -} - -/** - * Map an IntersectionHandler callback to an element. We only ever make one handler for one - * element, so even though these handlers might all be triggered by different - * observers, we can keep them in the same map. - */ -var observerCallbacks = new WeakMap(); -/** - * Multiple observers can be created for multiple element/document roots. Each with - * different settings. So here we store dictionaries of observers to each root, - * using serialised settings (threshold/margin) as lookup keys. - */ -var observers = new WeakMap(); -var fireObserverCallback = function (entry) { - var _a; - (_a = observerCallbacks.get(entry.target)) === null || _a === void 0 ? void 0 : _a(entry); -}; -var fireAllObserverCallbacks = function (entries) { - entries.forEach(fireObserverCallback); -}; -function initIntersectionObserver(_a) { - var root = _a.root, - options = tslib.__rest(_a, ["root"]); - var lookupRoot = root || document; - /** - * If we don't have an observer lookup map for this root, create one. - */ - if (!observers.has(lookupRoot)) { - observers.set(lookupRoot, {}); - } - var rootObservers = observers.get(lookupRoot); - var key = JSON.stringify(options); - /** - * If we don't have an observer for this combination of root and settings, - * create one. - */ - if (!rootObservers[key]) { - rootObservers[key] = new IntersectionObserver(fireAllObserverCallbacks, tslib.__assign({ - root: root - }, options)); - } - return rootObservers[key]; -} -function observeIntersection(element, options, callback) { - var rootInteresectionObserver = initIntersectionObserver(options); - observerCallbacks.set(element, callback); - rootInteresectionObserver.observe(element); - return function () { - observerCallbacks.delete(element); - rootInteresectionObserver.unobserve(element); - }; -} -function useViewport(_a) { - var visualElement = _a.visualElement, - whileInView = _a.whileInView, - onViewportEnter = _a.onViewportEnter, - onViewportLeave = _a.onViewportLeave, - _b = _a.viewport, - viewport = _b === void 0 ? {} : _b; - var state = React.useRef({ - hasEnteredView: false, - isInView: false - }); - var shouldObserve = Boolean(whileInView || onViewportEnter || onViewportLeave); - if (viewport.once && state.current.hasEnteredView) shouldObserve = false; - var useObserver = typeof IntersectionObserver === "undefined" ? useMissingIntersectionObserver : useIntersectionObserver; - useObserver(shouldObserve, state.current, visualElement, viewport); -} -var thresholdNames = { - some: 0, - all: 1 -}; -function useIntersectionObserver(shouldObserve, state, visualElement, _a) { - var root = _a.root, - rootMargin = _a.margin, - _b = _a.amount, - amount = _b === void 0 ? "some" : _b, - once = _a.once; - React.useEffect(function () { - if (!shouldObserve) return; - var options = { - root: root === null || root === void 0 ? void 0 : root.current, - rootMargin: rootMargin, - threshold: typeof amount === "number" ? amount : thresholdNames[amount] - }; - var intersectionCallback = function (entry) { - var _a; - var isIntersecting = entry.isIntersecting; - /** - * If there's been no change in the viewport state, early return. - */ - if (state.isInView === isIntersecting) return; - state.isInView = isIntersecting; - /** - * Handle hasEnteredView. If this is only meant to run once, and - * element isn't visible, early return. Otherwise set hasEnteredView to true. - */ - if (once && !isIntersecting && state.hasEnteredView) { - return; - } else if (isIntersecting) { - state.hasEnteredView = true; - } - (_a = visualElement.animationState) === null || _a === void 0 ? void 0 : _a.setActive(exports.AnimationType.InView, isIntersecting); - /** - * Use the latest committed props rather than the ones in scope - * when this observer is created - */ - var props = visualElement.getProps(); - var callback = isIntersecting ? props.onViewportEnter : props.onViewportLeave; - callback === null || callback === void 0 ? void 0 : callback(entry); - }; - return observeIntersection(visualElement.getInstance(), options, intersectionCallback); - }, [shouldObserve, root, rootMargin, amount]); -} -/** - * If IntersectionObserver is missing, we activate inView and fire onViewportEnter - * on mount. This way, the page will be in the state the author expects users - * to see it in for everyone. - */ -function useMissingIntersectionObserver(shouldObserve, state, visualElement, _a) { - var _b = _a.fallback, - fallback = _b === void 0 ? true : _b; - React.useEffect(function () { - if (!shouldObserve || !fallback) return; - if (env !== "production") { - warnOnce(false, "IntersectionObserver not available on this device. whileInView animations will trigger on mount."); - } - /** - * Fire this in an rAF because, at this point, the animation state - * won't have flushed for the first time and there's certain logic in - * there that behaves differently on the initial animation. - * - * This hook should be quite rarely called so setting this in an rAF - * is preferred to changing the behaviour of the animation state. - */ - requestAnimationFrame(function () { - var _a; - state.hasEnteredView = true; - var onViewportEnter = visualElement.getProps().onViewportEnter; - onViewportEnter === null || onViewportEnter === void 0 ? void 0 : onViewportEnter(null); - (_a = visualElement.animationState) === null || _a === void 0 ? void 0 : _a.setActive(exports.AnimationType.InView, true); - }); - }, [shouldObserve]); -} -var makeRenderlessComponent = function (hook) { - return function (props) { - hook(props); - return null; - }; -}; -var gestureAnimations = { - inView: makeRenderlessComponent(useViewport), - tap: makeRenderlessComponent(useTapGesture), - focus: makeRenderlessComponent(useFocusGesture), - hover: makeRenderlessComponent(useHoverGesture) -}; -var counter = 0; -var incrementId = function () { - return counter++; -}; -var useId = function () { - return useConstant(incrementId); -}; -/** - * Ideally we'd use the following code to support React 18 optionally. - * But this fairly fails in Webpack (otherwise treeshaking wouldn't work at all). - * Need to come up with a different way of figuring this out. - */ -// export const useId = (React as any).useId -// ? (React as any).useId -// : () => useConstant(incrementId) - -/** - * When a component is the child of `AnimatePresence`, it can use `usePresence` - * to access information about whether it's still present in the React tree. - * - * ```jsx - * import { usePresence } from "framer-motion" - * - * export const Component = () => { - * const [isPresent, safeToRemove] = usePresence() - * - * useEffect(() => { - * !isPresent && setTimeout(safeToRemove, 1000) - * }, [isPresent]) - * - * return
- * } - * ``` - * - * If `isPresent` is `false`, it means that a component has been removed the tree, but - * `AnimatePresence` won't really remove it until `safeToRemove` has been called. - * - * @public - */ -function usePresence() { - var context = React.useContext(PresenceContext); - if (context === null) return [true, null]; - var isPresent = context.isPresent, - onExitComplete = context.onExitComplete, - register = context.register; - // It's safe to call the following hooks conditionally (after an early return) because the context will always - // either be null or non-null for the lifespan of the component. - // Replace with useId when released in React - var id = useId(); - React.useEffect(function () { - return register(id); - }, []); - var safeToRemove = function () { - return onExitComplete === null || onExitComplete === void 0 ? void 0 : onExitComplete(id); - }; - return !isPresent && onExitComplete ? [false, safeToRemove] : [true]; -} -/** - * Similar to `usePresence`, except `useIsPresent` simply returns whether or not the component is present. - * There is no `safeToRemove` function. - * - * ```jsx - * import { useIsPresent } from "framer-motion" - * - * export const Component = () => { - * const isPresent = useIsPresent() - * - * useEffect(() => { - * !isPresent && console.log("I've been removed!") - * }, [isPresent]) - * - * return
- * } - * ``` - * - * @public - */ -function useIsPresent() { - return isPresent(React.useContext(PresenceContext)); -} -function isPresent(context) { - return context === null ? true : context.isPresent; -} -function shallowCompare(next, prev) { - if (!Array.isArray(prev)) return false; - var prevLength = prev.length; - if (prevLength !== next.length) return false; - for (var i = 0; i < prevLength; i++) { - if (prev[i] !== next[i]) return false; - } - return true; -} - -/** - * Converts seconds to milliseconds - * - * @param seconds - Time in seconds. - * @return milliseconds - Converted time in milliseconds. - */ -var secondsToMilliseconds = function (seconds) { - return seconds * 1000; -}; -var easingLookup = { - linear: popmotion.linear, - easeIn: popmotion.easeIn, - easeInOut: popmotion.easeInOut, - easeOut: popmotion.easeOut, - circIn: popmotion.circIn, - circInOut: popmotion.circInOut, - circOut: popmotion.circOut, - backIn: popmotion.backIn, - backInOut: popmotion.backInOut, - backOut: popmotion.backOut, - anticipate: popmotion.anticipate, - bounceIn: popmotion.bounceIn, - bounceInOut: popmotion.bounceInOut, - bounceOut: popmotion.bounceOut -}; -var easingDefinitionToFunction = function (definition) { - if (Array.isArray(definition)) { - // If cubic bezier definition, create bezier curve - heyListen.invariant(definition.length === 4, "Cubic bezier arrays must contain four numerical values."); - var _a = tslib.__read(definition, 4), - x1 = _a[0], - y1 = _a[1], - x2 = _a[2], - y2 = _a[3]; - return popmotion.cubicBezier(x1, y1, x2, y2); - } else if (typeof definition === "string") { - // Else lookup from table - heyListen.invariant(easingLookup[definition] !== undefined, "Invalid easing type '".concat(definition, "'")); - return easingLookup[definition]; - } - return definition; -}; -var isEasingArray = function (ease) { - return Array.isArray(ease) && typeof ease[0] !== "number"; -}; - -/** - * Check if a value is animatable. Examples: - * - * ✅: 100, "100px", "#fff" - * ❌: "block", "url(2.jpg)" - * @param value - * - * @internal - */ -var isAnimatable = function (key, value) { - // If the list of keys tat might be non-animatable grows, replace with Set - if (key === "zIndex") return false; - // If it's a number or a keyframes array, we can animate it. We might at some point - // need to do a deep isAnimatable check of keyframes, or let Popmotion handle this, - // but for now lets leave it like this for performance reasons - if (typeof value === "number" || Array.isArray(value)) return true; - if (typeof value === "string" && - // It's animatable if we have a string - styleValueTypes.complex.test(value) && - // And it contains numbers and/or colors - !value.startsWith("url(") // Unless it starts with "url(" - ) { - return true; - } - return false; -}; -var underDampedSpring = function () { - return { - type: "spring", - stiffness: 500, - damping: 25, - restSpeed: 10 - }; -}; -var criticallyDampedSpring = function (to) { - return { - type: "spring", - stiffness: 550, - damping: to === 0 ? 2 * Math.sqrt(550) : 30, - restSpeed: 10 - }; -}; -var linearTween = function () { - return { - type: "keyframes", - ease: "linear", - duration: 0.3 - }; -}; -var keyframes = function (values) { - return { - type: "keyframes", - duration: 0.8, - values: values - }; -}; -var defaultTransitions = { - x: underDampedSpring, - y: underDampedSpring, - z: underDampedSpring, - rotate: underDampedSpring, - rotateX: underDampedSpring, - rotateY: underDampedSpring, - rotateZ: underDampedSpring, - scaleX: criticallyDampedSpring, - scaleY: criticallyDampedSpring, - scale: criticallyDampedSpring, - opacity: linearTween, - backgroundColor: linearTween, - color: linearTween, - default: criticallyDampedSpring -}; -var getDefaultTransition = function (valueKey, to) { - var transitionFactory; - if (isKeyframesTarget(to)) { - transitionFactory = keyframes; - } else { - transitionFactory = defaultTransitions[valueKey] || defaultTransitions.default; - } - return tslib.__assign({ - to: to - }, transitionFactory(to)); -}; - -/** - * A map of default value types for common values - */ -var defaultValueTypes = tslib.__assign(tslib.__assign({}, numberValueTypes), { - // Color props - color: styleValueTypes.color, - backgroundColor: styleValueTypes.color, - outlineColor: styleValueTypes.color, - fill: styleValueTypes.color, - stroke: styleValueTypes.color, - // Border props - borderColor: styleValueTypes.color, - borderTopColor: styleValueTypes.color, - borderRightColor: styleValueTypes.color, - borderBottomColor: styleValueTypes.color, - borderLeftColor: styleValueTypes.color, - filter: styleValueTypes.filter, - WebkitFilter: styleValueTypes.filter -}); -/** - * Gets the default ValueType for the provided value key - */ -var getDefaultValueType = function (key) { - return defaultValueTypes[key]; -}; -function getAnimatableNone(key, value) { - var _a; - var defaultValueType = getDefaultValueType(key); - if (defaultValueType !== styleValueTypes.filter) defaultValueType = styleValueTypes.complex; - // If value is not recognised as animatable, ie "none", create an animatable version origin based on the target - return (_a = defaultValueType.getAnimatableNone) === null || _a === void 0 ? void 0 : _a.call(defaultValueType, value); -} -var instantAnimationState = { - current: false -}; - -/** - * Decide whether a transition is defined on a given Transition. - * This filters out orchestration options and returns true - * if any options are left. - */ -function isTransitionDefined(_a) { - _a.when; - _a.delay; - _a.delayChildren; - _a.staggerChildren; - _a.staggerDirection; - _a.repeat; - _a.repeatType; - _a.repeatDelay; - _a.from; - var transition = tslib.__rest(_a, ["when", "delay", "delayChildren", "staggerChildren", "staggerDirection", "repeat", "repeatType", "repeatDelay", "from"]); - return !!Object.keys(transition).length; -} -var legacyRepeatWarning = false; -/** - * Convert Framer Motion's Transition type into Popmotion-compatible options. - */ -function convertTransitionToAnimationOptions(_a) { - var ease = _a.ease, - times = _a.times, - yoyo = _a.yoyo, - flip = _a.flip, - loop = _a.loop, - transition = tslib.__rest(_a, ["ease", "times", "yoyo", "flip", "loop"]); - var options = tslib.__assign({}, transition); - if (times) options["offset"] = times; - /** - * Convert any existing durations from seconds to milliseconds - */ - if (transition.duration) options["duration"] = secondsToMilliseconds(transition.duration); - if (transition.repeatDelay) options.repeatDelay = secondsToMilliseconds(transition.repeatDelay); - /** - * Map easing names to Popmotion's easing functions - */ - if (ease) { - options["ease"] = isEasingArray(ease) ? ease.map(easingDefinitionToFunction) : easingDefinitionToFunction(ease); - } - /** - * Support legacy transition API - */ - if (transition.type === "tween") options.type = "keyframes"; - /** - * TODO: These options are officially removed from the API. - */ - if (yoyo || loop || flip) { - heyListen.warning(!legacyRepeatWarning, "yoyo, loop and flip have been removed from the API. Replace with repeat and repeatType options."); - legacyRepeatWarning = true; - if (yoyo) { - options.repeatType = "reverse"; - } else if (loop) { - options.repeatType = "loop"; - } else if (flip) { - options.repeatType = "mirror"; - } - options.repeat = loop || yoyo || flip || transition.repeat; - } - /** - * TODO: Popmotion 9 has the ability to automatically detect whether to use - * a keyframes or spring animation, but does so by detecting velocity and other spring options. - * It'd be good to introduce a similar thing here. - */ - if (transition.type !== "spring") options.type = "keyframes"; - return options; -} -/** - * Get the delay for a value by checking Transition with decreasing specificity. - */ -function getDelayFromTransition(transition, key) { - var _a, _b; - var valueTransition = getValueTransition(transition, key) || {}; - return (_b = (_a = valueTransition.delay) !== null && _a !== void 0 ? _a : transition.delay) !== null && _b !== void 0 ? _b : 0; -} -function hydrateKeyframes(options) { - if (Array.isArray(options.to) && options.to[0] === null) { - options.to = tslib.__spreadArray([], tslib.__read(options.to), false); - options.to[0] = options.from; - } - return options; -} -function getPopmotionAnimationOptions(transition, options, key) { - var _a; - if (Array.isArray(options.to)) { - (_a = transition.duration) !== null && _a !== void 0 ? _a : transition.duration = 0.8; - } - hydrateKeyframes(options); - /** - * Get a default transition if none is determined to be defined. - */ - if (!isTransitionDefined(transition)) { - transition = tslib.__assign(tslib.__assign({}, transition), getDefaultTransition(key, options.to)); - } - return tslib.__assign(tslib.__assign({}, options), convertTransitionToAnimationOptions(transition)); -} -/** - * - */ -function getAnimation(key, value, target, transition, onComplete) { - var _a; - var valueTransition = getValueTransition(transition, key); - var origin = (_a = valueTransition.from) !== null && _a !== void 0 ? _a : value.get(); - var isTargetAnimatable = isAnimatable(key, target); - if (origin === "none" && isTargetAnimatable && typeof target === "string") { - /** - * If we're trying to animate from "none", try and get an animatable version - * of the target. This could be improved to work both ways. - */ - origin = getAnimatableNone(key, target); - } else if (isZero(origin) && typeof target === "string") { - origin = getZeroUnit(target); - } else if (!Array.isArray(target) && isZero(target) && typeof origin === "string") { - target = getZeroUnit(origin); - } - var isOriginAnimatable = isAnimatable(key, origin); - heyListen.warning(isOriginAnimatable === isTargetAnimatable, "You are trying to animate ".concat(key, " from \"").concat(origin, "\" to \"").concat(target, "\". ").concat(origin, " is not an animatable value - to enable this animation set ").concat(origin, " to a value animatable to ").concat(target, " via the `style` property.")); - function start() { - var options = { - from: origin, - to: target, - velocity: value.getVelocity(), - onComplete: onComplete, - onUpdate: function (v) { - return value.set(v); - } - }; - return valueTransition.type === "inertia" || valueTransition.type === "decay" ? popmotion.inertia(tslib.__assign(tslib.__assign({}, options), valueTransition)) : popmotion.animate(tslib.__assign(tslib.__assign({}, getPopmotionAnimationOptions(valueTransition, options, key)), { - onUpdate: function (v) { - var _a; - options.onUpdate(v); - (_a = valueTransition.onUpdate) === null || _a === void 0 ? void 0 : _a.call(valueTransition, v); - }, - onComplete: function () { - var _a; - options.onComplete(); - (_a = valueTransition.onComplete) === null || _a === void 0 ? void 0 : _a.call(valueTransition); - } - })); - } - function set() { - var _a, _b; - var finalTarget = resolveFinalValueInKeyframes(target); - value.set(finalTarget); - onComplete(); - (_a = valueTransition === null || valueTransition === void 0 ? void 0 : valueTransition.onUpdate) === null || _a === void 0 ? void 0 : _a.call(valueTransition, finalTarget); - (_b = valueTransition === null || valueTransition === void 0 ? void 0 : valueTransition.onComplete) === null || _b === void 0 ? void 0 : _b.call(valueTransition); - return { - stop: function () {} - }; - } - return !isOriginAnimatable || !isTargetAnimatable || valueTransition.type === false ? set : start; -} -function isZero(value) { - return value === 0 || typeof value === "string" && parseFloat(value) === 0 && value.indexOf(" ") === -1; -} -function getZeroUnit(potentialUnitType) { - return typeof potentialUnitType === "number" ? 0 : getAnimatableNone("", potentialUnitType); -} -function getValueTransition(transition, key) { - return transition[key] || transition["default"] || transition; -} -/** - * Start animation on a MotionValue. This function is an interface between - * Framer Motion and Popmotion - */ -function startAnimation(key, value, target, transition) { - if (transition === void 0) { - transition = {}; - } - if (instantAnimationState.current) { - transition = { - type: false - }; - } - return value.start(function (onComplete) { - var delayTimer; - var controls; - var animation = getAnimation(key, value, target, transition, onComplete); - var delay = getDelayFromTransition(transition, key); - var start = function () { - return controls = animation(); - }; - if (delay) { - delayTimer = window.setTimeout(start, secondsToMilliseconds(delay)); - } else { - start(); - } - return function () { - clearTimeout(delayTimer); - controls === null || controls === void 0 ? void 0 : controls.stop(); - }; - }); -} - -/** - * Check if value is a numerical string, ie a string that is purely a number eg "100" or "-100.1" - */ -var isNumericalString = function (v) { - return /^\-?\d*\.?\d+$/.test(v); -}; - -/** - * Check if the value is a zero value string like "0px" or "0%" - */ -var isZeroValueString = function (v) { - return /^0[^.\s]+$/.test(v); -}; -function addUniqueItem(arr, item) { - arr.indexOf(item) === -1 && arr.push(item); -} -function removeItem(arr, item) { - var index = arr.indexOf(item); - index > -1 && arr.splice(index, 1); -} -// Adapted from array-move -function moveItem(_a, fromIndex, toIndex) { - var _b = tslib.__read(_a), - arr = _b.slice(0); - var startIndex = fromIndex < 0 ? arr.length + fromIndex : fromIndex; - if (startIndex >= 0 && startIndex < arr.length) { - var endIndex = toIndex < 0 ? arr.length + toIndex : toIndex; - var _c = tslib.__read(arr.splice(fromIndex, 1), 1), - item = _c[0]; - arr.splice(endIndex, 0, item); - } - return arr; -} -var SubscriptionManager = /** @class */function () { - function SubscriptionManager() { - this.subscriptions = []; - } - SubscriptionManager.prototype.add = function (handler) { - var _this = this; - addUniqueItem(this.subscriptions, handler); - return function () { - return removeItem(_this.subscriptions, handler); - }; - }; - SubscriptionManager.prototype.notify = function (a, b, c) { - var numSubscriptions = this.subscriptions.length; - if (!numSubscriptions) return; - if (numSubscriptions === 1) { - /** - * If there's only a single handler we can just call it without invoking a loop. - */ - this.subscriptions[0](a, b, c); - } else { - for (var i = 0; i < numSubscriptions; i++) { - /** - * Check whether the handler exists before firing as it's possible - * the subscriptions were modified during this loop running. - */ - var handler = this.subscriptions[i]; - handler && handler(a, b, c); - } - } - }; - SubscriptionManager.prototype.getSize = function () { - return this.subscriptions.length; - }; - SubscriptionManager.prototype.clear = function () { - this.subscriptions.length = 0; - }; - return SubscriptionManager; -}(); -var isFloat = function (value) { - return !isNaN(parseFloat(value)); -}; -/** - * `MotionValue` is used to track the state and velocity of motion values. - * - * @public - */ -var MotionValue = /** @class */function () { - /** - * @param init - The initiating value - * @param config - Optional configuration options - * - * - `transformer`: A function to transform incoming values with. - * - * @internal - */ - function MotionValue(init) { - var _this = this; - /** - * This will be replaced by the build step with the latest version number. - * When MotionValues are provided to motion components, warn if versions are mixed. - */ - this.version = "6.5.1"; - /** - * Duration, in milliseconds, since last updating frame. - * - * @internal - */ - this.timeDelta = 0; - /** - * Timestamp of the last time this `MotionValue` was updated. - * - * @internal - */ - this.lastUpdated = 0; - /** - * Functions to notify when the `MotionValue` updates. - * - * @internal - */ - this.updateSubscribers = new SubscriptionManager(); - /** - * Functions to notify when the velocity updates. - * - * @internal - */ - this.velocityUpdateSubscribers = new SubscriptionManager(); - /** - * Functions to notify when the `MotionValue` updates and `render` is set to `true`. - * - * @internal - */ - this.renderSubscribers = new SubscriptionManager(); - /** - * Tracks whether this value can output a velocity. Currently this is only true - * if the value is numerical, but we might be able to widen the scope here and support - * other value types. - * - * @internal - */ - this.canTrackVelocity = false; - this.updateAndNotify = function (v, render) { - if (render === void 0) { - render = true; - } - _this.prev = _this.current; - _this.current = v; - // Update timestamp - var _a = sync.getFrameData(), - delta = _a.delta, - timestamp = _a.timestamp; - if (_this.lastUpdated !== timestamp) { - _this.timeDelta = delta; - _this.lastUpdated = timestamp; - sync__default["default"].postRender(_this.scheduleVelocityCheck); - } - // Update update subscribers - if (_this.prev !== _this.current) { - _this.updateSubscribers.notify(_this.current); - } - // Update velocity subscribers - if (_this.velocityUpdateSubscribers.getSize()) { - _this.velocityUpdateSubscribers.notify(_this.getVelocity()); - } - // Update render subscribers - if (render) { - _this.renderSubscribers.notify(_this.current); - } - }; - /** - * Schedule a velocity check for the next frame. - * - * This is an instanced and bound function to prevent generating a new - * function once per frame. - * - * @internal - */ - this.scheduleVelocityCheck = function () { - return sync__default["default"].postRender(_this.velocityCheck); - }; - /** - * Updates `prev` with `current` if the value hasn't been updated this frame. - * This ensures velocity calculations return `0`. - * - * This is an instanced and bound function to prevent generating a new - * function once per frame. - * - * @internal - */ - this.velocityCheck = function (_a) { - var timestamp = _a.timestamp; - if (timestamp !== _this.lastUpdated) { - _this.prev = _this.current; - _this.velocityUpdateSubscribers.notify(_this.getVelocity()); - } - }; - this.hasAnimated = false; - this.prev = this.current = init; - this.canTrackVelocity = isFloat(this.current); - } - /** - * Adds a function that will be notified when the `MotionValue` is updated. - * - * It returns a function that, when called, will cancel the subscription. - * - * When calling `onChange` inside a React component, it should be wrapped with the - * `useEffect` hook. As it returns an unsubscribe function, this should be returned - * from the `useEffect` function to ensure you don't add duplicate subscribers.. - * - * ```jsx - * export const MyComponent = () => { - * const x = useMotionValue(0) - * const y = useMotionValue(0) - * const opacity = useMotionValue(1) - * - * useEffect(() => { - * function updateOpacity() { - * const maxXY = Math.max(x.get(), y.get()) - * const newOpacity = transform(maxXY, [0, 100], [1, 0]) - * opacity.set(newOpacity) - * } - * - * const unsubscribeX = x.onChange(updateOpacity) - * const unsubscribeY = y.onChange(updateOpacity) - * - * return () => { - * unsubscribeX() - * unsubscribeY() - * } - * }, []) - * - * return - * } - * ``` - * - * @privateRemarks - * - * We could look into a `useOnChange` hook if the above lifecycle management proves confusing. - * - * ```jsx - * useOnChange(x, () => {}) - * ``` - * - * @param subscriber - A function that receives the latest value. - * @returns A function that, when called, will cancel this subscription. - * - * @public - */ - MotionValue.prototype.onChange = function (subscription) { - return this.updateSubscribers.add(subscription); - }; - MotionValue.prototype.clearListeners = function () { - this.updateSubscribers.clear(); - }; - /** - * Adds a function that will be notified when the `MotionValue` requests a render. - * - * @param subscriber - A function that's provided the latest value. - * @returns A function that, when called, will cancel this subscription. - * - * @internal - */ - MotionValue.prototype.onRenderRequest = function (subscription) { - // Render immediately - subscription(this.get()); - return this.renderSubscribers.add(subscription); - }; - /** - * Attaches a passive effect to the `MotionValue`. - * - * @internal - */ - MotionValue.prototype.attach = function (passiveEffect) { - this.passiveEffect = passiveEffect; - }; - /** - * Sets the state of the `MotionValue`. - * - * @remarks - * - * ```jsx - * const x = useMotionValue(0) - * x.set(10) - * ``` - * - * @param latest - Latest value to set. - * @param render - Whether to notify render subscribers. Defaults to `true` - * - * @public - */ - MotionValue.prototype.set = function (v, render) { - if (render === void 0) { - render = true; - } - if (!render || !this.passiveEffect) { - this.updateAndNotify(v, render); - } else { - this.passiveEffect(v, this.updateAndNotify); - } - }; - /** - * Returns the latest state of `MotionValue` - * - * @returns - The latest state of `MotionValue` - * - * @public - */ - MotionValue.prototype.get = function () { - return this.current; - }; - /** - * @public - */ - MotionValue.prototype.getPrevious = function () { - return this.prev; - }; - /** - * Returns the latest velocity of `MotionValue` - * - * @returns - The latest velocity of `MotionValue`. Returns `0` if the state is non-numerical. - * - * @public - */ - MotionValue.prototype.getVelocity = function () { - // This could be isFloat(this.prev) && isFloat(this.current), but that would be wasteful - return this.canTrackVelocity ? - // These casts could be avoided if parseFloat would be typed better - popmotion.velocityPerSecond(parseFloat(this.current) - parseFloat(this.prev), this.timeDelta) : 0; - }; - /** - * Registers a new animation to control this `MotionValue`. Only one - * animation can drive a `MotionValue` at one time. - * - * ```jsx - * value.start() - * ``` - * - * @param animation - A function that starts the provided animation - * - * @internal - */ - MotionValue.prototype.start = function (animation) { - var _this = this; - this.stop(); - return new Promise(function (resolve) { - _this.hasAnimated = true; - _this.stopAnimation = animation(resolve); - }).then(function () { - return _this.clearAnimation(); - }); - }; - /** - * Stop the currently active animation. - * - * @public - */ - MotionValue.prototype.stop = function () { - if (this.stopAnimation) this.stopAnimation(); - this.clearAnimation(); - }; - /** - * Returns `true` if this value is currently animating. - * - * @public - */ - MotionValue.prototype.isAnimating = function () { - return !!this.stopAnimation; - }; - MotionValue.prototype.clearAnimation = function () { - this.stopAnimation = null; - }; - /** - * Destroy and clean up subscribers to this `MotionValue`. - * - * The `MotionValue` hooks like `useMotionValue` and `useTransform` automatically - * handle the lifecycle of the returned `MotionValue`, so this method is only necessary if you've manually - * created a `MotionValue` via the `motionValue` function. - * - * @public - */ - MotionValue.prototype.destroy = function () { - this.updateSubscribers.clear(); - this.renderSubscribers.clear(); - this.stop(); - }; - return MotionValue; -}(); -function motionValue(init) { - return new MotionValue(init); -} - -/** - * Tests a provided value against a ValueType - */ -var testValueType = function (v) { - return function (type) { - return type.test(v); - }; -}; - -/** - * ValueType for "auto" - */ -var auto = { - test: function (v) { - return v === "auto"; - }, - parse: function (v) { - return v; - } -}; - -/** - * A list of value types commonly used for dimensions - */ -var dimensionValueTypes = [styleValueTypes.number, styleValueTypes.px, styleValueTypes.percent, styleValueTypes.degrees, styleValueTypes.vw, styleValueTypes.vh, auto]; -/** - * Tests a dimensional value against the list of dimension ValueTypes - */ -var findDimensionValueType = function (v) { - return dimensionValueTypes.find(testValueType(v)); -}; - -/** - * A list of all ValueTypes - */ -var valueTypes = tslib.__spreadArray(tslib.__spreadArray([], tslib.__read(dimensionValueTypes), false), [styleValueTypes.color, styleValueTypes.complex], false); -/** - * Tests a value against the list of ValueTypes - */ -var findValueType = function (v) { - return valueTypes.find(testValueType(v)); -}; - -/** - * Set VisualElement's MotionValue, creating a new MotionValue for it if - * it doesn't exist. - */ -function setMotionValue(visualElement, key, value) { - if (visualElement.hasValue(key)) { - visualElement.getValue(key).set(value); - } else { - visualElement.addValue(key, motionValue(value)); - } -} -function setTarget(visualElement, definition) { - var resolved = resolveVariant(visualElement, definition); - var _a = resolved ? visualElement.makeTargetAnimatable(resolved, false) : {}, - _b = _a.transitionEnd, - transitionEnd = _b === void 0 ? {} : _b; - _a.transition; - var target = tslib.__rest(_a, ["transitionEnd", "transition"]); - target = tslib.__assign(tslib.__assign({}, target), transitionEnd); - for (var key in target) { - var value = resolveFinalValueInKeyframes(target[key]); - setMotionValue(visualElement, key, value); - } -} -function setVariants(visualElement, variantLabels) { - var reversedLabels = tslib.__spreadArray([], tslib.__read(variantLabels), false).reverse(); - reversedLabels.forEach(function (key) { - var _a; - var variant = visualElement.getVariant(key); - variant && setTarget(visualElement, variant); - (_a = visualElement.variantChildren) === null || _a === void 0 ? void 0 : _a.forEach(function (child) { - setVariants(child, variantLabels); - }); - }); -} -function setValues(visualElement, definition) { - if (Array.isArray(definition)) { - return setVariants(visualElement, definition); - } else if (typeof definition === "string") { - return setVariants(visualElement, [definition]); - } else { - setTarget(visualElement, definition); - } -} -function checkTargetForNewValues(visualElement, target, origin) { - var _a, _b, _c; - var _d; - var newValueKeys = Object.keys(target).filter(function (key) { - return !visualElement.hasValue(key); - }); - var numNewValues = newValueKeys.length; - if (!numNewValues) return; - for (var i = 0; i < numNewValues; i++) { - var key = newValueKeys[i]; - var targetValue = target[key]; - var value = null; - /** - * If the target is a series of keyframes, we can use the first value - * in the array. If this first value is null, we'll still need to read from the DOM. - */ - if (Array.isArray(targetValue)) { - value = targetValue[0]; - } - /** - * If the target isn't keyframes, or the first keyframe was null, we need to - * first check if an origin value was explicitly defined in the transition as "from", - * if not read the value from the DOM. As an absolute fallback, take the defined target value. - */ - if (value === null) { - value = (_b = (_a = origin[key]) !== null && _a !== void 0 ? _a : visualElement.readValue(key)) !== null && _b !== void 0 ? _b : target[key]; - } - /** - * If value is still undefined or null, ignore it. Preferably this would throw, - * but this was causing issues in Framer. - */ - if (value === undefined || value === null) continue; - if (typeof value === "string" && (isNumericalString(value) || isZeroValueString(value))) { - // If this is a number read as a string, ie "0" or "200", convert it to a number - value = parseFloat(value); - } else if (!findValueType(value) && styleValueTypes.complex.test(targetValue)) { - value = getAnimatableNone(key, targetValue); - } - visualElement.addValue(key, motionValue(value)); - (_c = (_d = origin)[key]) !== null && _c !== void 0 ? _c : _d[key] = value; - visualElement.setBaseTarget(key, value); - } -} -function getOriginFromTransition(key, transition) { - if (!transition) return; - var valueTransition = transition[key] || transition["default"] || transition; - return valueTransition.from; -} -function getOrigin(target, transition, visualElement) { - var _a, _b; - var origin = {}; - for (var key in target) { - origin[key] = (_a = getOriginFromTransition(key, transition)) !== null && _a !== void 0 ? _a : (_b = visualElement.getValue(key)) === null || _b === void 0 ? void 0 : _b.get(); - } - return origin; -} -function animateVisualElement(visualElement, definition, options) { - if (options === void 0) { - options = {}; - } - visualElement.notifyAnimationStart(definition); - var animation; - if (Array.isArray(definition)) { - var animations = definition.map(function (variant) { - return animateVariant(visualElement, variant, options); - }); - animation = Promise.all(animations); - } else if (typeof definition === "string") { - animation = animateVariant(visualElement, definition, options); - } else { - var resolvedDefinition = typeof definition === "function" ? resolveVariant(visualElement, definition, options.custom) : definition; - animation = animateTarget(visualElement, resolvedDefinition, options); - } - return animation.then(function () { - return visualElement.notifyAnimationComplete(definition); - }); -} -function animateVariant(visualElement, variant, options) { - var _a; - if (options === void 0) { - options = {}; - } - var resolved = resolveVariant(visualElement, variant, options.custom); - var _b = (resolved || {}).transition, - transition = _b === void 0 ? visualElement.getDefaultTransition() || {} : _b; - if (options.transitionOverride) { - transition = options.transitionOverride; - } - /** - * If we have a variant, create a callback that runs it as an animation. - * Otherwise, we resolve a Promise immediately for a composable no-op. - */ - var getAnimation = resolved ? function () { - return animateTarget(visualElement, resolved, options); - } : function () { - return Promise.resolve(); - }; - /** - * If we have children, create a callback that runs all their animations. - * Otherwise, we resolve a Promise immediately for a composable no-op. - */ - var getChildAnimations = ((_a = visualElement.variantChildren) === null || _a === void 0 ? void 0 : _a.size) ? function (forwardDelay) { - if (forwardDelay === void 0) { - forwardDelay = 0; - } - var _a = transition.delayChildren, - delayChildren = _a === void 0 ? 0 : _a, - staggerChildren = transition.staggerChildren, - staggerDirection = transition.staggerDirection; - return animateChildren(visualElement, variant, delayChildren + forwardDelay, staggerChildren, staggerDirection, options); - } : function () { - return Promise.resolve(); - }; - /** - * If the transition explicitly defines a "when" option, we need to resolve either - * this animation or all children animations before playing the other. - */ - var when = transition.when; - if (when) { - var _c = tslib.__read(when === "beforeChildren" ? [getAnimation, getChildAnimations] : [getChildAnimations, getAnimation], 2), - first = _c[0], - last = _c[1]; - return first().then(last); - } else { - return Promise.all([getAnimation(), getChildAnimations(options.delay)]); - } -} -/** - * @internal - */ -function animateTarget(visualElement, definition, _a) { - var _b; - var _c = _a === void 0 ? {} : _a, - _d = _c.delay, - delay = _d === void 0 ? 0 : _d, - transitionOverride = _c.transitionOverride, - type = _c.type; - var _e = visualElement.makeTargetAnimatable(definition), - _f = _e.transition, - transition = _f === void 0 ? visualElement.getDefaultTransition() : _f, - transitionEnd = _e.transitionEnd, - target = tslib.__rest(_e, ["transition", "transitionEnd"]); - if (transitionOverride) transition = transitionOverride; - var animations = []; - var animationTypeState = type && ((_b = visualElement.animationState) === null || _b === void 0 ? void 0 : _b.getState()[type]); - for (var key in target) { - var value = visualElement.getValue(key); - var valueTarget = target[key]; - if (!value || valueTarget === undefined || animationTypeState && shouldBlockAnimation(animationTypeState, key)) { - continue; - } - var valueTransition = tslib.__assign({ - delay: delay - }, transition); - /** - * Make animation instant if this is a transform prop and we should reduce motion. - */ - if (visualElement.shouldReduceMotion && isTransformProp(key)) { - valueTransition = tslib.__assign(tslib.__assign({}, valueTransition), { - type: false, - delay: 0 - }); - } - var animation = startAnimation(key, value, valueTarget, valueTransition); - animations.push(animation); - } - return Promise.all(animations).then(function () { - transitionEnd && setTarget(visualElement, transitionEnd); - }); -} -function animateChildren(visualElement, variant, delayChildren, staggerChildren, staggerDirection, options) { - if (delayChildren === void 0) { - delayChildren = 0; - } - if (staggerChildren === void 0) { - staggerChildren = 0; - } - if (staggerDirection === void 0) { - staggerDirection = 1; - } - var animations = []; - var maxStaggerDuration = (visualElement.variantChildren.size - 1) * staggerChildren; - var generateStaggerDuration = staggerDirection === 1 ? function (i) { - if (i === void 0) { - i = 0; - } - return i * staggerChildren; - } : function (i) { - if (i === void 0) { - i = 0; - } - return maxStaggerDuration - i * staggerChildren; - }; - Array.from(visualElement.variantChildren).sort(sortByTreeOrder).forEach(function (child, i) { - animations.push(animateVariant(child, variant, tslib.__assign(tslib.__assign({}, options), { - delay: delayChildren + generateStaggerDuration(i) - })).then(function () { - return child.notifyAnimationComplete(variant); - })); - }); - return Promise.all(animations); -} -function stopAnimation(visualElement) { - visualElement.forEachValue(function (value) { - return value.stop(); - }); -} -function sortByTreeOrder(a, b) { - return a.sortNodePosition(b); -} -/** - * Decide whether we should block this animation. Previously, we achieved this - * just by checking whether the key was listed in protectedKeys, but this - * posed problems if an animation was triggered by afterChildren and protectedKeys - * had been set to true in the meantime. - */ -function shouldBlockAnimation(_a, key) { - var protectedKeys = _a.protectedKeys, - needsAnimating = _a.needsAnimating; - var shouldBlock = protectedKeys.hasOwnProperty(key) && needsAnimating[key] !== true; - needsAnimating[key] = false; - return shouldBlock; -} -var variantPriorityOrder = [exports.AnimationType.Animate, exports.AnimationType.InView, exports.AnimationType.Focus, exports.AnimationType.Hover, exports.AnimationType.Tap, exports.AnimationType.Drag, exports.AnimationType.Exit]; -var reversePriorityOrder = tslib.__spreadArray([], tslib.__read(variantPriorityOrder), false).reverse(); -var numAnimationTypes = variantPriorityOrder.length; -function animateList(visualElement) { - return function (animations) { - return Promise.all(animations.map(function (_a) { - var animation = _a.animation, - options = _a.options; - return animateVisualElement(visualElement, animation, options); - })); - }; -} -function createAnimationState(visualElement) { - var animate = animateList(visualElement); - var state = createState(); - var allAnimatedKeys = {}; - var isInitialRender = true; - /** - * This function will be used to reduce the animation definitions for - * each active animation type into an object of resolved values for it. - */ - var buildResolvedTypeValues = function (acc, definition) { - var resolved = resolveVariant(visualElement, definition); - if (resolved) { - resolved.transition; - var transitionEnd = resolved.transitionEnd, - target = tslib.__rest(resolved, ["transition", "transitionEnd"]); - acc = tslib.__assign(tslib.__assign(tslib.__assign({}, acc), target), transitionEnd); - } - return acc; - }; - function isAnimated(key) { - return allAnimatedKeys[key] !== undefined; - } - /** - * This just allows us to inject mocked animation functions - * @internal - */ - function setAnimateFunction(makeAnimator) { - animate = makeAnimator(visualElement); - } - /** - * When we receive new props, we need to: - * 1. Create a list of protected keys for each type. This is a directory of - * value keys that are currently being "handled" by types of a higher priority - * so that whenever an animation is played of a given type, these values are - * protected from being animated. - * 2. Determine if an animation type needs animating. - * 3. Determine if any values have been removed from a type and figure out - * what to animate those to. - */ - function animateChanges(options, changedActiveType) { - var _a; - var props = visualElement.getProps(); - var context = visualElement.getVariantContext(true) || {}; - /** - * A list of animations that we'll build into as we iterate through the animation - * types. This will get executed at the end of the function. - */ - var animations = []; - /** - * Keep track of which values have been removed. Then, as we hit lower priority - * animation types, we can check if they contain removed values and animate to that. - */ - var removedKeys = new Set(); - /** - * A dictionary of all encountered keys. This is an object to let us build into and - * copy it without iteration. Each time we hit an animation type we set its protected - * keys - the keys its not allowed to animate - to the latest version of this object. - */ - var encounteredKeys = {}; - /** - * If a variant has been removed at a given index, and this component is controlling - * variant animations, we want to ensure lower-priority variants are forced to animate. - */ - var removedVariantIndex = Infinity; - var _loop_1 = function (i) { - var type = reversePriorityOrder[i]; - var typeState = state[type]; - var prop = (_a = props[type]) !== null && _a !== void 0 ? _a : context[type]; - var propIsVariant = isVariantLabel(prop); - /** - * If this type has *just* changed isActive status, set activeDelta - * to that status. Otherwise set to null. - */ - var activeDelta = type === changedActiveType ? typeState.isActive : null; - if (activeDelta === false) removedVariantIndex = i; - /** - * If this prop is an inherited variant, rather than been set directly on the - * component itself, we want to make sure we allow the parent to trigger animations. - * - * TODO: Can probably change this to a !isControllingVariants check - */ - var isInherited = prop === context[type] && prop !== props[type] && propIsVariant; - /** - * - */ - if (isInherited && isInitialRender && visualElement.manuallyAnimateOnMount) { - isInherited = false; - } - /** - * Set all encountered keys so far as the protected keys for this type. This will - * be any key that has been animated or otherwise handled by active, higher-priortiy types. - */ - typeState.protectedKeys = tslib.__assign({}, encounteredKeys); - // Check if we can skip analysing this prop early - if ( - // If it isn't active and hasn't *just* been set as inactive - !typeState.isActive && activeDelta === null || - // If we didn't and don't have any defined prop for this animation type - !prop && !typeState.prevProp || - // Or if the prop doesn't define an animation - isAnimationControls(prop) || typeof prop === "boolean") { - return "continue"; - } - /** - * As we go look through the values defined on this type, if we detect - * a changed value or a value that was removed in a higher priority, we set - * this to true and add this prop to the animation list. - */ - var variantDidChange = checkVariantsDidChange(typeState.prevProp, prop); - var shouldAnimateType = variantDidChange || - // If we're making this variant active, we want to always make it active - type === changedActiveType && typeState.isActive && !isInherited && propIsVariant || - // If we removed a higher-priority variant (i is in reverse order) - i > removedVariantIndex && propIsVariant; - /** - * As animations can be set as variant lists, variants or target objects, we - * coerce everything to an array if it isn't one already - */ - var definitionList = Array.isArray(prop) ? prop : [prop]; - /** - * Build an object of all the resolved values. We'll use this in the subsequent - * animateChanges calls to determine whether a value has changed. - */ - var resolvedValues = definitionList.reduce(buildResolvedTypeValues, {}); - if (activeDelta === false) resolvedValues = {}; - /** - * Now we need to loop through all the keys in the prev prop and this prop, - * and decide: - * 1. If the value has changed, and needs animating - * 2. If it has been removed, and needs adding to the removedKeys set - * 3. If it has been removed in a higher priority type and needs animating - * 4. If it hasn't been removed in a higher priority but hasn't changed, and - * needs adding to the type's protectedKeys list. - */ - var _b = typeState.prevResolvedValues, - prevResolvedValues = _b === void 0 ? {} : _b; - var allKeys = tslib.__assign(tslib.__assign({}, prevResolvedValues), resolvedValues); - var markToAnimate = function (key) { - shouldAnimateType = true; - removedKeys.delete(key); - typeState.needsAnimating[key] = true; - }; - for (var key in allKeys) { - var next = resolvedValues[key]; - var prev = prevResolvedValues[key]; - // If we've already handled this we can just skip ahead - if (encounteredKeys.hasOwnProperty(key)) continue; - /** - * If the value has changed, we probably want to animate it. - */ - if (next !== prev) { - /** - * If both values are keyframes, we need to shallow compare them to - * detect whether any value has changed. If it has, we animate it. - */ - if (isKeyframesTarget(next) && isKeyframesTarget(prev)) { - if (!shallowCompare(next, prev) || variantDidChange) { - markToAnimate(key); - } else { - /** - * If it hasn't changed, we want to ensure it doesn't animate by - * adding it to the list of protected keys. - */ - typeState.protectedKeys[key] = true; - } - } else if (next !== undefined) { - // If next is defined and doesn't equal prev, it needs animating - markToAnimate(key); - } else { - // If it's undefined, it's been removed. - removedKeys.add(key); - } - } else if (next !== undefined && removedKeys.has(key)) { - /** - * If next hasn't changed and it isn't undefined, we want to check if it's - * been removed by a higher priority - */ - markToAnimate(key); - } else { - /** - * If it hasn't changed, we add it to the list of protected values - * to ensure it doesn't get animated. - */ - typeState.protectedKeys[key] = true; - } - } - /** - * Update the typeState so next time animateChanges is called we can compare the - * latest prop and resolvedValues to these. - */ - typeState.prevProp = prop; - typeState.prevResolvedValues = resolvedValues; - /** - * - */ - if (typeState.isActive) { - encounteredKeys = tslib.__assign(tslib.__assign({}, encounteredKeys), resolvedValues); - } - if (isInitialRender && visualElement.blockInitialAnimation) { - shouldAnimateType = false; - } - /** - * If this is an inherited prop we want to hard-block animations - * TODO: Test as this should probably still handle animations triggered - * by removed values? - */ - if (shouldAnimateType && !isInherited) { - animations.push.apply(animations, tslib.__spreadArray([], tslib.__read(definitionList.map(function (animation) { - return { - animation: animation, - options: tslib.__assign({ - type: type - }, options) - }; - })), false)); - } - }; - /** - * Iterate through all animation types in reverse priority order. For each, we want to - * detect which values it's handling and whether or not they've changed (and therefore - * need to be animated). If any values have been removed, we want to detect those in - * lower priority props and flag for animation. - */ - for (var i = 0; i < numAnimationTypes; i++) { - _loop_1(i); - } - allAnimatedKeys = tslib.__assign({}, encounteredKeys); - /** - * If there are some removed value that haven't been dealt with, - * we need to create a new animation that falls back either to the value - * defined in the style prop, or the last read value. - */ - if (removedKeys.size) { - var fallbackAnimation_1 = {}; - removedKeys.forEach(function (key) { - var fallbackTarget = visualElement.getBaseTarget(key); - if (fallbackTarget !== undefined) { - fallbackAnimation_1[key] = fallbackTarget; - } - }); - animations.push({ - animation: fallbackAnimation_1 - }); - } - var shouldAnimate = Boolean(animations.length); - if (isInitialRender && props.initial === false && !visualElement.manuallyAnimateOnMount) { - shouldAnimate = false; - } - isInitialRender = false; - return shouldAnimate ? animate(animations) : Promise.resolve(); - } - /** - * Change whether a certain animation type is active. - */ - function setActive(type, isActive, options) { - var _a; - // If the active state hasn't changed, we can safely do nothing here - if (state[type].isActive === isActive) return Promise.resolve(); - // Propagate active change to children - (_a = visualElement.variantChildren) === null || _a === void 0 ? void 0 : _a.forEach(function (child) { - var _a; - return (_a = child.animationState) === null || _a === void 0 ? void 0 : _a.setActive(type, isActive); - }); - state[type].isActive = isActive; - var animations = animateChanges(options, type); - for (var key in state) { - state[key].protectedKeys = {}; - } - return animations; - } - return { - isAnimated: isAnimated, - animateChanges: animateChanges, - setActive: setActive, - setAnimateFunction: setAnimateFunction, - getState: function () { - return state; - } - }; -} -function checkVariantsDidChange(prev, next) { - if (typeof next === "string") { - return next !== prev; - } else if (isVariantLabels(next)) { - return !shallowCompare(next, prev); - } - return false; -} -function createTypeState(isActive) { - if (isActive === void 0) { - isActive = false; - } - return { - isActive: isActive, - protectedKeys: {}, - needsAnimating: {}, - prevResolvedValues: {} - }; -} -function createState() { - var _a; - return _a = {}, _a[exports.AnimationType.Animate] = createTypeState(true), _a[exports.AnimationType.InView] = createTypeState(), _a[exports.AnimationType.Hover] = createTypeState(), _a[exports.AnimationType.Tap] = createTypeState(), _a[exports.AnimationType.Drag] = createTypeState(), _a[exports.AnimationType.Focus] = createTypeState(), _a[exports.AnimationType.Exit] = createTypeState(), _a; -} -var animations = { - animation: makeRenderlessComponent(function (_a) { - var visualElement = _a.visualElement, - animate = _a.animate; - /** - * We dynamically generate the AnimationState manager as it contains a reference - * to the underlying animation library. We only want to load that if we load this, - * so people can optionally code split it out using the `m` component. - */ - visualElement.animationState || (visualElement.animationState = createAnimationState(visualElement)); - /** - * Subscribe any provided AnimationControls to the component's VisualElement - */ - if (isAnimationControls(animate)) { - React.useEffect(function () { - return animate.subscribe(visualElement); - }, [animate]); - } - }), - exit: makeRenderlessComponent(function (props) { - var custom = props.custom, - visualElement = props.visualElement; - var _a = tslib.__read(usePresence(), 2), - isPresent = _a[0], - safeToRemove = _a[1]; - var presenceContext = React.useContext(PresenceContext); - React.useEffect(function () { - var _a, _b; - visualElement.isPresent = isPresent; - var animation = (_a = visualElement.animationState) === null || _a === void 0 ? void 0 : _a.setActive(exports.AnimationType.Exit, !isPresent, { - custom: (_b = presenceContext === null || presenceContext === void 0 ? void 0 : presenceContext.custom) !== null && _b !== void 0 ? _b : custom - }); - !isPresent && (animation === null || animation === void 0 ? void 0 : animation.then(safeToRemove)); - }, [isPresent]); - }) -}; - -/** - * @internal - */ -var PanSession = /** @class */function () { - function PanSession(event, handlers, _a) { - var _this = this; - var _b = _a === void 0 ? {} : _a, - transformPagePoint = _b.transformPagePoint; - /** - * @internal - */ - this.startEvent = null; - /** - * @internal - */ - this.lastMoveEvent = null; - /** - * @internal - */ - this.lastMoveEventInfo = null; - /** - * @internal - */ - this.handlers = {}; - this.updatePoint = function () { - if (!(_this.lastMoveEvent && _this.lastMoveEventInfo)) return; - var info = getPanInfo(_this.lastMoveEventInfo, _this.history); - var isPanStarted = _this.startEvent !== null; - // Only start panning if the offset is larger than 3 pixels. If we make it - // any larger than this we'll want to reset the pointer history - // on the first update to avoid visual snapping to the cursoe. - var isDistancePastThreshold = popmotion.distance(info.offset, { - x: 0, - y: 0 - }) >= 3; - if (!isPanStarted && !isDistancePastThreshold) return; - var point = info.point; - var timestamp = sync.getFrameData().timestamp; - _this.history.push(tslib.__assign(tslib.__assign({}, point), { - timestamp: timestamp - })); - var _a = _this.handlers, - onStart = _a.onStart, - onMove = _a.onMove; - if (!isPanStarted) { - onStart && onStart(_this.lastMoveEvent, info); - _this.startEvent = _this.lastMoveEvent; - } - onMove && onMove(_this.lastMoveEvent, info); - }; - this.handlePointerMove = function (event, info) { - _this.lastMoveEvent = event; - _this.lastMoveEventInfo = transformPoint(info, _this.transformPagePoint); - // Because Safari doesn't trigger mouseup events when it's above a `',copyClassesToDropdown:!1,placeholder:null,hidePlaceholder:null,shouldLoad:function(n){return n.length>0},render:{}};function pr(n,e){var t=Object.assign({},Wo,e),i=t.dataAttr,r=t.labelField,o=t.valueField,s=t.disabledField,a=t.optgroupField,l=t.optgroupLabelField,c=t.optgroupValueField,u=n.tagName.toLowerCase(),d=n.getAttribute("placeholder")||n.getAttribute("data-placeholder");if(!d&&!t.allowEmptyOption){let v=n.querySelector('option[value=""]');v&&(d=v.textContent)}var p={placeholder:d,options:[],optgroups:[],items:[],maxItems:null},y=()=>{var v,w=p.options,T={},_=1;let S=0;var A=L=>{var I=Object.assign({},L.dataset),k=i&&I[i];return typeof k=="string"&&k.length&&(I=Object.assign(I,JSON.parse(k))),I},K=(L,I)=>{var k=qe(L.value);if(k!=null&&!(!k&&!t.allowEmptyOption)){if(T.hasOwnProperty(k)){if(I){var Y=T[k][a];Y?Array.isArray(Y)?Y.push(I):T[k][a]=[Y,I]:T[k][a]=I}}else{var $=A(L);$[r]=$[r]||L.textContent,$[o]=$[o]||k,$[s]=$[s]||L.disabled,$[a]=$[a]||I,$.$option=L,$.$order=$.$order||++S,T[k]=$,w.push($)}L.selected&&p.items.push(k)}},z=L=>{var I,k;k=A(L),k[l]=k[l]||L.getAttribute("label")||"",k[c]=k[c]||_++,k[s]=k[s]||L.disabled,k.$order=k.$order||++S,p.optgroups.push(k),I=k[c],ge(L.children,Y=>{K(Y,I)})};p.maxItems=n.hasAttribute("multiple")?null:1,ge(n.children,L=>{v=L.tagName.toLowerCase(),v==="optgroup"?z(L):v==="option"&&K(L)})},m=()=>{let v=n.getAttribute(i);if(v)p.options=JSON.parse(v),ge(p.options,T=>{p.items.push(T[o])});else{var w=n.value.trim()||"";if(!t.allowEmptyOption&&!w.length)return;let T=w.split(t.delimiter);ge(T,_=>{let S={};S[r]=_,S[o]=_,p.options.push(S)}),p.items=T}};return u==="select"?y():m(),Object.assign({},Wo,p,e)}var nl=0,_e=class extends Ho(oi){constructor(e,t){super(),this.order=0,this.isOpen=!1,this.isDisabled=!1,this.isReadOnly=!1,this.isInvalid=!1,this.isValid=!0,this.isLocked=!1,this.isFocused=!1,this.isInputHidden=!1,this.isSetup=!1,this.ignoreFocus=!1,this.ignoreHover=!1,this.hasOptions=!1,this.lastValue="",this.caretPos=0,this.loading=0,this.loadedSearches={},this.activeOption=null,this.activeItems=[],this.optgroups={},this.options={},this.userOptions={},this.items=[],this.refreshTimeout=null,nl++;var i,r=nt(e);if(r.tomselect)throw new Error("Tom Select already initialized on this element");r.tomselect=this;var o=window.getComputedStyle&&window.getComputedStyle(r,null);i=o.getPropertyValue("direction");let s=pr(r,t);this.settings=s,this.input=r,this.tabIndex=r.tabIndex||0,this.is_select_tag=r.tagName.toLowerCase()==="select",this.rtl=/rtl/i.test(i),this.inputId=dr(r,"tomselect-"+nl),this.isRequired=r.required,this.sifter=new cr(this.options,{diacritics:s.diacritics}),s.mode=s.mode||(s.maxItems===1?"single":"multi"),typeof s.hideSelected!="boolean"&&(s.hideSelected=s.mode==="multi"),typeof s.hidePlaceholder!="boolean"&&(s.hidePlaceholder=s.mode!=="multi");var a=s.createFilter;typeof a!="function"&&(typeof a=="string"&&(a=new RegExp(a)),a instanceof RegExp?s.createFilter=w=>a.test(w):s.createFilter=w=>this.settings.duplicates||!this.options[w]),this.initializePlugins(s.plugins),this.setupCallbacks(),this.setupTemplates();let l=nt("
"),c=nt("
"),u=this._render("dropdown"),d=nt('
'),p=this.input.getAttribute("class")||"",y=s.mode;var m;if(Fe(l,s.wrapperClass,p,y),Fe(c,s.controlClass),Nt(l,c),Fe(u,s.dropdownClass,y),s.copyClassesToDropdown&&Fe(u,p),Fe(d,s.dropdownContentClass),Nt(u,d),nt(s.dropdownParent||l).appendChild(u),Vo(s.controlInput)){m=nt(s.controlInput);var v=["autocorrect","autocapitalize","autocomplete","spellcheck"];ge(v,w=>{r.getAttribute(w)&&le(m,{[w]:r.getAttribute(w)})}),m.tabIndex=-1,c.appendChild(m),this.focus_node=m}else s.controlInput?(m=nt(s.controlInput),this.focus_node=m):(m=nt(""),this.focus_node=c);this.wrapper=l,this.dropdown=u,this.dropdown_content=d,this.control=c,this.control_input=m,this.setup()}setup(){let e=this,t=e.settings,i=e.control_input,r=e.dropdown,o=e.dropdown_content,s=e.wrapper,a=e.control,l=e.input,c=e.focus_node,u={passive:!0},d=e.inputId+"-ts-dropdown";le(o,{id:d}),le(c,{role:"combobox","aria-haspopup":"listbox","aria-expanded":"false","aria-controls":d});let p=dr(c,e.inputId+"-ts-control"),y="label[for='"+Ga(e.inputId)+"']",m=document.querySelector(y),v=e.focus.bind(e);if(m){De(m,"click",v),le(m,{for:p});let _=dr(m,e.inputId+"-ts-label");le(c,{"aria-labelledby":_}),le(o,{"aria-labelledby":_})}if(s.style.width=l.style.width,e.plugins.names.length){let _="plugin-"+e.plugins.names.join(" plugin-");Fe([s,r],_)}(t.maxItems===null||t.maxItems>1)&&e.is_select_tag&&le(l,{multiple:"multiple"}),t.placeholder&&le(i,{placeholder:t.placeholder}),!t.splitOn&&t.delimiter&&(t.splitOn=new RegExp("\\s*"+Lt(t.delimiter)+"+\\s*")),t.load&&t.loadThrottle&&(t.load=Ua(t.load,t.loadThrottle)),De(r,"mousemove",()=>{e.ignoreHover=!1}),De(r,"mouseenter",_=>{var S=hr(_.target,"[data-selectable]",r);S&&e.onOptionHover(_,S)},{capture:!0}),De(r,"click",_=>{let S=hr(_.target,"[data-selectable]");S&&(e.onOptionSelect(_,S),fe(_,!0))}),De(a,"click",_=>{var S=hr(_.target,"[data-ts-item]",a);if(S&&e.onItemSelect(_,S)){fe(_,!0);return}i.value==""&&(e.onClick(),fe(_,!0))}),De(c,"keydown",_=>e.onKeyDown(_)),De(i,"keypress",_=>e.onKeyPress(_)),De(i,"input",_=>e.onInput(_)),De(c,"blur",_=>e.onBlur(_)),De(c,"focus",_=>e.onFocus(_)),De(i,"paste",_=>e.onPaste(_));let w=_=>{let S=_.composedPath()[0];if(!s.contains(S)&&!r.contains(S)){e.isFocused&&e.blur(),e.inputState();return}S==i&&e.isOpen?_.stopPropagation():fe(_,!0)},T=()=>{e.isOpen&&e.positionDropdown()};De(document,"mousedown",w),De(window,"scroll",T,u),De(window,"resize",T,u),this._destroy=()=>{document.removeEventListener("mousedown",w),window.removeEventListener("scroll",T),window.removeEventListener("resize",T),m&&m.removeEventListener("click",v)},this.revertSettings={innerHTML:l.innerHTML,tabIndex:l.tabIndex},l.tabIndex=-1,l.insertAdjacentElement("afterend",e.wrapper),e.sync(!1),t.items=[],delete t.optgroups,delete t.options,De(l,"invalid",()=>{e.isValid&&(e.isValid=!1,e.isInvalid=!0,e.refreshState())}),e.updateOriginalInput(),e.refreshItems(),e.close(!1),e.inputState(),e.isSetup=!0,l.disabled?e.disable():l.readOnly?e.setReadOnly(!0):e.enable(),e.on("change",this.onChange),Fe(l,"tomselected","ts-hidden-accessible"),e.trigger("initialize"),t.preload===!0&&e.preload()}setupOptions(e=[],t=[]){this.addOptions(e),ge(t,i=>{this.registerOptionGroup(i)})}setupTemplates(){var e=this,t=e.settings.labelField,i=e.settings.optgroupLabelField,r={optgroup:o=>{let s=document.createElement("div");return s.className="optgroup",s.appendChild(o.options),s},optgroup_header:(o,s)=>'
'+s(o[i])+"
",option:(o,s)=>"
"+s(o[t])+"
",item:(o,s)=>"
"+s(o[t])+"
",option_create:(o,s)=>'
Add '+s(o.input)+"
",no_results:()=>'
No results found
',loading:()=>'
',not_loading:()=>{},dropdown:()=>"
"};e.settings.render=Object.assign({},r,e.settings.render)}setupCallbacks(){var e,t,i={initialize:"onInitialize",change:"onChange",item_add:"onItemAdd",item_remove:"onItemRemove",item_select:"onItemSelect",clear:"onClear",option_add:"onOptionAdd",option_remove:"onOptionRemove",option_clear:"onOptionClear",optgroup_add:"onOptionGroupAdd",optgroup_remove:"onOptionGroupRemove",optgroup_clear:"onOptionGroupClear",dropdown_open:"onDropdownOpen",dropdown_close:"onDropdownClose",type:"onType",load:"onLoad",focus:"onFocus",blur:"onBlur"};for(e in i)t=this.settings[i[e]],t&&this.on(e,t)}sync(e=!0){let t=this,i=e?pr(t.input,{delimiter:t.settings.delimiter}):t.settings;t.setupOptions(i.options,i.optgroups),t.setValue(i.items||[],!0),t.lastQuery=null}onClick(){var e=this;if(e.activeItems.length>0){e.clearActiveItems(),e.focus();return}e.isFocused&&e.isOpen?e.blur():e.focus()}onMouseDown(){}onChange(){fr(this.input,"input"),fr(this.input,"change")}onPaste(e){var t=this;if(t.isInputHidden||t.isLocked){fe(e);return}t.settings.splitOn&&setTimeout(()=>{var i=t.inputValue();if(i.match(t.settings.splitOn)){var r=i.trim().split(t.settings.splitOn);ge(r,o=>{qe(o)&&(this.options[o]?t.addItem(o):t.createItem(o))})}},0)}onKeyPress(e){var t=this;if(t.isLocked){fe(e);return}var i=String.fromCharCode(e.keyCode||e.which);if(t.settings.create&&t.settings.mode==="multi"&&i===t.settings.delimiter){t.createItem(),fe(e);return}}onKeyDown(e){var t=this;if(t.ignoreHover=!0,t.isLocked){e.keyCode!==9&&fe(e);return}switch(e.keyCode){case 65:if(Mt(fi,e)&&t.control_input.value==""){fe(e),t.selectAll();return}break;case 27:t.isOpen&&(fe(e,!0),t.close()),t.clearActiveItems();return;case 40:if(!t.isOpen&&t.hasOptions)t.open();else if(t.activeOption){let i=t.getAdjacent(t.activeOption,1);i&&t.setActiveOption(i)}fe(e);return;case 38:if(t.activeOption){let i=t.getAdjacent(t.activeOption,-1);i&&t.setActiveOption(i)}fe(e);return;case 13:t.canSelect(t.activeOption)?(t.onOptionSelect(e,t.activeOption),fe(e)):t.settings.create&&t.createItem()?fe(e):document.activeElement==t.control_input&&t.isOpen&&fe(e);return;case 37:t.advanceSelection(-1,e);return;case 39:t.advanceSelection(1,e);return;case 9:t.settings.selectOnTab&&(t.canSelect(t.activeOption)&&(t.onOptionSelect(e,t.activeOption),fe(e)),t.settings.create&&t.createItem()&&fe(e));return;case 8:case 46:t.deleteSelection(e);return}t.isInputHidden&&!Mt(fi,e)&&fe(e)}onInput(e){if(this.isLocked)return;let t=this.inputValue();if(this.lastValue!==t){if(this.lastValue=t,t==""){this._onInput();return}this.refreshTimeout&&window.clearTimeout(this.refreshTimeout),this.refreshTimeout=qa(()=>{this.refreshTimeout=null,this._onInput()},this.settings.refreshThrottle)}}_onInput(){let e=this.lastValue;this.settings.shouldLoad.call(this,e)&&this.load(e),this.refreshOptions(),this.trigger("type",e)}onOptionHover(e,t){this.ignoreHover||this.setActiveOption(t,!1)}onFocus(e){var t=this,i=t.isFocused;if(t.isDisabled||t.isReadOnly){t.blur(),fe(e);return}t.ignoreFocus||(t.isFocused=!0,t.settings.preload==="focus"&&t.preload(),i||t.trigger("focus"),t.activeItems.length||(t.inputState(),t.refreshOptions(!!t.settings.openOnFocus)),t.refreshState())}onBlur(e){if(document.hasFocus()!==!1){var t=this;if(t.isFocused){t.isFocused=!1,t.ignoreFocus=!1;var i=()=>{t.close(),t.setActiveItem(),t.setCaret(t.items.length),t.trigger("blur")};t.settings.create&&t.settings.createOnBlur?t.createItem(null,i):i()}}}onOptionSelect(e,t){var i,r=this;t.parentElement&&t.parentElement.matches("[data-disabled]")||(t.classList.contains("create")?r.createItem(null,()=>{r.settings.closeAfterSelect&&r.close()}):(i=t.dataset.value,typeof i!="undefined"&&(r.lastQuery=null,r.addItem(i),r.settings.closeAfterSelect&&r.close(),!r.settings.hideSelected&&e.type&&/click/.test(e.type)&&r.setActiveOption(t))))}canSelect(e){return!!(this.isOpen&&e&&this.dropdown_content.contains(e))}onItemSelect(e,t){var i=this;return!i.isLocked&&i.settings.mode==="multi"?(fe(e),i.setActiveItem(t,e),!0):!1}canLoad(e){return!(!this.settings.load||this.loadedSearches.hasOwnProperty(e))}load(e){let t=this;if(!t.canLoad(e))return;Fe(t.wrapper,t.settings.loadingClass),t.loading++;let i=t.loadCallback.bind(t);t.settings.load.call(t,e,i)}loadCallback(e,t){let i=this;i.loading=Math.max(i.loading-1,0),i.lastQuery=null,i.clearActiveOption(),i.setupOptions(e,t),i.refreshOptions(i.isFocused&&!i.isInputHidden),i.loading||gt(i.wrapper,i.settings.loadingClass),i.trigger("load",e,t)}preload(){var e=this.wrapper.classList;e.contains("preloaded")||(e.add("preloaded"),this.load(""))}setTextboxValue(e=""){var t=this.control_input,i=t.value!==e;i&&(t.value=e,fr(t,"update"),this.lastValue=e)}getValue(){return this.is_select_tag&&this.input.hasAttribute("multiple")?this.items:this.items.join(this.settings.delimiter)}setValue(e,t){var i=t?[]:["change"];$o(this,i,()=>{this.clear(t),this.addItems(e,t)})}setMaxItems(e){e===0&&(e=null),this.settings.maxItems=e,this.refreshState()}setActiveItem(e,t){var i=this,r,o,s,a,l,c;if(i.settings.mode!=="single"){if(!e){i.clearActiveItems(),i.isFocused&&i.inputState();return}if(r=t&&t.type.toLowerCase(),r==="click"&&Mt("shiftKey",t)&&i.activeItems.length){for(c=i.getLastActive(),s=Array.prototype.indexOf.call(i.control.children,c),a=Array.prototype.indexOf.call(i.control.children,e),s>a&&(l=s,s=a,a=l),o=s;o<=a;o++)e=i.control.children[o],i.activeItems.indexOf(e)===-1&&i.setActiveItemClass(e);fe(t)}else r==="click"&&Mt(fi,t)||r==="keydown"&&Mt("shiftKey",t)?e.classList.contains("active")?i.removeActiveItem(e):i.setActiveItemClass(e):(i.clearActiveItems(),i.setActiveItemClass(e));i.inputState(),i.isFocused||i.focus()}}setActiveItemClass(e){let t=this,i=t.control.querySelector(".last-active");i&>(i,"last-active"),Fe(e,"active last-active"),t.trigger("item_select",e),t.activeItems.indexOf(e)==-1&&t.activeItems.push(e)}removeActiveItem(e){var t=this.activeItems.indexOf(e);this.activeItems.splice(t,1),gt(e,"active")}clearActiveItems(){gt(this.activeItems,"active"),this.activeItems=[]}setActiveOption(e,t=!0){e!==this.activeOption&&(this.clearActiveOption(),e&&(this.activeOption=e,le(this.focus_node,{"aria-activedescendant":e.getAttribute("id")}),le(e,{"aria-selected":"true"}),Fe(e,"active"),t&&this.scrollToOption(e)))}scrollToOption(e,t){if(!e)return;let i=this.dropdown_content,r=i.clientHeight,o=i.scrollTop||0,s=e.offsetHeight,a=e.getBoundingClientRect().top-i.getBoundingClientRect().top+o;a+s>r+o?this.scroll(a-r+s,t):a{e.setActiveItemClass(i)}))}inputState(){var e=this;e.control.contains(e.control_input)&&(le(e.control_input,{placeholder:e.settings.placeholder}),e.activeItems.length>0||!e.isFocused&&e.settings.hidePlaceholder&&e.items.length>0?(e.setTextboxValue(),e.isInputHidden=!0):(e.settings.hidePlaceholder&&e.items.length>0&&le(e.control_input,{placeholder:""}),e.isInputHidden=!1),e.wrapper.classList.toggle("input-hidden",e.isInputHidden))}inputValue(){return this.control_input.value.trim()}focus(){var e=this;e.isDisabled||e.isReadOnly||(e.ignoreFocus=!0,e.control_input.offsetWidth?e.control_input.focus():e.focus_node.focus(),setTimeout(()=>{e.ignoreFocus=!1,e.onFocus()},0))}blur(){this.focus_node.blur(),this.onBlur()}getScoreFunction(e){return this.sifter.getScoreFunction(e,this.getSearchOptions())}getSearchOptions(){var e=this.settings,t=e.sortField;return typeof e.sortField=="string"&&(t=[{field:e.sortField}]),{fields:e.searchField,conjunction:e.searchConjunction,sort:t,nesting:e.nesting}}search(e){var t,i,r=this,o=this.getSearchOptions();if(r.settings.score&&(i=r.settings.score.call(r,e),typeof i!="function"))throw new Error('Tom Select "score" setting must be a function that returns a function');return e!==r.lastQuery?(r.lastQuery=e,t=r.sifter.search(e,Object.assign(o,{score:i})),r.currentResults=t):t=Object.assign({},r.currentResults),r.settings.hideSelected&&(t.items=t.items.filter(s=>{let a=qe(s.id);return!(a&&r.items.indexOf(a)!==-1)})),t}refreshOptions(e=!0){var t,i,r,o,s,a,l,c,u,d;let p={},y=[];var m=this,v=m.inputValue();let w=v===m.lastQuery||v==""&&m.lastQuery==null;var T=m.search(v),_=null,S=m.settings.shouldOpen||!1,A=m.dropdown_content;w&&(_=m.activeOption,_&&(u=_.closest("[data-group]"))),o=T.items.length,typeof m.settings.maxOptions=="number"&&(o=Math.min(o,m.settings.maxOptions)),o>0&&(S=!0);let K=(L,I)=>{let k=p[L];if(k!==void 0){let $=y[k];if($!==void 0)return[k,$.fragment]}let Y=document.createDocumentFragment();return k=y.length,y.push({fragment:Y,order:I,optgroup:L}),[k,Y]};for(t=0;t0&&($=$.cloneNode(!0),le($,{id:k.$id+"-clone-"+i,"aria-selected":null}),$.classList.add("ts-cloned"),gt($,"active"),m.activeOption&&m.activeOption.dataset.value==I&&u&&u.dataset.group===s.toString()&&(_=$)),Ce.appendChild($),s!=""&&(p[s]=Te)}}m.settings.lockOptgroupOrder&&y.sort((L,I)=>L.order-I.order),l=document.createDocumentFragment(),ge(y,L=>{let I=L.fragment,k=L.optgroup;if(!I||!I.children.length)return;let Y=m.optgroups[k];if(Y!==void 0){let $=document.createDocumentFragment(),ie=m.render("optgroup_header",Y);Nt($,ie),Nt($,I);let J=m.render("optgroup",{group:Y,options:$});Nt(l,J)}else Nt(l,I)}),A.innerHTML="",Nt(A,l),m.settings.highlight&&(Za(A),T.query.length&&T.tokens.length&&ge(T.tokens,L=>{Ja(A,L.regex)}));var z=L=>{let I=m.render(L,{input:v});return I&&(S=!0,A.insertBefore(I,A.firstChild)),I};if(m.loading?z("loading"):m.settings.shouldLoad.call(m,v)?T.items.length===0&&z("no_results"):z("not_loading"),c=m.canCreate(v),c&&(d=z("option_create")),m.hasOptions=T.items.length>0||c,S){if(T.items.length>0){if(!_&&m.settings.mode==="single"&&m.items[0]!=null&&(_=m.getOption(m.items[0])),!A.contains(_)){let L=0;d&&!m.settings.addPrecedence&&(L=1),_=m.selectable()[L]}}else d&&(_=d);e&&!m.isOpen&&(m.open(),m.scrollToOption(_,"auto")),m.setActiveOption(_)}else m.clearActiveOption(),e&&m.isOpen&&m.close(!1)}selectable(){return this.dropdown_content.querySelectorAll("[data-selectable]")}addOption(e,t=!1){let i=this;if(Array.isArray(e))return i.addOptions(e,t),!1;let r=qe(e[i.settings.valueField]);return r===null||i.options.hasOwnProperty(r)?!1:(e.$order=e.$order||++i.order,e.$id=i.inputId+"-opt-"+e.$order,i.options[r]=e,i.lastQuery=null,t&&(i.userOptions[r]=t,i.trigger("option_add",r,e)),r)}addOptions(e,t=!1){ge(e,i=>{this.addOption(i,t)})}registerOption(e){return this.addOption(e)}registerOptionGroup(e){var t=qe(e[this.settings.optgroupValueField]);return t===null?!1:(e.$order=e.$order||++this.order,this.optgroups[t]=e,t)}addOptionGroup(e,t){var i;t[this.settings.optgroupValueField]=e,(i=this.registerOptionGroup(t))&&this.trigger("optgroup_add",i,t)}removeOptionGroup(e){this.optgroups.hasOwnProperty(e)&&(delete this.optgroups[e],this.clearCache(),this.trigger("optgroup_remove",e))}clearOptionGroups(){this.optgroups={},this.clearCache(),this.trigger("optgroup_clear")}updateOption(e,t){let i=this;var r,o;let s=qe(e),a=qe(t[i.settings.valueField]);if(s===null)return;let l=i.options[s];if(l==null)return;if(typeof a!="string")throw new Error("Value must be set in option data");let c=i.getOption(s),u=i.getItem(s);if(t.$order=t.$order||l.$order,delete i.options[s],i.uncacheValue(a),i.options[a]=t,c){if(i.dropdown_content.contains(c)){let d=i._render("option",t);di(c,d),i.activeOption===c&&i.setActiveOption(d)}c.remove()}u&&(o=i.items.indexOf(s),o!==-1&&i.items.splice(o,1,a),r=i._render("item",t),u.classList.contains("active")&&Fe(r,"active"),di(u,r)),i.lastQuery=null}removeOption(e,t){let i=this;e=ci(e),i.uncacheValue(e),delete i.userOptions[e],delete i.options[e],i.lastQuery=null,i.trigger("option_remove",e),i.removeItem(e,t)}clearOptions(e){let t=(e||this.clearFilter).bind(this);this.loadedSearches={},this.userOptions={},this.clearCache();let i={};ge(this.options,(r,o)=>{t(r,o)&&(i[o]=r)}),this.options=this.sifter.items=i,this.lastQuery=null,this.trigger("option_clear")}clearFilter(e,t){return this.items.indexOf(t)>=0}getOption(e,t=!1){let i=qe(e);if(i===null)return null;let r=this.options[i];if(r!=null){if(r.$div)return r.$div;if(t)return this._render("option",r)}return null}getAdjacent(e,t,i="option"){var r=this,o;if(!e)return null;i=="item"?o=r.controlChildren():o=r.dropdown_content.querySelectorAll("[data-selectable]");for(let s=0;s0?o[s+1]:o[s-1];return null}getItem(e){if(typeof e=="object")return e;var t=qe(e);return t!==null?this.control.querySelector(`[data-value="${Bo(t)}"]`):null}addItems(e,t){var i=this,r=Array.isArray(e)?e:[e];r=r.filter(s=>i.items.indexOf(s)===-1);let o=r[r.length-1];r.forEach(s=>{i.isPending=s!==o,i.addItem(s,t)})}addItem(e,t){var i=t?[]:["change","dropdown_close"];$o(this,i,()=>{var r,o;let s=this,a=s.settings.mode,l=qe(e);if(!(l&&s.items.indexOf(l)!==-1&&(a==="single"&&s.close(),a==="single"||!s.settings.duplicates))&&!(l===null||!s.options.hasOwnProperty(l))&&(a==="single"&&s.clear(t),!(a==="multi"&&s.isFull()))){if(r=s._render("item",s.options[l]),s.control.contains(r)&&(r=r.cloneNode(!0)),o=s.isFull(),s.items.splice(s.caretPos,0,l),s.insertAtCaret(r),s.isSetup){if(!s.isPending&&s.settings.hideSelected){let c=s.getOption(l),u=s.getAdjacent(c,1);u&&s.setActiveOption(u)}!s.isPending&&!s.settings.closeAfterSelect&&s.refreshOptions(s.isFocused&&a!=="single"),s.settings.closeAfterSelect!=!1&&s.isFull()?s.close():s.isPending||s.positionDropdown(),s.trigger("item_add",l,r),s.isPending||s.updateOriginalInput({silent:t})}(!s.isPending||!o&&s.isFull())&&(s.inputState(),s.refreshState())}})}removeItem(e=null,t){let i=this;if(e=i.getItem(e),!e)return;var r,o;let s=e.dataset.value;r=jo(e),e.remove(),e.classList.contains("active")&&(o=i.activeItems.indexOf(e),i.activeItems.splice(o,1),gt(e,"active")),i.items.splice(r,1),i.lastQuery=null,!i.settings.persist&&i.userOptions.hasOwnProperty(s)&&i.removeOption(s,t),r{}){arguments.length===3&&(t=arguments[2]),typeof t!="function"&&(t=()=>{});var i=this,r=i.caretPos,o;if(e=e||i.inputValue(),!i.canCreate(e))return t(),!1;i.lock();var s=!1,a=l=>{if(i.unlock(),!l||typeof l!="object")return t();var c=qe(l[i.settings.valueField]);if(typeof c!="string")return t();i.setTextboxValue(),i.addOption(l,!0),i.setCaret(r),i.addItem(c),t(l),s=!0};return typeof i.settings.create=="function"?o=i.settings.create.call(this,e,a):o={[i.settings.labelField]:e,[i.settings.valueField]:e},s||a(o),!0}refreshItems(){var e=this;e.lastQuery=null,e.isSetup&&e.addItems(e.items),e.updateOriginalInput(),e.refreshState()}refreshState(){let e=this;e.refreshValidityState();let t=e.isFull(),i=e.isLocked;e.wrapper.classList.toggle("rtl",e.rtl);let r=e.wrapper.classList;r.toggle("focus",e.isFocused),r.toggle("disabled",e.isDisabled),r.toggle("readonly",e.isReadOnly),r.toggle("required",e.isRequired),r.toggle("invalid",!e.isValid),r.toggle("locked",i),r.toggle("full",t),r.toggle("input-active",e.isFocused&&!e.isInputHidden),r.toggle("dropdown-active",e.isOpen),r.toggle("has-options",Qa(e.options)),r.toggle("has-items",e.items.length>0)}refreshValidityState(){var e=this;e.input.validity&&(e.isValid=e.input.validity.valid,e.isInvalid=!e.isValid)}isFull(){return this.settings.maxItems!==null&&this.items.length>=this.settings.maxItems}updateOriginalInput(e={}){let t=this;var i,r;let o=t.input.querySelector('option[value=""]');if(t.is_select_tag){let l=function(c,u,d){return c||(c=nt('")),c!=o&&t.input.append(c),s.push(c),(c!=o||a>0)&&(c.selected=!0),c},s=[],a=t.input.querySelectorAll("option:checked").length;t.input.querySelectorAll("option:checked").forEach(c=>{c.selected=!1}),t.items.length==0&&t.settings.mode=="single"?l(o,"",""):t.items.forEach(c=>{if(i=t.options[c],r=i[t.settings.labelField]||"",s.includes(i.$option)){let u=t.input.querySelector(`option[value="${Bo(c)}"]:not(:checked)`);l(u,c,r)}else i.$option=l(i.$option,c,r)})}else t.input.value=t.getValue();t.isSetup&&(e.silent||t.trigger("change",t.getValue()))}open(){var e=this;e.isLocked||e.isOpen||e.settings.mode==="multi"&&e.isFull()||(e.isOpen=!0,le(e.focus_node,{"aria-expanded":"true"}),e.refreshState(),ui(e.dropdown,{visibility:"hidden",display:"block"}),e.positionDropdown(),ui(e.dropdown,{visibility:"visible",display:"block"}),e.focus(),e.trigger("dropdown_open",e.dropdown))}close(e=!0){var t=this,i=t.isOpen;e&&(t.setTextboxValue(),t.settings.mode==="single"&&t.items.length&&t.inputState()),t.isOpen=!1,le(t.focus_node,{"aria-expanded":"false"}),ui(t.dropdown,{display:"none"}),t.settings.hideSelected&&t.clearActiveOption(),t.refreshState(),i&&t.trigger("dropdown_close",t.dropdown)}positionDropdown(){if(this.settings.dropdownParent==="body"){var e=this.control,t=e.getBoundingClientRect(),i=e.offsetHeight+t.top+window.scrollY,r=t.left+window.scrollX;ui(this.dropdown,{width:t.width+"px",top:i+"px",left:r+"px"})}}clear(e){var t=this;if(t.items.length){var i=t.controlChildren();ge(i,r=>{t.removeItem(r,!0)}),t.inputState(),e||t.updateOriginalInput(),t.trigger("clear")}}insertAtCaret(e){let t=this,i=t.caretPos,r=t.control;r.insertBefore(e,r.children[i]||null),t.setCaret(i+1)}deleteSelection(e){var t,i,r,o,s=this;t=e&&e.keyCode===8?-1:1,i=Ya(s.control_input);let a=[];if(s.activeItems.length)o=zo(s.activeItems,t),r=jo(o),t>0&&r++,ge(s.activeItems,l=>a.push(l));else if((s.isFocused||s.settings.mode==="single")&&s.items.length){let l=s.controlChildren(),c;t<0&&i.start===0&&i.length===0?c=l[s.caretPos-1]:t>0&&i.start===s.inputValue().length&&(c=l[s.caretPos]),c!==void 0&&a.push(c)}if(!s.shouldDelete(a,e))return!1;for(fe(e,!0),typeof r!="undefined"&&s.setCaret(r);a.length;)s.removeItem(a.pop());return s.inputState(),s.positionDropdown(),s.refreshOptions(!1),!0}shouldDelete(e,t){let i=e.map(r=>r.dataset.value);return!(!i.length||typeof this.settings.onDelete=="function"&&this.settings.onDelete(i,t)===!1)}advanceSelection(e,t){var i,r,o=this;o.rtl&&(e*=-1),!o.inputValue().length&&(Mt(fi,t)||Mt("shiftKey",t)?(i=o.getLastActive(e),i?i.classList.contains("active")?r=o.getAdjacent(i,e,"item"):r=i:e>0?r=o.control_input.nextElementSibling:r=o.control_input.previousElementSibling,r&&(r.classList.contains("active")&&o.removeActiveItem(i),o.setActiveItemClass(r))):o.moveCaret(e))}moveCaret(e){}getLastActive(e){let t=this.control.querySelector(".last-active");if(t)return t;var i=this.control.querySelectorAll(".active");if(i)return zo(i,e)}setCaret(e){this.caretPos=this.items.length}controlChildren(){return Array.from(this.control.querySelectorAll("[data-ts-item]"))}lock(){this.setLocked(!0)}unlock(){this.setLocked(!1)}setLocked(e=this.isReadOnly||this.isDisabled){this.isLocked=e,this.refreshState()}disable(){this.setDisabled(!0),this.close()}enable(){this.setDisabled(!1)}setDisabled(e){this.focus_node.tabIndex=e?-1:this.tabIndex,this.isDisabled=e,this.input.disabled=e,this.control_input.disabled=e,this.setLocked()}setReadOnly(e){this.isReadOnly=e,this.input.readOnly=e,this.control_input.readOnly=e,this.setLocked()}destroy(){var e=this,t=e.revertSettings;e.trigger("destroy"),e.off(),e.wrapper.remove(),e.dropdown.remove(),e.input.innerHTML=t.innerHTML,e.input.tabIndex=t.tabIndex,gt(e.input,"tomselected","ts-hidden-accessible"),e._destroy(),delete e.input.tomselect}render(e,t){var i,r;let o=this;if(typeof this.settings.render[e]!="function"||(r=o.settings.render[e].call(this,t,ur),!r))return null;if(r=nt(r),e==="option"||e==="option_create"?t[o.settings.disabledField]?le(r,{"aria-disabled":"true"}):le(r,{"data-selectable":""}):e==="optgroup"&&(i=t.group[o.settings.optgroupValueField],le(r,{"data-group":i}),t.group[o.settings.disabledField]&&le(r,{"data-disabled":""})),e==="option"||e==="item"){let s=ci(t[o.settings.valueField]);le(r,{"data-value":s}),e==="item"?(Fe(r,o.settings.itemClass),le(r,{"data-ts-item":""})):(Fe(r,o.settings.optionClass),le(r,{role:"option",id:t.$id}),t.$div=r,o.options[s]=t)}return r}_render(e,t){let i=this.render(e,t);if(i==null)throw"HTMLElement expected";return i}clearCache(){ge(this.options,e=>{e.$div&&(e.$div.remove(),delete e.$div)})}uncacheValue(e){let t=this.getOption(e);t&&t.remove()}canCreate(e){return this.settings.create&&e.length>0&&this.settings.createFilter.call(this,e)}hook(e,t,i){var r=this,o=r[t];r[t]=function(){var s,a;return e==="after"&&(s=o.apply(r,arguments)),a=i.apply(r,arguments),e==="instead"?a:(e==="before"&&(s=o.apply(r,arguments)),s)}}};var bm=(n,e,t,i)=>{n.addEventListener(e,t,i)};function il(){bm(this.input,"change",()=>{this.sync()})}var _m=n=>typeof n=="undefined"||n===null?null:wm(n),wm=n=>typeof n=="boolean"?n?"1":"0":n+"",rl=(n,e=!1)=>{n&&(n.preventDefault(),e&&n.stopPropagation())},xm=n=>{if(n.jquery)return n[0];if(n instanceof HTMLElement)return n;if(Tm(n)){var e=document.createElement("template");return e.innerHTML=n.trim(),e.content.firstChild}return document.querySelector(n)},Tm=n=>typeof n=="string"&&n.indexOf("<")>-1;function ol(n){var e=this,t=e.onOptionSelect;e.settings.hideSelected=!1;let i=Object.assign({className:"tomselect-checkbox",checkedClassNames:void 0,uncheckedClassNames:void 0},n);var r=function(a,l){l?(a.checked=!0,i.uncheckedClassNames&&a.classList.remove(...i.uncheckedClassNames),i.checkedClassNames&&a.classList.add(...i.checkedClassNames)):(a.checked=!1,i.checkedClassNames&&a.classList.remove(...i.checkedClassNames),i.uncheckedClassNames&&a.classList.add(...i.uncheckedClassNames))},o=function(a){setTimeout(()=>{var l=a.querySelector("input."+i.className);l instanceof HTMLInputElement&&r(l,a.classList.contains("selected"))},1)};e.hook("after","setupTemplates",()=>{var s=e.settings.render.option;e.settings.render.option=(a,l)=>{var c=xm(s.call(e,a,l)),u=document.createElement("input");i.className&&u.classList.add(i.className),u.addEventListener("click",function(p){rl(p)}),u.type="checkbox";let d=_m(a[e.settings.valueField]);return r(u,!!(d&&e.items.indexOf(d)>-1)),c.prepend(u),c}}),e.on("item_remove",s=>{var a=e.getOption(s);a&&(a.classList.remove("selected"),o(a))}),e.on("item_add",s=>{var a=e.getOption(s);a&&o(a)}),e.hook("instead","onOptionSelect",(s,a)=>{if(a.classList.contains("selected")){a.classList.remove("selected"),e.removeItem(a.dataset.value),e.refreshOptions(),rl(s,!0);return}t.call(e,s,a),o(a)})}var Cm=n=>{if(n.jquery)return n[0];if(n instanceof HTMLElement)return n;if(Am(n)){var e=document.createElement("template");return e.innerHTML=n.trim(),e.content.firstChild}return document.querySelector(n)},Am=n=>typeof n=="string"&&n.indexOf("<")>-1;function sl(n){let e=this,t=Object.assign({className:"clear-button",title:"Clear All",html:i=>`
`},n);e.on("initialize",()=>{var i=Cm(t.html(t));i.addEventListener("click",r=>{e.isLocked||(e.clear(),e.settings.mode==="single"&&e.settings.allowEmptyOption&&e.addItem(""),r.preventDefault(),r.stopPropagation())}),e.control.appendChild(i)})}var Sm=(n,e=!1)=>{n&&(n.preventDefault(),e&&n.stopPropagation())},Dn=(n,e,t,i)=>{n.addEventListener(e,t,i)},Dm=(n,e)=>{if(Array.isArray(n))n.forEach(e);else for(var t in n)n.hasOwnProperty(t)&&e(n[t],t)},Om=n=>{if(n.jquery)return n[0];if(n instanceof HTMLElement)return n;if(Lm(n)){var e=document.createElement("template");return e.innerHTML=n.trim(),e.content.firstChild}return document.querySelector(n)},Lm=n=>typeof n=="string"&&n.indexOf("<")>-1,Mm=(n,e)=>{Dm(e,(t,i)=>{t==null?n.removeAttribute(i):n.setAttribute(i,""+t)})},Nm=(n,e)=>{var t;(t=n.parentNode)==null||t.insertBefore(e,n.nextSibling)},km=(n,e)=>{var t;(t=n.parentNode)==null||t.insertBefore(e,n)},Hm=(n,e)=>{do{var t;if(e=(t=e)==null?void 0:t.previousElementSibling,n==e)return!0}while(e&&e.previousElementSibling);return!1};function al(){var n=this;if(n.settings.mode!=="multi")return;var e=n.lock,t=n.unlock;let i=!0,r;n.hook("after","setupTemplates",()=>{var o=n.settings.render.item;n.settings.render.item=(s,a)=>{let l=Om(o.call(n,s,a));Mm(l,{draggable:"true"});let c=v=>{i||Sm(v),v.stopPropagation()},u=v=>{r=l,setTimeout(()=>{l.classList.add("ts-dragging")},0)},d=v=>{v.preventDefault(),l.classList.add("ts-drag-over"),y(l,r)},p=()=>{l.classList.remove("ts-drag-over")},y=(v,w)=>{w!==void 0&&(Hm(w,l)?Nm(v,w):km(v,w))},m=()=>{var v;document.querySelectorAll(".ts-drag-over").forEach(T=>T.classList.remove("ts-drag-over")),(v=r)==null||v.classList.remove("ts-dragging"),r=void 0;var w=[];n.control.querySelectorAll("[data-value]").forEach(T=>{if(T.dataset.value){let _=T.dataset.value;_&&w.push(_)}}),n.setValue(w)};return Dn(l,"mousedown",c),Dn(l,"dragstart",u),Dn(l,"dragenter",d),Dn(l,"dragover",d),Dn(l,"dragleave",p),Dn(l,"dragend",m),l}}),n.hook("instead","lock",()=>(i=!1,e.call(n))),n.hook("instead","unlock",()=>(i=!0,t.call(n)))}var Rm=(n,e=!1)=>{n&&(n.preventDefault(),e&&n.stopPropagation())},Im=n=>{if(n.jquery)return n[0];if(n instanceof HTMLElement)return n;if(Pm(n)){var e=document.createElement("template");return e.innerHTML=n.trim(),e.content.firstChild}return document.querySelector(n)},Pm=n=>typeof n=="string"&&n.indexOf("<")>-1;function ll(n){let e=this,t=Object.assign({title:"Untitled",headerClass:"dropdown-header",titleRowClass:"dropdown-header-title",labelClass:"dropdown-header-label",closeClass:"dropdown-header-close",html:i=>'
'+i.title+'×
'},n);e.on("initialize",()=>{var i=Im(t.html(t)),r=i.querySelector("."+t.closeClass);r&&r.addEventListener("click",o=>{Rm(o,!0),e.close()}),e.dropdown.insertBefore(i,e.dropdown.firstChild)})}var Fm=(n,e)=>{if(Array.isArray(n))n.forEach(e);else for(var t in n)n.hasOwnProperty(t)&&e(n[t],t)},$m=(n,...e)=>{var t=Bm(e);n=Vm(n),n.map(i=>{t.map(r=>{i.classList.remove(r)})})},Bm=n=>{var e=[];return Fm(n,t=>{typeof t=="string"&&(t=t.trim().split(/[\t\n\f\r\s]/)),Array.isArray(t)&&(e=e.concat(t))}),e.filter(Boolean)},Vm=n=>(Array.isArray(n)||(n=[n]),n),zm=(n,e)=>{if(!n)return-1;e=e||n.nodeName;for(var t=0;n=n.previousElementSibling;)n.matches(e)&&t++;return t};function cl(){var n=this;n.hook("instead","setCaret",e=>{n.settings.mode==="single"||!n.control.contains(n.control_input)?e=n.items.length:(e=Math.max(0,Math.min(n.items.length,e)),e!=n.caretPos&&!n.isPending&&n.controlChildren().forEach((t,i)=>{i{if(!n.isFocused)return;let t=n.getLastActive(e);if(t){let i=zm(t);n.setCaret(e>0?i+1:i),n.setActiveItem(),$m(t,"last-active")}else n.setCaret(n.caretPos+e)})}var jm=(n,e=!1)=>{n&&(n.preventDefault(),e&&n.stopPropagation())},Wm=(n,e,t,i)=>{n.addEventListener(e,t,i)},qm=(n,e)=>{if(Array.isArray(n))n.forEach(e);else for(var t in n)n.hasOwnProperty(t)&&e(n[t],t)},ul=n=>{if(n.jquery)return n[0];if(n instanceof HTMLElement)return n;if(Um(n)){var e=document.createElement("template");return e.innerHTML=n.trim(),e.content.firstChild}return document.querySelector(n)},Um=n=>typeof n=="string"&&n.indexOf("<")>-1,Ym=(n,...e)=>{var t=Gm(e);n=Km(n),n.map(i=>{t.map(r=>{i.classList.add(r)})})},Gm=n=>{var e=[];return qm(n,t=>{typeof t=="string"&&(t=t.trim().split(/[\t\n\f\r\s]/)),Array.isArray(t)&&(e=e.concat(t))}),e.filter(Boolean)},Km=n=>(Array.isArray(n)||(n=[n]),n);function dl(){let n=this;n.settings.shouldOpen=!0,n.hook("before","setup",()=>{n.focus_node=n.control,Ym(n.control_input,"dropdown-input");let e=ul('