@scalar/api-client 3.21.1 → 3.21.2

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.
Files changed (91) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/dist/components/SectionFilter.vue.d.ts +0 -2
  3. package/dist/components/SectionFilter.vue.d.ts.map +1 -1
  4. package/dist/components/SectionFilter.vue.js +1 -1
  5. package/dist/components/SectionFilter.vue.js.map +1 -1
  6. package/dist/components/SectionFilter.vue.script.js +2 -8
  7. package/dist/components/SectionFilter.vue.script.js.map +1 -1
  8. package/dist/components/SectionFilterButton.vue.d.ts +0 -1
  9. package/dist/components/SectionFilterButton.vue.d.ts.map +1 -1
  10. package/dist/components/SectionFilterButton.vue.js.map +1 -1
  11. package/dist/components/SectionFilterButton.vue.script.js +2 -10
  12. package/dist/components/SectionFilterButton.vue.script.js.map +1 -1
  13. package/dist/style.css +146 -81
  14. package/dist/v2/blocks/operation-block/components/Header.vue.d.ts.map +1 -1
  15. package/dist/v2/blocks/operation-block/components/Header.vue.js +1 -1
  16. package/dist/v2/blocks/operation-block/components/Header.vue.js.map +1 -1
  17. package/dist/v2/blocks/operation-block/components/Header.vue.script.js +2 -0
  18. package/dist/v2/blocks/operation-block/components/Header.vue.script.js.map +1 -1
  19. package/dist/v2/blocks/request-block/RequestBlock.vue.d.ts.map +1 -1
  20. package/dist/v2/blocks/request-block/RequestBlock.vue.js +1 -1
  21. package/dist/v2/blocks/request-block/RequestBlock.vue.js.map +1 -1
  22. package/dist/v2/blocks/request-block/RequestBlock.vue.script.js +17 -6
  23. package/dist/v2/blocks/request-block/RequestBlock.vue.script.js.map +1 -1
  24. package/dist/v2/blocks/request-block/components/RequestCodeSnippet.vue.script.js +2 -0
  25. package/dist/v2/blocks/request-block/components/RequestCodeSnippet.vue.script.js.map +1 -1
  26. package/dist/v2/blocks/response-block/ResponseBlock.vue.d.ts.map +1 -1
  27. package/dist/v2/blocks/response-block/ResponseBlock.vue.js +1 -1
  28. package/dist/v2/blocks/response-block/ResponseBlock.vue.js.map +1 -1
  29. package/dist/v2/blocks/response-block/ResponseBlock.vue.script.js +0 -2
  30. package/dist/v2/blocks/response-block/ResponseBlock.vue.script.js.map +1 -1
  31. package/dist/v2/blocks/scalar-address-bar-block/components/AddressBar.vue.d.ts.map +1 -1
  32. package/dist/v2/blocks/scalar-address-bar-block/components/AddressBar.vue.js +1 -1
  33. package/dist/v2/blocks/scalar-address-bar-block/components/AddressBar.vue.js.map +1 -1
  34. package/dist/v2/blocks/scalar-address-bar-block/components/AddressBar.vue.script.js +23 -43
  35. package/dist/v2/blocks/scalar-address-bar-block/components/AddressBar.vue.script.js.map +1 -1
  36. package/dist/v2/blocks/scalar-auth-selector-block/components/AuthSelector.vue.d.ts +7 -0
  37. package/dist/v2/blocks/scalar-auth-selector-block/components/AuthSelector.vue.d.ts.map +1 -1
  38. package/dist/v2/blocks/scalar-auth-selector-block/components/AuthSelector.vue.js.map +1 -1
  39. package/dist/v2/blocks/scalar-auth-selector-block/components/AuthSelector.vue.script.js +6 -0
  40. package/dist/v2/blocks/scalar-auth-selector-block/components/AuthSelector.vue.script.js.map +1 -1
  41. package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2.vue.d.ts.map +1 -1
  42. package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2.vue.js.map +1 -1
  43. package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2.vue.script.js +5 -5
  44. package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2.vue.script.js.map +1 -1
  45. package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthDataTableInput.vue.d.ts.map +1 -1
  46. package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthDataTableInput.vue.js.map +1 -1
  47. package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthDataTableInput.vue.script.js +11 -1
  48. package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthDataTableInput.vue.script.js.map +1 -1
  49. package/dist/v2/blocks/scalar-auth-selector-block/helpers/security-scheme.d.ts.map +1 -1
  50. package/dist/v2/blocks/scalar-auth-selector-block/helpers/security-scheme.js +1 -1
  51. package/dist/v2/blocks/scalar-auth-selector-block/helpers/security-scheme.js.map +1 -1
  52. package/dist/v2/components/code-input/CodeInputLite.vue.d.ts.map +1 -1
  53. package/dist/v2/components/code-input/CodeInputLite.vue.js +1 -1
  54. package/dist/v2/components/code-input/CodeInputLite.vue.js.map +1 -1
  55. package/dist/v2/components/code-input/CodeInputLite.vue.script.js +13 -1
  56. package/dist/v2/components/code-input/CodeInputLite.vue.script.js.map +1 -1
  57. package/dist/v2/components/data-table/DataTableInput.vue.d.ts.map +1 -1
  58. package/dist/v2/components/data-table/DataTableInput.vue.js +1 -1
  59. package/dist/v2/components/data-table/DataTableInput.vue.js.map +1 -1
  60. package/dist/v2/components/data-table/DataTableInput.vue.script.js +7 -2
  61. package/dist/v2/components/data-table/DataTableInput.vue.script.js.map +1 -1
  62. package/dist/v2/components/layout/CollapsibleSection.vue.d.ts +20 -0
  63. package/dist/v2/components/layout/CollapsibleSection.vue.d.ts.map +1 -1
  64. package/dist/v2/components/layout/CollapsibleSection.vue.js.map +1 -1
  65. package/dist/v2/components/layout/CollapsibleSection.vue.script.js +36 -16
  66. package/dist/v2/components/layout/CollapsibleSection.vue.script.js.map +1 -1
  67. package/dist/v2/components/layout/collapsible-section-heading-level.d.ts +13 -0
  68. package/dist/v2/components/layout/collapsible-section-heading-level.d.ts.map +1 -0
  69. package/dist/v2/components/layout/collapsible-section-heading-level.js +14 -0
  70. package/dist/v2/components/layout/collapsible-section-heading-level.js.map +1 -0
  71. package/dist/v2/components/layout/index.d.ts +1 -0
  72. package/dist/v2/components/layout/index.d.ts.map +1 -1
  73. package/dist/v2/components/layout/index.js +2 -1
  74. package/dist/v2/components/modals/ModalClientContainer.vue.d.ts.map +1 -1
  75. package/dist/v2/components/modals/ModalClientContainer.vue.js +1 -1
  76. package/dist/v2/components/modals/ModalClientContainer.vue.js.map +1 -1
  77. package/dist/v2/components/modals/ModalClientContainer.vue.script.js +10 -1
  78. package/dist/v2/components/modals/ModalClientContainer.vue.script.js.map +1 -1
  79. package/dist/v2/components/sidebar/SidebarToggle.vue.d.ts +15 -2
  80. package/dist/v2/components/sidebar/SidebarToggle.vue.d.ts.map +1 -1
  81. package/dist/v2/components/sidebar/SidebarToggle.vue.js +3 -1
  82. package/dist/v2/components/sidebar/SidebarToggle.vue.js.map +1 -1
  83. package/dist/v2/components/sidebar/SidebarToggle.vue.script.js +5 -5
  84. package/dist/v2/components/sidebar/SidebarToggle.vue.script.js.map +1 -1
  85. package/dist/v2/constants.js +1 -1
  86. package/dist/v2/features/modal/Modal.vue.d.ts.map +1 -1
  87. package/dist/v2/features/modal/Modal.vue.js.map +1 -1
  88. package/dist/v2/features/modal/Modal.vue.script.js +2 -1
  89. package/dist/v2/features/modal/Modal.vue.script.js.map +1 -1
  90. package/dist/vue-styles.css +114 -73
  91. package/package.json +12 -12
