gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Branchf13-avatar2a99730a|||PR ident#37 avatar in hlmref13-avatar/selector.js

9.0 KB

  1. // selector.js — ident's IDENTITY SELECTOR for an app's page (piece 3 of 6, ticket #26;
  2. // CONCEPT.md "Flow 2: identity selector"). Served by ident at /selector.js. An app's page:
  3. //
  4. // <script src="https://<ident>/selector.js"></script>
  5. // <ident-selector key="pk_…"></ident-selector> (the app's PUBLIC API key)
  6. //
  7. // The element (shadow DOM, ident's design) first says "choose ident". Opening it fetches
  8. // the identities of the ident user signed in in this browser from ident (credentials,
  9. // CORS: only from one of the app's registered origins with its key). Choosing one IS the
  10. // login: ident hands a one-time code, the element fires `ident-login` with
  11. // `event.detail.code`; the HOST'S SERVER trades the code with POST /api/exchange (key +
  12. // secret) for the app-specific identity id.
  13. // The host tells the element it is logged in: attribute `logged-in` (or `el.loggedIn =
  14. // true`). Logout on the website = the host resets it (remove the attribute, or
  15. // `el.loggedIn = false` / `el.reset()`). The element sets no cookie of its own.
  16. // Signed out of ident, the panel holds ident's own sign-in page in an iframe (/embed/signin; ident frames it only for the app's origins).
  17. // Restyling: CSS custom properties --ident-* on the element, and ::part(button | panel |
  18. // identity | status | message | link) — see ident's README "How apps use ident".
  19. (() => {
  20. if (!window.customElements || customElements.get('ident-selector')) return;
  21. const script = document.currentScript;
  22. const IDENT = new URL(script ? script.src : location.href).origin;
  23. const CSS = `
  24. :host {
  25. --_accent: var(--ident-accent, #ce9178);
  26. --_accent-text: var(--ident-accent-text, rgb(15, 20, 25));
  27. --_bg: var(--ident-background, rgb(35, 40, 45));
  28. --_text: var(--ident-text, rgb(195, 200, 205));
  29. --_strong: var(--ident-text-strong, rgb(245, 250, 255));
  30. --_muted: var(--ident-text-muted, rgb(145, 150, 155));
  31. --_border: var(--ident-border, rgb(70, 75, 80));
  32. --_radius: var(--ident-radius, .4rem);
  33. display: inline-block;
  34. max-width: 100%;
  35. font: var(--ident-font, 600 16px/1.5 system-ui, sans-serif);
  36. color: var(--_text);
  37. }
  38. :host([hidden]) { display: none; }
  39. * { box-sizing: border-box; }
  40. button { font: inherit; cursor: pointer; }
  41. [part~="button"] {
  42. display: inline-flex; align-items: center; gap: .5rem; max-width: 100%;
  43. padding: .6rem 1.1rem; color: var(--_accent-text); background: var(--_accent);
  44. border: 1px solid var(--_accent); border-radius: var(--_radius);
  45. }
  46. [part~="button"]:hover { filter: brightness(1.1); }
  47. [part~="button"]:focus-visible, [part~="identity"]:focus-visible { outline: 2px solid var(--_strong); outline-offset: 2px; }
  48. .mark { font-weight: 800; letter-spacing: .01em; }
  49. .caret { font-size: .75em; }
  50. [part~="panel"] {
  51. margin-top: .4rem; width: 20rem; max-width: 100%; padding: .5rem;
  52. background: var(--_bg); border: 1px solid var(--_border); border-radius: calc(var(--_radius) * 1.5);
  53. font-weight: 400;
  54. }
  55. ul { list-style: none; margin: 0; padding: 0; display: grid; gap: .3rem; }
  56. [part~="identity"] {
  57. display: block; width: 100%; text-align: left; padding: .55rem .8rem; overflow-wrap: anywhere;
  58. color: var(--_strong); background: transparent; border: 1px solid var(--_border); border-radius: var(--_radius);
  59. }
  60. [part~="identity"]:hover { border-color: var(--_accent); color: var(--_accent); }
  61. iframe { display: block; width: 100%; height: 19.5rem; /* until the frame reports its height */ border: 0; background: transparent; }
  62. @media (min-width: 600px) { iframe { height: 21rem; } }
  63. .head { margin: 0 0 .4rem; font-size: .85rem; color: var(--_muted); }
  64. [part~="message"] { margin: 0; padding: .3rem .2rem; font-size: .95rem; }
  65. [part~="link"] { color: var(--_accent); }
  66. [part~="status"] {
  67. display: inline-flex; align-items: center; gap: .5rem; max-width: 100%; overflow-wrap: anywhere;
  68. padding: .6rem 1.1rem; color: var(--_strong); background: var(--_bg);
  69. border: 1px solid var(--_border); border-radius: var(--_radius);
  70. }
  71. [part~="status"] .check { color: var(--_accent); }
  72. `;
  73. const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
  74. class IdentSelector extends HTMLElement {
  75. static get observedAttributes() { return ['logged-in', 'key']; }
  76. constructor() {
  77. super();
  78. this.attachShadow({ mode: 'open' });
  79. this._open = false;
  80. this._view = 'idle'; // idle | loading | list | signedout | error
  81. this._items = [];
  82. this._error = '';
  83. this._chosen = '';
  84. this._render();
  85. // the sign-in frame tells its content height (ident's /embed/signin, per step); only ident's own window is believed
  86. window.addEventListener('message', (e) => {
  87. const f = this.shadowRoot.getElementById('signin');
  88. const h = e.data && e.data.identFrameHeight;
  89. if (f && e.origin === IDENT && e.source === f.contentWindow && h > 0 && h < 3000) f.style.height = Math.ceil(h) + 'px';
  90. });
  91. }
  92. get key() { return this.getAttribute('key') || ''; }
  93. // where ident sends the browser after the sign-in (?ident_code=…): the attribute `return` (an absolute URL on the app's origin that handles
  94. // ident_code, e.g. the login button's), else this page
  95. get returnUrl() { return this.getAttribute('return') || location.href.split('#')[0]; }
  96. get loggedIn() { return this.hasAttribute('logged-in'); }
  97. set loggedIn(v) { this.toggleAttribute('logged-in', !!v); }
  98. reset() { this.loggedIn = false; }
  99. attributeChangedCallback(name) {
  100. if (name === 'logged-in' && !this.loggedIn) this._chosen = '';
  101. this._open = false;
  102. this._render();
  103. }
  104. async _toggle() {
  105. if (this._open) { this._open = false; this._render(); return; }
  106. this._open = true;
  107. this._view = 'loading';
  108. this._render();
  109. try {
  110. const r = await fetch(IDENT + '/api/selector/identities?key=' + encodeURIComponent(this.key), { credentials: 'include', cache: 'no-store' });
  111. if (!r.ok) throw new Error('HTTP ' + r.status);
  112. const j = await r.json();
  113. this._items = j.identities || [];
  114. this._view = j.signedIn ? 'list' : 'signedout';
  115. } catch (e) {
  116. // a refused origin/key has no CORS headers: the browser gives us nothing but this
  117. this._view = 'error';
  118. this._error = 'ident does not answer this site. Is it registered in ident with this API key?';
  119. }
  120. if (this._open) this._render();
  121. }
  122. async _choose(id, name) {
  123. this._view = 'loading';
  124. this._render();
  125. try {
  126. const r = await fetch(IDENT + '/api/selector/choose?key=' + encodeURIComponent(this.key), {
  127. method: 'POST', credentials: 'include', cache: 'no-store',
  128. headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ identity: id }),
  129. });
  130. const j = await r.json().catch(() => ({}));
  131. if (!r.ok || !j.code) throw new Error(j.error || ('HTTP ' + r.status));
  132. this._chosen = name;
  133. this._open = false;
  134. this._render();
  135. // THE LOGIN: the host's server trades this code (POST /api/exchange, key + secret)
  136. this.dispatchEvent(new CustomEvent('ident-login', { detail: { code: j.code }, bubbles: true, composed: true }));
  137. } catch (e) {
  138. this._view = 'error';
  139. this._error = 'ident refused: ' + e.message;
  140. this._render();
  141. }
  142. }
  143. _render() {
  144. const root = this.shadowRoot;
  145. if (this.loggedIn) {
  146. root.innerHTML = `<style>${CSS}</style><span part="status" id="status"><span class="check" aria-hidden="true">✓</span>` +
  147. `<span>logged in with <span class="mark">ident</span>${this._chosen ? ' · ' + esc(this._chosen) : ''}</span></span>`;
  148. return;
  149. }
  150. let panel = '';
  151. if (this._open) {
  152. let body = '';
  153. if (this._view === 'loading') body = `<p part="message" id="message">…</p>`;
  154. else if (this._view === 'list') {
  155. body = `<p class="head">Choose the identity to log in with</p><ul id="list">` +
  156. this._items.map((it) => `<li><button type="button" part="identity" data-id="${esc(it.id)}">${esc(it.name)}</button></li>`).join('') + `</ul>`;
  157. } else if (this._view === 'signedout') {
  158. body = `<iframe part="frame" id="signin" title="Sign in to ident" src="${esc(IDENT)}/embed/signin?key=${encodeURIComponent(this.key)}&amp;return=${encodeURIComponent(this.returnUrl)}"></iframe>`;
  159. } else if (this._view === 'error') body = `<p part="message" id="message">${esc(this._error)}</p>`;
  160. panel = `<div part="panel" id="panel">${body}</div>`;
  161. }
  162. root.innerHTML = `<style>${CSS}</style><button type="button" part="button" id="choose" aria-expanded="${this._open}">` +
  163. `<span>choose <span class="mark">ident</span></span><span class="caret" aria-hidden="true">${this._open ? '▲' : '▼'}</span></button>${panel}`;
  164. root.getElementById('choose').addEventListener('click', () => this._toggle());
  165. for (const b of root.querySelectorAll('[part~="identity"]')) {
  166. b.addEventListener('click', () => this._choose(b.dataset.id, b.textContent));
  167. }
  168. }
  169. }
  170. customElements.define('ident-selector', IdentSelector);
  171. })();

