techne-sdk 0.13.0 → 0.14.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.
@@ -0,0 +1,34 @@
1
+ /**
2
+ * techne-sdk/react/sign-in — the Techne sign-in form and the "Sign in with Techne" button as React components:
3
+ * `techne-sdk/sign-in`'s {@link mountSignIn} and {@link mountSignInButton} in a `<div>` of their own.
4
+ *
5
+ * ```tsx
6
+ * <SignInForm clientId="https://cafes.example/oauth-client-metadata.json" appName="Cafés" logo="/logo.png" />
7
+ * <SignInButton clientId={clientId} theme="light" size="small" />
8
+ * ```
9
+ *
10
+ * Its own subpath, so `techne-sdk/react` still loads no OAuth client. The form mounts again when an option
11
+ * changes; `onError` and `onClick` are read when called, so a new function each render does not remount it.
12
+ */
13
+ import { type CSSProperties } from 'react';
14
+ import { type SignInButtonOptions, type SignInFormOptions } from '../sign-in/index.js';
15
+ /** The `<div>` the form or the button is mounted in. */
16
+ interface Box {
17
+ className?: string;
18
+ style?: CSSProperties;
19
+ }
20
+ export type SignInFormProps = SignInFormOptions & Box;
21
+ export type SignInButtonProps = SignInButtonOptions & Box;
22
+ /** The sign-in form (`techne-sdk/sign-in`'s `mountSignIn`). */
23
+ export declare function SignInForm(props: SignInFormProps): import("react").DetailedReactHTMLElement<{
24
+ ref: import("react").RefObject<HTMLDivElement | null>;
25
+ className: string | undefined;
26
+ style: CSSProperties | undefined;
27
+ }, HTMLDivElement>;
28
+ /** The "Sign in with Techne" button (`techne-sdk/sign-in`'s `mountSignInButton`). */
29
+ export declare function SignInButton(props: SignInButtonProps): import("react").DetailedReactHTMLElement<{
30
+ ref: import("react").RefObject<HTMLDivElement | null>;
31
+ className: string | undefined;
32
+ style: CSSProperties | undefined;
33
+ }, HTMLDivElement>;
34
+ export {};
@@ -0,0 +1,52 @@
1
+ /**
2
+ * techne-sdk/react/sign-in — the Techne sign-in form and the "Sign in with Techne" button as React components:
3
+ * `techne-sdk/sign-in`'s {@link mountSignIn} and {@link mountSignInButton} in a `<div>` of their own.
4
+ *
5
+ * ```tsx
6
+ * <SignInForm clientId="https://cafes.example/oauth-client-metadata.json" appName="Cafés" logo="/logo.png" />
7
+ * <SignInButton clientId={clientId} theme="light" size="small" />
8
+ * ```
9
+ *
10
+ * Its own subpath, so `techne-sdk/react` still loads no OAuth client. The form mounts again when an option
11
+ * changes; `onError` and `onClick` are read when called, so a new function each render does not remount it.
12
+ */
13
+ import { createElement, useEffect, useLayoutEffect, useRef } from 'react';
14
+ import { mountSignIn, mountSignInButton } from '../sign-in/index.js';
15
+ /** Mount with `mount` in a div, again when the options (but the callbacks) change. `callbacks` and `mount` are
16
+ * module constants; the options are rebuilt from `key`, so the effect's dependencies are complete. */
17
+ function useMounted(props, callbacks, mount) {
18
+ const ref = useRef(null);
19
+ const latest = useRef(props);
20
+ useLayoutEffect(() => {
21
+ latest.current = props;
22
+ });
23
+ const { className, style, ...rest } = props;
24
+ const options = { ...rest };
25
+ for (const k of callbacks)
26
+ delete options[k];
27
+ // Whether each callback is given changes what the mount does (a button with onClick starts no sign-in).
28
+ const key = JSON.stringify([options, callbacks.map((k) => props[k] !== undefined)]);
29
+ useEffect(() => {
30
+ const el = ref.current;
31
+ if (!el)
32
+ return;
33
+ const [o, given] = JSON.parse(key);
34
+ callbacks.forEach((k, i) => {
35
+ if (given[i])
36
+ o[k] = (...args) => latest.current[k]?.(...args);
37
+ });
38
+ const m = mount(el, o);
39
+ return () => m.unmount();
40
+ }, [key, callbacks, mount]);
41
+ return createElement('div', { ref, className, style });
42
+ }
43
+ const FORM_CALLBACKS = ['onError'];
44
+ const BUTTON_CALLBACKS = ['onError', 'onClick'];
45
+ /** The sign-in form (`techne-sdk/sign-in`'s `mountSignIn`). */
46
+ export function SignInForm(props) {
47
+ return useMounted(props, FORM_CALLBACKS, mountSignIn);
48
+ }
49
+ /** The "Sign in with Techne" button (`techne-sdk/sign-in`'s `mountSignInButton`). */
50
+ export function SignInButton(props) {
51
+ return useMounted(props, BUTTON_CALLBACKS, mountSignInButton);
52
+ }
@@ -0,0 +1,33 @@
1
+ import { type SignInOptions } from '../auth/index.js';
2
+ /** What a sign-in from the form or the button carries: everything {@link signIn} takes but who is signing in. */
3
+ export type SignInFormClient = Omit<SignInOptions, 'handle' | 'email' | 'phone' | 'otherWays' | 'signUp'>;
4
+ /** What {@link mountSignIn} takes. */
5
+ export interface SignInFormOptions extends SignInFormClient {
6
+ /** The app's name, shown beside its logo and in the line under "Sign in". */
7
+ appName: string;
8
+ /** The app's logo: an image URL (a square, shown 44 px with rounded corners). None: the name alone. */
9
+ logo?: string;
10
+ /** Called when a sign-in could not start (the PDS could not be reached, say); the form also says so. */
11
+ onError?: (error: unknown) => void;
12
+ }
13
+ /** What {@link mountSignInButton} takes. */
14
+ export interface SignInButtonOptions extends SignInFormClient {
15
+ /** `dark`: black, for light backgrounds (the default). `light`: white with a black edge, for dark ones. */
16
+ theme?: 'dark' | 'light';
17
+ /** `medium`: 44 px tall (the default). `small`: 36 px, for a navigation bar. */
18
+ size?: 'medium' | 'small';
19
+ /** Called instead of {@link signIn} on a click (to show the form, say). */
20
+ onClick?: () => void;
21
+ /** Called when the sign-in could not start. */
22
+ onError?: (error: unknown) => void;
23
+ }
24
+ /** A mounted form or button. */
25
+ export interface Mounted {
26
+ /** Remove it from the page. */
27
+ unmount(): void;
28
+ }
29
+ /** Mount the sign-in form in `target` (appended to it). See the module doc for what it shows and does. */
30
+ export declare function mountSignIn(target: Element, options: SignInFormOptions): Mounted;
31
+ /** Mount the "Sign in with Techne" button in `target` (appended to it). A click starts {@link signIn} with no
32
+ * handle (the Techne sign-in page's first step), or calls `onClick` instead. */
33
+ export declare function mountSignInButton(target: Element, options: SignInButtonOptions): Mounted;
@@ -0,0 +1,483 @@
1
+ /**
2
+ * techne-sdk/sign-in — the Techne sign-in form and the "Sign in with Techne" button, for any web page, with
3
+ * no framework (`techne-sdk/react/sign-in` wraps both for React).
4
+ *
5
+ * ```ts
6
+ * import { mountSignIn } from 'techne-sdk/sign-in'
7
+ * mountSignIn(document.getElementById('sign-in'), {
8
+ * clientId: 'https://cafes.example/oauth-client-metadata.json',
9
+ * appName: 'Cafés',
10
+ * logo: '/logo.png',
11
+ * })
12
+ * ```
13
+ *
14
+ * The form is one card, one look for every app: the app's logo and name, "Sign in", a short line saying the
15
+ * app uses a Techne account, Email and Phone tabs (the phone with a country list that opens inside the card),
16
+ * "Send me a code", a line of fine print, a quiet "Other ways to sign in" and "Powered by Techne". "Send me a
17
+ * code" starts {@link signIn} with the address or number typed, so the Techne sign-in page opens on the
18
+ * code step, the code already sent; "Other ways to sign in" starts it with `otherWays`, the sign-in page's
19
+ * first step with passkey, Nostr key and a handle on another server open. After the code the person comes
20
+ * back to the app's redirect URI, where `restore` answers the session, as for any sign-in. The card keeps
21
+ * one size in every view (tab, country list) at a given width: 420 px wide at most, as wide as its container below that.
22
+ *
23
+ * Each form and button lives in a shadow root on an element of its own, appended to the target: its styles
24
+ * do not leak out and the page's do not reach in. The two brand fonts load from the home PDS.
25
+ */
26
+ import { getCountries, getCountryCallingCode, parsePhoneNumberFromString } from 'libphonenumber-js/min';
27
+ import { signIn, TECHNE_TOWN_PDS } from '../auth/index.js';
28
+ import { isEmailAddress, isNavigatedBack } from '../auth/hints.js';
29
+ import { BUTTON_CSS, FORM_CSS, fontFaces } from './styles.js';
30
+ /** The fine print under the button, per tab. */
31
+ const FINE = { email: 'We email you a code. No password.', phone: 'We text you a code. No password.' };
32
+ /** Where the form keeps the country last picked on this browser. */
33
+ const COUNTRY_STORAGE_KEY = 'techne-sdk:phone-country';
34
+ /** The country the list starts on when the browser's languages name none. */
35
+ const FALLBACK_COUNTRY = 'US';
36
+ const FORM_HTML = `
37
+ <div class="root card" part="card">
38
+ <div class="app"><img alt="" hidden><span class="name"></span></div>
39
+ <div class="views">
40
+ <div class="view main">
41
+ <h1>Sign in</h1>
42
+ <p class="lede"></p>
43
+ <form novalidate>
44
+ <div class="seg" role="tablist" aria-label="Sign in with">
45
+ <button type="button" role="tab" class="tab" id="tab-email" aria-controls="field-email" aria-selected="true">Email</button>
46
+ <button type="button" role="tab" class="tab" id="tab-phone" aria-controls="field-phone" aria-selected="false" tabindex="-1">Phone</button>
47
+ </div>
48
+ <div class="fields">
49
+ <div class="field" id="field-email" role="tabpanel" aria-labelledby="tab-email">
50
+ <label for="email">Email</label>
51
+ <input type="email" id="email" name="email" autocomplete="email" autocapitalize="none" autocorrect="off" spellcheck="false" placeholder="you@example.com" aria-describedby="fine">
52
+ </div>
53
+ <div class="field off" id="field-phone" role="tabpanel" aria-labelledby="tab-phone">
54
+ <label for="phone">Phone number</label>
55
+ <div class="phone-row">
56
+ <button type="button" class="country-btn" aria-haspopup="listbox" aria-expanded="false" aria-controls="picker"><span class="flag" aria-hidden="true"></span><span class="dial"></span><span class="caret" aria-hidden="true">&#9662;</span></button>
57
+ <input type="tel" id="phone" name="phone" autocomplete="tel-national" inputmode="tel" placeholder="Phone number" aria-describedby="fine">
58
+ </div>
59
+ </div>
60
+ </div>
61
+ <button type="submit" class="send">Send me a code</button>
62
+ <p class="fine" id="fine" aria-live="polite"></p>
63
+ </form>
64
+ <button type="button" class="other">Other ways to sign in</button>
65
+ </div>
66
+ <div class="picker" id="picker" hidden>
67
+ <button type="button" class="back">&#8249; Back</button>
68
+ <input type="text" class="search" placeholder="Search countries" autocomplete="off" spellcheck="false" role="combobox" aria-expanded="true" aria-controls="countries" aria-autocomplete="list" aria-label="Search countries">
69
+ <ul class="list" id="countries" role="listbox" aria-label="Countries"></ul>
70
+ </div>
71
+ </div>
72
+ <div class="powered">Powered by <a href="https://techne.town" target="_blank" rel="noopener"><span class="word">Techne</span><span class="sr"> (opens in a new tab)</span></a></div>
73
+ </div>`;
74
+ /** The document's one `<style>` with the brand fonts (`@font-face` is ignored inside a shadow root). */
75
+ function addFonts(doc, pds) {
76
+ if (doc.getElementById('techne-sdk-sign-in-fonts'))
77
+ return;
78
+ const style = doc.createElement('style');
79
+ style.id = 'techne-sdk-sign-in-fonts';
80
+ style.textContent = fontFaces(`${new URL(pds).origin}/static/fonts/`);
81
+ doc.head.appendChild(style);
82
+ }
83
+ /** A host element with an open shadow root holding `css`, appended to `target`. */
84
+ function host(target, css, pds) {
85
+ if (!target || typeof target.appendChild !== 'function')
86
+ throw new TypeError('techne-sdk/sign-in: mount on an element');
87
+ const doc = target.ownerDocument;
88
+ addFonts(doc, pds);
89
+ const el = doc.createElement('techne-sign-in');
90
+ const root = el.attachShadow({ mode: 'open' });
91
+ const style = doc.createElement('style');
92
+ style.textContent = css;
93
+ root.appendChild(style);
94
+ target.appendChild(el);
95
+ return { el, root };
96
+ }
97
+ /** The sign-in options to pass on: everything but the form's own. */
98
+ function clientOf(o, own) {
99
+ const rest = { ...o };
100
+ for (const k of own)
101
+ delete rest[k];
102
+ return rest;
103
+ }
104
+ const fold = (s) => s.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase();
105
+ const flagOf = (region) => String.fromCodePoint(0x1f1e6 + region.charCodeAt(0) - 65, 0x1f1e6 + region.charCodeAt(1) - 65);
106
+ /** Every country libphonenumber knows, named in the browser's languages, sorted by name. */
107
+ function countryList(languages) {
108
+ let names = null;
109
+ try {
110
+ names = new Intl.DisplayNames(languages, { type: 'region' });
111
+ }
112
+ catch {
113
+ names = null;
114
+ }
115
+ const out = getCountries().map((region) => {
116
+ let name = region;
117
+ try {
118
+ name = names?.of(region) || region;
119
+ }
120
+ catch {
121
+ name = region;
122
+ }
123
+ return { region, dial: getCountryCallingCode(region), name, key: fold(name) };
124
+ });
125
+ const collator = new Intl.Collator(languages);
126
+ return out.sort((a, b) => collator.compare(a.name, b.name));
127
+ }
128
+ /** The region of the first browser language that names one we know (as "fr" implies FR), else US. */
129
+ function defaultRegion(languages, known) {
130
+ for (const l of languages) {
131
+ let region = '';
132
+ try {
133
+ region = new Intl.Locale(l).maximize().region || '';
134
+ }
135
+ catch {
136
+ region = '';
137
+ }
138
+ if (known.has(region))
139
+ return region;
140
+ }
141
+ return FALLBACK_COUNTRY;
142
+ }
143
+ /** Whether this browser draws flag emoji (Windows draws two letters, which look like a mistake). */
144
+ function flagsDrawn(doc) {
145
+ try {
146
+ const c = doc.createElement('canvas');
147
+ c.width = c.height = 16;
148
+ const g = c.getContext('2d');
149
+ if (!g)
150
+ return false;
151
+ g.font = '14px sans-serif';
152
+ g.textBaseline = 'top';
153
+ g.fillText('\u{1F1FA}\u{1F1F8}', 0, 0);
154
+ const d = g.getImageData(0, 0, 16, 16).data;
155
+ for (let p = 0; p < d.length; p += 4)
156
+ if (d[p + 3] && (d[p] !== d[p + 1] || d[p + 1] !== d[p + 2]))
157
+ return true;
158
+ }
159
+ catch {
160
+ /* no canvas */
161
+ }
162
+ return false;
163
+ }
164
+ /** A typed number read under `region` (a number with its own `+` code wins); undefined when it reads as none. */
165
+ function parsePhone(typed, region) {
166
+ try {
167
+ return parsePhoneNumberFromString(typed || '', region);
168
+ }
169
+ catch {
170
+ return undefined;
171
+ }
172
+ }
173
+ /** A typed number as E.164 under `region`, or null when it cannot be one. */
174
+ function phoneE164(typed, region) {
175
+ const p = parsePhone(typed, region);
176
+ return p && p.isPossible() ? p.number : null;
177
+ }
178
+ /** Re-enable `buttons` when the page comes back from the back-forward cache (the person came back from the
179
+ * sign-in page). Answers the unsubscribe. */
180
+ function onBackForward(doc, enable) {
181
+ const onShow = (e) => {
182
+ if (e.persisted)
183
+ enable();
184
+ };
185
+ doc.defaultView?.addEventListener('pageshow', onShow);
186
+ return () => doc.defaultView?.removeEventListener('pageshow', onShow);
187
+ }
188
+ /** Mount the sign-in form in `target` (appended to it). See the module doc for what it shows and does. */
189
+ export function mountSignIn(target, options) {
190
+ if (!options?.appName?.trim())
191
+ throw new TypeError('techne-sdk/sign-in: mountSignIn needs appName (shown at the top of the form)');
192
+ const client = clientOf(options, ['appName', 'logo', 'onError']);
193
+ const { el, root } = host(target, FORM_CSS, options.pds ?? TECHNE_TOWN_PDS);
194
+ const doc = target.ownerDocument;
195
+ const wrap = doc.createElement('div');
196
+ wrap.innerHTML = FORM_HTML;
197
+ root.appendChild(wrap.firstElementChild);
198
+ const $ = (sel) => {
199
+ const found = root.querySelector(sel);
200
+ if (!found)
201
+ throw new Error(`techne-sdk/sign-in: the form has no ${sel}`);
202
+ return found;
203
+ };
204
+ const appName = options.appName.trim();
205
+ $('.app .name').textContent = appName;
206
+ if (options.logo) {
207
+ const img = $('.app img');
208
+ img.src = options.logo;
209
+ img.hidden = false;
210
+ }
211
+ $('.lede').textContent = `${appName} uses your Techne account. New here? The code we send makes one.`;
212
+ const form = $('form');
213
+ const send = $('.send');
214
+ const other = $('.other');
215
+ const fine = $('.fine');
216
+ const email = $('#email');
217
+ const phone = $('#phone');
218
+ const tabs = { email: $('#tab-email'), phone: $('#tab-phone') };
219
+ const fields = { email: $('#field-email'), phone: $('#field-phone') };
220
+ const main = $('.view.main');
221
+ const picker = $('.picker');
222
+ const countryBtn = $('.country-btn');
223
+ const search = $('.search');
224
+ const list = $('.list');
225
+ let mode = 'email';
226
+ function say(text, error = false) {
227
+ fine.textContent = text;
228
+ fine.classList.toggle('error', error);
229
+ }
230
+ function setTab(m, focus = false) {
231
+ mode = m;
232
+ for (const k of ['email', 'phone']) {
233
+ tabs[k].setAttribute('aria-selected', String(k === m));
234
+ tabs[k].tabIndex = k === m ? 0 : -1;
235
+ fields[k].classList.toggle('off', k !== m);
236
+ }
237
+ say(FINE[m]);
238
+ if (focus)
239
+ tabs[m].focus();
240
+ }
241
+ for (const k of ['email', 'phone'])
242
+ tabs[k].addEventListener('click', () => setTab(k));
243
+ $('.seg').addEventListener('keydown', (e) => {
244
+ const key = e.key;
245
+ if (key === 'ArrowLeft' || key === 'ArrowRight' || key === 'Home' || key === 'End') {
246
+ e.preventDefault();
247
+ setTab(key === 'Home' ? 'email' : key === 'End' ? 'phone' : mode === 'email' ? 'phone' : 'email', true);
248
+ }
249
+ });
250
+ // The country list.
251
+ const nav = doc.defaultView?.navigator;
252
+ const languages = nav?.languages?.length ? nav.languages : [nav?.language || 'en'];
253
+ const countries = countryList(languages);
254
+ const byRegion = new Map(countries.map((c) => [c.region, c]));
255
+ let stored = null;
256
+ try {
257
+ stored = doc.defaultView?.localStorage?.getItem(COUNTRY_STORAGE_KEY) ?? null;
258
+ }
259
+ catch {
260
+ stored = null;
261
+ }
262
+ let current = byRegion.get(stored ?? '') ?? byRegion.get(defaultRegion(languages, new Set(byRegion.keys()))) ?? countries[0];
263
+ let shown = [];
264
+ let active = 0;
265
+ if (!flagsDrawn(doc))
266
+ $('.root').classList.add('no-flags');
267
+ function setCountry(c, remember) {
268
+ current = c;
269
+ $('.country-btn .flag').textContent = flagOf(c.region);
270
+ $('.country-btn .dial').textContent = `+${c.dial}`;
271
+ countryBtn.setAttribute('aria-label', `Country: ${c.name} (+${c.dial}). Change country`);
272
+ if (remember) {
273
+ try {
274
+ doc.defaultView?.localStorage?.setItem(COUNTRY_STORAGE_KEY, c.region);
275
+ }
276
+ catch {
277
+ /* private mode */
278
+ }
279
+ }
280
+ }
281
+ function render() {
282
+ const q = fold(search.value.trim()).replace(/^\+/, '');
283
+ shown = q ? countries.filter((c) => c.key.includes(q) || c.dial.startsWith(q) || c.region.toLowerCase() === q) : [current, ...countries.filter((c) => c !== current)];
284
+ list.replaceChildren();
285
+ if (!shown.length) {
286
+ const li = doc.createElement('li');
287
+ li.className = 'empty';
288
+ li.textContent = 'No country matches';
289
+ list.appendChild(li);
290
+ search.removeAttribute('aria-activedescendant');
291
+ return;
292
+ }
293
+ shown.forEach((c, i) => {
294
+ const li = doc.createElement('li');
295
+ li.id = `country-${c.region}`;
296
+ li.setAttribute('role', 'option');
297
+ li.setAttribute('aria-selected', String(c === current));
298
+ const f = doc.createElement('span');
299
+ f.className = 'flag';
300
+ f.setAttribute('aria-hidden', 'true');
301
+ f.textContent = flagOf(c.region);
302
+ const n = doc.createElement('span');
303
+ n.className = 'cname';
304
+ n.textContent = c.name;
305
+ const d = doc.createElement('span');
306
+ d.className = 'code';
307
+ d.textContent = `+${c.dial}`;
308
+ li.append(f, n, d);
309
+ li.addEventListener('mousedown', (e) => e.preventDefault());
310
+ li.addEventListener('click', () => choose(i));
311
+ list.appendChild(li);
312
+ });
313
+ setActive(0);
314
+ }
315
+ function setActive(i) {
316
+ if (!shown.length)
317
+ return;
318
+ active = Math.max(0, Math.min(i, shown.length - 1));
319
+ const items = list.querySelectorAll('li[role=option]');
320
+ items.forEach((li, k) => li.classList.toggle('active', k === active));
321
+ const li = items[active];
322
+ if (li) {
323
+ search.setAttribute('aria-activedescendant', li.id);
324
+ li.scrollIntoView?.({ block: 'nearest' });
325
+ }
326
+ }
327
+ function openPicker() {
328
+ picker.hidden = false;
329
+ main.classList.add('off');
330
+ main.inert = true;
331
+ countryBtn.setAttribute('aria-expanded', 'true');
332
+ search.value = '';
333
+ render();
334
+ search.focus();
335
+ }
336
+ function closePicker(focusNumber) {
337
+ if (picker.hidden)
338
+ return;
339
+ picker.hidden = true;
340
+ main.classList.remove('off');
341
+ main.inert = false;
342
+ countryBtn.setAttribute('aria-expanded', 'false');
343
+ (focusNumber ? phone : countryBtn).focus();
344
+ }
345
+ function choose(i) {
346
+ const c = shown[i];
347
+ if (!c)
348
+ return;
349
+ setCountry(c, true);
350
+ closePicker(true);
351
+ }
352
+ countryBtn.addEventListener('click', () => (picker.hidden ? openPicker() : closePicker(false)));
353
+ $('.back').addEventListener('click', () => closePicker(false));
354
+ search.addEventListener('input', render);
355
+ search.addEventListener('keydown', (e) => {
356
+ const key = e.key;
357
+ if (key === 'ArrowDown')
358
+ (e.preventDefault(), setActive(active + 1));
359
+ else if (key === 'ArrowUp')
360
+ (e.preventDefault(), setActive(active - 1));
361
+ else if (key === 'Enter')
362
+ (e.preventDefault(), choose(active));
363
+ else if (key === 'Escape')
364
+ (e.preventDefault(), closePicker(false));
365
+ });
366
+ picker.addEventListener('keydown', (e) => {
367
+ if (e.key === 'Escape')
368
+ (e.preventDefault(), closePicker(false));
369
+ });
370
+ setCountry(current, false);
371
+ // A pasted or autofilled number shows the national way under its own country.
372
+ function tidy() {
373
+ const p = parsePhone(phone.value, current.region);
374
+ if (!p || !p.isValid())
375
+ return;
376
+ const own = p.country && byRegion.get(p.country);
377
+ if (own && own !== current)
378
+ setCountry(own, false);
379
+ const national = p.formatNational();
380
+ if (national.replace(/\D/g, '') !== phone.value.replace(/\D/g, ''))
381
+ phone.value = national;
382
+ }
383
+ phone.addEventListener('input', (e) => {
384
+ const t = e.inputType;
385
+ if (!t || t === 'insertFromPaste' || t === 'insertReplacementText')
386
+ tidy();
387
+ });
388
+ phone.addEventListener('change', tidy);
389
+ // Starting the sign-in.
390
+ let busy = false;
391
+ function setBusy(b) {
392
+ busy = b;
393
+ send.disabled = b;
394
+ other.disabled = b;
395
+ }
396
+ function start(o) {
397
+ setBusy(true);
398
+ signIn({ ...client, ...o }).then(() => setBusy(false), (err) => {
399
+ setBusy(false);
400
+ // The person came back from the sign-in page: the form is as they left it.
401
+ if (isNavigatedBack(err))
402
+ return say(FINE[mode]);
403
+ say('Could not reach Techne. Try again.', true);
404
+ options.onError?.(err);
405
+ });
406
+ }
407
+ const offBackForward = onBackForward(doc, () => setBusy(false));
408
+ form.addEventListener('submit', (e) => {
409
+ e.preventDefault();
410
+ if (busy)
411
+ return;
412
+ if (mode === 'email') {
413
+ const v = email.value.trim();
414
+ if (!isEmailAddress(v)) {
415
+ say(v ? 'That address does not look right.' : 'Enter your email address.', true);
416
+ email.focus();
417
+ return;
418
+ }
419
+ start({ email: v });
420
+ }
421
+ else {
422
+ const v = phoneE164(phone.value, current.region);
423
+ if (!v) {
424
+ say(phone.value.trim() ? 'That number does not look right.' : 'Enter your phone number.', true);
425
+ phone.focus();
426
+ return;
427
+ }
428
+ start({ phone: v });
429
+ }
430
+ });
431
+ other.addEventListener('click', () => {
432
+ if (!busy)
433
+ start({ otherWays: true });
434
+ });
435
+ setTab('email');
436
+ return {
437
+ unmount() {
438
+ offBackForward();
439
+ el.remove();
440
+ },
441
+ };
442
+ }
443
+ /** Mount the "Sign in with Techne" button in `target` (appended to it). A click starts {@link signIn} with no
444
+ * handle (the Techne sign-in page's first step), or calls `onClick` instead. */
445
+ export function mountSignInButton(target, options) {
446
+ const o = options ?? {};
447
+ const theme = o.theme ?? 'dark';
448
+ const size = o.size ?? 'medium';
449
+ if (theme !== 'dark' && theme !== 'light')
450
+ throw new TypeError(`techne-sdk/sign-in: theme is 'dark' or 'light' (got ${JSON.stringify(theme)})`);
451
+ if (size !== 'medium' && size !== 'small')
452
+ throw new TypeError(`techne-sdk/sign-in: size is 'medium' or 'small' (got ${JSON.stringify(size)})`);
453
+ const client = clientOf(o, ['theme', 'size', 'onClick', 'onError']);
454
+ const { el, root } = host(target, BUTTON_CSS, o.pds ?? TECHNE_TOWN_PDS);
455
+ const doc = target.ownerDocument;
456
+ const btn = doc.createElement('button');
457
+ btn.type = 'button';
458
+ btn.className = `root btn ${theme}${size === 'small' ? ' small' : ''}`;
459
+ btn.setAttribute('part', 'button');
460
+ btn.append('Sign in with ');
461
+ const word = doc.createElement('span');
462
+ word.className = 'word';
463
+ word.textContent = 'Techne';
464
+ btn.appendChild(word);
465
+ root.appendChild(btn);
466
+ btn.addEventListener('click', () => {
467
+ if (o.onClick)
468
+ return o.onClick();
469
+ btn.disabled = true;
470
+ signIn(client).then(() => (btn.disabled = false), (err) => {
471
+ btn.disabled = false;
472
+ if (!isNavigatedBack(err))
473
+ o.onError?.(err);
474
+ });
475
+ });
476
+ const offBackForward = onBackForward(doc, () => (btn.disabled = false));
477
+ return {
478
+ unmount() {
479
+ offBackForward();
480
+ el.remove();
481
+ },
482
+ };
483
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The sign-in form's and the button's styles: the Techne sign-in page's own values (ePDS auth-service
3
+ * `login-page.ts`, `phone/country-picker.ts` and shared `brand.ts`, as rendered in the approved mocks), in
4
+ * one sheet that lives in each form's shadow root. Nothing here reaches the host page, and the host page's
5
+ * rules do not reach in: `:host` resets every inherited property with `!important`, which beats the page's
6
+ * own rules on the host element.
7
+ *
8
+ * The two brand fonts are the Techne sign-in page's, loaded from the home PDS (`<pds>/static/fonts/`,
9
+ * served with `Access-Control-Allow-Origin: *`) under names of our own, so a host page's 'Octave' or
10
+ * 'Public Sans' is never touched. `@font-face` does not work inside a shadow root, so {@link fontFaces} goes
11
+ * into the document's head, once.
12
+ */
13
+ /** The font families the sheet names (ours: no host page uses them). */
14
+ export declare const SERIF = "'Techne Octave', Georgia, serif";
15
+ export declare const SANS = "'Techne Public Sans', Arial, sans-serif";
16
+ /** The `@font-face` rules for {@link SERIF} and {@link SANS}, from `base` (`<pds>/static/fonts/`). */
17
+ export declare function fontFaces(base: string): string;
18
+ /** The form's sheet. */
19
+ export declare const FORM_CSS = "\n:host { all: initial !important; display: block !important; }\n:host([hidden]) { display: none !important; }\n*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }\n.root { font-family: 'Techne Public Sans', Arial, sans-serif; color: #000; text-align: left; line-height: normal; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; }\nbutton, input { font-family: inherit; }\n:focus-visible { outline: 2px solid #000; outline-offset: 3px; }\n[hidden] { display: none !important; }\n.word { font-family: 'Techne Octave', Georgia, serif; font-weight: 500; font-feature-settings: 'dlig' 1; letter-spacing: -.01em; }\n\n.root { --muted: rgba(0,0,0,.58); --input-border: rgba(0,0,0,.12); }\n.card { width: 100%; max-width: 420px; padding: 28px; display: flex; flex-direction: column; background: #fff; border: 1px solid rgba(0,0,0,.05); border-radius: 20px; box-shadow: 0 6px 24px rgba(0,0,0,.06); }\n.app { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; min-width: 0; }\n.app img { width: 44px; height: 44px; border-radius: 12px; flex: none; display: block; object-fit: cover; }\n.app .name { font-size: 14px; font-weight: 500; color: var(--muted); overflow-wrap: anywhere; }\n/* Every view sits in one grid cell; the country list is laid over it. The cell is as tall as the main view\n whatever tab or view is showing, so the card keeps one size. */\n.views { position: relative; display: grid; flex: 1 0 auto; }\n.view { grid-area: 1 / 1; display: flex; flex-direction: column; min-width: 0; }\n.view.off { visibility: hidden; }\nh1 { font-family: 'Techne Octave', Georgia, serif; font-size: 28px; line-height: 1.2; font-weight: 500; letter-spacing: -.02em; color: #000; margin-bottom: 8px; font-feature-settings: 'dlig' 1; overflow-wrap: anywhere; text-wrap: balance; }\n.lede { color: var(--muted); font-size: 15px; line-height: 1.45; margin-bottom: 24px; text-wrap: pretty; }\n.seg { display: grid; grid-template-columns: 1fr 1fr; background: #EDEBE3; border-radius: 999px; padding: 4px; margin-bottom: 16px; }\n.tab { border: 0; background: none; padding: 9px 0; border-radius: 999px; font-size: 14px; font-weight: 500; color: var(--muted); cursor: pointer; transition: background .15s, color .15s, box-shadow .15s; }\n.tab[aria-selected=\"true\"] { background: #fff; color: #1A130F; box-shadow: 0 1px 4px rgba(0,0,0,.08); }\n.tab:focus-visible { outline-offset: 2px; }\n.fields { display: grid; }\n.field { grid-area: 1 / 1; text-align: left; }\n.field.off { visibility: hidden; }\nlabel { display: block; font-size: 13px; line-height: 18px; font-weight: 500; color: #000; margin-bottom: 6px; }\ninput { width: 100%; height: 48px; padding: 0 14px; border: 1.5px solid var(--input-border); border-radius: 12px; font-size: 16px; color: #000; background: #fff; outline: none; transition: border-color .15s; }\ninput:focus { border-color: #000; }\ninput:focus-visible { outline: none; }\ninput::placeholder { color: rgba(0,0,0,.4); }\n.phone-row { display: flex; gap: 8px; }\n.phone-row input { flex: 1 1 auto; min-width: 0; }\n.country-btn { flex: 0 0 auto; display: flex; align-items: center; gap: 6px; height: 48px; padding: 0 12px; border: 1.5px solid var(--input-border); border-radius: 12px; background: #fff; font-size: 16px; color: #1A130F; cursor: pointer; }\n.country-btn:focus-visible, .country-btn[aria-expanded=\"true\"] { outline: none; border-color: #000; }\n.country-btn .caret { color: var(--muted); font-size: 12px; }\n.flag { font-size: 20px; line-height: 1; }\n.no-flags .flag { display: none; }\n.send { width: 100%; height: 48px; margin-top: 16px; padding: 0 15px; background: #000; color: #fff; border: 0; border-radius: 999px; font-size: 15px; font-weight: 500; cursor: pointer; transition: opacity .15s; }\n.send:hover { opacity: .86; }\n.send:focus-visible { outline-offset: 2px; }\n.send:disabled { opacity: .7; cursor: default; }\n.fine { font-size: 13px; color: var(--muted); margin-top: 12px; line-height: 1.45; }\n.fine.error { color: #B3261E; }\n.other { align-self: center; margin-top: 18px; padding: 4px 2px; border: 0; background: none; font-size: 14px; font-weight: 400; color: rgba(0,0,0,.72); text-decoration: underline; text-decoration-color: rgba(0,0,0,.28); text-underline-offset: 3px; cursor: pointer; }\n.other:hover { color: #000; text-decoration-color: currentColor; }\n.other:disabled { cursor: default; }\n/* The country list: over the views, inside the card. */\n.picker { position: absolute; inset: 0; display: flex; flex-direction: column; background: #fff; }\n.back { align-self: flex-start; margin-bottom: 10px; padding: 4px 0; border: 0; background: none; border-radius: 4px; color: var(--muted); font-size: 14px; font-weight: 500; cursor: pointer; }\n.back:hover { color: #000; }\n.picker input { flex: none; }\n.list { list-style: none; flex: 1 1 0; min-height: 0; overflow-y: auto; margin-top: 8px; }\n.list li { display: flex; align-items: center; gap: 10px; padding: 10px 12px; border-radius: 8px; cursor: pointer; font-size: 15px; }\n.list li .cname { flex: 1 1 auto; min-width: 0; }\n.list li .code { color: var(--muted); }\n.list li.active, .list li:hover { background: #f3f1ec; }\n.list li[aria-selected=\"true\"] .cname { font-weight: 600; }\n.list li.empty { cursor: default; color: var(--muted); font-size: 14px; background: none; }\n.powered { display: flex; align-items: center; justify-content: center; gap: 6px; margin-top: 20px; font-size: 12px; color: var(--muted); }\n.powered a { text-decoration: none; color: #000; border-radius: 4px; }\n.powered .word { font-size: 16px; line-height: 1; }\n.sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }\n";
20
+ /** The "Sign in with Techne" button's sheet: `dark` (black, for light backgrounds) and `light` (white with a black
21
+ * edge), 44 px or 36 px (`small`) tall. The name only, never the mark beside it. */
22
+ export declare const BUTTON_CSS = "\n:host { all: initial !important; display: block !important; }\n:host([hidden]) { display: none !important; }\n*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }\n.root { font-family: 'Techne Public Sans', Arial, sans-serif; color: #000; text-align: left; line-height: normal; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; }\nbutton, input { font-family: inherit; }\n:focus-visible { outline: 2px solid #000; outline-offset: 3px; }\n[hidden] { display: none !important; }\n.word { font-family: 'Techne Octave', Georgia, serif; font-weight: 500; font-feature-settings: 'dlig' 1; letter-spacing: -.01em; }\n\n:host { display: inline-block !important; }\n.btn { display: inline-flex; align-items: center; height: 44px; padding: 0 22px; border-radius: 999px; font-family: 'Techne Public Sans', Arial, sans-serif; font-size: 15px; font-weight: 500; line-height: 1; white-space: nowrap; cursor: pointer; border: 1.5px solid #000; }\n.btn .word { font-size: 18px; line-height: 1; }\n.btn.dark { background: #000; color: #fff; }\n.btn.light { background: #fff; color: #000; }\n.btn.small { height: 36px; padding: 0 16px; font-size: 14px; }\n.btn.small .word { font-size: 16px; }\n.btn:hover { opacity: .86; }\n.btn:disabled { opacity: .7; cursor: default; }\n";