@rcooler/consent-react 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 RCooLeR
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,29 @@
1
- # Temporary Holding Version
1
+ # @rcooler/consent-react
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Controlled React administration components for consent settings. Install
4
+ `@rcooler/consent-react` with its React, `@rcooler/react-ui`, and
5
+ `@rcooler/react-admin` peer dependencies. See `package.json` for supported
6
+ versions.
7
+
8
+ ```tsx
9
+ import { useState } from "react";
10
+ import { ConsentPreview, ConsentSettingsEditor, validSettings } from "@rcooler/consent-react";
11
+ import type { ConsentSettingsValue } from "@rcooler/consent-react";
12
+ import "@rcooler/consent/consent.css";
13
+
14
+ function Settings({ initial }: { initial: ConsentSettingsValue }) {
15
+ const [value, setValue] = useState(initial);
16
+ return <>
17
+ <ConsentSettingsEditor value={value} onChange={setValue} locale="en" />
18
+ <ConsentPreview value={value} locale="en" />
19
+ <button disabled={!validSettings(value)}>Save</button>
20
+ </>;
21
+ }
22
+ ```
23
+
24
+ Connect the save action to your own authenticated administration endpoint. The
25
+ host owns validation, persistence, conflict handling, and policy version changes.
26
+ `managedServices` allows host-owned declarations to be included in validation
27
+ and preview; provide the same list to the editor, preview, and `validSettings`.
28
+ The preview uses temporary choices and does not activate services. Declaring or
29
+ deleting a service does not install or remove its integration on the site.
@@ -0,0 +1,7 @@
1
+ import type { Service } from "@rcooler/consent";
2
+ import type { ConsentSettingsValue } from "./settings.js";
3
+ export declare function ConsentPreview({ value, locale, managedServices, }: {
4
+ value: ConsentSettingsValue;
5
+ locale?: string;
6
+ managedServices?: readonly Service[];
7
+ }): import("react").JSX.Element;
@@ -0,0 +1,71 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // The real visitor UI with isolated, temporary storage and no activation adapters.
3
+ import { useEffect, useId, useRef, useState } from "react";
4
+ import { createConsent, mountConsent, regionalProfiles, regionalRulesVersion, } from "@rcooler/consent";
5
+ import { previewPolicy, validSettings } from "./settings.js";
6
+ import { settingsTranslator } from "./messages.js";
7
+ function temporaryStorage() {
8
+ const values = new Map();
9
+ return {
10
+ get length() {
11
+ return values.size;
12
+ },
13
+ clear: () => values.clear(),
14
+ getItem: (key) => values.get(key) ?? null,
15
+ key: (index) => [...values.keys()][index] ?? null,
16
+ removeItem: (key) => {
17
+ values.delete(key);
18
+ },
19
+ setItem: (key, value) => {
20
+ values.set(key, value);
21
+ },
22
+ };
23
+ }
24
+ export function ConsentPreview({ value, locale = "en", managedServices = [], }) {
25
+ const container = useRef(null);
26
+ const profileId = useId();
27
+ const countryId = useId();
28
+ const [profile, setProfile] = useState("global-strict");
29
+ const [country, setCountry] = useState("");
30
+ const [gpc, setGpc] = useState(false);
31
+ const t = settingsTranslator(locale);
32
+ const valid = validSettings(value, managedServices);
33
+ useEffect(() => {
34
+ if (!container.current || !valid)
35
+ return;
36
+ const hasCountry = /^[A-Z]{2}$/.test(country);
37
+ const selectedProfile = hasCountry ? profile : "global-strict";
38
+ const controller = createConsent({
39
+ config: {
40
+ enabled: true,
41
+ policy: previewPolicy(value, managedServices),
42
+ allowed_services: [],
43
+ recheck_after_seconds: 3600,
44
+ region: {
45
+ ...(hasCountry ? { country } : {}),
46
+ source: hasCountry ? "host" : "unknown",
47
+ profile_id: selectedProfile,
48
+ applicable_profiles: [
49
+ ...new Set([
50
+ "global-strict",
51
+ selectedProfile,
52
+ ...(value.regional?.applicable_profiles ?? []),
53
+ ]),
54
+ ],
55
+ rules_version: regionalRulesVersion,
56
+ selection_id: "0".repeat(64),
57
+ },
58
+ privacy_signals: { gpc },
59
+ },
60
+ storage: temporaryStorage(),
61
+ privacySignal: () => gpc,
62
+ locale,
63
+ });
64
+ const ui = mountConsent(controller, { container: container.current, locale });
65
+ return () => {
66
+ ui.destroy();
67
+ controller.destroy();
68
+ };
69
+ }, [value, managedServices, locale, valid, profile, country, gpc]);
70
+ return (_jsxs("section", { "aria-label": t("Preview"), children: [_jsx("h2", { children: t("Preview") }), _jsx("p", { children: t("Preview uses temporary choices and never activates services.") }), _jsx("label", { htmlFor: profileId, children: t("Preview profile") }), _jsx("select", { id: profileId, value: profile, onChange: (event) => setProfile(event.target.value), children: regionalProfiles.map((id) => (_jsx("option", { value: id, children: id }, id))) }), _jsx("label", { htmlFor: countryId, children: t("Preview country code") }), _jsx("input", { id: countryId, value: country, maxLength: 2, onChange: (event) => setCountry(event.target.value.toUpperCase().replace(/[^A-Z]/g, "")) }), _jsxs("label", { children: [_jsx("input", { type: "checkbox", checked: gpc, onChange: (event) => setGpc(event.target.checked) }), " ", t("Preview Global Privacy Control")] }), !valid && _jsx("p", { children: t("Preview unavailable until the settings are valid.") }), _jsx("div", { ref: container })] }));
71
+ }
@@ -0,0 +1,12 @@
1
+ import type { Service } from "@rcooler/consent";
2
+ import type { ConsentSettingsValue } from "./settings.js";
3
+ export interface ConsentSettingsEditorProps {
4
+ value: ConsentSettingsValue;
5
+ onChange: (value: ConsentSettingsValue) => void;
6
+ disabled?: boolean;
7
+ locale?: string;
8
+ translate?: (text: string) => string;
9
+ managedServices?: readonly Service[];
10
+ }
11
+ /** Edits declarations only; it never executes the configured services. */
12
+ export declare function ConsentSettingsEditor({ value, onChange, disabled, locale, translate, managedServices, }: ConsentSettingsEditorProps): import("react").JSX.Element;
@@ -0,0 +1,62 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // Controlled administration fields; the host owns saving, authentication and conflicts.
3
+ import { useState } from "react";
4
+ import { FormTable, FormTableRow, Notice } from "@rcooler/react-admin";
5
+ import { ServiceEditor } from "./ServiceEditor.js";
6
+ import { RegionalSettingsEditor } from "./RegionalSettingsEditor.js";
7
+ import { settingsTranslator } from "./messages.js";
8
+ import { validSettings } from "./settings.js";
9
+ /** Edits declarations only; it never executes the configured services. */
10
+ export function ConsentSettingsEditor({ value, onChange, disabled = false, locale = "en", translate, managedServices = [], }) {
11
+ const t = settingsTranslator(locale, translate);
12
+ const [selected, setSelected] = useState(locale);
13
+ const [newLocale, setNewLocale] = useState("");
14
+ const languages = Object.keys(value.notices);
15
+ const language = languages.includes(selected) ? selected : (languages[0] ?? "en");
16
+ const notice = value.notices[language];
17
+ const updateNotice = (key, text) => {
18
+ if (notice)
19
+ onChange({ ...value, notices: { ...value.notices, [language]: { ...notice, [key]: text } } });
20
+ };
21
+ const addLanguage = () => {
22
+ if (!/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/.test(newLocale) ||
23
+ value.notices[newLocale] ||
24
+ languages.length >= 20)
25
+ return;
26
+ onChange({
27
+ ...value,
28
+ notices: { ...value.notices, [newLocale]: { title: "", description: "", privacy_url: "/" } },
29
+ });
30
+ setSelected(newLocale);
31
+ setNewLocale("");
32
+ };
33
+ return (_jsxs("div", { lang: locale, children: [_jsx("p", { children: t("Changing purposes, services or notice text requires visitors to choose again.") }), _jsxs(FormTable, { children: [_jsx(FormTableRow, { label: t("Enable consent controls"), children: (control) => (_jsx("input", { ...control, type: "checkbox", checked: value.enabled, disabled: disabled, onChange: (event) => onChange({ ...value, enabled: event.target.checked }) })) }), _jsx(FormTableRow, { label: t("Choice lifetime (days)"), children: (control) => (_jsx("input", { ...control, className: "form-control", type: "number", min: 1, max: 3650, required: true, value: value.choice_ttl_days, disabled: disabled, onChange: (event) => onChange({ ...value, choice_ttl_days: Number(event.target.value) }) })) }), _jsx(FormTableRow, { label: t("Receipt retention (days)"), children: (control) => (_jsx("input", { ...control, className: "form-control", type: "number", min: 1, max: 3650, required: true, value: value.receipt_retention_days, disabled: disabled, onChange: (event) => onChange({ ...value, receipt_retention_days: Number(event.target.value) }) })) }), _jsx(FormTableRow, { label: t("Notice language"), children: (control) => (_jsx("select", { ...control, className: "form-select", value: language, disabled: disabled, onChange: (event) => setSelected(event.target.value), children: languages.map((tag) => (_jsx("option", { value: tag, children: tag }, tag))) })) }), notice && (_jsxs(_Fragment, { children: [_jsx(FormTableRow, { label: t("Notice title"), children: (control) => (_jsx("input", { ...control, className: "form-control", lang: language, maxLength: 120, required: true, value: notice.title, disabled: disabled, onChange: (event) => updateNotice("title", event.target.value) })) }), _jsx(FormTableRow, { label: t("Notice text"), children: (control) => (_jsx("textarea", { ...control, className: "form-control", lang: language, maxLength: 4000, rows: 4, required: true, value: notice.description, disabled: disabled, onChange: (event) => updateNotice("description", event.target.value) })) }), _jsx(FormTableRow, { label: t("Privacy policy URL"), children: (control) => (_jsx("input", { ...control, className: "form-control", maxLength: 2048, required: true, value: notice.privacy_url, disabled: disabled, onChange: (event) => updateNotice("privacy_url", event.target.value) })) })] })), _jsx(FormTableRow, { label: t("Language tag"), children: (control) => (_jsxs("span", { children: [_jsx("input", { ...control, className: "form-control", value: newLocale, maxLength: 64, disabled: disabled, onChange: (event) => setNewLocale(event.target.value) }), _jsx("button", { type: "button", className: "rc-button", disabled: disabled ||
34
+ !/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/.test(newLocale) ||
35
+ Boolean(value.notices[newLocale]) ||
36
+ languages.length >= 20, onClick: addLanguage, children: t("Add language") })] })) })] }), _jsx("button", { type: "button", className: "rc-button", disabled: disabled || languages.length < 2, onClick: () => {
37
+ const notices = { ...value.notices };
38
+ delete notices[language];
39
+ onChange({ ...value, notices });
40
+ }, children: t("Remove language") }), _jsx(RegionalSettingsEditor, { value: value, onChange: onChange, locale: locale, disabled: disabled, t: t }), _jsx("h2", { children: t("Services") }), _jsx("p", { children: t("Adding a declaration does not load a service. Connect it through the site's consent integration.") }), _jsx("p", { children: t("Deleting a declaration does not remove scripts already installed in your site. Remove or disable its integration too.") }), value.services.length === 0 && _jsx("p", { children: t("No optional services have been declared.") }), value.services.map((service, index) => (_jsx(ServiceEditor, { service: service, disabled: disabled, t: t, onChange: (next) => onChange({
41
+ ...value,
42
+ services: value.services.map((entry, position) => position === index ? next : entry),
43
+ }), onRemove: () => onChange({
44
+ ...value,
45
+ services: value.services.filter((_, position) => position !== index),
46
+ }) }, index))), _jsx("button", { type: "button", className: "rc-button", disabled: disabled || value.services.length + managedServices.length >= 64, onClick: () => onChange({
47
+ ...value,
48
+ services: [
49
+ ...value.services,
50
+ {
51
+ id: "",
52
+ name: "",
53
+ description: "",
54
+ provider: "",
55
+ category: "preferences",
56
+ kind: "iframe",
57
+ policy_url: "/",
58
+ storage: [],
59
+ },
60
+ ],
61
+ }), children: t("Add service") }), managedServices.length > 0 && (_jsxs("section", { children: [_jsx("h2", { children: t("Services managed by this application") }), _jsx("ul", { children: managedServices.map((service) => (_jsxs("li", { children: [service.name, " \u2014 ", service.description] }, service.id))) })] })), !validSettings(value, managedServices) && (_jsx(Notice, { tone: "warning", children: t("Complete every service and notice before saving. Use unique service IDs and valid HTTPS URLs or local policy paths.") }))] }));
62
+ }
@@ -0,0 +1,10 @@
1
+ import type { ConsentSettingsValue } from "./settings.js";
2
+ interface Props {
3
+ value: ConsentSettingsValue;
4
+ onChange: (value: ConsentSettingsValue) => void;
5
+ locale: string;
6
+ disabled: boolean;
7
+ t: (text: string) => string;
8
+ }
9
+ export declare function RegionalSettingsEditor({ value, onChange, locale, disabled, t }: Props): import("react").JSX.Element;
10
+ export {};
@@ -0,0 +1,50 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useState } from "react";
3
+ import { FormTable, FormTableRow } from "@rcooler/react-admin";
4
+ import { regionalProfiles, regionalRulesVersion } from "@rcooler/consent";
5
+ export function RegionalSettingsEditor({ value, onChange, locale, disabled, t }) {
6
+ const [profile, setProfile] = useState("global-strict");
7
+ const [selected, setSelected] = useState(locale);
8
+ const regional = value.regional ?? {
9
+ rules_version: regionalRulesVersion,
10
+ applicable_profiles: [],
11
+ };
12
+ const languages = Object.keys(value.notices);
13
+ const language = languages.includes(selected) ? selected : (languages[0] ?? "en");
14
+ const notice = regional.notices?.[profile]?.[language];
15
+ const rights = regional.rights?.[language] ?? {};
16
+ const update = (next) => onChange({ ...value, regional: next });
17
+ const setNotice = (next) => {
18
+ const notices = { ...regional.notices };
19
+ const localized = { ...notices[profile] };
20
+ if (next)
21
+ localized[language] = next;
22
+ else
23
+ delete localized[language];
24
+ if (Object.keys(localized).length)
25
+ notices[profile] = localized;
26
+ else
27
+ delete notices[profile];
28
+ update({ ...regional, notices });
29
+ };
30
+ const setRight = (key, text) => {
31
+ const all = { ...regional.rights };
32
+ const links = { ...all[language] };
33
+ if (text)
34
+ links[key] = text;
35
+ else
36
+ delete links[key];
37
+ if (Object.keys(links).length)
38
+ all[language] = links;
39
+ else
40
+ delete all[language];
41
+ update({ ...regional, rights: all });
42
+ };
43
+ return (_jsxs("fieldset", { disabled: disabled, children: [_jsx("legend", { children: t("Regional settings") }), _jsx("p", { children: t("Location is a hint and does not determine which laws apply.") }), _jsx("p", { children: t("Your host provides the location. If unavailable, the strict global profile applies.") }), _jsxs(FormTable, { children: [_jsx(FormTableRow, { label: t("Region profile"), children: (control) => (_jsx("select", { ...control, className: "form-select", value: profile, onChange: (event) => setProfile(event.target.value), children: regionalProfiles.map((id) => (_jsx("option", { value: id, children: id }, id))) })) }), _jsx(FormTableRow, { label: t("Additional applicable profile"), children: (control) => (_jsx("input", { ...control, type: "checkbox", checked: regional.applicable_profiles.includes(profile), disabled: !regional.applicable_profiles.includes(profile) &&
44
+ regional.applicable_profiles.length >= 32, onChange: (event) => update({
45
+ ...regional,
46
+ applicable_profiles: event.target.checked
47
+ ? [...regional.applicable_profiles, profile]
48
+ : regional.applicable_profiles.filter((id) => id !== profile),
49
+ }) })) }), _jsx(FormTableRow, { label: t("Regional language"), children: (control) => (_jsx("select", { ...control, className: "form-select", value: language, onChange: (event) => setSelected(event.target.value), children: languages.map((tag) => (_jsx("option", { value: tag, children: tag }, tag))) })) })] }), _jsx("p", { children: t("Regional notices supplement the main notice.") }), !notice && (_jsx("button", { type: "button", className: "rc-button", disabled: Object.keys(regional.notices ?? {}).length >= 32 && !regional.notices?.[profile], onClick: () => setNotice({ ...value.notices[language] }), children: t("Add regional notice") })), notice && (_jsxs(_Fragment, { children: [_jsxs(FormTable, { children: [_jsx(FormTableRow, { label: t("Regional notice title"), children: (control) => (_jsx("input", { ...control, className: "form-control", required: true, maxLength: 120, value: notice.title, onChange: (event) => setNotice({ ...notice, title: event.target.value }) })) }), _jsx(FormTableRow, { label: t("Regional notice text"), children: (control) => (_jsx("textarea", { ...control, className: "form-control", required: true, maxLength: 4000, value: notice.description, onChange: (event) => setNotice({ ...notice, description: event.target.value }) })) }), _jsx(FormTableRow, { label: t("Regional privacy policy URL"), children: (control) => (_jsx("input", { ...control, className: "form-control", required: true, maxLength: 2048, value: notice.privacy_url, onChange: (event) => setNotice({ ...notice, privacy_url: event.target.value }) })) })] }), _jsx("button", { type: "button", className: "rc-button", onClick: () => setNotice(undefined), children: t("Remove regional notice") })] })), _jsxs(FormTable, { children: [_jsx(FormTableRow, { label: t("Privacy rights request URL"), children: (control) => (_jsx("input", { ...control, className: "form-control", maxLength: 2048, value: rights.request_url ?? "", onChange: (event) => setRight("request_url", event.target.value) })) }), _jsx(FormTableRow, { label: t("Privacy rights appeal URL"), children: (control) => (_jsx("input", { ...control, className: "form-control", maxLength: 2048, value: rights.appeal_url ?? "", onChange: (event) => setRight("appeal_url", event.target.value) })) })] })] }));
50
+ }
@@ -0,0 +1,10 @@
1
+ import type { Service } from "@rcooler/consent";
2
+ interface Props {
3
+ service: Service;
4
+ onChange: (service: Service) => void;
5
+ onRemove: () => void;
6
+ disabled: boolean;
7
+ t: (text: string) => string;
8
+ }
9
+ export declare function ServiceEditor({ service, onChange, onRemove, disabled, t }: Props): import("react").JSX.Element;
10
+ export {};
@@ -0,0 +1,39 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // Declarative service editing; this component never loads a provider resource.
3
+ import { FormTable, FormTableRow } from "@rcooler/react-admin";
4
+ import { noRestrictions } from "@rcooler/consent";
5
+ export function ServiceEditor({ service, onChange, onRemove, disabled, t }) {
6
+ const field = (key, label, maxLength) => (_jsx(FormTableRow, { label: t(label), children: (control) => (_jsx("input", { ...control, className: "form-control", value: service[key] ?? "", maxLength: maxLength, onChange: (event) => onChange({ ...service, [key]: event.target.value }), disabled: disabled, required: key !== "destination" })) }));
7
+ const updateStorage = (index, value) => onChange({
8
+ ...service,
9
+ storage: service.storage.map((entry, position) => (position === index ? value : entry)),
10
+ });
11
+ return (_jsxs("fieldset", { disabled: disabled, className: "rc-card", children: [_jsx("legend", { children: service.name || t("Service name") }), _jsxs(FormTable, { children: [field("id", "Service ID", 63), field("name", "Service name", 120), field("description", "Purpose", 4000), field("provider", "Provider", 200), _jsx(FormTableRow, { label: t("Category"), children: (control) => (_jsxs("select", { ...control, className: "form-select", value: service.category, onChange: (event) => onChange({ ...service, category: event.target.value }), children: [_jsx("option", { value: "necessary", children: t("Necessary") }), _jsx("option", { value: "preferences", children: t("Preferences") }), _jsx("option", { value: "analytics", children: t("Analytics") }), _jsx("option", { value: "marketing", children: t("Marketing") })] })) }), _jsx(FormTableRow, { label: t("Integration"), children: (control) => (_jsxs("select", { ...control, className: "form-select", value: service.kind, onChange: (event) => onChange({ ...service, kind: event.target.value }), children: [_jsx("option", { value: "iframe", children: t("Embedded content") }), _jsx("option", { value: "script", children: t("Script") }), _jsx("option", { value: "custom", children: t("Application integration") })] })) }), field("destination", "Destination URL", 2048), field("policy_url", "Provider policy URL", 2048)] }), _jsxs("fieldset", { children: [_jsx("legend", { children: t("Data uses") }), _jsx("p", { children: t("Unknown data uses are blocked when privacy restrictions apply.") }), _jsxs("label", { children: [_jsx("input", { type: "checkbox", checked: service.processing !== undefined, onChange: (event) => {
12
+ if (event.target.checked)
13
+ onChange({ ...service, processing: noRestrictions() });
14
+ else {
15
+ const { processing: _processing, ...rest } = service;
16
+ onChange(rest);
17
+ }
18
+ } }), " ", t("Data uses reviewed")] }), service.processing &&
19
+ [
20
+ ["sale", "Sale of personal information"],
21
+ ["sharing", "Sharing"],
22
+ ["targeted_advertising", "Targeted advertising"],
23
+ ["sensitive_data", "Sensitive data"],
24
+ ].map(([key, label]) => (_jsxs("label", { children: [_jsx("input", { type: "checkbox", checked: service.processing?.[key] ?? false, onChange: (event) => {
25
+ if (service.processing)
26
+ onChange({
27
+ ...service,
28
+ processing: { ...service.processing, [key]: event.target.checked },
29
+ });
30
+ } }), " ", t(label)] }, key)))] }), _jsxs("fieldset", { children: [_jsx("legend", { children: t("Browser storage") }), service.storage.map((entry, index) => (_jsxs("div", { children: [_jsxs(FormTable, { children: [_jsx(FormTableRow, { label: t("Storage name"), children: (control) => (_jsx("input", { ...control, className: "form-control", value: entry.name, maxLength: 128, required: true, onChange: (event) => updateStorage(index, { ...entry, name: event.target.value }) })) }), _jsx(FormTableRow, { label: t("Storage type"), children: (control) => (_jsxs("select", { ...control, className: "form-select", value: entry.type, onChange: (event) => updateStorage(index, event.target.value === "localStorage"
31
+ ? { name: entry.name, type: "localStorage" }
32
+ : { name: entry.name, type: "cookie", path: "/" }), children: [_jsx("option", { value: "cookie", children: "Cookie" }), _jsx("option", { value: "localStorage", children: "localStorage" })] })) }), entry.type === "cookie" && (_jsxs(_Fragment, { children: [_jsx(FormTableRow, { label: t("Cookie domain"), children: (control) => (_jsx("input", { ...control, className: "form-control", value: entry.domain ?? "", maxLength: 253, onChange: (event) => updateStorage(index, { ...entry, domain: event.target.value }) })) }), _jsx(FormTableRow, { label: t("Cookie path"), children: (control) => (_jsx("input", { ...control, className: "form-control", value: entry.path ?? "/", maxLength: 512, onChange: (event) => updateStorage(index, { ...entry, path: event.target.value }) })) })] }))] }), _jsx("button", { type: "button", className: "rc-button", onClick: () => onChange({
33
+ ...service,
34
+ storage: service.storage.filter((_, position) => position !== index),
35
+ }), children: t("Remove storage item") })] }, index))), _jsx("button", { type: "button", className: "rc-button", disabled: service.storage.length >= 32, onClick: () => onChange({
36
+ ...service,
37
+ storage: [...service.storage, { name: "", type: "cookie", path: "/" }],
38
+ }), children: t("Add storage item") })] }), _jsx("button", { type: "button", className: "rc-button", onClick: onRemove, children: t("Remove service") })] }));
39
+ }
@@ -0,0 +1,5 @@
1
+ export { ConsentSettingsEditor } from "./ConsentSettingsEditor.js";
2
+ export type { ConsentSettingsEditorProps } from "./ConsentSettingsEditor.js";
3
+ export { ConsentPreview } from "./ConsentPreview.js";
4
+ export { validSettings, previewPolicy } from "./settings.js";
5
+ export type { ConsentSettingsValue } from "./settings.js";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { ConsentSettingsEditor } from "./ConsentSettingsEditor.js";
2
+ export { ConsentPreview } from "./ConsentPreview.js";
3
+ export { validSettings, previewPolicy } from "./settings.js";
@@ -0,0 +1,2 @@
1
+ /** Hosts may supply their own catalog; built-in text falls back to English. */
2
+ export declare function settingsTranslator(locale: string, translate?: (text: string) => string): (text: string) => string;
@@ -0,0 +1,75 @@
1
+ // English source messages and the built-in Ukrainian administration catalog.
2
+ const ukrainian = {
3
+ "Enable consent controls": "Увімкнути керування згодою",
4
+ "Choice lifetime (days)": "Строк дії вибору (днів)",
5
+ "Receipt retention (days)": "Зберігання записів згоди (днів)",
6
+ "Notice language": "Мова повідомлення",
7
+ "Notice title": "Заголовок повідомлення",
8
+ "Notice text": "Текст повідомлення",
9
+ "Privacy policy URL": "Адреса політики конфіденційності",
10
+ "Add language": "Додати мову",
11
+ "Language tag": "Код мови",
12
+ "Remove language": "Видалити мову",
13
+ Services: "Сервіси",
14
+ "Add service": "Додати сервіс",
15
+ "Remove service": "Видалити сервіс",
16
+ "Service ID": "Ідентифікатор сервісу",
17
+ "Service name": "Назва сервісу",
18
+ Purpose: "Мета",
19
+ Provider: "Постачальник",
20
+ Category: "Категорія",
21
+ Integration: "Інтеграція",
22
+ "Destination URL": "Адреса призначення",
23
+ "Provider policy URL": "Політика постачальника",
24
+ Necessary: "Необхідні",
25
+ Preferences: "Налаштування",
26
+ Analytics: "Аналітика",
27
+ Marketing: "Маркетинг",
28
+ "Embedded content": "Вбудований вміст",
29
+ Script: "Скрипт",
30
+ "Application integration": "Інтеграція застосунку",
31
+ "Browser storage": "Сховище браузера",
32
+ "Add storage item": "Додати елемент сховища",
33
+ "Remove storage item": "Видалити елемент сховища",
34
+ "Storage name": "Назва елемента сховища",
35
+ "Storage type": "Тип сховища",
36
+ "Cookie domain": "Домен cookie",
37
+ "Cookie path": "Шлях cookie",
38
+ "No optional services have been declared.": "Необов’язкові сервіси ще не оголошено.",
39
+ "Services managed by this application": "Сервіси, якими керує застосунок",
40
+ "Complete every service and notice before saving. Use unique service IDs and valid HTTPS URLs or local policy paths.": "Заповніть усі сервіси та повідомлення перед збереженням. Використовуйте унікальні ідентифікатори й коректні HTTPS-адреси або локальні шляхи політик.",
41
+ "Adding a declaration does not load a service. Connect it through the site's consent integration.": "Оголошення не завантажує сервіс. Підключіть його через інтеграцію згоди на сайті.",
42
+ "Changing purposes, services or notice text requires visitors to choose again.": "Після зміни цілей, сервісів або тексту повідомлення відвідувачі мають зробити вибір знову.",
43
+ "Deleting a declaration does not remove scripts already installed in your site. Remove or disable its integration too.": "Видалення оголошення не прибирає вже встановлені скрипти. Також видаліть або вимкніть відповідну інтеграцію.",
44
+ Preview: "Попередній перегляд",
45
+ "Preview uses temporary choices and never activates services.": "Попередній перегляд використовує тимчасовий вибір і не запускає сервіси.",
46
+ "Preview unavailable until the settings are valid.": "Попередній перегляд стане доступним після виправлення налаштувань.",
47
+ "Regional settings": "Регіональні налаштування",
48
+ "Location is a hint and does not determine which laws apply.": "Місцезнаходження є орієнтиром і не визначає застосовне законодавство.",
49
+ "Your host provides the location. If unavailable, the strict global profile applies.": "Місцезнаходження надає сайт. Якщо воно недоступне, застосовується суворий глобальний профіль.",
50
+ "Region profile": "Регіональний профіль",
51
+ "Additional applicable profile": "Додатковий застосовний профіль",
52
+ "Regional language": "Мова регіонального повідомлення",
53
+ "Regional notices supplement the main notice.": "Регіональні повідомлення доповнюють основне повідомлення.",
54
+ "Add regional notice": "Додати регіональне повідомлення",
55
+ "Remove regional notice": "Видалити регіональне повідомлення",
56
+ "Regional notice title": "Заголовок регіонального повідомлення",
57
+ "Regional notice text": "Текст регіонального повідомлення",
58
+ "Regional privacy policy URL": "Адреса регіональної політики конфіденційності",
59
+ "Privacy rights request URL": "Адреса запиту щодо прав на конфіденційність",
60
+ "Privacy rights appeal URL": "Адреса оскарження запиту",
61
+ "Data uses": "Використання даних",
62
+ "Unknown data uses are blocked when privacy restrictions apply.": "Невідоме використання даних блокується, коли діють обмеження конфіденційності.",
63
+ "Data uses reviewed": "Використання даних перевірено",
64
+ "Sale of personal information": "Продаж персональних даних",
65
+ Sharing: "Передача даних",
66
+ "Targeted advertising": "Таргетована реклама",
67
+ "Sensitive data": "Чутливі дані",
68
+ "Preview profile": "Профіль попереднього перегляду",
69
+ "Preview country code": "Код країни для перегляду",
70
+ "Preview Global Privacy Control": "Імітувати Global Privacy Control",
71
+ };
72
+ /** Hosts may supply their own catalog; built-in text falls back to English. */
73
+ export function settingsTranslator(locale, translate) {
74
+ return (text) => translate?.(text) ?? (locale.startsWith("uk") ? ukrainian[text] : undefined) ?? text;
75
+ }
@@ -0,0 +1,12 @@
1
+ import type { Notice, Policy, RegionalPolicy, Service } from "@rcooler/consent";
2
+ export interface ConsentSettingsValue {
3
+ enabled: boolean;
4
+ notices: Record<string, Notice>;
5
+ choice_ttl_days: number;
6
+ receipt_retention_days: number;
7
+ services: Service[];
8
+ regional?: RegionalPolicy;
9
+ }
10
+ /** Produces an isolated preview policy, with no service activation permissions. */
11
+ export declare function previewPolicy(value: ConsentSettingsValue, managedServices?: readonly Service[]): Policy;
12
+ export declare function validSettings(value: ConsentSettingsValue, managedServices?: readonly Service[]): boolean;
@@ -0,0 +1,19 @@
1
+ // Editable settings shared by administration hosts, independent of HTTP/auth.
2
+ import { validatePolicy } from "@rcooler/consent";
3
+ /** Produces an isolated preview policy, with no service activation permissions. */
4
+ export function previewPolicy(value, managedServices = []) {
5
+ return {
6
+ schema_version: 1,
7
+ site: "preview",
8
+ epoch: "preview",
9
+ version: 1,
10
+ expires_after_days: value.choice_ttl_days,
11
+ retention_days: value.receipt_retention_days,
12
+ notices: value.notices,
13
+ services: [...value.services, ...managedServices],
14
+ ...(value.regional ? { regional: value.regional } : {}),
15
+ };
16
+ }
17
+ export function validSettings(value, managedServices = []) {
18
+ return (typeof value.enabled === "boolean" && validatePolicy(previewPolicy(value, managedServices)));
19
+ }
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@rcooler/consent-react",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Consent administration controls for React hosts.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "exports": {
9
+ ".": {
10
+ "@rcooler/source": "./src/index.ts",
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "LICENSE"
18
+ ],
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/RCooLeR/consent.git",
22
+ "directory": "web/packages/consent-react"
23
+ },
24
+ "publishConfig": {
25
+ "access": "public",
26
+ "registry": "https://registry.npmjs.org"
27
+ },
28
+ "dependencies": {
29
+ "@rcooler/consent": "0.1.0"
30
+ },
31
+ "peerDependencies": {
32
+ "react": "^19.3.1",
33
+ "@rcooler/react-ui": "^0.3.0 || ^0.4.0",
34
+ "@rcooler/react-admin": "^0.3.0 || ^0.4.0"
35
+ },
36
+ "scripts": {
37
+ "build": "node ../../node_modules/@typescript/native/bin/tsc -p tsconfig.build.json",
38
+ "typecheck": "node ../../node_modules/@typescript/native/bin/tsc --noEmit -p tsconfig.json"
39
+ }
40
+ }