This commit is contained in:
Oscar
2026-06-04 14:37:19 +03:00
parent 2d665fab66
commit 1c69ff56bb
7 changed files with 247 additions and 45 deletions

View File

@@ -137,6 +137,47 @@ itemsRouter.get('/selected', (req, res) => {
* 400:
* description: Invalid id
*/
/**
* @openapi
* /api/items/add-value:
* post:
* summary: Create a new item with a given value
* tags: [Items]
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required: [value]
* properties:
* value:
* type: string
* responses:
* 200:
* description: Item created
* content:
* application/json:
* schema:
* type: object
* properties:
* id:
* type: integer
* value:
* type: string
* 400:
* description: Invalid value
*/
itemsRouter.post('/add-value', (req, res) => {
const value = req.body?.value
if (typeof value !== 'string' || value.trim() === '') {
res.status(400).json({ error: 'value must be a non-empty string' })
return
}
const id = store.addItemByValue(value.trim())
res.json({ id, value: value.trim() })
})
itemsRouter.post('/add', (req, res) => {
const id = req.body?.id
if (id === undefined || id === null || typeof id !== 'number' || !Number.isInteger(id)) {

View File

@@ -87,6 +87,15 @@ export function addItem(id: number): boolean {
return true
}
let nextAutoId = 1_000_001
export function addItemByValue(value: string): number {
const id = nextAutoId++
itemsById.set(id, value)
allItemsOrder.push(id)
return id
}
export function selectItem(id: number): boolean {
if (selectedIds.has(id) || !itemsById.has(id)) return false
selectedIds.add(id)

View File

@@ -72,6 +72,7 @@ const {
deselectItem,
reorderItem,
addItem,
addItemByValue,
} = useItems()
onMounted(() => {
@@ -94,8 +95,10 @@ async function handleReorder(id: number, afterId: number | null): Promise<void>
await reorderItem(id, afterId)
}
async function handleAdd(id: number) {
await addItem(id)
async function handleAdd(value: string) {
const item = await addItemByValue(value)
leftSearch.value = item.value
await fetchLeft(true)
}
</script>

View File

@@ -8,7 +8,7 @@
</h2>
<span v-if="total" class="item-count">{{ total }}</span>
</div>
<button class="btn-primary" @click="showAddModal = true">
<button class="btn-primary" @click="openModal">
<svg width="11" height="11" viewBox="0 0 11 11" fill="none" aria-hidden="true">
<path d="M5.5 1V10M1 5.5H10" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
</svg>
@@ -32,13 +32,15 @@
</div>
</div>
<div class="panel-body">
<div ref="panelBody" class="panel-body" @scroll="onScroll">
<div :style="{ height: topSpacer + 'px' }" aria-hidden="true" />
<ul class="item-list">
<li
v-for="(item, index) in items"
v-for="(item, vIdx) in visibleItems"
:key="item.id"
class="item-row"
:style="{ '--i': Math.min(index, 14) }"
:style="{ '--i': Math.min(vIdx, 14) }"
>
<span class="item-id">#{{ item.id }}</span>
<span class="item-value">{{ item.value }}</span>
@@ -50,6 +52,8 @@
</li>
</ul>
<div :style="{ height: bottomSpacer + 'px' }" aria-hidden="true" />
<div v-if="loading" class="status-row">
<span class="status-dots">
<span /><span /><span />
@@ -75,17 +79,18 @@
</button>
</div>
<input
v-model.number="addIdInput"
ref="addInputEl"
v-model="addValueInput"
class="modal-input"
type="number"
placeholder="Enter item ID"
type="text"
placeholder="Enter item value"
@keydown.enter="submitAdd"
>
<div class="modal-footer">
<button class="btn-ghost" @click="closeModal">
Cancel
</button>
<button class="btn-primary" @click="submitAdd">
<button class="btn-primary" :disabled="!addValueInput.trim()" @click="submitAdd">
Add item
</button>
</div>
@@ -97,7 +102,10 @@
<script setup lang="ts">
import type { Item } from '~/services/api'
import { onUnmounted, ref, watch } from 'vue'
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
const ITEM_HEIGHT = 47
const OVERSCAN = 5
const props = defineProps<{
items: Item[]
@@ -111,12 +119,48 @@ const emit = defineEmits<{
(e: 'update:search', val: string): void
(e: 'loadMore'): void
(e: 'select', id: number): void
(e: 'add', id: number): void
(e: 'add', value: string): void
}>()
// ── Virtual scroll ───────────────────────────────────────────────────────────
const panelBody = ref<HTMLElement | null>(null)
const scrollTop = ref(0)
const containerHeight = ref(500)
function onScroll() {
scrollTop.value = panelBody.value?.scrollTop ?? 0
}
const startIdx = computed(() =>
Math.max(0, Math.floor(scrollTop.value / ITEM_HEIGHT) - OVERSCAN),
)
const endIdx = computed(() =>
Math.min(
props.items.length,
Math.ceil((scrollTop.value + containerHeight.value) / ITEM_HEIGHT) + OVERSCAN,
),
)
const visibleItems = computed(() => props.items.slice(startIdx.value, endIdx.value))
const topSpacer = computed(() => startIdx.value * ITEM_HEIGHT)
const bottomSpacer = computed(() => (props.items.length - endIdx.value) * ITEM_HEIGHT)
let resizeObserver: ResizeObserver | null = null
onMounted(() => {
containerHeight.value = panelBody.value?.clientHeight ?? 500
resizeObserver = new ResizeObserver((entries) => {
const entry = entries[0]
if (entry)
containerHeight.value = entry.contentRect.height
})
if (panelBody.value)
resizeObserver.observe(panelBody.value)
})
// ── Infinite scroll sentinel ─────────────────────────────────────────────────
const sentinel = ref<HTMLElement | null>(null)
const showAddModal = ref(false)
const addIdInput = ref<number | null>(null)
let observer: IntersectionObserver | null = null
watch(sentinel, (el) => {
@@ -136,8 +180,11 @@ watch(sentinel, (el) => {
onUnmounted(() => {
observer?.disconnect()
resizeObserver?.disconnect()
})
// ── Search ───────────────────────────────────────────────────────────────────
let debounceTimer: ReturnType<typeof setTimeout> | null = null
function onSearchInput(e: Event) {
@@ -149,17 +196,29 @@ function onSearchInput(e: Event) {
}, 300)
}
// ── Add modal ────────────────────────────────────────────────────────────────
const showAddModal = ref(false)
const addValueInput = ref('')
const addInputEl = ref<HTMLInputElement | null>(null)
function openModal() {
showAddModal.value = true
nextTick(() => addInputEl.value?.focus())
}
function closeModal() {
showAddModal.value = false
addIdInput.value = null
addValueInput.value = ''
}
function submitAdd() {
if (addIdInput.value !== null && Number.isInteger(addIdInput.value)) {
emit('add', addIdInput.value)
addIdInput.value = null
const value = addValueInput.value.trim()
if (!value)
return
emit('add', value)
addValueInput.value = ''
showAddModal.value = false
}
}
</script>
@@ -280,6 +339,12 @@ function submitAdd() {
&:active {
transform: scale(0.97);
}
&:disabled {
opacity: 0.45;
cursor: not-allowed;
transform: none;
}
}
.btn-ghost {
@@ -520,6 +585,7 @@ function submitAdd() {
font-size: 0.875rem;
color: var(--text-primary);
outline: none;
box-sizing: border-box;
transition:
border-color 150ms ease,
background 150ms ease;
@@ -533,11 +599,6 @@ function submitAdd() {
border-color: var(--text-primary);
background: var(--surface);
}
&::-webkit-inner-spin-button,
&::-webkit-outer-spin-button {
-webkit-appearance: none;
}
}
.modal-footer {

View File

@@ -24,9 +24,11 @@
</div>
</div>
<div ref="panelBody" class="panel-body">
<div ref="panelBody" class="panel-body" @scroll="onScroll">
<div :style="{ height: topSpacer + 'px' }" aria-hidden="true" />
<VueDraggableNext
v-model="localItems"
v-model="visibleSlice"
tag="ul"
class="item-list"
handle=".drag-handle"
@@ -34,10 +36,10 @@
@end="onDragEndFull"
>
<li
v-for="(item, index) in localItems"
v-for="(item, vIdx) in visibleSlice"
:key="item.id"
class="item-row"
:style="{ '--i': Math.min(index, 14) }"
:style="{ '--i': Math.min(vIdx, 14) }"
>
<span class="drag-handle" title="Drag to reorder" aria-hidden="true">
<svg width="8" height="12" viewBox="0 0 8 12" fill="currentColor">
@@ -59,6 +61,8 @@
</li>
</VueDraggableNext>
<div :style="{ height: bottomSpacer + 'px' }" aria-hidden="true" />
<div v-if="loading" class="status-row">
<span class="status-dots">
<span /><span /><span />
@@ -74,9 +78,12 @@
<script setup lang="ts">
import type { Item } from '~/services/api'
import { onUnmounted, ref, watch } from 'vue'
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { VueDraggableNext } from 'vue-draggable-next'
const ITEM_HEIGHT = 47
const OVERSCAN = 5
const props = defineProps<{
items: Item[]
total: number | string
@@ -92,8 +99,62 @@ const emit = defineEmits<{
(e: 'reorder', id: number, afterId: number | null): void
}>()
const sentinel = ref<HTMLElement | null>(null)
// ── Local items (source of truth for drag ordering) ──────────────────────────
const localItems = ref([...props.items])
watch(() => props.items, (val) => {
localItems.value = [...val]
}, { deep: true })
// ── Virtual scroll ───────────────────────────────────────────────────────────
const panelBody = ref<HTMLElement | null>(null)
const scrollTop = ref(0)
const containerHeight = ref(500)
function onScroll() {
scrollTop.value = panelBody.value?.scrollTop ?? 0
}
const startIdx = computed(() =>
Math.max(0, Math.floor(scrollTop.value / ITEM_HEIGHT) - OVERSCAN),
)
const endIdx = computed(() =>
Math.min(
localItems.value.length,
Math.ceil((scrollTop.value + containerHeight.value) / ITEM_HEIGHT) + OVERSCAN,
),
)
// Writable computed: VueDraggableNext reads/writes the visible slice.
// The setter splices changes back into localItems so the full list stays in sync.
const visibleSlice = computed({
get: () => localItems.value.slice(startIdx.value, endIdx.value),
set: (newVal: Item[]) => {
localItems.value.splice(startIdx.value, endIdx.value - startIdx.value, ...newVal)
},
})
const topSpacer = computed(() => startIdx.value * ITEM_HEIGHT)
const bottomSpacer = computed(() => (localItems.value.length - endIdx.value) * ITEM_HEIGHT)
let resizeObserver: ResizeObserver | null = null
onMounted(() => {
containerHeight.value = panelBody.value?.clientHeight ?? 500
resizeObserver = new ResizeObserver((entries) => {
const entry = entries[0]
if (entry)
containerHeight.value = entry.contentRect.height
})
if (panelBody.value)
resizeObserver.observe(panelBody.value)
})
// ── Infinite scroll sentinel ─────────────────────────────────────────────────
const sentinel = ref<HTMLElement | null>(null)
let observer: IntersectionObserver | null = null
watch(sentinel, (el) => {
@@ -132,12 +193,16 @@ function scrollLoop() {
}
function onPointerMoveDrag(e: PointerEvent) {
if (!isDragging || !panelBody.value) return
if (!isDragging || !panelBody.value)
return
const rect = panelBody.value.getBoundingClientRect()
const y = e.clientY - rect.top
if (y >= 0 && y < SCROLL_ZONE) {
scrollSpeed = -((SCROLL_ZONE - y) / SCROLL_ZONE) * SCROLL_MAX_SPEED
}
else if (y > rect.height - SCROLL_ZONE && y <= rect.height) {
scrollSpeed = ((y - (rect.height - SCROLL_ZONE)) / SCROLL_ZONE) * SCROLL_MAX_SPEED
}
else {
scrollSpeed = 0
}
@@ -158,16 +223,23 @@ function onDragEndFull(event: { oldIndex: number, newIndex: number }): void {
cancelAnimationFrame(scrollRafId)
scrollRafId = null
}
const moved = localItems.value[event.newIndex]
if (!moved) return
const after = event.newIndex > 0 ? localItems.value[event.newIndex - 1] : null
// The visibleSlice setter has already applied the reorder to localItems.
// event indices are relative to the visible slice (startIdx offset).
const actualNewIdx = startIdx.value + event.newIndex
const moved = localItems.value[actualNewIdx]
if (!moved)
return
const after = actualNewIdx > 0 ? localItems.value[actualNewIdx - 1] : null
emit('reorder', moved.id!, after?.id ?? null)
}
onUnmounted(() => {
observer?.disconnect()
resizeObserver?.disconnect()
document.removeEventListener('pointermove', onPointerMoveDrag)
if (scrollRafId !== null) cancelAnimationFrame(scrollRafId)
if (scrollRafId !== null)
cancelAnimationFrame(scrollRafId)
})
// ── Search ───────────────────────────────────────────────────────────────────
@@ -182,14 +254,6 @@ function onSearchInput(e: Event) {
emit('update:search', val)
}, 300)
}
// ── Local items for drag-and-drop ────────────────────────────────────────────
const localItems = ref([...props.items])
watch(() => props.items, (val) => {
localItems.value = [...val]
}, { deep: true })
</script>
<style scoped lang="scss">
@@ -342,7 +406,7 @@ watch(() => props.items, (val) => {
display: flex;
align-items: center;
flex-shrink: 0;
padding: 2px;
padding: 6px;
transition: color 120ms ease;
user-select: none;

View File

@@ -114,6 +114,10 @@ export function useItems() {
await Promise.all([fetchLeft(true), fetchRight(true)])
}
async function addItemByValue(value: string): Promise<{ id: number; value: string }> {
return await client.api.itemsAddValueCreate({ value })
}
return {
leftItems,
leftItemsTotal,
@@ -131,5 +135,6 @@ export function useItems() {
deselectItem,
reorderItem,
addItem,
addItemByValue,
}
}

View File

@@ -268,6 +268,25 @@ export class Api<
...params,
}),
/**
* @tags Items
* @name ItemsAddValueCreate
* @summary Create a new item with a given value
* @request POST:/api/items/add-value
*/
itemsAddValueCreate: (
data: { value: string },
params: RequestParams = {},
) =>
this.request<{ id: number; value: string }, void>({
path: `/api/items/add-value`,
method: "POST",
body: data,
type: ContentType.Json,
format: "json",
...params,
}),
/**
* No description
*