@geektr.cloud/acrux-ui 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,13 +10,18 @@ pnpm add @geektr.cloud/acrux-ui
10
10
 
11
11
  ```ts
12
12
  import { PageEntry } from "@geektr.cloud/acrux-ui/page";
13
+ import { CodeBlock, registerCodeLanguage } from "@geektr.cloud/acrux-ui/display";
13
14
  import { Button } from "@geektr.cloud/acrux-ui/ui/button";
15
+
16
+ registerCodeLanguage("python", () => import("shiki/langs/python.mjs"), ["py"]);
14
17
  ```
15
18
 
19
+ `CodeBlock` 默认纯文本;`language` 启用懒加载高亮,`maxHighlightLength` 控制高亮输入阈值。
20
+
16
21
  也可以通过 shadcn-vue registry 安装可编辑源码;registry namespace 仍为 `@acrux`,与 npm scope 不同:
17
22
 
18
23
  ```sh
19
- npx shadcn-vue add @acrux/page
24
+ pnpx shadcn-vue add @acrux/page
20
25
  ```
21
26
 
22
27
  完整说明见 [registry 文档](https://acrux.geektr.cloud/packages/registry)与[仓库](https://github.com/geektr-cloud/acrux)。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geektr.cloud/acrux-ui",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "description": "有明确主张的 Vue 应用组件层与 shadcn 基础原语,同时提供源码包入口与 shadcn-vue registry。",
6
6
  "license": "MIT",
@@ -43,7 +43,8 @@
43
43
  "date-fns": "^4.4.0",
44
44
  "qrcode": "^1.5.4",
45
45
  "reka-ui": "^2.12.0",
46
- "@geektr.cloud/acrux-core": "0.1.1"
46
+ "shiki": "^4.6.0",
47
+ "@geektr.cloud/acrux-core": "0.2.0"
47
48
  },
48
49
  "devDependencies": {
49
50
  "@vitejs/plugin-vue": "^6.0.11",
@@ -56,7 +57,7 @@
56
57
  "vue-final-modal": "^5.0.1",
57
58
  "vue-router": "^5.5.3",
58
59
  "vue-tsc": "3.3.13",
59
- "@geektr.cloud/acrux-eslint-config": "0.1.1"
60
+ "@geektr.cloud/acrux-eslint-config": "0.2.0"
60
61
  },
