| 210 | * nie. |
| 211 | */ |
| 212 | export function slideClear( |
| 213 | box: HintRect, |
| 214 | viewport: { width: number; height: number }, |
| 215 | protect: readonly HintRect[], |
| 216 | margin: number, |
| 217 | ): HintRect | null { |
| 218 | const covers = (candidate: HintRect): number => |
| 219 | protect.reduce((sum, rect) => sum + overlapArea(candidate, rect), 0); |
| 220 | const inside = (candidate: HintRect): boolean => |
| 221 | candidate.x >= margin |
| 222 | && candidate.y >= margin |
| 223 | && candidate.x + candidate.width <= viewport.width - margin |
| 224 | && candidate.y + candidate.height <= viewport.height - margin; |
| 225 | |
| 226 | const tries: HintRect[] = []; |
| 227 | for (const rect of protect) { |
| 228 | if (overlapArea(box, rect) === 0) { |
| 229 | continue; |
| 230 | } |
| 231 | tries.push({ ...box, y: rect.y - box.height - 1 }); |
| 232 | tries.push({ ...box, y: rect.y + rect.height + 1 }); |
| 233 | tries.push({ ...box, x: rect.x - box.width - 1 }); |
| 234 | tries.push({ ...box, x: rect.x + rect.width + 1 }); |
| 235 | } |
| 236 | const moved = (candidate: HintRect): number => |
| 237 | Math.abs(candidate.x - box.x) + Math.abs(candidate.y - box.y); |
| 238 | const free = tries.filter((candidate) => inside(candidate) && covers(candidate) === 0); |
| 239 | if (free.length === 0) { |
| 240 | return null; |
| 241 | } |
| 242 | return free.reduce((best, candidate) => (moved(candidate) < moved(best) ? candidate : best)); |
| 243 | } |
| 244 | |
| 245 | /** |
| 246 | * Wo der Kasten hingehoert. |