World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#15184] web-v2(UI): Support UI for associate with tagValues (#15185)
Qian Xiaa14c1d2e3f2e
diff --git a/web-v2/web/src/app/metadataObjectsForTag/page.js b/web-v2/web/src/app/metadataObjectsForTag/page.jsindex 161d95269c..9ccbb3c73d 100644--- a/web-v2/web/src/app/metadataObjectsForTag/page.js+++ b/web-v2/web/src/app/metadataObjectsForTag/page.js@@ -83,6 +83,7 @@ export default function MetadataObjectsForTagPage() {metalake: currentMetalake,metadataObjectType: object.type,metadataObjectFullName: object.fullName,+ apiVersion: 1,data: { tagsToRemove: [tag] }}))diff --git a/web-v2/web/src/app/metadataObjectsForTag/page.test.jsx b/web-v2/web/src/app/metadataObjectsForTag/page.test.jsxnew file mode 100644index 0000000000..3dde96cd05--- /dev/null+++ b/web-v2/web/src/app/metadataObjectsForTag/page.test.jsx@@ -0,0 +1,86 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++import { afterEach, expect, it, vi } from 'vitest'+import { act } from 'react'+import { createRoot } from 'react-dom/client'+import MetadataObjectsForTagPage from './page'++const state = vi.hoisted(() => ({ dispatch: vi.fn(), params: new URLSearchParams('metalake=demo&tag=pii') }))+vi.mock('next/navigation', () => ({ useSearchParams: () => state.params, useRouter: () => ({ back: vi.fn() }) }))+vi.mock('@/lib/hooks/useStore', () => ({ useAppDispatch: () => state.dispatch, useAppSelector: vi.fn() }))+vi.mock('@/lib/store/tags', () => ({+ getTagDetails: args => ({ kind: 'tag', args }),+ associateTag: args => ({ kind: 'associate', args })+}))+vi.mock('@/lib/store/metalakes', () => ({ getMetadataObjectsForTag: args => ({ kind: 'objects', args }) }))+vi.mock('react-antd-column-resize', () => ({+ useAntdColumnResize: getColumns => ({ resizableColumns: getColumns().columns, components: {}, tableWidth: 500 })+}))+vi.mock('antd', async () => {+ const React = await import('react')++ return {+ Flex: ({ children }) => <div>{children}</div>,+ Input: Object.assign(({ children }) => <div>{children}</div>, { Search: () => null }),+ Spin: ({ children }) => <div>{children}</div>,+ Tag: ({ children }) => <span>{children}</span>,+ Tooltip: ({ children }) => <>{children}</>,+ Typography: { Title: ({ children }) => <div>{children}</div>, Paragraph: ({ children }) => <div>{children}</div> },+ Table: ({ dataSource, columns }) =>+ React.createElement('div', null, ...dataSource.map(record => columns[2].render(null, record)))+ }+})+vi.mock('@/components/Icons', () => ({+ default: { Delete: ({ onClick }) => <button onClick={onClick}>remove</button>, Undo2: () => null }+}))+vi.mock('@/components/SectionContainer', () => ({ default: ({ children }) => <div>{children}</div> }))++let root+let container+afterEach(async () => {+ if (root) await act(async () => root.unmount())+ container?.remove()+ vi.clearAllMocks()+})++it('removes a tag association using the v1 tag name shape', async () => {+ state.dispatch.mockImplementation(async action => {+ if (action.kind === 'objects') return { payload: [{ type: 'table', fullName: 'sales.orders' }] }++ return { payload: {} }+ })+ container = document.createElement('div')+ document.body.appendChild(container)+ root = createRoot(container)++ await act(async () => root.render(<MetadataObjectsForTagPage />))+ await act(async () => container.querySelector('button').click())++ expect(state.dispatch).toHaveBeenCalledWith({+ kind: 'associate',+ args: {+ metalake: 'demo',+ metadataObjectType: 'table',+ metadataObjectFullName: 'sales.orders',+ apiVersion: 1,+ data: { tagsToRemove: ['pii'] }+ }+ })+})diff --git a/web-v2/web/src/components/CustomTags.js b/web-v2/web/src/components/CustomTags.jsindex 79fcc3ff14..154678ada4 100644--- a/web-v2/web/src/components/CustomTags.js+++ b/web-v2/web/src/components/CustomTags.js@@ -22,7 +22,7 @@ import React, { useEffect, useRef, useState } from 'react'import { useRouter } from 'next/navigation'import { LockOutlined, PlusOutlined } from '@ant-design/icons'-import { Flex, Select, Space, Tag, Tooltip, theme } from 'antd'+import { Cascader, Flex, Input, Space, Tag, Tooltip, theme } from 'antd'import { useAppSelector, useAppDispatch } from '@/lib/hooks/useStore'import { associateTag } from '@/lib/store/tags'import { getCurrentEntityTags } from '@/lib/store/metalakes'@@ -40,6 +40,9 @@ export default function Tags({ ...props }) {const { token } = theme.useToken()const [inputVisible, setInputVisible] = useState(false)const [optionList, setOptionList] = useState([])+ const [selectedTag, setSelectedTag] = useState(null)+ const [selectedValue, setSelectedValue] = useState(undefined)+ const associatingRef = useRef(false)const inputRef = useRef(null)const router = useRouter()const store = useAppSelector(state => state.tags)@@ -69,7 +72,16 @@ export default function Tags({ ...props }) {useEffect(() => {if (inputVisible) {const options =- store.tagsData?.filter(tagOption => !tagsForEntity?.map(tag => tag.name)?.includes(tagOption.name)) || []+ store.tagsData?.filter(tagOption => {+ const associatedTag = tagsForEntity.find(tag => tag.name === tagOption.name)++ return (+ !associatedTag ||+ tagOption.allowedValues == null ||+ (tagOption.allowedValues?.length &&+ tagOption.allowedValues.some(value => !associatedTag.assignmentValues?.includes(value)))+ )+ }) || []setOptionList(options)inputRef.current?.focus()}@@ -79,61 +91,64 @@ export default function Tags({ ...props }) {setInputVisible(true)}- const tagRender = props => {- const { value, closable, onClose } = props+ const handleChange = path => {+ const tag = store.tagsData?.find(item => item.name === path[0])++ if (tag?.allowedValues == null && path[1] === '__no_value__') {+ associateSelectedTag(tag, undefined)- const onPreventMouseDown = event => {- event.preventDefault()- event.stopPropagation()+ return}- const tagColor = store.tagsData?.find(tag => tag.name === value)?.properties?.color-- return (- <Tag- color={tagColor}- onMouseDown={onPreventMouseDown}- closable={closable}- onClose={onClose}- style={{ marginInlineEnd: 4 }}- >- {value}- </Tag>++ setSelectedTag(tag)+ setSelectedValue(+ tag?.allowedValues == null && path[1] === '__custom_value__'+ ? ''+ : (path[1] ?? (tag?.allowedValues == null ? '' : undefined)))}- const handleChange = async value => {- if (value && !tagsForEntity?.map(tag => tag.name)?.includes(value)) {- await dispatch(- associateTag({- metalake: currentMetalake,- metadataObjectType,- metadataObjectFullName,- data: { tagsToAdd: [value] }- })- )+ const associateSelectedTag = async (tag, value) => {+ if (!tag || associatingRef.current) return+ if (tagsForEntity.some(item => item.name === tag.name && (!value || item.assignmentValues?.includes(value)))) {+ setSelectedTag(null)+ setSelectedValue(undefined)+ setInputVisible(false)++ return}+ associatingRef.current = true+ await dispatch(+ associateTag({+ metalake: currentMetalake,+ metadataObjectType,+ metadataObjectFullName,+ data: { tagsToAdd: [{ name: tag.name, ...(value !== undefined ? { value } : {}) }] }+ })+ )+ setSelectedTag(null)+ setSelectedValue(undefined)const tags = await getTagsForEntity()setTagsForEntity(tags)setInputVisible(false)+ associatingRef.current = false}- const handleClose = async removedTag => {+ const handleClose = async (tag, value) => {await dispatch(associateTag({metalake: currentMetalake,metadataObjectType,metadataObjectFullName,- data: { tagsToRemove: [removedTag] }+ data: {+ tagsToRemove: [{ name: tag.name, ...(value !== undefined ? { value } : {}) }]+ }}))const tags = await getTagsForEntity()setTagsForEntity(tags)}- const handleBlur = () => {- setInputVisible(false)- }-const handleClick = name => () => {router.push(`/metadataObjectsForTag?tag=${name}&metalake=${currentMetalake}`)}@@ -146,52 +161,103 @@ export default function Tags({ ...props }) {return (<Flex gap='4px 0' wrap>- {tagsForEntity?.map((tag, index) => {- const isLongTag = tag.name.length > 20- let color = tag.properties['color'] || 'grey'-- const tagElem = (- <Tag- key={tag.name + index}- color={color}- closable={!readOnly && !tag.inherited}- icon={tag.inherited ? <LockOutlined /> : null}- onClick={handleClick(tag.name)}- className='cursor-pointer'- style={{ userSelect: 'none' }}- onClose={() => handleClose(tag.name)}- >- <span>{isLongTag ? `${tag.name.slice(0, 20)}...` : tag.name}</span>- </Tag>- )-- return isLongTag ? (- <Tooltip title={tag.name} key={tag.name}>- {tagElem}- </Tooltip>- ) : (- tagElem- )- })}+ {tagsForEntity?.flatMap(tag =>+ (tag.assignmentValues?.length ? tag.assignmentValues : [undefined]).map((value, index) => {+ const label = value === undefined ? tag.name : `${tag.name}=${value}`+ const isLongTag = label.length > 20+ const color = tag.properties['color'] || 'grey'++ const tagElem = (+ <Tag+ key={`${tag.name}:${value ?? index}`}+ color={color}+ closable={!readOnly && !tag.inherited}+ icon={tag.inherited ? <LockOutlined /> : null}+ onClick={handleClick(tag.name)}+ className='cursor-pointer'+ style={{ userSelect: 'none' }}+ onClose={() => handleClose(tag, value)}+ >+ <span>{isLongTag ? `${label.slice(0, 20)}...` : label}</span>+ </Tag>+ )++ return isLongTag ? (+ <Tooltip title={label} key={`${tag.name}:${value}`}>+ {tagElem}+ </Tooltip>+ ) : (+ tagElem+ )+ })+ )}{tagsForEntity?.length === 0 && <span>No Tags </span>}{inputVisible && !readOnly && (- <Select+ <Cascadersize='small'- tagRender={tagRender}ref={inputRef}+ open={inputVisible}style={tagInputStyle}- onChange={handleChange}- onBlur={handleBlur}- >- {optionList.map(tag => (- <Select.Option value={tag.name} key={tag.name}>+ options={optionList.map(tag => ({+ value: tag.name,+ label: (<Space><span className='tag-swatch' style={{ backgroundColor: tag.properties?.color }}></span><span>{tag.name}</span></Space>- </Select.Option>- ))}- </Select>+ ),+ ...(tag.allowedValues?.length+ ? { children: tag.allowedValues.map(value => ({ value, label: value })) }+ : tag.allowedValues == null+ ? {+ children: [+ { value: '__no_value__', label: 'Assign without a value' },+ {+ value: '__custom_value__',+ label: (+ <Input+ size='small'+ placeholder='Enter value'+ maxLength={256}+ value={selectedTag?.name === tag.name ? selectedValue || '' : ''}+ onFocus={() => setSelectedTag(tag)}+ onMouseDown={event => {+ event.stopPropagation()+ setSelectedTag(tag)+ }}+ onChange={event => {+ setSelectedTag(tag)+ setSelectedValue(event.target.value)+ }}+ onBlur={() => {+ if (selectedValue?.trim()) {+ associateSelectedTag(tag, selectedValue.trim())+ } else {+ setSelectedTag(null)+ setInputVisible(false)+ }+ }}+ onKeyDown={event => event.stopPropagation()}+ />+ )+ }+ ]+ }+ : {})+ }))}+ onChange={handleChange}+ onBlur={() => {+ if (selectedTag && selectedTag.allowedValues == null) return+ if (selectedTag && selectedValue !== undefined && selectedValue !== '') {+ associateSelectedTag(selectedTag, selectedValue || undefined)+ } else if (selectedTag?.allowedValues?.length === 0) {+ associateSelectedTag(selectedTag, undefined)+ } else if (!selectedTag) {+ setInputVisible(false)+ }+ }}+ placeholder='Associate Tag'+ />)}{!inputVisible && !readOnly && (<Tag style={tagPlusStyle} icon={<PlusOutlined />} onClick={showInput}>diff --git a/web-v2/web/src/components/CustomTags.test.jsx b/web-v2/web/src/components/CustomTags.test.jsxnew file mode 100644index 0000000000..bb06c335c9--- /dev/null+++ b/web-v2/web/src/components/CustomTags.test.jsx@@ -0,0 +1,171 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++import { afterEach, expect, it, vi } from 'vitest'+import { act } from 'react'+import { createRoot } from 'react-dom/client'+import Tags from './CustomTags'++const mocks = vi.hoisted(() => ({+ dispatch: vi.fn(),+ blur: null,+ change: null,+ tagsData: [{ name: 'classification', allowedValues: null }]+}))+vi.mock('next/navigation', () => ({+ useRouter: () => ({ push: vi.fn() }),+ useSearchParams: () => new URLSearchParams('metalake=demo')+}))+vi.mock('@/lib/hooks/useStore', () => ({+ useAppDispatch: () => mocks.dispatch,+ useAppSelector: () => ({ tagsData: mocks.tagsData })+}))+vi.mock('@/lib/store/tags', () => ({ associateTag: args => ({ kind: 'associate', args }) }))+vi.mock('@/lib/store/metalakes', () => ({ getCurrentEntityTags: args => ({ kind: 'getTags', args }) }))+vi.mock('@ant-design/icons', () => ({ LockOutlined: () => null, PlusOutlined: () => null }))+vi.mock('antd', () => ({+ Cascader: props => {+ mocks.blur = props.onBlur+ mocks.change = props.onChange++ return (+ <div data-testid='cascader'>{props.options.flatMap(option => option.children?.map(child => child.label))}</div>+ )+ },+ Flex: ({ children }) => <div>{children}</div>,+ Input: props => <input {...props} />,+ Space: ({ children }) => <div>{children}</div>,+ Tag: ({ children, onClick }) => <button onClick={onClick}>{children}</button>,+ Tooltip: ({ children }) => <>{children}</>,+ theme: { useToken: () => ({ token: { colorBgContainer: 'white' } }) }+}))++let root+let container+afterEach(async () => {+ if (root) await act(async () => root.unmount())+ container?.remove()+ vi.clearAllMocks()+ mocks.blur = null+ mocks.change = null+ mocks.tagsData = [{ name: 'classification', allowedValues: null }]+})++it('closes the Associate Tag dropdown when dismissed without a selection', async () => {+ mocks.dispatch.mockResolvedValue({ payload: { tags: [] } })+ container = document.createElement('div')+ document.body.appendChild(container)+ root = createRoot(container)++ await act(async () => root.render(<Tags metadataObjectType='table' metadataObjectFullName='sales.orders' />))+ await act(async () =>+ [...container.querySelectorAll('button')].find(button => button.textContent.includes('Associate Tag')).click()+ )+ expect(container.querySelector('[data-testid="cascader"]')).not.toBeNull()++ await act(async () => mocks.blur())++ expect(container.querySelector('[data-testid="cascader"]')).toBeNull()+ expect(container.textContent).toContain('Associate Tag')+})++it('keeps the dropdown open when focusing a tag custom-value input', async () => {+ mocks.dispatch.mockResolvedValue({ payload: { tags: [] } })+ container = document.createElement('div')+ document.body.appendChild(container)+ root = createRoot(container)++ await act(async () => root.render(<Tags metadataObjectType='table' metadataObjectFullName='sales.orders' />))+ await act(async () => container.querySelector('button').click())+ const input = container.querySelector('input')++ await act(async () => input.dispatchEvent(new MouseEvent('mousedown', { bubbles: true })))+ await act(async () => mocks.blur())+ await act(async () => input.focus())++ expect(container.querySelector('[data-testid="cascader"]')).not.toBeNull()+ expect(document.activeElement).toBe(input)+})++it('associates an unrestricted tag without a value when explicitly selected', async () => {+ mocks.dispatch.mockResolvedValue({ payload: { tags: [] } })+ container = document.createElement('div')+ document.body.appendChild(container)+ root = createRoot(container)++ await act(async () => root.render(<Tags metadataObjectType='table' metadataObjectFullName='sales.orders' />))+ await act(async () => container.querySelector('button').click())+ await act(async () => mocks.change(['classification', '__no_value__']))++ expect(mocks.dispatch).toHaveBeenCalledWith({+ kind: 'associate',+ args: {+ metalake: 'demo',+ metadataObjectType: 'table',+ metadataObjectFullName: 'sales.orders',+ data: { tagsToAdd: [{ name: 'classification' }] }+ }+ })+})++it('closes the picker without requesting an already-associated value', async () => {+ mocks.tagsData = [{ name: 'classification', allowedValues: ['public', 'private'] }]+ mocks.dispatch.mockResolvedValue({+ payload: { tags: [{ name: 'classification', assignmentValues: ['public'], properties: {} }] }+ })+ container = document.createElement('div')+ document.body.appendChild(container)+ root = createRoot(container)++ await act(async () => root.render(<Tags metadataObjectType='table' metadataObjectFullName='sales.orders' />))+ await act(async () =>+ [...container.querySelectorAll('button')].find(button => button.textContent.includes('Associate Tag')).click()+ )+ await act(async () => mocks.change(['classification', 'public']))+ await act(async () => mocks.blur())++ expect(container.querySelector('[data-testid="cascader"]')).toBeNull()+ expect(mocks.dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ kind: 'associate' }))+})++it.each(['__no_value__', '__custom_value__'])(+ 'associates %s as a literal value when it is explicitly allowed',+ async literalValue => {+ mocks.tagsData = [{ name: 'classification', allowedValues: [literalValue] }]+ mocks.dispatch.mockResolvedValue({ payload: { tags: [] } })+ container = document.createElement('div')+ document.body.appendChild(container)+ root = createRoot(container)++ await act(async () => root.render(<Tags metadataObjectType='table' metadataObjectFullName='sales.orders' />))+ await act(async () => container.querySelector('button').click())+ await act(async () => mocks.change(['classification', literalValue]))+ await act(async () => mocks.blur())++ expect(mocks.dispatch).toHaveBeenCalledWith({+ kind: 'associate',+ args: {+ metalake: 'demo',+ metadataObjectType: 'table',+ metadataObjectFullName: 'sales.orders',+ data: { tagsToAdd: [{ name: 'classification', value: literalValue }] }+ }+ })+ }+)diff --git a/web-v2/web/src/lib/api/tags/index.js b/web-v2/web/src/lib/api/tags/index.jsindex a7ef9cfcee..62316c7a40 100644--- a/web-v2/web/src/lib/api/tags/index.js+++ b/web-v2/web/src/lib/api/tags/index.js@@ -62,9 +62,15 @@ export const updateTagApi = ({ metalake, tag, data }) => {})}-export const associateTagApi = ({ metalake, metadataObjectType, metadataObjectFullName, data }) => {+export const associateTagApi = ({ metalake, metadataObjectType, metadataObjectFullName, data, apiVersion = 2 }) => {+ const mediaType = apiVersion === 1 ? 'application/vnd.gravitino.v1+json' : 'application/vnd.gravitino.v2+json'+return defHttp.post({url: Apis.ASSOCIATE({ metalake, metadataObjectType, metadataObjectFullName }),+ headers: {+ 'Content-Type': apiVersion === 1 ? 'application/json' : mediaType,+ Accept: mediaType+ },data})}diff --git a/web-v2/web/src/lib/api/tags/index.test.js b/web-v2/web/src/lib/api/tags/index.test.jsnew file mode 100644index 0000000000..3614c49088--- /dev/null+++ b/web-v2/web/src/lib/api/tags/index.test.js@@ -0,0 +1,45 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++import { afterEach, expect, it, vi } from 'vitest'+import { associateTagApi } from './index'+import { defHttp } from '@/lib/utils/axios'++vi.mock('@/lib/utils/axios', () => ({ defHttp: { post: vi.fn() } }))++afterEach(() => vi.clearAllMocks())++it('uses the v1 media types for legacy tag-name association requests', () => {+ associateTagApi({+ metalake: 'demo',+ metadataObjectType: 'table',+ metadataObjectFullName: 'sales.orders',+ apiVersion: 1,+ data: { tagsToRemove: ['pii'] }+ })++ expect(defHttp.post).toHaveBeenCalledWith({+ url: '/api/metalakes/demo/objects/table/sales.orders/tags',+ headers: {+ 'Content-Type': 'application/json',+ Accept: 'application/vnd.gravitino.v1+json'+ },+ data: { tagsToRemove: ['pii'] }+ })+})diff --git a/web-v2/web/src/lib/store/tags/index.js b/web-v2/web/src/lib/store/tags/index.jsindex f9b5557057..9fe2e3b224 100644--- a/web-v2/web/src/lib/store/tags/index.js+++ b/web-v2/web/src/lib/store/tags/index.js@@ -90,8 +90,10 @@ export const deleteTag = createAsyncThunk('tags/deleteTag', async ({ metalake, texport const associateTag = createAsyncThunk('tags/associateTag',- async ({ metalake, metadataObjectType, metadataObjectFullName, data }) => {- const [err, res] = await to(associateTagApi({ metalake, metadataObjectType, metadataObjectFullName, data }))+ async ({ metalake, metadataObjectType, metadataObjectFullName, data, apiVersion }) => {+ const [err, res] = await to(+ associateTagApi({ metalake, metadataObjectType, metadataObjectFullName, data, apiVersion })+ )if (err || !res) {throw new Error(err)