61
62
  "peerDependencies": {
62
63
  "vue": "^3.5.46",
@@ -0,0 +1,71 @@
1
+ <script setup lang="ts">
2
+ import type { HTMLAttributes } from "vue";
3
+ import { Download } from "@lucide/vue";
4
+ import { cn } from "cn";
5
+ import { Button } from "../../ui/button";
6
+ import Icon from "./Icon.vue";
7
+ import IconBtn from "./IconBtn.vue";
8
+
9
+ defineOptions({ name: "DownloadBtn", inheritAttrs: false });
10
+
11
+ const props = withDefaults(
12
+ defineProps<{
13
+ value: string;
14
+ filename: string;
15
+ label?: string;
16
+ mimeType?: string;
17
+ showFilename?: boolean;
18
+ disabled?: boolean;
19
+ class?: HTMLAttributes["class"];
20
+ }>(),
21
+ {
22
+ label: "下载",
23
+ mimeType: "text/plain;charset=utf-8",
24
+ showFilename: false,
25
+ disabled: false,
26
+ class: undefined,
27
+ },
28
+ );
29
+
30
+ function onDownload() {
31
+ if (props.disabled || !props.value || !props.filename) return;
32
+ const url = URL.createObjectURL(new Blob([props.value], { type: props.mimeType }));
33
+ const anchor = document.createElement("a");
34
+ anchor.href = url;
35
+ anchor.download = props.filename;
36
+ anchor.hidden = true;
37
+ document.body.appendChild(anchor);
38
+ anchor.click();
39
+ anchor.remove();
40
+ window.setTimeout(() => URL.revokeObjectURL(url), 0);
41
+ }
42
+ </script>
43
+
44
+ <template>
45
+ <span data-slot="download-btn" :class="cn('inline-flex items-center gap-1', props.class)">
46
+ <IconBtn
47
+ v-if="!showFilename"
48
+ v-bind="$attrs"
49
+ :icon="Download"
50
+ :aria-label="label"
51
+ :disabled="disabled || !value || !filename"
52
+ size="icon-xs"
53
+ class="shrink-0"
54
+ @click="onDownload"
55
+ />
56
+ <Button
57
+ v-else
58
+ v-bind="$attrs"
59
+ type="button"
60
+ variant="ghost"
61
+ size="xs"
62
+ class="font-normal"
63
+ :aria-label="label"
64
+ :disabled="disabled || !value || !filename"
65
+ @click="onDownload"
66
+ >
67
+ <Icon :icon="Download" size="xs" aria-hidden="true" />
68
+ <span class="text-xs">{{ filename }}</span>
69
+ </Button>
70
+ </span>
71
+ </template>
@@ -1,5 +1,6 @@
1
1
  export { createAsyncLoaderRetry } from "./async";
2
2
  export { default as CopyBtn } from "./CopyBtn.vue";
3
+ export { default as DownloadBtn } from "./DownloadBtn.vue";
3
4
  export { default as EmptyValue } from "./EmptyValue.vue";
4
5
  export { default as Icon } from "./Icon.vue";
5
6
  export { default as IconBtn } from "./IconBtn.vue";
@@ -0,0 +1,49 @@
1
+ <!-- eslint-disable vue/multi-word-component-names -->
2
+ <script setup lang="ts">
3
+ import { useId, type HTMLAttributes } from "vue";
4
+ import { cn } from "cn";
5
+ import { Card as ShadcnCard, CardContent, CardHeader } from "../../ui/card";
6
+ import { Text } from "../base";
7
+
8
+ defineOptions({ name: "Card", inheritAttrs: false });
9
+
10
+ const props = withDefaults(
11
+ defineProps<{
12
+ title?: string;
13
+ description?: string;
14
+ class?: HTMLAttributes["class"];
15
+ }>(),
16
+ {
17
+ title: undefined,
18
+ description: undefined,
19
+ class: undefined,
20
+ },
21
+ );
22
+
23
+ const titleId = `${useId()}-card-title`;
24
+ </script>
25
+
26
+ <template>
27
+ <ShadcnCard
28
+ v-bind="$attrs"
29
+ as="article"
30
+ size="sm"
31
+ :aria-labelledby="title || $slots.title ? titleId : undefined"
32
+ :class="cn('min-w-0', props.class)"
33
+ >
34
+ <CardHeader v-if="title || description || $slots.title || $slots.description || $slots.actions">
35
+ <Text v-if="title || $slots.title" :id="titleId" variant="section">
36
+ <slot name="title">{{ title }}</slot>
37
+ </Text>
38
+ <Text v-if="description || $slots.description" variant="muted">
39
+ <slot name="description">{{ description }}</slot>
40
+ </Text>
41
+ <div v-if="$slots.actions" data-slot="card-action" class="row-span-2 self-center">
42
+ <slot name="actions" />
43
+ </div>
44
+ </CardHeader>
45
+ <CardContent class="flex flex-col gap-4">
46
+ <slot />
47
+ </CardContent>
48
+ </ShadcnCard>
49
+ </template>
@@ -1,35 +1,48 @@
1
1
  <script setup lang="ts">
2
2
  import type { HTMLAttributes } from "vue";
3
3
  import { computed, ref, useId } from "vue";
4
- import { cn } from "cn";
5
4
  import { ChevronDown, ChevronRight } from "@lucide/vue";
6
- import { CopyBtn, EmptyValue, IconBtn } from "../base";
5
+ import { cn } from "cn";
6
+ import { CopyBtn, DownloadBtn, EmptyValue, IconBtn } from "../base";
7
+ import { useHighlightedCode } from "./useHighlightedCode";
7
8
 
8
9
  defineOptions({ name: "CodeBlock", inheritAttrs: false });
9
10
 
10
11
  const props = withDefaults(
11
12
  defineProps<{
12
13
  value?: string | null;
14
+ language?: string;
13
15
  label?: string;
14
16
  copy?: boolean;
17
+ download?: boolean;
18
+ downloadFilename?: string;
19
+ downloadShowFilename?: boolean;
15
20
  collapsible?: boolean;
16
21
  defaultExpanded?: boolean;
17
22
  wrap?: boolean;
18
23
  maxHeight?: string;
24
+ maxHighlightLength?: number;
19
25
  copyLabel?: string;
26
+ downloadLabel?: string;
20
27
  expandLabel?: string;
21
28
  collapseLabel?: string;
22
29
  class?: HTMLAttributes["class"];
23
30
  }>(),
24
31
  {
25
32
  value: undefined,
33
+ language: undefined,
26
34
  label: undefined,
27
35
  copy: true,
36
+ download: false,
37
+ downloadFilename: "code.txt",
38
+ downloadShowFilename: false,
28
39
  collapsible: false,
29
40
  defaultExpanded: false,
30
41
  wrap: true,
31
42
  maxHeight: "12rem",
43
+ maxHighlightLength: 262_144,
32
44
  copyLabel: undefined,
45
+ downloadLabel: undefined,
33
46
  expandLabel: undefined,
34
47
  collapseLabel: undefined,
35
48
  class: undefined,
@@ -38,10 +51,23 @@ const props = withDefaults(
38
51
 
39
52
  const contentId = useId();
40
53
  const expanded = ref(props.defaultExpanded);
54
+ const highlightedLines = useHighlightedCode(
55
+ () => props.value ?? "",
56
+ () => props.language,
57
+ () => props.maxHighlightLength,
58
+ );
41
59
 
42
60
  const open = computed(() => !props.collapsible || expanded.value);
43
61
  const hasValue = computed(() => Boolean(props.value));
44
- const overlayCopy = computed(() => !props.collapsible && !props.label && props.copy && hasValue.value);
62
+ const hasFilenameDownload = computed(() => props.download && props.downloadShowFilename);
63
+ const overlayActions = computed(
64
+ () =>
65
+ !props.collapsible &&
66
+ !props.label &&
67
+ (props.copy || props.download) &&
68
+ hasValue.value &&
69
+ !hasFilenameDownload.value,
70
+ );
45
71
 
46
72
  const toggleLabel = computed(() => {
47
73
  const action = expanded.value ? "收起" : "展开";
@@ -50,11 +76,17 @@ const toggleLabel = computed(() => {
50
76
  });
51
77
 
52
78
  const copyAccessibleLabel = computed(() => props.copyLabel ?? (props.label ? `复制 ${props.label}` : "复制代码"));
79
+ const downloadAccessibleLabel = computed(
80
+ () => props.downloadLabel ?? (props.label ? `下载 ${props.label}` : "下载代码"),
81
+ );
53
82
  </script>
54
83
 
55
84
  <template>
56
85
  <div v-bind="$attrs" data-slot="code-block" :class="cn('relative flex min-w-0 flex-col gap-1 text-xs', props.class)">
57
- <div v-if="!overlayCopy && (collapsible || label || (copy && hasValue))" class="flex min-w-0 items-center gap-1">
86
+ <div
87
+ v-if="!overlayActions && (collapsible || label || ((copy || download) && hasValue))"
88
+ class="flex min-w-0 items-center gap-1"
89
+ >
58
90
  <IconBtn
59
91
  v-if="collapsible"
60
92
  :icon="expanded ? ChevronDown : ChevronRight"
@@ -66,26 +98,51 @@ const copyAccessibleLabel = computed(() => props.copyLabel ?? (props.label ? `
66
98
  @click="expanded = !expanded"
67
99
  />
68
100
  <span v-if="label" class="min-w-0 truncate text-muted-foreground">{{ label }}</span>
69
- <CopyBtn v-if="copy && hasValue" :value="value ?? ''" :label="copyAccessibleLabel" class="ml-auto shrink-0" />
101
+ <span v-if="(copy || download) && hasValue" class="ml-auto flex shrink-0 items-center gap-1">
102
+ <CopyBtn v-if="copy" :value="value ?? ''" :label="copyAccessibleLabel" />
103
+ <DownloadBtn
104
+ v-if="download"
105
+ :value="value ?? ''"
106
+ :filename="downloadFilename"
107
+ :label="downloadAccessibleLabel"
108
+ :show-filename="downloadShowFilename"
109
+ />
110
+ </span>
111
+ </div>
112
+ <div v-if="overlayActions" class="absolute top-1 right-1 z-10 flex items-center gap-1 bg-muted">
113
+ <CopyBtn v-if="copy" :value="value ?? ''" :label="copyAccessibleLabel" />
114
+ <DownloadBtn
115
+ v-if="download"
116
+ :value="value ?? ''"
117
+ :filename="downloadFilename"
118
+ :label="downloadAccessibleLabel"
119
+ :show-filename="downloadShowFilename"
120
+ />
70
121
  </div>
71
- <CopyBtn
72
- v-if="overlayCopy"
73
- :value="value ?? ''"
74
- :label="copyAccessibleLabel"
75
- class="absolute top-1 right-1 z-10 bg-muted"
76
- />
77
122
  <pre
78
123
  v-if="open && hasValue"
79
124
  :id="contentId"
125
+ dir="ltr"
80
126
  tabindex="0"
81
127
  :style="{ maxHeight }"
82
128
  :class="
83
129
  cn(
84
130
  'overflow-auto border border-border bg-muted p-2 text-xs focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none',
85
- overlayCopy && 'pr-10',
131
+ overlayActions && (copy && download ? 'pr-16' : 'pr-10'),
86
132
  )
87
133
  "
88
- ><code :class="wrap ? 'whitespace-pre-wrap break-all' : 'whitespace-pre'">{{ value }}</code></pre>
134
+ ><code
135
+ :class="cn(wrap ? 'whitespace-pre-wrap break-all' : 'whitespace-pre', language && `language-${language}`)"
136
+ ><template v-if="language"><span
137
+ v-for="(line, lineIndex) in highlightedLines"
138
+ :key="lineIndex"
139
+ class="block min-h-lh"
140
+ ><span
141
+ v-for="(token, tokenIndex) in line"
142
+ :key="tokenIndex"
143
+ :style="token.htmlStyle"
144
+ class="text-(--shiki-light) dark:text-(--shiki-dark)"
145
+ >{{ token.content }}</span></span></template><template v-else>{{ value }}</template></code></pre>
89
146
  <EmptyValue v-else-if="open" :id="contentId" />
90
147
  </div>
91
148
  </template>
@@ -0,0 +1,62 @@
1
+ import type { HighlighterCore } from "shiki/core";
2
+ import { createHighlighterCore } from "shiki/core";
3
+ import { createJavaScriptRegexEngine } from "shiki/engine/javascript";
4
+ import { resolveCodeLanguage } from "./code-languages";
5
+
6
+ export interface HighlightedToken {
7
+ content: string;
8
+ htmlStyle?: Record<string, string>;
9
+ }
10
+
11
+ let highlighter: Promise<HighlighterCore> | undefined;
12
+
13
+ async function getHighlighter() {
14
+ highlighter ??= createHighlighterCore({
15
+ themes: [import("shiki/themes/github-light.mjs"), import("shiki/themes/github-dark.mjs")],
16
+ langs: [],
17
+ engine: createJavaScriptRegexEngine({ forgiving: true }),
18
+ });
19
+
20
+ try {
21
+ return await highlighter;
22
+ } catch (error) {
23
+ highlighter = undefined;
24
+ throw error;
25
+ }
26
+ }
27
+
28
+ /** Load a registered grammar on demand, or return null for plain-text output. */
29
+ export async function loadHighlighter(language: string) {
30
+ const resolved = resolveCodeLanguage(language);
31
+ if (!resolved) return null;
32
+
33
+ const shiki = await getHighlighter();
34
+ if (!shiki.getLoadedLanguages().includes(resolved.name)) {
35
+ await shiki.loadLanguage(resolved.load);
36
+ }
37
+
38
+ return {
39
+ highlight(code: string): HighlightedToken[][] {
40
+ return shiki
41
+ .codeToTokens(code, {
42
+ lang: resolved.name,
43
+ themes: { light: "github-light", dark: "github-dark" },
44
+ defaultColor: false,
45
+ })
46
+ .tokens.map((line) =>
47
+ line.map((token) => ({
48
+ content: token.content,
49
+ htmlStyle: token.htmlStyle as Record<string, string> | undefined,
50
+ })),
51
+ );
52
+ },
53
+ };
54
+ }
55
+
56
+ export type CodeHighlighter = NonNullable<Awaited<ReturnType<typeof loadHighlighter>>>;
57
+
58
+ /** Highlight complete code without coupling tests to the Vue composable. */
59
+ export async function highlightCode(code: string, language: string) {
60
+ const highlighter = await loadHighlighter(language);
61
+ return highlighter?.highlight(code) ?? null;
62
+ }
@@ -0,0 +1,40 @@
1
+ import type { DynamicImportLanguageRegistration } from "shiki/core";
2
+
3
+ export type CodeLanguageLoader = DynamicImportLanguageRegistration;
4
+
5
+ export interface ResolvedCodeLanguage {
6
+ name: string;
7
+ load: CodeLanguageLoader;
8
+ }
9
+
10
+ const languages = new Map<string, CodeLanguageLoader>();
11
+ const aliases = new Map<string, string>();
12
+
13
+ function normalize(name: string) {
14
+ return name.trim().toLowerCase();
15
+ }
16
+
17
+ /** Register a lazy Shiki grammar without exposing the highlighter instance. */
18
+ export function registerCodeLanguage(name: string, load: CodeLanguageLoader, aliasList: string[] = []) {
19
+ const canonical = normalize(name);
20
+ const names = [...new Set([canonical, ...aliasList.map(normalize)])];
21
+ if (!canonical || names.some((item) => !item)) throw new Error("Code language names must not be empty");
22
+ for (const item of names) {
23
+ if (languages.has(item) || aliases.has(item)) throw new Error(`Code language "${item}" is already registered`);
24
+ }
25
+
26
+ languages.set(canonical, load);
27
+ for (const alias of names.slice(1)) aliases.set(alias, canonical);
28
+ }
29
+
30
+ export function resolveCodeLanguage(language: string): ResolvedCodeLanguage | undefined {
31
+ const requested = normalize(language);
32
+ const name = aliases.get(requested) ?? requested;
33
+ const load = languages.get(name);
34
+ return load ? { name, load } : undefined;
35
+ }
36
+
37
+ registerCodeLanguage("bash", () => import("shiki/langs/shellscript.mjs"), ["sh", "shell", "shellscript", "zsh"]);
38
+ registerCodeLanguage("json", () => import("shiki/langs/json.mjs"));
39
+ registerCodeLanguage("yaml", () => import("shiki/langs/yaml.mjs"), ["yml"]);
40
+ registerCodeLanguage("markdown", () => import("shiki/langs/markdown.mjs"), ["md"]);
@@ -1,4 +1,5 @@
1
1
  export { DataView, DataItem } from "./DataView.ts";
2
+ export { registerCodeLanguage, type CodeLanguageLoader } from "./code-languages.ts";
2
3
 
3
4
  export { default as DateFormatter } from "./DateFormatter.vue";
4
5
  export { default as Disclosure } from "./Disclosure.vue";
@@ -9,6 +10,7 @@ export { default as Pem } from "./Pem.vue";
9
10
  export { default as Route } from "./Route.vue";
10
11
 
11
12
  export { default as AsyncError } from "./AsyncError.vue";
13
+ export { default as Card } from "./Card.vue";
12
14
  export { default as CodeBlock } from "./CodeBlock.vue";
13
15
  export { default as CopyTag } from "./CopyTag.vue";
14
16
  export { default as Notice } from "./Notice.vue";
@@ -0,0 +1,54 @@
1
+ import type { MaybeRefOrGetter } from "vue";
2
+ import type { CodeHighlighter, HighlightedToken } from "./code-highlight";
3
+ import { resolveCodeLanguage } from "./code-languages";
4
+ import { computedAsync } from "@vueuse/core";
5
+ import { computed, toValue } from "vue";
6
+
7
+ interface LoadedHighlighter {
8
+ language: string;
9
+ highlighter: CodeHighlighter;
10
+ }
11
+
12
+ function plainLines(code: string): HighlightedToken[][] {
13
+ return code.split("\n").map((line) => (line ? [{ content: line }] : []));
14
+ }
15
+
16
+ /** Load a grammar reactively, then synchronously tokenize the latest value. */
17
+ export function useHighlightedCode(
18
+ value: MaybeRefOrGetter<string>,
19
+ language: MaybeRefOrGetter<string | undefined>,
20
+ maxLength: MaybeRefOrGetter<number>,
21
+ ) {
22
+ const loaded = computedAsync<LoadedHighlighter | null>(async () => {
23
+ const requested = toValue(language)?.toLowerCase();
24
+ const code = toValue(value);
25
+ const limit = toValue(maxLength);
26
+ if (!requested || !code || code.length > limit || limit <= 0 || typeof window === "undefined") return null;
27
+ if (!resolveCodeLanguage(requested)) return null;
28
+
29
+ try {
30
+ // Plain and oversized CodeBlocks do not download Shiki or any grammar.
31
+ const { loadHighlighter } = await import("./code-highlight");
32
+ const highlighter = await loadHighlighter(requested);
33
+ return highlighter ? { language: requested, highlighter } : null;
34
+ } catch {
35
+ return null;
36
+ }
37
+ }, null);
38
+
39
+ return computed<HighlightedToken[][]>(() => {
40
+ const raw = toValue(value);
41
+ // A final newline terminates the last line; it is not another empty line.
42
+ const code = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
43
+ const requested = toValue(language)?.toLowerCase();
44
+ const current = loaded.value;
45
+
46
+ if (!current || current.language !== requested || code.length > toValue(maxLength)) return plainLines(code);
47
+
48
+ try {
49
+ return current.highlighter.highlight(code);
50
+ } catch {
51
+ return plainLines(code);
52
+ }
53
+ });
54
+ }
@@ -0,0 +1,63 @@
1
+ <script setup lang="ts" generic="T extends string | string[] | null">
2
+ import { computed, provide, type HTMLAttributes } from "vue";
3
+ import { cn } from "cn";
4
+ import { ChoiceGroupKey } from "./choiceGroup";
5
+
6
+ defineOptions({ name: "ChoiceGroup", inheritAttrs: false });
7
+
8
+ const props = withDefaults(
9
+ defineProps<{
10
+ multiple?: boolean;
11
+ name: string;
12
+ disabled?: boolean;
13
+ class?: HTMLAttributes["class"];
14
+ }>(),
15
+ {
16
+ multiple: false,
17
+ disabled: false,
18
+ class: undefined,
19
+ },
20
+ );
21
+
22
+ const model = defineModel<T>({ required: true });
23
+ const selectedValues = computed<string[]>(() => (Array.isArray(model.value) ? model.value : []));
24
+
25
+ provide(ChoiceGroupKey, {
26
+ get multiple() {
27
+ return props.multiple;
28
+ },
29
+ get name() {
30
+ return props.name;
31
+ },
32
+ get disabled() {
33
+ return props.disabled;
34
+ },
35
+ isSelected(value) {
36
+ return props.multiple ? selectedValues.value.includes(value) : model.value === value;
37
+ },
38
+ update(value, checked) {
39
+ if (!props.multiple) {
40
+ if (checked) model.value = value as T;
41
+ return;
42
+ }
43
+
44
+ const next = new Set(selectedValues.value);
45
+ if (checked) next.add(value);
46
+ else next.delete(value);
47
+ model.value = [...next] as T;
48
+ },
49
+ });
50
+ </script>
51
+
52
+ <template>
53
+ <div
54
+ v-bind="$attrs"
55
+ data-slot="choice-group"
56
+ :data-multiple="multiple ? 'true' : undefined"
57
+ :class="
58
+ cn('flex min-w-0 flex-wrap items-center gap-2', !multiple && 'border border-border bg-card/30 p-2', props.class)
59
+ "
60
+ >
61
+ <slot />
62
+ </div>
63
+ </template>
@@ -0,0 +1,95 @@
1
+ <script setup lang="ts">
2
+ import { computed, inject, useId, type HTMLAttributes } from "vue";
3
+ import { Check } from "@lucide/vue";
4
+ import { cn } from "cn";
5
+ import { Badge } from "../../ui/badge";
6
+ import { Icon } from "../base";
7
+ import { ChoiceGroupKey } from "./choiceGroup";
8
+
9
+ defineOptions({ name: "ChoiceItem", inheritAttrs: false });
10
+
11
+ const props = withDefaults(
12
+ defineProps<{
13
+ value: string;
14
+ label?: string;
15
+ description?: string;
16
+ disabled?: boolean;
17
+ class?: HTMLAttributes["class"];
18
+ }>(),
19
+ {
20
+ label: undefined,
21
+ description: undefined,
22
+ disabled: false,
23
+ class: undefined,
24
+ },
25
+ );
26
+
27
+ const context = inject(ChoiceGroupKey);
28
+ if (!context) throw new Error("ChoiceItem must be used inside ChoiceGroup");
29
+ const group = context;
30
+ const inputId = `${useId()}-choice`;
31
+
32
+ const selected = computed(() => group.isSelected(props.value));
33
+ const disabled = computed(() => group.disabled || props.disabled);
34
+ const multiple = computed(() => group.multiple);
35
+
36
+ function update(event: Event) {
37
+ const checked = (event.target as HTMLInputElement).checked;
38
+ group.update(props.value, checked);
39
+ }
40
+ </script>
41
+
42
+ <template>
43
+ <Badge
44
+ v-bind="$attrs"
45
+ as="label"
46
+ :for="inputId"
47
+ variant="outline"
48
+ data-slot="choice-item"
49
+ :data-selected="selected ? 'true' : undefined"
50
+ :class="
51
+ cn(
52
+ 'choice-item h-6 cursor-pointer border-input/40 px-3 py-1 leading-none text-muted-foreground hover:border-input hover:text-foreground',
53
+ disabled && 'pointer-events-none cursor-not-allowed opacity-50',
54
+ props.class,
55
+ )
56
+ "
57
+ >
58
+ <input
59
+ :id="inputId"
60
+ class="sr-only"
61
+ :type="multiple ? 'checkbox' : 'radio'"
62
+ :name="group.name"
63
+ :value="value"
64
+ :checked="selected"
65
+ :disabled="disabled"
66
+ @change="update"
67
+ />
68
+ <Icon :icon="Check" size="xs" :class="selected ? 'visible' : 'invisible'" />
69
+ <slot :selected="selected" :disabled="disabled" :multiple="multiple">
70
+ <span v-if="label">{{ label }}</span>
71
+ <span v-if="description" class="font-normal text-muted-foreground">· {{ description }}</span>
72
+ </slot>
73
+ </Badge>
74
+ </template>
75
+
76
+ <style scoped>
77
+ .choice-item:has(input:checked) {
78
+ border-color: var(--primary);
79
+ background: color-mix(in oklab, var(--primary) 10%, transparent);
80
+ box-shadow: inset 0 0 0 1px var(--primary);
81
+ color: var(--foreground);
82
+ }
83
+
84
+ .choice-item:has(input:focus-visible) {
85
+ outline: 2px solid var(--ring);
86
+ outline-offset: 2px;
87
+ }
88
+
89
+ @media (forced-colors: active) {
90
+ .choice-item:has(input:checked),
91
+ .choice-item:has(input:focus-visible) {
92
+ outline: 2px solid Highlight;
93
+ }
94
+ }
95
+ </style>
@@ -103,6 +103,11 @@ const onBackspace = (index: number, event: KeyboardEvent) => {
103
103
  commit(rows.value.filter((_, rowIndex) => rowIndex !== index));
104
104
  if (previous) void focusInput(previous.id, true);
105
105
  };
106
+
107
+ const onKeydown = (index: number, event: KeyboardEvent) => {
108
+ if (event.key === "Enter") onEnter(index, event);
109
+ else if (event.key === "Backspace") onBackspace(index, event);
110
+ };
106
111
  </script>
107
112
 
108
113
  <template>
@@ -122,8 +127,7 @@ const onBackspace = (index: number, event: KeyboardEvent) => {
122
127
  :aria-label="props.rowLabel(index)"
123
128
  class="min-w-0 flex-1"
124
129
  @update:model-value="(value) => setLine(index, value)"
125
- @keydown.enter="onEnter(index, $event)"
126
- @keydown.backspace="onBackspace(index, $event)"
130
+ @keydown="onKeydown(index, $event)"
127
131
  />
128
132
  <IconBtn
129
133
  :icon="X"
@@ -0,0 +1,11 @@
1
+ import type { InjectionKey } from "vue";
2
+
3
+ export interface ChoiceGroupContext {
4
+ readonly multiple: boolean;
5
+ readonly name: string;
6
+ readonly disabled: boolean;
7
+ isSelected(value: string): boolean;
8
+ update(value: string, checked: boolean): void;
9
+ }
10
+
11
+ export const ChoiceGroupKey: InjectionKey<ChoiceGroupContext> = Symbol("ChoiceGroup");
@@ -1,3 +1,5 @@
1
+ export { default as ChoiceGroup } from "./ChoiceGroup.vue";
2
+ export { default as ChoiceItem } from "./ChoiceItem.vue";
1
3
  export { default as MultiLineInput } from "./MultiLineInput.vue";
2
4
  export { default as JsonTextArea } from "./JsonTextArea.vue";
3
5
  export { default as EntitySelect } from "./EntitySelect.vue";
@@ -1,20 +1,27 @@
1
1
  <script setup lang="ts">
2
+ import type { PrimitiveProps } from "reka-ui";
2
3
  import type { HTMLAttributes } from "vue";
4
+ import { Primitive } from "reka-ui";
3
5
  import { cn } from "cn";
4
6
 
5
7
  const props = withDefaults(
6
- defineProps<{
7
- class?: HTMLAttributes["class"];
8
- size?: "default" | "sm";
9
- }>(),
8
+ defineProps<
9
+ PrimitiveProps & {
10
+ class?: HTMLAttributes["class"];
11
+ size?: "default" | "sm";
12
+ }
13
+ >(),
10
14
  {
15
+ as: "div",
11
16
  size: "default",
12
17
  },
13
18
  );
14
19
  </script>
15
20
 
16
21
  <template>
17
- <div
22
+ <Primitive
23
+ :as="as"
24
+ :as-child="asChild"
18
25
  data-slot="card"
19
26
  :data-size="size"
20
27
  :class="
@@ -25,5 +32,5 @@ const props = withDefaults(
25
32
  "
26
33
  >
27
34
  <slot />
28
- </div>
35
+ </Primitive>
29
36
  </template>