Branches

Latest commits

  • 2a99730a|||PR ident#37 avatar in hlmre
  • fa4ed25bMerge branch 'f11-upsert' into mainIdent
  • 8f3d9bc9|||PR ident#42 keyed upsert and removemre
  • 675493b1ident#42: editing an identity upserts the one edited row (face editIdentity answers { identity, row }); a create or delete keeps the whole list because the rows' position-dependent parts (default, Delete, Identity n) changemre
  • 45e55303ident#42: an app write patches one row: upsert on create, edit and new secret, one-argument remove on delete; the faces answer the changed app (or the deleted id), not the whole listmre
  • 991641d4Merge branch 'f10-access' into mainIdent
  • e56d8273|||PR ident#34 part 4: access and inbox fixed classesmre
  • df7696dbident#34: tests: access ticks selector quoting fixmre
  • 7215903eident#34: access: the unstyled classes all, app, tick, apptick, plus are dropped; the gate finds the app ticks by input[name=app]mre
  • 69b0a0ceident#34: access: the pick buttons use Style.pickCard instead of class pickmre
  • dc702419Merge branch 'f9-choose' into mainIdent
  • 8caec771|||PR ident#34 restore .choose hookmre
  • 0dbff960Merge branch 'f8-shared' into mainIdent
  • d69665f6|||PR ident#34 part 3: shared look classes (wide, avatar, chip/used, conn, choose, who, inboxlink) moved to statics or droppedmre
  • 3a64dc48ident#34: chipLook: radius as the same var() string (a bare token name in a static does not compile); selector gate selectormre
  • eb039073ident#34: tests: signin and migration find the choice without the classmre
  • 4b94a594ident#34: tests: fix selector of the identity choicemre
  • bebc88e4ident#34: main.hl drops the unstyled classes inboxlink and whomre
  • b4e7ad04ident#34: the identity choice link/button has no class (rule on #chooselist a)mre
  • 3c33d6eaident#34: the connection link in inbox has no class (rule on #conns a)mre