@scalar/api-client 3.21.2 → 3.21.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/dist/style.css +18 -12
- package/dist/v2/blocks/operation-block/OperationBlock.vue.d.ts.map +1 -1
- package/dist/v2/blocks/operation-block/OperationBlock.vue.js.map +1 -1
- package/dist/v2/blocks/operation-block/OperationBlock.vue.script.js +11 -0
- package/dist/v2/blocks/operation-block/OperationBlock.vue.script.js.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestCodeSnippet.vue.d.ts.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestCodeSnippet.vue.js.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestCodeSnippet.vue.script.js +3 -0
- package/dist/v2/blocks/request-block/components/RequestCodeSnippet.vue.script.js.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestTableRow.vue.d.ts +2 -0
- package/dist/v2/blocks/request-block/components/RequestTableRow.vue.d.ts.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestTableRow.vue.js.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestTableRow.vue.script.js +3 -1
- package/dist/v2/blocks/request-block/components/RequestTableRow.vue.script.js.map +1 -1
- package/dist/v2/blocks/request-block/helpers/get-structured-body-rows.js +2 -1
- package/dist/v2/blocks/request-block/helpers/get-structured-body-rows.js.map +1 -1
- package/dist/v2/blocks/response-block/ResponseBlock.vue.d.ts +2 -0
- package/dist/v2/blocks/response-block/ResponseBlock.vue.d.ts.map +1 -1
- package/dist/v2/blocks/response-block/ResponseBlock.vue.js +1 -1
- package/dist/v2/blocks/response-block/ResponseBlock.vue.js.map +1 -1
- package/dist/v2/blocks/response-block/ResponseBlock.vue.script.js +26 -3
- package/dist/v2/blocks/response-block/ResponseBlock.vue.script.js.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/components/AuthSelector.vue.d.ts +2 -0
- package/dist/v2/blocks/scalar-auth-selector-block/components/AuthSelector.vue.d.ts.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/components/AuthSelector.vue.js.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/components/AuthSelector.vue.script.js +59 -42
- package/dist/v2/blocks/scalar-auth-selector-block/components/AuthSelector.vue.script.js.map +1 -1
- package/dist/v2/components/code-input/CodeInputLite.vue.d.ts +6 -2
- package/dist/v2/components/code-input/CodeInputLite.vue.d.ts.map +1 -1
- package/dist/v2/components/code-input/CodeInputLite.vue.js +1 -1
- package/dist/v2/components/code-input/CodeInputLite.vue.js.map +1 -1
- package/dist/v2/components/code-input/CodeInputLite.vue.script.js +3 -0
- package/dist/v2/components/code-input/CodeInputLite.vue.script.js.map +1 -1
- package/dist/v2/components/data-table/DataTableInputSelect.vue.d.ts +4 -4
- package/dist/v2/components/data-table/DataTableInputSelect.vue.d.ts.map +1 -1
- package/dist/v2/components/data-table/DataTableInputSelect.vue.js.map +1 -1
- package/dist/v2/components/data-table/DataTableInputSelect.vue.script.js +22 -16
- package/dist/v2/components/data-table/DataTableInputSelect.vue.script.js.map +1 -1
- package/dist/v2/constants.js +1 -1
- package/dist/v2/features/localization/locales/ar.d.ts +2 -0
- package/dist/v2/features/localization/locales/ar.d.ts.map +1 -1
- package/dist/v2/features/localization/locales/ar.js +2 -0
- package/dist/v2/features/localization/locales/ar.js.map +1 -1
- package/dist/v2/features/localization/locales/de.d.ts +2 -0
- package/dist/v2/features/localization/locales/de.d.ts.map +1 -1
- package/dist/v2/features/localization/locales/de.js +2 -0
- package/dist/v2/features/localization/locales/de.js.map +1 -1
- package/dist/v2/features/localization/locales/es.d.ts +2 -0
- package/dist/v2/features/localization/locales/es.d.ts.map +1 -1
- package/dist/v2/features/localization/locales/es.js +2 -0
- package/dist/v2/features/localization/locales/es.js.map +1 -1
- package/dist/v2/features/localization/locales/fr.d.ts +2 -0
- package/dist/v2/features/localization/locales/fr.d.ts.map +1 -1
- package/dist/v2/features/localization/locales/fr.js +2 -0
- package/dist/v2/features/localization/locales/fr.js.map +1 -1
- package/dist/v2/features/localization/locales/pt.d.ts +2 -0
- package/dist/v2/features/localization/locales/pt.d.ts.map +1 -1
- package/dist/v2/features/localization/locales/pt.js +2 -0
- package/dist/v2/features/localization/locales/pt.js.map +1 -1
- package/dist/v2/features/localization/locales/ru.d.ts +2 -0
- package/dist/v2/features/localization/locales/ru.d.ts.map +1 -1
- package/dist/v2/features/localization/locales/ru.js +2 -0
- package/dist/v2/features/localization/locales/ru.js.map +1 -1
- package/dist/v2/features/localization/locales/zh-cn.d.ts +2 -0
- package/dist/v2/features/localization/locales/zh-cn.d.ts.map +1 -1
- package/dist/v2/features/localization/locales/zh-cn.js +2 -0
- package/dist/v2/features/localization/locales/zh-cn.js.map +1 -1
- package/dist/v2/features/localization/translations.d.ts +2 -0
- package/dist/v2/features/localization/translations.d.ts.map +1 -1
- package/dist/v2/features/localization/translations.js +2 -0
- package/dist/v2/features/localization/translations.js.map +1 -1
- package/dist/v2/features/search/helpers/create-fuse-instance.js +1 -1
- package/dist/v2/features/search/helpers/create-fuse-instance.js.map +1 -1
- package/dist/vue-styles.css +11 -11
- package/package.json +9 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AuthSelector.vue.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/components/AuthSelector.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport {\n ScalarButton,\n type ScalarButton as ScalarButtonType,\n} from '@scalar/components/button'\nimport { ScalarComboboxMultiselect } from '@scalar/components/combobox'\nimport type { Icon } from '@scalar/components/icon'\nimport { ScalarIconButton } from '@scalar/components/icon-button'\nimport { ScalarListboxCheckbox } from '@scalar/components/listbox'\nimport { useModal } from '@scalar/components/modal'\nimport { ScalarIconCaretDown, ScalarIconTrash } from '@scalar/icons'\nimport type { SelectedSecurity } from '@scalar/workspace-store/entities/auth'\nimport type {\n AuthMeta,\n WorkspaceEventBus,\n} from '@scalar/workspace-store/events'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport { unpackProxyObject } from '@scalar/workspace-store/helpers/unpack-proxy'\nimport {\n isAuthOptional,\n type MergedSecuritySchemes,\n} from '@scalar/workspace-store/request-example'\nimport type { XScalarEnvironment } from '@scalar/workspace-store/schemas/extensions/document/x-scalar-environments'\nimport type {\n OpenApiDocument,\n SecurityRequirementObject,\n ServerObject,\n} from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\nimport { computed, ref, useId } from 'vue'\n\nimport DeleteRequestAuthModal from '@/v2/blocks/scalar-auth-selector-block/components/DeleteRequestAuthModal.vue'\nimport type { OAuth2Options } from '@/v2/blocks/scalar-auth-selector-block/components/OAuth2.vue'\nimport {\n formatComplexScheme,\n formatScheme,\n getSecuritySchemeOptions,\n type SecuritySchemeOption,\n} from '@/v2/blocks/scalar-auth-selector-block/helpers/security-scheme'\nimport { CollapsibleSection } from '@/v2/components/layout'\nimport { useLocalization } from '@/v2/features/localization'\n\nimport RequestAuthDataTable from './RequestAuthDataTable.vue'\n\nconst {\n environment,\n eventBus,\n createAnySecurityScheme = false,\n canDeleteSchemes = true,\n defaultOpen = true,\n heading = true,\n isStatic = false,\n meta,\n proxyUrl,\n securityRequirements,\n securitySchemes,\n selectedSecurity,\n server,\n title,\n options,\n documentType,\n} = defineProps<{\n environment: XScalarEnvironment\n eventBus: WorkspaceEventBus\n /** Allows adding authentication which is not in the document */\n createAnySecurityScheme?: boolean\n /**\n * Whether schemes can be deleted from the selector. Enabled for the editable client, disabled in\n * the read-only reference where the schemes come from the document and cannot be removed.\n */\n canDeleteSchemes?: boolean\n /** Whether the authentication disclosure should start expanded */\n defaultOpen?: boolean\n /**\n * Whether the title belongs in the document outline. The client renders the\n * selector as one section of a request, so it is a heading there. A surface\n * that only offers the schemes as a card of controls, such as the reference,\n * turns it off and the card is named as a group instead.\n */\n heading?: boolean\n /** Creates a static disclosure that cannot be collapsed */\n isStatic?: boolean\n meta: AuthMeta\n proxyUrl: string\n securityRequirements: OpenApiDocument['security']\n securitySchemes: MergedSecuritySchemes\n selectedSecurity: SelectedSecurity | undefined\n server: ServerObject | null\n title: string\n /** Any config options required for the OAuth2 flow */\n options?: OAuth2Options\n /** Type of the document the schemes belong to, used to label the missing-type warning */\n documentType?: 'openapi' | 'asyncapi'\n}>()\n\nconst { translate, translations } = useLocalization()\n\nconst titleId = useId()\nconst comboboxButtonRef = ref<typeof ScalarButtonType | null>(null)\nconst isDisclosureOpen = ref(false)\n\nconst deleteModal = useModal()\nconst schemeToDelete = ref<{\n label: string\n payload: SecurityRequirementObject\n} | null>(null)\n\n/**\n * Determines if authentication is required or optional\n *\n * Auth is optional when there is an empty security requirement and no complex requirements.\n * Complex requirements have multiple auth schemes combined (e.g., API key + OAuth).\n */\nconst authIndicator = computed<{ icon: Icon; text: string } | null>(() => {\n if (!securityRequirements?.length) {\n return null\n }\n\n const isOptional = isAuthOptional(securityRequirements)\n\n return {\n icon: isOptional ? 'Unlock' : 'Lock',\n text: isOptional\n ? translate('apiClient.authSelector.optional')\n : translate('apiClient.authSelector.required'),\n }\n})\n\n/** All available auth scheme options for the dropdown */\nconst availableSchemeOptions = computed(() =>\n getSecuritySchemeOptions(\n securityRequirements ?? [],\n securitySchemes ?? {},\n selectedSecurity?.selectedSchemes ?? [],\n createAnySecurityScheme,\n translations.value.apiClient,\n ),\n)\n\n/** Currently active auth schemes selected for this operation or collection */\nconst activeSchemeOptions = computed<SecuritySchemeOption[]>(() => {\n const schemes = selectedSecurity?.selectedSchemes\n if (!schemes?.length) {\n return []\n }\n\n return schemes.flatMap((requirement) => {\n const schemeNames = Object.keys(requirement)\n\n if (schemeNames.length === 0) {\n return []\n }\n\n // Complex auth requirement with multiple schemes\n if (schemeNames.length > 1) {\n return formatComplexScheme(requirement)\n }\n\n // Simple auth requirement with single scheme\n const schemeName = schemeNames[0]\n if (!schemeName) {\n return []\n }\n\n const scheme = getResolvedRef(securitySchemes?.[schemeName])\n if (!scheme) {\n return []\n }\n\n return formatScheme({\n name: schemeName,\n value: requirement,\n })\n })\n})\n\n/**\n * Opens the combobox dropdown when clicking the auth indicator badge.\n * Prevents the disclosure from toggling if it is already open.\n */\nconst handleAuthIndicatorClick = (event: Event): void => {\n if (isDisclosureOpen.value) {\n event.stopPropagation()\n }\n comboboxButtonRef.value?.$el.click()\n}\n\n/**\n * Updates the selected auth schemes.\n * Separates existing schemes from newly created ones for the event payload.\n */\nconst handleSchemeSelection = (selected: SecuritySchemeOption[]): void => {\n const existingSchemes = selected\n .filter((option) => option.payload === undefined)\n .map((option) => unpackProxyObject(option.value, { depth: 2 }))\n\n const newSchemes = selected\n .filter((option) => option.payload !== undefined)\n .map((option) => ({\n name: option.label,\n scheme: option.payload!,\n }))\n\n eventBus.emit('auth:update:selected-security-schemes', {\n selectedRequirements: existingSchemes,\n newSchemes,\n meta,\n })\n}\n\n/** Shows the delete confirmation modal for the selected scheme */\nconst handleDeleteRequest = (option: {\n label: string\n value: SecurityRequirementObject\n}): void => {\n schemeToDelete.value = { label: option.label, payload: option.value }\n deleteModal.show()\n}\n\n/** Deletes the selected auth scheme after confirmation */\nconst handleDeleteConfirm = (): void => {\n if (!schemeToDelete.value) {\n return\n }\n\n eventBus.emit('auth:delete:security-scheme', {\n names: Object.keys(schemeToDelete.value.payload),\n })\n\n schemeToDelete.value = null\n deleteModal.hide()\n}\n\ndefineExpose({\n authIndicator,\n selectedSchemeOptions: activeSchemeOptions,\n schemeOptions: availableSchemeOptions,\n})\n</script>\n<template>\n <CollapsibleSection\n class=\"group/params relative\"\n :defaultOpen\n :heading\n :isStatic=\"isStatic\"\n :itemCount=\"activeSchemeOptions.length\"\n @update:modelValue=\"(open) => (isDisclosureOpen = open)\">\n <template #title>\n <div\n :id=\"titleId\"\n class=\"inline-flex items-center gap-0.5 leading-[20px]\">\n <span>{{ title }}</span>\n\n <span\n v-if=\"authIndicator\"\n class=\"text-c-3 hover:bg-b-3 hover:text-c-1 -my-0.5 -mr-1 cursor-pointer rounded px-1 py-0.5 leading-[normal] font-normal\"\n :class=\"{ 'text-c-1': authIndicator.icon === 'Lock' }\"\n data-testid=\"auth-indicator\"\n @click=\"handleAuthIndicatorClick\">\n {{ authIndicator.text }}\n </span>\n </div>\n </template>\n\n <!-- Auth Dropdown (hidden when only one scheme is available) -->\n <template #actions>\n <ScalarComboboxMultiselect\n class=\"w-72 text-xs\"\n :modelValue=\"activeSchemeOptions\"\n multiple\n :options=\"availableSchemeOptions\"\n placement=\"bottom-end\"\n teleport\n @delete=\"handleDeleteRequest\"\n @update:modelValue=\"handleSchemeSelection\">\n <ScalarButton\n ref=\"comboboxButtonRef\"\n :aria-describedby=\"titleId\"\n class=\"group/combobox-button hover:text-c-1 text-c-2 flex h-fit w-full items-center gap-1 px-0.75 py-0.25 text-base font-normal\"\n variant=\"ghost\">\n <!-- Single auth scheme selected -->\n <template v-if=\"activeSchemeOptions.length === 1\">\n {{\n translate('apiClient.authSelector.selectedType', {\n type: activeSchemeOptions[0]?.label ?? '',\n })\n }}\n </template>\n\n <!-- Multiple auth schemes selected -->\n <template v-else-if=\"activeSchemeOptions.length > 1\">\n {{ translate('apiClient.authSelector.multipleTypes') }}\n </template>\n\n <!-- No auth schemes selected -->\n <template v-else>\n {{ translate('apiClient.authSelector.selectType') }}\n </template>\n\n <ScalarIconCaretDown\n class=\"size-3 shrink-0 transition-transform duration-100 group-aria-expanded/combobox-button:rotate-180\"\n weight=\"bold\" />\n </ScalarButton>\n\n <template #option=\"{ option, selected }\">\n <ScalarListboxCheckbox\n multiselect\n :selected=\"selected\" />\n <div class=\"min-w-0 flex-1 truncate\">\n {{ option.label }}\n </div>\n <ScalarIconButton\n v-if=\"option.isDeletable && canDeleteSchemes\"\n class=\"-m-0.5 shrink-0 p-0.5 opacity-0 group-hover/item:opacity-100\"\n :icon=\"ScalarIconTrash\"\n :label=\"\n translate('apiClient.authSelector.deleteScheme', {\n name: option.label,\n })\n \"\n size=\"xs\"\n @click.stop=\"handleDeleteRequest(option)\" />\n </template>\n </ScalarComboboxMultiselect>\n </template>\n\n <!-- Auth Table -->\n <RequestAuthDataTable\n :activeAuthIndex=\"selectedSecurity?.selectedIndex ?? 0\"\n :documentType\n :environment\n :eventBus\n :isStatic\n :meta\n :options\n :proxyUrl\n :securitySchemes\n :selectedSchemeOptions=\"activeSchemeOptions\"\n :server />\n\n <!-- Delete Auth Modal -->\n <DeleteRequestAuthModal\n v-if=\"schemeToDelete\"\n :label=\"schemeToDelete.label\"\n :scheme=\"schemeToDelete\"\n :state=\"deleteModal\"\n @close=\"deleteModal.hide()\"\n @delete=\"handleDeleteConfirm\" />\n </CollapsibleSection>\n</template>\n"],"mappings":""}
|
|
1
|
+
{"version":3,"file":"AuthSelector.vue.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/components/AuthSelector.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport {\n ScalarButton,\n type ScalarButton as ScalarButtonType,\n} from '@scalar/components/button'\nimport { ScalarComboboxMultiselect } from '@scalar/components/combobox'\nimport type { Icon } from '@scalar/components/icon'\nimport { ScalarIconButton } from '@scalar/components/icon-button'\nimport { ScalarListboxCheckbox } from '@scalar/components/listbox'\nimport { useModal } from '@scalar/components/modal'\nimport { ScalarIconCaretDown, ScalarIconTrash } from '@scalar/icons'\nimport type { SelectedSecurity } from '@scalar/workspace-store/entities/auth'\nimport type {\n AuthMeta,\n WorkspaceEventBus,\n} from '@scalar/workspace-store/events'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport { unpackProxyObject } from '@scalar/workspace-store/helpers/unpack-proxy'\nimport {\n isAuthOptional,\n type MergedSecuritySchemes,\n} from '@scalar/workspace-store/request-example'\nimport type { XScalarEnvironment } from '@scalar/workspace-store/schemas/extensions/document/x-scalar-environments'\nimport type {\n OpenApiDocument,\n SecurityRequirementObject,\n ServerObject,\n} from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\nimport { computed, ref, useId } from 'vue'\n\nimport DeleteRequestAuthModal from '@/v2/blocks/scalar-auth-selector-block/components/DeleteRequestAuthModal.vue'\nimport type { OAuth2Options } from '@/v2/blocks/scalar-auth-selector-block/components/OAuth2.vue'\nimport {\n formatComplexScheme,\n formatScheme,\n getSecuritySchemeOptions,\n type SecuritySchemeOption,\n} from '@/v2/blocks/scalar-auth-selector-block/helpers/security-scheme'\nimport { CollapsibleSection } from '@/v2/components/layout'\nimport { useLocalization } from '@/v2/features/localization'\n\nimport RequestAuthDataTable from './RequestAuthDataTable.vue'\n\nconst {\n environment,\n eventBus,\n createAnySecurityScheme = false,\n canDeleteSchemes = true,\n defaultOpen = true,\n heading = true,\n hideSingleRequiredScheme = false,\n isStatic = false,\n meta,\n proxyUrl,\n securityRequirements,\n securitySchemes,\n selectedSecurity,\n server,\n title,\n options,\n documentType,\n} = defineProps<{\n environment: XScalarEnvironment\n eventBus: WorkspaceEventBus\n /** Allows adding authentication which is not in the document */\n createAnySecurityScheme?: boolean\n /**\n * Whether schemes can be deleted from the selector. Enabled for the editable client, disabled in\n * the read-only reference where the schemes come from the document and cannot be removed.\n */\n canDeleteSchemes?: boolean\n /** Whether the authentication disclosure should start expanded */\n defaultOpen?: boolean\n /**\n * Whether the title belongs in the document outline. The client renders the\n * selector as one section of a request, so it is a heading there. A surface\n * that only offers the schemes as a card of controls, such as the reference,\n * turns it off and the card is named as a group instead.\n */\n heading?: boolean\n /** Hides a sole active required choice in the reference while preserving client controls. */\n hideSingleRequiredScheme?: boolean\n /** Creates a static disclosure that cannot be collapsed */\n isStatic?: boolean\n meta: AuthMeta\n proxyUrl: string\n securityRequirements: OpenApiDocument['security']\n securitySchemes: MergedSecuritySchemes\n selectedSecurity: SelectedSecurity | undefined\n server: ServerObject | null\n title: string\n /** Any config options required for the OAuth2 flow */\n options?: OAuth2Options\n /** Type of the document the schemes belong to, used to label the missing-type warning */\n documentType?: 'openapi' | 'asyncapi'\n}>()\n\nconst { translate, translations } = useLocalization()\n\nconst titleId = useId()\nconst comboboxButtonRef = ref<typeof ScalarButtonType | null>(null)\nconst isDisclosureOpen = ref(false)\n\nconst deleteModal = useModal()\nconst schemeToDelete = ref<{\n label: string\n payload: SecurityRequirementObject\n} | null>(null)\n\n/**\n * Determines if authentication is required or optional\n *\n * Auth is optional when there is an empty security requirement and no complex requirements.\n * Complex requirements have multiple auth schemes combined (e.g., API key + OAuth).\n */\nconst authIndicator = computed<{ icon: Icon; text: string } | null>(() => {\n if (!securityRequirements?.length) {\n return null\n }\n\n const isOptional = isAuthOptional(securityRequirements)\n\n return {\n icon: isOptional ? 'Unlock' : 'Lock',\n text: isOptional\n ? translate('apiClient.authSelector.optional')\n : translate('apiClient.authSelector.required'),\n }\n})\n\n/** All available auth scheme options for the dropdown */\nconst availableSchemeOptions = computed(() =>\n getSecuritySchemeOptions(\n securityRequirements ?? [],\n securitySchemes ?? {},\n selectedSecurity?.selectedSchemes ?? [],\n createAnySecurityScheme,\n translations.value.apiClient,\n ),\n)\n\n/** Currently active auth schemes selected for this operation or collection */\nconst activeSchemeOptions = computed<SecuritySchemeOption[]>(() => {\n const schemes = selectedSecurity?.selectedSchemes\n if (!schemes?.length) {\n return []\n }\n\n return schemes.flatMap((requirement) => {\n const schemeNames = Object.keys(requirement)\n\n if (schemeNames.length === 0) {\n return []\n }\n\n // Complex auth requirement with multiple schemes\n if (schemeNames.length > 1) {\n return formatComplexScheme(requirement)\n }\n\n // Simple auth requirement with single scheme\n const schemeName = schemeNames[0]\n if (!schemeName) {\n return []\n }\n\n const scheme = getResolvedRef(securitySchemes?.[schemeName])\n if (!scheme) {\n return []\n }\n\n return formatScheme({\n name: schemeName,\n value: requirement,\n })\n })\n})\n\n/** Keep selection available whenever it can change auth or recover an empty saved selection. */\nconst showSchemeSelector = computed<boolean>(() => {\n if (\n !hideSingleRequiredScheme ||\n createAnySecurityScheme ||\n securityRequirements?.length !== 1 ||\n Object.keys(securityRequirements[0] ?? {}).length === 0\n ) {\n return true\n }\n\n const schemeOptions = availableSchemeOptions.value.flatMap((option) =>\n 'options' in option ? option.options : [option],\n )\n\n return (\n schemeOptions.length !== 1 ||\n activeSchemeOptions.value.length !== 1 ||\n activeSchemeOptions.value[0]?.id !== schemeOptions[0]?.id\n )\n})\n\n/**\n * Opens the combobox dropdown when clicking the auth indicator badge.\n * Prevents the disclosure from toggling if it is already open.\n */\nconst handleAuthIndicatorClick = (event: Event): void => {\n if (!showSchemeSelector.value) {\n return\n }\n\n if (isDisclosureOpen.value) {\n event.stopPropagation()\n }\n comboboxButtonRef.value?.$el.click()\n}\n\n/**\n * Updates the selected auth schemes.\n * Separates existing schemes from newly created ones for the event payload.\n */\nconst handleSchemeSelection = (selected: SecuritySchemeOption[]): void => {\n const existingSchemes = selected\n .filter((option) => option.payload === undefined)\n .map((option) => unpackProxyObject(option.value, { depth: 2 }))\n\n const newSchemes = selected\n .filter((option) => option.payload !== undefined)\n .map((option) => ({\n name: option.label,\n scheme: option.payload!,\n }))\n\n eventBus.emit('auth:update:selected-security-schemes', {\n selectedRequirements: existingSchemes,\n newSchemes,\n meta,\n })\n}\n\n/** Shows the delete confirmation modal for the selected scheme */\nconst handleDeleteRequest = (option: {\n label: string\n value: SecurityRequirementObject\n}): void => {\n schemeToDelete.value = { label: option.label, payload: option.value }\n deleteModal.show()\n}\n\n/** Deletes the selected auth scheme after confirmation */\nconst handleDeleteConfirm = (): void => {\n if (!schemeToDelete.value) {\n return\n }\n\n eventBus.emit('auth:delete:security-scheme', {\n names: Object.keys(schemeToDelete.value.payload),\n })\n\n schemeToDelete.value = null\n deleteModal.hide()\n}\n\ndefineExpose({\n authIndicator,\n selectedSchemeOptions: activeSchemeOptions,\n schemeOptions: availableSchemeOptions,\n})\n</script>\n<template>\n <CollapsibleSection\n class=\"group/params relative\"\n :defaultOpen\n :heading\n :isStatic=\"isStatic\"\n :itemCount=\"activeSchemeOptions.length\"\n @update:modelValue=\"(open) => (isDisclosureOpen = open)\">\n <template #title>\n <div\n :id=\"titleId\"\n class=\"inline-flex items-center gap-0.5 leading-[20px]\">\n <span>{{ title }}</span>\n\n <span\n v-if=\"authIndicator\"\n class=\"text-c-3 -my-0.5 -mr-1 rounded px-1 py-0.5 leading-[normal] font-normal\"\n :class=\"{\n 'text-c-1': authIndicator.icon === 'Lock',\n 'hover:bg-b-3 hover:text-c-1 cursor-pointer': showSchemeSelector,\n }\"\n data-testid=\"auth-indicator\"\n @click=\"handleAuthIndicatorClick\">\n {{ authIndicator.text }}\n </span>\n </div>\n </template>\n\n <!-- The client keeps its selection and deletion controls. -->\n <template\n v-if=\"showSchemeSelector\"\n #actions>\n <ScalarComboboxMultiselect\n class=\"w-72 text-xs\"\n :modelValue=\"activeSchemeOptions\"\n multiple\n :options=\"availableSchemeOptions\"\n placement=\"bottom-end\"\n teleport\n @delete=\"handleDeleteRequest\"\n @update:modelValue=\"handleSchemeSelection\">\n <ScalarButton\n ref=\"comboboxButtonRef\"\n :aria-describedby=\"titleId\"\n class=\"group/combobox-button hover:text-c-1 text-c-2 flex h-fit w-full items-center gap-1 px-0.75 py-0.25 text-base font-normal\"\n variant=\"ghost\">\n <!-- Single auth scheme selected -->\n <template v-if=\"activeSchemeOptions.length === 1\">\n {{\n translate('apiClient.authSelector.selectedType', {\n type: activeSchemeOptions[0]?.label ?? '',\n })\n }}\n </template>\n\n <!-- Multiple auth schemes selected -->\n <template v-else-if=\"activeSchemeOptions.length > 1\">\n {{ translate('apiClient.authSelector.multipleTypes') }}\n </template>\n\n <!-- No auth schemes selected -->\n <template v-else>\n {{ translate('apiClient.authSelector.selectType') }}\n </template>\n\n <ScalarIconCaretDown\n class=\"size-3 shrink-0 transition-transform duration-100 group-aria-expanded/combobox-button:rotate-180\"\n weight=\"bold\" />\n </ScalarButton>\n\n <template #option=\"{ option, selected }\">\n <ScalarListboxCheckbox\n multiselect\n :selected=\"selected\" />\n <div class=\"min-w-0 flex-1 truncate\">\n {{ option.label }}\n </div>\n <ScalarIconButton\n v-if=\"option.isDeletable && canDeleteSchemes\"\n class=\"-m-0.5 shrink-0 p-0.5 opacity-0 group-hover/item:opacity-100\"\n :icon=\"ScalarIconTrash\"\n :label=\"\n translate('apiClient.authSelector.deleteScheme', {\n name: option.label,\n })\n \"\n size=\"xs\"\n @click.stop=\"handleDeleteRequest(option)\" />\n </template>\n </ScalarComboboxMultiselect>\n </template>\n\n <!-- Auth Table -->\n <RequestAuthDataTable\n :activeAuthIndex=\"selectedSecurity?.selectedIndex ?? 0\"\n :documentType\n :environment\n :eventBus\n :isStatic\n :meta\n :options\n :proxyUrl\n :securitySchemes\n :selectedSchemeOptions=\"activeSchemeOptions\"\n :server />\n\n <!-- Delete Auth Modal -->\n <DeleteRequestAuthModal\n v-if=\"schemeToDelete\"\n :label=\"schemeToDelete.label\"\n :scheme=\"schemeToDelete\"\n :state=\"deleteModal\"\n @close=\"deleteModal.hide()\"\n @delete=\"handleDeleteConfirm\" />\n </CollapsibleSection>\n</template>\n"],"mappings":""}
|
|
@@ -3,7 +3,7 @@ import CollapsibleSection_default from "../../../components/layout/CollapsibleSe
|
|
|
3
3
|
import DeleteRequestAuthModal_default from "./DeleteRequestAuthModal.vue.js";
|
|
4
4
|
import { formatComplexScheme, formatScheme, getSecuritySchemeOptions } from "../helpers/security-scheme.js";
|
|
5
5
|
import RequestAuthDataTable_default from "./RequestAuthDataTable.vue.js";
|
|
6
|
-
import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createTextVNode, createVNode, defineComponent, normalizeClass, openBlock, ref, toDisplayString, unref, useId, withCtx, withModifiers } from "vue";
|
|
6
|
+
import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createSlots, createTextVNode, createVNode, defineComponent, normalizeClass, openBlock, ref, toDisplayString, unref, useId, withCtx, withModifiers } from "vue";
|
|
7
7
|
import { ScalarButton } from "@scalar/components/button";
|
|
8
8
|
import { ScalarListboxCheckbox } from "@scalar/components/listbox";
|
|
9
9
|
import { ScalarIconCaretDown, ScalarIconTrash } from "@scalar/icons";
|
|
@@ -37,6 +37,10 @@ var AuthSelector_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ def
|
|
|
37
37
|
type: Boolean,
|
|
38
38
|
default: true
|
|
39
39
|
},
|
|
40
|
+
hideSingleRequiredScheme: {
|
|
41
|
+
type: Boolean,
|
|
42
|
+
default: false
|
|
43
|
+
},
|
|
40
44
|
isStatic: {
|
|
41
45
|
type: Boolean,
|
|
42
46
|
default: false
|
|
@@ -91,11 +95,18 @@ var AuthSelector_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ def
|
|
|
91
95
|
});
|
|
92
96
|
});
|
|
93
97
|
});
|
|
98
|
+
/** Keep selection available whenever it can change auth or recover an empty saved selection. */
|
|
99
|
+
const showSchemeSelector = computed(() => {
|
|
100
|
+
if (!__props.hideSingleRequiredScheme || __props.createAnySecurityScheme || __props.securityRequirements?.length !== 1 || Object.keys(__props.securityRequirements[0] ?? {}).length === 0) return true;
|
|
101
|
+
const schemeOptions = availableSchemeOptions.value.flatMap((option) => "options" in option ? option.options : [option]);
|
|
102
|
+
return schemeOptions.length !== 1 || activeSchemeOptions.value.length !== 1 || activeSchemeOptions.value[0]?.id !== schemeOptions[0]?.id;
|
|
103
|
+
});
|
|
94
104
|
/**
|
|
95
105
|
* Opens the combobox dropdown when clicking the auth indicator badge.
|
|
96
106
|
* Prevents the disclosure from toggling if it is already open.
|
|
97
107
|
*/
|
|
98
108
|
const handleAuthIndicatorClick = (event) => {
|
|
109
|
+
if (!showSchemeSelector.value) return;
|
|
99
110
|
if (isDisclosureOpen.value) event.stopPropagation();
|
|
100
111
|
comboboxButtonRef.value?.$el.click();
|
|
101
112
|
};
|
|
@@ -143,17 +154,59 @@ var AuthSelector_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ def
|
|
|
143
154
|
isStatic: __props.isStatic,
|
|
144
155
|
itemCount: activeSchemeOptions.value.length,
|
|
145
156
|
"onUpdate:modelValue": _cache[1] || (_cache[1] = (open) => isDisclosureOpen.value = open)
|
|
146
|
-
}, {
|
|
157
|
+
}, createSlots({
|
|
147
158
|
title: withCtx(() => [createElementVNode("div", {
|
|
148
159
|
id: unref(titleId),
|
|
149
160
|
class: "inline-flex items-center gap-0.5 leading-[20px]"
|
|
150
161
|
}, [createElementVNode("span", null, toDisplayString(__props.title), 1), authIndicator.value ? (openBlock(), createElementBlock("span", {
|
|
151
162
|
key: 0,
|
|
152
|
-
class: normalizeClass(["text-c-3
|
|
163
|
+
class: normalizeClass(["text-c-3 -my-0.5 -mr-1 rounded px-1 py-0.5 leading-[normal] font-normal", {
|
|
164
|
+
"text-c-1": authIndicator.value.icon === "Lock",
|
|
165
|
+
"hover:bg-b-3 hover:text-c-1 cursor-pointer": showSchemeSelector.value
|
|
166
|
+
}]),
|
|
153
167
|
"data-testid": "auth-indicator",
|
|
154
168
|
onClick: handleAuthIndicatorClick
|
|
155
169
|
}, toDisplayString(authIndicator.value.text), 3)) : createCommentVNode("", true)], 8, _hoisted_1)]),
|
|
156
|
-
|
|
170
|
+
default: withCtx(() => [createVNode(RequestAuthDataTable_default, {
|
|
171
|
+
activeAuthIndex: __props.selectedSecurity?.selectedIndex ?? 0,
|
|
172
|
+
documentType: __props.documentType,
|
|
173
|
+
environment: __props.environment,
|
|
174
|
+
eventBus: __props.eventBus,
|
|
175
|
+
isStatic: __props.isStatic,
|
|
176
|
+
meta: __props.meta,
|
|
177
|
+
options: __props.options,
|
|
178
|
+
proxyUrl: __props.proxyUrl,
|
|
179
|
+
securitySchemes: __props.securitySchemes,
|
|
180
|
+
selectedSchemeOptions: activeSchemeOptions.value,
|
|
181
|
+
server: __props.server
|
|
182
|
+
}, null, 8, [
|
|
183
|
+
"activeAuthIndex",
|
|
184
|
+
"documentType",
|
|
185
|
+
"environment",
|
|
186
|
+
"eventBus",
|
|
187
|
+
"isStatic",
|
|
188
|
+
"meta",
|
|
189
|
+
"options",
|
|
190
|
+
"proxyUrl",
|
|
191
|
+
"securitySchemes",
|
|
192
|
+
"selectedSchemeOptions",
|
|
193
|
+
"server"
|
|
194
|
+
]), schemeToDelete.value ? (openBlock(), createBlock(DeleteRequestAuthModal_default, {
|
|
195
|
+
key: 0,
|
|
196
|
+
label: schemeToDelete.value.label,
|
|
197
|
+
scheme: schemeToDelete.value,
|
|
198
|
+
state: unref(deleteModal),
|
|
199
|
+
onClose: _cache[0] || (_cache[0] = ($event) => unref(deleteModal).hide()),
|
|
200
|
+
onDelete: handleDeleteConfirm
|
|
201
|
+
}, null, 8, [
|
|
202
|
+
"label",
|
|
203
|
+
"scheme",
|
|
204
|
+
"state"
|
|
205
|
+
])) : createCommentVNode("", true)]),
|
|
206
|
+
_: 2
|
|
207
|
+
}, [showSchemeSelector.value ? {
|
|
208
|
+
name: "actions",
|
|
209
|
+
fn: withCtx(() => [createVNode(unref(ScalarComboboxMultiselect), {
|
|
157
210
|
class: "w-72 text-xs",
|
|
158
211
|
modelValue: activeSchemeOptions.value,
|
|
159
212
|
multiple: "",
|
|
@@ -197,44 +250,8 @@ var AuthSelector_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ def
|
|
|
197
250
|
}, 8, ["aria-describedby"])]),
|
|
198
251
|
_: 1
|
|
199
252
|
}, 8, ["modelValue", "options"])]),
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
documentType: __props.documentType,
|
|
203
|
-
environment: __props.environment,
|
|
204
|
-
eventBus: __props.eventBus,
|
|
205
|
-
isStatic: __props.isStatic,
|
|
206
|
-
meta: __props.meta,
|
|
207
|
-
options: __props.options,
|
|
208
|
-
proxyUrl: __props.proxyUrl,
|
|
209
|
-
securitySchemes: __props.securitySchemes,
|
|
210
|
-
selectedSchemeOptions: activeSchemeOptions.value,
|
|
211
|
-
server: __props.server
|
|
212
|
-
}, null, 8, [
|
|
213
|
-
"activeAuthIndex",
|
|
214
|
-
"documentType",
|
|
215
|
-
"environment",
|
|
216
|
-
"eventBus",
|
|
217
|
-
"isStatic",
|
|
218
|
-
"meta",
|
|
219
|
-
"options",
|
|
220
|
-
"proxyUrl",
|
|
221
|
-
"securitySchemes",
|
|
222
|
-
"selectedSchemeOptions",
|
|
223
|
-
"server"
|
|
224
|
-
]), schemeToDelete.value ? (openBlock(), createBlock(DeleteRequestAuthModal_default, {
|
|
225
|
-
key: 0,
|
|
226
|
-
label: schemeToDelete.value.label,
|
|
227
|
-
scheme: schemeToDelete.value,
|
|
228
|
-
state: unref(deleteModal),
|
|
229
|
-
onClose: _cache[0] || (_cache[0] = ($event) => unref(deleteModal).hide()),
|
|
230
|
-
onDelete: handleDeleteConfirm
|
|
231
|
-
}, null, 8, [
|
|
232
|
-
"label",
|
|
233
|
-
"scheme",
|
|
234
|
-
"state"
|
|
235
|
-
])) : createCommentVNode("", true)]),
|
|
236
|
-
_: 1
|
|
237
|
-
}, 8, [
|
|
253
|
+
key: "0"
|
|
254
|
+
} : void 0]), 1032, [
|
|
238
255
|
"defaultOpen",
|
|
239
256
|
"heading",
|
|
240
257
|
"isStatic",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AuthSelector.vue.script.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/components/AuthSelector.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport {\n ScalarButton,\n type ScalarButton as ScalarButtonType,\n} from '@scalar/components/button'\nimport { ScalarComboboxMultiselect } from '@scalar/components/combobox'\nimport type { Icon } from '@scalar/components/icon'\nimport { ScalarIconButton } from '@scalar/components/icon-button'\nimport { ScalarListboxCheckbox } from '@scalar/components/listbox'\nimport { useModal } from '@scalar/components/modal'\nimport { ScalarIconCaretDown, ScalarIconTrash } from '@scalar/icons'\nimport type { SelectedSecurity } from '@scalar/workspace-store/entities/auth'\nimport type {\n AuthMeta,\n WorkspaceEventBus,\n} from '@scalar/workspace-store/events'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport { unpackProxyObject } from '@scalar/workspace-store/helpers/unpack-proxy'\nimport {\n isAuthOptional,\n type MergedSecuritySchemes,\n} from '@scalar/workspace-store/request-example'\nimport type { XScalarEnvironment } from '@scalar/workspace-store/schemas/extensions/document/x-scalar-environments'\nimport type {\n OpenApiDocument,\n SecurityRequirementObject,\n ServerObject,\n} from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\nimport { computed, ref, useId } from 'vue'\n\nimport DeleteRequestAuthModal from '@/v2/blocks/scalar-auth-selector-block/components/DeleteRequestAuthModal.vue'\nimport type { OAuth2Options } from '@/v2/blocks/scalar-auth-selector-block/components/OAuth2.vue'\nimport {\n formatComplexScheme,\n formatScheme,\n getSecuritySchemeOptions,\n type SecuritySchemeOption,\n} from '@/v2/blocks/scalar-auth-selector-block/helpers/security-scheme'\nimport { CollapsibleSection } from '@/v2/components/layout'\nimport { useLocalization } from '@/v2/features/localization'\n\nimport RequestAuthDataTable from './RequestAuthDataTable.vue'\n\nconst {\n environment,\n eventBus,\n createAnySecurityScheme = false,\n canDeleteSchemes = true,\n defaultOpen = true,\n heading = true,\n isStatic = false,\n meta,\n proxyUrl,\n securityRequirements,\n securitySchemes,\n selectedSecurity,\n server,\n title,\n options,\n documentType,\n} = defineProps<{\n environment: XScalarEnvironment\n eventBus: WorkspaceEventBus\n /** Allows adding authentication which is not in the document */\n createAnySecurityScheme?: boolean\n /**\n * Whether schemes can be deleted from the selector. Enabled for the editable client, disabled in\n * the read-only reference where the schemes come from the document and cannot be removed.\n */\n canDeleteSchemes?: boolean\n /** Whether the authentication disclosure should start expanded */\n defaultOpen?: boolean\n /**\n * Whether the title belongs in the document outline. The client renders the\n * selector as one section of a request, so it is a heading there. A surface\n * that only offers the schemes as a card of controls, such as the reference,\n * turns it off and the card is named as a group instead.\n */\n heading?: boolean\n /** Creates a static disclosure that cannot be collapsed */\n isStatic?: boolean\n meta: AuthMeta\n proxyUrl: string\n securityRequirements: OpenApiDocument['security']\n securitySchemes: MergedSecuritySchemes\n selectedSecurity: SelectedSecurity | undefined\n server: ServerObject | null\n title: string\n /** Any config options required for the OAuth2 flow */\n options?: OAuth2Options\n /** Type of the document the schemes belong to, used to label the missing-type warning */\n documentType?: 'openapi' | 'asyncapi'\n}>()\n\nconst { translate, translations } = useLocalization()\n\nconst titleId = useId()\nconst comboboxButtonRef = ref<typeof ScalarButtonType | null>(null)\nconst isDisclosureOpen = ref(false)\n\nconst deleteModal = useModal()\nconst schemeToDelete = ref<{\n label: string\n payload: SecurityRequirementObject\n} | null>(null)\n\n/**\n * Determines if authentication is required or optional\n *\n * Auth is optional when there is an empty security requirement and no complex requirements.\n * Complex requirements have multiple auth schemes combined (e.g., API key + OAuth).\n */\nconst authIndicator = computed<{ icon: Icon; text: string } | null>(() => {\n if (!securityRequirements?.length) {\n return null\n }\n\n const isOptional = isAuthOptional(securityRequirements)\n\n return {\n icon: isOptional ? 'Unlock' : 'Lock',\n text: isOptional\n ? translate('apiClient.authSelector.optional')\n : translate('apiClient.authSelector.required'),\n }\n})\n\n/** All available auth scheme options for the dropdown */\nconst availableSchemeOptions = computed(() =>\n getSecuritySchemeOptions(\n securityRequirements ?? [],\n securitySchemes ?? {},\n selectedSecurity?.selectedSchemes ?? [],\n createAnySecurityScheme,\n translations.value.apiClient,\n ),\n)\n\n/** Currently active auth schemes selected for this operation or collection */\nconst activeSchemeOptions = computed<SecuritySchemeOption[]>(() => {\n const schemes = selectedSecurity?.selectedSchemes\n if (!schemes?.length) {\n return []\n }\n\n return schemes.flatMap((requirement) => {\n const schemeNames = Object.keys(requirement)\n\n if (schemeNames.length === 0) {\n return []\n }\n\n // Complex auth requirement with multiple schemes\n if (schemeNames.length > 1) {\n return formatComplexScheme(requirement)\n }\n\n // Simple auth requirement with single scheme\n const schemeName = schemeNames[0]\n if (!schemeName) {\n return []\n }\n\n const scheme = getResolvedRef(securitySchemes?.[schemeName])\n if (!scheme) {\n return []\n }\n\n return formatScheme({\n name: schemeName,\n value: requirement,\n })\n })\n})\n\n/**\n * Opens the combobox dropdown when clicking the auth indicator badge.\n * Prevents the disclosure from toggling if it is already open.\n */\nconst handleAuthIndicatorClick = (event: Event): void => {\n if (isDisclosureOpen.value) {\n event.stopPropagation()\n }\n comboboxButtonRef.value?.$el.click()\n}\n\n/**\n * Updates the selected auth schemes.\n * Separates existing schemes from newly created ones for the event payload.\n */\nconst handleSchemeSelection = (selected: SecuritySchemeOption[]): void => {\n const existingSchemes = selected\n .filter((option) => option.payload === undefined)\n .map((option) => unpackProxyObject(option.value, { depth: 2 }))\n\n const newSchemes = selected\n .filter((option) => option.payload !== undefined)\n .map((option) => ({\n name: option.label,\n scheme: option.payload!,\n }))\n\n eventBus.emit('auth:update:selected-security-schemes', {\n selectedRequirements: existingSchemes,\n newSchemes,\n meta,\n })\n}\n\n/** Shows the delete confirmation modal for the selected scheme */\nconst handleDeleteRequest = (option: {\n label: string\n value: SecurityRequirementObject\n}): void => {\n schemeToDelete.value = { label: option.label, payload: option.value }\n deleteModal.show()\n}\n\n/** Deletes the selected auth scheme after confirmation */\nconst handleDeleteConfirm = (): void => {\n if (!schemeToDelete.value) {\n return\n }\n\n eventBus.emit('auth:delete:security-scheme', {\n names: Object.keys(schemeToDelete.value.payload),\n })\n\n schemeToDelete.value = null\n deleteModal.hide()\n}\n\ndefineExpose({\n authIndicator,\n selectedSchemeOptions: activeSchemeOptions,\n schemeOptions: availableSchemeOptions,\n})\n</script>\n<template>\n <CollapsibleSection\n class=\"group/params relative\"\n :defaultOpen\n :heading\n :isStatic=\"isStatic\"\n :itemCount=\"activeSchemeOptions.length\"\n @update:modelValue=\"(open) => (isDisclosureOpen = open)\">\n <template #title>\n <div\n :id=\"titleId\"\n class=\"inline-flex items-center gap-0.5 leading-[20px]\">\n <span>{{ title }}</span>\n\n <span\n v-if=\"authIndicator\"\n class=\"text-c-3 hover:bg-b-3 hover:text-c-1 -my-0.5 -mr-1 cursor-pointer rounded px-1 py-0.5 leading-[normal] font-normal\"\n :class=\"{ 'text-c-1': authIndicator.icon === 'Lock' }\"\n data-testid=\"auth-indicator\"\n @click=\"handleAuthIndicatorClick\">\n {{ authIndicator.text }}\n </span>\n </div>\n </template>\n\n <!-- Auth Dropdown (hidden when only one scheme is available) -->\n <template #actions>\n <ScalarComboboxMultiselect\n class=\"w-72 text-xs\"\n :modelValue=\"activeSchemeOptions\"\n multiple\n :options=\"availableSchemeOptions\"\n placement=\"bottom-end\"\n teleport\n @delete=\"handleDeleteRequest\"\n @update:modelValue=\"handleSchemeSelection\">\n <ScalarButton\n ref=\"comboboxButtonRef\"\n :aria-describedby=\"titleId\"\n class=\"group/combobox-button hover:text-c-1 text-c-2 flex h-fit w-full items-center gap-1 px-0.75 py-0.25 text-base font-normal\"\n variant=\"ghost\">\n <!-- Single auth scheme selected -->\n <template v-if=\"activeSchemeOptions.length === 1\">\n {{\n translate('apiClient.authSelector.selectedType', {\n type: activeSchemeOptions[0]?.label ?? '',\n })\n }}\n </template>\n\n <!-- Multiple auth schemes selected -->\n <template v-else-if=\"activeSchemeOptions.length > 1\">\n {{ translate('apiClient.authSelector.multipleTypes') }}\n </template>\n\n <!-- No auth schemes selected -->\n <template v-else>\n {{ translate('apiClient.authSelector.selectType') }}\n </template>\n\n <ScalarIconCaretDown\n class=\"size-3 shrink-0 transition-transform duration-100 group-aria-expanded/combobox-button:rotate-180\"\n weight=\"bold\" />\n </ScalarButton>\n\n <template #option=\"{ option, selected }\">\n <ScalarListboxCheckbox\n multiselect\n :selected=\"selected\" />\n <div class=\"min-w-0 flex-1 truncate\">\n {{ option.label }}\n </div>\n <ScalarIconButton\n v-if=\"option.isDeletable && canDeleteSchemes\"\n class=\"-m-0.5 shrink-0 p-0.5 opacity-0 group-hover/item:opacity-100\"\n :icon=\"ScalarIconTrash\"\n :label=\"\n translate('apiClient.authSelector.deleteScheme', {\n name: option.label,\n })\n \"\n size=\"xs\"\n @click.stop=\"handleDeleteRequest(option)\" />\n </template>\n </ScalarComboboxMultiselect>\n </template>\n\n <!-- Auth Table -->\n <RequestAuthDataTable\n :activeAuthIndex=\"selectedSecurity?.selectedIndex ?? 0\"\n :documentType\n :environment\n :eventBus\n :isStatic\n :meta\n :options\n :proxyUrl\n :securitySchemes\n :selectedSchemeOptions=\"activeSchemeOptions\"\n :server />\n\n <!-- Delete Auth Modal -->\n <DeleteRequestAuthModal\n v-if=\"schemeToDelete\"\n :label=\"schemeToDelete.label\"\n :scheme=\"schemeToDelete\"\n :state=\"deleteModal\"\n @close=\"deleteModal.hide()\"\n @delete=\"handleDeleteConfirm\" />\n </CollapsibleSection>\n</template>\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"AuthSelector.vue.script.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/components/AuthSelector.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport {\n ScalarButton,\n type ScalarButton as ScalarButtonType,\n} from '@scalar/components/button'\nimport { ScalarComboboxMultiselect } from '@scalar/components/combobox'\nimport type { Icon } from '@scalar/components/icon'\nimport { ScalarIconButton } from '@scalar/components/icon-button'\nimport { ScalarListboxCheckbox } from '@scalar/components/listbox'\nimport { useModal } from '@scalar/components/modal'\nimport { ScalarIconCaretDown, ScalarIconTrash } from '@scalar/icons'\nimport type { SelectedSecurity } from '@scalar/workspace-store/entities/auth'\nimport type {\n AuthMeta,\n WorkspaceEventBus,\n} from '@scalar/workspace-store/events'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport { unpackProxyObject } from '@scalar/workspace-store/helpers/unpack-proxy'\nimport {\n isAuthOptional,\n type MergedSecuritySchemes,\n} from '@scalar/workspace-store/request-example'\nimport type { XScalarEnvironment } from '@scalar/workspace-store/schemas/extensions/document/x-scalar-environments'\nimport type {\n OpenApiDocument,\n SecurityRequirementObject,\n ServerObject,\n} from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\nimport { computed, ref, useId } from 'vue'\n\nimport DeleteRequestAuthModal from '@/v2/blocks/scalar-auth-selector-block/components/DeleteRequestAuthModal.vue'\nimport type { OAuth2Options } from '@/v2/blocks/scalar-auth-selector-block/components/OAuth2.vue'\nimport {\n formatComplexScheme,\n formatScheme,\n getSecuritySchemeOptions,\n type SecuritySchemeOption,\n} from '@/v2/blocks/scalar-auth-selector-block/helpers/security-scheme'\nimport { CollapsibleSection } from '@/v2/components/layout'\nimport { useLocalization } from '@/v2/features/localization'\n\nimport RequestAuthDataTable from './RequestAuthDataTable.vue'\n\nconst {\n environment,\n eventBus,\n createAnySecurityScheme = false,\n canDeleteSchemes = true,\n defaultOpen = true,\n heading = true,\n hideSingleRequiredScheme = false,\n isStatic = false,\n meta,\n proxyUrl,\n securityRequirements,\n securitySchemes,\n selectedSecurity,\n server,\n title,\n options,\n documentType,\n} = defineProps<{\n environment: XScalarEnvironment\n eventBus: WorkspaceEventBus\n /** Allows adding authentication which is not in the document */\n createAnySecurityScheme?: boolean\n /**\n * Whether schemes can be deleted from the selector. Enabled for the editable client, disabled in\n * the read-only reference where the schemes come from the document and cannot be removed.\n */\n canDeleteSchemes?: boolean\n /** Whether the authentication disclosure should start expanded */\n defaultOpen?: boolean\n /**\n * Whether the title belongs in the document outline. The client renders the\n * selector as one section of a request, so it is a heading there. A surface\n * that only offers the schemes as a card of controls, such as the reference,\n * turns it off and the card is named as a group instead.\n */\n heading?: boolean\n /** Hides a sole active required choice in the reference while preserving client controls. */\n hideSingleRequiredScheme?: boolean\n /** Creates a static disclosure that cannot be collapsed */\n isStatic?: boolean\n meta: AuthMeta\n proxyUrl: string\n securityRequirements: OpenApiDocument['security']\n securitySchemes: MergedSecuritySchemes\n selectedSecurity: SelectedSecurity | undefined\n server: ServerObject | null\n title: string\n /** Any config options required for the OAuth2 flow */\n options?: OAuth2Options\n /** Type of the document the schemes belong to, used to label the missing-type warning */\n documentType?: 'openapi' | 'asyncapi'\n}>()\n\nconst { translate, translations } = useLocalization()\n\nconst titleId = useId()\nconst comboboxButtonRef = ref<typeof ScalarButtonType | null>(null)\nconst isDisclosureOpen = ref(false)\n\nconst deleteModal = useModal()\nconst schemeToDelete = ref<{\n label: string\n payload: SecurityRequirementObject\n} | null>(null)\n\n/**\n * Determines if authentication is required or optional\n *\n * Auth is optional when there is an empty security requirement and no complex requirements.\n * Complex requirements have multiple auth schemes combined (e.g., API key + OAuth).\n */\nconst authIndicator = computed<{ icon: Icon; text: string } | null>(() => {\n if (!securityRequirements?.length) {\n return null\n }\n\n const isOptional = isAuthOptional(securityRequirements)\n\n return {\n icon: isOptional ? 'Unlock' : 'Lock',\n text: isOptional\n ? translate('apiClient.authSelector.optional')\n : translate('apiClient.authSelector.required'),\n }\n})\n\n/** All available auth scheme options for the dropdown */\nconst availableSchemeOptions = computed(() =>\n getSecuritySchemeOptions(\n securityRequirements ?? [],\n securitySchemes ?? {},\n selectedSecurity?.selectedSchemes ?? [],\n createAnySecurityScheme,\n translations.value.apiClient,\n ),\n)\n\n/** Currently active auth schemes selected for this operation or collection */\nconst activeSchemeOptions = computed<SecuritySchemeOption[]>(() => {\n const schemes = selectedSecurity?.selectedSchemes\n if (!schemes?.length) {\n return []\n }\n\n return schemes.flatMap((requirement) => {\n const schemeNames = Object.keys(requirement)\n\n if (schemeNames.length === 0) {\n return []\n }\n\n // Complex auth requirement with multiple schemes\n if (schemeNames.length > 1) {\n return formatComplexScheme(requirement)\n }\n\n // Simple auth requirement with single scheme\n const schemeName = schemeNames[0]\n if (!schemeName) {\n return []\n }\n\n const scheme = getResolvedRef(securitySchemes?.[schemeName])\n if (!scheme) {\n return []\n }\n\n return formatScheme({\n name: schemeName,\n value: requirement,\n })\n })\n})\n\n/** Keep selection available whenever it can change auth or recover an empty saved selection. */\nconst showSchemeSelector = computed<boolean>(() => {\n if (\n !hideSingleRequiredScheme ||\n createAnySecurityScheme ||\n securityRequirements?.length !== 1 ||\n Object.keys(securityRequirements[0] ?? {}).length === 0\n ) {\n return true\n }\n\n const schemeOptions = availableSchemeOptions.value.flatMap((option) =>\n 'options' in option ? option.options : [option],\n )\n\n return (\n schemeOptions.length !== 1 ||\n activeSchemeOptions.value.length !== 1 ||\n activeSchemeOptions.value[0]?.id !== schemeOptions[0]?.id\n )\n})\n\n/**\n * Opens the combobox dropdown when clicking the auth indicator badge.\n * Prevents the disclosure from toggling if it is already open.\n */\nconst handleAuthIndicatorClick = (event: Event): void => {\n if (!showSchemeSelector.value) {\n return\n }\n\n if (isDisclosureOpen.value) {\n event.stopPropagation()\n }\n comboboxButtonRef.value?.$el.click()\n}\n\n/**\n * Updates the selected auth schemes.\n * Separates existing schemes from newly created ones for the event payload.\n */\nconst handleSchemeSelection = (selected: SecuritySchemeOption[]): void => {\n const existingSchemes = selected\n .filter((option) => option.payload === undefined)\n .map((option) => unpackProxyObject(option.value, { depth: 2 }))\n\n const newSchemes = selected\n .filter((option) => option.payload !== undefined)\n .map((option) => ({\n name: option.label,\n scheme: option.payload!,\n }))\n\n eventBus.emit('auth:update:selected-security-schemes', {\n selectedRequirements: existingSchemes,\n newSchemes,\n meta,\n })\n}\n\n/** Shows the delete confirmation modal for the selected scheme */\nconst handleDeleteRequest = (option: {\n label: string\n value: SecurityRequirementObject\n}): void => {\n schemeToDelete.value = { label: option.label, payload: option.value }\n deleteModal.show()\n}\n\n/** Deletes the selected auth scheme after confirmation */\nconst handleDeleteConfirm = (): void => {\n if (!schemeToDelete.value) {\n return\n }\n\n eventBus.emit('auth:delete:security-scheme', {\n names: Object.keys(schemeToDelete.value.payload),\n })\n\n schemeToDelete.value = null\n deleteModal.hide()\n}\n\ndefineExpose({\n authIndicator,\n selectedSchemeOptions: activeSchemeOptions,\n schemeOptions: availableSchemeOptions,\n})\n</script>\n<template>\n <CollapsibleSection\n class=\"group/params relative\"\n :defaultOpen\n :heading\n :isStatic=\"isStatic\"\n :itemCount=\"activeSchemeOptions.length\"\n @update:modelValue=\"(open) => (isDisclosureOpen = open)\">\n <template #title>\n <div\n :id=\"titleId\"\n class=\"inline-flex items-center gap-0.5 leading-[20px]\">\n <span>{{ title }}</span>\n\n <span\n v-if=\"authIndicator\"\n class=\"text-c-3 -my-0.5 -mr-1 rounded px-1 py-0.5 leading-[normal] font-normal\"\n :class=\"{\n 'text-c-1': authIndicator.icon === 'Lock',\n 'hover:bg-b-3 hover:text-c-1 cursor-pointer': showSchemeSelector,\n }\"\n data-testid=\"auth-indicator\"\n @click=\"handleAuthIndicatorClick\">\n {{ authIndicator.text }}\n </span>\n </div>\n </template>\n\n <!-- The client keeps its selection and deletion controls. -->\n <template\n v-if=\"showSchemeSelector\"\n #actions>\n <ScalarComboboxMultiselect\n class=\"w-72 text-xs\"\n :modelValue=\"activeSchemeOptions\"\n multiple\n :options=\"availableSchemeOptions\"\n placement=\"bottom-end\"\n teleport\n @delete=\"handleDeleteRequest\"\n @update:modelValue=\"handleSchemeSelection\">\n <ScalarButton\n ref=\"comboboxButtonRef\"\n :aria-describedby=\"titleId\"\n class=\"group/combobox-button hover:text-c-1 text-c-2 flex h-fit w-full items-center gap-1 px-0.75 py-0.25 text-base font-normal\"\n variant=\"ghost\">\n <!-- Single auth scheme selected -->\n <template v-if=\"activeSchemeOptions.length === 1\">\n {{\n translate('apiClient.authSelector.selectedType', {\n type: activeSchemeOptions[0]?.label ?? '',\n })\n }}\n </template>\n\n <!-- Multiple auth schemes selected -->\n <template v-else-if=\"activeSchemeOptions.length > 1\">\n {{ translate('apiClient.authSelector.multipleTypes') }}\n </template>\n\n <!-- No auth schemes selected -->\n <template v-else>\n {{ translate('apiClient.authSelector.selectType') }}\n </template>\n\n <ScalarIconCaretDown\n class=\"size-3 shrink-0 transition-transform duration-100 group-aria-expanded/combobox-button:rotate-180\"\n weight=\"bold\" />\n </ScalarButton>\n\n <template #option=\"{ option, selected }\">\n <ScalarListboxCheckbox\n multiselect\n :selected=\"selected\" />\n <div class=\"min-w-0 flex-1 truncate\">\n {{ option.label }}\n </div>\n <ScalarIconButton\n v-if=\"option.isDeletable && canDeleteSchemes\"\n class=\"-m-0.5 shrink-0 p-0.5 opacity-0 group-hover/item:opacity-100\"\n :icon=\"ScalarIconTrash\"\n :label=\"\n translate('apiClient.authSelector.deleteScheme', {\n name: option.label,\n })\n \"\n size=\"xs\"\n @click.stop=\"handleDeleteRequest(option)\" />\n </template>\n </ScalarComboboxMultiselect>\n </template>\n\n <!-- Auth Table -->\n <RequestAuthDataTable\n :activeAuthIndex=\"selectedSecurity?.selectedIndex ?? 0\"\n :documentType\n :environment\n :eventBus\n :isStatic\n :meta\n :options\n :proxyUrl\n :securitySchemes\n :selectedSchemeOptions=\"activeSchemeOptions\"\n :server />\n\n <!-- Delete Auth Modal -->\n <DeleteRequestAuthModal\n v-if=\"schemeToDelete\"\n :label=\"schemeToDelete.label\"\n :scheme=\"schemeToDelete\"\n :state=\"deleteModal\"\n @close=\"deleteModal.hide()\"\n @delete=\"handleDeleteConfirm\" />\n </CollapsibleSection>\n</template>\n"],"mappings":"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"}
|
|
@@ -41,7 +41,9 @@ declare const __VLS_export: __VLS_WithSlots<import("vue").DefineComponent<{
|
|
|
41
41
|
/** Schema type — drives boolean select mode when `boolean` is included */
|
|
42
42
|
type?: string | string[];
|
|
43
43
|
/** Predefined enum values; when set the input is replaced by a select */
|
|
44
|
-
enum?:
|
|
44
|
+
enum?: unknown[];
|
|
45
|
+
/** Text representation of array selections. */
|
|
46
|
+
arrayEncoding?: "json" | "comma-separated";
|
|
45
47
|
/** Example values; when set (and no enum/boolean) the input is replaced by a select */
|
|
46
48
|
examples?: string[];
|
|
47
49
|
/** Default value to suggest in select modes */
|
|
@@ -96,7 +98,9 @@ declare const __VLS_export: __VLS_WithSlots<import("vue").DefineComponent<{
|
|
|
96
98
|
/** Schema type — drives boolean select mode when `boolean` is included */
|
|
97
99
|
type?: string | string[];
|
|
98
100
|
/** Predefined enum values; when set the input is replaced by a select */
|
|
99
|
-
enum?:
|
|
101
|
+
enum?: unknown[];
|
|
102
|
+
/** Text representation of array selections. */
|
|
103
|
+
arrayEncoding?: "json" | "comma-separated";
|
|
100
104
|
/** Example values; when set (and no enum/boolean) the input is replaced by a select */
|
|
101
105
|
examples?: string[];
|
|
102
106
|
/** Default value to suggest in select modes */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CodeInputLite.vue.d.ts","sourceRoot":"","sources":["../../../../src/v2/components/code-input/CodeInputLite.vue"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"CodeInputLite.vue.d.ts","sourceRoot":"","sources":["../../../../src/v2/components/code-input/CodeInputLite.vue"],"names":[],"mappings":"AAomCA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,2EAA2E,CAAA;AAkBnH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AAErD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAA;AAQ1D;;;;;;;;GAQG;wBACkB,OAAO,YAAY;AAAxC,wBAAyC;AAKzC,QAAA,MAAM,YAAY;gBAoCJ,mBAAmB;IAC/B,gFAAgF;iBACnE,kBAAkB,GAAG,SAAS;IAC3C,kDAAkD;eACvC,OAAO;IAClB,wFAAwF;eAC7E,OAAO;IAClB,yBAAyB;YACjB,OAAO;IACf,6DAA6D;aACpD,YAAY;IACrB,0CAA0C;kBAC5B,MAAM;IACpB,8BAA8B;eACnB,OAAO;IAClB,0BAA0B;iBACb,OAAO;IACpB,6DAA6D;oBAC7C,OAAO;IACvB,4DAA4D;mBAC7C,OAAO;IACtB,+DAA+D;uBAC5C,OAAO;IAC1B,yEAAyE;kBAC3D,OAAO;IACrB,0EAA0E;WACnE,MAAM,GAAG,MAAM,EAAE;IACxB,yEAAyE;WAClE,OAAO,EAAE;IAChB,+CAA+C;oBAC/B,MAAM,GAAG,iBAAiB;IAC1C,uFAAuF;eAC5E,MAAM,EAAE;IACnB,+CAA+C;cACrC,mBAAmB;IAC7B,0DAA0D;eAC/C,OAAO;;IAquBlB,6DAA6D;uBAC1C,OAAO,GAAG,KAAK,GAAG,MAAM,KAAG,IAAI;IAclD,0EAA0E;mCACjD,IAAI;IAQ7B,6DAA6D;oBAC/C,MAAM;IACpB,wCAAwC;0BACpB,MAAM,GAAG,SAAS;;;;;;cA3yBV,UAAU;cAAQ,aAAa;;;;;gBAO/C,mBAAmB;IAC/B,gFAAgF;iBACnE,kBAAkB,GAAG,SAAS;IAC3C,kDAAkD;eACvC,OAAO;IAClB,wFAAwF;eAC7E,OAAO;IAClB,yBAAyB;YACjB,OAAO;IACf,6DAA6D;aACpD,YAAY;IACrB,0CAA0C;kBAC5B,MAAM;IACpB,8BAA8B;eACnB,OAAO;IAClB,0BAA0B;iBACb,OAAO;IACpB,6DAA6D;oBAC7C,OAAO;IACvB,4DAA4D;mBAC7C,OAAO;IACtB,+DAA+D;uBAC5C,OAAO;IAC1B,yEAAyE;kBAC3D,OAAO;IACrB,0EAA0E;WACnE,MAAM,GAAG,MAAM,EAAE;IACxB,yEAAyE;WAClE,OAAO,EAAE;IAChB,+CAA+C;oBAC/B,MAAM,GAAG,iBAAiB;IAC1C,uFAAuF;eAC5E,MAAM,EAAE;IACnB,+CAA+C;cACrC,mBAAmB;IAC7B,0DAA0D;eAC/C,OAAO;;;;cA3CU,UAAU;cAAQ,aAAa;;;;;cA4mC/C,CAAC,KAAK,IAAiB,KAAK,GAAG;;WAClC,CAAC,KAAK,IAAiB,KAAK,GAAG;EAYtC,CAAC;AACL,KAAK,eAAe,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,GAAG;IAChC,QAAO;QACN,MAAM,EAAE,CAAC,CAAC;KACV,CAAA;CACD,CAAC"}
|
|
@@ -3,7 +3,7 @@ import CodeInputLite_vue_vue_type_script_setup_true_lang_default from "./CodeInp
|
|
|
3
3
|
/* empty css */
|
|
4
4
|
/* empty css */
|
|
5
5
|
//#region src/v2/components/code-input/CodeInputLite.vue
|
|
6
|
-
var CodeInputLite_default = /*#__PURE__*/ _plugin_vue_export_helper_default(CodeInputLite_vue_vue_type_script_setup_true_lang_default, [["__scopeId", "data-v-
|
|
6
|
+
var CodeInputLite_default = /*#__PURE__*/ _plugin_vue_export_helper_default(CodeInputLite_vue_vue_type_script_setup_true_lang_default, [["__scopeId", "data-v-f06520bd"]]);
|
|
7
7
|
//#endregion
|
|
8
8
|
export { CodeInputLite_default as default };
|
|
9
9
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CodeInputLite.vue.js","names":[],"sources":["../../../../src/v2/components/code-input/CodeInputLite.vue"],"sourcesContent":["<script lang=\"ts\">\n/**\n * CodeInputLite\n *\n * Single-line `contenteditable` editor that renders `{{varname}}` as atomic\n * pill spans (`contenteditable=\"false\"`) and offers an env-variable\n * autocomplete on `{{`. The value is still exposed as a `{{name}}`-bearing\n * string via `update:modelValue`; DOM ↔ model conversion lives in\n * `renderModel` and `serializeEditor`.\n */\nexport default {\n inheritAttrs: false,\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { isDefined } from '@scalar/helpers/array/is-defined'\nimport { REGEX } from '@scalar/helpers/regex/regex-helpers'\nimport {\n CONTEXT_FUNCTION_NAMES,\n getContextFunctionComment,\n isContextFunctionName,\n type ContextFunctionName,\n} from '@scalar/workspace-store/request-example'\nimport type { XScalarEnvironment } from '@scalar/workspace-store/schemas/extensions/document/x-scalar-environments'\nimport { nanoid } from 'nanoid'\nimport {\n computed,\n createApp,\n nextTick,\n onBeforeUnmount,\n onMounted,\n ref,\n useAttrs,\n useTemplateRef,\n watch,\n type App,\n} from 'vue'\n\nimport DataTableInputSelect from '@/v2/components/data-table/DataTableInputSelect.vue'\nimport EnvironmentVariableDropdown from '@/v2/features/environments/components/EnvironmentVariablesDropdown.vue'\nimport { useLocalization } from '@/v2/features/localization'\nimport type { ClientLayout } from '@/v2/types/layout'\n\nimport type { CodeInputModelValue } from './CodeInput.vue'\nimport { buildPillContext } from './helpers/build-pill-context'\nimport { lookupVariableValue } from './helpers/lookup-variable-value'\nimport { pillSignature } from './helpers/pill-signature'\nimport { serializeValue } from './helpers/serialize-value'\nimport PillTooltipHost from './PillTooltipHost.vue'\n\nconst {\n modelValue,\n environment,\n disabled = false,\n readOnly = false,\n error = false,\n layout = 'desktop',\n placeholder,\n required = false,\n emitOnBlur = true,\n alwaysEmitChange = false,\n withVariables = true,\n withFakeData = false,\n linethrough = false,\n type,\n enum: enumProp,\n examples,\n default: defaultProp,\n nullable = false,\n} = defineProps<Props>()\n\nconst emit = defineEmits<{\n 'update:modelValue': [value: string]\n 'submit': [value: string, event: KeyboardEvent | FocusEvent]\n 'blur': [value: string, event: FocusEvent]\n 'navigate': [route: { page: 'document'; path: 'environment' }]\n}>()\n\nconst { translate } = useLocalization()\n\ntype Props = {\n modelValue: CodeInputModelValue\n /** Environment for variable substitution. Pass undefined to disable env vars */\n environment: XScalarEnvironment | undefined\n /** Render as a non-interactive read-only label */\n disabled?: boolean\n /** Render the input with the native `readonly` attribute (still focusable, no edits) */\n readOnly?: boolean\n /** Show error styling */\n error?: boolean\n /** Layout context affects styling and dropdown visibility */\n layout?: ClientLayout\n /** Placeholder text for an empty input */\n placeholder?: string\n /** Show required indicator */\n required?: boolean\n /** Emit submit on blur */\n emitOnBlur?: boolean\n /** Render variable pills + show the autocomplete dropdown */\n withVariables?: boolean\n /** Include `{{$guid}}` etc. in the autocomplete dropdown */\n withFakeData?: boolean\n /** Always emit change events even if the value is unchanged */\n alwaysEmitChange?: boolean\n /** Strike-through styling for the input text (e.g. overridden values) */\n linethrough?: boolean\n /** Schema type — drives boolean select mode when `boolean` is included */\n type?: string | string[]\n /** Predefined enum values; when set the input is replaced by a select */\n enum?: string[]\n /** Example values; when set (and no enum/boolean) the input is replaced by a select */\n examples?: string[]\n /** Default value to suggest in select modes */\n default?: CodeInputModelValue\n /** Whether the boolean select includes a `null` option */\n nullable?: boolean\n}\n\nconst attrs = useAttrs()\nconst ariaLabel = computed(() =>\n typeof attrs['aria-label'] === 'string' ? attrs['aria-label'] : undefined,\n)\n/** Lifted to the editable surface like aria-label, so a visible label can name it */\nconst ariaLabelledby = computed(() =>\n typeof attrs['aria-labelledby'] === 'string'\n ? attrs['aria-labelledby']\n : undefined,\n)\n/**\n * The wrapper is a generic div, and ARIA prohibits naming a generic element,\n * so the naming attributes only go on the editor and not on the wrapper.\n */\nconst wrapperAttrs = computed(() => {\n const {\n 'aria-label': _ariaLabel,\n 'aria-labelledby': _ariaLabelledby,\n ...rest\n } = attrs\n return rest\n})\n\n/**\n * The id only matters once the dropdown opens (`aria-controls` /\n * `aria-activedescendant`), so we defer `nanoid()` until first focus to\n * keep idle instances cheap. A consumer-supplied `id` attr is preserved.\n */\nconst generatedComponentId = ref<string | null>(null)\nconst componentId = computed((): string | undefined =>\n typeof attrs.id === 'string'\n ? attrs.id\n : (generatedComponentId.value ?? undefined),\n)\nconst ensureComponentId = (): void => {\n if (\n (typeof attrs.id !== 'string' || !attrs.id) &&\n generatedComponentId.value === null\n ) {\n generatedComponentId.value = `id-${nanoid()}`\n }\n}\n\nconst editorRef = useTemplateRef<HTMLDivElement>('editorRef')\nconst dropdownRef = ref<InstanceType<\n typeof EnvironmentVariableDropdown\n> | null>(null)\n\n/** Id of the dropdown's `role=\"listbox\"` element, for the combobox wiring. */\nconst listboxId = computed((): string | undefined =>\n componentId.value ? `${componentId.value}-listbox` : undefined,\n)\n\n/**\n * Id of the option the dropdown currently highlights. Mirrors the dropdown's\n * own selection so the editor can expose it via `aria-activedescendant`.\n */\nconst activeOptionId = computed(\n (): string | undefined => dropdownRef.value?.activeOptionId,\n)\n\nconst isFocused = ref(false)\nconst isEmpty = ref(true)\n\n/**\n * True while an IME composition is in progress. Rebuilding the editor DOM\n * mid-composition (e.g. when `{{` forms a pill) cancels the composition, so we\n * defer those rebuilds until `compositionend`.\n */\nconst isComposing = ref(false)\n\n/**\n * Whether the serialized value should count as empty for placeholder display.\n *\n * `contenteditable` can leave behind invisible residue after some delete\n * sequences — most commonly a non-breaking space (`\\u00a0`) — which makes a\n * visually empty field report a non-zero length and silently drop its\n * placeholder. Trimming covers that case; `\\u00a0` counts as whitespace, so a\n * field that only holds editor residue is treated as empty. This affects the\n * placeholder flag only, never the value emitted via `serializeEditor`.\n */\nconst isBlankValue = (text: string): boolean => text.trim().length === 0\n\n// ───────────────────────────────────────────────────────────────────\n// Rendering-mode detection (parity with CodeInput's select dispatch)\n// ───────────────────────────────────────────────────────────────────\n\n/** True when the schema type is exactly `boolean` (or includes it in a tuple type). */\nconst isBooleanMode = computed((): boolean => {\n if (enumProp?.length) {\n return false\n }\n return type === 'boolean' || (Array.isArray(type) && type.includes('boolean'))\n})\n\nconst booleanOptions = computed((): string[] =>\n nullable ? ['true', 'false', 'null'] : ['true', 'false'],\n)\n\n/** Default type when the schema is a tuple — picks the first non-null entry. */\nconst defaultType = computed((): string | undefined => {\n if (Array.isArray(type)) {\n return type.find((t) => t !== 'null') ?? 'string'\n }\n return type\n})\n\nconst handleSelectChange = (value: string): void =>\n emit('update:modelValue', value)\n\n// ───────────────────────────────────────────────────────────────────\n// Per-pill tooltip apps\n// ───────────────────────────────────────────────────────────────────\n\nlet pillTooltipApps: App[] = []\n\n/**\n * Per-pill tooltips are the heaviest part of the render (a Vue app +\n * `useTooltip` watch + listeners each), so we defer mounting them until\n * the first interaction (focus, pointerover, or dropdown open). Once on,\n * subsequent rebuilds remount tooltips for the new pills.\n */\nlet tooltipsActive = false\n\nconst teardownPillTooltips = (): void => {\n for (const app of pillTooltipApps) {\n app.unmount()\n }\n pillTooltipApps = []\n}\n\nconst mountPillTooltips = (): void => {\n if (!editorRef.value || layout === 'modal') {\n return\n }\n const pills = editorRef.value.querySelectorAll<HTMLElement>('.scalar-pill')\n for (const pillEl of pills) {\n const variableName = pillEl.dataset.variable ?? ''\n const context = buildPillContext(variableName, environment)\n const app = createApp(PillTooltipHost, {\n context,\n target: pillEl,\n translate,\n })\n // PillTooltipHost is renderless; useTooltip attaches to `target` directly.\n app.mount(document.createElement('div'))\n pillTooltipApps.push(app)\n }\n}\n\n// ───────────────────────────────────────────────────────────────────\n// DOM ↔ model conversion\n// ───────────────────────────────────────────────────────────────────\n\n/**\n * Build a pill `<span>` for the given variable. `contentEditable = 'false'`\n * makes the browser treat it as a single atom (arrow keys jump over it,\n * Backspace deletes it whole); `{{` / `}}` only live in the model string.\n */\nconst createPillElement = (\n name: string,\n start: number,\n end: number,\n): HTMLSpanElement => {\n const isCtx = isContextFunctionName(name)\n const span = document.createElement('span')\n span.className = isCtx ? 'scalar-pill scalar-pill--context-fn' : 'scalar-pill'\n span.contentEditable = 'false'\n span.dataset.variable = name\n // Model-coordinate offsets (the pill stands in for the full `{{name}}`).\n // Used by click forwarding and tests to map a pill back to the value.\n span.dataset.pillStart = String(start)\n span.dataset.pillEnd = String(end)\n\n const color = isCtx\n ? 'var(--scalar-color-3)'\n : environment?.color || 'var(--scalar-color-1)'\n span.style.setProperty('--tw-bg-base', color)\n\n // Fade env pills with no usable value. A falsy check (not just\n // `=== undefined`) matches the tooltip path's `Boolean(value)`, so a\n // variable declared with an empty string fades here too.\n const isUndefinedEnv = !isCtx && !lookupVariableValue(environment, name)\n if (isUndefinedEnv) {\n span.style.opacity = '0.5'\n }\n\n span.textContent = name\n return span\n}\n\n/** Render a model string into the editor as a mix of text nodes + pills. */\nconst renderModel = (text: string): void => {\n const editor = editorRef.value\n if (!editor) {\n return\n }\n\n teardownPillTooltips()\n editor.replaceChildren()\n\n if (!withVariables || !text.includes('{{')) {\n if (text) {\n editor.appendChild(document.createTextNode(text))\n }\n isEmpty.value = isBlankValue(text)\n return\n }\n\n const regex = new RegExp(REGEX.VARIABLES.source, REGEX.VARIABLES.flags)\n let lastIndex = 0\n let match: RegExpExecArray | null\n\n while ((match = regex.exec(text)) !== null) {\n const start = match.index\n const end = start + match[0].length\n if (start > lastIndex) {\n editor.appendChild(document.createTextNode(text.slice(lastIndex, start)))\n }\n editor.appendChild(createPillElement(match[1] ?? '', start, end))\n lastIndex = end\n }\n\n if (lastIndex < text.length) {\n editor.appendChild(document.createTextNode(text.slice(lastIndex)))\n }\n\n isEmpty.value = false\n if (tooltipsActive) {\n mountPillTooltips()\n }\n}\n\n/** Length the given child contributes to the serialized model string. */\nconst modelLengthOf = (node: Node): number => {\n if (node.nodeType === Node.TEXT_NODE) {\n return (node.textContent ?? '').length\n }\n if (node instanceof HTMLElement && node.classList.contains('scalar-pill')) {\n return `{{${node.dataset.variable ?? ''}}}`.length\n }\n // Defensive: a stray element (e.g. browser-inserted <br>) — use its text.\n return (node.textContent ?? '').length\n}\n\n/** Read the editor DOM back into a `{{name}}`-bearing model string. */\nconst serializeEditor = (): string => {\n const editor = editorRef.value\n if (!editor) {\n return ''\n }\n let out = ''\n for (const node of Array.from(editor.childNodes)) {\n if (node.nodeType === Node.TEXT_NODE) {\n out += node.textContent ?? ''\n } else if (\n node instanceof HTMLElement &&\n node.classList.contains('scalar-pill')\n ) {\n out += `{{${node.dataset.variable ?? ''}}}`\n } else if (node instanceof HTMLElement) {\n // Flatten any stray <br> / <div> the browser may inject on paste/Enter.\n out += node.textContent ?? ''\n }\n }\n return out\n}\n\nlet lastPillSignature: string | null = null\nlet lastEnvKey = ''\n\n/**\n * Cache key for the env + `withVariables` state. Includes variable\n * name/value pairs so the watcher notices adds/removes/edits even when\n * `environment.color` is unchanged — without that, pills keep stale\n * `isDefined` opacity and tooltip values until the input itself changes.\n */\nconst computeEnvKey = (): string => {\n const color = environment?.color ?? ''\n const flag = withVariables ? '1' : '0'\n const variables = environment?.variables ?? []\n let vars = ''\n for (const v of variables) {\n const value =\n typeof v.value === 'string' ? v.value : (v.value?.default ?? '')\n // Unit separators (\\x1f / \\x1e) so values can safely contain `|` or `=`.\n vars += `\\x1f${v.name}\\x1e${value}`\n }\n return `${color}|${flag}|${vars}`\n}\n\n/** Idempotent: first call flips `tooltipsActive` and mounts pill tooltips. */\nconst ensureTooltipsActive = (): void => {\n if (tooltipsActive) {\n return\n }\n tooltipsActive = true\n mountPillTooltips()\n}\n\n// ───────────────────────────────────────────────────────────────────\n// Caret ↔ model offset\n// ───────────────────────────────────────────────────────────────────\n\n/** Selection start as a model-string offset, or `null` if not inside the editor. */\nconst getModelCaret = (): number | null => {\n const editor = editorRef.value\n if (!editor) {\n return null\n }\n const selection = window.getSelection()\n if (!selection || selection.rangeCount === 0) {\n return null\n }\n const range = selection.getRangeAt(0)\n if (\n range.startContainer !== editor &&\n !editor.contains(range.startContainer)\n ) {\n return null\n }\n\n // Anchored on the editor itself: `startOffset` is a child index.\n if (range.startContainer === editor) {\n let pos = 0\n for (\n let i = 0;\n i < range.startOffset && i < editor.childNodes.length;\n i++\n ) {\n pos += modelLengthOf(editor.childNodes.item(i))\n }\n return pos\n }\n\n let pos = 0\n for (const child of Array.from(editor.childNodes)) {\n if (child === range.startContainer) {\n return pos + range.startOffset\n }\n // Pills are non-editable; if a browser quirk still lands a selection\n // inside one, snap to the nearest boundary instead of getting stuck.\n if (child.contains(range.startContainer)) {\n return range.startOffset === 0 ? pos : pos + modelLengthOf(child)\n }\n pos += modelLengthOf(child)\n }\n return pos\n}\n\n/** Place the caret at the given model offset, walking the DOM to find it. */\nconst setModelCaret = (target: number): void => {\n const editor = editorRef.value\n if (!editor) {\n return\n }\n const range = document.createRange()\n let pos = 0\n let placed = false\n\n for (const child of Array.from(editor.childNodes)) {\n const len = modelLengthOf(child)\n if (pos + len >= target) {\n if (child.nodeType === Node.TEXT_NODE) {\n const into = Math.max(\n 0,\n Math.min(target - pos, (child.textContent ?? '').length),\n )\n range.setStart(child, into)\n } else if (target - pos <= 0) {\n range.setStartBefore(child)\n } else {\n range.setStartAfter(child)\n }\n placed = true\n break\n }\n pos += len\n }\n\n if (!placed) {\n range.selectNodeContents(editor)\n range.collapse(false)\n } else {\n range.collapse(true)\n }\n\n const selection = window.getSelection()\n if (!selection) {\n return\n }\n selection.removeAllRanges()\n selection.addRange(range)\n}\n\n// ───────────────────────────────────────────────────────────────────\n// Environment variable dropdown\n// ───────────────────────────────────────────────────────────────────\n\nconst showDropdown = ref(false)\nconst dropdownQuery = ref('')\nconst dropdownPosition = ref({ left: 0, top: 0 })\n\nconst contextFunctionDropdownItems = computed(() =>\n withFakeData\n ? CONTEXT_FUNCTION_NAMES.map((key) => ({\n key,\n description: getContextFunctionComment(key as ContextFunctionName),\n }))\n : [],\n)\n\nconst displayVariablesDropdown = computed(\n (): boolean =>\n showDropdown.value &&\n withVariables &&\n layout !== 'modal' &&\n (Boolean(environment) || withFakeData),\n)\n\nconst updateDropdownVisibility = (): void => {\n const editor = editorRef.value\n if (!editor) {\n return\n }\n const caret = getModelCaret()\n if (caret === null) {\n showDropdown.value = false\n return\n }\n const text = serializeEditor().slice(0, caret)\n const lastOpen = text.lastIndexOf('{{')\n const lastClose = text.lastIndexOf('}}')\n\n if (lastOpen <= lastClose) {\n showDropdown.value = false\n return\n }\n\n dropdownQuery.value = text.slice(lastOpen + 2)\n // Make sure the combobox has an id before it advertises `aria-expanded`, so\n // `aria-controls` always resolves to the listbox we are about to render.\n ensureComponentId()\n showDropdown.value = true\n\n // Anchor under the caret; `getBoundingClientRect` gives the caret rect in one read.\n nextTick(() => {\n const selection = window.getSelection()\n if (!selection || selection.rangeCount === 0 || !editorRef.value) {\n return\n }\n const r = selection.getRangeAt(0).cloneRange()\n r.collapse(true)\n const rect = r.getBoundingClientRect()\n const editorRect = editorRef.value.getBoundingClientRect()\n // Some browsers collapse empty ranges to a zero rect — fall back to the editor edge.\n dropdownPosition.value = {\n left: rect.left || editorRect.left,\n top: rect.bottom || editorRect.bottom,\n }\n })\n}\n\nconst handleDropdownSelect = (item: string): void => {\n if (readOnly) {\n return\n }\n const caret = getModelCaret() ?? 0\n const value = serializeEditor()\n const from = Math.max(0, caret - dropdownQuery.value.length - 2)\n const to = caret\n const next = `${value.slice(0, from)}{{${item}}}${value.slice(to)}`\n const nextCursor = from + `{{${item}}}`.length\n\n // Pill set changed — force a re-render and reposition the caret.\n lastPillSignature = pillSignature(next, withVariables)\n renderModel(next)\n setModelCaret(nextCursor)\n\n showDropdown.value = false\n emitChange(next, { skipDropdownCheck: true })\n}\n\n// ───────────────────────────────────────────────────────────────────\n// Change / focus / blur\n// ───────────────────────────────────────────────────────────────────\n\nconst emitChange = (\n value: string,\n opts: { skipDropdownCheck?: boolean } = {},\n): void => {\n const same = value === serializeValue(modelValue)\n if (alwaysEmitChange || !same) {\n emit('update:modelValue', value)\n }\n if (!opts.skipDropdownCheck) {\n updateDropdownVisibility()\n }\n}\n\nconst handleInput = (): void => {\n const text = serializeEditor()\n isEmpty.value = isBlankValue(text)\n\n // Only rebuild when the pill set changes (e.g. `}}` closed a pattern, or\n // a value was pasted). Skipping it for plain-text edits preserves the\n // live selection — important for IME composition and double-click select.\n // Also defer while composing; `handleCompositionEnd` re-runs this path so the\n // rebuild happens once the IME has committed its text.\n const sig = pillSignature(text, withVariables)\n if (!isComposing.value && sig !== lastPillSignature) {\n const caret = getModelCaret()\n lastPillSignature = sig\n renderModel(text)\n if (caret !== null) {\n setModelCaret(caret)\n }\n }\n\n emitChange(text)\n}\n\nconst handleCompositionStart = (): void => {\n isComposing.value = true\n}\n\nconst handleCompositionEnd = (): void => {\n isComposing.value = false\n // Run the deferred input path now that the composition has committed, so any\n // pill that formed during composition is rendered.\n handleInput()\n}\n\nconst handleFocus = (): void => {\n isFocused.value = true\n ensureComponentId()\n ensureTooltipsActive()\n}\n\nconst handleBlur = (event: FocusEvent): void => {\n isFocused.value = false\n showDropdown.value = false\n const value = serializeEditor()\n // Check the serialized `value`, not `modelValue` — a `0` or `false` model is\n // a valid non-empty entry that should still submit on blur.\n if (emitOnBlur && value) {\n emit('submit', value, event)\n }\n emit('blur', value, event)\n}\n\n/**\n * Strip rich content on paste; `contenteditable=\"plaintext-only\"` is not\n * reliable cross-browser, so we intercept and use `insertText` to keep undo.\n */\nconst handlePaste = (event: ClipboardEvent): void => {\n event.preventDefault()\n const text = event.clipboardData?.getData('text/plain') ?? ''\n if (!text) {\n return\n }\n document.execCommand('insertText', false, text.replace(/\\r?\\n/g, ' '))\n // `insertText` normally fires an `input` event, but that is not guaranteed\n // across browsers. Run the same path explicitly so pill rendering, emptiness,\n // `update:modelValue`, and the dropdown never lag behind the pasted DOM.\n handleInput()\n}\n\n// ───────────────────────────────────────────────────────────────────\n// Keyboard handling\n// ───────────────────────────────────────────────────────────────────\n\nconst handleKeyDown = (event: KeyboardEvent): void => {\n if (showDropdown.value) {\n if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {\n event.preventDefault()\n event.stopPropagation()\n dropdownRef.value?.handleArrowKey(\n event.key === 'ArrowDown' ? 'down' : 'up',\n )\n return\n }\n if (event.key === 'Enter') {\n event.preventDefault()\n event.stopPropagation()\n dropdownRef.value?.handleSelect()\n return\n }\n if (event.key === 'Escape') {\n event.preventDefault()\n event.stopPropagation()\n showDropdown.value = false\n return\n }\n }\n\n if (event.key === 'Enter') {\n // Block the browser default so a contenteditable div does not insert\n // <br> / <div> and break single-line semantics, then emit submit\n // (used by the table editors).\n event.preventDefault()\n emit('submit', serializeEditor(), event)\n return\n }\n\n // Backspace / Delete: pill atomicity is handled by the browser via\n // `contenteditable=\"false\"` on pills — no manual `}}`-pair handling needed.\n}\n\n// ───────────────────────────────────────────────────────────────────\n// Click forwarding & lifecycle\n// ───────────────────────────────────────────────────────────────────\n\n/**\n * Clicking a pill selects it whole, so a subsequent Backspace deletes it\n * in one keystroke and typing replaces it — the usual chip/mention model.\n */\nconst handleEditorClick = (event: MouseEvent): void => {\n const target =\n event.target instanceof Element\n ? event.target.closest<HTMLElement>('.scalar-pill')\n : null\n if (!target) {\n return\n }\n const editor = editorRef.value\n if (!editor) {\n return\n }\n editor.focus()\n const range = document.createRange()\n range.selectNode(target)\n const selection = window.getSelection()\n selection?.removeAllRanges()\n selection?.addRange(range)\n updateDropdownVisibility()\n}\n\nonMounted(() => {\n const initial = serializeValue(modelValue)\n lastPillSignature = pillSignature(initial, withVariables)\n lastEnvKey = computeEnvKey()\n renderModel(initial)\n isEmpty.value = isBlankValue(initial)\n\n // `autofocus` on a contenteditable div is not honoured natively, so focus\n // the editor ourselves when the consumer passes the attribute.\n if (Object.hasOwn(attrs, 'autofocus')) {\n editorRef.value?.focus()\n }\n})\n\nwatch(\n () => modelValue,\n (next) => {\n const serialized = serializeValue(next)\n // Always sync the placeholder flag, even when the DOM already matches and we\n // skip the rebuild below. Otherwise a value cell that switches from select\n // mode (no editor element) into the empty editor keeps a stale `isEmpty`,\n // and the placeholder silently disappears.\n isEmpty.value = isBlankValue(serialized)\n if (serializeEditor() === serialized) {\n return\n }\n lastPillSignature = pillSignature(serialized, withVariables)\n renderModel(serialized)\n },\n)\n\n// The editable surface only exists in \"editor mode\" (see template). When a row switches into editor\n// mode after mount — most notably when this component instance is reused for a different table row —\n// `onMounted` has already run and the `modelValue` watch fired while `editorRef` was still null, so\n// the model was never painted into the freshly created element and the cell renders empty.\n//\n// Paint the model when the element appears, but only into a still-empty editor: an editor that\n// already holds text is either up to date or ahead of `modelValue` with an uncommitted edit/paste,\n// and must not be clobbered.\n//\n// `flush: 'sync'` makes the paint part of the same step that creates the element. Vue assigns a\n// non-null template ref from a post-render effect, so the element is already mounted and patched\n// when this runs — deferring any further (the `pre` default, or `post`) only pushes the paint past\n// the consumer effects that run later in the same flush. A parent that focuses the cell as it\n// switches into editor mode would then place the caret in a still-empty editor, and the paint's\n// `replaceChildren` would drop that selection.\nwatch(\n editorRef,\n (editor) => {\n if (!editor || !isBlankValue(serializeEditor())) {\n return\n }\n const serialized = serializeValue(modelValue)\n if (serialized === '') {\n return\n }\n lastPillSignature = pillSignature(serialized, withVariables)\n renderModel(serialized)\n },\n { flush: 'sync' },\n)\n\nwatch(\n [() => environment, () => withVariables],\n () => {\n // Env changes affect pill colour and `isDefined` opacity — rebuild.\n const envKey = computeEnvKey()\n if (envKey === lastEnvKey) {\n return\n }\n lastEnvKey = envKey\n // Most rows are plain text; skip the DOM walk when there are no pills.\n // Pills introduced later flow through `handleInput` / the modelValue\n // watcher, which update `lastPillSignature`.\n if (lastPillSignature === '') {\n return\n }\n lastPillSignature = pillSignature(serializeEditor(), withVariables)\n // Preserve the caret across the rebuild so editing does not jump to the\n // start when the environment changes mid-edit (mirrors `handleInput`).\n const caret = getModelCaret()\n renderModel(serializeEditor())\n if (caret !== null) {\n setModelCaret(caret)\n }\n },\n // Variables are often mutated in place (e.g. editing a value in the env\n // editor) without the object reference changing — deep watch catches it.\n { deep: true },\n)\n\nonBeforeUnmount(() => {\n teardownPillTooltips()\n})\n\n// ───────────────────────────────────────────────────────────────────\n// Public API\n// ───────────────────────────────────────────────────────────────────\n\ndefineExpose({\n /** Focus the editor. `position` controls caret placement. */\n focus: (position?: 'start' | 'end' | number): void => {\n const editor = editorRef.value\n if (!editor) {\n return\n }\n editor.focus()\n if (!isDefined(position)) {\n return\n }\n const length = serializeEditor().length\n const pos =\n position === 'start' ? 0 : position === 'end' ? length : position\n setModelCaret(pos)\n },\n /** Replace the current value programmatically and re-render the pills. */\n setContent: (next = ''): void => {\n if (serializeEditor() === next) {\n return\n }\n lastPillSignature = pillSignature(next, withVariables)\n renderModel(next)\n isEmpty.value = isBlankValue(next)\n },\n /** Read the current value as a `{{name}}`-bearing string. */\n getValue: (): string => serializeEditor(),\n /** Caret offset in the model string. */\n cursorPosition: (): number | undefined => {\n const c = getModelCaret()\n return c === null ? undefined : c\n },\n isFocused,\n editorRef,\n})\n</script>\n\n<template>\n <!-- Disabled mode: read-only label -->\n <div\n v-if=\"disabled\"\n class=\"text-c-2 flex cursor-default items-center justify-center\"\n :class=\"{\n 'font-code pr-2 pl-1 text-base': layout === 'modal',\n 'px-2': layout !== 'modal',\n 'line-through': linethrough,\n }\"\n data-testid=\"code-input-lite-disabled\">\n <span class=\"whitespace-nowrap\">{{ modelValue }}</span>\n </div>\n\n <!-- Enum mode: select dropdown with predefined values -->\n <DataTableInputSelect\n v-else-if=\"enumProp?.length\"\n :default=\"defaultProp\"\n :modelValue=\"modelValue\"\n :type=\"defaultType\"\n :value=\"enumProp\"\n @update:modelValue=\"handleSelectChange\" />\n\n <!-- Boolean mode: select dropdown with true/false (and optionally null) -->\n <DataTableInputSelect\n v-else-if=\"isBooleanMode\"\n :default=\"defaultProp\"\n :modelValue=\"modelValue\"\n :value=\"booleanOptions\"\n @update:modelValue=\"handleSelectChange\" />\n\n <!-- Examples mode: select dropdown with example values -->\n <DataTableInputSelect\n v-else-if=\"examples?.length\"\n :default=\"defaultProp\"\n :modelValue=\"modelValue\"\n :value=\"examples\"\n @update:modelValue=\"handleSelectChange\" />\n\n <!-- Editor mode -->\n <div\n v-else\n :id=\"componentId\"\n v-bind=\"wrapperAttrs\"\n class=\"code-input-lite group/code-input-lite peer relative w-full leading-[1.44] -outline-offset-1 has-[:focus-visible]:rounded-[4px] has-[:focus-visible]:outline\"\n :class=\"{\n 'code-input-lite--error': error,\n 'code-input-lite--empty': isEmpty,\n 'line-through': linethrough,\n }\">\n <!-- The single editable surface; see the file header for how pills work. -->\n <div\n ref=\"editorRef\"\n :aria-activedescendant=\"\n displayVariablesDropdown ? activeOptionId : undefined\n \"\n :aria-autocomplete=\"withVariables ? 'list' : undefined\"\n :aria-controls=\"displayVariablesDropdown ? listboxId : undefined\"\n :aria-expanded=\"displayVariablesDropdown ? 'true' : undefined\"\n :aria-invalid=\"error ? 'true' : undefined\"\n :aria-label=\"ariaLabel\"\n :aria-labelledby=\"ariaLabelledby\"\n :aria-readonly=\"readOnly ? 'true' : undefined\"\n :aria-required=\"required ? 'true' : undefined\"\n class=\"code-input-lite__editor\"\n :contenteditable=\"readOnly ? 'false' : 'true'\"\n :data-placeholder=\"placeholder\"\n :role=\"withVariables ? 'combobox' : 'textbox'\"\n spellcheck=\"false\"\n @blur=\"handleBlur\"\n @click=\"handleEditorClick\"\n @compositionend=\"handleCompositionEnd\"\n @compositionstart=\"handleCompositionStart\"\n @focus=\"handleFocus\"\n @input=\"handleInput\"\n @keydown=\"handleKeyDown\"\n @paste=\"handlePaste\"\n @pointerover=\"ensureTooltipsActive\" />\n </div>\n\n <!--\n Slots and the required indicator are siblings of the mode templates so\n they render in every mode and so `absolute right-0` anchors to the\n surrounding (relative) cell rather than the shrink-wrapped mode wrapper.\n -->\n <div\n v-if=\"$slots.warning\"\n class=\"centered-y text-orange absolute right-7 text-xs\">\n <slot name=\"warning\" />\n </div>\n <div\n v-if=\"$slots.icon\"\n class=\"centered-y absolute right-0 flex h-full items-center p-1.5 group-has-[.code-input-lite__editor:focus]:z-1\">\n <slot name=\"icon\" />\n </div>\n <div\n v-if=\"required\"\n class=\"required centered-y text-xxs text-c-3 group-[.error]:text-red bg-b-1 pointer-events-none absolute right-0 mr-0.5 pt-px pr-2 opacity-100 shadow-[-8px_0_4px_var(--scalar-background-1)] transition-opacity duration-150 peer-has-[.code-input-lite__editor:focus]:opacity-0\">\n {{ translate('apiClient.codeInputLite.required') }}\n </div>\n\n <EnvironmentVariableDropdown\n v-if=\"displayVariablesDropdown\"\n ref=\"dropdownRef\"\n :contextFunctionItems=\"contextFunctionDropdownItems\"\n :dropdownPosition=\"dropdownPosition\"\n :environment=\"environment\"\n :listboxId=\"listboxId\"\n :query=\"dropdownQuery\"\n @close=\"showDropdown = false\"\n @redirect=\"emit('navigate', { page: 'document', path: 'environment' })\"\n @select=\"handleDropdownSelect\" />\n</template>\n\n<style scoped>\n.code-input-lite {\n /* Flex so the editor centres vertically in whatever height the cell gives us.\n Font properties inherit so we adopt the surrounding typography. */\n display: flex;\n align-items: center;\n}\n\n.code-input-lite__editor {\n /* Everything font-related inherits from the surrounding context. */\n font: inherit;\n letter-spacing: inherit;\n flex: 1;\n min-width: 0;\n background: transparent;\n outline: none;\n color: var(--scalar-color-1);\n caret-color: var(--scalar-color-1);\n /* Single-line: horizontal scroll keeps the caret visible for long values;\n the scrollbar itself is hidden (would be noisy inside a table cell). */\n white-space: pre;\n overflow-x: auto;\n overflow-y: hidden;\n scrollbar-width: none;\n padding: 0 0.5em;\n box-sizing: border-box;\n line-height: 1.44;\n /* Positioning context for the absolutely positioned placeholder. */\n position: relative;\n}\n\n.code-input-lite__editor::-webkit-scrollbar {\n display: none;\n}\n\n/* Absolute so the placeholder does not occupy flow space inside the\n contenteditable; otherwise the caret would land after it on focus.\n `pointer-events: none` lets clicks fall through to focus the editor.\n Hidden on focus so it never renders on top of the text caret. */\n.code-input-lite--empty .code-input-lite__editor:not(:focus)::before {\n content: attr(data-placeholder);\n color: var(--scalar-color-3);\n pointer-events: none;\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0.5em;\n display: flex;\n align-items: center;\n}\n\n.code-input-lite--error .code-input-lite__editor {\n outline: 1px solid var(--scalar-color-red);\n}\n</style>\n\n<style>\n/* Pill styling. Each pill is `<span contenteditable=\"false\">name</span>` —\n an atomic widget; the caret lands before or after it, never inside. */\n.scalar-pill {\n color: var(--scalar-color-2);\n border-radius: var(--scalar-radius-full);\n display: inline-block;\n font-family: var(--scalar-font-code);\n font-size: 0.9em;\n line-height: 1.4;\n vertical-align: baseline;\n background: var(--scalar-background-3);\n padding: 0.125em 0.6em;\n margin-right: 0.35em;\n cursor: text;\n /* Single click selects the whole pill — chip/mention model, deletes in one go. */\n user-select: all;\n -webkit-user-select: all;\n}\n\n.dark-mode .scalar-pill {\n background: color-mix(\n in srgb,\n var(--tw-bg-base, var(--scalar-color-1)),\n transparent 90%\n );\n}\n\n.light-mode .scalar-pill {\n background: var(--scalar-background-3);\n}\n\n.scalar-pill--context-fn {\n /* Inset box-shadow as a border so the layout box stays identical to plain pills. */\n box-shadow: 0 0 0 1px\n color-mix(in srgb, var(--scalar-color-3), transparent 35%) inset;\n}\n\n.dark-mode .scalar-pill--context-fn {\n background: color-mix(in srgb, var(--scalar-background-3), transparent 55%);\n}\n\n.light-mode .scalar-pill--context-fn {\n background: color-mix(in srgb, var(--scalar-background-3), transparent 40%);\n}\n</style>\n"],"mappings":""}
|
|
1
|
+
{"version":3,"file":"CodeInputLite.vue.js","names":[],"sources":["../../../../src/v2/components/code-input/CodeInputLite.vue"],"sourcesContent":["<script lang=\"ts\">\n/**\n * CodeInputLite\n *\n * Single-line `contenteditable` editor that renders `{{varname}}` as atomic\n * pill spans (`contenteditable=\"false\"`) and offers an env-variable\n * autocomplete on `{{`. The value is still exposed as a `{{name}}`-bearing\n * string via `update:modelValue`; DOM ↔ model conversion lives in\n * `renderModel` and `serializeEditor`.\n */\nexport default {\n inheritAttrs: false,\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { isDefined } from '@scalar/helpers/array/is-defined'\nimport { REGEX } from '@scalar/helpers/regex/regex-helpers'\nimport {\n CONTEXT_FUNCTION_NAMES,\n getContextFunctionComment,\n isContextFunctionName,\n type ContextFunctionName,\n} from '@scalar/workspace-store/request-example'\nimport type { XScalarEnvironment } from '@scalar/workspace-store/schemas/extensions/document/x-scalar-environments'\nimport { nanoid } from 'nanoid'\nimport {\n computed,\n createApp,\n nextTick,\n onBeforeUnmount,\n onMounted,\n ref,\n useAttrs,\n useTemplateRef,\n watch,\n type App,\n} from 'vue'\n\nimport DataTableInputSelect from '@/v2/components/data-table/DataTableInputSelect.vue'\nimport EnvironmentVariableDropdown from '@/v2/features/environments/components/EnvironmentVariablesDropdown.vue'\nimport { useLocalization } from '@/v2/features/localization'\nimport type { ClientLayout } from '@/v2/types/layout'\n\nimport type { CodeInputModelValue } from './CodeInput.vue'\nimport { buildPillContext } from './helpers/build-pill-context'\nimport { lookupVariableValue } from './helpers/lookup-variable-value'\nimport { pillSignature } from './helpers/pill-signature'\nimport { serializeValue } from './helpers/serialize-value'\nimport PillTooltipHost from './PillTooltipHost.vue'\n\nconst {\n modelValue,\n environment,\n disabled = false,\n readOnly = false,\n error = false,\n layout = 'desktop',\n placeholder,\n required = false,\n emitOnBlur = true,\n alwaysEmitChange = false,\n withVariables = true,\n withFakeData = false,\n linethrough = false,\n type,\n enum: enumProp,\n arrayEncoding,\n examples,\n default: defaultProp,\n nullable = false,\n} = defineProps<Props>()\n\nconst emit = defineEmits<{\n 'update:modelValue': [value: string]\n 'submit': [value: string, event: KeyboardEvent | FocusEvent]\n 'blur': [value: string, event: FocusEvent]\n 'navigate': [route: { page: 'document'; path: 'environment' }]\n}>()\n\nconst { translate } = useLocalization()\n\ntype Props = {\n modelValue: CodeInputModelValue\n /** Environment for variable substitution. Pass undefined to disable env vars */\n environment: XScalarEnvironment | undefined\n /** Render as a non-interactive read-only label */\n disabled?: boolean\n /** Render the input with the native `readonly` attribute (still focusable, no edits) */\n readOnly?: boolean\n /** Show error styling */\n error?: boolean\n /** Layout context affects styling and dropdown visibility */\n layout?: ClientLayout\n /** Placeholder text for an empty input */\n placeholder?: string\n /** Show required indicator */\n required?: boolean\n /** Emit submit on blur */\n emitOnBlur?: boolean\n /** Render variable pills + show the autocomplete dropdown */\n withVariables?: boolean\n /** Include `{{$guid}}` etc. in the autocomplete dropdown */\n withFakeData?: boolean\n /** Always emit change events even if the value is unchanged */\n alwaysEmitChange?: boolean\n /** Strike-through styling for the input text (e.g. overridden values) */\n linethrough?: boolean\n /** Schema type — drives boolean select mode when `boolean` is included */\n type?: string | string[]\n /** Predefined enum values; when set the input is replaced by a select */\n enum?: unknown[]\n /** Text representation of array selections. */\n arrayEncoding?: 'json' | 'comma-separated'\n /** Example values; when set (and no enum/boolean) the input is replaced by a select */\n examples?: string[]\n /** Default value to suggest in select modes */\n default?: CodeInputModelValue\n /** Whether the boolean select includes a `null` option */\n nullable?: boolean\n}\n\nconst attrs = useAttrs()\nconst ariaLabel = computed(() =>\n typeof attrs['aria-label'] === 'string' ? attrs['aria-label'] : undefined,\n)\n/** Lifted to the editable surface like aria-label, so a visible label can name it */\nconst ariaLabelledby = computed(() =>\n typeof attrs['aria-labelledby'] === 'string'\n ? attrs['aria-labelledby']\n : undefined,\n)\n/**\n * The wrapper is a generic div, and ARIA prohibits naming a generic element,\n * so the naming attributes only go on the editor and not on the wrapper.\n */\nconst wrapperAttrs = computed(() => {\n const {\n 'aria-label': _ariaLabel,\n 'aria-labelledby': _ariaLabelledby,\n ...rest\n } = attrs\n return rest\n})\n\n/**\n * The id only matters once the dropdown opens (`aria-controls` /\n * `aria-activedescendant`), so we defer `nanoid()` until first focus to\n * keep idle instances cheap. A consumer-supplied `id` attr is preserved.\n */\nconst generatedComponentId = ref<string | null>(null)\nconst componentId = computed((): string | undefined =>\n typeof attrs.id === 'string'\n ? attrs.id\n : (generatedComponentId.value ?? undefined),\n)\nconst ensureComponentId = (): void => {\n if (\n (typeof attrs.id !== 'string' || !attrs.id) &&\n generatedComponentId.value === null\n ) {\n generatedComponentId.value = `id-${nanoid()}`\n }\n}\n\nconst editorRef = useTemplateRef<HTMLDivElement>('editorRef')\nconst dropdownRef = ref<InstanceType<\n typeof EnvironmentVariableDropdown\n> | null>(null)\n\n/** Id of the dropdown's `role=\"listbox\"` element, for the combobox wiring. */\nconst listboxId = computed((): string | undefined =>\n componentId.value ? `${componentId.value}-listbox` : undefined,\n)\n\n/**\n * Id of the option the dropdown currently highlights. Mirrors the dropdown's\n * own selection so the editor can expose it via `aria-activedescendant`.\n */\nconst activeOptionId = computed(\n (): string | undefined => dropdownRef.value?.activeOptionId,\n)\n\nconst isFocused = ref(false)\nconst isEmpty = ref(true)\n\n/**\n * True while an IME composition is in progress. Rebuilding the editor DOM\n * mid-composition (e.g. when `{{` forms a pill) cancels the composition, so we\n * defer those rebuilds until `compositionend`.\n */\nconst isComposing = ref(false)\n\n/**\n * Whether the serialized value should count as empty for placeholder display.\n *\n * `contenteditable` can leave behind invisible residue after some delete\n * sequences — most commonly a non-breaking space (`\\u00a0`) — which makes a\n * visually empty field report a non-zero length and silently drop its\n * placeholder. Trimming covers that case; `\\u00a0` counts as whitespace, so a\n * field that only holds editor residue is treated as empty. This affects the\n * placeholder flag only, never the value emitted via `serializeEditor`.\n */\nconst isBlankValue = (text: string): boolean => text.trim().length === 0\n\n// ───────────────────────────────────────────────────────────────────\n// Rendering-mode detection (parity with CodeInput's select dispatch)\n// ───────────────────────────────────────────────────────────────────\n\n/** True when the schema type is exactly `boolean` (or includes it in a tuple type). */\nconst isBooleanMode = computed((): boolean => {\n if (enumProp?.length) {\n return false\n }\n return type === 'boolean' || (Array.isArray(type) && type.includes('boolean'))\n})\n\nconst booleanOptions = computed((): string[] =>\n nullable ? ['true', 'false', 'null'] : ['true', 'false'],\n)\n\n/** Default type when the schema is a tuple — picks the first non-null entry. */\nconst defaultType = computed((): string | undefined => {\n if (Array.isArray(type)) {\n return type.find((t) => t !== 'null') ?? 'string'\n }\n return type\n})\n\nconst handleSelectChange = (value: string): void =>\n emit('update:modelValue', value)\n\n// ───────────────────────────────────────────────────────────────────\n// Per-pill tooltip apps\n// ───────────────────────────────────────────────────────────────────\n\nlet pillTooltipApps: App[] = []\n\n/**\n * Per-pill tooltips are the heaviest part of the render (a Vue app +\n * `useTooltip` watch + listeners each), so we defer mounting them until\n * the first interaction (focus, pointerover, or dropdown open). Once on,\n * subsequent rebuilds remount tooltips for the new pills.\n */\nlet tooltipsActive = false\n\nconst teardownPillTooltips = (): void => {\n for (const app of pillTooltipApps) {\n app.unmount()\n }\n pillTooltipApps = []\n}\n\nconst mountPillTooltips = (): void => {\n if (!editorRef.value || layout === 'modal') {\n return\n }\n const pills = editorRef.value.querySelectorAll<HTMLElement>('.scalar-pill')\n for (const pillEl of pills) {\n const variableName = pillEl.dataset.variable ?? ''\n const context = buildPillContext(variableName, environment)\n const app = createApp(PillTooltipHost, {\n context,\n target: pillEl,\n translate,\n })\n // PillTooltipHost is renderless; useTooltip attaches to `target` directly.\n app.mount(document.createElement('div'))\n pillTooltipApps.push(app)\n }\n}\n\n// ───────────────────────────────────────────────────────────────────\n// DOM ↔ model conversion\n// ───────────────────────────────────────────────────────────────────\n\n/**\n * Build a pill `<span>` for the given variable. `contentEditable = 'false'`\n * makes the browser treat it as a single atom (arrow keys jump over it,\n * Backspace deletes it whole); `{{` / `}}` only live in the model string.\n */\nconst createPillElement = (\n name: string,\n start: number,\n end: number,\n): HTMLSpanElement => {\n const isCtx = isContextFunctionName(name)\n const span = document.createElement('span')\n span.className = isCtx ? 'scalar-pill scalar-pill--context-fn' : 'scalar-pill'\n span.contentEditable = 'false'\n span.dataset.variable = name\n // Model-coordinate offsets (the pill stands in for the full `{{name}}`).\n // Used by click forwarding and tests to map a pill back to the value.\n span.dataset.pillStart = String(start)\n span.dataset.pillEnd = String(end)\n\n const color = isCtx\n ? 'var(--scalar-color-3)'\n : environment?.color || 'var(--scalar-color-1)'\n span.style.setProperty('--tw-bg-base', color)\n\n // Fade env pills with no usable value. A falsy check (not just\n // `=== undefined`) matches the tooltip path's `Boolean(value)`, so a\n // variable declared with an empty string fades here too.\n const isUndefinedEnv = !isCtx && !lookupVariableValue(environment, name)\n if (isUndefinedEnv) {\n span.style.opacity = '0.5'\n }\n\n span.textContent = name\n return span\n}\n\n/** Render a model string into the editor as a mix of text nodes + pills. */\nconst renderModel = (text: string): void => {\n const editor = editorRef.value\n if (!editor) {\n return\n }\n\n teardownPillTooltips()\n editor.replaceChildren()\n\n if (!withVariables || !text.includes('{{')) {\n if (text) {\n editor.appendChild(document.createTextNode(text))\n }\n isEmpty.value = isBlankValue(text)\n return\n }\n\n const regex = new RegExp(REGEX.VARIABLES.source, REGEX.VARIABLES.flags)\n let lastIndex = 0\n let match: RegExpExecArray | null\n\n while ((match = regex.exec(text)) !== null) {\n const start = match.index\n const end = start + match[0].length\n if (start > lastIndex) {\n editor.appendChild(document.createTextNode(text.slice(lastIndex, start)))\n }\n editor.appendChild(createPillElement(match[1] ?? '', start, end))\n lastIndex = end\n }\n\n if (lastIndex < text.length) {\n editor.appendChild(document.createTextNode(text.slice(lastIndex)))\n }\n\n isEmpty.value = false\n if (tooltipsActive) {\n mountPillTooltips()\n }\n}\n\n/** Length the given child contributes to the serialized model string. */\nconst modelLengthOf = (node: Node): number => {\n if (node.nodeType === Node.TEXT_NODE) {\n return (node.textContent ?? '').length\n }\n if (node instanceof HTMLElement && node.classList.contains('scalar-pill')) {\n return `{{${node.dataset.variable ?? ''}}}`.length\n }\n // Defensive: a stray element (e.g. browser-inserted <br>) — use its text.\n return (node.textContent ?? '').length\n}\n\n/** Read the editor DOM back into a `{{name}}`-bearing model string. */\nconst serializeEditor = (): string => {\n const editor = editorRef.value\n if (!editor) {\n return ''\n }\n let out = ''\n for (const node of Array.from(editor.childNodes)) {\n if (node.nodeType === Node.TEXT_NODE) {\n out += node.textContent ?? ''\n } else if (\n node instanceof HTMLElement &&\n node.classList.contains('scalar-pill')\n ) {\n out += `{{${node.dataset.variable ?? ''}}}`\n } else if (node instanceof HTMLElement) {\n // Flatten any stray <br> / <div> the browser may inject on paste/Enter.\n out += node.textContent ?? ''\n }\n }\n return out\n}\n\nlet lastPillSignature: string | null = null\nlet lastEnvKey = ''\n\n/**\n * Cache key for the env + `withVariables` state. Includes variable\n * name/value pairs so the watcher notices adds/removes/edits even when\n * `environment.color` is unchanged — without that, pills keep stale\n * `isDefined` opacity and tooltip values until the input itself changes.\n */\nconst computeEnvKey = (): string => {\n const color = environment?.color ?? ''\n const flag = withVariables ? '1' : '0'\n const variables = environment?.variables ?? []\n let vars = ''\n for (const v of variables) {\n const value =\n typeof v.value === 'string' ? v.value : (v.value?.default ?? '')\n // Unit separators (\\x1f / \\x1e) so values can safely contain `|` or `=`.\n vars += `\\x1f${v.name}\\x1e${value}`\n }\n return `${color}|${flag}|${vars}`\n}\n\n/** Idempotent: first call flips `tooltipsActive` and mounts pill tooltips. */\nconst ensureTooltipsActive = (): void => {\n if (tooltipsActive) {\n return\n }\n tooltipsActive = true\n mountPillTooltips()\n}\n\n// ───────────────────────────────────────────────────────────────────\n// Caret ↔ model offset\n// ───────────────────────────────────────────────────────────────────\n\n/** Selection start as a model-string offset, or `null` if not inside the editor. */\nconst getModelCaret = (): number | null => {\n const editor = editorRef.value\n if (!editor) {\n return null\n }\n const selection = window.getSelection()\n if (!selection || selection.rangeCount === 0) {\n return null\n }\n const range = selection.getRangeAt(0)\n if (\n range.startContainer !== editor &&\n !editor.contains(range.startContainer)\n ) {\n return null\n }\n\n // Anchored on the editor itself: `startOffset` is a child index.\n if (range.startContainer === editor) {\n let pos = 0\n for (\n let i = 0;\n i < range.startOffset && i < editor.childNodes.length;\n i++\n ) {\n pos += modelLengthOf(editor.childNodes.item(i))\n }\n return pos\n }\n\n let pos = 0\n for (const child of Array.from(editor.childNodes)) {\n if (child === range.startContainer) {\n return pos + range.startOffset\n }\n // Pills are non-editable; if a browser quirk still lands a selection\n // inside one, snap to the nearest boundary instead of getting stuck.\n if (child.contains(range.startContainer)) {\n return range.startOffset === 0 ? pos : pos + modelLengthOf(child)\n }\n pos += modelLengthOf(child)\n }\n return pos\n}\n\n/** Place the caret at the given model offset, walking the DOM to find it. */\nconst setModelCaret = (target: number): void => {\n const editor = editorRef.value\n if (!editor) {\n return\n }\n const range = document.createRange()\n let pos = 0\n let placed = false\n\n for (const child of Array.from(editor.childNodes)) {\n const len = modelLengthOf(child)\n if (pos + len >= target) {\n if (child.nodeType === Node.TEXT_NODE) {\n const into = Math.max(\n 0,\n Math.min(target - pos, (child.textContent ?? '').length),\n )\n range.setStart(child, into)\n } else if (target - pos <= 0) {\n range.setStartBefore(child)\n } else {\n range.setStartAfter(child)\n }\n placed = true\n break\n }\n pos += len\n }\n\n if (!placed) {\n range.selectNodeContents(editor)\n range.collapse(false)\n } else {\n range.collapse(true)\n }\n\n const selection = window.getSelection()\n if (!selection) {\n return\n }\n selection.removeAllRanges()\n selection.addRange(range)\n}\n\n// ───────────────────────────────────────────────────────────────────\n// Environment variable dropdown\n// ───────────────────────────────────────────────────────────────────\n\nconst showDropdown = ref(false)\nconst dropdownQuery = ref('')\nconst dropdownPosition = ref({ left: 0, top: 0 })\n\nconst contextFunctionDropdownItems = computed(() =>\n withFakeData\n ? CONTEXT_FUNCTION_NAMES.map((key) => ({\n key,\n description: getContextFunctionComment(key as ContextFunctionName),\n }))\n : [],\n)\n\nconst displayVariablesDropdown = computed(\n (): boolean =>\n showDropdown.value &&\n withVariables &&\n layout !== 'modal' &&\n (Boolean(environment) || withFakeData),\n)\n\nconst updateDropdownVisibility = (): void => {\n const editor = editorRef.value\n if (!editor) {\n return\n }\n const caret = getModelCaret()\n if (caret === null) {\n showDropdown.value = false\n return\n }\n const text = serializeEditor().slice(0, caret)\n const lastOpen = text.lastIndexOf('{{')\n const lastClose = text.lastIndexOf('}}')\n\n if (lastOpen <= lastClose) {\n showDropdown.value = false\n return\n }\n\n dropdownQuery.value = text.slice(lastOpen + 2)\n // Make sure the combobox has an id before it advertises `aria-expanded`, so\n // `aria-controls` always resolves to the listbox we are about to render.\n ensureComponentId()\n showDropdown.value = true\n\n // Anchor under the caret; `getBoundingClientRect` gives the caret rect in one read.\n nextTick(() => {\n const selection = window.getSelection()\n if (!selection || selection.rangeCount === 0 || !editorRef.value) {\n return\n }\n const r = selection.getRangeAt(0).cloneRange()\n r.collapse(true)\n const rect = r.getBoundingClientRect()\n const editorRect = editorRef.value.getBoundingClientRect()\n // Some browsers collapse empty ranges to a zero rect — fall back to the editor edge.\n dropdownPosition.value = {\n left: rect.left || editorRect.left,\n top: rect.bottom || editorRect.bottom,\n }\n })\n}\n\nconst handleDropdownSelect = (item: string): void => {\n if (readOnly) {\n return\n }\n const caret = getModelCaret() ?? 0\n const value = serializeEditor()\n const from = Math.max(0, caret - dropdownQuery.value.length - 2)\n const to = caret\n const next = `${value.slice(0, from)}{{${item}}}${value.slice(to)}`\n const nextCursor = from + `{{${item}}}`.length\n\n // Pill set changed — force a re-render and reposition the caret.\n lastPillSignature = pillSignature(next, withVariables)\n renderModel(next)\n setModelCaret(nextCursor)\n\n showDropdown.value = false\n emitChange(next, { skipDropdownCheck: true })\n}\n\n// ───────────────────────────────────────────────────────────────────\n// Change / focus / blur\n// ───────────────────────────────────────────────────────────────────\n\nconst emitChange = (\n value: string,\n opts: { skipDropdownCheck?: boolean } = {},\n): void => {\n const same = value === serializeValue(modelValue)\n if (alwaysEmitChange || !same) {\n emit('update:modelValue', value)\n }\n if (!opts.skipDropdownCheck) {\n updateDropdownVisibility()\n }\n}\n\nconst handleInput = (): void => {\n const text = serializeEditor()\n isEmpty.value = isBlankValue(text)\n\n // Only rebuild when the pill set changes (e.g. `}}` closed a pattern, or\n // a value was pasted). Skipping it for plain-text edits preserves the\n // live selection — important for IME composition and double-click select.\n // Also defer while composing; `handleCompositionEnd` re-runs this path so the\n // rebuild happens once the IME has committed its text.\n const sig = pillSignature(text, withVariables)\n if (!isComposing.value && sig !== lastPillSignature) {\n const caret = getModelCaret()\n lastPillSignature = sig\n renderModel(text)\n if (caret !== null) {\n setModelCaret(caret)\n }\n }\n\n emitChange(text)\n}\n\nconst handleCompositionStart = (): void => {\n isComposing.value = true\n}\n\nconst handleCompositionEnd = (): void => {\n isComposing.value = false\n // Run the deferred input path now that the composition has committed, so any\n // pill that formed during composition is rendered.\n handleInput()\n}\n\nconst handleFocus = (): void => {\n isFocused.value = true\n ensureComponentId()\n ensureTooltipsActive()\n}\n\nconst handleBlur = (event: FocusEvent): void => {\n isFocused.value = false\n showDropdown.value = false\n const value = serializeEditor()\n // Check the serialized `value`, not `modelValue` — a `0` or `false` model is\n // a valid non-empty entry that should still submit on blur.\n if (emitOnBlur && value) {\n emit('submit', value, event)\n }\n emit('blur', value, event)\n}\n\n/**\n * Strip rich content on paste; `contenteditable=\"plaintext-only\"` is not\n * reliable cross-browser, so we intercept and use `insertText` to keep undo.\n */\nconst handlePaste = (event: ClipboardEvent): void => {\n event.preventDefault()\n const text = event.clipboardData?.getData('text/plain') ?? ''\n if (!text) {\n return\n }\n document.execCommand('insertText', false, text.replace(/\\r?\\n/g, ' '))\n // `insertText` normally fires an `input` event, but that is not guaranteed\n // across browsers. Run the same path explicitly so pill rendering, emptiness,\n // `update:modelValue`, and the dropdown never lag behind the pasted DOM.\n handleInput()\n}\n\n// ───────────────────────────────────────────────────────────────────\n// Keyboard handling\n// ───────────────────────────────────────────────────────────────────\n\nconst handleKeyDown = (event: KeyboardEvent): void => {\n if (showDropdown.value) {\n if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {\n event.preventDefault()\n event.stopPropagation()\n dropdownRef.value?.handleArrowKey(\n event.key === 'ArrowDown' ? 'down' : 'up',\n )\n return\n }\n if (event.key === 'Enter') {\n event.preventDefault()\n event.stopPropagation()\n dropdownRef.value?.handleSelect()\n return\n }\n if (event.key === 'Escape') {\n event.preventDefault()\n event.stopPropagation()\n showDropdown.value = false\n return\n }\n }\n\n if (event.key === 'Enter') {\n // Block the browser default so a contenteditable div does not insert\n // <br> / <div> and break single-line semantics, then emit submit\n // (used by the table editors).\n event.preventDefault()\n emit('submit', serializeEditor(), event)\n return\n }\n\n // Backspace / Delete: pill atomicity is handled by the browser via\n // `contenteditable=\"false\"` on pills — no manual `}}`-pair handling needed.\n}\n\n// ───────────────────────────────────────────────────────────────────\n// Click forwarding & lifecycle\n// ───────────────────────────────────────────────────────────────────\n\n/**\n * Clicking a pill selects it whole, so a subsequent Backspace deletes it\n * in one keystroke and typing replaces it — the usual chip/mention model.\n */\nconst handleEditorClick = (event: MouseEvent): void => {\n const target =\n event.target instanceof Element\n ? event.target.closest<HTMLElement>('.scalar-pill')\n : null\n if (!target) {\n return\n }\n const editor = editorRef.value\n if (!editor) {\n return\n }\n editor.focus()\n const range = document.createRange()\n range.selectNode(target)\n const selection = window.getSelection()\n selection?.removeAllRanges()\n selection?.addRange(range)\n updateDropdownVisibility()\n}\n\nonMounted(() => {\n const initial = serializeValue(modelValue)\n lastPillSignature = pillSignature(initial, withVariables)\n lastEnvKey = computeEnvKey()\n renderModel(initial)\n isEmpty.value = isBlankValue(initial)\n\n // `autofocus` on a contenteditable div is not honoured natively, so focus\n // the editor ourselves when the consumer passes the attribute.\n if (Object.hasOwn(attrs, 'autofocus')) {\n editorRef.value?.focus()\n }\n})\n\nwatch(\n () => modelValue,\n (next) => {\n const serialized = serializeValue(next)\n // Always sync the placeholder flag, even when the DOM already matches and we\n // skip the rebuild below. Otherwise a value cell that switches from select\n // mode (no editor element) into the empty editor keeps a stale `isEmpty`,\n // and the placeholder silently disappears.\n isEmpty.value = isBlankValue(serialized)\n if (serializeEditor() === serialized) {\n return\n }\n lastPillSignature = pillSignature(serialized, withVariables)\n renderModel(serialized)\n },\n)\n\n// The editable surface only exists in \"editor mode\" (see template). When a row switches into editor\n// mode after mount — most notably when this component instance is reused for a different table row —\n// `onMounted` has already run and the `modelValue` watch fired while `editorRef` was still null, so\n// the model was never painted into the freshly created element and the cell renders empty.\n//\n// Paint the model when the element appears, but only into a still-empty editor: an editor that\n// already holds text is either up to date or ahead of `modelValue` with an uncommitted edit/paste,\n// and must not be clobbered.\n//\n// `flush: 'sync'` makes the paint part of the same step that creates the element. Vue assigns a\n// non-null template ref from a post-render effect, so the element is already mounted and patched\n// when this runs — deferring any further (the `pre` default, or `post`) only pushes the paint past\n// the consumer effects that run later in the same flush. A parent that focuses the cell as it\n// switches into editor mode would then place the caret in a still-empty editor, and the paint's\n// `replaceChildren` would drop that selection.\nwatch(\n editorRef,\n (editor) => {\n if (!editor || !isBlankValue(serializeEditor())) {\n return\n }\n const serialized = serializeValue(modelValue)\n if (serialized === '') {\n return\n }\n lastPillSignature = pillSignature(serialized, withVariables)\n renderModel(serialized)\n },\n { flush: 'sync' },\n)\n\nwatch(\n [() => environment, () => withVariables],\n () => {\n // Env changes affect pill colour and `isDefined` opacity — rebuild.\n const envKey = computeEnvKey()\n if (envKey === lastEnvKey) {\n return\n }\n lastEnvKey = envKey\n // Most rows are plain text; skip the DOM walk when there are no pills.\n // Pills introduced later flow through `handleInput` / the modelValue\n // watcher, which update `lastPillSignature`.\n if (lastPillSignature === '') {\n return\n }\n lastPillSignature = pillSignature(serializeEditor(), withVariables)\n // Preserve the caret across the rebuild so editing does not jump to the\n // start when the environment changes mid-edit (mirrors `handleInput`).\n const caret = getModelCaret()\n renderModel(serializeEditor())\n if (caret !== null) {\n setModelCaret(caret)\n }\n },\n // Variables are often mutated in place (e.g. editing a value in the env\n // editor) without the object reference changing — deep watch catches it.\n { deep: true },\n)\n\nonBeforeUnmount(() => {\n teardownPillTooltips()\n})\n\n// ───────────────────────────────────────────────────────────────────\n// Public API\n// ───────────────────────────────────────────────────────────────────\n\ndefineExpose({\n /** Focus the editor. `position` controls caret placement. */\n focus: (position?: 'start' | 'end' | number): void => {\n const editor = editorRef.value\n if (!editor) {\n return\n }\n editor.focus()\n if (!isDefined(position)) {\n return\n }\n const length = serializeEditor().length\n const pos =\n position === 'start' ? 0 : position === 'end' ? length : position\n setModelCaret(pos)\n },\n /** Replace the current value programmatically and re-render the pills. */\n setContent: (next = ''): void => {\n if (serializeEditor() === next) {\n return\n }\n lastPillSignature = pillSignature(next, withVariables)\n renderModel(next)\n isEmpty.value = isBlankValue(next)\n },\n /** Read the current value as a `{{name}}`-bearing string. */\n getValue: (): string => serializeEditor(),\n /** Caret offset in the model string. */\n cursorPosition: (): number | undefined => {\n const c = getModelCaret()\n return c === null ? undefined : c\n },\n isFocused,\n editorRef,\n})\n</script>\n\n<template>\n <!-- Disabled mode: read-only label -->\n <div\n v-if=\"disabled\"\n class=\"text-c-2 flex cursor-default items-center justify-center\"\n :class=\"{\n 'font-code pr-2 pl-1 text-base': layout === 'modal',\n 'px-2': layout !== 'modal',\n 'line-through': linethrough,\n }\"\n data-testid=\"code-input-lite-disabled\">\n <span class=\"whitespace-nowrap\">{{ modelValue }}</span>\n </div>\n\n <!-- Enum mode: select dropdown with predefined values -->\n <DataTableInputSelect\n v-else-if=\"enumProp?.length\"\n :arrayEncoding=\"arrayEncoding\"\n :default=\"defaultProp\"\n :modelValue=\"modelValue\"\n :type=\"defaultType\"\n :value=\"enumProp\"\n @update:modelValue=\"handleSelectChange\" />\n\n <!-- Boolean mode: select dropdown with true/false (and optionally null) -->\n <DataTableInputSelect\n v-else-if=\"isBooleanMode\"\n :default=\"defaultProp\"\n :modelValue=\"modelValue\"\n :value=\"booleanOptions\"\n @update:modelValue=\"handleSelectChange\" />\n\n <!-- Examples mode: select dropdown with example values -->\n <DataTableInputSelect\n v-else-if=\"examples?.length\"\n :default=\"defaultProp\"\n :modelValue=\"modelValue\"\n :value=\"examples\"\n @update:modelValue=\"handleSelectChange\" />\n\n <!-- Editor mode -->\n <div\n v-else\n :id=\"componentId\"\n v-bind=\"wrapperAttrs\"\n class=\"code-input-lite group/code-input-lite peer relative w-full leading-[1.44] -outline-offset-1 has-[:focus-visible]:rounded-[4px] has-[:focus-visible]:outline\"\n :class=\"{\n 'code-input-lite--error': error,\n 'code-input-lite--empty': isEmpty,\n 'line-through': linethrough,\n }\">\n <!-- The single editable surface; see the file header for how pills work. -->\n <div\n ref=\"editorRef\"\n :aria-activedescendant=\"\n displayVariablesDropdown ? activeOptionId : undefined\n \"\n :aria-autocomplete=\"withVariables ? 'list' : undefined\"\n :aria-controls=\"displayVariablesDropdown ? listboxId : undefined\"\n :aria-expanded=\"displayVariablesDropdown ? 'true' : undefined\"\n :aria-invalid=\"error ? 'true' : undefined\"\n :aria-label=\"ariaLabel\"\n :aria-labelledby=\"ariaLabelledby\"\n :aria-readonly=\"readOnly ? 'true' : undefined\"\n :aria-required=\"required ? 'true' : undefined\"\n class=\"code-input-lite__editor\"\n :contenteditable=\"readOnly ? 'false' : 'true'\"\n :data-placeholder=\"placeholder\"\n :role=\"withVariables ? 'combobox' : 'textbox'\"\n spellcheck=\"false\"\n @blur=\"handleBlur\"\n @click=\"handleEditorClick\"\n @compositionend=\"handleCompositionEnd\"\n @compositionstart=\"handleCompositionStart\"\n @focus=\"handleFocus\"\n @input=\"handleInput\"\n @keydown=\"handleKeyDown\"\n @paste=\"handlePaste\"\n @pointerover=\"ensureTooltipsActive\" />\n </div>\n\n <!--\n Slots and the required indicator are siblings of the mode templates so\n they render in every mode and so `absolute right-0` anchors to the\n surrounding (relative) cell rather than the shrink-wrapped mode wrapper.\n -->\n <div\n v-if=\"$slots.warning\"\n class=\"centered-y text-orange absolute right-7 text-xs\">\n <slot name=\"warning\" />\n </div>\n <div\n v-if=\"$slots.icon\"\n class=\"centered-y absolute right-0 flex h-full items-center p-1.5 group-has-[.code-input-lite__editor:focus]:z-1\">\n <slot name=\"icon\" />\n </div>\n <div\n v-if=\"required\"\n class=\"required centered-y text-xxs text-c-3 group-[.error]:text-red bg-b-1 pointer-events-none absolute right-0 mr-0.5 pt-px pr-2 opacity-100 shadow-[-8px_0_4px_var(--scalar-background-1)] transition-opacity duration-150 peer-has-[.code-input-lite__editor:focus]:opacity-0\">\n {{ translate('apiClient.codeInputLite.required') }}\n </div>\n\n <EnvironmentVariableDropdown\n v-if=\"displayVariablesDropdown\"\n ref=\"dropdownRef\"\n :contextFunctionItems=\"contextFunctionDropdownItems\"\n :dropdownPosition=\"dropdownPosition\"\n :environment=\"environment\"\n :listboxId=\"listboxId\"\n :query=\"dropdownQuery\"\n @close=\"showDropdown = false\"\n @redirect=\"emit('navigate', { page: 'document', path: 'environment' })\"\n @select=\"handleDropdownSelect\" />\n</template>\n\n<style scoped>\n.code-input-lite {\n /* Flex so the editor centres vertically in whatever height the cell gives us.\n Font properties inherit so we adopt the surrounding typography. */\n display: flex;\n align-items: center;\n}\n\n.code-input-lite__editor {\n /* Everything font-related inherits from the surrounding context. */\n font: inherit;\n letter-spacing: inherit;\n flex: 1;\n min-width: 0;\n background: transparent;\n outline: none;\n color: var(--scalar-color-1);\n caret-color: var(--scalar-color-1);\n /* Single-line: horizontal scroll keeps the caret visible for long values;\n the scrollbar itself is hidden (would be noisy inside a table cell). */\n white-space: pre;\n overflow-x: auto;\n overflow-y: hidden;\n scrollbar-width: none;\n padding: 0 0.5em;\n box-sizing: border-box;\n line-height: 1.44;\n /* Positioning context for the absolutely positioned placeholder. */\n position: relative;\n}\n\n.code-input-lite__editor::-webkit-scrollbar {\n display: none;\n}\n\n/* Absolute so the placeholder does not occupy flow space inside the\n contenteditable; otherwise the caret would land after it on focus.\n `pointer-events: none` lets clicks fall through to focus the editor.\n Hidden on focus so it never renders on top of the text caret. */\n.code-input-lite--empty .code-input-lite__editor:not(:focus)::before {\n content: attr(data-placeholder);\n color: var(--scalar-color-3);\n pointer-events: none;\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0.5em;\n display: flex;\n align-items: center;\n}\n\n.code-input-lite--error .code-input-lite__editor {\n outline: 1px solid var(--scalar-color-red);\n}\n</style>\n\n<style>\n/* Pill styling. Each pill is `<span contenteditable=\"false\">name</span>` —\n an atomic widget; the caret lands before or after it, never inside. */\n.scalar-pill {\n color: var(--scalar-color-2);\n border-radius: var(--scalar-radius-full);\n display: inline-block;\n font-family: var(--scalar-font-code);\n font-size: 0.9em;\n line-height: 1.4;\n vertical-align: baseline;\n background: var(--scalar-background-3);\n padding: 0.125em 0.6em;\n margin-right: 0.35em;\n cursor: text;\n /* Single click selects the whole pill — chip/mention model, deletes in one go. */\n user-select: all;\n -webkit-user-select: all;\n}\n\n.dark-mode .scalar-pill {\n background: color-mix(\n in srgb,\n var(--tw-bg-base, var(--scalar-color-1)),\n transparent 90%\n );\n}\n\n.light-mode .scalar-pill {\n background: var(--scalar-background-3);\n}\n\n.scalar-pill--context-fn {\n /* Inset box-shadow as a border so the layout box stays identical to plain pills. */\n box-shadow: 0 0 0 1px\n color-mix(in srgb, var(--scalar-color-3), transparent 35%) inset;\n}\n\n.dark-mode .scalar-pill--context-fn {\n background: color-mix(in srgb, var(--scalar-background-3), transparent 55%);\n}\n\n.light-mode .scalar-pill--context-fn {\n background: color-mix(in srgb, var(--scalar-background-3), transparent 40%);\n}\n</style>\n"],"mappings":""}
|
|
@@ -92,6 +92,7 @@ var CodeInputLite_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ de
|
|
|
92
92
|
},
|
|
93
93
|
type: {},
|
|
94
94
|
enum: {},
|
|
95
|
+
arrayEncoding: {},
|
|
95
96
|
examples: {},
|
|
96
97
|
default: { type: [
|
|
97
98
|
String,
|
|
@@ -559,12 +560,14 @@ var CodeInputLite_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ de
|
|
|
559
560
|
"data-testid": "code-input-lite-disabled"
|
|
560
561
|
}, [createElementVNode("span", _hoisted_1, toDisplayString(__props.modelValue), 1)], 2)) : __props.enum?.length ? (openBlock(), createBlock(DataTableInputSelect_default, {
|
|
561
562
|
key: 1,
|
|
563
|
+
arrayEncoding: __props.arrayEncoding,
|
|
562
564
|
default: __props.default,
|
|
563
565
|
modelValue: __props.modelValue,
|
|
564
566
|
type: defaultType.value,
|
|
565
567
|
value: __props.enum,
|
|
566
568
|
"onUpdate:modelValue": handleSelectChange
|
|
567
569
|
}, null, 8, [
|
|
570
|
+
"arrayEncoding",
|
|
568
571
|
"default",
|
|
569
572
|
"modelValue",
|
|
570
573
|
"type",
|