anki/ts/components/ButtonGroupItem.svelte

67 lines
2.3 KiB
Svelte
Raw Normal View History

<!--
Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="typescript">
import WithTheming from "./WithTheming.svelte";
import Detachable from "./Detachable.svelte";
2021-05-06 01:22:55 +02:00
import type { ButtonRegistration } from "./buttons";
import { ButtonPosition } from "./buttons";
import type { Register } from "./registration";
2021-05-06 01:22:55 +02:00
import { getContext, hasContext } from "svelte";
import { buttonGroupKey } from "./context-keys";
export let id: string | undefined = undefined;
2021-05-06 01:22:55 +02:00
export let registration: ButtonRegistration | undefined = undefined;
2021-05-07 14:31:08 +02:00
let detached: boolean;
2021-05-06 01:22:55 +02:00
let position_: ButtonPosition;
let style: string;
const radius = "5px";
2021-05-06 01:22:55 +02:00
2021-09-02 21:01:29 +02:00
const leftStyle = `--border-left-radius: ${radius}; --border-right-radius: 0; `;
const rightStyle = `--border-left-radius: 0; --border-right-radius: ${radius}; `;
2021-05-06 01:22:55 +02:00
$: {
switch (position_) {
case ButtonPosition.Standalone:
style = `--border-left-radius: ${radius}; --border-right-radius: ${radius}; `;
break;
2021-09-02 21:01:29 +02:00
case ButtonPosition.InlineStart:
style = leftStyle;
2021-05-06 01:22:55 +02:00
break;
case ButtonPosition.Center:
style = "--border-left-radius: 0; --border-right-radius: 0; ";
break;
2021-09-02 21:01:29 +02:00
case ButtonPosition.InlineEnd:
style = rightStyle;
2021-05-06 01:22:55 +02:00
break;
}
}
2021-05-06 01:22:55 +02:00
if (registration) {
const { detach, position } = registration;
2021-05-07 14:31:08 +02:00
detach.subscribe((value: boolean) => (detached = value));
2021-05-06 01:22:55 +02:00
position.subscribe((value: ButtonPosition) => (position_ = value));
} else if (hasContext(buttonGroupKey)) {
const registerComponent =
getContext<Register<ButtonRegistration>>(buttonGroupKey);
const { detach, position } = registerComponent();
2021-05-07 14:31:08 +02:00
detach.subscribe((value: boolean) => (detached = value));
2021-05-06 01:22:55 +02:00
position.subscribe((value: ButtonPosition) => (position_ = value));
} else {
2021-05-07 14:31:08 +02:00
detached = false;
2021-05-06 01:22:55 +02:00
position_ = ButtonPosition.Standalone;
}
</script>
2021-05-06 01:22:55 +02:00
<!-- div in WithTheming is necessary to preserve item position -->
<WithTheming {id} {style}>
2021-05-07 14:31:08 +02:00
<Detachable {detached}>
2021-05-06 01:22:55 +02:00
<slot />
</Detachable>
</WithTheming>