wip
This commit is contained in:
commit
d8f2407ddf
44 changed files with 10377 additions and 0 deletions
7
.gitignore
vendored
Normal file
7
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
node_modules/
|
||||
dist/
|
||||
test-results/
|
||||
playwright-report/
|
||||
*.local
|
||||
.DS_Store
|
||||
*.tsbuildinfo
|
||||
5
.prettierignore
Normal file
5
.prettierignore
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
node_modules
|
||||
dist
|
||||
test-results
|
||||
playwright-report
|
||||
package-lock.json
|
||||
1
.prettierrc.json
Normal file
1
.prettierrc.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{ "singleQuote": true, "printWidth": 100, "trailingComma": "all" }
|
||||
59
README.md
Normal file
59
README.md
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
# Floor planner
|
||||
|
||||
A single-page flooring and skirting planner built with Vite, React and TypeScript. All measurements use millimetres; areas are displayed in square metres. Run it locally or host `dist/` on any static web host.
|
||||
|
||||
```sh
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Use a supported Node.js release (22.12+ or 24+). Open the local URL printed by Vite.
|
||||
|
||||
```sh
|
||||
npm test # Pure geometry, planning, URL and CSV tests
|
||||
npx playwright install chromium
|
||||
npm run test:e2e # Desktop Chromium and mobile-sized Chromium
|
||||
npm run build # Strict TypeScript check and production build
|
||||
npm run check # Build, unit tests and browser tests
|
||||
```
|
||||
|
||||
## Planning workflow
|
||||
|
||||
1. Start with a rectangle, fireplace recess, or custom outline. Enter wall lengths in order. The first wall runs east; the turn **after** each wall is positive for right and negative for left. For example, a clockwise rectangle has 90° turns. The final corner is derived from the closed outline.
|
||||
2. Add door openings with a width and an offset from the wall's start. Include architrave/trim in the width where skirting must be omitted. Doors terminate skirting; laminate ends at the room outline with a transition and expansion gap. Rooms are planned independently.
|
||||
3. For a custom outline, the closing-wall suggestion gives the required length and turn. Add it, then replace the suggested length with the actual measured length. An outline must close within the chosen tolerance and have no intersections or invalid doors before a cut plan can be produced.
|
||||
4. Set material dimensions, spacer, kerf and minimum piece sizes alongside the measurements. Kerf means material removed by the blade: a 3 mm cut leaves 600 mm + 397 mm from a 1,000 mm board. Both kerf fields have keyboard and touch tooltips. Skirting stock lengths are purchase options, not a fixed inventory. Materials are shared across rooms; direction is per room.
|
||||
5. The drawing and cut plan update on the same page. Flooring and skirting are visible together, with the whole drawing fitting the page without an internal scrollbar. Warnings follow their room, even when rooms share a name. Every installed board is drawn, including full lengths without labels. Only cuts and reusable offcuts receive sequential codes starting at F1 for flooring and A1 for the first room’s skirting. Identical flooring cuts share a batch row; each piece has a small shape preview that opens exact dimensions in a popup. Skirting previews use equal scales on both axes, with close-ups of each end to show the actual mitre angle. Source allocations identify the stock used by each piece. Export CSV for both materials, or print the plan.
|
||||
6. Copy the link to save or share the complete project. Measurements, materials, selected room and selected piece live in a compressed, versioned URL fragment. Old links containing steps, layers and zoom still load; those obsolete view choices are ignored. Reloading or opening that link reproduces the plan. Browser back/forward restores room changes. There is no local storage, account, API, database or analytics. Fonts are system fonts; the app makes no external font requests.
|
||||
|
||||
## Calculation rules and practical limits
|
||||
|
||||
- Geometry follows measured vectors, checks final-wall length/direction, detects crossings and validates opening bounds and overlaps. A small accepted closure residual snaps only the final wall to the origin, with a visible warning. A mismatch can indicate measurement error or an irregular wall; lengths and corner angles alone cannot identify or reconstruct a bow. Remeasure and represent known changes of direction as additional segments.
|
||||
- Polygon offsets and clipping use `clipper-lib` at 0.001 mm internal precision. Displayed dimensions are rounded to 0.1 mm. The supplied cut templates contain board-relative polygon vertices and edge lengths for angled and notched pieces.
|
||||
- Laminate is inset from every wall, including fireplace recesses. Interior rows retain full factory width. When the final row would be narrower than the minimum, the first and last rows share the width equally. A bounded search also compares other feasible edge-row arrangements.
|
||||
- Brick uses a half-board stagger. Random is deterministic, prefers usable offcuts and avoids a repeating two-row sequence when feasible. The offset is the nearest end-joint distance on the adjacent row's grid, not a distance from a wall. Half a board is the largest possible nearest-joint offset. Settings that cannot be met produce an error instead of a partial layout.
|
||||
- Minimum laminate sizes apply to each clipped piece's bounding length/width. Irregular shapes can still have narrow tips or necks; their exact templates are available in the cut popups. Product-specific click systems and assembly sequences are not simulated.
|
||||
- Offcut reuse preserves the needed left/right factory ends. Only full-width end remnants are available for reuse; ripped side strips and shaped scraps are conservatively waste. Crosscuts include kerf. The stock count is actual allocated boards, not an area-only estimate. Waste includes kerf and unused material, including still-usable stock remainders.
|
||||
- Skirting internal corners use butt joints: the previous wall runs through and the next is shortened by thickness, adjusted for non-square corners. Coping is excluded. External corners use equal mitres. Minimum sizes apply after corner allowances and door subtraction. An unavoidable undersized run is an error.
|
||||
- Skirting cut lengths are the longest-point envelope. Cut square blanks first, then bevel their ends as specified; this keeps reusable stock remainders square. Back lengths and diagram positions locate the wall-facing edge. The stock allocation includes crosscut kerf and counts the additional bevel passes.
|
||||
- Flooring uses a bounded beam search, minimizing purchased boards, then saw passes. Skirting compares full-stock, balanced and offcut-aware splits and packs them across offered lengths, preferring less waste, then fewer cuts. Available offcuts can move the next wall’s joints. Minimum lengths are reserved on both front and back edges of angled pieces. These are deterministic, auditable heuristics rather than guarantees of a global minimum. Room order is an input and can affect shared-offcut allocation.
|
||||
- Board counts exclude an extra allowance for damage or mistakes. Spacer, minimum size and staggering defaults are editable starting values; follow the exact product's installation instructions. For example, [Quick-Step's installation guidance](https://www.quick-step.co.uk/en-gb/laminate/installation) provides product-specific manuals, and its [room-transition guidance](https://www.quick-step.co.uk/en-gb/frequently-asked-questions/laminate/preparation-and-installation/do-i-really-need-expansion-gaps-between-every-room) explains separate expansion joints.
|
||||
- Links are bounded to 20 rooms, 100 walls per room and 30 doors per wall. Flooring calculations are bounded to 2,000 purchased boards and 500 rows per room. Large plans may take longer; very large projects should be split into separate links. Long links may exceed the limits of a messaging service.
|
||||
|
||||
## Code map
|
||||
|
||||
| File | Responsibility |
|
||||
| ------------------------ | ----------------------------------------------------------- |
|
||||
| `src/lib/types.ts` | Inputs and derived result contracts |
|
||||
| `src/lib/defaults.ts` | Starter measurements and deterministic IDs |
|
||||
| `src/lib/geometry.ts` | Vector tracing, closure, validation and polygon offsets |
|
||||
| `src/lib/flooring.ts` | Row search, clipping, factory-end-aware stock allocation |
|
||||
| `src/lib/skirting.ts` | Corner allowances, run splitting and stock allocation |
|
||||
| `src/lib/url-state.ts` | Canonical schema, compression and untrusted-link validation |
|
||||
| `src/lib/use-project.ts` | URL and browser-history synchronization |
|
||||
| `src/lib/export.ts` | CSV generation, including formula-injection protection |
|
||||
| `src/components/` | Editors, SVG drawing and linked cut tables |
|
||||
| `tests/` | Pure calculation and state tests |
|
||||
| `e2e/` | Actual browser workflows at desktop and mobile sizes |
|
||||
|
||||
Only the inputs and view selections are persisted. Geometry, plans, quantities, warning messages and drawings are derived. There are no timestamps or random-number calls in the planners. `npm run build` also checks unused variables and strict TypeScript types.
|
||||
580
e2e/planner.spec.ts
Normal file
580
e2e/planner.spec.ts
Normal file
|
|
@ -0,0 +1,580 @@
|
|||
import { expect, test } from '@playwright/test';
|
||||
import type { Page } from '@playwright/test';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { decodeState } from '../src/lib/url-state';
|
||||
import { planFlooring } from '../src/lib/flooring';
|
||||
import { planSkirting } from '../src/lib/skirting';
|
||||
import { flooringCuts, skirtingCuts, uncutFlooring } from '../src/lib/cut-list';
|
||||
import { mm } from '../src/lib/format';
|
||||
|
||||
const errors = new WeakMap<Page, string[]>();
|
||||
const preview = (page: Page) => page.getByRole('region', { name: 'Floor plan preview' });
|
||||
const floorRows = (page: Page) =>
|
||||
page.getByRole('table', { name: 'Flooring cuts and offcut placements' }).locator('tbody tr');
|
||||
const skirtRows = (page: Page) =>
|
||||
page.getByRole('table', { name: 'Skirting pieces requiring cuts' }).locator('tbody tr');
|
||||
const floorCodes = (page: Page) =>
|
||||
floorRows(page).getByRole('button', { name: /^Preview flooring cut / });
|
||||
const skirtCodes = (page: Page) =>
|
||||
skirtRows(page).getByRole('button', { name: /^Preview skirting cut / });
|
||||
const state = (page: Page) => decodeState(new URL(page.url()).hash).state;
|
||||
const plans = (page: Page) => {
|
||||
const { project } = state(page);
|
||||
return {
|
||||
project,
|
||||
floor: planFlooring(project.rooms, project.flooring, project.tolerance),
|
||||
skirt: planSkirting(project.rooms, project.skirting, project.tolerance),
|
||||
};
|
||||
};
|
||||
|
||||
async function openWalls(page: Page) {
|
||||
if (
|
||||
!(await page
|
||||
.locator('.wall-details')
|
||||
.evaluate((element) => (element as HTMLDetailsElement).open))
|
||||
) {
|
||||
await page.locator('.wall-details summary').click();
|
||||
}
|
||||
}
|
||||
|
||||
async function noHorizontalOverflow(page: Page) {
|
||||
expect(
|
||||
await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1),
|
||||
).toBe(true);
|
||||
}
|
||||
|
||||
async function noDrawingScroll(page: Page) {
|
||||
const scrollContainers = await preview(page).evaluate((root) =>
|
||||
[root, ...root.querySelectorAll('*')]
|
||||
.filter((element): element is HTMLElement => element instanceof HTMLElement)
|
||||
.filter((element) => {
|
||||
const style = getComputedStyle(element);
|
||||
return (
|
||||
(/auto|scroll/.test(style.overflowX) && element.scrollWidth > element.clientWidth + 1) ||
|
||||
(/auto|scroll/.test(style.overflowY) && element.scrollHeight > element.clientHeight + 1)
|
||||
);
|
||||
})
|
||||
.map((element) => element.className),
|
||||
);
|
||||
expect(
|
||||
scrollContainers,
|
||||
'The room drawing must use the page scroll, without its own scrollbars',
|
||||
).toEqual([]);
|
||||
}
|
||||
|
||||
async function noWallLabelOverlap(page: Page) {
|
||||
const labels = await preview(page)
|
||||
.locator('.wall-label text')
|
||||
.evaluateAll((elements) =>
|
||||
elements.map((element) => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
return {
|
||||
text: element.textContent,
|
||||
x: rect.x,
|
||||
y: rect.y,
|
||||
right: rect.right,
|
||||
bottom: rect.bottom,
|
||||
};
|
||||
}),
|
||||
);
|
||||
expect(labels).toHaveLength(8);
|
||||
const overlaps: string[] = [];
|
||||
labels.forEach((label, i) =>
|
||||
labels.slice(i + 1).forEach((other) => {
|
||||
if (
|
||||
Math.min(label.right, other.right) - Math.max(label.x, other.x) > 0.5 &&
|
||||
Math.min(label.bottom, other.bottom) - Math.max(label.y, other.y) > 0.5
|
||||
) {
|
||||
overlaps.push(`${label.text} overlaps ${other.text}`);
|
||||
}
|
||||
}),
|
||||
);
|
||||
expect(overlaps, 'Fireplace wall dimensions should remain independently readable').toEqual([]);
|
||||
}
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
errors.set(page, []);
|
||||
page.on('pageerror', (error) => errors.get(page)!.push(error.message));
|
||||
await page.goto('/');
|
||||
await expect(page.getByRole('heading', { name: 'Room measurements' })).toBeVisible();
|
||||
});
|
||||
|
||||
test.afterEach(async ({ page }) => {
|
||||
expect(errors.get(page), 'The application should not throw browser errors').toEqual([]);
|
||||
});
|
||||
|
||||
test('measurements, materials, drawing and both cut lists share one page', async ({ page }) => {
|
||||
await expect(page.getByLabel('Room width', { exact: true })).toHaveValue('4800');
|
||||
await expect(page.getByLabel('Room length', { exact: true })).toHaveValue('3600');
|
||||
for (const label of ['Board length', 'Board width', 'Stock length 1', 'Skirting thickness']) {
|
||||
await expect(page.getByLabel(label, { exact: true })).toBeVisible();
|
||||
}
|
||||
await expect(page.getByRole('heading', { name: 'Materials', exact: true })).toBeVisible();
|
||||
await expect(page.getByRole('heading', { name: /^Flooring cuts/ })).toBeVisible();
|
||||
await expect(page.getByRole('heading', { name: /^Skirting cuts/ })).toBeVisible();
|
||||
await expect(preview(page).getByText('Outline closed', { exact: true })).toBeVisible();
|
||||
await expect(page.locator('.layer-switch, .step-nav')).toHaveCount(0);
|
||||
await expect(page.locator('.app-header').getByText('mm', { exact: true })).toHaveCount(0);
|
||||
await expect(page.getByRole('button', { name: /^Zoom (in|out)$/ })).toHaveCount(0);
|
||||
await noDrawingScroll(page);
|
||||
await expect(
|
||||
page.getByRole('button', { name: /Choose materials|Get my cut plan|Measure room/ }),
|
||||
).toHaveCount(0);
|
||||
await expect(
|
||||
page.getByText(
|
||||
/LESS WASTE\. MORE CONFIDENCE|A better floor starts|Thoughtful plans|Saved in your URL|bounded heuristic|inspect narrow tips/i,
|
||||
),
|
||||
).toHaveCount(0);
|
||||
expect(
|
||||
await page.locator('#cut-plan').evaluate((element) => element.getBoundingClientRect().top),
|
||||
).toBeGreaterThan(
|
||||
await page.locator('#materials').evaluate((element) => element.getBoundingClientRect().bottom),
|
||||
);
|
||||
});
|
||||
|
||||
test('drawing includes full boards, while numbered cut thumbnails stay complete and sequential', async ({
|
||||
page,
|
||||
}) => {
|
||||
const { project, floor, skirt } = plans(page);
|
||||
const cutFloor = flooringCuts(floor);
|
||||
const cutSkirt = skirtingCuts(skirt);
|
||||
const wholeBoards = uncutFlooring(floor, project.flooring).wholeBoards;
|
||||
expect(wholeBoards).toBeGreaterThan(0);
|
||||
await expect(floorCodes(page)).toHaveCount(cutFloor.length);
|
||||
await expect(skirtCodes(page)).toHaveCount(cutSkirt.length);
|
||||
const shownCodes = await floorCodes(page).evaluateAll((buttons) =>
|
||||
buttons.map((button) =>
|
||||
button.getAttribute('aria-label')!.replace('Preview flooring cut ', ''),
|
||||
),
|
||||
);
|
||||
expect(shownCodes.sort()).toEqual(cutFloor.map((piece) => piece.id).sort());
|
||||
expect(cutFloor.map((piece) => piece.id)).toEqual(cutFloor.map((_, i) => `F${i + 1}`));
|
||||
expect(cutSkirt.map((piece) => piece.id)).toEqual(cutSkirt.map((_, i) => `A${i + 1}`));
|
||||
expect(await floorRows(page).count(), 'Repeated dimensions share one cutting batch').toBeLessThan(
|
||||
cutFloor.length,
|
||||
);
|
||||
const batches = await floorRows(page).evaluateAll((rows) =>
|
||||
rows.map((row) => ({
|
||||
codes: [...row.querySelectorAll('button[aria-label^="Preview flooring cut "]')].map(
|
||||
(button) => button.getAttribute('aria-label')!.replace('Preview flooring cut ', ''),
|
||||
),
|
||||
size: row.querySelector('.batch-size')?.textContent?.trim(),
|
||||
quantity: row.querySelector('.batch-qty')?.textContent?.trim(),
|
||||
})),
|
||||
);
|
||||
for (const batch of batches) {
|
||||
expect(batch.quantity).toBe(String(batch.codes.length));
|
||||
for (const code of batch.codes) {
|
||||
const piece = cutFloor.find((piece) => piece.id === code)!;
|
||||
expect(batch.size).toBe(`${mm(piece.length)} × ${mm(piece.width)}`);
|
||||
}
|
||||
}
|
||||
await expect(preview(page).locator('.floor-piece')).toHaveCount(floor.pieces.length);
|
||||
await expect(preview(page).locator('.skirt-piece')).toHaveCount(skirt.pieces.length);
|
||||
await expect(preview(page).getByRole('button', { name: /^Select flooring cut / })).toHaveCount(
|
||||
cutFloor.length,
|
||||
);
|
||||
await expect(preview(page).getByRole('button', { name: /^Select skirting cut / })).toHaveCount(
|
||||
cutSkirt.length,
|
||||
);
|
||||
await expect(page.locator('.flooring-cuts .cut-summary')).toContainText(
|
||||
`${wholeBoards} full boards laid uncut`,
|
||||
);
|
||||
const drawnCodes = await preview(page).locator('svg text').allTextContents();
|
||||
for (const piece of floor.pieces.filter((piece) => !piece.cut && !piece.reused)) {
|
||||
expect(shownCodes).not.toContain(piece.id);
|
||||
expect(drawnCodes).not.toContain(piece.id);
|
||||
}
|
||||
const skirtCutIds = new Set(cutSkirt.map((piece) => piece.id));
|
||||
for (const piece of skirt.pieces.filter((piece) => !skirtCutIds.has(piece.id))) {
|
||||
expect(drawnCodes).not.toContain(piece.id);
|
||||
await expect(
|
||||
preview(page).locator(`.skirt-piece[data-piece-id="${piece.id}"]`),
|
||||
).toHaveAttribute('aria-hidden', 'true');
|
||||
}
|
||||
const repeatedCode = batches.find((batch) => batch.codes.length > 1)!.codes.at(-1)!;
|
||||
const repeatedPiece = cutFloor.find((piece) => piece.id === repeatedCode)!;
|
||||
const thumbnail = page.getByRole('button', {
|
||||
name: `Preview flooring cut ${repeatedCode}`,
|
||||
exact: true,
|
||||
});
|
||||
await expect(thumbnail.locator('svg')).toBeVisible();
|
||||
await thumbnail.click();
|
||||
const dialog = page.getByRole('dialog', { name: `Flooring cut ${repeatedCode}`, exact: true });
|
||||
await expect(dialog).toBeVisible();
|
||||
await expect(dialog.locator('.cut-origin')).toContainText(`Row ${repeatedPiece.row}`);
|
||||
await expect(dialog.locator('.cut-origin')).toContainText(repeatedPiece.stockId);
|
||||
await expect(dialog.getByRole('img', { name: `Flooring shape ${repeatedCode}` })).toBeVisible();
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(page.getByRole('dialog')).toHaveCount(0);
|
||||
await expect(thumbnail).toBeFocused();
|
||||
await expect(page.getByRole('button', { name: 'Export CSV' })).toBeEnabled();
|
||||
});
|
||||
|
||||
test('inconsistent final measurements block cuts and small residuals show the expected length', async ({
|
||||
page,
|
||||
}) => {
|
||||
await openWalls(page);
|
||||
await page.getByLabel('Wall 4 length', { exact: true }).fill('3700');
|
||||
await expect(page.getByText(/The outline is open by 100\.0 mm/).first()).toBeVisible();
|
||||
await expect(floorRows(page)).toHaveCount(0);
|
||||
await expect(skirtRows(page)).toHaveCount(0);
|
||||
await expect(page.getByRole('button', { name: 'Export CSV' })).toBeDisabled();
|
||||
await page.getByLabel('Wall 4 length', { exact: true }).fill('3605');
|
||||
await expect(page.getByText(/non-straight wall/)).toBeVisible();
|
||||
await expect(page.getByText('Final wall: 3,600 mm expected · 5 mm difference')).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: 'Export CSV' })).toBeEnabled();
|
||||
expect(await floorRows(page).count()).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test('room warnings stay with their room even when two room names match', async ({ page }) => {
|
||||
await openWalls(page);
|
||||
await page.getByLabel('Wall 4 length', { exact: true }).fill('3605');
|
||||
await expect(page.getByText(/non-straight wall/).first()).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Add room', exact: true }).click();
|
||||
await page.getByLabel('Room name', { exact: true }).fill('Living room');
|
||||
expect(state(page).project.rooms.map((room) => room.name)).toEqual([
|
||||
'Living room',
|
||||
'Living room',
|
||||
]);
|
||||
await expect(page.getByText(/non-straight wall/)).toHaveCount(0);
|
||||
await page.locator('.room-tab').first().click();
|
||||
await expect(page.getByText(/non-straight wall/).first()).toBeVisible();
|
||||
await openWalls(page);
|
||||
await page.getByLabel('Wall 4 length', { exact: true }).fill('3700');
|
||||
await expect(page.getByText(/outline is open by 100\.0 mm/).first()).toBeVisible();
|
||||
await page.locator('.room-tab').nth(1).click();
|
||||
await expect(page.getByText(/outline is open by 100\.0 mm/)).toHaveCount(0);
|
||||
await page.locator('.room-tab').first().click();
|
||||
await expect(page.getByText(/outline is open by 100\.0 mm/).first()).toBeVisible();
|
||||
});
|
||||
|
||||
test('custom walls close using a calculated wall that can be measured again', async ({ page }) => {
|
||||
await page.getByRole('button', { name: 'Custom', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Add a wall', exact: true }).click();
|
||||
await page.getByLabel('Wall 2 length', { exact: true }).fill('3000');
|
||||
await page.getByRole('button', { name: 'Add a wall', exact: true }).click();
|
||||
await page.getByLabel('Wall 3 length', { exact: true }).fill('4000');
|
||||
await expect(page.getByText('3,000 mm to close')).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Add closing wall' }).click();
|
||||
await expect(preview(page).getByText('Outline closed', { exact: true })).toBeVisible();
|
||||
await openWalls(page);
|
||||
await expect(page.getByLabel('Wall 4 length', { exact: true })).toHaveValue('3000');
|
||||
await page.getByLabel('Wall 4 length', { exact: true }).fill('3050');
|
||||
await expect(page.getByText(/3,000 mm expected; length differs by 50 mm/)).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: 'Export CSV' })).toBeDisabled();
|
||||
});
|
||||
|
||||
test('fireplace thumbnails open true-scale mitres and shaped floor cuts in dialogs', async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.getByRole('button', { name: 'With fireplace' }).click();
|
||||
await expect(page.getByLabel('Wall 8 length', { exact: true })).toHaveValue('3600');
|
||||
await expect(preview(page).getByRole('img', { name: /floor plan with/ })).toHaveAttribute(
|
||||
'aria-label',
|
||||
/8 walls/,
|
||||
);
|
||||
await noWallLabelOverlap(page);
|
||||
const { floor, skirt } = plans(page);
|
||||
const mitred = skirtingCuts(skirt).find(
|
||||
(piece) => Math.abs(piece.leftMitre) === 45 || Math.abs(piece.rightMitre) === 45,
|
||||
)!;
|
||||
expect(mitred).toBeDefined();
|
||||
const thumbnail = page.getByRole('button', {
|
||||
name: `Preview skirting cut ${mitred.id}`,
|
||||
exact: true,
|
||||
});
|
||||
await expect(thumbnail.locator('svg').first()).toBeVisible();
|
||||
await thumbnail.click();
|
||||
const dialog = page.getByRole('dialog', { name: `Skirting cut ${mitred.id}`, exact: true });
|
||||
await expect(dialog).toBeVisible();
|
||||
await expect(dialog).toContainText(/long point/i);
|
||||
const end = Math.abs(mitred.leftMitre) === 45 ? 'left' : 'right';
|
||||
const projected = await dialog
|
||||
.locator(`.skirting-cut-edge[data-end="${end}"]`)
|
||||
.evaluate((element) => {
|
||||
const line = element as SVGLineElement;
|
||||
const matrix = line.getScreenCTM()!;
|
||||
const start = new DOMPoint(line.x1.baseVal.value, line.y1.baseVal.value).matrixTransform(
|
||||
matrix,
|
||||
);
|
||||
const finish = new DOMPoint(line.x2.baseVal.value, line.y2.baseVal.value).matrixTransform(
|
||||
matrix,
|
||||
);
|
||||
return { dx: Math.abs(finish.x - start.x), dy: Math.abs(finish.y - start.y) };
|
||||
});
|
||||
expect(projected.dx).toBeGreaterThan(5);
|
||||
expect(projected.dy).toBeGreaterThan(5);
|
||||
expect(
|
||||
projected.dx,
|
||||
'A 45° mitre must have equal horizontal and vertical screen distances',
|
||||
).toBeCloseTo(projected.dy, 1);
|
||||
await page.getByRole('button', { name: 'Close cut preview', exact: true }).click();
|
||||
await expect(thumbnail).toBeFocused();
|
||||
const shaped = flooringCuts(floor).find((piece) => piece.shaped)!;
|
||||
expect(shaped).toBeDefined();
|
||||
await page
|
||||
.getByRole('button', { name: `Preview flooring cut ${shaped.id}`, exact: true })
|
||||
.click();
|
||||
await expect(
|
||||
page.getByRole('dialog', { name: `Flooring cut ${shaped.id}`, exact: true }),
|
||||
).toBeVisible();
|
||||
await expect(page.getByRole('img', { name: `Flooring shape ${shaped.id}` })).toBeVisible();
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(page.getByRole('dialog')).toHaveCount(0);
|
||||
await expect(page.locator('.selected-cut')).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('door positions and material lengths update skirting immediately', async ({ page }) => {
|
||||
const before = await page.locator('.skirting-cuts').innerText();
|
||||
await page.getByRole('button', { name: 'Add a doorway' }).click();
|
||||
await expect(page.locator('.door-card')).toHaveCount(2);
|
||||
await page.locator('.door-card').last().getByRole('combobox').selectOption({ label: 'W1' });
|
||||
const movedDoor = page.locator('.door-card').first();
|
||||
await movedDoor.getByLabel('Door offset', { exact: true }).fill('1200');
|
||||
await movedDoor.getByLabel('Door width', { exact: true }).fill('900');
|
||||
expect(state(page).project.rooms[0].walls[0].doors[0]).toMatchObject({
|
||||
offset: 1200,
|
||||
width: 900,
|
||||
});
|
||||
await expect(page.getByRole('button', { name: 'Export CSV' })).toBeEnabled();
|
||||
expect(await page.locator('.skirting-cuts').innerText()).not.toBe(before);
|
||||
await page.getByLabel('Stock length 1', { exact: true }).fill('3600');
|
||||
await page.getByLabel('Skirting thickness', { exact: true }).fill('22');
|
||||
const { skirt } = plans(page);
|
||||
await expect(skirtCodes(page)).toHaveCount(skirtingCuts(skirt).length);
|
||||
await expect(page.locator('.skirting-cuts .cut-summary')).toContainText(
|
||||
`Buy ${skirt.stockCount} lengths`,
|
||||
);
|
||||
await expect(page.getByRole('button', { name: 'Export CSV' })).toBeEnabled();
|
||||
await movedDoor.getByLabel('Door width', { exact: true }).fill('6000');
|
||||
await expect(page.getByText(/must fit within the wall/).first()).toBeVisible();
|
||||
await expect(skirtRows(page)).toHaveCount(0);
|
||||
await expect(page.getByRole('button', { name: 'Export CSV' })).toBeDisabled();
|
||||
});
|
||||
|
||||
test('invalid skirting settings keep flooring results usable', async ({ page }) => {
|
||||
const floorCount = await floorCodes(page).count();
|
||||
await page.getByLabel('Stock length 1', { exact: true }).fill('100');
|
||||
await expect(skirtRows(page)).toHaveCount(0);
|
||||
await expect(floorCodes(page)).toHaveCount(floorCount);
|
||||
await expect(page.locator('.issue.error').first()).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: 'Export CSV' })).toBeDisabled();
|
||||
await page.getByLabel('Stock length 1', { exact: true }).fill('2400');
|
||||
expect(await skirtRows(page).count()).toBeGreaterThan(0);
|
||||
await expect(page.getByRole('button', { name: 'Export CSV' })).toBeEnabled();
|
||||
});
|
||||
|
||||
test('pattern, direction and spacers persist without steps, layers or stored results', async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.getByLabel('Room length', { exact: true }).fill('3650');
|
||||
await page.getByRole('button', { name: 'Random', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Across first wall', exact: true }).click();
|
||||
await page.getByLabel('Wall spacer', { exact: true }).fill('12');
|
||||
expect(state(page).project.flooring).toMatchObject({ pattern: 'random', gap: 12 });
|
||||
expect(state(page).project.rooms[0].direction).toBe(90);
|
||||
expect(Object.keys(state(page).view).sort()).toEqual(['roomId', 'selectedPiece']);
|
||||
expect(Object.keys(state(page)).sort()).toEqual(['project', 'view']);
|
||||
const table = await page.locator('.flooring-cuts tbody').innerText();
|
||||
await page.reload();
|
||||
await expect(page.getByLabel('Wall spacer', { exact: true })).toHaveValue('12');
|
||||
await expect(page.getByRole('button', { name: 'Random', exact: true })).toHaveAttribute(
|
||||
'aria-pressed',
|
||||
'true',
|
||||
);
|
||||
await expect(
|
||||
page.getByRole('button', { name: 'Across first wall', exact: true }),
|
||||
).toHaveAttribute('aria-pressed', 'true');
|
||||
await expect(page.locator('.flooring-cuts tbody')).toHaveText(table, { useInnerText: true });
|
||||
await noHorizontalOverflow(page);
|
||||
expect(await page.evaluate(() => Object.keys(localStorage))).toEqual([]);
|
||||
});
|
||||
|
||||
test('a narrow remainder is shared between the first and last flooring rows', async ({ page }) => {
|
||||
// 3650 minus two 10 mm spacers leaves 19 full rows and a 20 mm sliver.
|
||||
await page.getByLabel('Room length', { exact: true }).fill('3650');
|
||||
const { floor } = plans(page);
|
||||
for (const row of [1, 20]) {
|
||||
const piece = flooringCuts(floor).find((piece) => piece.row === row);
|
||||
expect(piece).toBeDefined();
|
||||
const group = floorRows(page).filter({
|
||||
has: page.getByRole('button', { name: `Preview flooring cut ${piece!.id}`, exact: true }),
|
||||
});
|
||||
await expect(group.locator('[data-label="Cut size · mm"]')).toContainText('× 105');
|
||||
}
|
||||
});
|
||||
|
||||
test('multiple rooms retain independent measurements with combined cut lists', async ({ page }) => {
|
||||
await page.getByRole('button', { name: 'Add room', exact: true }).click();
|
||||
await expect(page.getByLabel('Room name', { exact: true })).toHaveValue('Room 2');
|
||||
await page.getByLabel('Room name', { exact: true }).fill('Study');
|
||||
await page.getByLabel('Room width', { exact: true }).fill('3200');
|
||||
expect(state(page).project.rooms).toHaveLength(2);
|
||||
expect(state(page).project.rooms[0].walls[0].length).toBe(4800);
|
||||
expect(state(page).project.rooms[1].walls[0].length).toBe(3200);
|
||||
expect(await floorRows(page).filter({ hasText: 'Living room' }).count()).toBeGreaterThan(0);
|
||||
expect(await skirtRows(page).filter({ hasText: 'Study' }).count()).toBeGreaterThan(0);
|
||||
await page.getByRole('button', { name: /^Living room.*m²/ }).click();
|
||||
await expect(page.getByLabel('Room width', { exact: true })).toHaveValue('4800');
|
||||
await page.getByRole('button', { name: /^Study.*m²/ }).click();
|
||||
await expect(page.getByLabel('Room width', { exact: true })).toHaveValue('3200');
|
||||
await page.getByRole('button', { name: 'Remove this room' }).click();
|
||||
expect(state(page).project.rooms).toHaveLength(1);
|
||||
await page.reload();
|
||||
await expect(page.getByLabel('Room name', { exact: true })).toHaveValue('Living room');
|
||||
});
|
||||
|
||||
test('shared URLs reopen the selected preview and CSV contains every cut once', async ({
|
||||
page,
|
||||
context,
|
||||
}) => {
|
||||
await page.getByLabel('Room name', { exact: true }).fill('Café 北');
|
||||
const { floor, skirt } = plans(page);
|
||||
const pieceCode = flooringCuts(floor)[0].id;
|
||||
await page
|
||||
.getByRole('button', { name: `Preview flooring cut ${pieceCode}`, exact: true })
|
||||
.click();
|
||||
await expect(
|
||||
page.getByRole('dialog', { name: `Flooring cut ${pieceCode}`, exact: true }),
|
||||
).toBeVisible();
|
||||
expect(state(page).view.selectedPiece).toBe(pieceCode);
|
||||
const shareUrl = page.url();
|
||||
const originalTable = await page.locator('.flooring-cuts tbody').innerText();
|
||||
const shared = await context.newPage();
|
||||
await shared.goto(shareUrl);
|
||||
await expect(
|
||||
shared.getByRole('dialog', { name: `Flooring cut ${pieceCode}`, exact: true }),
|
||||
).toBeVisible();
|
||||
await expect(shared.locator('.flooring-cuts tbody')).toHaveText(originalTable, {
|
||||
useInnerText: true,
|
||||
});
|
||||
await shared.reload();
|
||||
await expect(
|
||||
shared.getByRole('dialog', { name: `Flooring cut ${pieceCode}`, exact: true }),
|
||||
).toBeVisible();
|
||||
await shared.close();
|
||||
await page.keyboard.press('Escape');
|
||||
expect(state(page).view.selectedPiece).toBeNull();
|
||||
const downloadPromise = page.waitForEvent('download');
|
||||
await page.getByRole('button', { name: 'Export CSV' }).click();
|
||||
const download = await downloadPromise;
|
||||
expect(download.suggestedFilename()).toBe('flooring-cut-plan.csv');
|
||||
const csv = await readFile((await download.path())!, 'utf8');
|
||||
expect(csv).toContain('"Material","Room","Piece","Stock"');
|
||||
expect(csv).toContain(`"Flooring","Café 北","${pieceCode}"`);
|
||||
expect(csv.split('\r\n').filter((line) => line.startsWith('"Flooring",'))).toHaveLength(
|
||||
flooringCuts(floor).length,
|
||||
);
|
||||
expect(csv.split('\r\n').filter((line) => line.startsWith('"Skirting",'))).toHaveLength(
|
||||
skirtingCuts(skirt).length,
|
||||
);
|
||||
for (const piece of floor.pieces.filter((piece) => !piece.cut && !piece.reused))
|
||||
expect(csv).not.toContain(`"${piece.id}"`);
|
||||
expect(csv).not.toContain('bounded heuristic');
|
||||
await context.grantPermissions(['clipboard-read', 'clipboard-write']);
|
||||
const closedUrl = page.url();
|
||||
await page.getByRole('button', { name: 'Copy link', exact: true }).click();
|
||||
await expect(page.getByText('Link copied', { exact: true })).toBeVisible();
|
||||
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(closedUrl);
|
||||
await page.reload();
|
||||
await expect(page.locator('.flooring-cuts tbody')).toHaveText(originalTable, {
|
||||
useInnerText: true,
|
||||
});
|
||||
});
|
||||
|
||||
test('saw kerf help works with keyboard and touch or mouse', async ({ page, isMobile }) => {
|
||||
for (const name of ['What is saw kerf?', 'What is skirting saw kerf?']) {
|
||||
const button = page.getByRole('button', { name, exact: true });
|
||||
await button.focus();
|
||||
await button.press('Space');
|
||||
await expect(button).toHaveAttribute('aria-expanded', 'true');
|
||||
await expect(page.getByRole('tooltip')).toContainText(
|
||||
'Width of material removed by the saw blade.',
|
||||
);
|
||||
await expect(page.getByRole('tooltip')).toContainText('600 mm + 397 mm');
|
||||
await button.press('Escape');
|
||||
await expect(page.getByRole('tooltip')).toHaveCount(0);
|
||||
if (isMobile) await button.tap();
|
||||
else await button.click();
|
||||
await expect(page.getByRole('tooltip')).toBeVisible();
|
||||
await noHorizontalOverflow(page);
|
||||
await page.getByLabel('Board length', { exact: true }).focus();
|
||||
await expect(page.getByRole('tooltip')).toHaveCount(0);
|
||||
}
|
||||
});
|
||||
|
||||
test('invalid URLs recover when measurements are edited', async ({ page }) => {
|
||||
await page.goto('/#plan=broken');
|
||||
await expect(page.getByText(/Could not load this plan/)).toBeVisible();
|
||||
await page.getByLabel('Room name', { exact: true }).fill('Recovered plan');
|
||||
await expect(page.getByText(/Could not load this plan/)).toHaveCount(0);
|
||||
expect(decodeState(new URL(page.url()).hash).error).toBeNull();
|
||||
await page.reload();
|
||||
await expect(page.getByLabel('Room name', { exact: true })).toHaveValue('Recovered plan');
|
||||
});
|
||||
|
||||
for (const width of [320, 390]) {
|
||||
test(`phone layout works at ${width} px with readable inputs and touch targets`, async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width, height: 844 });
|
||||
await openWalls(page);
|
||||
await page.getByRole('button', { name: 'What is saw kerf?', exact: true }).click();
|
||||
await noHorizontalOverflow(page);
|
||||
await expect(page.getByRole('tooltip')).toBeVisible();
|
||||
const smallControls = await page
|
||||
.locator('button, input, select, summary')
|
||||
.evaluateAll((elements) =>
|
||||
elements.flatMap((element) => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
return rect.width > 0 && rect.height > 0 && (rect.width < 39.5 || rect.height < 39.5)
|
||||
? [
|
||||
{
|
||||
label: element.getAttribute('aria-label') || element.textContent?.trim(),
|
||||
width: rect.width,
|
||||
height: rect.height,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
}),
|
||||
);
|
||||
expect(smallControls, 'Every visible form control should have a usable touch target').toEqual(
|
||||
[],
|
||||
);
|
||||
const smallInputs = await page
|
||||
.locator('input, select')
|
||||
.evaluateAll((elements) =>
|
||||
elements
|
||||
.filter(
|
||||
(element) =>
|
||||
element.getBoundingClientRect().height > 0 &&
|
||||
parseFloat(getComputedStyle(element).fontSize) < 16,
|
||||
)
|
||||
.map((element) => element.getAttribute('aria-label') || element.id),
|
||||
);
|
||||
expect(smallInputs, '16 px input text avoids phone browser zoom').toEqual([]);
|
||||
expect(
|
||||
await floorRows(page)
|
||||
.first()
|
||||
.evaluate((element) => getComputedStyle(element).display),
|
||||
).toMatch(/block|grid/);
|
||||
await page.getByRole('button', { name: 'With fireplace' }).click();
|
||||
await noWallLabelOverlap(page);
|
||||
await noDrawingScroll(page);
|
||||
await skirtCodes(page).first().click();
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog).toBeVisible();
|
||||
const box = await dialog.boundingBox();
|
||||
expect(box!.x).toBeGreaterThanOrEqual(0);
|
||||
expect(box!.y).toBeGreaterThanOrEqual(0);
|
||||
expect(box!.x + box!.width).toBeLessThanOrEqual(width);
|
||||
expect(box!.y + box!.height).toBeLessThanOrEqual(844);
|
||||
await noHorizontalOverflow(page);
|
||||
await page.mouse.click(1, 1);
|
||||
await expect(page.getByRole('dialog')).toHaveCount(0);
|
||||
expect(state(page).view.selectedPiece).toBeNull();
|
||||
await page.getByText('Source lengths for skirting cuts', { exact: true }).click();
|
||||
await noHorizontalOverflow(page);
|
||||
});
|
||||
}
|
||||
17
index.html
Normal file
17
index.html
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="theme-color" content="#17263f" />
|
||||
<meta
|
||||
name="description"
|
||||
content="Room measurements, flooring and skirting materials, and labelled cutting plans."
|
||||
/>
|
||||
<title>Floor planner</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
2336
package-lock.json
generated
Normal file
2336
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
36
package.json
Normal file
36
package.json
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
{
|
||||
"name": "floor-planner",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --host 0.0.0.0",
|
||||
"build": "tsc -b && vite build",
|
||||
"preview": "vite preview --host 0.0.0.0",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"test:e2e": "playwright test",
|
||||
"check": "npm run build && npm test && npm run test:e2e",
|
||||
"format": "prettier --write .",
|
||||
"format:check": "prettier --check ."
|
||||
},
|
||||
"dependencies": {
|
||||
"clipper-lib": "^6.4.2",
|
||||
"lucide-react": "^0.468.0",
|
||||
"lz-string": "^1.5.0",
|
||||
"react": "^19.1.1",
|
||||
"react-dom": "^19.1.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.55.0",
|
||||
"@types/clipper-lib": "^6.4.0",
|
||||
"@types/node": "^24.3.0",
|
||||
"@types/react": "^19.1.10",
|
||||
"@types/react-dom": "^19.1.9",
|
||||
"@vitejs/plugin-react": "^5.0.0",
|
||||
"prettier": "^3.9.6",
|
||||
"typescript": "~5.9.2",
|
||||
"vite": "^7.1.3",
|
||||
"vitest": "^4.1.11"
|
||||
}
|
||||
}
|
||||
16
playwright.config.ts
Normal file
16
playwright.config.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import { defineConfig, devices } from '@playwright/test';
|
||||
export default defineConfig({
|
||||
testDir: './e2e',
|
||||
fullyParallel: true,
|
||||
reporter: 'list',
|
||||
use: { baseURL: 'http://127.0.0.1:5173', trace: 'retain-on-failure' },
|
||||
projects: [
|
||||
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
|
||||
{ name: 'mobile', use: { ...devices['iPhone 13'], defaultBrowserType: 'chromium' } },
|
||||
],
|
||||
webServer: {
|
||||
command: 'npm run dev -- --port 5173 --strictPort',
|
||||
url: 'http://127.0.0.1:5173',
|
||||
reuseExistingServer: !process.env.CI,
|
||||
},
|
||||
});
|
||||
259
src/App.tsx
Normal file
259
src/App.tsx
Normal file
|
|
@ -0,0 +1,259 @@
|
|||
import { useMemo, useRef } from 'react';
|
||||
import { Copy, Plus, Printer, ArrowDown } from 'lucide-react';
|
||||
import { useProject } from './lib/use-project';
|
||||
import { rectangle, nextId } from './lib/defaults';
|
||||
import { buildGeometry } from './lib/geometry';
|
||||
import { planFlooring } from './lib/flooring';
|
||||
import { planSkirting } from './lib/skirting';
|
||||
import { area, mm } from './lib/format';
|
||||
import { isSkirtingCut } from './lib/cut-list';
|
||||
import type { Project, Room } from './lib/types';
|
||||
import { OutlineEditor } from './components/OutlineEditor';
|
||||
import { MaterialsEditor } from './components/MaterialsEditor';
|
||||
import { FloorPlan } from './components/FloorPlan';
|
||||
import { CutList } from './components/CutList';
|
||||
import { Issues } from './components/Fields';
|
||||
|
||||
const jump = (id: string) => document.getElementById(id)?.scrollIntoView({ block: 'start' });
|
||||
|
||||
export default function App() {
|
||||
const { state, error, update } = useProject();
|
||||
const { project, view } = state;
|
||||
const copyStatus = useRef<HTMLOutputElement>(null);
|
||||
const room = project.rooms.find((r) => r.id === view.roomId) ?? project.rooms[0];
|
||||
const geometries = useMemo(
|
||||
() => project.rooms.map((r) => buildGeometry(r, project.tolerance)),
|
||||
[project.rooms, project.tolerance],
|
||||
);
|
||||
const geometry = geometries[project.rooms.indexOf(room)];
|
||||
const flooring = useMemo(
|
||||
() => planFlooring(project.rooms, project.flooring, project.tolerance),
|
||||
[project.rooms, project.flooring, project.tolerance],
|
||||
);
|
||||
const skirting = useMemo(
|
||||
() => planSkirting(project.rooms, project.skirting, project.tolerance),
|
||||
[project.rooms, project.skirting, project.tolerance],
|
||||
);
|
||||
const floorErrors = flooring.issues.filter((i) => i.severity === 'error');
|
||||
const skirtErrors = skirting.issues.filter((i) => i.severity === 'error');
|
||||
const roomErrors = [...floorErrors, ...skirtErrors].filter(
|
||||
(issue) => !issue.roomId || issue.roomId === room.id,
|
||||
);
|
||||
const totalArea = geometries.reduce((sum, g) => sum + (g.valid ? g.area : 0), 0);
|
||||
const wholeBoards = flooring.pieces.filter(
|
||||
(p) =>
|
||||
!p.cut &&
|
||||
Math.abs(p.length - project.flooring.length) < 0.01 &&
|
||||
Math.abs(p.width - project.flooring.width) < 0.01,
|
||||
).length;
|
||||
const wholeSkirting = skirting.pieces.filter((p) => !isSkirtingCut(p, skirting)).length;
|
||||
|
||||
const changeProject = (fn: (p: Project) => Project) =>
|
||||
update((s) => ({ ...s, project: fn(s.project), view: { ...s.view, selectedPiece: null } }));
|
||||
const changeRoom = (fn: (r: Room) => Room) =>
|
||||
changeProject((p) => ({ ...p, rooms: p.rooms.map((r) => (r.id === room.id ? fn(r) : r)) }));
|
||||
const select = (id: string | null, roomId?: string) =>
|
||||
update((s) => ({
|
||||
...s,
|
||||
view: { ...s.view, roomId: roomId ?? s.view.roomId, selectedPiece: id },
|
||||
}));
|
||||
const addRoom = () =>
|
||||
update((s) => {
|
||||
const id = nextId(
|
||||
'room',
|
||||
s.project.rooms.map((r) => r.id),
|
||||
);
|
||||
return {
|
||||
...s,
|
||||
project: {
|
||||
...s.project,
|
||||
rooms: [...s.project.rooms, rectangle(id, `Room ${s.project.rooms.length + 1}`)],
|
||||
},
|
||||
view: { ...s.view, roomId: id, selectedPiece: null },
|
||||
};
|
||||
}, true);
|
||||
const removeRoom = () =>
|
||||
update((s) => {
|
||||
const rooms = s.project.rooms.filter((r) => r.id !== room.id);
|
||||
return {
|
||||
...s,
|
||||
project: { ...s.project, rooms },
|
||||
view: { ...s.view, roomId: rooms[0].id, selectedPiece: null },
|
||||
};
|
||||
}, true);
|
||||
const copyLink = async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(window.location.href);
|
||||
if (copyStatus.current) copyStatus.current.textContent = 'Link copied';
|
||||
} catch {
|
||||
if (copyStatus.current)
|
||||
copyStatus.current.textContent = 'Copy the address from your browser.';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<header className="app-header">
|
||||
<div className="app-title">
|
||||
<span className="square-mark" aria-hidden="true" />
|
||||
<h1>Floor planner</h1>
|
||||
</div>
|
||||
<div className="header-actions">
|
||||
<button className="button" onClick={copyLink}>
|
||||
<Copy size={17} />
|
||||
Copy link
|
||||
</button>
|
||||
<button
|
||||
className="button"
|
||||
onClick={() => window.print()}
|
||||
disabled={floorErrors.length > 0 || skirtErrors.length > 0}
|
||||
>
|
||||
<Printer size={17} />
|
||||
<span>Print</span>
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
<main className="app-main">
|
||||
<output ref={copyStatus} className="copy-status" aria-live="polite" />
|
||||
{error && (
|
||||
<p className="url-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<div className="project-bar">
|
||||
<div className="room-tabs" aria-label="Rooms">
|
||||
{project.rooms.map((r, index) => (
|
||||
<button
|
||||
key={r.id}
|
||||
className={`room-tab ${r.id === room.id ? 'active' : ''}`}
|
||||
aria-pressed={r.id === room.id}
|
||||
onClick={() =>
|
||||
update(
|
||||
(s) => ({ ...s, view: { ...s.view, roomId: r.id, selectedPiece: null } }),
|
||||
true,
|
||||
)
|
||||
}
|
||||
>
|
||||
{r.name || 'Untitled room'}
|
||||
<small>
|
||||
{geometries[index].valid ? `${area(geometries[index].area)} m²` : 'Check outline'}
|
||||
</small>
|
||||
</button>
|
||||
))}
|
||||
<button className="add-room" onClick={addRoom} disabled={project.rooms.length >= 20}>
|
||||
<Plus size={17} />
|
||||
Add room
|
||||
</button>
|
||||
</div>
|
||||
<span className="project-area">{area(totalArea)} m² total</span>
|
||||
</div>
|
||||
<nav className="page-jumps" aria-label="Jump to section">
|
||||
<button onClick={() => jump('measurements')}>
|
||||
Room <ArrowDown size={13} />
|
||||
</button>
|
||||
<button onClick={() => jump('materials')}>
|
||||
Materials <ArrowDown size={13} />
|
||||
</button>
|
||||
<button onClick={() => jump('drawing')}>
|
||||
Drawing <ArrowDown size={13} />
|
||||
</button>
|
||||
<button onClick={() => jump('cut-plan')}>
|
||||
Cuts <ArrowDown size={13} />
|
||||
</button>
|
||||
</nav>
|
||||
<div className="workspace">
|
||||
<div className="input-columns">
|
||||
<section
|
||||
className="editor-panel room-editor"
|
||||
id="measurements"
|
||||
aria-label="Room measurements"
|
||||
>
|
||||
<OutlineEditor
|
||||
room={room}
|
||||
geometry={geometry}
|
||||
tolerance={project.tolerance}
|
||||
changeRoom={changeRoom}
|
||||
changeProject={changeProject}
|
||||
remove={removeRoom}
|
||||
canRemove={project.rooms.length > 1}
|
||||
/>
|
||||
</section>
|
||||
<section
|
||||
className="editor-panel materials-editor"
|
||||
id="materials"
|
||||
aria-label="Materials"
|
||||
>
|
||||
<MaterialsEditor
|
||||
project={project}
|
||||
room={room}
|
||||
changeRoom={changeRoom}
|
||||
changeProject={changeProject}
|
||||
/>
|
||||
</section>
|
||||
</div>
|
||||
<div className="drawing-column" id="drawing">
|
||||
<FloorPlan
|
||||
room={room}
|
||||
geometry={geometry}
|
||||
flooring={flooring}
|
||||
skirting={skirting}
|
||||
selectedPiece={view.selectedPiece}
|
||||
select={(id) => select(id)}
|
||||
/>
|
||||
<section className="purchase-summary" aria-label="Materials to buy">
|
||||
<h2>
|
||||
Materials to buy <small>{project.rooms.length > 1 ? 'All rooms' : room.name}</small>
|
||||
</h2>
|
||||
<div className="purchase-item flooring">
|
||||
<span className="material-key floor-key" aria-hidden="true" />
|
||||
<div>
|
||||
<strong>
|
||||
{floorErrors.length ? '—' : flooring.boardCount} <span>floorboards</span>
|
||||
</strong>
|
||||
<p>
|
||||
{mm(project.flooring.length)} × {mm(project.flooring.width)} mm · {wholeBoards}{' '}
|
||||
used whole
|
||||
</p>
|
||||
</div>
|
||||
<span className="waste-stat">
|
||||
{floorErrors.length ? '—' : mm(flooring.wastePercent)}%<small>waste</small>
|
||||
</span>
|
||||
</div>
|
||||
<div className="purchase-item skirting">
|
||||
<span className="material-key skirt-key" aria-hidden="true" />
|
||||
<div>
|
||||
<strong>
|
||||
{skirtErrors.length ? '—' : skirting.stockCount} <span>skirting lengths</span>
|
||||
</strong>
|
||||
<p>
|
||||
{[...new Set(skirting.stocks.map((s) => s.length))]
|
||||
.sort((a, b) => a - b)
|
||||
.map(
|
||||
(l) =>
|
||||
`${skirting.stocks.filter((s) => s.length === l).length} × ${mm(l)} mm`,
|
||||
)
|
||||
.join(' + ') || 'Check settings'}{' '}
|
||||
· {wholeSkirting} used whole
|
||||
</p>
|
||||
</div>
|
||||
<span className="waste-stat">
|
||||
{skirtErrors.length ? '—' : mm(skirting.waste / 1000)} m<small>waste</small>
|
||||
</span>
|
||||
</div>
|
||||
</section>
|
||||
<Issues issues={roomErrors} />
|
||||
</div>
|
||||
</div>
|
||||
<div id="cut-plan">
|
||||
<CutList
|
||||
project={project}
|
||||
flooring={flooring}
|
||||
skirting={skirting}
|
||||
selectedPiece={view.selectedPiece}
|
||||
select={select}
|
||||
/>
|
||||
</div>
|
||||
</main>
|
||||
</>
|
||||
);
|
||||
}
|
||||
160
src/components/CutDialog.tsx
Normal file
160
src/components/CutDialog.tsx
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
import { useEffect, useRef } from 'react';
|
||||
import { X } from 'lucide-react';
|
||||
import type { FlooringPiece, Project, SkirtingPiece } from '../lib/types';
|
||||
import { flooringInstructions } from '../lib/cut-instructions';
|
||||
import { readyOffcutInstructions } from '../lib/cut-list';
|
||||
import { exactMm, flooringTemplate, skirtingTemplate } from '../lib/cut-preview';
|
||||
import { FlooringPreview, SkirtingPreview } from './CutPreview';
|
||||
|
||||
interface Props {
|
||||
floor?: FlooringPiece;
|
||||
skirt?: SkirtingPiece;
|
||||
project: Project;
|
||||
close: () => void;
|
||||
}
|
||||
|
||||
export function CutDialog({ floor, skirt, project, close }: Props) {
|
||||
const dialog = useRef<HTMLDialogElement>(null);
|
||||
const opener = useRef<HTMLElement | null>(null);
|
||||
const selected = floor ?? skirt;
|
||||
useEffect(() => {
|
||||
const element = dialog.current;
|
||||
if (!element) return;
|
||||
if (selected && !element.open) {
|
||||
opener.current =
|
||||
document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
||||
element.showModal();
|
||||
} else if (!selected && element.open) {
|
||||
element.close();
|
||||
if (opener.current?.isConnected) opener.current.focus({ preventScroll: true });
|
||||
}
|
||||
}, [selected?.id]);
|
||||
|
||||
const room =
|
||||
selected &&
|
||||
(project.rooms.find((candidate) => candidate.id === selected.roomId)?.name ?? selected.roomId);
|
||||
const template = floor
|
||||
? flooringTemplate(floor)
|
||||
: skirt
|
||||
? skirtingTemplate(skirt, project.skirting.thickness)
|
||||
: [];
|
||||
return (
|
||||
<dialog
|
||||
ref={dialog}
|
||||
className="cut-dialog"
|
||||
aria-labelledby="cut-dialog-title"
|
||||
onCancel={(event) => {
|
||||
event.preventDefault();
|
||||
close();
|
||||
}}
|
||||
onClick={(event) => {
|
||||
if (event.target !== event.currentTarget) return;
|
||||
const box = event.currentTarget.getBoundingClientRect();
|
||||
if (
|
||||
event.clientX < box.left ||
|
||||
event.clientX > box.right ||
|
||||
event.clientY < box.top ||
|
||||
event.clientY > box.bottom
|
||||
)
|
||||
close();
|
||||
}}
|
||||
>
|
||||
<header className="cut-dialog-header">
|
||||
<h2 id="cut-dialog-title">
|
||||
{floor ? `Flooring cut ${floor.id}` : skirt ? `Skirting cut ${skirt.id}` : 'Cut preview'}
|
||||
</h2>
|
||||
<button className="icon-button" aria-label="Close cut preview" onClick={close} autoFocus>
|
||||
<X size={20} />
|
||||
</button>
|
||||
</header>
|
||||
<div className="cut-dialog-body">
|
||||
{floor && (
|
||||
<>
|
||||
<p className="cut-origin">
|
||||
{room} · Row {floor.row} · Source {floor.stockId}
|
||||
{floor.reused ? ' · Reused offcut' : ''}
|
||||
</p>
|
||||
<FlooringPreview piece={floor} />
|
||||
<p className="cut-instructions">
|
||||
{floor.cut ? flooringInstructions(floor) : readyOffcutInstructions(floor)}
|
||||
</p>
|
||||
<p className="helper">
|
||||
Left and right run along the board; top and bottom are its long edges.
|
||||
</p>
|
||||
{floor.shaped && (
|
||||
<>
|
||||
<p>
|
||||
Mark these coordinates from the blank’s top-left corner: x along the board, y
|
||||
across it.
|
||||
</p>
|
||||
<div className="coordinates">
|
||||
{template.map((point, index) => (
|
||||
<span key={index}>
|
||||
{index + 1}: ({exactMm(point.x)}, {exactMm(point.y)}) mm
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<p className="cut-edge-lengths">
|
||||
{template
|
||||
.map((point, index) => {
|
||||
const next = template[(index + 1) % template.length];
|
||||
return `${index + 1}–${((index + 1) % template.length) + 1}: ${exactMm(Math.hypot(next.x - point.x, next.y - point.y))} mm`;
|
||||
})
|
||||
.join(' · ')}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{skirt && (
|
||||
<>
|
||||
<p className="cut-origin">
|
||||
{room} · Wall {skirt.wallIndex + 1} · Source {skirt.stockId}
|
||||
</p>
|
||||
<SkirtingPreview piece={skirt} thickness={project.skirting.thickness} />
|
||||
<dl className="cut-measurements">
|
||||
<div>
|
||||
<dt>Long point</dt>
|
||||
<dd>{exactMm(skirt.length)} mm</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Wall-facing length</dt>
|
||||
<dd>{exactMm(skirt.backLength)} mm</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Left mitre</dt>
|
||||
<dd>
|
||||
{exactMm(Math.abs(skirt.leftMitre))}° · {skirt.leftType}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Right mitre</dt>
|
||||
<dd>
|
||||
{exactMm(Math.abs(skirt.rightMitre))}° · {skirt.rightType}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
{template.length === 4 && (
|
||||
<>
|
||||
<p>
|
||||
Cut the square blank first. Mark these distances from its left end, then join the
|
||||
front and back marks at each end:
|
||||
</p>
|
||||
<div className="coordinates">
|
||||
<span>Back left: {exactMm(template[0].x)} mm</span>
|
||||
<span>Back right: {exactMm(template[1].x)} mm</span>
|
||||
<span>Front left: {exactMm(template[3].x)} mm</span>
|
||||
<span>Front right: {exactMm(template[2].x)} mm</span>
|
||||
</div>
|
||||
<p className="helper">
|
||||
Left and right follow the wall direction. Mitre angles are measured from a square
|
||||
cut; the marked points show which way to lean each cut.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</dialog>
|
||||
);
|
||||
}
|
||||
267
src/components/CutList.tsx
Normal file
267
src/components/CutList.tsx
Normal file
|
|
@ -0,0 +1,267 @@
|
|||
import { Download } from 'lucide-react';
|
||||
import type { FlooringPlan, Project, SkirtingPlan } from '../lib/types';
|
||||
import { degree, mm } from '../lib/format';
|
||||
import { downloadCsv } from '../lib/export';
|
||||
import {
|
||||
flooringCuts,
|
||||
groupFlooringCuts,
|
||||
skirtingCuts,
|
||||
uncutFlooring,
|
||||
uncutSkirting,
|
||||
} from '../lib/cut-list';
|
||||
import { FlooringPreview, SkirtingPreview } from './CutPreview';
|
||||
import { CutDialog } from './CutDialog';
|
||||
|
||||
function StockAllocations({
|
||||
title,
|
||||
items,
|
||||
}: {
|
||||
title: string;
|
||||
items: { id: string; pieces: string[]; size: string; remainder: string }[];
|
||||
}) {
|
||||
if (!items.length) return null;
|
||||
return (
|
||||
<details className="stock-allocations">
|
||||
<summary>{title}</summary>
|
||||
<ul className="allocation-list">
|
||||
{items.map((item) => (
|
||||
<li key={item.id} className="stock-card">
|
||||
<strong>
|
||||
{item.id} <span>· {item.size}</span>
|
||||
</strong>
|
||||
<span>{item.pieces.join(' + ')}</span>
|
||||
<small>{item.remainder}</small>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
interface Props {
|
||||
project: Project;
|
||||
flooring: FlooringPlan;
|
||||
skirting: SkirtingPlan;
|
||||
selectedPiece: string | null;
|
||||
select: (id: string | null, roomId?: string) => void;
|
||||
}
|
||||
|
||||
export function CutList({ project, flooring, skirting, selectedPiece, select }: Props) {
|
||||
const floorCuts = flooringCuts(flooring),
|
||||
skirtCuts = skirtingCuts(skirting);
|
||||
const floorGroups = groupFlooringCuts(flooring);
|
||||
const floorIds = new Set(floorCuts.map((piece) => piece.id));
|
||||
const skirtIds = new Set(skirtCuts.map((piece) => piece.id));
|
||||
const wholeFloor = uncutFlooring(flooring, project.flooring);
|
||||
const wholeSkirt = uncutSkirting(skirting);
|
||||
const selectedFloor = floorCuts.find((piece) => piece.id === selectedPiece);
|
||||
const selectedSkirt = skirtCuts.find((piece) => piece.id === selectedPiece);
|
||||
const roomName = (id: string) => project.rooms.find((room) => room.id === id)?.name ?? id;
|
||||
const errors = [...flooring.issues, ...skirting.issues].some(
|
||||
(issue) => issue.severity === 'error',
|
||||
);
|
||||
|
||||
return (
|
||||
<section className="cut-list-card" aria-labelledby="cut-plan-title">
|
||||
<div className="cut-list-header">
|
||||
<div>
|
||||
<h2 id="cut-plan-title">Cut plan</h2>
|
||||
<p className="helper">
|
||||
Cut pieces and offcut placements. All measurements are in millimetres.
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
className="button secondary small"
|
||||
onClick={() => downloadCsv(project, flooring, skirting)}
|
||||
disabled={errors || (!flooring.pieces.length && !skirting.pieces.length)}
|
||||
>
|
||||
<Download size={16} />
|
||||
Export CSV
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<section className="material-cuts flooring-cuts" aria-labelledby="flooring-cuts-title">
|
||||
<h3 id="flooring-cuts-title">
|
||||
Flooring cuts <span className="count-badge">{floorCuts.length}</span>
|
||||
</h3>
|
||||
<p className="cut-summary">
|
||||
Buy {flooring.boardCount} boards · {flooring.pieces.length} installed pieces ·{' '}
|
||||
{wholeFloor.wholeBoards} full boards laid uncut
|
||||
{wholeFloor.readyOffcuts > 0 &&
|
||||
` · ${wholeFloor.readyOffcuts} offcuts need no further cuts`}
|
||||
.
|
||||
</p>
|
||||
{floorCuts.length ? (
|
||||
<div className="table-scroll">
|
||||
<table className="cut-table">
|
||||
<caption className="sr-only">Flooring cuts and offcut placements</caption>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">Pieces</th>
|
||||
<th scope="col">Qty</th>
|
||||
<th scope="col">Cut size · mm</th>
|
||||
<th scope="col">Room</th>
|
||||
<th scope="col">Action</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{floorGroups.map((group) => {
|
||||
const first = group[0];
|
||||
return (
|
||||
<tr
|
||||
key={first.id}
|
||||
className={`flooring-batch ${group.some((piece) => piece.id === selectedPiece) ? 'selected' : ''}`}
|
||||
>
|
||||
<td data-label="Pieces" className="batch-codes">
|
||||
<div className="piece-chips">
|
||||
{group.map((piece) => (
|
||||
<button
|
||||
key={piece.id}
|
||||
className={`piece-link piece-chip cut-preview-button flooring-preview-button ${piece.id === selectedPiece ? 'selected' : ''}`}
|
||||
aria-label={`Preview flooring cut ${piece.id}`}
|
||||
aria-haspopup="dialog"
|
||||
onClick={() => select(piece.id, piece.roomId)}
|
||||
>
|
||||
<span className="cut-thumbnail" aria-hidden="true">
|
||||
<FlooringPreview piece={piece} compact />
|
||||
</span>
|
||||
<span className="cut-preview-code">{piece.id}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</td>
|
||||
<td data-label="Qty" className="batch-qty numeric">
|
||||
{group.length}
|
||||
</td>
|
||||
<td data-label="Cut size · mm" className="batch-size numeric">
|
||||
{mm(first.length)} × {mm(first.width)}
|
||||
</td>
|
||||
<td data-label="Room" className="batch-room">
|
||||
{roomName(first.roomId)}
|
||||
</td>
|
||||
<td data-label="Action" className="batch-action">
|
||||
{!first.cut
|
||||
? 'Use offcut · no new cut'
|
||||
: first.shaped
|
||||
? 'Shaped cut'
|
||||
: 'Rectangular cut'}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : (
|
||||
<p className="empty-state">
|
||||
{flooring.pieces.length
|
||||
? 'No flooring cuts needed.'
|
||||
: 'Complete the outline and flooring measurements to calculate cuts.'}
|
||||
</p>
|
||||
)}
|
||||
<StockAllocations
|
||||
title="Source boards for flooring cuts"
|
||||
items={flooring.stocks
|
||||
.filter((stock) => stock.pieceIds.some((id) => floorIds.has(id)))
|
||||
.map((stock) => ({
|
||||
id: stock.id,
|
||||
pieces: stock.pieceIds.filter((id) => floorIds.has(id)),
|
||||
size: `${mm(project.flooring.length)} × ${mm(project.flooring.width)} mm`,
|
||||
remainder: `${mm(stock.remaining)} mm remaining`,
|
||||
}))}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section className="material-cuts skirting-cuts" aria-labelledby="skirting-cuts-title">
|
||||
<h3 id="skirting-cuts-title">
|
||||
Skirting cuts <span className="count-badge">{skirtCuts.length}</span>
|
||||
</h3>
|
||||
<p className="cut-summary">
|
||||
Buy {skirting.stockCount} lengths · {skirting.pieces.length} installed pieces ·{' '}
|
||||
{wholeSkirt.reduce((sum, group) => sum + group.count, 0)} full lengths installed uncut.
|
||||
</p>
|
||||
<p className="helper">
|
||||
Lengths use the longest point. Mitres are saw settings from square; left and right follow
|
||||
the wall direction.
|
||||
</p>
|
||||
{skirtCuts.length ? (
|
||||
<div className="table-scroll">
|
||||
<table className="cut-table">
|
||||
<caption className="sr-only">Skirting pieces requiring cuts</caption>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">Piece</th>
|
||||
<th scope="col">Room / wall</th>
|
||||
<th scope="col">Length · mm</th>
|
||||
<th scope="col">Left / right</th>
|
||||
<th scope="col">Source</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{skirtCuts.map((piece) => (
|
||||
<tr key={piece.id} className={selectedPiece === piece.id ? 'selected' : ''}>
|
||||
<td data-label="Piece">
|
||||
<button
|
||||
className="piece-link cut-preview-button skirting-preview-button"
|
||||
aria-label={`Preview skirting cut ${piece.id}`}
|
||||
aria-haspopup="dialog"
|
||||
onClick={() => select(piece.id, piece.roomId)}
|
||||
>
|
||||
<span className="cut-thumbnail" aria-hidden="true">
|
||||
<SkirtingPreview
|
||||
piece={piece}
|
||||
thickness={project.skirting.thickness}
|
||||
compact
|
||||
/>
|
||||
</span>
|
||||
<span className="cut-preview-code">{piece.id}</span>
|
||||
</button>
|
||||
</td>
|
||||
<td data-label="Room / wall">
|
||||
{roomName(piece.roomId)}
|
||||
<small>Wall {piece.wallIndex + 1}</small>
|
||||
</td>
|
||||
<td data-label="Length · mm" className="numeric">
|
||||
{mm(piece.length)}
|
||||
<small>{mm(piece.backLength)} at wall</small>
|
||||
</td>
|
||||
<td data-label="Left / right">
|
||||
{degree(piece.leftMitre)} / {degree(piece.rightMitre)}
|
||||
<small>
|
||||
{piece.leftType} / {piece.rightType}
|
||||
</small>
|
||||
</td>
|
||||
<td data-label="Source">{piece.stockId}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : (
|
||||
<p className="empty-state">
|
||||
{skirting.pieces.length
|
||||
? 'No skirting cuts needed.'
|
||||
: 'Complete the outline and skirting measurements to calculate cuts.'}
|
||||
</p>
|
||||
)}
|
||||
<StockAllocations
|
||||
title="Source lengths for skirting cuts"
|
||||
items={skirting.stocks
|
||||
.filter((stock) => stock.pieceIds.some((id) => skirtIds.has(id)))
|
||||
.map((stock) => ({
|
||||
id: stock.id,
|
||||
pieces: stock.pieceIds.filter((id) => skirtIds.has(id)),
|
||||
size: `${mm(stock.length)} mm`,
|
||||
remainder: `${mm(stock.waste)} mm waste including kerf`,
|
||||
}))}
|
||||
/>
|
||||
</section>
|
||||
<CutDialog
|
||||
floor={selectedFloor}
|
||||
skirt={selectedSkirt}
|
||||
project={project}
|
||||
close={() => select(null)}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
166
src/components/CutPreview.tsx
Normal file
166
src/components/CutPreview.tsx
Normal file
|
|
@ -0,0 +1,166 @@
|
|||
import { Fragment } from 'react';
|
||||
import type { FlooringPiece, SkirtingPiece } from '../lib/types';
|
||||
import {
|
||||
exactMm,
|
||||
flooringTemplate,
|
||||
fullPreviewBox,
|
||||
skirtingEndBoxes,
|
||||
skirtingTemplate,
|
||||
viewBox,
|
||||
} from '../lib/cut-preview';
|
||||
|
||||
export function FlooringPreview({
|
||||
piece,
|
||||
compact = false,
|
||||
}: {
|
||||
piece: FlooringPiece;
|
||||
compact?: boolean;
|
||||
}) {
|
||||
const template = flooringTemplate(piece);
|
||||
const Wrapper = compact ? 'span' : 'figure';
|
||||
return (
|
||||
<Wrapper className={`flooring-preview-figure ${compact ? 'compact-preview' : 'exact-preview'}`}>
|
||||
<svg
|
||||
className="flooring-preview"
|
||||
viewBox={viewBox(fullPreviewBox(piece.length, piece.width))}
|
||||
preserveAspectRatio="xMidYMid meet"
|
||||
aria-hidden={compact || undefined}
|
||||
role={compact ? undefined : 'img'}
|
||||
aria-label={compact ? undefined : `Flooring shape ${piece.id}`}
|
||||
>
|
||||
<polygon
|
||||
points={template.map((point) => `${point.x},${point.y}`).join(' ')}
|
||||
fill="#dbeafe"
|
||||
stroke="#2563eb"
|
||||
strokeWidth={compact ? 1 : 1.5}
|
||||
vectorEffect="non-scaling-stroke"
|
||||
/>
|
||||
{!compact &&
|
||||
piece.shaped &&
|
||||
template.map((point, index) => (
|
||||
<text
|
||||
key={index}
|
||||
x={point.x}
|
||||
y={point.y - Math.max(piece.length, piece.width) * 0.015}
|
||||
textAnchor="middle"
|
||||
fontSize={Math.max(piece.length, piece.width) * 0.025}
|
||||
fill="#1e40af"
|
||||
>
|
||||
{index + 1}
|
||||
</text>
|
||||
))}
|
||||
</svg>
|
||||
{!compact && (
|
||||
<figcaption>
|
||||
Length {exactMm(piece.length)} mm × width {exactMm(piece.width)} mm · top view, to scale
|
||||
</figcaption>
|
||||
)}
|
||||
</Wrapper>
|
||||
);
|
||||
}
|
||||
|
||||
export function SkirtingPreview({
|
||||
piece,
|
||||
thickness,
|
||||
compact = false,
|
||||
}: {
|
||||
piece: SkirtingPiece;
|
||||
thickness: number;
|
||||
compact?: boolean;
|
||||
}) {
|
||||
const template = skirtingTemplate(piece, thickness);
|
||||
const Wrapper = compact ? 'span' : 'div';
|
||||
const EndWrapper = compact ? 'span' : 'figure';
|
||||
const Grid = compact ? 'span' : 'div';
|
||||
if (template.length !== 4) return <span className="helper">Shape template unavailable</span>;
|
||||
const boxes = skirtingEndBoxes(template, thickness);
|
||||
const points = template.map((point) => `${point.x},${point.y}`).join(' ');
|
||||
const ends = [
|
||||
{ side: 'left', back: template[0], front: template[3], box: boxes.left },
|
||||
{ side: 'right', back: template[1], front: template[2], box: boxes.right },
|
||||
] as const;
|
||||
return (
|
||||
<Wrapper className={`skirting-preview ${compact ? 'compact-preview' : 'exact-preview'}`}>
|
||||
{!compact && (
|
||||
<figure className="skirting-full-preview">
|
||||
<svg
|
||||
viewBox={viewBox(fullPreviewBox(piece.length, thickness))}
|
||||
preserveAspectRatio="xMidYMid meet"
|
||||
role="img"
|
||||
aria-label={`Full skirting shape ${piece.id}`}
|
||||
>
|
||||
<polygon
|
||||
points={points}
|
||||
fill="#ffedd5"
|
||||
stroke="#c2410c"
|
||||
strokeWidth={1}
|
||||
vectorEffect="non-scaling-stroke"
|
||||
/>
|
||||
</svg>
|
||||
<figcaption>
|
||||
Full length {exactMm(piece.length)} mm × thickness {exactMm(thickness)} mm · top view,
|
||||
to scale
|
||||
</figcaption>
|
||||
</figure>
|
||||
)}
|
||||
<Grid className="skirting-end-grid">
|
||||
{ends.map((end, index) => (
|
||||
<Fragment key={end.side}>
|
||||
<EndWrapper className={`skirting-end ${end.side}-end`}>
|
||||
<svg
|
||||
className="skirting-end-preview"
|
||||
data-end={end.side}
|
||||
viewBox={viewBox(end.box)}
|
||||
preserveAspectRatio="xMidYMid meet"
|
||||
overflow="hidden"
|
||||
aria-hidden={compact || undefined}
|
||||
role={compact ? undefined : 'img'}
|
||||
aria-label={
|
||||
compact
|
||||
? undefined
|
||||
: `${end.side === 'left' ? 'Left' : 'Right'} mitre close-up ${piece.id}`
|
||||
}
|
||||
>
|
||||
<polygon
|
||||
points={points}
|
||||
fill="#ffedd5"
|
||||
stroke="#c2410c"
|
||||
strokeWidth={1}
|
||||
vectorEffect="non-scaling-stroke"
|
||||
/>
|
||||
<line
|
||||
className="skirting-cut-edge"
|
||||
data-end={end.side}
|
||||
x1={end.back.x}
|
||||
y1={end.back.y}
|
||||
x2={end.front.x}
|
||||
y2={end.front.y}
|
||||
stroke="#9a3412"
|
||||
strokeWidth={compact ? 1.5 : 2.5}
|
||||
vectorEffect="non-scaling-stroke"
|
||||
/>
|
||||
</svg>
|
||||
{!compact && (
|
||||
<figcaption>
|
||||
{index === 0 ? 'Left' : 'Right'} end ·{' '}
|
||||
{exactMm(Math.abs(index === 0 ? piece.leftMitre : piece.rightMitre))}°
|
||||
</figcaption>
|
||||
)}
|
||||
</EndWrapper>
|
||||
{index === 0 && (
|
||||
<span className="board-break" aria-hidden="true">
|
||||
//
|
||||
</span>
|
||||
)}
|
||||
</Fragment>
|
||||
))}
|
||||
</Grid>
|
||||
{!compact && (
|
||||
<p className="helper">
|
||||
End close-ups; the middle is omitted. The back edge faces the wall, the front edge faces
|
||||
the room. Both axes use the same scale.
|
||||
</p>
|
||||
)}
|
||||
</Wrapper>
|
||||
);
|
||||
}
|
||||
96
src/components/Fields.tsx
Normal file
96
src/components/Fields.tsx
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
import { useId, useState } from 'react';
|
||||
import type { Issue } from '../lib/types';
|
||||
import { AlertCircle, Info, Check } from 'lucide-react';
|
||||
export function NumberField({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
unit = 'mm',
|
||||
min = 0,
|
||||
max,
|
||||
step = 1,
|
||||
hint,
|
||||
tooltip,
|
||||
}: {
|
||||
label: string;
|
||||
value: number;
|
||||
onChange: (n: number) => void;
|
||||
unit?: string;
|
||||
min?: number;
|
||||
max?: number;
|
||||
step?: number;
|
||||
hint?: string;
|
||||
tooltip?: string;
|
||||
}) {
|
||||
const id = useId();
|
||||
const [showTooltip, setShowTooltip] = useState(false);
|
||||
return (
|
||||
<div className="field">
|
||||
<span className="field-label">
|
||||
<label htmlFor={id}>{label}</label>
|
||||
{tooltip && (
|
||||
<span className="field-tooltip">
|
||||
<button
|
||||
type="button"
|
||||
className="tooltip-button"
|
||||
aria-label={`What is ${label.toLowerCase()}?`}
|
||||
aria-expanded={showTooltip}
|
||||
aria-controls={`${id}-tooltip`}
|
||||
aria-describedby={showTooltip ? `${id}-tooltip` : undefined}
|
||||
onClick={() => setShowTooltip((shown) => !shown)}
|
||||
onBlur={() => setShowTooltip(false)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Escape') setShowTooltip(false);
|
||||
}}
|
||||
>
|
||||
?
|
||||
</button>
|
||||
{showTooltip && (
|
||||
<span id={`${id}-tooltip`} role="tooltip" className="tooltip-content">
|
||||
{tooltip}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="number-input">
|
||||
<input
|
||||
id={id}
|
||||
type="number"
|
||||
inputMode="decimal"
|
||||
value={value}
|
||||
min={min}
|
||||
max={max}
|
||||
step={step}
|
||||
aria-describedby={hint ? `${id}-hint` : undefined}
|
||||
onChange={(e) => onChange(Number(e.target.value))}
|
||||
/>
|
||||
<span>{unit}</span>
|
||||
</span>
|
||||
{hint && <small id={`${id}-hint`}>{hint}</small>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export function Issues({ issues, compact = false }: { issues: Issue[]; compact?: boolean }) {
|
||||
const unique = issues.filter(
|
||||
(issue, i) => issues.findIndex((item) => item.message === issue.message) === i,
|
||||
);
|
||||
return (
|
||||
<div className={`issues ${compact ? 'compact' : ''}`} role="status">
|
||||
{unique.map((issue, i) => (
|
||||
<div className={`issue ${issue.severity}`} key={i}>
|
||||
{issue.severity === 'info' ? <Info size={16} /> : <AlertCircle size={16} />}
|
||||
<span>{issue.message}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export function ClosedBadge({ closed }: { closed: boolean }) {
|
||||
return (
|
||||
<span className={`badge ${closed ? 'success' : 'pending'}`}>
|
||||
{closed ? <Check size={12} /> : <AlertCircle size={12} />}{' '}
|
||||
{closed ? 'Outline closed' : 'Check outline'}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
365
src/components/FloorPlan.tsx
Normal file
365
src/components/FloorPlan.tsx
Normal file
|
|
@ -0,0 +1,365 @@
|
|||
import { useId } from 'react';
|
||||
import type { FlooringPlan, Geometry, Point, Room, SkirtingPlan, WallEdge } from '../lib/types';
|
||||
import { area, mm } from '../lib/format';
|
||||
import { signedArea } from '../lib/geometry';
|
||||
import { isSkirtingCut } from '../lib/cut-list';
|
||||
import { skirtingPolygon } from '../lib/skirting-polygon';
|
||||
import { dimensionLabels } from '../lib/dimension-labels';
|
||||
import type { DimensionLabel, LabelBox } from '../lib/dimension-labels';
|
||||
import { ClosedBadge } from './Fields';
|
||||
|
||||
const points = (path: Point[]) => path.map((p) => `${p.x},${p.y}`).join(' ');
|
||||
const midpoint = (a: Point, b: Point): Point => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 });
|
||||
|
||||
function Wall({ edge, span, label }: { edge: WallEdge; span: number; label: DimensionLabel }) {
|
||||
const { normal: n, offset } = label;
|
||||
const dx = edge.end.x - edge.start.x,
|
||||
dy = edge.end.y - edge.start.y;
|
||||
const length = Math.hypot(dx, dy) || 1;
|
||||
return (
|
||||
<g className="wall-drawing">
|
||||
<line
|
||||
x1={edge.start.x}
|
||||
y1={edge.start.y}
|
||||
x2={edge.end.x}
|
||||
y2={edge.end.y}
|
||||
stroke="#27364a"
|
||||
strokeWidth={span * 0.003}
|
||||
/>
|
||||
<line
|
||||
x1={edge.start.x + n.x * offset}
|
||||
y1={edge.start.y + n.y * offset}
|
||||
x2={edge.end.x + n.x * offset}
|
||||
y2={edge.end.y + n.y * offset}
|
||||
stroke="#8591a3"
|
||||
strokeWidth={span * 0.001}
|
||||
/>
|
||||
{[edge.start, edge.end].map((p, i) => (
|
||||
<line
|
||||
key={i}
|
||||
x1={p.x + n.x * (offset - span * 0.01)}
|
||||
y1={p.y + n.y * (offset - span * 0.01)}
|
||||
x2={p.x + n.x * (offset + span * 0.01)}
|
||||
y2={p.y + n.y * (offset + span * 0.01)}
|
||||
stroke="#8591a3"
|
||||
strokeWidth={span * 0.001}
|
||||
/>
|
||||
))}
|
||||
<g
|
||||
className="wall-label"
|
||||
transform={`translate(${label.x} ${label.y}) rotate(${label.angle})`}
|
||||
>
|
||||
<rect
|
||||
x={-label.width / 2}
|
||||
y={-label.font * 0.75}
|
||||
width={label.width}
|
||||
height={label.font * 1.5}
|
||||
fill="#fffdf7"
|
||||
/>
|
||||
<text textAnchor="middle" dominantBaseline="middle" fontSize={label.font} fill="#17263f">
|
||||
{label.text}
|
||||
</text>
|
||||
</g>
|
||||
{edge.doors
|
||||
.filter((d) => d.offset >= 0 && d.width > 0 && d.offset + d.width <= edge.length + 0.001)
|
||||
.map((door) => {
|
||||
const a = {
|
||||
x: edge.start.x + (dx / length) * door.offset,
|
||||
y: edge.start.y + (dy / length) * door.offset,
|
||||
};
|
||||
const b = { x: a.x + (dx / length) * door.width, y: a.y + (dy / length) * door.width };
|
||||
const swing = { x: a.x - n.x * door.width, y: a.y - n.y * door.width };
|
||||
const clockwise = dx * -n.y - dy * -n.x > 0;
|
||||
return (
|
||||
<g key={door.id}>
|
||||
<line
|
||||
x1={a.x}
|
||||
y1={a.y}
|
||||
x2={b.x}
|
||||
y2={b.y}
|
||||
stroke="#fffdf7"
|
||||
strokeWidth={span * 0.012}
|
||||
/>
|
||||
<line
|
||||
x1={a.x}
|
||||
y1={a.y}
|
||||
x2={swing.x}
|
||||
y2={swing.y}
|
||||
stroke="#53647c"
|
||||
strokeWidth={span * 0.002}
|
||||
/>
|
||||
<path
|
||||
d={`M ${b.x} ${b.y} A ${door.width} ${door.width} 0 0 ${clockwise ? 1 : 0} ${swing.x} ${swing.y}`}
|
||||
fill="none"
|
||||
stroke="#53647c"
|
||||
strokeWidth={span * 0.0015}
|
||||
strokeDasharray={`${span * 0.01} ${span * 0.008}`}
|
||||
/>
|
||||
<title>
|
||||
Door: {mm(door.width)} mm, {mm(door.offset)} mm from W{edge.index + 1} start
|
||||
</title>
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
interface Props {
|
||||
room: Room;
|
||||
geometry: Geometry;
|
||||
flooring: FlooringPlan;
|
||||
skirting: SkirtingPlan;
|
||||
selectedPiece: string | null;
|
||||
select: (id: string) => void;
|
||||
}
|
||||
|
||||
export function FloorPlan({ room, geometry, flooring, skirting, selectedPiece, select }: Props) {
|
||||
const hatch = useId().replaceAll(':', '');
|
||||
const allPoints = geometry.edges.flatMap((edge) => [edge.start, edge.end]);
|
||||
const minX = Math.min(0, ...allPoints.map((p) => p.x)),
|
||||
maxX = Math.max(100, ...allPoints.map((p) => p.x));
|
||||
const minY = Math.min(0, ...allPoints.map((p) => p.y)),
|
||||
maxY = Math.max(100, ...allPoints.map((p) => p.y));
|
||||
const span = Math.max(maxX - minX, maxY - minY, 1000),
|
||||
font = span * 0.024;
|
||||
const orientation = Math.sign(signedArea(geometry.vertices)) || 1;
|
||||
const floorPieces = flooring.pieces.filter((p) => p.roomId === room.id);
|
||||
const skirtPieces = skirting.pieces.filter((p) => p.roomId === room.id);
|
||||
const skirtLabels = new Map<string, Point>();
|
||||
const reserved: LabelBox[] = [];
|
||||
for (const piece of skirtPieces) {
|
||||
if (!isSkirtingCut(piece, skirting)) continue;
|
||||
const center = midpoint(piece.start, piece.end);
|
||||
const length = Math.hypot(piece.end.x - piece.start.x, piece.end.y - piece.start.y) || 1;
|
||||
const x = center.x + ((orientation * (piece.end.y - piece.start.y)) / length) * span * 0.032;
|
||||
const y = center.y - ((orientation * (piece.end.x - piece.start.x)) / length) * span * 0.032;
|
||||
skirtLabels.set(piece.id, { x, y });
|
||||
reserved.push({
|
||||
minX: x - font * 1.2,
|
||||
maxX: x + font * 1.2,
|
||||
minY: y - font * 0.7,
|
||||
maxY: y + font * 0.7,
|
||||
});
|
||||
}
|
||||
const labels = dimensionLabels(geometry.edges, span, orientation, reserved);
|
||||
const boxes = [...reserved, ...labels.map((label) => label.box)];
|
||||
const left = Math.min(minX, ...boxes.map((b) => b.minX)) - span * 0.035;
|
||||
const top = Math.min(minY, ...boxes.map((b) => b.minY)) - span * 0.035;
|
||||
const width = Math.max(maxX, ...boxes.map((b) => b.maxX)) + span * 0.035 - left;
|
||||
const height = Math.max(maxY, ...boxes.map((b) => b.maxY)) + span * 0.035 - top;
|
||||
return (
|
||||
<section className="drawing-card" aria-label="Floor plan preview">
|
||||
<div className="drawing-header">
|
||||
<h2>
|
||||
Floor plan <small>{area(geometry.area)} m²</small>
|
||||
</h2>
|
||||
<ClosedBadge closed={geometry.closed && geometry.valid} />
|
||||
</div>
|
||||
<div className="drawing-legend">
|
||||
<span>
|
||||
<i className="floor-key" />
|
||||
Flooring
|
||||
</span>
|
||||
<span>
|
||||
<i className="skirt-key" />
|
||||
Skirting
|
||||
</span>
|
||||
</div>
|
||||
<div className="drawing-viewport">
|
||||
<svg
|
||||
className="room-svg"
|
||||
role="img"
|
||||
aria-label={`${room.name} floor plan with ${geometry.edges.length} walls, ${floorPieces.length} floorboards and ${skirtPieces.length} skirting pieces`}
|
||||
viewBox={`${left} ${top} ${width} ${height}`}
|
||||
width={width}
|
||||
height={height}
|
||||
preserveAspectRatio="xMidYMid meet"
|
||||
>
|
||||
<defs>
|
||||
<pattern
|
||||
id={hatch}
|
||||
width={span * 0.02}
|
||||
height={span * 0.02}
|
||||
patternUnits="userSpaceOnUse"
|
||||
patternTransform="rotate(45)"
|
||||
>
|
||||
<line
|
||||
x1="0"
|
||||
y1="0"
|
||||
x2="0"
|
||||
y2={span * 0.02}
|
||||
stroke="#1647ab"
|
||||
strokeOpacity=".16"
|
||||
strokeWidth={span * 0.003}
|
||||
/>
|
||||
</pattern>
|
||||
</defs>
|
||||
{geometry.closed && <polygon points={points(geometry.vertices)} fill="#fff" />}
|
||||
{floorPieces.map((piece) => {
|
||||
const cut = piece.cut || piece.reused;
|
||||
const x =
|
||||
(Math.min(...piece.polygon.map((p) => p.x)) +
|
||||
Math.max(...piece.polygon.map((p) => p.x))) /
|
||||
2;
|
||||
const y =
|
||||
(Math.min(...piece.polygon.map((p) => p.y)) +
|
||||
Math.max(...piece.polygon.map((p) => p.y))) /
|
||||
2;
|
||||
return (
|
||||
<g
|
||||
key={piece.id}
|
||||
className={`floor-piece ${cut ? 'svg-cut floor-cut' : 'uncut'}`}
|
||||
data-material="flooring"
|
||||
data-piece-id={piece.id}
|
||||
role={cut ? 'button' : undefined}
|
||||
tabIndex={cut ? 0 : undefined}
|
||||
aria-hidden={cut ? undefined : true}
|
||||
aria-label={cut ? `Select flooring cut ${piece.id}` : undefined}
|
||||
aria-pressed={cut ? selectedPiece === piece.id : undefined}
|
||||
onClick={cut ? () => select(piece.id) : undefined}
|
||||
onKeyDown={
|
||||
cut
|
||||
? (e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
select(piece.id);
|
||||
}
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<polygon
|
||||
points={points(piece.polygon)}
|
||||
fill={
|
||||
cut ? (selectedPiece === piece.id ? '#ceddf9' : `url(#${hatch})`) : '#f5f6f8'
|
||||
}
|
||||
stroke={cut ? '#1647ab' : '#9baabd'}
|
||||
strokeWidth={span * (selectedPiece === piece.id ? 0.003 : 0.0012)}
|
||||
/>
|
||||
{cut && (
|
||||
<>
|
||||
<g
|
||||
transform={`translate(${x} ${y})${room.direction === 90 ? ' rotate(90)' : ''}`}
|
||||
pointerEvents="none"
|
||||
>
|
||||
<rect
|
||||
x={-font * 1.1}
|
||||
y={-font * 0.55}
|
||||
width={font * 2.2}
|
||||
height={font * 1.1}
|
||||
fill="#1647ab"
|
||||
/>
|
||||
<text
|
||||
textAnchor="middle"
|
||||
dominantBaseline="middle"
|
||||
fill="#fff"
|
||||
fontSize={font * 0.76}
|
||||
fontWeight="600"
|
||||
>
|
||||
{piece.id}
|
||||
</text>
|
||||
</g>
|
||||
<title>
|
||||
{piece.id}: {mm(piece.length)} × {mm(piece.width)} mm
|
||||
</title>
|
||||
</>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{geometry.edges.map((edge, i) => (
|
||||
<Wall key={edge.wallId} edge={edge} span={span} label={labels[i]} />
|
||||
))}
|
||||
{skirtPieces.map((piece) => {
|
||||
const cut = isSkirtingCut(piece, skirting);
|
||||
const label = skirtLabels.get(piece.id);
|
||||
// Each template uses its true wall-facing and room-facing edges, including mitres.
|
||||
const thickness = piece.template ? Math.max(...piece.template.map((p) => p.y)) : 0;
|
||||
const polygon = skirtingPolygon(piece, thickness, orientation);
|
||||
return (
|
||||
<g
|
||||
key={piece.id}
|
||||
className={`skirt-piece ${cut ? 'svg-cut skirt-cut' : 'uncut'}`}
|
||||
data-material="skirting"
|
||||
data-piece-id={piece.id}
|
||||
role={cut ? 'button' : undefined}
|
||||
tabIndex={cut ? 0 : undefined}
|
||||
aria-hidden={cut ? undefined : true}
|
||||
aria-label={cut ? `Select skirting cut ${piece.id}` : undefined}
|
||||
aria-pressed={cut ? selectedPiece === piece.id : undefined}
|
||||
onClick={cut ? () => select(piece.id) : undefined}
|
||||
onKeyDown={
|
||||
cut
|
||||
? (e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
select(piece.id);
|
||||
}
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<polygon
|
||||
points={points(polygon)}
|
||||
fill={selectedPiece === piece.id ? '#17263f' : '#b74900'}
|
||||
stroke="#8d3800"
|
||||
strokeWidth={span * 0.001}
|
||||
/>
|
||||
{cut && (
|
||||
<line
|
||||
x1={piece.start.x}
|
||||
y1={piece.start.y}
|
||||
x2={piece.end.x}
|
||||
y2={piece.end.y}
|
||||
stroke="transparent"
|
||||
strokeWidth={span * 0.025}
|
||||
/>
|
||||
)}
|
||||
{label && (
|
||||
<g transform={`translate(${label.x} ${label.y})`} pointerEvents="none">
|
||||
<rect
|
||||
x={-font * 1.1}
|
||||
y={-font * 0.58}
|
||||
width={font * 2.2}
|
||||
height={font * 1.16}
|
||||
fill="#fffdf7"
|
||||
stroke="#b74900"
|
||||
strokeWidth={span * 0.0012}
|
||||
/>
|
||||
<text
|
||||
textAnchor="middle"
|
||||
dominantBaseline="middle"
|
||||
fill="#8d3800"
|
||||
fontSize={font * 0.8}
|
||||
fontWeight="700"
|
||||
>
|
||||
{piece.id}
|
||||
</text>
|
||||
</g>
|
||||
)}
|
||||
{cut && (
|
||||
<title>
|
||||
{piece.id}: {mm(piece.length)} mm · {mm(piece.leftMitre)}° /{' '}
|
||||
{mm(piece.rightMitre)}°
|
||||
</title>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{!geometry.closed && geometry.edges.length > 1 && (
|
||||
<line
|
||||
x1={geometry.edges.at(-1)!.end.x}
|
||||
y1={geometry.edges.at(-1)!.end.y}
|
||||
x2="0"
|
||||
y2="0"
|
||||
stroke="#b74900"
|
||||
strokeWidth={span * 0.003}
|
||||
strokeDasharray={`${span * 0.015} ${span * 0.008}`}
|
||||
/>
|
||||
)}
|
||||
</svg>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
178
src/components/MaterialsEditor.tsx
Normal file
178
src/components/MaterialsEditor.tsx
Normal file
|
|
@ -0,0 +1,178 @@
|
|||
import { Plus, Trash2, ArrowRight, ArrowDown } from 'lucide-react';
|
||||
import type { Project, Room, FlooringSettings, SkirtingSettings } from '../lib/types';
|
||||
import { NumberField } from './Fields';
|
||||
|
||||
interface Props {
|
||||
project: Project;
|
||||
room: Room;
|
||||
changeProject: (fn: (p: Project) => Project) => void;
|
||||
changeRoom: (fn: (r: Room) => Room) => void;
|
||||
}
|
||||
|
||||
const kerfHelp =
|
||||
'Width of material removed by the saw blade. A 3 mm blade turns a 1,000 mm board into 600 mm + 397 mm after one cut.';
|
||||
|
||||
export function MaterialsEditor({ project, room, changeProject, changeRoom }: Props) {
|
||||
const f = project.flooring;
|
||||
const s = project.skirting;
|
||||
const floor = (key: keyof FlooringSettings, value: number | string) =>
|
||||
changeProject((p) => ({ ...p, flooring: { ...p.flooring, [key]: value } }));
|
||||
const skirt = (key: keyof SkirtingSettings, value: number | number[]) =>
|
||||
changeProject((p) => ({ ...p, skirting: { ...p.skirting, [key]: value } }));
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="editor-heading">
|
||||
<h2>Materials</h2>
|
||||
<span>Shared across rooms · mm</span>
|
||||
</div>
|
||||
<section className="material-section flooring" aria-labelledby="flooring-materials">
|
||||
<h3 id="flooring-materials" className="material-heading">
|
||||
Floorboards
|
||||
</h3>
|
||||
<div className="field-grid">
|
||||
<NumberField
|
||||
label="Board length"
|
||||
value={f.length}
|
||||
min={1}
|
||||
onChange={(n) => floor('length', n)}
|
||||
/>
|
||||
<NumberField
|
||||
label="Board width"
|
||||
value={f.width}
|
||||
min={1}
|
||||
onChange={(n) => floor('width', n)}
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<span>Laying pattern</span>
|
||||
<div className="segmented" role="group" aria-label="Laying pattern">
|
||||
<button
|
||||
className={f.pattern === 'brick' ? 'active' : ''}
|
||||
aria-pressed={f.pattern === 'brick'}
|
||||
onClick={() => floor('pattern', 'brick')}
|
||||
>
|
||||
Brick
|
||||
</button>
|
||||
<button
|
||||
className={f.pattern === 'random' ? 'active' : ''}
|
||||
aria-pressed={f.pattern === 'random'}
|
||||
onClick={() => floor('pattern', 'random')}
|
||||
>
|
||||
Random
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="field">
|
||||
<span>Board direction · {room.name}</span>
|
||||
<div className="segmented" role="group" aria-label="Board direction">
|
||||
<button
|
||||
className={room.direction === 0 ? 'active' : ''}
|
||||
aria-pressed={room.direction === 0}
|
||||
onClick={() => changeRoom((r) => ({ ...r, direction: 0 }))}
|
||||
>
|
||||
<ArrowRight size={16} aria-hidden="true" /> Along first wall
|
||||
</button>
|
||||
<button
|
||||
className={room.direction === 90 ? 'active' : ''}
|
||||
aria-pressed={room.direction === 90}
|
||||
onClick={() => changeRoom((r) => ({ ...r, direction: 90 }))}
|
||||
>
|
||||
<ArrowDown size={16} aria-hidden="true" /> Across first wall
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="field-grid">
|
||||
<NumberField label="Wall spacer" value={f.gap} onChange={(n) => floor('gap', n)} />
|
||||
<NumberField
|
||||
label="Saw kerf"
|
||||
value={f.kerf}
|
||||
onChange={(n) => floor('kerf', n)}
|
||||
tooltip={kerfHelp}
|
||||
/>
|
||||
<NumberField
|
||||
label="Minimum joint offset"
|
||||
value={f.minOffset}
|
||||
onChange={(n) => floor('minOffset', n)}
|
||||
/>
|
||||
<NumberField
|
||||
label="Maximum joint offset"
|
||||
value={f.maxOffset}
|
||||
onChange={(n) => floor('maxOffset', n)}
|
||||
/>
|
||||
<NumberField
|
||||
label="Shortest end piece"
|
||||
value={f.minLength}
|
||||
min={1}
|
||||
onChange={(n) => floor('minLength', n)}
|
||||
/>
|
||||
<NumberField
|
||||
label="Narrowest edge row"
|
||||
value={f.minWidth}
|
||||
min={1}
|
||||
onChange={(n) => floor('minWidth', n)}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
<section className="material-section skirting" aria-labelledby="skirting-materials">
|
||||
<h3 id="skirting-materials" className="material-heading">
|
||||
Skirting boards
|
||||
</h3>
|
||||
{s.stockLengths.map((length, i) => (
|
||||
<div className="stock-input" key={i}>
|
||||
<NumberField
|
||||
label={`Stock length ${i + 1}`}
|
||||
value={length}
|
||||
min={1}
|
||||
onChange={(n) =>
|
||||
skirt(
|
||||
'stockLengths',
|
||||
s.stockLengths.map((v, j) => (i === j ? n : v)),
|
||||
)
|
||||
}
|
||||
/>
|
||||
<button
|
||||
className="icon-button"
|
||||
aria-label={`Remove stock length ${i + 1}`}
|
||||
disabled={s.stockLengths.length === 1}
|
||||
onClick={() =>
|
||||
skirt(
|
||||
'stockLengths',
|
||||
s.stockLengths.filter((_, j) => i !== j),
|
||||
)
|
||||
}
|
||||
>
|
||||
<Trash2 size={16} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<button
|
||||
className="text-button"
|
||||
onClick={() => skirt('stockLengths', [...s.stockLengths, 3600])}
|
||||
disabled={s.stockLengths.length >= 10}
|
||||
>
|
||||
<Plus size={16} /> Add a stock length
|
||||
</button>
|
||||
<div className="field-grid">
|
||||
<NumberField
|
||||
label="Skirting thickness"
|
||||
value={s.thickness}
|
||||
onChange={(n) => skirt('thickness', n)}
|
||||
/>
|
||||
<NumberField
|
||||
label="Minimum piece"
|
||||
value={s.minLength}
|
||||
min={1}
|
||||
onChange={(n) => skirt('minLength', n)}
|
||||
/>
|
||||
<NumberField
|
||||
label="Skirting saw kerf"
|
||||
value={s.kerf}
|
||||
onChange={(n) => skirt('kerf', n)}
|
||||
tooltip={kerfHelp}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
);
|
||||
}
|
||||
364
src/components/OutlineEditor.tsx
Normal file
364
src/components/OutlineEditor.tsx
Normal file
|
|
@ -0,0 +1,364 @@
|
|||
import { Plus, Trash2, DoorOpen, Check, MoveUpRight } from 'lucide-react';
|
||||
import type { Geometry, Project, Room, Wall } from '../lib/types';
|
||||
import { fireplace, rectangle, nextId } from '../lib/defaults';
|
||||
import { normalizeAngle } from '../lib/geometry';
|
||||
import { mm } from '../lib/format';
|
||||
import { NumberField, Issues } from './Fields';
|
||||
interface Props {
|
||||
room: Room;
|
||||
geometry: Geometry;
|
||||
tolerance: number;
|
||||
changeRoom: (fn: (room: Room) => Room) => void;
|
||||
changeProject: (fn: (project: Project) => Project) => void;
|
||||
remove: () => void;
|
||||
canRemove: boolean;
|
||||
}
|
||||
export function OutlineEditor({
|
||||
room,
|
||||
geometry,
|
||||
tolerance,
|
||||
changeRoom,
|
||||
changeProject,
|
||||
remove,
|
||||
canRemove,
|
||||
}: Props) {
|
||||
const changeWall = (id: string, fn: (wall: Wall) => Wall) =>
|
||||
changeRoom((r) => ({ ...r, walls: r.walls.map((w) => (w.id === id ? fn(w) : w)) }));
|
||||
const isRectangle =
|
||||
room.walls.length === 4 &&
|
||||
room.walls.every((w) => w.turn === 90) &&
|
||||
room.walls[0].length === room.walls[2].length &&
|
||||
room.walls[1].length === room.walls[3].length;
|
||||
const lastEdge = geometry.edges.at(-1);
|
||||
const finalExpectedLength = lastEdge ? Math.hypot(lastEdge.start.x, lastEdge.start.y) : 0;
|
||||
const addWall = () =>
|
||||
changeRoom((r) => ({
|
||||
...r,
|
||||
walls: [
|
||||
...r.walls,
|
||||
{
|
||||
id: nextId(
|
||||
`${r.id}-w`,
|
||||
r.walls.map((w) => w.id),
|
||||
),
|
||||
length: 1000,
|
||||
turn: 90,
|
||||
doors: [],
|
||||
},
|
||||
],
|
||||
}));
|
||||
const closeOutline = () =>
|
||||
changeRoom((r) => ({
|
||||
...r,
|
||||
walls: [
|
||||
...r.walls.map((w, i) =>
|
||||
i === r.walls.length - 1 ? { ...w, turn: geometry.closingTurn } : w,
|
||||
),
|
||||
{
|
||||
id: nextId(
|
||||
`${r.id}-w`,
|
||||
r.walls.map((w) => w.id),
|
||||
),
|
||||
length: Math.round(geometry.closingLength * 10) / 10,
|
||||
turn: 90,
|
||||
doors: [],
|
||||
},
|
||||
],
|
||||
}));
|
||||
const addDoor = () => {
|
||||
const target = room.walls[room.walls.length - 1];
|
||||
if (!target) return;
|
||||
changeWall(target.id, (w) => ({
|
||||
...w,
|
||||
doors: [
|
||||
...w.doors,
|
||||
{
|
||||
id: nextId(
|
||||
`${room.id}-door`,
|
||||
room.walls.flatMap((w) => w.doors.map((d) => d.id)),
|
||||
),
|
||||
offset: Math.min(500, Math.max(0, w.length - 826)),
|
||||
width: 826,
|
||||
},
|
||||
],
|
||||
}));
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<div className="editor-heading">
|
||||
<h2>Room measurements</h2>
|
||||
<span>Millimetres</span>
|
||||
</div>
|
||||
<label className="field">
|
||||
<span>Room name</span>
|
||||
<input
|
||||
value={room.name}
|
||||
maxLength={80}
|
||||
onChange={(e) => changeRoom((r) => ({ ...r, name: e.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
<div className="template-options">
|
||||
<button
|
||||
className={isRectangle ? 'template active' : 'template'}
|
||||
aria-pressed={isRectangle}
|
||||
onClick={() => changeRoom((r) => rectangle(r.id, r.name))}
|
||||
>
|
||||
<span className="rectangle-icon" />
|
||||
Rectangle
|
||||
</button>
|
||||
<button
|
||||
className={room.walls.length === 8 ? 'template active' : 'template'}
|
||||
aria-pressed={room.walls.length === 8}
|
||||
onClick={() => changeRoom((r) => fireplace(r.id, r.name))}
|
||||
>
|
||||
<span className="fireplace-icon" />
|
||||
With fireplace
|
||||
</button>
|
||||
<button
|
||||
className="template"
|
||||
onClick={() =>
|
||||
changeRoom((r) => ({
|
||||
...r,
|
||||
walls: [{ id: `${r.id}-w1`, length: 4000, turn: 90, doors: [] }],
|
||||
}))
|
||||
}
|
||||
>
|
||||
<MoveUpRight size={19} />
|
||||
Custom
|
||||
</button>
|
||||
</div>
|
||||
{isRectangle && (
|
||||
<div className="field-grid quick-dimensions">
|
||||
<NumberField
|
||||
label="Room width"
|
||||
value={room.walls[0].length}
|
||||
min={1}
|
||||
onChange={(n) =>
|
||||
changeRoom((r) => ({
|
||||
...r,
|
||||
walls: r.walls.map((w, i) => (i % 2 === 0 ? { ...w, length: n } : w)),
|
||||
}))
|
||||
}
|
||||
/>
|
||||
<NumberField
|
||||
label="Room length"
|
||||
value={room.walls[1].length}
|
||||
min={1}
|
||||
onChange={(n) =>
|
||||
changeRoom((r) => ({
|
||||
...r,
|
||||
walls: r.walls.map((w, i) => (i % 2 === 1 ? { ...w, length: n } : w)),
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<details className="wall-details" open={!isRectangle}>
|
||||
<summary>
|
||||
Walls & corners <span>{room.walls.length} walls</span>
|
||||
</summary>
|
||||
<p className="helper">
|
||||
Start to the right; work clockwise. Right turn: <b>90°</b>. Left turn: <b>−90°</b>.
|
||||
</p>
|
||||
<div className="wall-table">
|
||||
<div className="wall-head">
|
||||
<span>Wall</span>
|
||||
<span>Length · mm</span>
|
||||
<span>Next turn · °</span>
|
||||
<span />
|
||||
</div>
|
||||
{room.walls.map((wall, i) => (
|
||||
<div className="wall-row" key={wall.id}>
|
||||
<span className="wall-code">W{i + 1}</span>
|
||||
<input
|
||||
aria-label={`Wall ${i + 1} length`}
|
||||
type="number"
|
||||
inputMode="decimal"
|
||||
min={1}
|
||||
step={1}
|
||||
value={wall.length}
|
||||
onChange={(e) =>
|
||||
changeWall(wall.id, (w) => ({ ...w, length: Number(e.target.value) }))
|
||||
}
|
||||
/>
|
||||
<input
|
||||
aria-label={`Wall ${i + 1} turn`}
|
||||
type="number"
|
||||
inputMode="decimal"
|
||||
min={-179}
|
||||
max={179}
|
||||
step={0.1}
|
||||
value={
|
||||
geometry.closed && i === room.walls.length - 1
|
||||
? Math.round(normalizeAngle(-(lastEdge?.heading ?? 0)) * 10) / 10
|
||||
: wall.turn
|
||||
}
|
||||
title={
|
||||
geometry.closed && i === room.walls.length - 1
|
||||
? 'The final corner is derived from the closed outline.'
|
||||
: 'Turn after this wall; positive turns right.'
|
||||
}
|
||||
disabled={geometry.closed && i === room.walls.length - 1}
|
||||
onChange={(e) =>
|
||||
changeWall(wall.id, (w) => ({ ...w, turn: Number(e.target.value) }))
|
||||
}
|
||||
/>
|
||||
<button
|
||||
className="icon-button"
|
||||
aria-label={`Remove wall ${i + 1}`}
|
||||
disabled={room.walls.length === 1}
|
||||
onClick={() =>
|
||||
changeRoom((r) => ({ ...r, walls: r.walls.filter((w) => w.id !== wall.id) }))
|
||||
}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<button className="text-button" onClick={addWall} disabled={room.walls.length >= 100}>
|
||||
<Plus size={15} /> Add a wall
|
||||
</button>
|
||||
</details>
|
||||
{geometry.closed ? (
|
||||
<div className="closure-check">
|
||||
<Check size={17} />
|
||||
<div>
|
||||
<strong>Outline closed</strong>
|
||||
<span>
|
||||
Closing gap {mm(geometry.gap)} mm · tolerance {mm(tolerance)} mm
|
||||
</span>
|
||||
<span>
|
||||
Final wall: {mm(finalExpectedLength)} mm expected ·{' '}
|
||||
{mm(Math.abs(geometry.finalLengthError))} mm difference
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
room.walls.length >= 2 &&
|
||||
geometry.closingLength > 0 && (
|
||||
<div className="closure-suggestion">
|
||||
<div>
|
||||
<strong>{mm(geometry.closingLength)} mm to close</strong>
|
||||
<p>Next turn {mm(geometry.closingTurn)}°. After adding, enter the measured length.</p>
|
||||
<button
|
||||
className="text-button"
|
||||
onClick={closeOutline}
|
||||
disabled={room.walls.length >= 100 || Math.abs(geometry.closingTurn) >= 179.99}
|
||||
>
|
||||
Add closing wall <Plus size={14} />
|
||||
</button>
|
||||
{room.walls.length >= 3 && (
|
||||
<p>
|
||||
If W{room.walls.length} is the final wall: {mm(finalExpectedLength)} mm expected;
|
||||
length differs by {mm(Math.abs(geometry.finalLengthError))} mm, direction by{' '}
|
||||
{mm(Math.abs(geometry.finalAngleError))}°.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
<Issues issues={geometry.issues.filter((i) => i.severity !== 'info')} compact />
|
||||
<div className="panel-divider" />
|
||||
<div className="subheading">
|
||||
<h3>
|
||||
<DoorOpen size={16} /> Doorways
|
||||
</h3>
|
||||
<span>{room.walls.reduce((n, w) => n + w.doors.length, 0)} openings</span>
|
||||
</div>
|
||||
<p className="helper">
|
||||
Width includes trim where skirting stops. Offset is measured from the wall’s start.
|
||||
</p>
|
||||
{room.walls.flatMap((wall, wallIndex) =>
|
||||
wall.doors.map((door) => (
|
||||
<div className="door-card" key={door.id}>
|
||||
<div className="door-card-title">
|
||||
<label>
|
||||
On wall{' '}
|
||||
<select
|
||||
aria-label={`Door ${door.id} wall`}
|
||||
value={wall.id}
|
||||
onChange={(e) =>
|
||||
changeRoom((r) => ({
|
||||
...r,
|
||||
walls: r.walls.map((w) =>
|
||||
w.id === wall.id
|
||||
? { ...w, doors: w.doors.filter((d) => d.id !== door.id) }
|
||||
: w.id === e.target.value
|
||||
? { ...w, doors: [...w.doors, door] }
|
||||
: w,
|
||||
),
|
||||
}))
|
||||
}
|
||||
>
|
||||
{room.walls.map((w, i) => (
|
||||
<option key={w.id} value={w.id}>
|
||||
W{i + 1}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<button
|
||||
className="icon-button"
|
||||
aria-label={`Remove door on wall ${wallIndex + 1}`}
|
||||
onClick={() =>
|
||||
changeWall(wall.id, (w) => ({
|
||||
...w,
|
||||
doors: w.doors.filter((d) => d.id !== door.id),
|
||||
}))
|
||||
}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="field-grid">
|
||||
<NumberField
|
||||
label="Door offset"
|
||||
value={door.offset}
|
||||
onChange={(n) =>
|
||||
changeWall(wall.id, (w) => ({
|
||||
...w,
|
||||
doors: w.doors.map((d) => (d.id === door.id ? { ...d, offset: n } : d)),
|
||||
}))
|
||||
}
|
||||
/>
|
||||
<NumberField
|
||||
label="Door width"
|
||||
min={1}
|
||||
value={door.width}
|
||||
onChange={(n) =>
|
||||
changeWall(wall.id, (w) => ({
|
||||
...w,
|
||||
doors: w.doors.map((d) => (d.id === door.id ? { ...d, width: n } : d)),
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)),
|
||||
)}
|
||||
<button
|
||||
className="text-button"
|
||||
onClick={addDoor}
|
||||
disabled={!room.walls.length || room.walls.at(-1)!.doors.length >= 30}
|
||||
>
|
||||
<Plus size={15} /> Add a doorway
|
||||
</button>
|
||||
<div className="panel-divider" />
|
||||
<NumberField
|
||||
label="Measurement tolerance"
|
||||
value={tolerance}
|
||||
max={50}
|
||||
onChange={(n) => changeProject((p) => ({ ...p, tolerance: n }))}
|
||||
hint="Largest closing gap accepted for the cut plan."
|
||||
/>
|
||||
{canRemove && (
|
||||
<button className="text-button danger remove-room" onClick={remove}>
|
||||
<Trash2 size={14} />
|
||||
Remove this room
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
21
src/lib/cut-instructions.ts
Normal file
21
src/lib/cut-instructions.ts
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import type { FlooringPiece } from './types';
|
||||
/** These instructions describe the factory edges needed by the allocation, not a saw brand's orientation. */
|
||||
export function flooringInstructions(piece: FlooringPiece): string {
|
||||
const ends =
|
||||
piece.factoryLeft && piece.factoryRight
|
||||
? 'Keep both factory ends.'
|
||||
: piece.factoryLeft
|
||||
? 'Keep the left factory end; trim from the right.'
|
||||
: piece.factoryRight
|
||||
? 'Keep the right factory end; trim from the left.'
|
||||
: 'Neither short end joins another board.';
|
||||
const rip =
|
||||
piece.ripEdge === 'top'
|
||||
? 'Rip the top long edge; keep the bottom factory edge.'
|
||||
: piece.ripEdge === 'bottom'
|
||||
? 'Rip the bottom long edge; keep the top factory edge.'
|
||||
: piece.ripEdge === 'both'
|
||||
? 'Trim both long edges to the perimeter template.'
|
||||
: 'Keep factory long edges wherever they join the next row.';
|
||||
return `${ends} ${rip}`;
|
||||
}
|
||||
78
src/lib/cut-list.ts
Normal file
78
src/lib/cut-list.ts
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
import type {
|
||||
FlooringPiece,
|
||||
FlooringPlan,
|
||||
FlooringSettings,
|
||||
SkirtingPiece,
|
||||
SkirtingPlan,
|
||||
} from './types';
|
||||
|
||||
const sameLength = (a: number, b: number) => Math.abs(a - b) < 0.01;
|
||||
|
||||
/** A ready offcut still needs a placement code; only fresh, uncut whole boards are omitted. */
|
||||
export const flooringCuts = (plan: FlooringPlan) =>
|
||||
plan.pieces.filter((piece) => piece.cut || piece.reused);
|
||||
|
||||
export function isSkirtingCut(piece: SkirtingPiece, plan: SkirtingPlan): boolean {
|
||||
const stock = plan.stocks.find((candidate) => candidate.id === piece.stockId);
|
||||
return (
|
||||
!stock ||
|
||||
!sameLength(piece.length, stock.length) ||
|
||||
Math.abs(piece.leftMitre) > 0.001 ||
|
||||
Math.abs(piece.rightMitre) > 0.001
|
||||
);
|
||||
}
|
||||
|
||||
export const skirtingCuts = (plan: SkirtingPlan) =>
|
||||
plan.pieces.filter((piece) => isSkirtingCut(piece, plan));
|
||||
|
||||
export function uncutFlooring(plan: FlooringPlan, settings: FlooringSettings) {
|
||||
const uncut = plan.pieces.filter((piece) => !piece.cut);
|
||||
const wholeBoards = uncut.filter(
|
||||
(piece) => sameLength(piece.length, settings.length) && sameLength(piece.width, settings.width),
|
||||
).length;
|
||||
return { wholeBoards, readyOffcuts: uncut.length - wholeBoards };
|
||||
}
|
||||
|
||||
export function uncutSkirting(plan: SkirtingPlan): { length: number; count: number }[] {
|
||||
const counts = new Map<number, number>();
|
||||
for (const piece of plan.pieces) {
|
||||
if (!isSkirtingCut(piece, plan)) counts.set(piece.length, (counts.get(piece.length) ?? 0) + 1);
|
||||
}
|
||||
return [...counts].sort(([a], [b]) => a - b).map(([length, count]) => ({ length, count }));
|
||||
}
|
||||
|
||||
/** Ready remnants need placement instructions, never another trimming instruction. */
|
||||
export function readyOffcutInstructions(piece: FlooringPiece): string {
|
||||
const ends =
|
||||
piece.factoryLeft && piece.factoryRight
|
||||
? 'both'
|
||||
: piece.factoryLeft
|
||||
? 'left'
|
||||
: piece.factoryRight
|
||||
? 'right'
|
||||
: 'neither';
|
||||
return `Use offcut; no new cut. Required factory short ends: ${ends}.`;
|
||||
}
|
||||
|
||||
/** Batch identical cuts without losing any placement codes or changing factory-edge orientation. */
|
||||
export function groupFlooringCuts(plan: FlooringPlan): FlooringPiece[][] {
|
||||
const groups = new Map<string, FlooringPiece[]>();
|
||||
const precise = (value: number) => Math.round(value * 1000);
|
||||
for (const piece of flooringCuts(plan)) {
|
||||
const key = JSON.stringify([
|
||||
piece.roomId,
|
||||
precise(piece.length),
|
||||
precise(piece.width),
|
||||
piece.shaped,
|
||||
piece.cut,
|
||||
piece.factoryLeft,
|
||||
piece.factoryRight,
|
||||
piece.ripEdge,
|
||||
piece.shaped ? piece.template.map((point) => [precise(point.x), precise(point.y)]) : null,
|
||||
]);
|
||||
const group = groups.get(key);
|
||||
if (group) group.push(piece);
|
||||
else groups.set(key, [piece]);
|
||||
}
|
||||
return [...groups.values()];
|
||||
}
|
||||
60
src/lib/cut-preview.ts
Normal file
60
src/lib/cut-preview.ts
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
import type { FlooringPiece, Point, SkirtingPiece } from './types';
|
||||
|
||||
export interface PreviewBox {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
export const exactMm = (value: number) =>
|
||||
new Intl.NumberFormat('en-GB', { maximumFractionDigits: 3 }).format(value);
|
||||
export const viewBox = (box: PreviewBox) => `${box.x} ${box.y} ${box.width} ${box.height}`;
|
||||
|
||||
export function flooringTemplate(piece: FlooringPiece): Point[] {
|
||||
if (piece.template.length) return piece.template;
|
||||
return piece.shaped
|
||||
? []
|
||||
: [
|
||||
{ x: 0, y: 0 },
|
||||
{ x: piece.length, y: 0 },
|
||||
{ x: piece.length, y: piece.width },
|
||||
{ x: 0, y: piece.width },
|
||||
];
|
||||
}
|
||||
|
||||
export function skirtingTemplate(piece: SkirtingPiece, thickness: number): Point[] {
|
||||
if (piece.template?.length === 4) return piece.template;
|
||||
if (piece.leftMitre !== 0 || piece.rightMitre !== 0) return [];
|
||||
return [
|
||||
{ x: 0, y: 0 },
|
||||
{ x: piece.length, y: 0 },
|
||||
{ x: piece.length, y: thickness },
|
||||
{ x: 0, y: thickness },
|
||||
];
|
||||
}
|
||||
|
||||
/** Padding changes the viewport only; all vertices stay in their original millimetres. */
|
||||
export function fullPreviewBox(length: number, width: number): PreviewBox {
|
||||
const padding = Math.max(length, width, 1) * 0.06;
|
||||
return { x: -padding, y: -padding, width: length + 2 * padding, height: width + 2 * padding };
|
||||
}
|
||||
|
||||
/** Equal square windows enlarge both axes equally; a 45° mitre remains 45°. */
|
||||
export function skirtingEndBoxes(
|
||||
template: Point[],
|
||||
thickness: number,
|
||||
): { left: PreviewBox; right: PreviewBox } {
|
||||
const [backLeft, backRight, frontRight, frontLeft] = template;
|
||||
const side = Math.max(
|
||||
1,
|
||||
thickness * 3,
|
||||
Math.abs(backLeft.x - frontLeft.x) / 0.76,
|
||||
Math.abs(backRight.x - frontRight.x) / 0.76,
|
||||
);
|
||||
const padding = side * 0.12;
|
||||
const common = { y: (thickness - side) / 2, width: side, height: side };
|
||||
return {
|
||||
left: { ...common, x: Math.min(backLeft.x, frontLeft.x) - padding },
|
||||
right: { ...common, x: Math.max(backRight.x, frontRight.x) - side + padding },
|
||||
};
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue