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
11 changes: 11 additions & 0 deletions .claude/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"version": "0.0.1",
"configurations": [
{
"name": "client",
"runtimeExecutable": "pnpm",
"runtimeArgs": ["--filter", "client", "dev"],
"port": 5173
}
]
}
19 changes: 18 additions & 1 deletion apps/client/src/components/FieldCanvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ interface FieldCanvasProps {
onAdd: (type: FieldType, insertIndex?: number) => void;
onReorder: (fields: BuilderField[]) => void;
onRemove: (id: string) => void;
isDirty?: boolean;
}

interface BuilderDndProviderProps {
Expand Down Expand Up @@ -201,6 +202,7 @@ export function FieldCanvas({
selectedId,
onSelect,
onRemove,
isDirty = false,
}: Omit<FieldCanvasProps, 'onAdd' | 'onReorder'>) {
const { t } = useI18n();
const { active, over } = useDndContext();
Expand All @@ -226,7 +228,22 @@ export function FieldCanvas({
<div className="card h-100">
<div className="card-header d-flex justify-content-between align-items-center">
<h4 className="card-title mb-0">{t('builder.canvas.title')}</h4>
<span className="text-muted small">{t('builder.saveDraft.label')}</span>
<span
className={`small ${isDirty ? 'text-warning' : 'text-muted'}`}
data-testid="builder-save-status"
>
{isDirty ? (
<>
<i className="ti ti-alert-circle me-1" aria-hidden="true" />
{t('builder.status.unsaved')}
</>
) : (
<>
<i className="ti ti-check me-1" aria-hidden="true" />
{t('builder.status.saved')}
</>
)}
</span>
</div>
<div
className="card-body p-0"
Expand Down
49 changes: 49 additions & 0 deletions apps/client/src/components/UnsavedChangesModal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { useI18n } from '../contexts/I18nContext';

interface UnsavedChangesModalProps {
isOpen: boolean;
onLeave: () => void;
onStay: () => void;
}

export function UnsavedChangesModal({ isOpen, onLeave, onStay }: UnsavedChangesModalProps) {
const { t } = useI18n();

if (!isOpen) return null;

return (
<div
className="modal show d-block"
role="dialog"
aria-modal="true"
aria-labelledby="unsaved-title"
>
<div className="modal-dialog modal-dialog-centered">
<div className="modal-content">
<div className="modal-header">
<h5 id="unsaved-title" className="modal-title">
{t('unsaved.title')}
</h5>
<button
type="button"
className="btn-close"
onClick={onStay}
aria-label={t('common.close')}
/>
</div>
<div className="modal-body">
<p className="mb-0">{t('unsaved.message')}</p>
</div>
<div className="modal-footer">
<button type="button" className="btn btn-secondary" onClick={onStay}>
{t('unsaved.stay')}
</button>
<button type="button" className="btn btn-danger" onClick={onLeave}>
{t('unsaved.leave')}
</button>
</div>
</div>
</div>
</div>
);
}
20 changes: 18 additions & 2 deletions apps/client/src/contexts/I18nContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,15 @@ const resources = {
'builder.options.noOptions': 'Aucune option configurable pour ce type.',
'builder.validation.title': 'Règles de validation',
'builder.validation.noRules': 'Aucune règle pour ce type.',
'builder.saveDraft.label': 'Brouillon enregistré automatiquement',
'builder.deleteFailed':
'Le champ « {{name}} » n’a pas pu être supprimé. Il a été rétabli; réessayez.',
'builder.status.unsaved': 'Modifications non enregistrées',
'builder.status.saved': 'Toutes les modifications sont enregistrées',
'unsaved.title': 'Modifications non enregistrées',
'unsaved.message':
'Cette page contient des modifications qui ne sont pas encore enregistrées. Si vous quittez maintenant, elles seront perdues.',
'unsaved.stay': 'Rester sur la page',
'unsaved.leave': 'Quitter sans enregistrer',
'builder.destructive.title': 'Changement destructif',
'builder.destructive.affectedRecords_one': '{{count}} fiche concernée',
'builder.destructive.affectedRecords_other': '{{count}} fiches concernées',
Expand Down Expand Up @@ -482,7 +490,15 @@ const resources = {
'builder.options.noOptions': 'No configurable options for this type.',
'builder.validation.title': 'Validation rules',
'builder.validation.noRules': 'No rules for this type.',
'builder.saveDraft.label': 'Autosaved draft',
'builder.deleteFailed':
'Field "{{name}}" could not be deleted. It has been restored; please try again.',
'builder.status.unsaved': 'Unsaved changes',
'builder.status.saved': 'All changes saved',
'unsaved.title': 'Unsaved changes',
'unsaved.message':
'This page has changes that have not been saved yet. If you leave now, they will be lost.',
'unsaved.stay': 'Stay on this page',
'unsaved.leave': 'Leave without saving',
'builder.destructive.title': 'Destructive change',
'builder.destructive.affectedRecords_one': '{{count}} record affected',
'builder.destructive.affectedRecords_other': '{{count}} records affected',
Expand Down
7 changes: 5 additions & 2 deletions apps/client/src/lib/apiClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,11 @@ class ApiClient {
});
}

async delete<T>(endpoint: string): Promise<T> {
return this.request<T>(endpoint, { method: 'DELETE' });
async delete<T>(endpoint: string, data?: unknown): Promise<T> {
return this.request<T>(endpoint, {
method: 'DELETE',
body: data === undefined ? undefined : JSON.stringify(data),
});
}
}

Expand Down
104 changes: 104 additions & 0 deletions apps/client/src/routes/__tests__/builder-unsaved-guard.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { apiClient } from '../../lib/apiClient';
import { render } from '../../test/render';

/**
* Captures the options the page passes to useBlocker so the test can ask the page
* the same question the router would: "would leaving right now discard work?".
*/
let blockerOpts: { shouldBlockFn: () => boolean; enableBeforeUnload: () => boolean } | null = null;
let blockerResolver: any = { status: 'idle' };

Check warning on line 13 in apps/client/src/routes/__tests__/builder-unsaved-guard.test.tsx

View workflow job for this annotation

GitHub Actions / Lint

Unexpected any. Specify a different type

vi.mock('@tanstack/react-router', () => ({
createFileRoute: () => () => ({}),
useParams: () => ({ databaseId: 'db-1', tableId: 'tbl-1' }),
useBlocker: (opts: any) => {

Check warning on line 18 in apps/client/src/routes/__tests__/builder-unsaved-guard.test.tsx

View workflow job for this annotation

GitHub Actions / Lint

Unexpected any. Specify a different type
blockerOpts = opts;
return blockerResolver;
},
}));

import StructureBuilder from '../builder.$databaseId.$tableId';

const mockDatabase = { id: 'db-1', name: 'Patrimoine', workspace_id: 'ws-1' };
const mockTable = { id: 'tbl-1', name: 'Ouvrages', database_id: 'db-1' };
const mockFields = [
{
id: 'f1',
name: 'Titre',
type: 'title',
position: 0,
options: {},
validation: {},
table_id: 'tbl-1',
},
];

function renderBuilder() {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<QueryClientProvider client={queryClient}>
<StructureBuilder />
</QueryClientProvider>
);
}

describe('schema builder unsaved-changes guard', () => {
beforeEach(() => {
blockerOpts = null;
blockerResolver = { status: 'idle' };
vi.spyOn(apiClient, 'get').mockImplementation((url: string) => {
if (url.startsWith('/databases/')) return Promise.resolve(mockDatabase) as any;

Check warning on line 54 in apps/client/src/routes/__tests__/builder-unsaved-guard.test.tsx

View workflow job for this annotation

GitHub Actions / Lint

Unexpected any. Specify a different type
if (url.startsWith('/tables/')) return Promise.resolve(mockTable) as any;

Check warning on line 55 in apps/client/src/routes/__tests__/builder-unsaved-guard.test.tsx

View workflow job for this annotation

GitHub Actions / Lint

Unexpected any. Specify a different type
if (url.startsWith('/fields?')) return Promise.resolve(mockFields) as any;

Check warning on line 56 in apps/client/src/routes/__tests__/builder-unsaved-guard.test.tsx

View workflow job for this annotation

GitHub Actions / Lint

Unexpected any. Specify a different type
if (url.startsWith('/tables?')) return Promise.resolve([mockTable]) as any;

Check warning on line 57 in apps/client/src/routes/__tests__/builder-unsaved-guard.test.tsx

View workflow job for this annotation

GitHub Actions / Lint

Unexpected any. Specify a different type
return Promise.resolve([]) as any;
});
});

it('does not block navigation when the draft matches what was loaded', async () => {
renderBuilder();

expect(await screen.findByText('All changes saved')).toBeInTheDocument();
expect(blockerOpts?.shouldBlockFn()).toBe(false);
expect(blockerOpts?.enableBeforeUnload()).toBe(false);
});

it('blocks navigation and warns once a field is edited', async () => {
const user = userEvent.setup();
renderBuilder();

const nameInput = await screen.findByLabelText('Field name');
await user.type(nameInput, ' modifié');

await waitFor(() => {
expect(screen.getByText('Unsaved changes')).toBeInTheDocument();
});

// Both in-app navigation and tab close/reload must be guarded.
expect(blockerOpts?.shouldBlockFn()).toBe(true);
expect(blockerOpts?.enableBeforeUnload()).toBe(true);
});

it('offers to stay or leave when the router reports a blocked navigation', async () => {
const user = userEvent.setup();
const proceed = vi.fn();
const reset = vi.fn();
blockerResolver = { status: 'blocked', proceed, reset };

renderBuilder();

expect(await screen.findByRole('dialog')).toBeInTheDocument();
expect(screen.getByText(/have not been saved yet/i)).toBeInTheDocument();

await user.click(screen.getByRole('button', { name: 'Stay on this page' }));
expect(reset).toHaveBeenCalledTimes(1);
expect(proceed).not.toHaveBeenCalled();

await user.click(screen.getByRole('button', { name: 'Leave without saving' }));
expect(proceed).toHaveBeenCalledTimes(1);
});
});
Loading
Loading