|
7 | 7 | */ |
8 | 8 | import { useMemo } from 'react' |
9 | 9 | import { useController, type Control } from 'react-hook-form' |
10 | | -import { useNavigate, type LoaderFunctionArgs } from 'react-router-dom' |
| 10 | +import { useNavigate, useParams, type LoaderFunctionArgs } from 'react-router-dom' |
11 | 11 | import * as R from 'remeda' |
12 | 12 |
|
13 | 13 | import { |
@@ -74,7 +74,17 @@ export const valuesToRuleUpdate = (values: FirewallRuleValues): VpcFirewallRuleU |
74 | 74 | targets: values.targets, |
75 | 75 | }) |
76 | 76 |
|
77 | | -const defaultValues: FirewallRuleValues = { |
| 77 | +/** convert in the opposite direction for when we're creating from existing rule */ |
| 78 | +const ruleToValues = (rule: VpcFirewallRule): FirewallRuleValues => ({ |
| 79 | + ...rule, |
| 80 | + enabled: rule.status === 'enabled', |
| 81 | + protocols: rule.filters.protocols || [], |
| 82 | + ports: rule.filters.ports || [], |
| 83 | + hosts: rule.filters.hosts || [], |
| 84 | +}) |
| 85 | + |
| 86 | +/** Empty form for when we're not creating from an existing rule */ |
| 87 | +const defaultValuesEmpty: FirewallRuleValues = { |
78 | 88 | enabled: true, |
79 | 89 | name: '', |
80 | 90 | description: '', |
@@ -586,6 +596,18 @@ export function CreateFirewallRuleForm() { |
586 | 596 | }) |
587 | 597 | const existingRules = useMemo(() => R.sortBy(data.rules, (r) => r.priority), [data]) |
588 | 598 |
|
| 599 | + // The :rule path param is optional. If it is present, we are creating a |
| 600 | + // rule from an existing one, so we find that rule and copy it into the form |
| 601 | + // values. Note that if we fail to find the rule by name (which should be |
| 602 | + // very unlikely) we just pretend we never saw a name in the path and start |
| 603 | + // from scratch. |
| 604 | + const { rule: ruleName } = useParams() |
| 605 | + const originalRule = existingRules.find((rule) => rule.name === ruleName) |
| 606 | + |
| 607 | + const defaultValues: FirewallRuleValues = originalRule |
| 608 | + ? ruleToValues({ ...originalRule, name: originalRule.name + '-copy' }) |
| 609 | + : defaultValuesEmpty |
| 610 | + |
589 | 611 | const form = useForm({ defaultValues }) |
590 | 612 |
|
591 | 613 | return ( |
|
0 commit comments