@@ -1 +1 @@
1
- {"version":3,"file":"RequestAuthDataTableInput.vue.script.js","names":["$attrs"],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/components/RequestAuthDataTableInput.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport type { XScalarEnvironment } from '@scalar/workspace-store/schemas/extensions/document/x-scalar-environments'\nimport { useId } from 'vue'\n\nimport type { VueClassProp } from '@/types/vue'\nimport { DataTableInput } from '@/v2/components/data-table'\n\nconst {\n containerClass,\n environment,\n readOnly = false,\n required = false,\n type,\n} = defineProps<{\n containerClass?: VueClassProp\n environment: XScalarEnvironment\n readOnly?: boolean\n required?: boolean\n type?: string\n}>()\n\nconst emit = defineEmits<{\n (e: 'inputFocus'): void\n (e: 'inputBlur'): void\n (e: 'selectVariable', value: string): void\n}>()\n\nconst modelValue = defineModel<string>({ default: '', required: true })\nconst id = useId()\n</script>\n<template>\n <DataTableInput\n :id=\"id\"\n v-bind=\"$attrs\"\n v-model=\"modelValue\"\n :canAddCustomEnumValue=\"!readOnly\"\n :containerClass=\"containerClass\"\n :environment=\"environment\"\n :readOnly=\"readOnly\"\n :required=\"required\"\n :type=\"type\"\n @inputBlur=\"emit('inputBlur')\"\n @inputFocus=\"emit('inputFocus')\"\n @selectVariable=\"emit('selectVariable', $event)\">\n <template #default>\n <label :for=\"id\">\n <slot />\n </label>\n </template>\n <template #icon>\n <slot name=\"icon\" />\n </template>\n </DataTableInput>\n</template>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAqBA,MAAM,OAAO;EAMb,MAAM,aAAa,SAAmB,SAAA,YAAgC;EACtE,MAAM,KAAK,MAAM;;uBAGf,YAqBiB,MAAA,sBAAA,GArBjB,WAqBiB,EApBd,IAAI,MAAA,EAAA,EAAE,GACCA,KAAAA,QAAM;gBACL,WAAA;4EAAU,QAAA;IAClB,uBAAqB,CAAG,QAAA;IACxB,gBAAgB,QAAA;IAChB,aAAa,QAAA;IACb,UAAU,QAAA;IACV,UAAU,QAAA;IACV,MAAM,QAAA;IACN,aAAS,OAAA,OAAA,OAAA,MAAA,WAAE,KAAI,WAAA;IACf,cAAU,OAAA,OAAA,OAAA,MAAA,WAAE,KAAI,YAAA;IAChB,kBAAc,OAAA,OAAA,OAAA,MAAA,WAAE,KAAI,kBAAmB,MAAM;;IACnC,SAAO,cAGR,CAFR,mBAEQ,SAAA,EAFA,KAAK,MAAA,EAAA,EAAE,GAAA,CACb,WAAQ,KAAA,QAAA,SAAA,CAAA,GAAA,GAAA,UAAA,CAAA,CAAA;IAGD,MAAI,cACO,CAApB,WAAoB,KAAA,QAAA,MAAA,CAAA,CAAA"}
1
+ {"version":3,"file":"RequestAuthDataTableInput.vue.script.js","names":["$attrs"],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/components/RequestAuthDataTableInput.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport type { XScalarEnvironment } from '@scalar/workspace-store/schemas/extensions/document/x-scalar-environments'\nimport { useId } from 'vue'\n\nimport type { VueClassProp } from '@/types/vue'\nimport { DataTableInput } from '@/v2/components/data-table'\n\nconst {\n containerClass,\n environment,\n readOnly = false,\n required = false,\n type,\n} = defineProps<{\n containerClass?: VueClassProp\n environment: XScalarEnvironment\n readOnly?: boolean\n required?: boolean\n type?: string\n}>()\n\nconst emit = defineEmits<{\n (e: 'inputFocus'): void\n (e: 'inputBlur'): void\n (e: 'selectVariable', value: string): void\n}>()\n\nconst modelValue = defineModel<string>({ default: '', required: true })\nconst id = useId()\n/**\n * The unmasked editor is a contenteditable div, which a <label for> cannot\n * name, so the field points back at the visible label via aria-labelledby.\n * The masked native input keeps its <label for> and gets the same text.\n */\nconst labelId = `${id}-label`\n</script>\n<template>\n <DataTableInput\n :id=\"id\"\n v-bind=\"$attrs\"\n v-model=\"modelValue\"\n :aria-labelledby=\"labelId\"\n :canAddCustomEnumValue=\"!readOnly\"\n :containerClass=\"containerClass\"\n :environment=\"environment\"\n :readOnly=\"readOnly\"\n :required=\"required\"\n :type=\"type\"\n @inputBlur=\"emit('inputBlur')\"\n @inputFocus=\"emit('inputFocus')\"\n @selectVariable=\"emit('selectVariable', $event)\">\n <template #default>\n <label\n :id=\"labelId\"\n :for=\"id\">\n <slot />\n </label>\n </template>\n <template #icon>\n <slot name=\"icon\" />\n </template>\n </DataTableInput>\n</template>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAqBA,MAAM,OAAO;EAMb,MAAM,aAAa,SAAmB,SAAA,YAAgC;EACtE,MAAM,KAAK,MAAM;;;;;;EAMjB,MAAM,UAAU,GAAG,GAAG;;uBAGpB,YAwBiB,MAAA,sBAAA,GAxBjB,WAwBiB,EAvBd,IAAI,MAAA,EAAA,EAAE,GACCA,KAAAA,QAAM;gBACL,WAAA;4EAAU,QAAA;IAClB,mBAAiB;IACjB,uBAAqB,CAAG,QAAA;IACxB,gBAAgB,QAAA;IAChB,aAAa,QAAA;IACb,UAAU,QAAA;IACV,UAAU,QAAA;IACV,MAAM,QAAA;IACN,aAAS,OAAA,OAAA,OAAA,MAAA,WAAE,KAAI,WAAA;IACf,cAAU,OAAA,OAAA,OAAA,MAAA,WAAE,KAAI,YAAA;IAChB,kBAAc,OAAA,OAAA,OAAA,MAAA,WAAE,KAAI,kBAAmB,MAAM;;IACnC,SAAO,cAKR,CAJR,mBAIQ,SAAA;KAHL,IAAI;KACJ,KAAK,MAAA,EAAA;QACN,WAAQ,KAAA,QAAA,SAAA,CAAA,GAAA,GAAA,UAAA,CAAA,CAAA;IAGD,MAAI,cACO,CAApB,WAAoB,KAAA,QAAA,MAAA,CAAA,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"security-scheme.d.ts","sourceRoot":"","sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/security-scheme.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAA;AAGxE,OAAO,KAAK,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,MAAM,yCAAyC,CAAA;AAC5G,OAAO,KAAK,EACV,gBAAgB,EAChB,eAAe,EACf,yBAAyB,EACzB,oBAAoB,EACrB,MAAM,8DAA8D,CAAA;AAYrE,gEAAgE;AAChE,MAAM,MAAM,oBAAoB,GAAG;IACjC,EAAE,EAAE,MAAM,CAAA;IACV,KAAK,EAAE,MAAM,CAAA;IACb,KAAK,EAAE,yBAAyB,CAAA;IAChC,WAAW,CAAC,EAAE,OAAO,CAAA;IACrB,OAAO,CAAC,EAAE,oBAAoB,CAAA;CAC/B,CAAA;AAED,mEAAmE;AACnE,MAAM,MAAM,mBAAmB,GAAG;IAChC,KAAK,EAAE,MAAM,CAAA;IACb,OAAO,EAAE,oBAAoB,EAAE,CAAA;CAChC,CAAA;AAKD;;;;;GAKG;AACH,eAAO,MAAM,YAAY,GAAI,iBAAiB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,yBAAyB,CAAA;CAAE;;;;;CAK9F,CAAA;AAEF,uCAAuC;AACvC,eAAO,MAAM,mBAAmB,GAAI,QAAQ,WAAW,CAAC,eAAe,CAAC,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC;;;;;CAIxF,CAAA;AAuCJ;;;;;;;;GAQG;AACH,eAAO,MAAM,0BAA0B,GACrC,iBAAiB,WAAW,CAAC,gBAAgB,CAAC,iBAAiB,CAAC,CAAC,GAAG,qBAAqB,KACxF;IACD,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,EAAE,sBAAsB,CAAA;IAC7B,QAAQ,EAAE,mBAAmB,GAAG,UAAU,CAAA;IAC1C,MAAM,EAAE,MAAM,EAAE,CAAA;CACjB,GAAG,IAgCH,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,wBAAwB,GACnC,UAAU,WAAW,CAAC,eAAe,CAAC,UAAU,CAAC,CAAC,EAClD,iBAAiB,WAAW,CAAC,gBAAgB,CAAC,iBAAiB,CAAC,CAAC,GAAG,qBAAqB;AACzF,iGAAiG;AACjG,iBAAiB,yBAAyB,EAAE;AAC5C,gEAAgE;AAChE,uBAAqB,EACrB,SAAQ,IAAI,CAAC,qBAAqB,EAAE,cAAc,GAAG,aAAa,CAAM,KACvE,oBAAoB,EAAE,GAAG,mBAAmB,EAuF9C,CAAA"}
1
+ {"version":3,"file":"security-scheme.d.ts","sourceRoot":"","sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/security-scheme.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAA;AAGxE,OAAO,KAAK,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,MAAM,yCAAyC,CAAA;AAC5G,OAAO,KAAK,EACV,gBAAgB,EAChB,eAAe,EACf,yBAAyB,EACzB,oBAAoB,EACrB,MAAM,8DAA8D,CAAA;AAYrE,gEAAgE;AAChE,MAAM,MAAM,oBAAoB,GAAG;IACjC,EAAE,EAAE,MAAM,CAAA;IACV,KAAK,EAAE,MAAM,CAAA;I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, canA
109
109
  if (scheme && !isHidden(scheme)) {
110
110
  const formatted = formatScheme({
111
111
  name,
112
- value: { [name]: [] }
112
+ value: selectedByRequirement.get(requirementSignature({ [name]: [] })) ?? { [name]: scheme.type === "oauth2" ? [...scheme["x-default-scopes"] ?? []] : [] }
113
113
  });
114
114
  availableFormatted.push(formatted);
115
115
  existingIds.add(formatted.id);
@@ -1 +1 @@
1
- {"version":3,"file":"security-scheme.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/security-scheme.ts"],"sourcesContent":["import { objectEntries } from '@scalar/helpers/object/object-entries'\nimport { generateHash } from '@scalar/helpers/string/generate-hash'\nimport type { ApiClientTranslations } from '@scalar/types/api-reference'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport { isHidden } from '@scalar/workspace-store/helpers/is-hidden'\nimport type { MergedSecuritySchemes, OAuthFlowsObjectSecret } from '@scalar/workspace-store/request-example'\nimport type {\n ComponentsObject,\n OpenApiDocument,\n SecurityRequirementObject,\n SecuritySchemeObject,\n} from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\n\nimport { authOptions } from '@/v2/blocks/scalar-auth-selector-block/helpers/auth-options'\nimport { en } from '@/v2/features/localization/translations'\n\n/**\n * Minimal shape read by `isHidden`. Some scheme union members (AsyncAPI broker schemes) do not\n * structurally carry the ignore extensions, so we cast to this before the check to satisfy the\n * weak-type check without widening `isHidden` itself.\n */\ntype Hideable = { 'x-internal'?: boolean; 'x-scalar-ignore'?: boolean }\n\n/** A single security scheme option used in the auth dropdown */\nexport type SecuritySchemeOption = {\n id: string\n label: string\n value: SecurityRequirementObject\n isDeletable?: boolean\n payload?: SecuritySchemeObject\n}\n\n/** A group of security scheme options used in the auth dropdown */\nexport type SecuritySchemeGroup = {\n label: string\n options: SecuritySchemeOption[]\n}\n\nconst requirementSignature = (requirement: SecurityRequirementObject): string =>\n JSON.stringify(Object.keys(requirement))\n\n/**\n * Format a scheme object into a display object\n *\n * We also add a hash to the id to ensure it is unique across\n * multiple requirements of the same scheme with different scopes\n */\nexport const formatScheme = ({ name, value }: { name: string; value: SecurityRequirementObject }) => ({\n id: generateHash(JSON.stringify(value)),\n label: name,\n value,\n isDeletable: true,\n})\n\n/** Formats complex security schemes */\nexport const formatComplexScheme = (scheme: NonNullable<OpenApiDocument['security']>[number]) =>\n formatScheme({\n name: Object.keys(scheme).join(' & '),\n value: scheme,\n })\n\n/**\n * Formats a security requirement into a SecuritySchemeOption.\n * Handles both simple (single key) and complex (multiple keys) auth schemes.\n */\nconst formatSecurityRequirement = (\n requirement: SecurityRequirementObject,\n securitySchemes: NonNullable<ComponentsObject['securitySchemes']> | MergedSecuritySchemes,\n): SecuritySchemeOption | undefined => {\n const keys = Object.keys(requirement)\n\n // Complex auth (multiple keys)\n if (keys.length > 1) {\n // Drop the whole AND combination if any of its schemes is hidden via x-scalar-ignore — a\n // partly hidden requirement cannot be configured, so it should not appear as an option.\n const anyHidden = keys.some((key) => {\n const scheme = getResolvedRef(securitySchemes[key])\n return scheme ? isHidden(scheme as Hideable) : false\n })\n if (anyHidden) {\n return undefined\n }\n return formatComplexScheme(requirement)\n }\n\n // Simple auth (single key)\n if (keys[0]) {\n const scheme = getResolvedRef(securitySchemes[keys[0]])\n // Drop schemes that do not exist or are hidden from the auth UI via x-scalar-ignore.\n if (!scheme || isHidden(scheme as Hideable)) {\n return undefined\n }\n return formatScheme({ name: keys[0], value: requirement })\n }\n\n return undefined\n}\n\n/**\n * Finds the oauth2 scheme best suited to power a bearer scheme's \"Authorize via OAuth2\" shortcut:\n * the first scheme with an interactive grant (authorization code / implicit), the kind that sends\n * a user to an IdP login. Prefers the authorization-code grant (which can refresh) over one\n * offering only implicit, so the more capable flow wins even when it is declared later.\n *\n * This only surfaces a convenience shortcut on the bearer form — it never hides the oauth2 scheme,\n * which stays independently selectable in the auth dropdown.\n */\nexport const getOauth2AcquisitionTarget = (\n securitySchemes: NonNullable<ComponentsObject['securitySchemes']> | MergedSecuritySchemes,\n): {\n name: string\n flows: OAuthFlowsObjectSecret\n flowType: 'authorizationCode' | 'implicit'\n scopes: string[]\n} | null => {\n let implicitFallback: {\n name: string\n flows: OAuthFlowsObjectSecret\n flowType: 'implicit'\n scopes: string[]\n } | null = null\n\n for (const [name, schemeRef] of Object.entries(securitySchemes)) {\n const scheme = getResolvedRef(schemeRef)\n // Skip schemes hidden from the auth UI via x-scalar-ignore, so the shortcut never\n // targets a flow the user cannot see or configure.\n if (scheme?.type !== 'oauth2' || isHidden(scheme)) {\n continue\n }\n const flows = scheme.flows as OAuthFlowsObjectSecret | undefined\n if (!flows) {\n continue\n }\n const scopes = (scheme as { 'x-default-scopes'?: string[] })['x-default-scopes'] ?? []\n\n // Authorization code can refresh, so it wins outright the moment we find one.\n if (flows.authorizationCode && !isHidden(flows.authorizationCode)) {\n return { name, flows, flowType: 'authorizationCode', scopes }\n }\n // Otherwise remember the first implicit-only scheme in case no auth-code flow turns up.\n if (flows.implicit && !isHidden(flows.implicit) && !implicitFallback) {\n implicitFallback = { name, flows, flowType: 'implicit', scopes }\n }\n }\n\n return implicitFallback\n}\n\n/**\n * Generates the options for the security scheme combobox\n *\n * Contains either a flat list, or different groups of required, available, and add new\n */\nexport const getSecuritySchemeOptions = (\n security: NonNullable<OpenApiDocument['security']>,\n securitySchemes: NonNullable<ComponentsObject['securitySchemes']> | MergedSecuritySchemes,\n /** We need to add the selected schemes if they do not already exist in the calculated options */\n selectedSchemes: SecurityRequirementObject[],\n /** Allows adding authentication which is not in the document */\n canAddNewAuth = false,\n labels: Pick<ApiClientTranslations, 'authSelector' | 'authOptions'> = en,\n): SecuritySchemeOption[] | SecuritySchemeGroup[] => {\n const selectedByRequirement = new Map(\n selectedSchemes.map((selectedScheme) => [requirementSignature(selectedScheme), selectedScheme]),\n )\n\n /**\n * Build required schemes formatted as options and track scheme names in a single pass.\n * We use names (not full IDs) because we want to exclude any scheme that is already\n * required, regardless of its specific scopes or hash.\n */\n const { requiredFormatted, requiredSchemeNames, existingIds } = security.reduce<{\n requiredFormatted: SecuritySchemeOption[]\n requiredSchemeNames: Set<string>\n existingIds: Set<string>\n }>(\n (acc, requirement) => {\n // If a required requirement is selected with scopes, use that selected value to\n // keep a single option entry and avoid a phantom duplicate.\n const requirementValue = selectedByRequirement.get(requirementSignature(requirement)) ?? requirement\n const formatted = formatSecurityRequirement(requirementValue, securitySchemes)\n if (formatted) {\n acc.requiredFormatted.push(formatted)\n acc.existingIds.add(formatted.id)\n }\n for (const name of Object.keys(requirement)) {\n acc.requiredSchemeNames.add(name)\n }\n return acc\n },\n {\n requiredFormatted: [],\n requiredSchemeNames: new Set<string>(),\n existingIds: new Set<string>(),\n },\n )\n\n // Build available schemes (excluding schemes that are in the required list)\n const availableFormatted: SecuritySchemeOption[] = []\n for (const [name, schemeRef] of Object.entries(securitySchemes)) {\n if (requiredSchemeNames.has(name)) {\n continue\n }\n\n const scheme = getResolvedRef(schemeRef)\n // Skip schemes hidden from the auth UI via x-scalar-ignore.\n if (scheme && !isHidden(scheme as Hideable)) {\n const formatted = formatScheme({ name, value: { [name]: [] } })\n availableFormatted.push(formatted)\n existingIds.add(formatted.id)\n }\n }\n\n /**\n * Add selected schemes to available if they do not already exist\n * This ensures that selected schemes with specific scopes are always available as options\n */\n for (const selectedScheme of selectedSchemes) {\n const formatted = formatSecurityRequirement(selectedScheme, securitySchemes)\n if (formatted && !existingIds.has(formatted.id)) {\n availableFormatted.push(formatted)\n existingIds.add(formatted.id)\n }\n }\n\n const options = [\n { label: labels.authSelector.requiredGroup, options: requiredFormatted },\n { label: labels.authSelector.availableGroup, options: availableFormatted },\n ]\n\n // We don't return the groups if we don't have any required schemes\n if (!canAddNewAuth) {\n return requiredFormatted.length ? options : availableFormatted\n }\n\n // Add new authentication options (unless explicitly hidden)\n options.push({\n label: labels.authSelector.addGroup,\n options: objectEntries(authOptions).map(([key, value]) => ({\n id: key,\n label: labels.authOptions[key],\n value: { [key]: [] },\n payload: value.payload,\n isDeletable: false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9B;CACF;CAEA,MAAM,UAAU,CACd;EAAE,OAAO,OAAO,aAAa;EAAe,SAAS;CAAkB,GACvE;EAAE,OAAO,OAAO,aAAa;EAAgB,SAAS;CAAmB,CAC3E;CAGA,IAAI,CAAC,eACH,OAAO,kBAAkB,SAAS,UAAU;CAI9C,QAAQ,KAAK;EACX,OAAO,OAAO,aAAa;EAC3B,SAAS,cAAc,WAAW,CAAC,CAAC,KAAK,CAAC,KAAK,YAAY;GACzD,IAAI;GACJ,OAAO,OAAO,YAAY;GAC1B,OAAO,GAAG,MAAM,CAAC,EAAE;GACnB,SAAS,MAAM;GACf,aAAa;EACf,EAAE;CACJ,CAAC;CAED,OAAO;AACT"}
1
+ {"version":3,"file":"security-scheme.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/security-scheme.ts"],"sourcesContent":["import { objectEntries } from '@scalar/helpers/object/object-entries'\nimport { generateHash } from '@scalar/helpers/string/generate-hash'\nimport type { ApiClientTranslations } from '@scalar/types/api-reference'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport { isHidden } from '@scalar/workspace-store/helpers/is-hidden'\nimport type { MergedSecuritySchemes, OAuthFlowsObjectSecret } from '@scalar/workspace-store/request-example'\nimport type {\n ComponentsObject,\n OpenApiDocument,\n SecurityRequirementObject,\n SecuritySchemeObject,\n} from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\n\nimport { authOptions } from '@/v2/blocks/scalar-auth-selector-block/helpers/auth-options'\nimport { en } from '@/v2/features/localization/translations'\n\n/**\n * Minimal shape read by `isHidden`. Some scheme union members (AsyncAPI broker schemes) do not\n * structurally carry the ignore extensions, so we cast to this before the check to satisfy the\n * weak-type check without widening `isHidden` itself.\n */\ntype Hideable = { 'x-internal'?: boolean; 'x-scalar-ignore'?: boolean }\n\n/** A single security scheme option used in the auth dropdown */\nexport type SecuritySchemeOption = {\n id: string\n label: string\n value: SecurityRequirementObject\n isDeletable?: boolean\n payload?: SecuritySchemeObject\n}\n\n/** A group of security scheme options used in the auth dropdown */\nexport type SecuritySchemeGroup = {\n label: string\n options: SecuritySchemeOption[]\n}\n\nconst requirementSignature = (requirement: SecurityRequirementObject): string =>\n JSON.stringify(Object.keys(requirement))\n\n/**\n * Format a scheme object into a display object\n *\n * We also add a hash to the id to ensure it is unique across\n * multiple requirements of the same scheme with different scopes\n */\nexport const formatScheme = ({ name, value }: { name: string; value: SecurityRequirementObject }) => ({\n id: generateHash(JSON.stringify(value)),\n label: name,\n value,\n isDeletable: true,\n})\n\n/** Formats complex security schemes */\nexport const formatComplexScheme = (scheme: NonNullable<OpenApiDocument['security']>[number]) =>\n formatScheme({\n name: Object.keys(scheme).join(' & '),\n value: scheme,\n })\n\n/**\n * Formats a security requirement into a SecuritySchemeOption.\n * Handles both simple (single key) and complex (multiple keys) auth schemes.\n */\nconst formatSecurityRequirement = (\n requirement: SecurityRequirementObject,\n securitySchemes: NonNullable<ComponentsObject['securitySchemes']> | MergedSecuritySchemes,\n): SecuritySchemeOption | undefined => {\n const keys = Object.keys(requirement)\n\n // Complex auth (multiple keys)\n if (keys.length > 1) {\n // Drop the whole AND combination if any of its schemes is hidden via x-scalar-ignore — a\n // partly hidden requirement cannot be configured, so it should not appear as an option.\n const anyHidden = keys.some((key) => {\n const scheme = getResolvedRef(securitySchemes[key])\n return scheme ? isHidden(scheme as Hideable) : false\n })\n if (anyHidden) {\n return undefined\n }\n return formatComplexScheme(requirement)\n }\n\n // Simple auth (single key)\n if (keys[0]) {\n const scheme = getResolvedRef(securitySchemes[keys[0]])\n // Drop schemes that do not exist or are hidden from the auth UI via x-scalar-ignore.\n if (!scheme || isHidden(scheme as Hideable)) {\n return undefined\n }\n return formatScheme({ name: keys[0], value: requirement })\n }\n\n return undefined\n}\n\n/**\n * Finds the oauth2 scheme best suited to power a bearer scheme's \"Authorize via OAuth2\" shortcut:\n * the first scheme with an interactive grant (authorization code / implicit), the kind that sends\n * a user to an IdP login. Prefers the authorization-code grant (which can refresh) over one\n * offering only implicit, so the more capable flow wins even when it is declared later.\n *\n * This only surfaces a convenience shortcut on the bearer form — it never hides the oauth2 scheme,\n * which stays independently selectable in the auth dropdown.\n */\nexport const getOauth2AcquisitionTarget = (\n securitySchemes: NonNullable<ComponentsObject['securitySchemes']> | MergedSecuritySchemes,\n): {\n name: string\n flows: OAuthFlowsObjectSecret\n flowType: 'authorizationCode' | 'implicit'\n scopes: string[]\n} | null => {\n let implicitFallback: {\n name: string\n flows: OAuthFlowsObjectSecret\n flowType: 'implicit'\n scopes: string[]\n } | null = null\n\n for (const [name, schemeRef] of Object.entries(securitySchemes)) {\n const scheme = getResolvedRef(schemeRef)\n // Skip schemes hidden from the auth UI via x-scalar-ignore, so the shortcut never\n // targets a flow the user cannot see or configure.\n if (scheme?.type !== 'oauth2' || isHidden(scheme)) {\n continue\n }\n const flows = scheme.flows as OAuthFlowsObjectSecret | undefined\n if (!flows) {\n continue\n }\n const scopes = (scheme as { 'x-default-scopes'?: string[] })['x-default-scopes'] ?? []\n\n // Authorization code can refresh, so it wins outright the moment we find one.\n if (flows.authorizationCode && !isHidden(flows.authorizationCode)) {\n return { name, flows, flowType: 'authorizationCode', scopes }\n }\n // Otherwise remember the first implicit-only scheme in case no auth-code flow turns up.\n if (flows.implicit && !isHidden(flows.implicit) && !implicitFallback) {\n implicitFallback = { name, flows, flowType: 'implicit', scopes }\n }\n }\n\n return implicitFallback\n}\n\n/**\n * Generates the options for the security scheme combobox\n *\n * Contains either a flat list, or different groups of required, available, and add new\n */\nexport const getSecuritySchemeOptions = (\n security: NonNullable<OpenApiDocument['security']>,\n securitySchemes: NonNullable<ComponentsObject['securitySchemes']> | MergedSecuritySchemes,\n /** We need to add the selected schemes if they do not already exist in the calculated options */\n selectedSchemes: SecurityRequirementObject[],\n /** Allows adding authentication which is not in the document */\n canAddNewAuth = false,\n labels: Pick<ApiClientTranslations, 'authSelector' | 'authOptions'> = en,\n): SecuritySchemeOption[] | SecuritySchemeGroup[] => {\n const selectedByRequirement = new Map(\n selectedSchemes.map((selectedScheme) => [requirementSignature(selectedScheme), selectedScheme]),\n )\n\n /**\n * Build required schemes formatted as options and track scheme names in a single pass.\n * We use names (not full IDs) because we want to exclude any scheme that is already\n * required, regardless of its specific scopes or hash.\n */\n const { requiredFormatted, requiredSchemeNames, existingIds } = security.reduce<{\n requiredFormatted: SecuritySchemeOption[]\n requiredSchemeNames: Set<string>\n existingIds: Set<string>\n }>(\n (acc, requirement) => {\n // If a required requirement is selected with scopes, use that selected value to\n // keep a single option entry and avoid a phantom duplicate.\n const requirementValue = selectedByRequirement.get(requirementSignature(requirement)) ?? requirement\n const formatted = formatSecurityRequirement(requirementValue, securitySchemes)\n if (formatted) {\n acc.requiredFormatted.push(formatted)\n acc.existingIds.add(formatted.id)\n }\n for (const name of Object.keys(requirement)) {\n acc.requiredSchemeNames.add(name)\n }\n return acc\n },\n {\n requiredFormatted: [],\n requiredSchemeNames: new Set<string>(),\n existingIds: new Set<string>(),\n },\n )\n\n // Build available schemes (excluding schemes that are in the required list)\n const availableFormatted: SecuritySchemeOption[] = []\n for (const [name, schemeRef] of Object.entries(securitySchemes)) {\n if (requiredSchemeNames.has(name)) {\n continue\n }\n\n const scheme = getResolvedRef(schemeRef)\n // Skip schemes hidden from the auth UI via x-scalar-ignore.\n if (scheme && !isHidden(scheme as Hideable)) {\n // Reuse the current selection so changing scopes does not create a second option.\n // Defaults seed a new selection, but must not replace scopes the user deliberately cleared.\n const value = selectedByRequirement.get(requirementSignature({ [name]: [] })) ?? {\n [name]: scheme.type === 'oauth2' ? [...(scheme['x-default-scopes'] ?? [])] : [],\n }\n const formatted = formatScheme({ name, value })\n availableFormatted.push(formatted)\n existingIds.add(formatted.id)\n }\n }\n\n /**\n * Add selected schemes to available if they do not already exist\n * This ensures that selected schemes with specific scopes are always available as options\n */\n for (const selectedScheme of selectedSchemes) {\n const formatted = formatSecurityRequirement(selectedScheme, securitySchemes)\n if (formatted && !existingIds.has(formatted.id)) {\n availableFormatted.push(formatted)\n existingIds.add(formatted.id)\n }\n }\n\n const options = [\n { label: labels.authSelector.requiredGroup, options: requiredFormatted },\n { label: labels.authSelector.availableGroup, options: availableFormatted },\n ]\n\n // We don't return the groups if we don't have any required schemes\n if (!canAddNewAuth) {\n return requiredFormatted.length ? options : availableFormatted\n }\n\n // Add new authentication options (unless explicitly hidden)\n options.push({\n label: labels.authSelector.addGroup,\n options: objectEntries(authOptions).map(([key, value]) => ({\n id: key,\n label: labels.authOptions[key],\n value: { [key]: [] },\n payload: value.payload,\n isDeletable: false,\n })),\n })\n\n return options\n}\n"],"mappings":";;;;;;;AAsCA,IAAM,wBAAwB,gBAC5B,KAAK,UAAU,OAAO,KAAK,WAAW,CAAC;;;;;;;AAQzC,IAAa,gBAAgB,EAAE,MAAM,aAAiE;CACpG,IAAI,aAAa,KAAK,UAAU,KAAK,CAAC;CACtC,OAAO;CACP;CACA,aAAa;AACf;;AAGA,IAAa,uBAAuB,WAClC,aAAa;CACX,MAAM,OAAO,KAAK,MAAM,CAAC,CAAC,KAAK,KAAK;CACpC,OAAO;AACT,CAAC;;;;;AAMH,IAAM,6BACJ,aACA,oBACqC;CACrC,MAAM,OAAO,OAAO,KAAK,WAAW;CAGpC,IAAI,KAAK,SAAS,GAAG;EAOnB,IAJkB,KAAK,MAAM,QAAQ;GACnC,MAAM,SAAS,eAAe,gBAAgB,IAAI;GAClD,OAAO,SAAS,SAAS,MAAkB,IAAI;EACjD,CACI,GACF;EAEF,OAAO,oBAAoB,WAAW;CACxC;CAGA,IAAI,KAAK,IAAI;EACX,MAAM,SAAS,eAAe,gBAAgB,KAAK,GAAG;EAEtD,IAAI,CAAC,UAAU,SAAS,MAAkB,GACxC;EAEF,OAAO,aAAa;GAAE,MAAM,KAAK;GAAI,OAAO;EAAY,CAAC;CAC3D;AAGF;;;;;;;;;;AAWA,IAAa,8BACX,oBAMU;CACV,IAAI,mBAKO;CAEX,KAAK,MAAM,CAAC,MAAM,cAAc,OAAO,QAAQ,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f,uFAAuF;eAC5E,MAAM,EAAE;IACnB,+CAA+C;cACrC,mBAAmB;IAC7B,0DAA0D;eAC/C,OAAO;;;;cAzCU,UAAU;cAAQ,aAAa;;;;;cAmlC/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"}
1
+ {"version":3,"file":"CodeInputLite.vue.d.ts","sourceRoot":"","sources":["../../../../src/v2/components/code-input/CodeInputLite.vue"],"names":[],"mappings":"AAgmCA,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;gBAmCJ,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,MAAM,EAAE;IACf,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;;;;;;cAzyBV,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,MAAM,EAAE;IACf,uFAAuF;eAC5E,MAAM,EAAE;IACnB,+CAA+C;cACrC,mBAAmB;IAC7B,0DAA0D;eAC/C,OAAO;;;;cAzCU,UAAU;cAAQ,aAAa;;;;;cAwmC/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-9bca2f92"]]);
6
+ var CodeInputLite_default = /*#__PURE__*/ _plugin_vue_export_helper_default(CodeInputLite_vue_vue_type_script_setup_true_lang_default, [["__scopeId", "data-v-360ebc3c"]]);
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\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=\"$attrs\"\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-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 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":""}
@@ -21,6 +21,7 @@ var _hoisted_3 = [
21
21
  "aria-expanded",
22
22
  "aria-invalid",
23
23
  "aria-label",
24
+ "aria-labelledby",
24
25
  "aria-readonly",
25
26
  "aria-required",
26
27
  "contenteditable",
@@ -115,6 +116,16 @@ var CodeInputLite_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ de
115
116
  const { translate } = useLocalization();
116
117
  const attrs = useAttrs();
117
118
  const ariaLabel = computed(() => typeof attrs["aria-label"] === "string" ? attrs["aria-label"] : void 0);
119
+ /** Lifted to the editable surface like aria-label, so a visible label can name it */
120
+ const ariaLabelledby = computed(() => typeof attrs["aria-labelledby"] === "string" ? attrs["aria-labelledby"] : void 0);
121
+ /**
122
+ * The wrapper is a generic div, and ARIA prohibits naming a generic element,
123
+ * so the naming attributes only go on the editor and not on the wrapper.
124
+ */
125
+ const wrapperAttrs = computed(() => {
126
+ const { "aria-label": _ariaLabel, "aria-labelledby": _ariaLabelledby, ...rest } = attrs;
127
+ return rest;
128
+ });
118
129
  /**
119
130
  * The id only matters once the dropdown opens (`aria-controls` /
120
131
  * `aria-activedescendant`), so we defer `nanoid()` until first focus to
@@ -581,7 +592,7 @@ var CodeInputLite_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ de
581
592
  ])) : (openBlock(), createElementBlock("div", mergeProps({
582
593
  key: 4,
583
594
  id: componentId.value
584
- }, _ctx.$attrs, { 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", {
595
+ }, wrapperAttrs.value, { 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", {
585
596
  "code-input-lite--error": __props.error,
586
597
  "code-input-lite--empty": isEmpty.value,
587
598
  "line-through": __props.linethrough
@@ -594,6 +605,7 @@ var CodeInputLite_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ de
594
605
  "aria-expanded": displayVariablesDropdown.value ? "true" : void 0,
595
606
  "aria-invalid": __props.error ? "true" : void 0,
596
607
  "aria-label": ariaLabel.value,
608
+ "aria-labelledby": ariaLabelledby.value,
597
609
  "aria-readonly": __props.readOnly ? "true" : void 0,
598
610
  "aria-required": __props.required ? "true" : void 0,
599
611
  class: "code-input-lite__editor",