60 lines
1.4 KiB
TypeScript
60 lines
1.4 KiB
TypeScript
export interface ShareLinkControllerOptions {
|
|
input: HTMLInputElement;
|
|
copyControl: HTMLButtonElement;
|
|
copyLabel?: string;
|
|
copiedLabel?: string;
|
|
onCopy?: (link: string) => void | Promise<void>;
|
|
onError?: (error: unknown) => void;
|
|
}
|
|
|
|
export interface ShareLinkController {
|
|
getLink: () => string;
|
|
setLink: (link: string) => void;
|
|
copy: () => Promise<void>;
|
|
destroy: () => void;
|
|
}
|
|
|
|
export function createShareLinkController({
|
|
input,
|
|
copyControl,
|
|
copyLabel = "Скопировать",
|
|
copiedLabel = "Скопировано",
|
|
onCopy,
|
|
onError,
|
|
}: ShareLinkControllerOptions): ShareLinkController {
|
|
input.readOnly = true;
|
|
|
|
const render = (copied = false) => {
|
|
copyControl.disabled = !input.value;
|
|
copyControl.dataset.copied = copied ? "true" : "false";
|
|
copyControl.textContent = copied ? copiedLabel : copyLabel;
|
|
};
|
|
|
|
const copy = async () => {
|
|
const link = input.value;
|
|
if (!link) return;
|
|
try {
|
|
if (onCopy) await onCopy(link);
|
|
else await navigator.clipboard.writeText(link);
|
|
render(true);
|
|
} catch (error) {
|
|
render(false);
|
|
onError?.(error);
|
|
}
|
|
};
|
|
|
|
const handleClick = () => void copy();
|
|
copyControl.addEventListener("click", handleClick);
|
|
render();
|
|
|
|
return {
|
|
getLink: () => input.value,
|
|
setLink: (link) => {
|
|
input.value = link;
|
|
render(false);
|
|
},
|
|
copy,
|
|
destroy: () => copyControl.removeEventListener("click", handleClick),
|
|
};
|
|
}
|