TreeSelect
Seleccionar nodos de árbol con marcas de búsqueda, carga y relacionadas.
Cuándo usar
TreeSelect Selecciona una subdivisión, una sección de documentación u otra entrada de la jerarquía. El árbol se abre en un panel y el valor contiene la clave de nodo. Si la aplicación necesita una ruta completa y columnas de nivel individual, use Cascader.
Pase el treeData incrustado con value único. El título title explica la elección a la persona; key se puede configurar por separado, pero el valor del modelo se determina value. Para árbol permanente sin campo de entrada es Tree.
CSS Prefijo TreeSelect Mostrar total ConfigProvider.prefixCls y local prefixCls sin estado de restablecimiento. control y etiquetas usan Select prefix; Popup agrega un sufijo -tree-dropdown. El árbol anidado conserva el adaptador de árbol nativo y las clases nativas: Local prefix TreeSelect no es Tree.prefixCls.
Esquemas y declaraciones de datos
Esquema propio y datos planos Comparar value/label/children a través de fieldNames y muestra treeDataSimpleMode. La búsqueda predeterminada usa el campo value literal, por lo que se establece explícitamente showSearch.treeNodeFilterProp para el otro esquema. Las devoluciones de llamada de selección y filtrado obtienen los campos personalizados originales. simple mode construye estándar children a id/pId; Si coincide fieldNames deje el nombre children como estándar. Los datos de entrada no se cambian.
Nodos declarativos Usar TreeSelect.TreeNode y nombrado TreeSelectTreeNode. treeData tiene prioridad sobre los anuncios. Las estrategias están disponibles como TreeSelect.SHOW_PARENT, show_child y show_all. icono y switcherIcon Aceptar contenido o fragmento con TreeEventNode. class/style, data-* y aria-* se aplican a la cuerda; styles.popup.item se solapa con su propio estilo.
Valor de nodo
Single devuelve una cadena o una clave numérica. multiple Devuelve una matriz de teclas. Para labelInValue en lugar de la clave, se usa el objeto con value y label en lugar de la clave; treeCheckStrictly Activa este formato automáticamente.
| Tarea | Configuración | Ejemplo |
|---|---|---|
| Seleccionar un nodo | treeData, value, onChange |
Seleccionar nodo de treeData |
| Seleccionar nodos independientes | multiple |
Múltiples nodos |
| Marcar una rama con descendientes | treeCheckable |
Marcas relacionadas |
| Marque una casilla de verificación de forma independiente | treeCheckStrictly |
Marcas independientes |
| Reciba una llave junto con una etiqueta | labelInValue |
etiqueta |
El control gestionado recibe value e informa una nueva selección a través de onChange. A diferencia de los componentes con bind:value, aquí la propia aplicación asigna el resultado a su estado. defaultValue Establece el valor local inicial. informes de limpieza individuales undefined, multiple — matriz vacía; El ejemplo básico normaliza la falta de elección en null.
El segundo argumento onChange contiene etiquetas o null para formato labelInValue, el tercero es triggerValue. Esta es la clave de nodo que causó el cambio, no su ruta principal. Por el camino, construya un mapa de los padres usando treeData de antemano.
Marcas relacionadas
treeCheckable Incluye multiple y la relación de los padres con la descendencia. show_child Devuelve los nodos finales marcados, show_parent combina la rama completa, show_all incluye padre e hijo. Comparación de estrategias muestra la diferencia de resultados; La estrategia afecta al modelo emitido, no solo a la etiqueta.
treeCheckable toma TreeSelectCheckableContent: boolean, texto, números, bigint, snippet, matrices anidadas, iterables y Promise. Solo se utiliza la verdad del valor JavaScript. false, null, undefined, "", 0, -0, NaN y 0n no incluyen marcas; [], snippet y Promise incluyen casillas de verificación estándar. El contenido no se emite: no se llama a Snippet, iterable no, no se espera Promise.
Contenido treeCheckable Permite comparar banderas. El ejemplo incluyó explícitamente multiple, por lo que la matriz de valores seleccionados también se guarda cuando se desactivan las marcas.
treeCheckStrictly Deshabilita el enlace de marcas y devuelve objetos con value y label. Al cambiar el modo, haga coincidir el tipo de estado con el nuevo formato. Para multiple normales sin casilla de verificación, los nodos se seleccionan de forma independiente.
selectable=false Prohíbe la selección del encabezado mientras se mantiene la apertura de la rama. disabled Bloquea el nodo, disableCheckbox desactiva la marca por separado, checkable=false elimina su casilla de verificación. El ejemplo básico le permite abrir la "interfaz" sin elegir este encabezado.
Límite de selección
Límite de selección TreeSelect Muestra maxCount multiple casilla de verificación vinculada y treeCheckStrictly. Los valores iniciales y gestionados no se cortan cuando se reduce el límite; También se tienen en cuenta los valores desconocidos. Puede desmarcar o borrar la selección después de alcanzar el límite. Este es el límite de elección, no el número de etiquetas visibles: maxTagCount Limite las etiquetas visibles.
explícito showCheckedStrategy=SHOW_PARENT desactiva el límite distinto de cero. show_all lo deshabilita sin treeCheckStrictly; Para normal multiple No establezca esta estrategia explícitamente si necesita un límite. show_child y estricto conservan la restricción. maxCount=0 prohíbe nuevos valores incluso con show_parent/show_all; En single, el límite no se aplica.
Para Show_Child, la rama principal puede no estar disponible si sus hijos directos no se colocan en el resto del límite. Además, se comprueba el número total de valores después de la marca asociada. El intento de selección puede causar onSelect/onDeselect sin onChange si el conjunto total excede el límite distinto de cero. Cambiar maxCount Guarda la selección actual; El modo de conmutación en el ejemplo lo borra explícitamente para que coincida con el formato de claves y objetos estrictos.
Divulgación con encabezado
Divulgación TreeSelect Encabezado Muestra treeExpandAction=false, click y doubleClick. De forma predeterminada, el encabezado solo selecciona un nodo. treeExpandedKeys y onTreeExpand Controlar la divulgación independientemente de value; Modo de cambio Guarda el estado.
En click onTreeExpand se llama el modo antes de onChange/onSelect. En multiple, el doble clic real primero hace dos opciones normales, luego abre la rama. Ctrl/Meta/Shift Suprime el encabezado de apertura, manteniendo la selección. El conmutador, la casilla de verificación y el teclado funcionan de forma independiente; Enter Selecciona un nodo activo. explícito isLeaf=true prohíbe la divulgación; disabled Prohíbe la selección, pero permite la divulgación del encabezado.
Búsqueda y ramas asincrónicas
showSearch Habilitado de forma predeterminada para multiple. Para buscar encabezados, pase showSearch={{ treeNodeFilterProp: 'title' }}. En el mismo objeto son filterTreeNode, searchValue, onSearch y autoClearSearchValue. Ejemplo de búsqueda Almacena la solicitud por separado del nodo seleccionado y la borra explícitamente después de la selección.
Cuando cierra el sencillo, se borra la búsqueda. para searchValue controlado tomar la cuerda vacía en onSearch; Se guarda el nodo seleccionado. En multiple cerrar el panel por sí solo no borra la solicitud.
Separadores de búsqueda Mostrar tokenSeparators: matriz de cadenas o función (text: string) => string[]. La partición borra la solicitud y cierra el panel, pero no llama a onChange o onSelect y no selecciona nodos por las palabras ingresadas. La elección se hace por separado en el árbol.
Durante el IME, la división está esperando compositionend. Para insertar una lista de cadenas, agregue \n o \r\n a la matriz delimitada, o use la función. La función devuelve partes rotas; Una matriz vacía o una sola cadena de origen significa que no hay partición.
loadData Obtiene un nodo abierto y devuelve Promise. Agregue children cargado a treeData hasta que se complete. Para una rama que aún no se ha cargado, establezca isLeaf=false, para el nodo final true. Ejemplo asincrónico Completa el Promise pendiente y borra el temporizador al salir de la página.
durante la búsqueda loadData no se llama. Para la búsqueda del servidor, procese showSearch.onSearch y actualice treeData en la aplicación; No espere una solicitud por separado cada vez que coincida el filtro local. treeExpandedKeys y treeLoadedKeys Controlar ramas abiertas y cargadas por separado de la value seleccionada.
Enfoque y Eventos
Enfoque y Eventos TreeSelect muestra showAction=['focus'] y el registro del controlador. El panel se abre delante de onFocus. Una matriz vacía o ['click'] retiene la apertura normal con un puntero. Cambio showAction El campo ya enfocado no abre el panel por sí mismo. autoFocus y tabIndex especificar atributos de campo; Nativo autofocus y tabindex tienen prioridad. Cuando se hidrata, el autofoco conserva el foco de otro control. maxLength, como en el original, no limita la búsqueda; Nativo maxlength Especifica la restricción del navegador.
Primero se llama el campo onkeydown nativo, luego onInputKeyDown, procesamiento interno y raíz onKeyDown. Para cancelar una selección o abrir, use event.preventDefault() en onkeydown nativo. preventDefault en onInputKeyDown no cancela la selección; stopPropagation Detiene la devolución de llamada raíz. La entrada retenida selecciona una vez a keyup o blur. En el campo ReadOnly, el espacio abre el panel; Escape lo cierra. Al pulsar ENTER/Espacio en el botón de limpieza no se transfiere a la raíz onKeyDown.
onFocus/onBlur Ser real focusin/focusout. Las devoluciones de llamada raíz obtienen currentTarget raíz real, div predeterminado; Manejadores de Editor Nativo - Entrada o textarea. El panel emergente tiene su propio límite de evento DOM. Cierre con teclado y pulsación externa se retrasa hasta la raíz key/blur devolución de llamada. En el servidor de devolución de llamada, autofocus y los temporizadores no se inician.
En el ejemplo del evento, puede cambiar single/multiple y buscar. Al volver a presionar el campo único sin buscar, se cierra el panel; Con una búsqueda, la deja abierta. En multiple Al pulsar la entrada se guarda el panel abierto y lo cambia a un área de campo libre. Limpieza de un solo ratón cierra el panel retrasado; En multiple guarda su estado. onFocus/onBlur y onClick Los campos no reciben un evento de popup, incluido el contenido del usuario.
Etiquetas y etiquetas devueltas
Pantalla de etiquetas Compara numérico y responsive maxTagCount. Este es el número de etiquetas visibles; Los valores completos permanecen en las devoluciones de llamada y FormData. maxTagTextLength Solo corta texto y etiquetas numéricas manteniendo tooltip y etiquetas completas. Los fragmentos y las matrices siguen siendo contenido opaco. Las etiquetas sensibles se miden después del montaje; En el servidor, se ocultan hasta la medición.
tagRender Obtiene TreeSelectTagInfo: label Llamado vía render, closable/onClose Gestionar la eliminación. El contador tiene isMaxTag=true y no contiene value/index/onClose. maxTagPlaceholder Obtiene registros omitidos completos. en treeTitleRender label en onChange se convierte en un fragmento de enlace: está en modo normal en etiquetas, en labelInValue/estricto — en la grabación value y Las etiquetas son null. etiqueta propia de nodo Guarda el fragmento y lo emite después del campo Desmontar. Para mostrar, marque typeof label === 'función'; JSON.stringify no muestra el contenido de Snippet.
Campo, panel y diseño
Ranuras de campo y panel Mostrar prefix, suffix y popupRender. suffix recibe open, enfocado, searchValue, showSearch y loading; Tiene prioridad sobre suffixIcon y null/undefined devuelve la selección de iconos estándar. suffixIcon=null Oculta la flecha. removeIcon Cambia el icono de etiqueta normal. allowClear toma objeto con clearIcon y nombre disponible label. Borrar una búsqueda no vacía provoca onSearch con una cadena vacía.
FormItem.hasFeedback Añade un icono de verificación junto a la flecha estándar. suffixIcon=null Oculta la flecha pero guarda la retroalimentación. Own suffix Reemplaza el contenido de esta área y no agrega retroalimentación automáticamente.
En popupRender Llamar al snippet que se pasa al menú para emitir el árbol original. El campo anidado puede enfocarse y guardar el calado entre las aberturas del panel. Semantic styles Mostrar objetos y funciones classNames/styles. Las ranuras de campo incluyen root,prefix,input,suffix,clear,content,placeholder, item, itemContent y itemRemove; La ventana emergente contiene root, item, itemTitle y itemSwitcher. Las funciones se permiten propiedades. CSS especificado por cadenas. ConfigProvider.treeSelect conjuntos variant, classNames, styles y switcherIcon; Las clases locales se combinan con el proveedor, la cadena local de la ranura emergente reemplaza el estilo correspondiente. La entrada anidada del proveedor sustituye al conjunto principal.
onPopupVisibleChange, popupStyle, choiceTransitionName y local direction son aceptados pero no cambiando el comportamiento. Para eventos, use onOpenChange, para diseño — styles.popup.root, para RTL — ConfigProvider.direction. Los valores originales están disponibles en devoluciones de llamada semánticas. Nativo HTML dir sigue siendo un atributo separado.
Alineación del panel
Alineación del panel TreeSelect Compara popupAlign y builtinPlacements. El primer parámetro anula los campos de la posición seleccionada; offset, targetOffset y overflow se reemplazan por completo. Los porcentajes en offset se calculan desde el panel, en targetOffset — desde el campo.
builtinPlacements Reemplaza la tarjeta de cuatro posiciones por completo, incluyendo un objeto explícitamente vacío. Si no hay ninguna entrada seleccionada, se utiliza centrado, no la entrada estándar del mapa anterior.
ConfigProvider.popupOverflow Selecciona el área de mapa estándar: Viewport o área de documento scroll. Ejemplo general Muestra herencia y viewport explícito. propio builtinPlacements, incluida una tarjeta vacía, reemplaza la estándar; Local popupAlign.htmlRegion tiene prioridad. El cambio de modo general actualiza el mapa para el próximo recálculo, manteniendo las coordenadas actuales.
Abrir panel Guarda la alineación calculada hasta placement Cambio, tamaño de campo o tamaño del panel, resize Desplazamiento de ventana o antepasado. Cambiar el mapa por sí mismo no vuelve a calcular las coordenadas. Cambio popupAlign Provoca un recálculo inmediato solo si no hay ninguna entrada de tarjeta seleccionada.
Animación de panel
Animación de panel TreeSelect Muestra la transición estándar, su nombre CSS, animation y deshabilitar la transición con nombre. transitionName=undefined Selecciona el prefijo deslizante estándar ConfigProvider; transitionName="" Deshabilita la transición con nombre. no vacío animation tiene prioridad y forma un nombre del prefijo Select, -dropdown- y su valor.
Para su propio nombre define CSS entrada y salida; El ejemplo utiliza Fade. Completar el efecto CSS completa la fase correspondiente. El nombre sin CSS no recibe un temporizador de finalización artificial. El panel guarda el DOM después de salir, la reapertura de las interrupciones se cierra y se guarda la búsqueda multiple. Estos ajustes se refieren al panel, no a la apertura de las ramas de los árboles.
theme.token.motion=false Deshabilita el inicio de la transición con nombre cuando se abre. Cambiar la configuración o el nombre durante la fase ya iniciada no lo fuerza.
Propietario
components.root Reemplaza el campo: etiquetas estándar, afijos y components.input no se muestran. En Ejemplo de raíz Button, muestra la etiqueta seleccionada y recibe un aria para abrir el árbol. Al quitar la ranura raíz, se devuelve el selector normal con el valor actual.
components.input Reemplaza solo al editor, manteniendo el diseño del selector, las etiquetas y suffix. Editor de área de texto Muestra el cambio de editor, etiquetas receptivas y orden de devolución de llamada. La búsqueda y el valor seleccionado siguen siendo datos diferentes.
Cuando multiple y maxTagCount="responsive" propio editor participa en la medición de etiquetas y puede obtener una colocación absoluta suffix. Cambiar el tamaño de un campo o editor actualiza el número de etiquetas visibles. El panel conserva la unión al campo en resize y desplazamiento, incluso en RTL.
Fragmento obtiene attributes y register. Pase los atributos al elemento DOM real y regístrelo a través de {@attach register}. Para el componente de biblioteca, puede registrar un objeto con inputElement, nativeElement y usando métodos focus/blur. La limpieza devuelta se utiliza en $effect; Los REF se eliminan al reemplazar o desmontar. Formulario de ejemplo pasa los atributos a Input, mantiene la conexión de campo con TreeSelect y no agrega un segundo valor de formulario.
Objeto { render, props } Añade propios atributos. En la entrada, tienen prioridad, y las devoluciones de llamada van frente a las internas; Los atributos internos raíz son prioridad, y las devoluciones de llamada internas van primero. Aplicar atributos ya combinados para guardar controladores. Para cancelar el procesamiento del teclado, use onkeydown TreeSelect nativo.
Parámetros RootElement y EditorElement Refinar tipos de eventos y refs. bind:nativeElement devuelve la raíz actual, bind:inputElement — entrada o textarea; Con la ranura raíz, no hay editor. Se quitó la ranura: obtuve el div/input estándar. La raíz nativa es responsable de mostrar el valor, ARIA y las restricciones nativas, incluidas disabled.
Virtualización y desplazamiento
popupMatchSelectWidth Repite el ancho del campo en true, ajusta el panel al contenido en false o establece el ancho en px por número. El ancho del campo sigue siendo el mínimo. Falta Prop y undefined Heredar ConfigProvider.popupMatchSelectWidth. Ancho total del panel compara la herencia con true y el número local Select.
Árbol grande Contiene 600 nudos. virtual heredado de ConfigProvider.virtual y habilitado por defecto. listHeight Límites Viewport, listItemHeight Establece la estimación de altura de línea inicial, listItemScrollOffset Agrega sangría al moverse al nodo activo. popupMatchSelectWidth=false deshabilita la virtualización; El valor numérico establece el ancho del panel. La propiedad se hereda de ConfigProvider si no se establece localmente.
vía bind:this disponible TreeSelectRef con focus, blur y scrollTo. El método toma las coordenadas key/index con align y offset. Ir a la rama autoExpand revela su ruta interna si la divulgación no se especifica en Props. onPopupScroll Obtiene el evento viewport Árbol. Las flechas y Enter continúan trabajando con el nodo activo; aria-activedescendant apunta a una cuerda mientras está presente en el DOM.
showScrollBar se acepta como una propiedad heredada, pero no se pasa al árbol y no cambia el desplazamiento. No lo use para controlar la barra de desplazamiento TreeSelect.
Mapeo y formulario
treeTitleRender y switcherIcon Aceptar Svelte Fragmentos. Sus etiquetas Cambiar la pantalla del nodo sin cambiarlo value. popupMatchSelectWidth Establece el ancho del panel, listHeight — altura; Para etiquetas largas, revise el panel en una pantalla estrecha.
TreeSelect Soporta virtualización, esquemas de campo, mode simple, etiquetas, ranuras de panel y semántica styles. El conjunto completo compatible se proporciona en API.
en Formulario de suscripción onChange Actualizaciones form.setFieldValue y reset Restauraciones initialValues. label Especifica el nombre del campo disponible. Flechas Mover Enfoque en un árbol, Enter Selecciona un nodo, Escape Cierra la ventana emergente; focus/blur disponible a través de una instancia de componente.
Diseño TreeSelect Usos Fichas de diseño (tokens de diseño) Tema actual.
Ejemplos
Seleccionar nodo de treeData
El árbol se establece a través de treeData. Single devuelve la clave del nodo seleccionado; La interfaz principal se abre pero no está seleccionada.
<script lang="ts">
import { TreeSelect, type TreeSelectNode, type TreeSelectValue } from '@woodger/antd';
const treeData: TreeSelectNode[] = [
{ value: 'ui', title: "Interfaz", selectable: false, children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] },
{ value: 'data', title: "Datos", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Sección no disponible", disabled: true }
];
let value = $state<TreeSelectValue>(null);
</script>
<TreeSelect
aria-label={("Sección básica")}
{treeData}
{value}
treeDefaultExpandAll
allowClear
placeholder={("Seleccionar sección")}
onChange={next => { value = next ?? null; }}
/>
<p><output aria-label={("Nodo seleccionado")}>{JSON.stringify(value)}</output></p>
Múltiples nodos
multiple Selecciona los nodos de forma independiente. las etiquetas de formulario de etiquetas seleccionadas; La eliminación de etiquetas cambia el modelo.
<script lang="ts">
import { TreeSelect, type TreeSelectNode, type TreeSelectValue } from '@woodger/antd';
const treeData: TreeSelectNode[] = [
{ value: 'ui', title: "Interfaz", selectable: false, children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] },
{ value: 'data', title: "Datos", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Sección no disponible", disabled: true }
];
let value = $state<TreeSelectValue>(['button']);
</script>
<TreeSelect
aria-label={("Múltiples secciones")}
{treeData}
{value}
multiple
treeDefaultExpandAll
allowClear
showSearch={{ treeNodeFilterProp: 'title' }}
onChange={next => { value = next; }}
/>
<p><output
aria-label={("Múltiples nodos seleccionados")}
>{JSON.stringify(value)}</output></p>
Marcas relacionadas
treeCheckable Incluye multiple y la relación de los padres con la descendencia. De forma predeterminada, show_child devuelve los nodos finales.
<script lang="ts">
import { TreeSelect, type TreeSelectNode, type TreeSelectValue } from '@woodger/antd';
const treeData: TreeSelectNode[] = [
{ value: 'ui', title: "Interfaz", selectable: false, children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] },
{ value: 'data', title: "Datos", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Sección no disponible", disabled: true }
];
let value = $state<TreeSelectValue>([]);
</script>
<TreeSelect
aria-label={("Secciones relacionadas")}
{treeData}
{value}
treeCheckable
treeDefaultExpandAll
onChange={next => { value = next; }}
/>
<p><output
aria-label={("Nodos seleccionados relacionados")}
>{JSON.stringify(value)}</output></p>
Contenido treeCheckable
Texto, matriz vacía y fragmento de fragmento incluyen la casilla de verificación estándar. No se muestra el contenido; multiple Guarda la matriz de valores seleccionados.
<script lang="ts">
import {
RadioGroup,
TreeSelect,
type TreeSelectCheckableContent,
type TreeSelectValue
} from '@woodger/antd';
const flags: Record<string, TreeSelectCheckableContent> = {
true: true,
false: false,
'"checkbox"': 'checkbox',
'[]': []
};
const treeData = [{ value: 'ui', title: 'UI', children: [
{ value: 'button', title: 'Button' },
{ value: 'input', title: 'Input' }
] }];
let flag = $state('true');
let value = $state<TreeSelectValue>([]);
</script>
<style>
.controls { margin-bottom: 16px; }
</style>
{#snippet checkboxContent()}<strong data-checkable-content>Checkbox</strong>{/snippet}
<div class="controls">
<RadioGroup
aria-label={("Valor treeCheckable")}
options={['true', 'false', '"checkbox"', '[]', 'Snippet']}
bind:value={flag}
/>
</div>
<TreeSelect
aria-label={("Selección con treeCheckable")}
{treeData}
treeCheckable={flag === 'Snippet' ? checkboxContent : flags[flag]}
{value}
multiple
showSearch={false}
treeDefaultExpandAll
onChange={next => { value = next; }}
/>
<p><output aria-label={("Nodos seleccionados con bandera treeCheckable")}>
{JSON.stringify(value)}
</output></p>
Cambio de límite inverso guarda la opción, cambia el modo en este ejemplo. él. Show_Parent y No String Show_All desactiva el límite distinto de cero; maxCount=0 prohíbe una nueva opción.
Límite de selección TreeSelect
maxCount Límite multiple y casilla de verificación. Comparar estrategias y estricto; Se guardan los valores iniciales por encima del límite.
<script lang="ts">
import { TreeSelect, type TreeSelectValue } from '@woodger/antd';
const modes = ['multiple', 'SHOW_CHILD', 'SHOW_PARENT', 'SHOW_ALL', 'strict'] as const;
let mode = $state<typeof modes[number]>('multiple');
let maxCount = $state(2);
let value = $state<TreeSelectValue>(['button']);
const strategy = $derived(
mode === 'SHOW_CHILD' || mode === 'SHOW_PARENT' || mode === 'SHOW_ALL'
? mode
: undefined
);
const treeData = $derived([
{ value: 'ui', title: ("Interfaz"), children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] },
{ value: 'data', title: ("Datos"), children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] }
]);
</script>
<div class="controls">
<label>maxCount <select value={maxCount} onchange={event => {
maxCount = Number(event.currentTarget.value);
}}>
{#each [0, 1, 2, 3] as count (count)}<option value={count}>{count}</option>{/each}
</select></label>
<label>{("Modo de limitación")} <select value={mode} onchange={event => {
const next = modes.find(item => item === event.currentTarget.value);
if (next) {
mode = next;
value = [];
}
}}>
{#each modes as item (item)}<option
value={item}
>{item === 'strict' ? 'treeCheckStrictly' : item}</option>{/each}
</select></label>
</div>
<TreeSelect aria-label={("Selección de restricción TreeSelect")}
{treeData} {value} {maxCount} multiple treeDefaultExpandAll allowClear
treeCheckable={mode !== 'multiple'} treeCheckStrictly={mode === 'strict'}
showCheckedStrategy={strategy} showSearch={{ treeNodeFilterProp: 'title' }}
onChange={next => { value = next; }} />
<p><output
aria-label={("Valor límite TreeSelect")}
>{JSON.stringify(value)}</output></p>
<p>
{("Cambio de límite inverso guarda la opción, cambia el modo en este ejemplo. él. Show_Parent y No String Show_All desactiva el límite distinto de cero; maxCount=0 prohíbe una nueva opción.")}
</p>
<style>
.controls {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin-block-end: 12px;
}
</style>
SHOW_ALL
SHOW_PARENT
SHOW_CHILD
Estrategia de nodos marcados
show_all Muestra padre y descendencia, show_parent contrae la rama, show_child deja las hojas.
<script lang="ts">
import { TreeSelect, type TreeSelectNode } from '@woodger/antd';
const treeData: TreeSelectNode[] = [
{ value: 'ui', title: "Interfaz", selectable: false, children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] },
{ value: 'data', title: "Datos", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Sección no disponible", disabled: true }
];
const strategies = ['SHOW_ALL', 'SHOW_PARENT', 'SHOW_CHILD'] as const;
</script>
<style>
.examples {
display: grid;
gap: 16px;
}
p {
margin: 0 0 8px;
}
</style>
<div class="examples">
{#each strategies as strategy (strategy)}
<div><p>{(strategy)}</p><TreeSelect
aria-label={("Estrategia TreeSelect " + String((strategy)) + "")}
{treeData}
treeCheckable
showCheckedStrategy={strategy}
defaultValue={['button', 'input']}
treeDefaultExpandAll
/></div>
{/each}
</div>
Marcas independientes
treeCheckStrictly deshabilita a los padres e hijos e incluye labelInValue. El resultado son objetos con value y label.
<script lang="ts">
import { TreeSelect, type TreeSelectNode, type TreeSelectValue } from '@woodger/antd';
const treeData: TreeSelectNode[] = [
{ value: 'ui', title: "Interfaz", selectable: false, children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] },
{ value: 'data', title: "Datos", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Sección no disponible", disabled: true }
];
let value = $state<TreeSelectValue>([]);
</script>
<TreeSelect
aria-label={("Secciones independientes")}
{treeData}
{value}
treeCheckStrictly
treeDefaultExpandAll
onChange={next => { value = next; }}
/>
<p><output
aria-label={("Nodos seleccionados independientes")}
>{JSON.stringify(value)}</output></p>
etiqueta
labelInValue devuelve un objeto en lugar de una clave simple. La tecla numérica retiene el tipo number.
<script lang="ts">
import { TreeSelect, type TreeSelectValue } from '@woodger/antd';
let value = $state<TreeSelectValue>(null);
</script>
<TreeSelect aria-label={("Sección")} treeData={[{
value: 10,
title: "Documentación"
}, { value: 20, title: "Ejemplos" }]}
{value} labelInValue allowClear onChange={next => { value = next ?? null; }} />
<p><output aria-label={("Seleccionar objeto de nodo")}>{JSON.stringify(value)}</output></p>
Búsqueda por etiqueta
showSearch especifica searchValue controlado y filtrado por title. Las coincidencias anidadas guardan la rama principal.
<script lang="ts">
import { TreeSelect, type TreeSelectNode, type TreeSelectValue } from '@woodger/antd';
const treeData: TreeSelectNode[] = [
{ value: 'ui', title: "Interfaz", selectable: false, children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] },
{ value: 'data', title: "Datos", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Sección no disponible", disabled: true }
];
let value = $state<TreeSelectValue>(null);
let search = $state('');
function handleChange(next: TreeSelectValue) {
value = next ?? null;
search = '';
}
</script>
<TreeSelect aria-label={("Buscar la sección")} {treeData} {value} treeDefaultExpandAll
showSearch={{
treeNodeFilterProp: 'title',
searchValue: search,
onSearch: next => { search = next; }
}}
notFoundContent={("Secciones no encontradas")} onChange={handleChange} />
<p><output aria-label={("Búsqueda y sección seleccionada")}>{(search
|| ("Búsqueda vacía"))}; {JSON.stringify(value)}</output></p>
Búsqueda:
Seleccionado:
Separadores de búsqueda
tokenSeparators Toma una matriz o función. El separador borra la búsqueda y cierra el panel, guardando la selección; Esta no es una elección automática de nodos.
<script lang="ts">
import {
Button,
TreeSelect,
type TreeSelectTokenSeparators,
type TreeSelectValue
} from '@woodger/antd';
const treeData = [{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }];
let value = $state<TreeSelectValue>(['button']);
let search = $state('');
let splitter = $state('array');
const tokenSeparators = $derived<TreeSelectTokenSeparators>(
splitter === 'function'
? text => text.split(/[;\r\n]+/)
: [',', '\n']
);
</script>
<div class="controls">
<label>{("Separadores de búsqueda")} <select bind:value={splitter}>
<option value="array">{("Envoltura de comas y líneas")}</option>
<option value="function">{("Función: punto y coma")}</option>
</select></label>
<Button onclick={() => { search = ''; value = ['button']; }}>
{("Restablecer el ejemplo del delimitador")}
</Button>
</div>
<TreeSelect
aria-label={("Buscar TreeSelect con delimitadores")}
{treeData}
{value}
multiple
{tokenSeparators}
showSearch={{
searchValue: search,
treeNodeFilterProp: 'title',
onSearch: next => { search = next; }
}}
onChange={next => { value = next ?? []; search = ''; }}
/>
<p>{("Búsqueda: ")}<output aria-label={("Buscar con delimitadores")}>{search
|| ("Búsqueda vacía")}</output></p>
<p>{("Seleccionado: ")}<output
aria-label={("Nodos seleccionados con delimitadores")}
>{JSON.stringify(value)}</output></p>
<style>
.controls {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
margin-bottom: 16px;
}
select { max-width: 100%; }
label { min-width: 0; }
</style>
Descarga asincrónica
loadData devoluciones Promise y actualizaciones treeData. La búsqueda no llama al cargador. Temporizador y Espera Promise Terminar en desmontaje.
<script lang="ts">
import { onDestroy } from 'svelte';
import { TreeSelect, type TreeSelectNode } from '@woodger/antd';
let treeData = $state<TreeSelectNode[]>([{ value: 'catalog', title: "Catálogo", isLeaf: false }]);
let pending = $state(false);
let timer: ReturnType<typeof setTimeout> | undefined;
let finish: (() => void) | undefined;
function handleLoad() {
pending = true;
return new Promise<void>(resolve => {
finish = resolve;
timer = setTimeout(() => {
treeData = [{ value: 'catalog', title: "Catálogo", isLeaf: false, children: [
{ value: 'guides', title: "Manuales", isLeaf: true }
] }];
pending = false;
timer = undefined;
finish = undefined;
resolve();
}, 600);
});
}
onDestroy(() => {
clearTimeout(timer);
finish?.();
});
</script>
<TreeSelect
aria-label={("Descargar sección")}
{treeData}
loadData={handleLoad}
placeholder={("Ampliar Catálogo")}
/>
<p><output aria-label={("Estado de carga de árbol")}>{(pending ? "Cargando…" : "Directorio Listo")}</output></p>
Ctrl, META y SHIFT Guardar la acción de selección sin encabezado. El botón de apertura y el teclado funcionan por separado.
Divulgación TreeSelect Encabezado
treeExpandAction: false, click o doubleClick. La selección y la divulgación se controlan por separado; Modo de cambio Guarda el estado.
<script lang="ts">
import {
TreeSelect,
type TreeExpandAction,
type TreeKey,
type TreeSelectValue
} from '@woodger/antd';
let action = $state<TreeExpandAction>(false);
let expanded = $state<TreeKey[]>([]);
let value = $state<TreeSelectValue>([]);
const treeData = $derived([
{
value: 'ui', title: ("Interfaz"), children: [
{ value: 'button', title: 'Button', isLeaf: true },
{ value: 'input', title: 'Input', isLeaf: true }
]
}
]);
</script>
<style>
label {
display: block;
margin-block-end: 12px;
}
</style>
<label>treeExpandAction <select value={String(action)} onchange={event => {
const next = event.currentTarget.value;
action = next === 'click' || next === 'doubleClick' ? next : false;
}}>
<option value="false">false</option>
<option value="click">click</option>
<option value="doubleClick">doubleClick</option>
</select></label>
<TreeSelect aria-label={("Divulgación TreeSelect Encabezado")}
{treeData} {value} multiple showSearch={false} treeExpandAction={action}
treeExpandedKeys={expanded} onTreeExpand={keys => { expanded = keys; }}
onChange={next => { value = next; }} />
<p><output aria-label="treeExpandedKeys">{JSON.stringify(expanded)}</output></p>
<p><output aria-label="value">{JSON.stringify(value)}</output></p>
<p>
{("Ctrl, META y SHIFT Guardar la acción de selección sin encabezado. El botón de apertura y el teclado funcionan por separado.")}
</p>
Líneas de árboles e interruptor
treeLine Muestra las conexiones, showLeafIcon controla las hojas. switcherIcon recibe TreeEventNode; treeIcon Incluye iconos de nodos.
<script lang="ts">
import { TreeSelect, type TreeEventNode, type TreeSelectNode } from '@woodger/antd';
const treeData: TreeSelectNode[] = [
{ value: 'ui', title: "Interfaz", selectable: false, children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] },
{ value: 'data', title: "Datos", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Sección no disponible", disabled: true }
];
</script>
{#snippet switcher(node: TreeEventNode)}<span aria-hidden="true">{(node.expanded ? '−' : '+')}</span>{/snippet}
<TreeSelect
aria-label={("Árbol con líneas")}
{treeData}
treeDefaultExpandAll
treeLine={{ showLeafIcon: true }}
treeIcon
switcherIcon={switcher}
/>
Posición de árbol
Cuatro valores placement Especifique la ubicación preferida de la ventana emergente. classNames.popup.root Agrega una clase de marco de panel.
<script lang="ts">
import { TreeSelect, type TreeSelectNode } from '@woodger/antd';
const treeData: TreeSelectNode[] = [
{ value: 'ui', title: "Interfaz", selectable: false, children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] },
{ value: 'data', title: "Datos", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Sección no disponible", disabled: true }
];
const placements = ['topLeft', 'topRight', 'bottomLeft', 'bottomRight'] as const;
</script>
<style>
.examples {
display: grid;
gap: 16px;
}
:global(.tree-select-example-popup) {
outline: 2px solid var(--ant-color-primary);
outline-offset: 2px;
}
</style>
<div class="examples">
{#each placements as placement (placement)}
<TreeSelect
aria-label={("Posición de árbol " + String((placement)) + "")}
{treeData}
{placement}
classNames={{ popup: { root: 'tree-select-example-popup' } }}
placeholder={(placement)}
/>
{/each}
</div>
popupAlign.offset: [16, 12]
builtinPlacements: Indentación del panel 16 px
Alineación del panel TreeSelect
PopupAlign Cambios de compensación, builtinPlacements Reemplaza el mapa de posición. Compare la sangría de dos campos.
<script lang="ts">
import { TreeSelect, type TreeSelectPopupAlign } from '@woodger/antd';
const treeData = [{ value: 'ui', title: 'UI', children: [
{ value: 'button', title: 'Button' },
{ value: 'input', title: 'Input' }
] }];
const overflow = { adjustX: true, adjustY: true };
const placements = {
bottomLeft: { points: ['tl', 'bl'], offset: [0, 16], overflow },
bottomRight: { points: ['tr', 'br'], offset: [0, 16], overflow },
topLeft: { points: ['bl', 'tl'], offset: [0, -16], overflow },
topRight: { points: ['br', 'tr'], offset: [0, -16], overflow }
} satisfies Readonly<Record<string, TreeSelectPopupAlign>>;
</script>
<style>
.examples {
display: grid;
gap: 20px;
}
p { margin: 0 0 8px; }
</style>
<div class="examples">
<div>
<p><code>popupAlign.offset: [16, 12]</code></p>
<TreeSelect
aria-label={("Desplazamiento del panel TreeSelect")}
{treeData}
placement="bottomLeft"
popupAlign={{ offset: [16, 12] }}
placeholder={("Seleccionar componente")}
treeDefaultExpandAll
/>
</div>
<div>
<p><code>builtinPlacements</code>: {("Indentación del panel 16 px")}</p>
<TreeSelect
aria-label={("TreeSelect")}
{treeData}
placement="bottomLeft"
builtinPlacements={placements}
placeholder={("Seleccionar componente")}
treeDefaultExpandAll
/>
</div>
</div>
Animación de panel TreeSelect
Transición estándar, nombre propio CSS y animation. vacío transitionName deshabilita la transición con nombre; animation tiene prioridad.
<script lang="ts">
import { RadioGroup, TreeSelect, type TreeSelectValue } from '@woodger/antd';
const treeData = [{ value: 'ui', title: 'UI', children: [
{ value: 'button', title: 'Button' },
{ value: 'input', title: 'Input' }
] }];
let mode = $state('default');
let value = $state<TreeSelectValue>(['button']);
let search = $state('');
const animation = $derived(mode === 'animation' ? 'fade' : undefined);
const transitionName = $derived.by(() => {
if (mode === 'default') {
return undefined;
}
if (mode === 'transition') {
return 'tree-select-example-fade';
}
return '';
});
</script>
<style>
.controls { margin-bottom: 16px; }
:global(.tree-select-example-fade-appear),
:global(.tree-select-example-fade-enter),
:global(.tree-select-example-motion-dropdown-fade-appear),
:global(.tree-select-example-motion-dropdown-fade-enter) {
opacity: 0;
}
:global(.tree-select-example-fade-appear-active),
:global(.tree-select-example-fade-enter-active),
:global(.tree-select-example-motion-dropdown-fade-appear-active),
:global(.tree-select-example-motion-dropdown-fade-enter-active) {
animation: tree-select-example-show var(--ant-motion-duration-mid, .2s) ease both;
}
:global(.tree-select-example-fade-leave-active),
:global(.tree-select-example-motion-dropdown-fade-leave-active) {
animation: tree-select-example-hide var(--ant-motion-duration-mid, .2s) ease both;
}
@keyframes tree-select-example-show {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes tree-select-example-hide {
from { opacity: 1; }
to { opacity: 0; }
}
</style>
<div class="controls">
<RadioGroup
aria-label={("Transición de panel TreeSelect")}
options={([
{ value: 'default', label: "Transición estándar" },
{ value: 'transition', label: 'transitionName' },
{ value: 'animation', label: 'animation' },
{ value: 'none', label: "Sin animación" }
])}
bind:value={mode}
/>
</div>
<TreeSelect
aria-label={("TreeSelect Animación de panel")}
prefixCls="tree-select-example-motion"
{treeData}
{value}
{animation}
{transitionName}
multiple
treeDefaultExpandAll
classNames={{ popup: { root: 'tree-select-example-motion-popup' } }}
showSearch={{
searchValue: search,
treeNodeFilterProp: 'title',
onSearch: next => { search = next; }
}}
onChange={next => { value = next; }}
/>
Opciones de diseño
outlined, filled, borderless y underlined usan una selección de árbol y nodo.
<script lang="ts">
import { TreeSelect, type TreeSelectNode } from '@woodger/antd';
const treeData: TreeSelectNode[] = [
{ value: 'ui', title: "Interfaz", selectable: false, children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] },
{ value: 'data', title: "Datos", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Sección no disponible", disabled: true }
];
const variants = ['outlined', 'filled', 'borderless', 'underlined'] as const;
</script>
<style>
.examples {
display: grid;
gap: 16px;
}
</style>
<div class="examples">
{#each variants as variant (variant)}<TreeSelect aria-label={("Opción TreeSelect " + String((variant)) + "")} {treeData} {variant} placeholder={(variant)} />{/each}
</div>
Estado de validación
error y warning Establecer el estado. Un campo completamente inaccesible y un nodo inaccesible se muestran por separado.
<script lang="ts">
import { TreeSelect, type TreeSelectNode } from '@woodger/antd';
const treeData: TreeSelectNode[] = [
{ value: 'ui', title: "Interfaz", selectable: false, children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] },
{ value: 'data', title: "Datos", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Sección no disponible", disabled: true }
];
</script>
<style>
.examples {
display: grid;
gap: 16px;
}
</style>
<div class="examples">
<TreeSelect
aria-label={("Error")}
{treeData}
status="error"
placeholder={("Error")}
/>
<TreeSelect
aria-label={("Secciones de advertencia")}
{treeData}
multiple
status="warning"
placeholder={("Advertencia")}
/>
<TreeSelect
aria-label={("Árbol no disponible")}
{treeData}
disabled
defaultValue="button"
/>
</div>
Dimensiones
large, medium y small. El campo sin size local hereda la configuración de la partición.
<script lang="ts">
import { TreeSelect, type TreeSelectNode } from '@woodger/antd';
const treeData: TreeSelectNode[] = [
{ value: 'ui', title: "Interfaz", selectable: false, children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] },
{ value: 'data', title: "Datos", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Sección no disponible", disabled: true }
];
const sizes = ['large', 'medium', 'small'] as const;
</script>
<style>
.examples {
display: grid;
gap: 16px;
}
</style>
<div class="examples">
{#each sizes as size (size)}<TreeSelect aria-label={("Tamaño TreeSelect " + String((size)) + "")} {treeData} {size} placeholder={(size)} />{/each}
</div>
etiqueta propia de nodo
treeTitleRender — Svelte Fragmento. Cambia la etiqueta en el árbol y el valor seleccionado, guardando la clave.
<script lang="ts">
import type { Snippet } from 'svelte';
import { Button, Flex, TreeSelect, type TreeSelectNode } from '@woodger/antd';
let mounted = $state(true);
let savedLabel = $state<Snippet>();
const treeData: TreeSelectNode[] = [
{ value: 'ui', title: "Interfaz", selectable: false, children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] },
{ value: 'data', title: "Datos", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Sección no disponible", disabled: true }
];
</script>
{#snippet title(node: TreeSelectNode)}
<span>
{#if typeof node.title === 'function'}
{@render node.title()}
{:else}
{(node.title)}
{/if}
{#if node.children}
<small>({(node.children.length)})</small>
{/if}
</span>
{/snippet}
<Flex vertical align="start" gap="medium">
{#if mounted}
<TreeSelect
aria-label={("Árbol con etiquetas")}
{treeData}
treeDefaultExpandAll
treeTitleRender={title}
defaultValue="button"
onChange={(_value, labels) => {
const label = labels?.[0];
savedLabel = typeof label === 'function' ? label : undefined;
}}
/>
{/if}
<Button
onclick={() => { mounted = !mounted; }}
>{("Mostrar u ocultar TreeSelect")}</Button>
</Flex>
<output
aria-label={("etiqueta guardada TreeSelect")}
>{#if savedLabel}{@render savedLabel()}{/if}</output>
<style>
output {
display: block;
margin-top: 12px;
}
</style>
fieldNames
treeDataSimpleMode
Esquema propio y datos planos
fieldNames Compara los campos del registro; treeDataSimpleMode Construye jerarquía id/pId. Devolución de llamada Obtiene los campos originales.
<script lang="ts">
import { TreeSelect } from '@woodger/antd';
interface Entry { code: string; caption: string; payload: { section: string }; nodes?: Entry[] }
const records: Entry[] = [{ code: 'ui', caption: 'UI', payload: { section: 'ui' }, nodes: [
{ code: 'button', caption: 'Button', payload: { section: 'ui' } }
] }];
const flat = [
{ id: 1, pId: 0, value: 'ui', title: 'UI' },
{ id: 2, pId: 1, value: 'button', title: 'Button' }
];
let selected = $state('');
</script>
<div class="examples">
<div>
<p>fieldNames</p>
<TreeSelect aria-label={("Campos propios TreeSelect")} treeData={records}
fieldNames={{ value: 'code', label: 'caption', children: 'nodes' }} treeDefaultExpandAll
showSearch={{ treeNodeFilterProp: 'caption' }}
onSelect={(
_value,
node
) => { selected = node ? `${node.code}: ${node.payload.section}` : ''; }} />
<output aria-label={("Entrada original TreeSelect")}>{selected}</output>
</div>
<div>
<p>treeDataSimpleMode</p>
<TreeSelect aria-label={("Datos planos TreeSelect")} treeData={flat}
treeDataSimpleMode={{ rootPId: 0 }} treeDefaultExpandAll />
</div>
</div>
<style>.examples {
display: grid;
gap: 16px;
} p {
margin: 0 0 8px;
} output {
display: block;
margin-top: 8px;
}</style>
Ranuras de campo y panel TreeSelect
prefix, suffix, icono de limpieza y popupRender. El campo dentro del panel guarda el borrador al reabrir.
<script lang="ts">
import type { Snippet } from 'svelte';
import { TreeSelect, Input, type TreeSelectSuffixInfo } from '@woodger/antd';
let draft = $state('');
const treeData = [{ value: 'ui', title: 'UI', children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] }];
</script>
{#snippet popup(menu: Snippet)}
{@render menu()}
<div class="popup-footer">
<Input aria-label={("Borrador TreeSelect")} bind:value={draft} />
</div>
{/snippet}
{#snippet suffix(info: TreeSelectSuffixInfo)}<span
aria-hidden="true"
>{info.open ? '▴' : '▾'}</span>{/snippet}
<TreeSelect aria-label={("Panel propio TreeSelect")} {treeData} treeDefaultExpandAll
prefix="UI" {suffix} popupRender={popup}
allowClear={{ clearIcon: '×', label: ("Borrar TreeSelect") }}
showSearch={{ treeNodeFilterProp: 'title' }} />
<style>
.popup-footer {
padding: 8px;
border-top: 1px solid var(--ant-color-border-secondary);
}
</style>
Semantic styles TreeSelect
Ajustes ConfigProvider, Función styles, placeholder y fragmentos de conmutador. La ranura local superpone los estilos del proveedor.
<script lang="ts">
import { ConfigProvider, TreeSelect } from '@woodger/antd';
let outlined = $state(true);
const treeData = [{ value: 'ui', title: 'UI', children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] }];
</script>
<label><input
type="checkbox"
bind:checked={outlined}
/>{("Seleccionar panel TreeSelect")}</label>
{#snippet placeholder()}<em>{("Seleccionar componente")}</em>{/snippet}
{#snippet switcher(node: { expanded: boolean })}<span
aria-hidden="true"
>{node.expanded ? '−' : '+'}</span>{/snippet}
<ConfigProvider treeSelect={{
variant: 'filled', switcherIcon: switcher,
styles: { popup: { root: 'border:1px solid var(--ant-color-primary-border)' } }
}}>
<TreeSelect
aria-label={("Diseño TreeSelect")}
{treeData}
{placeholder}
treeDefaultExpandAll
classNames={{ popup: { root: 'tree-select-semantic-popup' } }}
styles={({ props }) => ({
root: props.variant === 'filled' ? 'border-radius:8px' : undefined,
popup: {
root: outlined
? `
outline: 2px solid var(--ant-color-primary);
outline-offset: 2px;
`
: 'outline:none'
}
})}
/>
</ConfigProvider>
<style>
label {
display: block;
margin-bottom: 16px;
}
</style>
Árbol grande TreeSelect
600 nodos, ConfigProvider.virtual, estimación de altura de fila y desplazándose hasta la clave a través de TreeSelectRef.
<script lang="ts">
import { tick } from 'svelte';
import {
Button,
ConfigProvider,
TreeSelect,
type TreeSelectRef,
type TreeScrollConfig
} from '@woodger/antd';
const treeData = Array.from({ length: 600 }, (_, index) => ({
value: index,
title: `Node ${index}`
}));
let control = $state<TreeSelectRef>();
let opened = $state(false);
let virtual = $state(true);
async function scrollTo(config: TreeScrollConfig) {
opened = true;
await tick();
control?.scrollTo(config);
control?.focus();
}
</script>
<div class="controls">
<label><input type="checkbox" bind:checked={virtual} />ConfigProvider.virtual</label>
<Button onclick={() => { opened = true; }} >{("Abrir un árbol grande")}</Button>
<Button onclick={() => scrollTo({ key: 480, align: 'top' })}>scrollTo 480</Button>
<Button onclick={() => scrollTo({ top: 0 })}>{("Al comienzo del árbol")}</Button>
</div>
<ConfigProvider {virtual} popupMatchSelectWidth={true}>
<TreeSelect bind:this={control} aria-label={("Virtual TreeSelect")}
{treeData} open={opened} onOpenChange={next => { opened = next; }}
listHeight={224} listItemHeight={28} listItemScrollOffset={4}
showSearch={{ treeNodeFilterProp: 'title' }} />
</ConfigProvider>
<style>.controls {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
margin-bottom: 16px;
}</style>
Nodos declarativos TreeSelect
TreeSelect.TreeNode y con nombre TreeSelectTreeNode, estrategia estática, iconos y diseño de líneas.
<script lang="ts">
import { TreeSelect, TreeSelectTreeNode, type TreeEventNode } from '@woodger/antd';
</script>
{#snippet icon(node: TreeEventNode)}<span
aria-hidden="true"
>{node.isLeaf ? '•' : '▣'}</span>{/snippet}
{#snippet switcher(node: TreeEventNode)}<span
aria-hidden="true"
>{node.expanded ? '−' : '+'}</span>{/snippet}
<TreeSelect
aria-label={("Nodos declarativos TreeSelect")}
treeCheckable
treeDefaultExpandAll
showCheckedStrategy={TreeSelect.SHOW_PARENT}
treeIcon
switcherIcon={switcher}
>
<TreeSelect.TreeNode value="ui" title="UI" {icon}>
<TreeSelect.TreeNode value="button" title="Button" {icon} isLeaf
class="tree-select-featured-node" style="font-weight:600" data-component="button" />
<TreeSelectTreeNode value="input" title="Input" {icon} isLeaf />
</TreeSelect.TreeNode>
</TreeSelect>
Enfoque y Eventos TreeSelect
showAction Abre el árbol Enfoque. El registro muestra el orden de las devoluciones de llamada nativas, input y raíz y la cancelación de entrada.
<script lang="ts">
import { Button, TreeSelect, type TreeSelectRef, type TreeSelectValue } from '@woodger/antd';
const treeData = [{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }];
let control = $state<TreeSelectRef>();
let focusAction = $state(true);
let mode = $state('multiple');
let searchable = $state(false);
let cancellation = $state('none');
let value = $state<TreeSelectValue>([]);
let events = $state<string[]>([]);
function record(kind: string, event?: Event) {
const target = event?.currentTarget instanceof Element
? event.currentTarget.tagName
: '';
const key = event instanceof KeyboardEvent ? event.key : '';
events = [...events, [kind, key, target].filter(Boolean).join(' ')].slice(-12);
}
</script>
<div class="controls">
<label>{("Modo de campo de eventos")} <select value={mode} onchange={event => {
mode = event.currentTarget.value;
value = mode === 'multiple' ? [] : null;
}}>
<option value="single">single</option>
<option value="multiple">multiple</option>
</select></label>
<label><input
type="checkbox"
bind:checked={searchable}
/>{("Búsqueda en el campo de evento")}</label>
<label><input type="checkbox" bind:checked={focusAction} />showAction=['focus']</label>
<label>{("Cancelar Ingrese")} <select bind:value={cancellation}>
<option value="none">{("No cancelar")}</option>
<option value="native">onkeydown.preventDefault()</option>
<option value="hook">onInputKeyDown.preventDefault()</option>
</select></label>
<Button onclick={() => control?.focus()}>{("Enfoque de campo TreeSelect")}</Button>
<Button onclick={() => { events = []; }}>{("Borrar registro de eventos")}</Button>
</div>
<TreeSelect
bind:this={control}
aria-label={("Eventos TreeSelect")}
{treeData}
{value}
multiple={mode === 'multiple'}
showSearch={searchable}
allowClear
tabIndex={0}
showAction={focusAction ? ['focus'] : []}
onOpenChange={open => record(`open=${open}`)}
onChange={next => { value = next ?? (mode === 'multiple' ? [] : null); record('change'); }}
onkeydown={event => {
record('native', event);
if (cancellation === 'native' && event.key === 'Enter') event.preventDefault();
}}
onInputKeyDown={event => {
record('input', event);
if (cancellation === 'hook' && event.key === 'Enter') event.preventDefault();
}}
onKeyDown={event => record('root', event)}
onKeyUp={event => record('keyup', event)}
onFocus={event => record('focus', event)}
onBlur={event => record('blur', event)}
onMouseDown={event => record('mousedown', event)}
onClick={event => record('click', event)}
onMouseEnter={event => record('mouseenter', event)}
onMouseLeave={event => record('mouseleave', event)}
/>
<p><output
aria-label={("Selección en ejemplos de eventos")}
>{JSON.stringify(value)}</output></p>
<pre aria-label={("Registro de eventos TreeSelect")}>{events.join('\n')}</pre>
<style>
.controls {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
margin-bottom: 16px;
}
label { min-width: 0; }
select { max-width: 100%; }
pre {
min-height: 4em;
max-height: 12em;
overflow: auto;
white-space: pre-wrap;
overflow-wrap: anywhere;
font-size: 12px;
}
</style>
Seleccionado:
nativeElement:
Raíz propia TreeSelect
components.root Reemplaza el campo por completo. Button obtiene atributos y registra el DOM; La etiqueta y el aria son fijados por el propietario.
RootTreeSelect.svelte<script lang="ts"> import { Button, Checkbox, TreeSelect, type TreeSelectRef, type TreeSelectRootContext, type TreeSelectValue } from '@woodger/antd'; import ComponentButton from './ComponentButton.svelte'; const treeData = [{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }]; let value = $state<TreeSelectValue>(null); let open = $state(false); let custom = $state(true); let control = $state<TreeSelectRef>(); let nativeElement = $state<HTMLButtonElement | HTMLDivElement>(); const label = $derived.by(() => { const selectedNode = treeData.find(node => node.value === value); const title = selectedNode?.title; return title ?? ("Seleccionar componente"); }); </script> {#snippet root(context: TreeSelectRootContext<HTMLButtonElement>)} <ComponentButton {context} {label} /> {/snippet} <div class="controls"> <Checkbox bind:checked={custom}>{("Raíz propia TreeSelect")}</Checkbox> <Button onclick={() => control?.focus()}>{("Enfoque raíz TreeSelect")}</Button> <Button onclick={() => { value = null; open = false; }} >{("Restablecer raíz")}</Button> </div> <TreeSelect id="tree-select-components-root" aria-label={("Selección a través de su propia raíz")} {treeData} {value} {open} bind:this={control} bind:nativeElement onOpenChange={next => { open = next; }} onChange={next => { value = next ?? null; }} components={custom ? { root: { render: root, props: { id: 'tree-select-components-root', 'aria-haspopup': 'tree', 'aria-expanded': open, 'aria-controls': open ? 'tree-select-components-root-list' : undefined } } } : undefined} /> <p>{("Seleccionado: ")}<output aria-label={("Selección de raíz propia")}>{JSON .stringify(value)}</output></p> <p>nativeElement: <output aria-label={("Dom raíz propia")}>{nativeElement ?.tagName ?? '—'}</output></p> <style> .controls { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; margin-bottom: 16px; } </style>ComponentButton.svelte<script lang="ts"> import { Button, type ButtonProps, type TreeSelectRootContext } from '@woodger/antd'; let { context, label }: { context: TreeSelectRootContext<HTMLButtonElement>; label: string } = $props(); let element = $state<HTMLButtonElement | HTMLAnchorElement>(); const register = $derived(context.register); const buttonProps = $derived.by<ButtonProps>(() => { const { type, color: _nativeColor, class: className, ...attributes } = context.attributes; return { ...attributes, class: className == null ? undefined : String(className), htmlType: type ?? 'button' }; }); $effect(() => { if (element instanceof HTMLButtonElement) { return register(element); } }); </script> <Button {...buttonProps} block bind:nativeElement={element}>{label}</Button>
Seleccionado:
inputElement:
Editor propio TreeSelect
components.input Sólo reemplaza al editor. TextArea guarda etiquetas y colocación receptiva; La revista muestra propiedades, devoluciones de llamada nativas, de gancho y raíz.
<script lang="ts">
import {
Checkbox,
TreeSelect,
type TreeSelectInputContext,
type TreeSelectValue
} from '@woodger/antd';
const treeData = [{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }, {
value: 'table',
title: 'Table'
}];
let value = $state<TreeSelectValue>(['button', 'input']);
let search = $state('');
let custom = $state(true);
let inputElement = $state<HTMLInputElement | HTMLTextAreaElement>();
let events = $state<string[]>([]);
function record(kind: string, event: KeyboardEvent) {
const tag = event.currentTarget instanceof Element
? event.currentTarget.tagName
: '';
events = [...events, `${kind} ${event.key} ${tag}`].slice(-8);
}
</script>
{#snippet editor({ attributes, register }: TreeSelectInputContext<HTMLTextAreaElement>)}
<textarea {...attributes} rows={1} {@attach register}></textarea>
{/snippet}
<div class="controls">
<Checkbox bind:checked={custom}>
{("Editor de área de texto en TreeSelect")}
</Checkbox>
</div>
<TreeSelect
aria-label={("Selección con propia Editor")}
{treeData}
{value}
multiple
maxTagCount="responsive"
bind:inputElement
onChange={next => { value = next ?? []; search = ''; }}
showSearch={{
searchValue: search,
treeNodeFilterProp: 'title',
onSearch: next => { search = next; }
}}
components={custom ? {
input: {
render: editor, props: {
onkeydown: event => record(
'props',
event
)
}
}
} : undefined}
onkeydown={event => record('native', event)}
onInputKeyDown={event => record('hook', event)}
onKeyDown={event => record('root', event)}
/>
<p>{("Seleccionado: ")}<output
aria-label={("Selección de editor propio")}
>{JSON.stringify(value)}</output></p>
<p>inputElement: <output aria-label={("Editor propio DOM")}>{inputElement
?.tagName
?? '—'}</output></p>
<pre aria-label={("Ordenador del Editor")}>{events.join('\n')}</pre>
<style>
.controls { margin-bottom: 16px; }
textarea { resize: none; }
pre {
max-height: 8em;
overflow: auto;
white-space: pre-wrap;
overflow-wrap: anywhere;
font-size: 12px;
}
</style>
Editor propio en el formulario
Input Registrar compuesto ref con focus/blur. Form Guarda el nodo seleccionado, comprueba el campo y vuelve a crear el editor en reset.
ComponentsFormTreeSelect.svelte<script lang="ts"> import { Button, Form, FormItem, TreeSelect, createForm, type TreeSelectInputContext, type TreeSelectValue } from '@woodger/antd'; import ComponentInput from './ComponentInput.svelte'; const form = createForm<{ component: TreeSelectValue }>({ initialValues: { component: null } }); const treeData = [{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }]; let result = $state('—'); </script> {#snippet editor(context: TreeSelectInputContext<HTMLInputElement>)}<ComponentInput {context} />{/snippet} <Form {form} aria-label={("Formulario con editor propio TreeSelect")} onFinish={values => { result = JSON.stringify(values.component); }} > <FormItem name="component" label={("Componente con editor propio")} rules={([{ required: true, message: "Seleccione un componente en el campo Editor." }])} > <TreeSelect {treeData} value={form.values.component} components={{ input: editor }} showSearch={{ treeNodeFilterProp: 'title' }} onChange={next => form.setFieldValue( 'component', next ?? null )} /> </FormItem> <div class="actions"> <Button htmlType="submit" type="primary">{("Guardar componente")}</Button> <Button onclick={() => form.focusField('component')}> {("Editor foco a través del formulario")} </Button> <Button htmlType="reset" onclick={() => { result = '—'; }} >{("Restablecer componente")}</Button> </div> </Form> <p><output aria-label={("Resultado del formulario con")}>{result}</output></p> <style> .actions { display: flex; flex-wrap: wrap; gap: 12px; } </style>ComponentInput.svelte<script lang="ts"> import { Input, type TreeSelectInputContext } from '@woodger/antd'; let { context }: { context: TreeSelectInputContext<HTMLInputElement> } = $props(); let input = $state<HTMLInputElement>(); let nativeElement = $state<HTMLElement>(); let control = $state<{ focus(options?: FocusOptions): void; blur(): void }>(); const register = $derived(context.register); const inputProps = $derived.by(() => { const { value, defaultValue, size, class: className, ...attributes } = context.attributes; return { ...attributes, value: String(value ?? ''), defaultValue: defaultValue === undefined ? undefined : String(defaultValue), class: className == null ? undefined : String(className), htmlSize: size ?? undefined }; }); $effect(() => { const editor = input, root = nativeElement, instance = control; if (!editor || !root || !instance) { return; } return register({ inputElement: editor, nativeElement: root, focus: options => instance.focus(options), blur: () => instance.blur() }); }); </script> <Input {...inputProps} bind:inputElement={input} bind:nativeElement bind:this={control} />
Suscripción de la sección en el Formulario
Formulario original de la revisión: marcas relacionadas, búsqueda, selección requerida, submit y reset. Form Las tiendas dejan llaves.
<script lang="ts">
import { TreeSelect, Form, FormItem, Button, createForm } from '@woodger/antd';
const data = [
{
value: 'components',
title: "Componentes",
children: [
{ value: 'button', title: 'Button' },
{ value: 'input', title: 'Input' },
{ value: 'select', title: 'Select' }
]
},
{
value: 'docs',
title: "Documentación",
children: [{ value: 'start', title: "Primeros pasos" }]
}
];
const form = createForm<{ topics: string[] }>(
{
initialValues: { topics: ['button'] },
rules: ({ topics: [{ required: true, message: "Seleccionar secciones." }] })
}
);
let result = $state('');
</script>
<style>
output {
display: block;
margin-top: 16px;
}
</style>
<div style="
max-width: 640px;
min-width: 0;
">
<Form {form} onFinish={values => { result = values.topics.join(', '); }}>
<FormItem name="topics" label={("Suscripción de la sección")}><TreeSelect
treeData={data}
value={form.values.topics}
treeCheckable
treeDefaultExpandAll
showSearch={{ treeNodeFilterProp: 'title' }}
allowClear
placeholder={("Seleccionar secciones")}
onChange={next => form.setFieldValue('topics', next)}
/></FormItem>
<div
style="
display: flex;
gap: 8px;
flex-wrap: wrap;
"
><Button
type="primary"
htmlType="submit"
>{("Guardar Secciones")}</Button><Button
htmlType="reset"
>{("Restablecer secciones")}</Button></div>
</Form>
<output aria-label={("Secciones guardadas")}>{result}</output>
</div>
Sin valor local, el control usa general -select, popup - common -tree-select-dropdown. Con prefixCls local, ambos usan el mismo espacio de nombres y la ventana emergente agrega -Dropdown. El árbol anidado guarda el adaptador de árbol nativo y sus propias clases: Prefijo local TreeSelect no es igual al árbol.prefixCls.
CSS Prefijo TreeSelect
Espacio de nombres general ConfigProvider y local prefixCls; El estado del componente se guarda al cambiar el nombre.
<script lang="ts">
import { Checkbox, ConfigProvider, TreeSelect, type TreeSelectValue } from '@woodger/antd';
let custom = $state(true);
let local = $state(true);
const prefix = $derived(custom ? 'suite' : 'ant');
const localPrefix = $derived(local ? 'project-tree-select' : '');
let value = $state<TreeSelectValue>(['docs']);
</script>
<style>
.example,
.prefix-stage {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 16px;
min-width: 0;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
p { margin: 0; }
output { overflow-wrap: anywhere; }
</style>
<div class="example">
<div class="controls">
<Checkbox bind:checked={custom}>{("Prefijo general TreeSelect Suite")}</Checkbox>
<Checkbox bind:checked={local}>{("Prefijo local TreeSelect")}</Checkbox>
</div>
<ConfigProvider prefixCls={prefix} theme={{ cssVar: { prefix: 'tree-select-theme' } }}>
<div class="prefix-stage">
<TreeSelect prefixCls={localPrefix} {value} onChange={next => value = next}
treeCheckable treeDefaultExpandAll showSearch={{ treeNodeFilterProp: 'title' }}
aria-label={("TreeSelect con")}
style="width:100%" treeData={[
{
value: 'project', title: "Proyecto", children: [
{ value: 'docs', title: "Documentación" }, { value: 'examples', title: "Ejemplos" }
]
}
]} />
<output
aria-label={("Seleccionar TreeSelect con prefijo")}
>{JSON.stringify(value)}</output>
</div>
</ConfigProvider>
<output
aria-label={("CSS-prefijo TreeSelect")}
>{("General: ")}{prefix}{("; Local: ")}{(localPrefix
|| ("del proveedor"))}</output>
<p>
{("Sin valor local, el control usa general -select, popup - common -tree-select-dropdown. Con prefixCls local, ambos usan el mismo espacio de nombres y la ventana emergente agrega -Dropdown. El árbol anidado guarda el adaptador de árbol nativo y sus propias clases: Prefijo local TreeSelect no es igual al árbol.prefixCls.")}
</p>
</div>
API
Temas principales TreeSelect y funciones adicionales públicas API. Se combinan los datos básicos y generados a partir de árboles; Algunos ejemplos muestran la alineación y animación del panel.
| Tema | Muestra o restricción |
|---|---|
| Basic / Generate from tree data | Jerarquía treeData; Los nodos declarativos se muestran por separado. |
| Multiple Selection | Selección independiente y eliminación de etiquetas. |
| Checkable | Related checkbox; Las estrategias adicionales y las estrictas se muestran por separado. |
| Contenido treeCheckable | El valor del indicador incluye marcas sin mostrar su contenido. |
| Asynchronous loading | Promise, actualización y limpieza de árboles. |
| Show Tree Line | Líneas, hojas y fragmento de conmutador. |
| Divulgación TreeSelect Encabezado | Tres modos treeExpandAction y controlados treeExpandedKeys. |
| Placement | Cuatro posiciones de panel. |
| Alineación del panel TreeSelect | Offset y mapa de posición propio. |
| Animación de panel TreeSelect | Transiciones estándar y nativas, deshabilitando la animación. |
| Variants | Cuatro diseños de campo. |
| Status | Error, advertencia y disabled. |
| Max Count | maxCount limita la elección; maxTagCount Límites solo etiquetas visibles. |
| Prefix and Suffix | prefix, suffix, suffixIcon, removeIcon y popupRender. |
| Custom semantic dom styling | Objetos y Funciones classNames/styles; Ajustes ConfigProvider.treeSelect. |
| Enfoque y Eventos TreeSelect | Apertura de enfoque, orden de devolución de llamada y cancelación del procesamiento del teclado. |
| Separadores de búsqueda | Matriz de delimitadores, función, insertar cadenas y guardar valores seleccionados. |
| Raíz propia TreeSelect | Reemplazo de campo completo, atributos, registro de DOM y retorno de raíz estándar. |
| Editor propio TreeSelect | TextArea en lugar de input, guardando etiquetas y encargados de pedidos. |
| Editor propio en el formulario | Compuesto ref Biblioteca Input Enfoque de campo, validación y reset. |
| Virtual list | Cadenas virtuales y scrollTo por tecla. |
| TreeNode | Anuncios, iconos y atributos de cadena. |
| Tags | Abreviatura y colocación de etiqueta receptiva. |
| Data schemas | Campos propios y lista plana. |
| Propiedad | Descripción | Tipo | Predeterminado |
|---|---|---|---|
components | Root reemplaza completamente el selector y tiene prioridad sobre la entrada. La entrada reemplaza al editor guardando etiquetas y afijos. Snippet obtiene atributos/registro; El objeto también toma propiedades. | TreeSelectComponents<RootElement, EditorElement> | undefined |
tokenSeparators | ReadOnly-Array de (text: string) => string[]. La partición borra la búsqueda y cierra el panel sin onChange/onSelect; IME espera compositionend. | TreeSelectTokenSeparators | undefined |
showScrollBar | se acepta por compatibilidad, pero no se pasa al árbol y no cambia de desplazamiento. | boolean | "optional" | undefined |
showAction | Enfoque añade una apertura de enfoque. matriz vacía y click guardar apertura con puntero; Cambiar los propiedades con el enfoque ya establecido no abre el panel. | ('focus' | 'click')[] | undefined |
autoFocus | autofoco de campo después del montaje; Nativo autofocus tiene prioridad. La hidratación conserva el foco de otro control. | boolean | undefined |
tabIndex | Orden de enfoque del teclado; Nativo tabindex tiene prioridad. | number | undefined |
maxLength | Como en el original, no limita la búsqueda TreeSelect. Para DOM, use nativo maxlength. | number | undefined |
onInputKeyDown | Campo de gancho después de onkeydown nativo. Su preventDefault no cancela la elección; Para cancelar, use nativo onkeydown. | DOMAttributes<EditorElement | HTMLInputElement>['onkeydown'] | undefined |
onKeyDown | Devolución de llamada del teclado raíz después del procesamiento interno. onKeyUp Informa la liberación de la llave. | DOMAttributes<RootElement | HTMLDivElement>['onkeydown'] | undefined |
onFocus | Real focusin; onBlur obtiene focusout. currentTarget Corresponde a la raíz DOM, div predeterminado. | DOMAttributes<RootElement | HTMLDivElement>['onfocusin'] | undefined |
onMouseDown | Evento de control de raíces; también apoyado onClick, onMouseEnter y onMouseLeave. | DOMAttributes<RootElement | HTMLDivElement>['onmousedown'] | undefined |
styles | CSS ranuras semánticas; Las ranuras emergentes locales reemplazan los estilos apropiados del proveedor. | TreeSelectSemanticValue<TreeSelectStyles> | undefined |
children | TreeSelect.TreeNode o TreeSelectTreeNode; treeData tiene prioridad sobre los anuncios. | Snippet | undefined |
fieldNames | Nombres de campo value, label y children. Para buscar su etiqueta explícitamente establecido treeNodeFilterProp. | TreeSelectFieldNames | value / label / children |
treeDataSimpleMode | Construcciones children por id/pId; rootPId Especifica el padre de las raíces. El nombre children sigue siendo estándar. | boolean | TreeSelectSimpleModeConfig | false |
maxTagCount | Número de etiquetas visibles. Todos los valores seleccionados se almacenan en callbacks y FormData. | number | "responsive" | undefined |
maxTagTextLength | Texto de etiquetas de accesos directos; tooltip y las devoluciones de llamada guardan la etiqueta completa. | number | undefined |
maxTagPlaceholder | Contenido de contador o fragmento con registros omitidos y sellos completos. | TreeSelectTagPlaceholder | + N ... |
tagRender | label — Fragmento; closable/onClose Gestionar la eliminación. El resumen tiene isMaxTag=true sin value/index/onClose. | Snippet<[TreeSelectTagInfo]> | undefined |
popupRender | Panel propio; Llamar menu() Guarda el árbol original. Los campos anidados pueden obtener el foco. | Snippet<[Snippet]> | undefined |
prefix | Contenido frente al campo. | TreeSelectLabel | undefined |
suffix | Contenido o fragmento con open, enfocado, searchValue, showSearch y loading; tiene prioridad sobre suffixIcon. | TreeSelectSuffix | undefined |
suffixIcon | Insignia propia; null Oculta la flecha. | TreeSelectLabel | Flecha estándar |
removeIcon | Icono de eliminación de etiquetas regular. tagRender Establece su propio margen de beneficio. | TreeSelectLabel | × |
placeholder | Campo vacío de texto, número, matriz o fragmento. | TreeSelectLabel | undefined |
virtual | Virtualización de cadenas. popupMatchSelectWidth=false lo desactiva. | boolean | ConfigProvider.virtual / true |
listItemHeight | Estimación de altura de línea inicial; 0 Deshabilita la virtualización. | number | controlHeightSM + paddingXXS |
listItemScrollOffset | sangría adicional al pasar al nodo activo. | number | 0 |
popupMatchSelectWidth | true establece el ancho del campo, false — ancho por contenido y deshabilita la virtualización. conjuntos de números px; El ancho del campo sigue siendo el mínimo. undefined hereda ConfigProvider. | boolean | number | ConfigProvider / true |
treeIcon | Incluye iconos del nodo icon. La función se utiliza como bandera, el contenido establece el nodo. | TreeSelectNodeIcon | false |
switcherIcon | Contenido o fragmento con TreeEventNode. El valor local se superpone al proveedor; false Deja un interruptor vacío. | TreeSelectSwitcherIcon | ConfigProvider.treeSelect |
prefixCls | Prefijo local completo Select control y TreeSelect Popup. Sin él, se utilizan -select y -tree-select comunes; Con él, ambos obtienen un espacio de nombres. Nativo Tree Adaptador almacena sus propias clases. | string | ConfigProvider.prefixCls + "-select" |
classNames | Campo, etiqueta y ventana emergente; objeto o función con info.props. | TreeSelectSemanticValue<TreeSelectClassNames> | undefined |
treeData | Jerarquía con value único. Sus campos son compatibles, icon, switcherIcon, class/style, data-* y aria-*. | readonly Data[] | [] |
value | Clave administrada, objeto de etiqueta o matriz. Al despejar solo, tome undefined como null para mantener el modo controlado. bind:value No compatible. | TreeSelectValue | undefined |
defaultValue | Inicie el valor local, lea una vez. | TreeSelectValue | undefined |
onChange | Nuevo valor y extra.triggerValue. treeTitleRender devuelve label-fragmentos; en labelInValue están en value y las etiquetas son null. | (value, labels, extra) => void | — |
multiple | Selección independiente de múltiples nodos. treeCheckable y treeCheckStrictly también incluyen multiple. | boolean | false |
treeCheckable | El valor se utiliza como bandera: Truthy incluye la casilla de verificación estándar y multiple. Una matriz vacía y un fragmento incluyen marcas; No se muestra el contenido. | TreeSelectCheckableContent | false |
maxCount | Límite multiple incluyendo la casilla de verificación/estricta y valores desconocidos. No corta el conjunto de inicio. Show_Parent explícito y Show_all sin límite de inhabilitación estricto discapacitado; 0 prohíbe una nueva opción. en sencillo no se aplica. | number | undefined |
treeCheckStrictly | casilla de verificación independiente y automática labelInValue. | boolean | false |
showCheckedStrategy | Administrar etiquetas y el resultado de una selección relacionada. sin treeCheckable Usar show_all. | SHOW_ALL | SHOW_PARENT | SHOW_CHILD | Show_child en treeCheckable |
labelInValue | Objetos { value, label, halfChecked? } en lugar de teclas simples. | boolean | false |
showSearch | El objeto contiene searchValue, onSearch, filterTreeNode, treeNodeFilterProp y autoClearSearchValue. Para buscar por etiqueta, especifique title. | boolean | TreeSelectSearchConfig | single: false; multiple: true |
loadData | Cargas children con actualización treeData. No se invoca durante la búsqueda. | (node) => PromiseLike<unknown> | — |
treeExpandedKeys | Divulgación gestionada con onTreeExpand; treeDefaultExpandedKeys y treeDefaultExpandAll Set Start. | readonly TreeKey[] | estado local |
treeExpandAction | Divulgación con título. Ctrl/Meta/Shift Suprime la apertura, manteniendo la selección. En el modo de clic onTreeExpand precede onChange/onSelect. | false | "click" | "doubleClick" | false |
treeLoadedKeys | Nodos cargados gestionados con onTreeLoad. | readonly TreeKey[] | estado local |
treeLine | Conexiones de árbol y pantalla de hojas. treeIcon Incluye iconos de nodos. | boolean | { showLeafIcon: TreeSelectSwitcherIcon } | false |
treeTitleRender | Contenido del nodo y etiquetas devueltas. Snippet se puede guardar y emitir después del campo de desmontaje. | Snippet<[Data]> | etiqueta de nodo |
allowClear | Limpieza y onClear. los conjuntos de objetos clearIcon y el nombre disponible label; La búsqueda no vacía se borra con onSearch. | boolean | TreeSelectAllowClear | false |
open | Popup gestionado con onOpenChange, defaultOpen Establece el inicio. | boolean | estado local |
listHeight | Altura del árbol de la ventana gráfica. onPopupScroll Obtiene este evento contenedor. | number | 256 |
placement | Lado emergente preferido. popupMatchSelectWidth Establece el ancho, getPopupContainer — contenedor. | topLeft | topRight | bottomLeft | bottomRight | en la dirección de la interfaz |
popupAlign | anula los campos de la posición seleccionada; offset, targetOffset y desbordamiento se reemplazan por completo. Las coordenadas se guardan hasta el evento de recálculo. | TreeSelectPopupAlign | undefined |
builtinPlacements | Reemplaza completamente el mapa de posición. Un objeto vacío no restaura registros estándar; La posición que falta centra el panel. | Readonly<Record<string, TreeSelectPopupAlign>> | undefined |
animation | El valor no vacío selecciona la transición del prefijo Select y el sufijo animation superposición transitionName. Para su propio nombre necesita CSS. | string | undefined |
transitionName | Nombre CSS Transición del panel. undefined Selecciona el deslizamiento estándar, la cadena vacía deshabilita la transición con nombre. | string | ConfigProvider.prefixCls + "-slide-up" |
onOpenChange | Reporta una solicitud para abrir o cerrar el panel. En el modo administrado, actualice open con este valor. | (open: boolean) => void | undefined |
onPopupVisibleChange | aceptado sin llamar. El cambio en el estado de los informes del panel onOpenChange. | (open: boolean) => void | undefined |
popupStyle | aceptado sin uso. El diseño del panel se establece a través de styles.popup.root. | string | undefined |
choiceTransitionName | se acepta pero el desbordamiento actual no aplica la animación de etiquetas. | string | undefined |
direction | se acepta sin cambiar de dirección. RTL y los conjuntos de posición predeterminados ConfigProvider; HTML DIR es un atributo separado. | ltr | rtl | ConfigProvider.direction |
size | Tamaño del campo; status — error o warning. | large | medium | small | de ConfigProvider |
variant | Prop. local → más cercano Form.variant → ConfigProvider.treeSelect.variant → General ConfigProvider.variant → outlined. | Variant | del contexto / delineado |
nativeElement | Ref de la raíz registrada. sin components.root devuelve la div; Cuando se borra el desmontaje. | RootElement | HTMLDivElement | — |
inputElement | Ref Editor: input o textarea. con components.root sin editor; Al quitar la ranura de entrada devuelve la entrada estándar. | EditorElement | HTMLInputElement | — |
Los tipos completos están en el paquete. ConfigProvider.treeSelect conjuntos variant, classNames, styles y switcherIcon. Las clases locales se combinan con la configuración del proveedor; Las ranuras locales CSS reemplazan los estilos correspondientes.
Métodos
vía bind:this disponible TreeSelectRef con focus(options?), blur() y scrollTo(config). Para acceder al DOM hay bind:inputElement y bind:nativeElement.
<script lang="ts">
import { Button, TreeSelect, type TreeSelectRef } from '@woodger/antd';
let control = $state<TreeSelectRef>();
</script>
<style>
.controls {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
}
</style>
<div class="controls">
<TreeSelect
bind:this={control}
aria-label={("Métodos TreeSelect")}
style="width:min(100%,240px)"
treeData={[{ value: 'docs', title: "Documentación" }]}
/>
<Button onclick={() => control?.focus()}>{("Enfoque TreeSelect")}</Button>
<Button onclick={() => control?.blur()}>{("Eliminar el enfoque TreeSelect")}</Button>
</div>
DOM y disponibilidad
Editor estándar tiene el cuadro combinado de roles, aria-haspopup="tree", aria-expanded, aria-controls y el niño activo. components.input Obtiene estos atributos en atributos; Para components.root la disponibilidad la establece el propietario. la ventana emergente contiene treeitem y casilla de verificación; El nombre de campo disponible se establece en aria-label o FormItem.
Flechas Mueve el nodo activo y abre ramas, enter selects, Escape cierra la ventana emergente. La búsqueda conserva la apariencia de los padres de los nodos coincidentes. Ramas no disponibles y selectable=false Limite las acciones correspondientes.
La clase de panel se establece a través de classNames.popup.root; Ejemplo de posición muestra su marco. classNames y styles Apoyo a las ranuras de campo, etiquetas y popup incluyendo funciones con info.props. treeTitleRender, icon y switcherIcon especifican el contenido de los nodos. Para hacer un árbol, use las fichas que se muestran a continuación.
Tokens de diseño
Los siete tokens de componentes se verifican con Ant.Design y se aplican a través de theme.components.TreeSelect. El campo exterior también utiliza tokens de componentes Select. Un proveedor anidado aísla el diseño de los ejemplos vecinos.
<script lang="ts">
import { ConfigProvider, TreeSelect } from '@woodger/antd';
</script>
<ConfigProvider theme={{
components: {
TreeSelect: {
titleHeight: 36,
switcherSize: 24,
indentSize: 28,
nodeHoverBg: '#f9f0ff',
nodeHoverColor: '#531dab',
nodeSelectedBg: '#722ed1',
nodeSelectedColor: '#fff'
}
}
}}>
<TreeSelect
aria-label={("Fichas TreeSelect")}
treeDefaultExpandAll
defaultValue="button"
style="width:min(100%,320px)"
treeData={[
{
value: 'ui', title: "Interfaz", children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
]
}
]}
/>
</ConfigProvider>
| Simbólico | Asignar |
|---|---|
indentSize | Acolchado a nivel de árbol. |
switcherSize | Ancho del área de interruptor de derivación. |
titleHeight | Altura de cadena de nodo. |
nodeHoverBg | Fondo del nodo al flotar. |
nodeHoverColor | Color del nodo al flotar. |
nodeSelectedBg | Fondo de nodo seleccionado. |
nodeSelectedColor | Color del nodo seleccionado. |
Tokens comunes del tema actual
Los valores se leen a través de theme.useToken() y responden a la configuración de la sección.
| Simbólico | Valor actual |
|---|---|
colorBgContainer | #ffffff |
colorBgContainerDisabled | rgba(0,0,0,0.04) |
colorBgElevated | #ffffff |
colorBgTextHover | rgba(0,0,0,0.06) |
colorBorder | #d9d9d9 |
colorFillQuaternary | rgba(0,0,0,0.02) |
colorPrimary | #2f54eb |
colorPrimaryBorder | #adc6ff |
colorPrimaryHover | #597ef7 |
colorSplit | rgba(5,5,5,0.06) |
colorText | rgba(0,0,0,0.88) |
colorTextDisabled | rgba(0,0,0,0.25) |
colorTextQuaternary | rgba(0,0,0,0.25) |
colorWhite | #fff |
borderRadius | 6 |
borderRadiusSM | 4 |
controlInteractiveSize | 16 |
controlItemBgActiveDisabled | rgba(0,0,0,0.15) |
controlItemBgHover | rgba(0,0,0,0.04) |
fontFamily | -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial,
'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol',
'Noto Color Emoji' |
fontSize | 14 |
fontSizeLG | 16 |
fontWeightStrong | 600 |
lineHeight | 1.5714285714285714 |
lineType | solid |
lineWidth | 1 |
lineWidthBold | 2 |
lineWidthFocus | 3 |
marginXS | 8 |
motion | true |
motionDurationFast | 0.1s |
motionDurationMid | 0.2s |
motionDurationSlow | 0.3s |
motionEaseInBack | cubic-bezier(0.71, -0.46, 0.88, 0.6) |
motionEaseOutBack | cubic-bezier(0.12, 0.4, 0.29, 1.46) |
paddingXS | 8 |
FAQ
¿Cómo conseguir el padre en onChange?
Coincidir con el value o extra.triggerValue seleccionado con el treeData original o con la tarjeta del padre. No se agrega la ruta completa en extra.
¿Por qué la búsqueda no causa loadData?
Búsqueda filtra el árbol conocido. Expanda la rama perezosa fuera de la búsqueda u organice una búsqueda de servidor a través de showSearch.onSearch y actualice treeData.
¿Por qué se seleccionan varios nodos a la vez?
treeCheckable Enlaza al padre con la descendencia e incluye multiple. treeCheckStrictly deshabilita este enlace y habilita labelInValue; Regular multiple Selecciona nodos sin marcas vinculadas.
¿Cómo mostrar etiquetas largas?
Establecer popupMatchSelectWidth número o false y comprobar la disponibilidad del panel en una pantalla estrecha. listHeight Cambia la altura de la ventana gráfica; virtual Gestiona la virtualización.