diff --git a/src/assets/mdi.ts b/src/assets/mdi.ts index 3681cee8f3..db20429761 100644 --- a/src/assets/mdi.ts +++ b/src/assets/mdi.ts @@ -79,6 +79,7 @@ import { mdiPlus, mdiPlusCircle, mdiPlusCircleOutline, + mdiRefresh, mdiSend, mdiSlack, mdiSnowflake, @@ -117,6 +118,7 @@ const mdi: MdiIconsMapping = { 'microphone-off': mdiMicrophoneOff, pin: mdiPin, search: mdiMagnify, + refresh: mdiRefresh, history: mdiHistory, creation: mdiCreation, 'file-upload': mdiFileUpload, diff --git a/src/components/Main/MainView/MessageElement/MessageTools.vue b/src/components/Main/MainView/MessageElement/MessageTools.vue index 7544143b7f..689ad7ead5 100644 --- a/src/components/Main/MainView/MessageElement/MessageTools.vue +++ b/src/components/Main/MainView/MessageElement/MessageTools.vue @@ -8,7 +8,7 @@
diff --git a/src/components/Main/StampPicker/StampPickerStampSetSelectorItem.vue b/src/components/Main/StampPicker/StampPickerStampSetSelectorItem.vue index 5f608452df..1311d4d2f9 100644 --- a/src/components/Main/StampPicker/StampPickerStampSetSelectorItem.vue +++ b/src/components/Main/StampPicker/StampPickerStampSetSelectorItem.vue @@ -1,68 +1,33 @@ diff --git a/src/components/UI/StampSetIcon.vue b/src/components/UI/StampSetIcon.vue new file mode 100644 index 0000000000..8f65d7ccac --- /dev/null +++ b/src/components/UI/StampSetIcon.vue @@ -0,0 +1,35 @@ + + + diff --git a/src/composables/dom/useSortable.ts b/src/composables/dom/useSortable.ts new file mode 100644 index 0000000000..fd3fa1fdc3 --- /dev/null +++ b/src/composables/dom/useSortable.ts @@ -0,0 +1,93 @@ +import { + type MaybeRefOrGetter, + type Ref, + computed, + shallowRef, + toValue, + watch +} from 'vue' + +import Sortable from 'sortablejs' + +import { type SortableDrag, useSortableOutside } from './useSortableOutside' + +type DragStartEvent = Sortable.SortableEvent & { + originalEvent?: MouseEvent | TouchEvent +} + +type Options = Omit< + Sortable.Options, + 'draggable' | 'group' | 'onEnd' | 'onStart' | 'onUpdate' | 'scroll' | 'store' +> & { + /** リストの外でも指定した軸に沿って並べ替える */ + sortOutside?: Sortable.Direction + scroll?: MaybeRefOrGetter + supportPointer?: boolean +} + +export const useSortable = ( + container: Readonly>, + onReorder: (ids: string[]) => void, + { sortOutside, scroll, ...options }: Options = {} +) => { + const activeDrag = shallowRef() + const isDragging = computed(() => activeDrag.value !== undefined) + + if (sortOutside) useSortableOutside(activeDrag, sortOutside) + + const endDrag = () => { + activeDrag.value = undefined + } + + watch( + [container, () => toValue(scroll)], + ([element, scrollOption], _, onCleanup) => { + if (!element) return + + const scrollTarget = scrollOption ?? (sortOutside ? element : undefined) + let nextItem: Element | null = null + const sortable = Sortable.create(element, { + animation: 150, + draggable: '>[data-id]', + ...options, + ...(scrollTarget !== undefined && { scroll: scrollTarget }), + ...(sortOutside && { + direction: sortOutside, + forceFallback: true, + fallbackOnBody: true, + bubbleScroll: options.bubbleScroll ?? false + }), + onStart: ({ item, originalEvent }: DragStartEvent) => { + nextItem = item.nextElementSibling + activeDrag.value = { + sortable, + item, + startPoint: + originalEvent && 'touches' in originalEvent + ? originalEvent.touches[0] + : originalEvent + } + }, + onEnd: endDrag, + onUpdate: ({ item }) => { + const ids = sortable.toArray() + + // Vue が並べ替え前の DOM を基準に差分を適用できるようにする + element.insertBefore( + item, + nextItem?.parentElement === element ? nextItem : null + ) + onReorder(ids) + } + }) + + onCleanup(() => { + endDrag() + sortable.destroy() + }) + }, + { immediate: true, flush: 'post' } + ) + + return { isDragging } +} diff --git a/src/composables/dom/useSortableOutside.ts b/src/composables/dom/useSortableOutside.ts new file mode 100644 index 0000000000..fda302b1b2 --- /dev/null +++ b/src/composables/dom/useSortableOutside.ts @@ -0,0 +1,111 @@ +import { type Ref, computed, watch } from 'vue' + +import { useEventListener } from '@vueuse/core' +import type Sortable from 'sortablejs' + +type PointerPosition = Pick + +export type SortableDrag = { + sortable: Sortable + item: HTMLElement + startPoint: PointerPosition | undefined +} + +const geometry = { + horizontal: { + pointer: 'clientX', + start: 'left', + scroll: 'scrollLeft', + offset: 'offsetLeft', + border: 'clientLeft', + size: 'offsetWidth' + }, + vertical: { + pointer: 'clientY', + start: 'top', + scroll: 'scrollTop', + offset: 'offsetTop', + border: 'clientTop', + size: 'offsetHeight' + } +} as const + +export const useSortableOutside = ( + activeDrag: Readonly>, + direction: Sortable.Direction +) => { + const axis = geometry[direction] + const draggingList = computed(() => activeDrag.value?.sortable.el) + const scrollContainer = computed(() => { + const scroll = activeDrag.value?.sortable.option('scroll') + return scroll instanceof HTMLElement ? scroll : draggingList.value + }) + let pointer: PointerPosition | undefined + + const reorderOutsideList = () => { + if (!activeDrag.value || !pointer) return + + const { sortable, item } = activeDrag.value + const { el: list } = sortable + const { clientX, clientY } = pointer + const bounds = list.getBoundingClientRect() + const viewport = scrollContainer.value?.getBoundingClientRect() ?? bounds + + const insideX = + clientX >= Math.max(bounds.left, viewport.left) && + clientX < Math.min(bounds.right, viewport.right) + const insideY = + clientY >= Math.max(bounds.top, viewport.top) && + clientY < Math.min(bounds.bottom, viewport.bottom) + if (insideX && insideY) return + + const items = [...list.querySelectorAll(':scope > [data-id]')] + + const currentIndex = items.indexOf(item) + if (currentIndex < 0) return + + const position = + pointer[axis.pointer] - bounds[axis.start] + list[axis.scroll] + + const nextIndex = items.filter(other => { + if (other === item) return false + + // アニメーション中もレイアウト上の位置を使って挿入先を判定する + const origin = + other.offsetParent === list ? -list[axis.border] : list[axis.offset] + const center = other[axis.offset] - origin + other[axis.size] / 2 + return center <= position + }).length + + if (nextIndex === currentIndex) return + + const ids = sortable.toArray() + const [id] = ids.splice(currentIndex, 1) + if (id === undefined) return + + ids.splice(nextIndex, 0, id) + sortable.sort(ids, true) + } + + watch( + activeDrag, + drag => { + pointer = drag?.startPoint + reorderOutsideList() + }, + { flush: 'sync' } + ) + + const updatePointer = (event: MouseEvent | TouchEvent) => { + pointer = 'touches' in event ? event.touches[0] : event + reorderOutsideList() + } + + useEventListener( + () => draggingList.value?.ownerDocument, + ['pointermove', 'mousemove', 'touchmove'], + updatePointer, + { passive: true } + ) + useEventListener(scrollContainer, 'scroll', reorderOutsideList) +} diff --git a/src/store/app/featureFlagSettings.ts b/src/store/app/featureFlagSettings.ts index 012703de4e..f1ce082037 100644 --- a/src/store/app/featureFlagSettings.ts +++ b/src/store/app/featureFlagSettings.ts @@ -50,7 +50,7 @@ export const featureFlagDescriptions = { stamp_recommendation_v3: { title: 'スタンプのレコメンデーション', description: - 'スタンプ履歴の代わりに、利用傾向に合わせたおすすめを表示するようにします。', + 'スタンプピッカーにおすすめタブを追加し、タブの並び順を変更できるようにします。ホバーメニューの表示元は「スタンプパレット」設定で選べます。', defaultValue: true, endAt: new Date('2026-11-30T23:59') } diff --git a/src/store/domain/stampRecommendations.ts b/src/store/domain/stampRecommendations.ts index 0bcaae7f93..c05680938e 100644 --- a/src/store/domain/stampRecommendations.ts +++ b/src/store/domain/stampRecommendations.ts @@ -76,10 +76,8 @@ export const useStampRecommendations = convertToRefsStore( export const useTopStampIds = () => { const { featureFlags } = useFeatureFlagSettings() - const { stampRecommendations, stampRecommendationsFetched } = - useStampRecommendations() - const { recentStampIds, stampHistoryFetched } = useStampHistory() - const { stampsMapFetched } = useStampsStore() + const { stampRecommendations } = useStampRecommendations() + const { recentStampIds } = useStampHistory() const topStampIds = computed(() => featureFlags.value.stamp_recommendation_v3.enabled @@ -87,15 +85,7 @@ export const useTopStampIds = () => { : recentStampIds.value ) - const topStampIdsFetched = computed( - () => - stampsMapFetched.value && - (featureFlags.value.stamp_recommendation_v3.enabled - ? stampRecommendationsFetched.value - : stampHistoryFetched.value) - ) - - return { topStampIds, topStampIdsFetched } + return { topStampIds } } if (import.meta.hot) { diff --git a/src/store/ui/stampPicker.ts b/src/store/ui/stampPicker.ts index 4515cb4e65..269e252d10 100644 --- a/src/store/ui/stampPicker.ts +++ b/src/store/ui/stampPicker.ts @@ -7,13 +7,13 @@ import { useEventListener } from '@vueuse/core' import { acceptHMRUpdate, defineStore } from 'pinia' import { throttle } from 'throttle-debounce' -import type { StampSet } from '/@/components/Main/StampPicker/composables/useStampSetSelector' import useIndexedDbValue from '/@/composables/storage/useIndexedDbValue' import type { Point } from '/@/lib/basic/point' -import { useStampPalettesStore } from '/@/store/entities/stampPalettes' import { convertToRefsStore } from '/@/store/utils/convertToRefsStore' import type { StampId } from '/@/types/entity-ids' +import type { StampSet } from './stampPickerSettings' + export type SelectedStampData = { id: StampId sizeEffect?: SizeEffect @@ -61,37 +61,36 @@ const getPositionFromAlignment = ( } } +type StampPickerSelection = { + selected?: StampSet + type?: StampSet['type'] + id?: string +} + const useStampPickerPinia = defineStore('ui/stampPicker', () => { const selectHandler = ref(defaultSelectHandler) - const initialStampSetValue: StampSet = { - type: 'history', - id: '' - } - const [state] = useIndexedDbValue( + const [state] = useIndexedDbValue( 'store/ui/stampPicker/currentStampSet', 1, {}, - initialStampSetValue + {} ) - const { nonEmptyStampPaletteIds } = useStampPalettesStore() - const currentStampSet = computed({ - get: () => state, - set: (newValue: StampSet) => { - state.id = newValue.id - state.type = newValue.type + const currentStampSet = computed({ + get: (): StampSet => { + const { selected, type, id } = state + if (selected) return selected + if (id && (type === 'palette' || type === 'category')) return { type, id } + + // 旧履歴タブはフラグが有効な場合にレコメンデーションを表示していた + return { type: 'recommendation', id: '' } + }, + set: ({ type, id }: StampSet) => { + state.selected = { type, id } } }) - const validateCurrentStampSet = () => { - if (currentStampSet.value.type !== 'palette') return - if (!nonEmptyStampPaletteIds.value.includes(currentStampSet.value.id)) { - currentStampSet.value.type = 'history' - currentStampSet.value.id = '' - } - } - const isEffectEnabled = ref(false) const position = ref() const alignment = ref('top-right') @@ -107,7 +106,6 @@ const useStampPickerPinia = defineStore('ui/stampPicker', () => { return { selectHandler, currentStampSet, - validateCurrentStampSet, isEffectEnabled, position, alignment, diff --git a/src/store/ui/stampPickerSettings.ts b/src/store/ui/stampPickerSettings.ts new file mode 100644 index 0000000000..ff8262e92f --- /dev/null +++ b/src/store/ui/stampPickerSettings.ts @@ -0,0 +1,135 @@ +import { computed, toRef } from 'vue' + +import { acceptHMRUpdate, defineStore } from 'pinia' + +import useLocalStorageValue from '/@/composables/storage/useLocalStorage' +import { isDefined } from '/@/lib/basic/array' +import { useFeatureFlagSettings } from '/@/store/app/featureFlagSettings' +import { useStampHistory } from '/@/store/domain/stampHistory' +import { useStampRecommendations } from '/@/store/domain/stampRecommendations' +import { useStampPalettesStore } from '/@/store/entities/stampPalettes' +import { useStampsStore } from '/@/store/entities/stamps' +import { convertToRefsStore } from '/@/store/utils/convertToRefsStore' + +export type StampSet = { + type: 'recommendation' | 'history' | 'palette' | 'category' + id: string +} + +export type StampPickerTab = StampSet & { label: string } + +const recommendationTab = { + type: 'recommendation', + id: '', + label: 'レコメンデーション' +} as const satisfies StampPickerTab + +const historyTab = { + type: 'history', + id: '', + label: '最近使ったスタンプ' +} as const satisfies StampPickerTab + +export const getStampSetKey = ({ type, id }: StampSet) => + id ? `${type}:${id}` : type + +const QUICK_REACTION_COUNT = 3 + +const useStampPickerSettingsPinia = defineStore( + 'ui/stampPickerSettings', + () => { + const [settings] = useLocalStorageValue( + 'store/ui/stampPickerSettings', + 1, + {}, + { + tabOrder: [] as string[], + quickReactionSource: recommendationTab.type as string + } + ) + + const { featureFlags } = useFeatureFlagSettings() + const { stampPalettesMap, nonEmptyStampPaletteIds } = + useStampPalettesStore() + const { stampRecommendations } = useStampRecommendations() + const { recentStampIds } = useStampHistory() + const { initialRecentStamps, stampsMap } = useStampsStore() + + const isRecommendationEnabled = computed( + () => featureFlags.value.stamp_recommendation_v3.enabled + ) + const defaultTab = computed(() => + isRecommendationEnabled.value ? recommendationTab : historyTab + ) + const personalTabs = computed((): StampPickerTab[] => [ + ...(isRecommendationEnabled.value ? [recommendationTab] : []), + historyTab, + ...nonEmptyStampPaletteIds.value + .map(id => stampPalettesMap.value.get(id)) + .filter(isDefined) + .map(palette => ({ + type: 'palette' as const, + id: palette.id, + label: palette.name + })) + ]) + + const quickReactionTab = computed(() => { + if (!isRecommendationEnabled.value) return historyTab + + return ( + personalTabs.value.find( + tab => getStampSetKey(tab) === settings.quickReactionSource + ) ?? recommendationTab + ) + }) + const quickReactionSource = computed({ + get: () => getStampSetKey(quickReactionTab.value), + set: (key: string) => { + settings.quickReactionSource = key + } + }) + const quickReactionStampIds = computed(() => { + const tab = quickReactionTab.value + + if (tab.type === 'palette') { + const stamps = stampPalettesMap.value.get(tab.id)?.stamps ?? [] + return stamps + .slice(0, QUICK_REACTION_COUNT) + .filter(id => stampsMap.value.has(id)) + } + + const ids = + tab.type === 'recommendation' + ? stampRecommendations.value + : recentStampIds.value + const topIds = ids.slice(0, QUICK_REACTION_COUNT) + if (topIds.length === QUICK_REACTION_COUNT) return topIds + + const fallbackIds = initialRecentStamps.value.map(stamp => stamp.id) + return [...new Set([...topIds, ...fallbackIds])].slice( + 0, + QUICK_REACTION_COUNT + ) + }) + + return { + isRecommendationEnabled, + defaultTab, + personalTabs, + tabOrder: toRef(settings, 'tabOrder'), + quickReactionSource, + quickReactionStampIds + } + } +) + +export const useStampPickerSettings = convertToRefsStore( + useStampPickerSettingsPinia +) + +if (import.meta.hot) { + import.meta.hot.accept( + acceptHMRUpdate(useStampPickerSettingsPinia, import.meta.hot) + ) +} diff --git a/src/views/Settings/StampPaletteTab/StampPaletteTab.vue b/src/views/Settings/StampPaletteTab/StampPaletteTab.vue index fffcfd3c39..47a0363af9 100644 --- a/src/views/Settings/StampPaletteTab/StampPaletteTab.vue +++ b/src/views/Settings/StampPaletteTab/StampPaletteTab.vue @@ -1,27 +1,75 @@ - + diff --git a/tests/unit/components/Main/StampPicker/composables/useStampList.spec.ts b/tests/unit/components/Main/StampPicker/composables/useStampList.spec.ts index e3304488f1..5d75e1eb33 100644 --- a/tests/unit/components/Main/StampPicker/composables/useStampList.spec.ts +++ b/tests/unit/components/Main/StampPicker/composables/useStampList.spec.ts @@ -3,24 +3,20 @@ import type { Stamp } from '@traptitech/traq' import { computed, effectScope, nextTick, ref } from 'vue' import useStampList from '/@/components/Main/StampPicker/composables/useStampList' -import type { StampSet } from '/@/components/Main/StampPicker/composables/useStampSetSelector' import { useStampCategory } from '/@/store/domain/stampCategory' -import { useTopStampIds } from '/@/store/domain/stampRecommendations' +import { useStampRecommendations } from '/@/store/domain/stampRecommendations' import { useStampPalettesStore } from '/@/store/entities/stampPalettes' import { useStampsStore } from '/@/store/entities/stamps' +import type { StampSet } from '/@/store/ui/stampPickerSettings' -vi.mock('/@/store/app/featureFlagSettings', () => ({ - useFeatureFlagSettings: () => ({ - featureFlags: computed(() => ({ - stamp_recommendation_v3: { enabled: true } - })) - }) -})) vi.mock('/@/store/domain/stampCategory', () => ({ useStampCategory: vi.fn() })) +vi.mock('/@/store/domain/stampHistory', () => ({ + useStampHistory: () => ({ recentStampIds: ref([]) }) +})) vi.mock('/@/store/domain/stampRecommendations', () => ({ - useTopStampIds: vi.fn() + useStampRecommendations: vi.fn() })) vi.mock('/@/store/entities/stampPalettes', () => ({ useStampPalettesStore: vi.fn() @@ -35,7 +31,9 @@ describe('useStampList', () => { const stampsMap = ref(new Map()) const scopes: ReturnType[] = [] - const openPicker = (stampSet: StampSet = { type: 'history', id: '' }) => { + const openPicker = ( + stampSet: StampSet = { type: 'recommendation', id: '' } + ) => { const scope = effectScope() scopes.push(scope) const currentStampSet = ref(stampSet) @@ -48,11 +46,14 @@ describe('useStampList', () => { topStampIds.value = ['a', 'b'] topStampIdsFetched.value = true stampsMap.value = new Map(['a', 'b', 'c'].map(id => [id, createStamp(id)])) - vi.mocked(useTopStampIds).mockReturnValue({ - topStampIds: computed(() => topStampIds.value), - topStampIdsFetched: computed(() => topStampIdsFetched.value) + vi.mocked(useStampRecommendations, { partial: true }).mockReturnValue({ + stampRecommendations: computed(() => topStampIds.value), + stampRecommendationsFetched: topStampIdsFetched + }) + vi.mocked(useStampsStore, { partial: true }).mockReturnValue({ + stampsMap, + stampsMapFetched: ref(true) }) - vi.mocked(useStampsStore, { partial: true }).mockReturnValue({ stampsMap }) vi.mocked(useStampCategory, { partial: true }).mockReturnValue({ traQStampCategory: ref({ name: 'traq', stampIds: ['a', 'b', 'c'] }), unicodeStampCategories: ref([]) @@ -108,7 +109,7 @@ describe('useStampList', () => { topStampIds.value = ['c', 'b', 'a'] await nextTick() - picker.currentStampSet.value = { type: 'history', id: '' } + picker.currentStampSet.value = { type: 'recommendation', id: '' } expect(picker.stamps.value.map(stamp => stamp.id)).toEqual(['c', 'b', 'a']) topStampIds.value = ['a', 'b', 'c'] @@ -121,7 +122,7 @@ describe('useStampList', () => { topStampIds.value = ['c', 'b', 'a'] await nextTick() - picker.currentStampSet.value = { type: 'history', id: '' } + picker.currentStampSet.value = { type: 'recommendation', id: '' } expect(picker.stamps.value.map(stamp => stamp.id)).toEqual(['c', 'b', 'a']) }) diff --git a/tests/unit/components/Main/StampPicker/composables/useStampListLoading.spec.ts b/tests/unit/components/Main/StampPicker/composables/useStampListLoading.spec.ts index 1c18d09eb6..2a80595711 100644 --- a/tests/unit/components/Main/StampPicker/composables/useStampListLoading.spec.ts +++ b/tests/unit/components/Main/StampPicker/composables/useStampListLoading.spec.ts @@ -1,14 +1,14 @@ import type { Stamp } from '@traptitech/traq' -import { computed, effectScope, nextTick, ref } from 'vue' +import { effectScope, nextTick, ref } from 'vue' import { createPinia, setActivePinia } from 'pinia' import useStampList from '/@/components/Main/StampPicker/composables/useStampList' -import type { StampSet } from '/@/components/Main/StampPicker/composables/useStampSetSelector' import { useStampHistory } from '/@/store/domain/stampHistory' import { useStampRecommendations } from '/@/store/domain/stampRecommendations' import { useStampsStore } from '/@/store/entities/stamps' +import type { StampSet } from '/@/store/ui/stampPickerSettings' type RecommendationsResponse = { data: { stampId: string; score: number }[] @@ -28,13 +28,6 @@ vi.mock('/@/lib/apis', () => ({ getMyStampHistory: mockGetHistory } })) -vi.mock('/@/store/app/featureFlagSettings', () => ({ - useFeatureFlagSettings: () => ({ - featureFlags: computed(() => ({ - stamp_recommendation_v3: { enabled: recommendationsEnabled.value } - })) - }) -})) vi.mock('/@/store/domain/stampCategory', async () => { const { ref } = await import('vue') return { @@ -54,28 +47,26 @@ vi.mock('/@/store/entities/stamps', () => ({ useStampsStore: vi.fn() })) -const recommendationsEnabled = ref(true) - describe('useStampList with stamp stores', () => { const stampsMap = ref(new Map()) const stampsMapFetched = ref(true) const scopes: ReturnType[] = [] - const openPicker = () => { + const openPicker = ( + type: 'recommendation' | 'history' = 'recommendation' + ) => { const scope = effectScope() scopes.push(scope) - const picker = scope.run(() => - useStampList(ref({ type: 'history', id: '' })) - ) + const selectedStampSet = ref({ type, id: '' }) + const picker = scope.run(() => useStampList(selectedStampSet)) if (!picker) throw new Error('Picker scope is inactive') - return picker + return { ...picker, selectedStampSet } } beforeEach(() => { vi.useFakeTimers() mockGetRecommendations.mockReset() mockGetHistory.mockReset() - recommendationsEnabled.value = true stampsMapFetched.value = true stampsMap.value = new Map(stamps.map(stamp => [stamp.id, stamp])) vi.mocked(useStampsStore, { partial: true }).mockReturnValue({ @@ -93,10 +84,10 @@ describe('useStampList with stamp stores', () => { vi.useRealTimers() }) - it.each([true, false])( - 'freezes only recommendations after usage (recommendations enabled: %s)', - async enabled => { - recommendationsEnabled.value = enabled + it.each(['recommendation', 'history'] as const)( + 'freezes only recommendations after usage (active tab: %s)', + async type => { + const isRecommendation = type === 'recommendation' mockGetRecommendations.mockResolvedValue({ data: [ { stampId: 'a', score: 2 }, @@ -112,27 +103,27 @@ describe('useStampList with stamp stores', () => { const { recordStampUsage, fetchStampRecommendations } = useStampRecommendations() const { upsertLocalStampHistory, fetchStampHistory } = useStampHistory() - await (enabled ? fetchStampRecommendations() : fetchStampHistory()) - const picker = openPicker() + await Promise.all([fetchStampRecommendations(), fetchStampHistory()]) + const picker = openPicker(type) expect(picker.stamps.value.map(stamp => stamp.id)).toEqual(['a', 'b']) recordStampUsage('b') upsertLocalStampHistory('b', new Date(3000)) await nextTick() expect(picker.stamps.value.map(stamp => stamp.id)).toEqual( - enabled ? ['a', 'b'] : ['b', 'a'] + isRecommendation ? ['a', 'b'] : ['b', 'a'] ) recordStampUsage('c') upsertLocalStampHistory('c', new Date(4000)) await nextTick() expect(picker.stamps.value.map(stamp => stamp.id)).toEqual( - enabled ? ['a', 'b'] : ['c', 'b', 'a'] + isRecommendation ? ['a', 'b'] : ['c', 'b', 'a'] ) } ) - it('releases the frozen list when recommendations are disabled while open', async () => { + it('shows the live history when switching from recommendations to history', async () => { mockGetRecommendations.mockResolvedValue({ data: [ { stampId: 'a', score: 2 }, @@ -151,7 +142,7 @@ describe('useStampList with stamp stores', () => { const picker = openPicker() expect(picker.stamps.value.map(stamp => stamp.id)).toEqual(['a', 'b']) - recommendationsEnabled.value = false + picker.selectedStampSet.value = { type: 'history', id: '' } await nextTick() expect(picker.stamps.value.map(stamp => stamp.id)).toEqual(['b', 'a']) @@ -160,10 +151,9 @@ describe('useStampList with stamp stores', () => { expect(picker.stamps.value.map(stamp => stamp.id)).toEqual(['a', 'b']) }) - it.each([true, false])( - 'accepts the fetched list after local usage (recommendations enabled: %s)', - async enabled => { - recommendationsEnabled.value = enabled + it.each(['recommendation', 'history'] as const)( + 'accepts the fetched list after local usage (active tab: %s)', + async type => { const recommendations = Promise.withResolvers() const history = Promise.withResolvers() mockGetRecommendations.mockReturnValue(recommendations.promise) @@ -171,10 +161,11 @@ describe('useStampList with stamp stores', () => { const { recordStampUsage, fetchStampRecommendations } = useStampRecommendations() const { upsertLocalStampHistory, fetchStampHistory } = useStampHistory() - const fetching = enabled - ? fetchStampRecommendations() - : fetchStampHistory() - const picker = openPicker() + const fetching = + type === 'recommendation' + ? fetchStampRecommendations() + : fetchStampHistory() + const picker = openPicker(type) picker.filterState.query = 'cc' expect(picker.stamps.value.map(stamp => stamp.id)).toEqual(['c']) diff --git a/tests/unit/components/Main/StampPicker/composables/useStampSetSelector.spec.ts b/tests/unit/components/Main/StampPicker/composables/useStampSetSelector.spec.ts new file mode 100644 index 0000000000..a388f45e3f --- /dev/null +++ b/tests/unit/components/Main/StampPicker/composables/useStampSetSelector.spec.ts @@ -0,0 +1,143 @@ +import { computed, nextTick, ref } from 'vue' + +import { createPinia, disposePinia, setActivePinia } from 'pinia' + +import useStampSetSelector from '/@/components/Main/StampPicker/composables/useStampSetSelector' +import { + type StampSet, + getStampSetKey, + useStampPickerSettings +} from '/@/store/ui/stampPickerSettings' + +const recommendationsEnabled = ref(true) +const currentStampSet = ref({ type: 'recommendation', id: '' }) +const palette = { + id: 'my-palette', + name: 'パレット', + stamps: ['d', 'c', 'b', 'a'] +} +const stampPalettesMap = ref(new Map([[palette.id, palette]])) + +vi.mock('/@/store/app/featureFlagSettings', () => ({ + useFeatureFlagSettings: () => ({ + featureFlags: computed(() => ({ + stamp_recommendation_v3: { enabled: recommendationsEnabled.value } + })) + }) +})) +vi.mock('/@/store/domain/stampCategory', () => ({ + useStampCategory: () => ({ + traQStampCategory: ref({ name: 'traq', stampIds: [] }), + unicodeStampCategories: ref([{ name: 'people', stampIds: [] }]) + }) +})) +vi.mock('/@/store/domain/stampHistory', () => ({ + useStampHistory: () => ({ recentStampIds: ref(['b', 'a', 'd']) }) +})) +vi.mock('/@/store/domain/stampRecommendations', () => ({ + useStampRecommendations: () => ({ + stampRecommendations: ref(['a', 'b', 'c']) + }) +})) +vi.mock('/@/store/entities/stampPalettes', () => ({ + useStampPalettesStore: () => ({ + stampPalettesMap, + nonEmptyStampPaletteIds: computed(() => [...stampPalettesMap.value.keys()]) + }) +})) +vi.mock('/@/store/entities/stamps', () => ({ + useStampsStore: () => ({ + initialRecentStamps: ref([]), + stampsMap: ref(new Map(['a', 'b', 'c', 'd'].map(id => [id, { id }]))) + }) +})) +vi.mock('/@/store/ui/stampPicker', () => ({ + useStampPicker: () => ({ currentStampSet }) +})) + +describe('stamp picker settings', () => { + let pinia: ReturnType + + beforeEach(() => { + localStorage.clear() + recommendationsEnabled.value = true + currentStampSet.value = { type: 'recommendation', id: '' } + stampPalettesMap.value = new Map([[palette.id, palette]]) + pinia = createPinia() + setActivePinia(pinia) + useStampPickerSettings(pinia) + }) + + afterEach(() => { + disposePinia(pinia) + }) + + it('shows both personal tabs and restores their saved order and quick reaction source', async () => { + const { stampSets, selectedStampSet, tabOrder } = useStampSetSelector() + const { quickReactionSource } = useStampPickerSettings() + const initialOrder = [ + 'recommendation', + 'history', + 'palette:my-palette', + 'category:traq', + 'category:unicode-people' + ] + expect(stampSets.value.map(getStampSetKey)).toEqual(initialOrder) + + const reordered = [ + 'history', + 'palette:my-palette', + 'category:traq', + 'category:unicode-people', + 'recommendation' + ] + tabOrder.value = reordered + quickReactionSource.value = 'palette:my-palette' + await nextTick() + expect(stampSets.value.map(getStampSetKey)).toEqual(reordered) + expect(selectedStampSet.value.type).toBe('recommendation') + + disposePinia(pinia) + pinia = createPinia() + setActivePinia(pinia) + useStampPickerSettings(pinia) + expect(useStampSetSelector().stampSets.value.map(getStampSetKey)).toEqual( + reordered + ) + expect(useStampPickerSettings().quickReactionStampIds.value).toEqual([ + 'd', + 'c', + 'b' + ]) + }) + + it('changes quick reactions independently and falls back when the selected source is unavailable', () => { + const { stampSets, selectedStampSet } = useStampSetSelector() + const { quickReactionSource, quickReactionStampIds } = + useStampPickerSettings() + + expect(quickReactionStampIds.value).toEqual(['a', 'b', 'c']) + quickReactionSource.value = 'history' + expect(quickReactionStampIds.value).toEqual(['b', 'a', 'd']) + expect(selectedStampSet.value.type).toBe('recommendation') + + quickReactionSource.value = 'palette:my-palette' + expect(quickReactionStampIds.value).toEqual(['d', 'c', 'b']) + + recommendationsEnabled.value = false + expect(stampSets.value.map(tab => tab.type)).toEqual([ + 'history', + 'palette', + 'category', + 'category' + ]) + expect(selectedStampSet.value.type).toBe('history') + expect(quickReactionStampIds.value).toEqual(['b', 'a', 'd']) + + recommendationsEnabled.value = true + expect(quickReactionStampIds.value).toEqual(['d', 'c', 'b']) + stampPalettesMap.value.delete(palette.id) + expect(quickReactionSource.value).toBe('recommendation') + expect(quickReactionStampIds.value).toEqual(['a', 'b', 'c']) + }) +})