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: * 400:
* description: Invalid id * 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) => { itemsRouter.post('/add', (req, res) => {
const id = req.body?.id const id = req.body?.id
if (id === undefined || id === null || typeof id !== 'number' || !Number.isInteger(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 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 { export function selectItem(id: number): boolean {
if (selectedIds.has(id) || !itemsById.has(id)) return false if (selectedIds.has(id) || !itemsById.has(id)) return false
selectedIds.add(id) selectedIds.add(id)

View File

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

View File

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

View File

@@ -24,9 +24,11 @@
</div> </div>
</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 <VueDraggableNext
v-model="localItems" v-model="visibleSlice"
tag="ul" tag="ul"
class="item-list" class="item-list"
handle=".drag-handle" handle=".drag-handle"
@@ -34,10 +36,10 @@
@end="onDragEndFull" @end="onDragEndFull"
> >
<li <li
v-for="(item, index) in localItems" v-for="(item, vIdx) in visibleSlice"
:key="item.id" :key="item.id"
class="item-row" 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"> <span class="drag-handle" title="Drag to reorder" aria-hidden="true">
<svg width="8" height="12" viewBox="0 0 8 12" fill="currentColor"> <svg width="8" height="12" viewBox="0 0 8 12" fill="currentColor">
@@ -59,6 +61,8 @@
</li> </li>
</VueDraggableNext> </VueDraggableNext>
<div :style="{ height: bottomSpacer + 'px' }" aria-hidden="true" />
<div v-if="loading" class="status-row"> <div v-if="loading" class="status-row">
<span class="status-dots"> <span class="status-dots">
<span /><span /><span /> <span /><span /><span />
@@ -74,9 +78,12 @@
<script setup lang="ts"> <script setup lang="ts">
import type { Item } from '~/services/api' 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' import { VueDraggableNext } from 'vue-draggable-next'
const ITEM_HEIGHT = 47
const OVERSCAN = 5
const props = defineProps<{ const props = defineProps<{
items: Item[] items: Item[]
total: number | string total: number | string
@@ -92,8 +99,62 @@ const emit = defineEmits<{
(e: 'reorder', id: number, afterId: number | null): void (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 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 let observer: IntersectionObserver | null = null
watch(sentinel, (el) => { watch(sentinel, (el) => {
@@ -132,12 +193,16 @@ function scrollLoop() {
} }
function onPointerMoveDrag(e: PointerEvent) { function onPointerMoveDrag(e: PointerEvent) {
if (!isDragging || !panelBody.value) return if (!isDragging || !panelBody.value)
return
const rect = panelBody.value.getBoundingClientRect() const rect = panelBody.value.getBoundingClientRect()
const y = e.clientY - rect.top const y = e.clientY - rect.top
if (y >= 0 && y < SCROLL_ZONE) { if (y >= 0 && y < SCROLL_ZONE) {
scrollSpeed = -((SCROLL_ZONE - y) / SCROLL_ZONE) * SCROLL_MAX_SPEED 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 { else {
scrollSpeed = 0 scrollSpeed = 0
} }
@@ -158,16 +223,23 @@ function onDragEndFull(event: { oldIndex: number, newIndex: number }): void {
cancelAnimationFrame(scrollRafId) cancelAnimationFrame(scrollRafId)
scrollRafId = null scrollRafId = null
} }
const moved = localItems.value[event.newIndex]
if (!moved) return // The visibleSlice setter has already applied the reorder to localItems.
const after = event.newIndex > 0 ? localItems.value[event.newIndex - 1] : null // 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) emit('reorder', moved.id!, after?.id ?? null)
} }
onUnmounted(() => { onUnmounted(() => {
observer?.disconnect() observer?.disconnect()
resizeObserver?.disconnect()
document.removeEventListener('pointermove', onPointerMoveDrag) document.removeEventListener('pointermove', onPointerMoveDrag)
if (scrollRafId !== null) cancelAnimationFrame(scrollRafId) if (scrollRafId !== null)
cancelAnimationFrame(scrollRafId)
}) })
// ── Search ─────────────────────────────────────────────────────────────────── // ── Search ───────────────────────────────────────────────────────────────────
@@ -182,14 +254,6 @@ function onSearchInput(e: Event) {
emit('update:search', val) emit('update:search', val)
}, 300) }, 300)
} }
// ── Local items for drag-and-drop ────────────────────────────────────────────
const localItems = ref([...props.items])
watch(() => props.items, (val) => {
localItems.value = [...val]
}, { deep: true })
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
@@ -342,7 +406,7 @@ watch(() => props.items, (val) => {
display: flex; display: flex;
align-items: center; align-items: center;
flex-shrink: 0; flex-shrink: 0;
padding: 2px; padding: 6px;
transition: color 120ms ease; transition: color 120ms ease;
user-select: none; user-select: none;

View File

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

View File

@@ -268,6 +268,25 @@ export class Api<
...params, ...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 * No description
* *