@revenuecat/purchases-ui-js
Version:
Web components for Paywalls. Powered by RevenueCat
62 lines (61 loc) • 2 kB
JavaScript
import { getContext, setContext } from "svelte";
import { derived, writable } from "svelte/store";
const key = Symbol("inputChoice");
export function createInputChoiceContext(fieldId, mode, required = false, selectionRange = null, initialSelectedIds = []) {
const selectedOptionIds = writable(new Set(initialSelectedIds));
const isAtMax = derived(selectedOptionIds, (ids) => {
if (selectionRange?.max == null)
return false;
return ids.size >= selectionRange.max;
});
const isSatisfied = derived(selectedOptionIds, (ids) => {
const count = ids.size;
if (!required && selectionRange == null) {
return true;
}
if (required && selectionRange == null) {
return count >= 1;
}
if (required && selectionRange != null) {
if (selectionRange.min === selectionRange.max) {
return count === selectionRange.min;
}
return count >= selectionRange.min && count <= selectionRange.max;
}
return true;
});
// Track isAtMax value for use in selectOption closure
let currentIsAtMax = false;
isAtMax.subscribe((v) => (currentIsAtMax = v));
const selectOption = (optionId) => {
selectedOptionIds.update((current) => {
if (mode === "single") {
return new Set([optionId]);
}
const next = new Set(current);
if (next.has(optionId)) {
next.delete(optionId);
}
else if (!currentIsAtMax) {
next.add(optionId);
}
return next;
});
};
return {
fieldId,
mode,
required,
selectionRange,
selectedOptionIds,
selectOption,
isAtMax,
isSatisfied,
};
}
export function setInputChoiceContext(context) {
setContext(key, context);
}
export function getInputChoiceContext() {
return getContext(key);
}