Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ A clean, cloud-synced web app for cataloguing your physical storage boxes and th

- **Box & Item Catalog** - Create boxes with a name, location, description, tags and photos, and add items to them
- **Photos** - Attach several photos to any box or item, taken with the in-app camera or picked from the gallery; open them fullscreen with pinch and double-tap zoom
- **No Accidental Duplicates** - While you type the name of a new box or item, existing ones with a similar name (typos included) are listed under the field; tap one to open it instead of creating it again
- **Box Locations** - Record where each box physically is ("attic, shelf 2"); earlier locations are offered as you type
- **Fuzzy Search** - Find items by name, description or tag, powered by [Fuse.js](https://www.fusejs.io/). Searching the box list also looks at locations and inside the boxes, and says which item matched
- **Tagging System** - Boxes and items share one tag vocabulary; rename, merge or delete a tag everywhere from a central manager
Expand Down Expand Up @@ -75,6 +76,12 @@ over it.
3. Give it a name and, optionally, a location, a description, tags and photos.
4. Open the box and tap **+** again to start cataloguing its contents.

While you type a name, boxes or items you already have with a similar name are
listed under the field. Tap one (or reach it with the arrow keys and press
Enter) to open it instead: a box opens, an item opens in its edit form, where it
can be moved to another box. The list is only a reminder; **Create Box** and
**Add Item** still create a new one.

### Navigating

| View | How to reach it |
Expand Down
3 changes: 3 additions & 0 deletions src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2127,6 +2127,8 @@ function App() {
askConfirm={askConfirm}
knownLocations={knownLocations}
availableTags={tagSuggestions}
boxes={boxes}
onOpenExisting={handleBoxClick}
/>

<AddItemModal
Expand All @@ -2138,6 +2140,7 @@ function App() {
availableItems={allItems}
availableTags={tagSuggestions}
onSelectExisting={handleSelectExistingItem}
onOpenExisting={handleEditItem}
askConfirm={askConfirm}
/>

Expand Down
38 changes: 26 additions & 12 deletions src/components/AddBoxModal.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ import { usePhotoCapture } from '../native/usePhotoCapture';
import { useTranslation } from '../translations';
import { LocationInput } from './LocationInput';
import { TagInput } from './TagInput';
import { NameInputWithMatches } from './NameInputWithMatches';
import { parseTagInput } from '../utils/tagUtils';

export function AddBoxModal({ isOpen, onClose, onAdd, askConfirm, knownLocations = [], availableTags = [] }) {
export function AddBoxModal({ isOpen, onClose, onAdd, askConfirm, knownLocations = [], availableTags = [], boxes = [], onOpenExisting }) {
const { t } = useTranslation();
const [name, setName] = useState('');
const [description, setDescription] = useState('');
Expand Down Expand Up @@ -46,6 +47,13 @@ export function AddBoxModal({ isOpen, onClose, onAdd, askConfirm, knownLocations
if (typeof onClose === 'function') onClose();
};

// The box being described already exists: open it instead of making a
// second one.
const handleOpenExisting = (box) => {
handleClose();
if (typeof onOpenExisting === 'function') onOpenExisting(box);
};

const handleFileChange = async (e) => {
// Capture the firing input up front so we can reset it after the await
// (works for both the camera and the gallery input).
Expand Down Expand Up @@ -115,17 +123,23 @@ export function AddBoxModal({ isOpen, onClose, onAdd, askConfirm, knownLocations
return (
<Modal isOpen={isOpen} onClose={handleClose} title={t('box.addTitle')}>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-sm font-medium text-muted mb-1">{t('common.name')}</label>
<input
type="text"
required
value={name}
onChange={(e) => setName(e.target.value)}
className="input"
placeholder={t('box.namePlaceholder')}
/>
</div>
<NameInputWithMatches
label={t('common.name')}
value={name}
onChange={setName}
placeholder={t('box.namePlaceholder')}
candidates={boxes}
heading={(count) => t('box.existingMatches', { count })}
renderLabel={(box) => (
<span className="block text-sm font-medium text-content line-clamp-2 break-words">
{box.name}
{box.location && (
<span className="font-normal text-muted"> / {box.location}</span>
)}
</span>
)}
onPick={handleOpenExisting}
/>

<LocationInput
value={location}
Expand Down
36 changes: 24 additions & 12 deletions src/components/AddItemModal.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@ import { CameraCaptureModal } from './CameraCaptureModal';
import { FullscreenImageModal } from './FullscreenImageModal';
import { TagInput } from './TagInput';
import { BoxPicker } from './BoxPicker';
import { NameInputWithMatches } from './NameInputWithMatches';
import { Upload, Trash2, Search, Camera, Package, X, Check } from 'lucide-react';
import { makeDerivatives, refsToThumbs, getImageRefs } from '../utils/imageUtils';
import { useModalDraft, clearDraft } from '../utils/draftStorage';
import { usePhotoCapture } from '../native/usePhotoCapture';
import { useTranslation } from '../translations';
import { parseTagInput } from '../utils/tagUtils';

export function AddItemModal({ isOpen, onClose, onAdd, boxes = [], initialBoxId = '', availableItems = [], availableTags = [], onSelectExisting, askConfirm }) {
export function AddItemModal({ isOpen, onClose, onAdd, boxes = [], initialBoxId = '', availableItems = [], availableTags = [], onSelectExisting, onOpenExisting, askConfirm }) {
const { t, lang } = useTranslation();
const [mode, setMode] = useState('create'); // 'create' | 'select'
const [name, setName] = useState('');
Expand Down Expand Up @@ -66,6 +67,13 @@ export function AddItemModal({ isOpen, onClose, onAdd, boxes = [], initialBoxId
if (typeof onClose === 'function') onClose();
};

// The thing being typed already exists: open it (where it can also be
// moved to this box) instead of filing a second one.
const handleOpenExisting = (item) => {
handleClose();
if (typeof onOpenExisting === 'function') onOpenExisting(item);
};

// Filter items that can be selected (exclude items already in current box)
const selectableItems = useMemo(() => {
return availableItems.filter(item => item.boxId !== initialBoxId);
Expand Down Expand Up @@ -228,17 +236,21 @@ export function AddItemModal({ isOpen, onClose, onAdd, boxes = [], initialBoxId
{/* Create New Mode */}
{mode === 'create' && (
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-sm font-medium text-muted mb-1">{t('common.name')}</label>
<input
type="text"
required
value={name}
onChange={(e) => setName(e.target.value)}
className="input"
placeholder={t('item.namePlaceholder')}
/>
</div>
<NameInputWithMatches
label={t('common.name')}
value={name}
onChange={setName}
placeholder={t('item.namePlaceholder')}
candidates={availableItems}
heading={(count) => t('item.existingMatches', { count })}
renderLabel={(item) => (
<>
<span className="block text-sm font-medium text-content truncate">{item.name}</span>
<span className="block text-xs text-muted truncate">{getBoxName(item.boxId)}</span>
</>
)}
onPick={handleOpenExisting}
/>

<BoxPicker value={selectedBoxId} onChange={setSelectedBoxId} boxes={boxes} />

Expand Down
179 changes: 179 additions & 0 deletions src/components/NameInputWithMatches.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
import Fuse from 'fuse.js';
import { Package, ChevronRight } from 'lucide-react';
import { useBackHandler } from '../native/backHandler';
import { getImageRefs, refsToThumbs } from '../utils/imageUtils';

const MIN_QUERY = 2;
const MAX_MATCHES = 5;

/**
* The name field of a create form, with the existing boxes or items whose
* names look like what is being typed listed under it, so "Зимно яке" is
* opened rather than created a second time.
*
* A hint, not a gate: the form's own button still creates, and Enter still
* submits unless the arrows have reached a row first. Not an autocomplete
* either, which is why the list is headed by `heading` ("you already have")
* and a pick opens the existing entry instead of filling in the field.
* `heading` is a function of the number of matches, for the plural.
*
* Fuzzy on the name only, so a typo still finds the duplicate;
* `ignoreLocation` because a long name is as likely to match in the middle as
* at the start. Combobox mechanics follow BoxPicker.
*/
export function NameInputWithMatches({
label,
value,
onChange,
placeholder,
candidates = [],
heading,
renderLabel,
onPick,
}) {
const id = useId();
const wrapRef = useRef(null);
const listRef = useRef(null);
const [focused, setFocused] = useState(false);
const [dismissed, setDismissed] = useState(false);
// -1 = nothing highlighted, so Enter submits the form as before. Only the
// arrows move it (no hover tracking, unlike BoxPicker): a pointer resting
// on a row must not turn Enter into "open this one".
const [active, setActive] = useState(-1);

const fuse = useMemo(
() => new Fuse(candidates, { keys: ['name'], threshold: 0.3, ignoreLocation: true }),
[candidates]
);

const q = value.trim();
const matches = useMemo(
() => (q.length >= MIN_QUERY ? fuse.search(q, { limit: MAX_MATCHES }).map(r => r.item) : []),
[q, fuse]
);

const open = focused && !dismissed && matches.length > 0;

const close = useCallback(() => {
setDismissed(true);
setActive(-1);
}, []);

// Android Back closes the list before it closes the modal.
useBackHandler(open, close);

// Keep the highlighted row in view, scrolling the list only, not the
// modal behind it, which would jump under the keyboard.
useEffect(() => {
const list = listRef.current;
const row = list?.querySelector(`[data-index="${active}"]`);
if (!row) return;
if (row.offsetTop < list.scrollTop) {
list.scrollTop = row.offsetTop;
} else if (row.offsetTop + row.offsetHeight > list.scrollTop + list.clientHeight) {
list.scrollTop = row.offsetTop + row.offsetHeight - list.clientHeight;
}
}, [active, open]);

const handleKeyDown = (e) => {
if (e.nativeEvent.isComposing) return;
if (e.key === 'ArrowDown') {
if (!matches.length) return;
e.preventDefault();
setDismissed(false);
setActive(i => (open ? Math.min(i + 1, matches.length - 1) : 0));
} else if (e.key === 'ArrowUp' && open) {
e.preventDefault();
setActive(i => Math.max(i - 1, -1));
} else if (e.key === 'Enter' && open && matches[active]) {
e.preventDefault();
onPick(matches[active]);
} else if (e.key === 'Escape' && open) {
// Stop here, or the modal's Escape listener closes the whole form.
e.preventDefault();
e.stopPropagation();
close();
}
};

const optionId = (index) => `${id}-opt-${index}`;

return (
<div
ref={wrapRef}
className="relative"
onFocus={() => setFocused(true)}
onBlur={(e) => {
if (!wrapRef.current?.contains(e.relatedTarget)) {
setFocused(false);
setActive(-1);
}
}}
>
<label htmlFor={`${id}-input`} className="block text-sm font-medium text-muted mb-1">
{label}
</label>
<input
id={`${id}-input`}
type="text"
required
role="combobox"
aria-expanded={open}
aria-controls={`${id}-list`}
aria-autocomplete="list"
aria-activedescendant={open && matches[active] ? optionId(active) : undefined}
value={value}
onChange={(e) => {
onChange(e.target.value);
setDismissed(false);
setActive(-1);
}}
onKeyDown={handleKeyDown}
className="input"
placeholder={placeholder}
/>

{open && (
<div
ref={listRef}
id={`${id}-list`}
role="listbox"
aria-label={heading(matches.length)}
className="box-picker__list"
// Keep focus where it is: a tap on a row must not blur the
// field (and close the list) before the click lands.
onPointerDown={(e) => e.preventDefault()}
>
<div aria-hidden="true" className="px-2 pt-1.5 pb-1 text-xs font-semibold uppercase tracking-wider text-muted">
{heading(matches.length)}
</div>
{matches.map((entry, index) => {
const thumb = refsToThumbs(getImageRefs(entry))[0];
return (
<div
key={entry.id}
id={optionId(index)}
data-index={index}
role="option"
aria-selected={index === active}
onClick={() => onPick(entry)}
className={`picker-row cursor-pointer ${index === active ? 'box-picker__row--active' : ''}`}
>
{thumb ? (
<img src={thumb} alt="" className="picker-row__thumb" />
) : (
<span className="picker-row__thumb flex items-center justify-center text-muted">
<Package size={18} />
</span>
)}
<span className="flex-1 min-w-0">{renderLabel(entry)}</span>
<ChevronRight size={18} className="shrink-0 text-muted" aria-hidden="true" />
</div>
);
})}
</div>
)}
</div>
);
}
4 changes: 4 additions & 0 deletions src/translations/bg.json
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@
"box.edit": "Редактирай {{box.the}}",
"box.editAria": "Редактирай {{name}}",
"box.namePlaceholder": "напр. Инструменти от гаража",
"box.existingMatches_one": "Вече имаш {{box.similar}} {{box.one}}:",
"box.existingMatches_other": "Вече имаш подобни {{box.many}}:",
"box.descriptionPlaceholder": "Какво има в {{box.the}}?",
"box.actions": "Действия с {{box.the}}",
"box.removeKeepItems": "Премахни (запази {{item.theMany}})",
Expand Down Expand Up @@ -114,6 +116,8 @@
"item.editAria": "Редактирай {{name}}",
"item.actions": "Действия с {{item.the}}",
"item.namePlaceholder": "напр. Чук",
"item.existingMatches_one": "Вече имаш {{item.similar}} {{item.one}}:",
"item.existingMatches_other": "Вече имаш подобни {{item.many}}:",
"item.descriptionPlaceholder": "Подробности за {{item.the}}...",
"item.tagsPlaceholder": "инструмент, тежко, метал...",
"item.tagsHint": "Докосни, за да добавиш",
Expand Down
4 changes: 4 additions & 0 deletions src/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@
"box.edit": "Edit {{^box.one}}",
"box.editAria": "Edit {{name}}",
"box.namePlaceholder": "e.g., Garage Tools",
"box.existingMatches_one": "You already have a {{box.similar}} {{box.one}}:",
"box.existingMatches_other": "You already have {{box.similar}} {{box.many}}:",
"box.descriptionPlaceholder": "What's in this {{box.one}}?",
"box.actions": "{{^box.one}} actions",
"box.removeKeepItems": "Remove (keep {{item.many}})",
Expand Down Expand Up @@ -114,6 +116,8 @@
"item.editAria": "Edit {{name}}",
"item.actions": "{{^item.one}} actions",
"item.namePlaceholder": "e.g., Hammer",
"item.existingMatches_one": "You already have a {{item.similar}} {{item.one}}:",
"item.existingMatches_other": "You already have {{item.similar}} {{item.many}}:",
"item.descriptionPlaceholder": "Details about the {{item.one}}...",
"item.tagsPlaceholder": "tool, heavy, metal...",
"item.tagsHint": "Tap chips to add",
Expand Down
3 changes: 2 additions & 1 deletion src/translations/terms.bg.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"optimized": { "m": "оптимизиран", "f": "оптимизирана", "n": "оптимизирано" },
"found": { "m": "намерен", "f": "намерена", "n": "намерено" },
"previous": { "m": "предишен", "f": "предишна", "n": "предишно" },
"next": { "m": "следващ", "f": "следваща", "n": "следващо" }
"next": { "m": "следващ", "f": "следваща", "n": "следващо" },
"similar": { "m": "подобен", "f": "подобна", "n": "подобно" }
}
}
3 changes: 2 additions & 1 deletion src/translations/terms.en.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"optimized": "Optimized",
"found": "found",
"previous": "previous",
"next": "next"
"next": "next",
"similar": "similar"
}
}
Loading