useyuva 0.0.7 → 0.0.9
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/README.md +98 -6
- package/dist/esm/analytics.js +1 -0
- package/dist/esm/chat.js +2 -2
- package/dist/esm/client-p9899hvt.js +1 -0
- package/dist/esm/docs.js +4 -61
- package/dist/esm/index-8hzbxjv3.js +12 -0
- package/dist/esm/index-98r96a7e.js +2 -0
- package/dist/esm/index-c6q8br7d.js +2 -0
- package/dist/esm/index-gk84nm8f.js +2 -0
- package/dist/esm/index-rdzxvj2r.js +2 -0
- package/dist/esm/index.js +1 -1
- package/dist/esm/nuxt/module.js +7 -3
- package/dist/esm/nuxt/runtime/analytics.js +6 -0
- package/dist/esm/nuxt/runtime/components.js +32 -0
- package/dist/esm/nuxt/runtime/plugin.js +11 -0
- package/dist/esm/react.js +2 -1
- package/dist/esm/subscribe.js +33 -0
- package/dist/esm/thread-btm71nxt.js +61 -0
- package/dist/esm/yuva-chat-zzebx8pk.js +193 -0
- package/dist/types/analytics/core.d.ts +47 -0
- package/dist/types/analytics/handle.d.ts +3 -0
- package/dist/types/analytics.d.ts +1 -0
- package/dist/types/client/api.d.ts +11 -0
- package/dist/types/client/client.d.ts +6 -1
- package/dist/types/docs/base.d.ts +3 -2
- package/dist/types/docs/define.d.ts +1 -0
- package/dist/types/docs/discussions.d.ts +4 -13
- package/dist/types/docs/dom.d.ts +1 -0
- package/dist/types/docs/thread.d.ts +71 -0
- package/dist/types/docs.d.ts +2 -2
- package/dist/types/i18n.d.ts +2 -2
- package/dist/types/index.d.ts +1 -1
- package/dist/types/locales/de/docs.d.ts +2 -0
- package/dist/types/locales/de/loader.d.ts +2 -0
- package/dist/types/locales/de/panel.d.ts +2 -0
- package/dist/types/locales/de/subscribe.d.ts +2 -0
- package/dist/types/locales/de/thread.d.ts +2 -0
- package/dist/types/locales/en/subscribe.d.ts +2 -0
- package/dist/types/locales/en/thread.d.ts +2 -0
- package/dist/types/locales/tr/subscribe.d.ts +2 -0
- package/dist/types/locales/tr/thread.d.ts +2 -0
- package/dist/types/nuxt/module.d.ts +8 -1
- package/dist/types/nuxt/runtime/analytics.d.ts +2 -0
- package/dist/types/nuxt/runtime/components.d.ts +34 -0
- package/dist/types/nuxt/runtime/plugin.d.ts +6 -0
- package/dist/types/react.d.ts +18 -0
- package/dist/types/schema.gen.d.ts +15384 -5025
- package/dist/types/subscribe/element.d.ts +34 -0
- package/dist/types/subscribe.d.ts +4 -0
- package/dist/types/translate.d.ts +5 -0
- package/dist/widget/yuva-docs-thread-8st0egsq.js +61 -0
- package/dist/widget/yuva-subscribe-client-s3cx942g.js +11 -0
- package/dist/yuva-analytics.js +1 -0
- package/dist/yuva-chat.js +6 -6
- package/dist/yuva-docs.js +8 -65
- package/dist/yuva-subscribe.js +33 -0
- package/dist/yuva.js +2 -2
- package/package.json +27 -4
- package/dist/esm/index-cmr5w646.js +0 -2
- package/dist/esm/index-dj5dhqc1.js +0 -12
- package/dist/esm/yuva-chat-acme1k5r.js +0 -193
package/README.md
CHANGED
|
@@ -7,8 +7,10 @@ JavaScript SDK for [Yuva](https://github.com/productdevbook/yuva), open-source c
|
|
|
7
7
|
| `useyuva` | `createYuvaClient()`: the contact side (`/client/v1`) without DOM. Browsers, Node 22+, Bun, Deno, workers. |
|
|
8
8
|
| `useyuva/chat` | The `<yuva-chat>` web component, built on that client. Browser only. |
|
|
9
9
|
| `useyuva/docs` | `<yuva-page-feedback>` and `<yuva-discussions>` for documentation pages. Registers in the browser only, so it is safe to import during SSR. |
|
|
10
|
-
| `useyuva/
|
|
11
|
-
| `useyuva/
|
|
10
|
+
| `useyuva/subscribe` | `<yuva-subscribe>`, a mailing list sign-up form. Registers in the browser only. |
|
|
11
|
+
| `useyuva/analytics` | `createAnalytics()`: cookieless pageviews and engagement for an analytics property. Does nothing during SSR. |
|
|
12
|
+
| `useyuva/react` | `YuvaProvider`, `useConversations`, `useMessages`, `YuvaAnalytics`, `useYuvaAnalytics`. React 18+ is an optional peer. |
|
|
13
|
+
| `useyuva/nuxt` | A Nuxt module: `YuvaChat`, `YuvaPageFeedback`, `YuvaDiscussions` and `YuvaSubscribe` components, configured once in `nuxt.config`. |
|
|
12
14
|
| `useyuva/api` | A typed `/v1` client for backends (API key), generated from the OpenAPI contract. |
|
|
13
15
|
|
|
14
16
|
```sh
|
|
@@ -16,7 +18,9 @@ npm install useyuva
|
|
|
16
18
|
```
|
|
17
19
|
|
|
18
20
|
Without a bundler, the server hosts the widget itself: `<script src="https://<your-yuva>/yuva.js" defer></script>`,
|
|
19
|
-
|
|
21
|
+
the documentation page elements without the chat: `<script src="https://<your-yuva>/yuva-docs.js" defer></script>`,
|
|
22
|
+
the subscribe form: `<script src="https://<your-yuva>/yuva-subscribe.js" defer></script>`,
|
|
23
|
+
and analytics: `<script src="https://<your-yuva>/yuva-analytics.js" data-key="yuva_ak_…" defer></script>`.
|
|
20
24
|
|
|
21
25
|
## Client
|
|
22
26
|
|
|
@@ -108,6 +112,11 @@ Reader sign-in:
|
|
|
108
112
|
- `discussionWriter()` resolves to `"reader"`, `"contact"` (an identity token) or `null` (read only).
|
|
109
113
|
- `openReaderPopup(server, channel)` and `readerConnectUrl(server, channel, origin)` are the same popup without a client.
|
|
110
114
|
|
|
115
|
+
Mailing lists:
|
|
116
|
+
|
|
117
|
+
- `lists()` returns the channel's public lists and a `form_token`; `subscribe({ email, list_ids, page_url, consent_text, form_token })` answers `{ confirmation }` the same way for every address. Send the token back 2 seconds to 2 hours after `lists()`.
|
|
118
|
+
- With an identity token: `subscriptions()` lists the public lists with the contact's `state`; `subscribeList(listId, { consent_text })` and `unsubscribeList(listId)` change it.
|
|
119
|
+
|
|
111
120
|
Errors worth handling: `403 sign_in_required`, `discussions_off`, `discussion_locked`, `edit_window_closed`, `forbidden`; `400 page_origin`; `429 rate_limited`.
|
|
112
121
|
|
|
113
122
|
## Chat element
|
|
@@ -148,18 +157,101 @@ Events: `yuva-rating` (`{ page, rating, previous }`), `yuva-feedback` (`{ page,
|
|
|
148
157
|
and `yuva-reader` (`{ name, initials }` or `null`). In React use `YuvaPageFeedback` and
|
|
149
158
|
`YuvaDiscussions` from `useyuva/react` (`onDiscussion`, `onPost`, `onReader`).
|
|
150
159
|
|
|
160
|
+
## Subscribe form
|
|
161
|
+
|
|
162
|
+
```ts
|
|
163
|
+
import "useyuva/subscribe";
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
```html
|
|
167
|
+
<yuva-subscribe channel="yuva_pk_…" server="https://support.example.com" layout="inline"></yuva-subscribe>
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
Takes `channel`, `server`, `locale`, `dir` and `identity-token`, plus `lists` (comma-separated ids;
|
|
171
|
+
empty for every public list, with a checkbox each when there is more than one), `layout` (`stacked`
|
|
172
|
+
or `inline`), `name` (`optional` or `required` adds a name field), `button-text`, `consent` (your
|
|
173
|
+
own consent sentence) and `privacy-url`. The consent sentence next to the unticked box is sent as it
|
|
174
|
+
is shown. With an identity token it shows a switch per list instead of the e-mail field. Style it
|
|
175
|
+
with `--yuva-accent`, `--yuva-on-accent`, `--yuva-radius`, `--yuva-font` and
|
|
176
|
+
`::part(field|button|consent|status)`. Events: `yuva-subscribe` (`{ lists, confirmation }`) and
|
|
177
|
+
`yuva-subscribe-error` (`{ code }`); `YuvaSubscribe` in `useyuva/react` (`onSubscribe`, `onError`)
|
|
178
|
+
and Nuxt (`@subscribe`, `@error`).
|
|
179
|
+
|
|
180
|
+
## Analytics
|
|
181
|
+
|
|
182
|
+
```html
|
|
183
|
+
<script defer data-key="yuva_ak_…" src="https://support.example.com/yuva-analytics.js"></script>
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
```ts
|
|
187
|
+
import { createAnalytics } from "useyuva/analytics";
|
|
188
|
+
|
|
189
|
+
const analytics = createAnalytics({ server: "https://support.example.com", key: "yuva_ak_…" });
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
Counts a pageview on load and on every History API navigation (`pushState`, back and forward; not
|
|
193
|
+
`replaceState`, not a query change), and one `engagement` per view with the visible and focused
|
|
194
|
+
time and the deepest scroll when the page is hidden or left. Events go out as `text/plain`, so the
|
|
195
|
+
browser sends no preflight; events of one moment share a request, and the last one is sent with
|
|
196
|
+
`sendBeacon`. A `403` from the server stops sending for the page.
|
|
197
|
+
|
|
198
|
+
Nothing is put on the device and no cookie is read: the only storage access is reading
|
|
199
|
+
`localStorage.yuva_optout`, written by `optOut()`. With `navigator.globalPrivacyControl`, Do Not
|
|
200
|
+
Track or `navigator.webdriver` nothing is sent at all.
|
|
201
|
+
|
|
202
|
+
| Attribute | Option | |
|
|
203
|
+
|---|---|---|
|
|
204
|
+
| `data-key` | `key` | The property's public key. |
|
|
205
|
+
| `data-api` | `server` | The Yuva server; the script defaults to the origin it was loaded from. Set it when you serve the endpoint from your own domain. |
|
|
206
|
+
| `data-hash` | `hash: true` | Hash routing: the fragment is part of the page. |
|
|
207
|
+
| `data-consent="required"` | `consent: "required"` | Send nothing until `consent({ analytics: true })`. |
|
|
208
|
+
| `data-manual` | `manual: true` | No automatic pageviews; call `pageview()`. |
|
|
209
|
+
| `data-outbound` | `outbound: true` | A click on a link to another host sends `outbound_click` with prop `url`. |
|
|
210
|
+
| `data-files` | `files: true` | A click on a link to a pdf, zip, dmg, exe, apk, csv, xls(x), doc(x), ppt(x), mp3 or mp4 file sends `file_download` with prop `url`. |
|
|
211
|
+
| `data-chat` | `chat: true` | Opening a `<yuva-chat>` on the page sends `chat_open`. |
|
|
212
|
+
|
|
213
|
+
Methods (`window.yuva` for the script): `pageview({ url?, referrer? })`,
|
|
214
|
+
`track(name, { props?, revenue? })`, `notFound()`, `consent({ analytics })` (or `consent(false)`),
|
|
215
|
+
`optOut()`, `optIn()`, and `destroy()`. Calls made before the script loads go to
|
|
216
|
+
`(window.yuvaq = window.yuvaq || []).push(["track", "Signup", { props: { plan: "pro" } }])`.
|
|
217
|
+
|
|
218
|
+
```ts
|
|
219
|
+
analytics.track("Signup", { props: { plan: "pro", seats: 3 }, revenue: { amount: "29.90", currency: "EUR" } });
|
|
220
|
+
analytics.notFound(); // on the site's 404 page
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
`track` sends a custom event on the current page: up to 30 props (keys of 1 to 300 characters, not
|
|
224
|
+
starting with `$` or `yuva_`; string, number or boolean values) and revenue as a decimal amount in an
|
|
225
|
+
ISO 4217 currency, which Yuva never converts. The server refuses `pageview`, `engagement`, `screen`
|
|
226
|
+
and names starting with `$` or `yuva_`. `notFound()` sends `not_found`, which does not stop the visit
|
|
227
|
+
from bouncing. Every event follows consent mode, the opt-out, GPC, Do Not Track and `webdriver`
|
|
228
|
+
like pageviews do. `<yuva-chat>` dispatches `yuva-open` (bubbling, composed) when its launcher
|
|
229
|
+
opens it; the embedded layout does not.
|
|
230
|
+
Links to `#yuva-optout` and `#yuva-optin` opt the visitor out and back in.
|
|
231
|
+
|
|
232
|
+
In React, render `<YuvaAnalytics server="…" publicKey="yuva_ak_…" outbound />` once (it renders nothing; the
|
|
233
|
+
other options are props too) and call
|
|
234
|
+
`useYuvaAnalytics()` anywhere for `pageview`, `track`, `notFound`, `consent`, `optOut` and `optIn`; calls before it has
|
|
235
|
+
loaded wait for it. The prop is `publicKey` because React keeps `key` for itself. In Nuxt, set `yuva.analytics` (below) and use `useYuvaAnalytics()`.
|
|
236
|
+
|
|
151
237
|
## Nuxt
|
|
152
238
|
|
|
153
239
|
```ts
|
|
154
240
|
// nuxt.config.ts
|
|
155
241
|
export default defineNuxtConfig({
|
|
156
242
|
modules: ["useyuva/nuxt"],
|
|
157
|
-
yuva: {
|
|
243
|
+
yuva: {
|
|
244
|
+
server: "https://support.example.com",
|
|
245
|
+
channel: "yuva_pk_…",
|
|
246
|
+
analytics: { key: "yuva_ak_…" },
|
|
247
|
+
},
|
|
158
248
|
});
|
|
159
249
|
```
|
|
160
250
|
|
|
161
|
-
`NUXT_PUBLIC_YUVA_SERVER`, `NUXT_PUBLIC_YUVA_CHANNEL
|
|
162
|
-
|
|
251
|
+
`NUXT_PUBLIC_YUVA_SERVER`, `NUXT_PUBLIC_YUVA_CHANNEL`, `NUXT_PUBLIC_YUVA_LOCALE` and, when
|
|
252
|
+
`analytics` is set, `NUXT_PUBLIC_YUVA_ANALYTICS_KEY` override the options at runtime. `analytics`
|
|
253
|
+
takes `key`, `server` (defaults to `yuva.server`), `hash`, `consent`, `manual`, `outbound`, `files` and `chat`, adds a client
|
|
254
|
+
plugin and auto-imports `useYuvaAnalytics()`. `<YuvaChat />`, `<YuvaPageFeedback />`, `<YuvaDiscussions />` and `<YuvaSubscribe />` are
|
|
163
255
|
auto-imported, render on the server and load their element in the browser when they mount. Props
|
|
164
256
|
are the attributes in camelCase (`pageTitle`, `identityToken`, which also takes a function);
|
|
165
257
|
events are `@rating`, `@feedback`, `@discussion`, `@post`, `@reader` and `@unread`. `yuva-*` tags are custom elements in
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var OPT_OUT_KEY="yuva_optout",noop=()=>{};function createAnalytics(options){if(typeof window>"u"||!options.key)return{pageview:noop,track:noop,notFound:noop,consent:noop,optOut:noop,optIn:noop,destroy:noop};let nav=navigator,doc=document,storage=()=>{try{return localStorage}catch{}},url=`${options.server.replace(/\/$/,"")}/client/v1/analytics/${options.key}`,hash=options.hash,blocked=nav.globalPrivacyControl||nav.doNotTrack=="1"||nav.webdriver,off=blocked||storage()?.getItem("yuva_optout")=="1",consented=!options.consent,queue=[],view="",page="",referrer=doc.referrer,ms=0,since=0,depth=0,flush=(beacon)=>{let body=JSON.stringify(queue[1]?{e:queue}:queue[0]);if(queue[0]&&(queue=[],!(beacon&&nav.sendBeacon?.(url,body))))fetch(url,{method:"POST",body,keepalive:!0,credentials:"omit"}).then((res)=>void(res.status==403&&(off=blocked=!0)),noop)},send=(event)=>{if(off||!consented)return;if(hash)event.h=!0;if(options.consent)event.c={a:1};if(queue.push(event)<2)setTimeout(flush)},tick=()=>{let now=Date.now();if(since)ms+=now-since;since=doc.visibilityState=="visible"&&doc.hasFocus()?now:0},scroll=()=>{depth=Math.max(depth,Math.min(100,Math.round((scrollY+innerHeight)/doc.documentElement.scrollHeight*100))||0)},engagement=()=>{if(tick(),page&&ms>0)send({n:"engagement",u:page,ms:Math.min(ms,1800000),sd:depth});ms=0,depth=0,scroll()},key=()=>location.pathname+(hash?location.hash:""),pageview=(opts={})=>{if(off||!consented)return;engagement(),view=key(),page=opts.url||location.href,send({n:"pageview",u:page,r:opts.referrer??referrer,w:innerWidth}),referrer=void 0},track=(name,{props,revenue}={})=>send({n:name,u:page||location.href,p:props,$:revenue&&{a:revenue.amount,c:revenue.currency}}),auto=()=>!options.manual&&view!=key()&&pageview(),leave=()=>{engagement(),flush(!0)},optOut=()=>{off=!0,queue=[],storage()?.setItem("yuva_optout","1")},optIn=()=>{off=blocked,storage()?.removeItem("yuva_optout")},push=history.pushState,wrapped=function(...args){push.apply(this,args),auto()};history.pushState=wrapped;let on={popstate:auto,hashchange:auto,prerenderingchange:auto,scroll,focus:tick,blur:tick,pagehide:leave,visibilitychange:()=>doc.visibilityState=="hidden"?leave():tick(),click:(event)=>{let link=event.target.closest?.("a");if(!link)return;let href=link.getAttribute("href"),choice=href=="#yuva-optout"?optOut:href=="#yuva-optin"?optIn:0,name=options.files&&/\.(pdf|zip|dmg|exe|apk|csv|xlsx?|docx?|pptx?|mp[34])$/i.test(link.pathname)?"file_download":options.outbound&&link.host!=location.host&&"outbound_click";if(choice)event.preventDefault(),choice();else if(name&&/^https?:/.test(link.href))track(name,{props:{url:link.href}})}};if(options.chat)on["yuva-open"]=()=>track("chat_open");for(let t in on)addEventListener(t,on[t],!0);if(!doc.prerendering)auto();return{pageview,track,notFound:()=>track("not_found"),consent:(choice)=>{if(consented=choice===!0||!!choice.analytics,consented)auto();else queue=[]},optOut,optIn,destroy:()=>{if(leave(),off=!0,history.pushState==wrapped)history.pushState=push;for(let t in on)removeEventListener(t,on[t],!0)}}}export{OPT_OUT_KEY,createAnalytics};
|
package/dist/esm/chat.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{resolveLocale,
|
|
1
|
+
import{resolveLocale,catalogFor,translatePlain}from"./index-c6q8br7d.js";import{directionOf,launcherOf,contrastOn,readStored,writeStored}from"./index-98r96a7e.js";var styles=`
|
|
2
2
|
:host {
|
|
3
3
|
--yuva-accent: #2563eb;
|
|
4
4
|
--yuva-on-accent: #ffffff;
|
|
@@ -106,4 +106,4 @@ import{resolveLocale,directionOf,catalogFor,translatePlain,launcherOf,contrastOn
|
|
|
106
106
|
block-size: 100%;
|
|
107
107
|
min-block-size: 320px;
|
|
108
108
|
}
|
|
109
|
-
`,chatIcon='<svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round" aria-hidden="true"><path d="M4 5h16v11H9l-5 4z"/></svg>',closeIcon='<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>',scriptSrc=document.currentScript instanceof HTMLScriptElement?document.currentScript.src:"";class YuvaChatElement extends HTMLElement{static observedAttributes=["channel","server","layout","locale","dir","identity-token","open"];static loadPanel=()=>import(new URL("yuva-chat.js",scriptSrc||location.href).href);#root;#launcher=null;#badge=null;#panel;#controller=null;#messages={};#open=!1;#unread=0;#identity=null;#refused=!1;constructor(){super();this.#root=this.attachShadow({mode:"open"}),this.#panel=document.createElement("section"),this.#panel.className="panel",this.#panel.setAttribute("role","dialog"),this.#panel.hidden=!0,this.#panel.addEventListener("keydown",(event)=>{if(event.key==="Escape"&&this.layout==="launcher")this.close()})}get layout(){return this.getAttribute("layout")==="embedded"?"embedded":"launcher"}get channel(){return this.getAttribute("channel")}get server(){return(this.getAttribute("server")||(scriptSrc?new URL(scriptSrc).origin:location.origin)).replace(/\/+$/,"")}get locale(){return resolveLocale(this.getAttribute("locale"),navigator.language)}get isOpen(){return this.#open}get unread(){return this.#unread}setIdentityToken(source){if(this.#identity=source,this.#controller)this.#controller.then((controller)=>controller.identityChanged())}async signOut(){if(this.#identity=null,this.removeAttribute("identity-token"),this.#controller)await(await this.#controller).signOut()}async rate(conversationId,rating,comment){return(await this.#ensureController()).rate(conversationId,rating,comment)}connectedCallback(){this.#render();let channel=this.channel;if(this.layout==="embedded"||this.hasAttribute("open")||!channel)return;let stored=readStored(channel);if(stored.launcher)this.#applyLauncher(stored.launcher);let idle=()=>{if(!this.isConnected||this.#controller||this.channel!==channel)return;if(stored.session)this.#ensureController();else this.#styleLauncher(channel)};if("requestIdleCallback"in window)requestIdleCallback(idle,{timeout:3000});else setTimeout(idle,1000)}#styleLauncher(channel){fetch(`${this.server}/client/v1/channels/${encodeURIComponent(channel)}`,{credentials:"omit"}).then((response)=>{if(response.status===403||response.status===404)this.#refuse();return response.ok?response.json():null}).then((inbox)=>{if(!inbox||this.channel!==channel||this.#controller)return;let launcher=launcherOf(inbox);this.#applyLauncher(launcher),writeStored(channel,{...readStored(channel),launcher})}).catch(()=>{return})}disconnectedCallback(){let controller=this.#controller;if(this.#controller=null,controller)controller.then((c)=>c.destroy())}attributeChangedCallback(name,previous,value){if(!this.isConnected||previous===value)return;if(name==="open"){value===null?this.close():this.open();return}if(name==="identity-token"){if(this.#controller)this.#controller.then((controller)=>controller.identityChanged());return}if(name==="channel"||name==="server"){this.disconnectedCallback(),this.#refused=!1,this.#render();return}if(this.#render(),this.#controller)this.#controller.then((controller)=>controller.update())}async open(){if(this.#open||this.#refused)return;this.#open=!0,this.toggleAttribute("open-panel",!0),this.#syncLauncher();let controller=await this.#ensureController();if(!this.#open)return;this.#panel.hidden=!1,controller.opened()}close(){if(!this.#open||this.layout==="embedded")return;if(this.#open=!1,this.toggleAttribute("open-panel",!1),this.#panel.hidden=!0,this.#syncLauncher(),this.#launcher?.focus(),this.#controller)this.#controller.then((controller)=>controller.closed())}toggle(){return this.#open?this.close():this.open()}#config(){return{channel:this.channel,server:this.server,layout:this.layout,locale:this.locale}}#ensureController(){return this.#controller??=YuvaChatElement.loadPanel().then(({mount})=>mount({panel:this.#panel,config:()=>this.#config(),identityToken:async()=>this.#identity?await this.#identity()??null:this.getAttribute("identity-token"),isOpen:()=>this.#open,close:()=>this.close(),setUnread:(count)=>{this.#unread=count,this.#syncLauncher(),this.dispatchEvent(new CustomEvent("yuva-unread",{detail:{count}}))},setLauncher:(style)=>this.#applyLauncher(style),refused:()=>this.#refuse()})),this.#controller}#refuse(){if(this.#refused)return;this.#refused=!0,console.warn(`Yuva: channel ${this.channel} is unknown or does not allow ${location.origin}`),this.#open=!1,this.toggleAttribute("open-panel",!1),this.disconnectedCallback(),this.#render()}#applyLauncher(style){if(this.setAttribute("position",style.position==="left"?"left":"right"),style.color&&/^#[0-9a-f]{6}$/i.test(style.color))this.style.setProperty("--yuva-accent",style.color),this.style.setProperty("--yuva-on-accent",contrastOn(style.color))}#render(){let locale=this.locale;this.#messages=catalogFor(locale),this.setAttribute("lang",locale);let style=document.createElement("style");if(style.textContent=styles,this.#panel.dir=this.getAttribute("dir")??directionOf(locale),this.#panel.setAttribute("aria-modal","false"),this.#refused){this.#launcher=null,this.#badge=null,this.#root.replaceChildren();return}if(this.layout==="embedded"){this.#launcher=null,this.#badge=null,this.#root.replaceChildren(style,this.#panel),this.#open=!1,this.open();return}let launcher=document.createElement("button");if(launcher.type="button",launcher.className="launcher",launcher.addEventListener("click",()=>void this.toggle()),this.#launcher=launcher,this.#badge=document.createElement("span"),this.#badge.className="badge",this.#badge.setAttribute("aria-hidden","true"),this.#root.replaceChildren(style,this.#panel,launcher),this.#syncLauncher(),this.hasAttribute("open")&&!this.#open)this.open()}#syncLauncher(){let launcher=this.#launcher,badge=this.#badge;if(!launcher||!badge)return;let count=this.#unread;launcher.setAttribute("aria-expanded",String(this.#open)),launcher.setAttribute("aria-label",this.#open?translatePlain(this.#messages,{id:"pqZJT2"}):count>0?translatePlain(this.#messages,{id:"OkHvGB",values:{count}}):translatePlain(this.#messages,{id:"6I7cJR"})),launcher.innerHTML=this.#open?closeIcon:chatIcon,badge.textContent=count>9?"9+":String(count),badge.hidden=this.#open||count===0,launcher.append(badge)}}function define(){if(!customElements.get("yuva-chat"))customElements.define("yuva-chat",YuvaChatElement)}YuvaChatElement.loadPanel=()=>import("./yuva-chat-
|
|
109
|
+
`,chatIcon='<svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round" aria-hidden="true"><path d="M4 5h16v11H9l-5 4z"/></svg>',closeIcon='<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>',scriptSrc=document.currentScript instanceof HTMLScriptElement?document.currentScript.src:"";class YuvaChatElement extends HTMLElement{static observedAttributes=["channel","server","layout","locale","dir","identity-token","open"];static loadPanel=()=>import(new URL("yuva-chat.js",scriptSrc||location.href).href);#root;#launcher=null;#badge=null;#panel;#controller=null;#messages={};#open=!1;#unread=0;#identity=null;#refused=!1;constructor(){super();this.#root=this.attachShadow({mode:"open"}),this.#panel=document.createElement("section"),this.#panel.className="panel",this.#panel.setAttribute("role","dialog"),this.#panel.hidden=!0,this.#panel.addEventListener("keydown",(event)=>{if(event.key==="Escape"&&this.layout==="launcher")this.close()})}get layout(){return this.getAttribute("layout")==="embedded"?"embedded":"launcher"}get channel(){return this.getAttribute("channel")}get server(){return(this.getAttribute("server")||(scriptSrc?new URL(scriptSrc).origin:location.origin)).replace(/\/+$/,"")}get locale(){return resolveLocale(this.getAttribute("locale"),navigator.language)}get isOpen(){return this.#open}get unread(){return this.#unread}setIdentityToken(source){if(this.#identity=source,this.#controller)this.#controller.then((controller)=>controller.identityChanged())}async signOut(){if(this.#identity=null,this.removeAttribute("identity-token"),this.#controller)await(await this.#controller).signOut()}async rate(conversationId,rating,comment){return(await this.#ensureController()).rate(conversationId,rating,comment)}connectedCallback(){this.#render();let channel=this.channel;if(this.layout==="embedded"||this.hasAttribute("open")||!channel)return;let stored=readStored(channel);if(stored.launcher)this.#applyLauncher(stored.launcher);let idle=()=>{if(!this.isConnected||this.#controller||this.channel!==channel)return;if(stored.session)this.#ensureController();else this.#styleLauncher(channel)};if("requestIdleCallback"in window)requestIdleCallback(idle,{timeout:3000});else setTimeout(idle,1000)}#styleLauncher(channel){fetch(`${this.server}/client/v1/channels/${encodeURIComponent(channel)}`,{credentials:"omit"}).then((response)=>{if(response.status===403||response.status===404)this.#refuse();return response.ok?response.json():null}).then((inbox)=>{if(!inbox||this.channel!==channel||this.#controller)return;let launcher=launcherOf(inbox);this.#applyLauncher(launcher),writeStored(channel,{...readStored(channel),launcher})}).catch(()=>{return})}disconnectedCallback(){let controller=this.#controller;if(this.#controller=null,controller)controller.then((c)=>c.destroy())}attributeChangedCallback(name,previous,value){if(!this.isConnected||previous===value)return;if(name==="open"){value===null?this.close():this.open();return}if(name==="identity-token"){if(this.#controller)this.#controller.then((controller)=>controller.identityChanged());return}if(name==="channel"||name==="server"){this.disconnectedCallback(),this.#refused=!1,this.#render();return}if(this.#render(),this.#controller)this.#controller.then((controller)=>controller.update())}async open(){if(this.#open||this.#refused)return;this.#open=!0,this.toggleAttribute("open-panel",!0),this.#syncLauncher();let controller=await this.#ensureController();if(!this.#open)return;if(this.#panel.hidden=!1,controller.opened(),this.layout!=="embedded")this.dispatchEvent(new Event("yuva-open",{bubbles:!0,composed:!0}))}close(){if(!this.#open||this.layout==="embedded")return;if(this.#open=!1,this.toggleAttribute("open-panel",!1),this.#panel.hidden=!0,this.#syncLauncher(),this.#launcher?.focus(),this.#controller)this.#controller.then((controller)=>controller.closed())}toggle(){return this.#open?this.close():this.open()}#config(){return{channel:this.channel,server:this.server,layout:this.layout,locale:this.locale}}#ensureController(){return this.#controller??=YuvaChatElement.loadPanel().then(({mount})=>mount({panel:this.#panel,config:()=>this.#config(),identityToken:async()=>this.#identity?await this.#identity()??null:this.getAttribute("identity-token"),isOpen:()=>this.#open,close:()=>this.close(),setUnread:(count)=>{this.#unread=count,this.#syncLauncher(),this.dispatchEvent(new CustomEvent("yuva-unread",{detail:{count}}))},setLauncher:(style)=>this.#applyLauncher(style),refused:()=>this.#refuse()})),this.#controller}#refuse(){if(this.#refused)return;this.#refused=!0,console.warn(`Yuva: channel ${this.channel} is unknown or does not allow ${location.origin}`),this.#open=!1,this.toggleAttribute("open-panel",!1),this.disconnectedCallback(),this.#render()}#applyLauncher(style){if(this.setAttribute("position",style.position==="left"?"left":"right"),style.color&&/^#[0-9a-f]{6}$/i.test(style.color))this.style.setProperty("--yuva-accent",style.color),this.style.setProperty("--yuva-on-accent",contrastOn(style.color))}#render(){let locale=this.locale;this.#messages=catalogFor(locale),this.setAttribute("lang",locale);let style=document.createElement("style");if(style.textContent=styles,this.#panel.dir=this.getAttribute("dir")??directionOf(locale),this.#panel.setAttribute("aria-modal","false"),this.#refused){this.#launcher=null,this.#badge=null,this.#root.replaceChildren();return}if(this.layout==="embedded"){this.#launcher=null,this.#badge=null,this.#root.replaceChildren(style,this.#panel),this.#open=!1,this.open();return}let launcher=document.createElement("button");if(launcher.type="button",launcher.className="launcher",launcher.addEventListener("click",()=>void this.toggle()),this.#launcher=launcher,this.#badge=document.createElement("span"),this.#badge.className="badge",this.#badge.setAttribute("aria-hidden","true"),this.#root.replaceChildren(style,this.#panel,launcher),this.#syncLauncher(),this.hasAttribute("open")&&!this.#open)this.open()}#syncLauncher(){let launcher=this.#launcher,badge=this.#badge;if(!launcher||!badge)return;let count=this.#unread;launcher.setAttribute("aria-expanded",String(this.#open)),launcher.setAttribute("aria-label",this.#open?translatePlain(this.#messages,{id:"pqZJT2"}):count>0?translatePlain(this.#messages,{id:"OkHvGB",values:{count}}):translatePlain(this.#messages,{id:"6I7cJR"})),launcher.innerHTML=this.#open?closeIcon:chatIcon,badge.textContent=count>9?"9+":String(count),badge.hidden=this.#open||count===0,launcher.append(badge)}}function define(){if(!customElements.get("yuva-chat"))customElements.define("yuva-chat",YuvaChatElement)}YuvaChatElement.loadPanel=()=>import("./yuva-chat-zzebx8pk.js");define();export{YuvaChatElement,define};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{storageKey2,readerStorageKey2,randomId2,YuvaClient2,createYuvaClient2}from"./index-8hzbxjv3.js";export{YuvaClient2 as YuvaClient,createYuvaClient2 as createYuvaClient,randomId2 as randomId,readerStorageKey2 as readerStorageKey,storageKey2 as storageKey};
|
package/dist/esm/docs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{resolveLocale,
|
|
1
|
+
import{createYuvaClient2}from"./index-8hzbxjv3.js";import{resolveLocale,translatePlain}from"./index-c6q8br7d.js";import{el}from"./index-rdzxvj2r.js";import{ApiError2}from"./index-gk84nm8f.js";import{directionOf,launcherOf,contrastOn,readStored,writeStored}from"./index-98r96a7e.js";var messages=JSON.parse(`{"-UxBoG":["Deleted member"],"1UzENP":["No"],"2lF8Zj":["Unanswered"],"5lWFkC":["Sign in"],"78dEKp":["Sort discussions"],"7oGBMv":["Discussions"],"8Ekoev":["You can't do that."],"8ntmc1":["Votes: ",["0"]],"D16wQE":["Could not open the discussion. Try again."],"D9CFV5":["Anonymous"],"E_qvzP":["Enter a valid e-mail address."],"EmiQvf":["Thanks! Anything we could add? (optional)"],"FMWGhb":["Deleted reader"],"G2fuEb":["Locked"],"GQVIIl":["You seem to be offline."],"GqCA_t":["Answered"],"Hw3P48":["Replies: ",["0"]],"JlFcis":["Send"],"KDw4GX":["Try again"],"KEjhwb":["This discussion is locked."],"KM6m8p":["Team"],"LwDe8g":["Sign in to take part in the discussion."],"MDmQKn":["Could not load the discussions."],"Pwqkdw":["Loading…"],"SOvBw9":["Was this page helpful?"],"Sad2tK":["Sending…"],"Su3Vyp":["Check the title and the text and try again."],"U7H5Fm":["Sorry about that. What was missing or unclear?"],"UbRKMZ":["Pending"],"WWy8TN":["Top"],"XJURKP":["E-mail address"],"a_qtPP":["E-mail for a reply (optional)"],"b6Orhy":["Have a question or an idea? Start the first one."],"b_f4xj":["Posts can be edited for 30 minutes after they are written."],"d6N994":["Thanks for your feedback."],"fMPkxb":["Show more"],"fcWrnU":["Sign out"],"isRobC":["New"],"j-3eim":["Discussions about this page"],"l75CjT":["Yes"],"lWv8id":["Awaiting approval"],"nLqMRA":["Team member"],"nW3go1":["Your browser blocked the sign-in window. Allow pop-ups for this site and try again."],"pzatAP":["Loading discussions…"],"rpfOwz":["No discussions about this page yet."],"tA4dAO":["No thanks"],"tAL5wg":["Could not send. Try again."],"tayT8P":["Discussions are turned off for this site."],"twEQ41":["Every discussion on this page has an answer."],"tzsBOP":["Too many attempts. Wait a moment and try again."],"uuIskV":["Sign in to write to us."],"xOTzt5":["just now"],"z1qf6l":["Start a discussion"],"zmA6sS":["Reader"]}`);var messages2=JSON.parse('{"-UxBoG":["Gelöschtes Mitglied"],"1UzENP":["Nein"],"2lF8Zj":["Unbeantwortet"],"5lWFkC":["Anmelden"],"78dEKp":["Diskussionen sortieren"],"7oGBMv":["Diskussionen"],"8Ekoev":["Das können Sie nicht tun."],"8ntmc1":["Stimmen: ",["0"]],"D16wQE":["Die Diskussion konnte nicht eröffnet werden. Versuchen Sie es erneut."],"D9CFV5":["Anonym"],"E_qvzP":["Geben Sie eine gültige E-Mail-Adresse ein."],"EmiQvf":["Danke! Können wir noch etwas ergänzen? (optional)"],"FMWGhb":["Gelöschter Leser"],"G2fuEb":["Gesperrt"],"GQVIIl":["Sie scheinen offline zu sein."],"GqCA_t":["Beantwortet"],"Hw3P48":["Antworten: ",["0"]],"JlFcis":["Senden"],"KDw4GX":["Erneut versuchen"],"KEjhwb":["Diese Diskussion ist gesperrt."],"KM6m8p":["Team"],"LwDe8g":["Melden Sie sich an, um an der Diskussion teilzunehmen."],"MDmQKn":["Die Diskussionen konnten nicht geladen werden."],"Pwqkdw":["Wird geladen…"],"SOvBw9":["War diese Seite hilfreich?"],"Sad2tK":["Wird gesendet…"],"Su3Vyp":["Prüfen Sie Titel und Text und versuchen Sie es erneut."],"U7H5Fm":["Das tut uns leid. Was hat gefehlt oder war unklar?"],"UbRKMZ":["Ausstehend"],"WWy8TN":["Beliebteste"],"XJURKP":["E-Mail-Adresse"],"a_qtPP":["E-Mail für eine Antwort (optional)"],"b6Orhy":["Haben Sie eine Frage oder eine Idee? Starten Sie die erste Diskussion."],"b_f4xj":["Beiträge können bis 30 Minuten nach dem Schreiben bearbeitet werden."],"d6N994":["Danke für Ihr Feedback."],"fMPkxb":["Mehr anzeigen"],"fcWrnU":["Abmelden"],"isRobC":["Neu"],"j-3eim":["Diskussionen zu dieser Seite"],"l75CjT":["Ja"],"lWv8id":["Wartet auf Freigabe"],"nLqMRA":["Teammitglied"],"nW3go1":["Ihr Browser hat das Anmeldefenster blockiert. Erlauben Sie Pop-ups für diese Website und versuchen Sie es erneut."],"pzatAP":["Diskussionen werden geladen…"],"rpfOwz":["Zu dieser Seite gibt es noch keine Diskussionen."],"tA4dAO":["Nein, danke"],"tAL5wg":["Senden fehlgeschlagen. Versuchen Sie es erneut."],"tayT8P":["Diskussionen sind für diese Website deaktiviert."],"twEQ41":["Jede Diskussion auf dieser Seite hat eine Antwort."],"tzsBOP":["Zu viele Versuche. Warten Sie einen Moment und versuchen Sie es erneut."],"uuIskV":["Melden Sie sich an, um uns zu schreiben."],"xOTzt5":["gerade eben"],"z1qf6l":["Diskussion starten"],"zmA6sS":["Leser"]}');var messages3=JSON.parse('{"-UxBoG":["Silinmiş üye"],"1UzENP":["Hayır"],"2lF8Zj":["Yanıtsız"],"5lWFkC":["Giriş yap"],"78dEKp":["Tartışmaları sırala"],"7oGBMv":["Tartışmalar"],"8Ekoev":["Bunu yapamazsınız."],"8ntmc1":["Oylar: ",["0"]],"D16wQE":["Tartışma açılamadı. Yeniden deneyin."],"D9CFV5":["Anonim"],"E_qvzP":["Geçerli bir e-posta adresi girin."],"EmiQvf":["Teşekkürler! Ekleyebileceğimiz bir şey var mı? (isteğe bağlı)"],"FMWGhb":["Silinmiş okuyucu"],"G2fuEb":["Kilitli"],"GQVIIl":["Çevrimdışı görünüyorsunuz."],"GqCA_t":["Yanıtlandı"],"Hw3P48":["Yanıtlar: ",["0"]],"JlFcis":["Gönder"],"KDw4GX":["Yeniden dene"],"KEjhwb":["Bu tartışma kilitli."],"KM6m8p":["Ekip"],"LwDe8g":["Tartışmaya katılmak için giriş yapın."],"MDmQKn":["Tartışmalar yüklenemedi."],"Pwqkdw":["Yükleniyor…"],"SOvBw9":["Bu sayfa işinize yaradı mı?"],"Sad2tK":["Gönderiliyor…"],"Su3Vyp":["Başlığı ve metni kontrol edip yeniden deneyin."],"U7H5Fm":["Üzgünüz. Eksik ya da anlaşılmayan ne vardı?"],"UbRKMZ":["Bekliyor"],"WWy8TN":["En çok oy alan"],"XJURKP":["E-posta adresi"],"a_qtPP":["Yanıt için e-posta (isteğe bağlı)"],"b6Orhy":["Bir sorunuz ya da fikriniz mi var? İlk tartışmayı siz başlatın."],"b_f4xj":["Gönderiler yazıldıktan sonra 30 dakika içinde düzenlenebilir."],"d6N994":["Geri bildiriminiz için teşekkürler."],"fMPkxb":["Daha fazla göster"],"fcWrnU":["Çıkış yap"],"isRobC":["Yeni"],"j-3eim":["Bu sayfayla ilgili tartışmalar"],"l75CjT":["Evet"],"lWv8id":["Onay bekliyor"],"nLqMRA":["Ekip üyesi"],"nW3go1":["Tarayıcınız giriş penceresini engelledi. Bu site için açılır pencerelere izin verip yeniden deneyin."],"pzatAP":["Tartışmalar yükleniyor…"],"rpfOwz":["Bu sayfayla ilgili henüz bir tartışma yok."],"tA4dAO":["Hayır, teşekkürler"],"tAL5wg":["Gönderilemedi. Yeniden deneyin."],"tayT8P":["Bu sitede tartışmalar kapalı."],"twEQ41":["Bu sayfadaki her tartışmanın bir yanıtı var."],"tzsBOP":["Çok fazla deneme. Biraz bekleyip tekrar deneyin."],"uuIskV":["Bize yazmak için oturum açın."],"xOTzt5":["az önce"],"z1qf6l":["Tartışma başlat"],"zmA6sS":["Okur"]}');var shared=Symbol.for("yuva.navigation");function navigation(){let win=window,target=win[shared];if(target)return target;let created=new EventTarget;target=win[shared]=created;let notify=()=>created.dispatchEvent(new Event("change"));for(let name of["pushState","replaceState"]){let original=history[name];history[name]=function(...args){let result=original.apply(this,args);return notify(),result}}return window.addEventListener("popstate",notify),window.addEventListener("hashchange",notify),target}function pageOf(value){try{let url=new URL(value||location.href,location.href);return url.search="",url.hash="",url.href}catch{return value||location.href}}function followPage(listener){let target=navigation(),scheduled=!1,changed=()=>{if(scheduled)return;scheduled=!0,queueMicrotask(()=>{scheduled=!1,listener()})};return target.addEventListener("change",changed),()=>target.removeEventListener("change",changed)}var catalogs={en:messages,tr:messages3,de:messages2},settings=new Map,Base=typeof HTMLElement>"u"?class{}:HTMLElement,scriptSrc=typeof document<"u"&&document.currentScript instanceof HTMLScriptElement?document.currentScript.src:"",baseStyles=`
|
|
2
2
|
:host {
|
|
3
3
|
--yuva-accent: #2563eb;
|
|
4
4
|
--yuva-on-accent: #ffffff;
|
|
@@ -46,11 +46,7 @@ textarea:focus-visible, input:focus-visible { outline: 2px solid var(--yuva-acce
|
|
|
46
46
|
.send:focus-visible, .link:focus-visible { outline: 2px solid var(--yuva-accent); outline-offset: 2px; }
|
|
47
47
|
.link { padding: 0; border: 0; background: none; color: inherit; font: inherit; text-decoration: underline; cursor: pointer; opacity: 0.8; }
|
|
48
48
|
@media (max-width: 480px) { textarea, input { font-size: 16px; } }
|
|
49
|
-
`;
|
|
50
|
-
`).split(`
|
|
51
|
-
`),paragraph=[],list=null,quote=[],flush=()=>{if(paragraph.length)fragment.append(block("p",paragraph));if(quote.length){let element=document.createElement("blockquote");element.append(preview(quote.join(`
|
|
52
|
-
`))),fragment.append(element)}paragraph=[],quote=[],list=null};for(let i=0;i<lines.length;i++){let line=lines[i]??"",fence=/^\s*(```|~~~)/.exec(line);if(fence){flush();let code=[];while(++i<lines.length&&!(lines[i]??"").trimStart().startsWith(fence[1]??"```"))code.push(lines[i]??"");let pre=document.createElement("pre");pre.append(Object.assign(document.createElement("code"),{textContent:code.join(`
|
|
53
|
-
`)})),fragment.append(pre);continue}if(/^\s*$/.test(line)){flush();continue}let quoted=/^\s*>\s?(.*)$/.exec(line);if(quoted){if(paragraph.length||list)flush();quote.push(quoted[1]??"");continue}let heading=/^\s*(#{1,6})\s+(.*)$/.exec(line);if(heading){flush(),fragment.append(block(`h${Math.min(6,(heading[1]?.length??1)+2)}`,[heading[2]??""]));continue}let item=/^\s*(?:([-*+])|(\d+)[.)])\s+(.*)$/.exec(line);if(item){let tag=item[1]?"ul":"ol";if(paragraph.length||quote.length||list&&list.tagName.toLowerCase()!==tag)flush();if(!list)list=document.createElement(tag),fragment.append(list);list.append(block("li",[item[3]??""]));continue}if(quote.length)flush();if(list&&/^\s{2,}/.test(line)){list.lastElementChild?.append(" ",...inline(line.trim()));continue}list=null,paragraph.push(line.trim())}return flush(),fragment}var hashPrefix="#yuva-discussion-",cacheFor=60000,editWindow=1800000,loads=new Map;function forget(prefix){for(let key of loads.keys())if(key.startsWith(prefix))loads.delete(key)}var svg=(path,size=16)=>`<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${path}</svg>`,icons={up:svg('<path d="M12 19V5M5 12l7-7 7 7"/>'),comment:svg('<path d="M21 12a8 8 0 01-11.6 7.1L4 20l1-4.6A8 8 0 1121 12z"/>'),check:svg('<path d="M20 6L9 17l-5-5"/>'),checkCircle:svg('<circle cx="12" cy="12" r="9"/><path d="M8 12l3 3 5-6"/>'),lock:svg('<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 018 0v4"/>'),clock:svg('<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>'),back:svg('<path d="M19 12H5M12 19l-7-7 7-7"/>'),bell:svg('<path d="M18 8a6 6 0 10-12 0c0 7-3 9-3 9h18s-3-2-3-9M13.7 21a2 2 0 01-3.4 0"/>')},styles=`
|
|
49
|
+
`;class YuvaDocsElement extends Base{static observedAttributes=["channel","server","locale","dir","page","page-title","identity-token"];root;inbox=null;pageUrl="";refused=!1;direction="ltr";#messages=messages;#client=null;#identity=null;#unfollow=null;#settingsFor="";#connected=!1;#accentColor="";constructor(){super();this.root=this.attachShadow({mode:"open"})}get channel(){return this.getAttribute("channel")}set channel(value){this.#attribute("channel",value)}get server(){return(this.getAttribute("server")||(scriptSrc?new URL(scriptSrc).origin:location.origin)).replace(/\/+$/,"")}set server(value){this.#attribute("server",value)}get locale(){return resolveLocale(this.getAttribute("locale"),navigator.language)}set locale(value){this.#attribute("locale",value)}get page(){return this.pageUrl||pageOf(this.getAttribute("page"))}set page(value){this.#attribute("page",value)}get pageTitle(){return this.getAttribute("page-title")||document.title}set pageTitle(value){this.#attribute("page-title",value)}#attribute(name,value){if(value===null||value===void 0||value==="")this.removeAttribute(name);else this.setAttribute(name,value)}setIdentityToken(source){if(this.#identity=source,this.#client?.setIdentityToken(()=>this.#identityToken()),this.#connected&&!this.refused)this.render()}connectedCallback(){this.#connected=!0,this.#unfollow??=followPage(()=>this.#syncPage()),this.pageUrl=pageOf(this.getAttribute("page")),this.#applyLocale(),this.#loadSettings(),this.render(),this.pageChanged()}disconnectedCallback(){this.#connected=!1,this.#unfollow?.(),this.#unfollow=null}attributeChangedCallback(name,previous,value){if(!this.#connected||previous===value)return;if(name==="channel"||name==="server"){this.#client?.reset(),this.#client=null,this.refused=!1,this.inbox=null,this.#settingsFor="",this.#loadSettings(),this.reset(),this.render(),this.pageChanged();return}if(name==="page")return this.#syncPage();if(name==="identity-token")this.#client?.setIdentityToken(()=>this.#identityToken());if(name==="locale"||name==="dir")this.#applyLocale();this.render()}t(descriptor){return translatePlain(this.#messages,descriptor,messages)}client(){return this.#client??=createYuvaClient2({server:this.server,channel:this.channel??"",identityToken:()=>this.#identityToken()}),this.#client}get identified(){return!!this.#identity||this.hasAttribute("identity-token")}get canWrite(){return this.identified||this.inbox?.chat.allow_anonymous!==!1}emit(type,detail){this.dispatchEvent(new CustomEvent(type,{detail,bubbles:!0,composed:!0}))}refusal(error,channelRequest=!0){let refused=error instanceof ApiError2&&(error.code==="origin_not_allowed"||error.code==="page_origin"||channelRequest&&error.status===404);if(refused&&!this.refused)this.refused=!0,console.warn(`Yuva: channel ${this.channel} is unknown or does not allow ${this.pageUrl}`),this.root.replaceChildren();return refused}errorText(error){let code=error instanceof ApiError2?error.code:"";if(code==="rate_limited")return this.t({id:"tzsBOP"});if(code==="network")return this.t({id:"GQVIIl"});if(code==="anonymous_not_allowed"||code==="invalid_identity_token")return this.t({id:"uuIskV"});return this.t({id:"tAL5wg"})}frame(css,...children){let style=el("style");style.textContent=baseStyles+css;let wrapper=el("div","frame");if(wrapper.dir=this.direction,wrapper.lang=this.locale,this.#accentColor)wrapper.style.setProperty("--yuva-accent",this.#accentColor),wrapper.style.setProperty("--yuva-on-accent",contrastOn(this.#accentColor));wrapper.append(...children);let focused=null;try{focused=this.root.activeElement}catch{}if(this.root.replaceChildren(style,wrapper),focused instanceof HTMLElement&&focused.isConnected)focused.focus({preventScroll:!0})}async#identityToken(){return this.#identity?await this.#identity()??null:this.getAttribute("identity-token")}#syncPage(){if(!this.#connected)return;let page=pageOf(this.getAttribute("page"));if(page===this.pageUrl)return;this.pageUrl=page,this.reset(),this.render(),this.pageChanged()}#applyLocale(){let locale=this.locale;this.#messages=catalogs[locale]??messages,this.direction=this.getAttribute("dir")==="rtl"?"rtl":this.getAttribute("dir")==="ltr"?"ltr":directionOf(locale)}#loadSettings(){let channel=this.channel,key=`${this.server} ${channel}`;if(!channel||this.#settingsFor===key)return;this.#settingsFor=key;let stored=readStored(channel).launcher;if(stored?.color)this.#accent(stored.color);let request=settings.get(key);if(!request)request=this.client().channelSettings(),settings.set(key,request),request.catch(()=>settings.delete(key));request.then((inbox)=>{if(this.channel!==channel)return;this.inbox=inbox;let launcher=launcherOf(inbox);if(launcher.color)this.#accent(launcher.color);if(writeStored(channel,{...readStored(channel),launcher}),!this.refused)this.render()}).catch((error)=>{if(this.channel===channel)this.refusal(error)})}#accent(color){if(!/^#[0-9a-f]{6}$/i.test(color))return;this.#accentColor=color}}var hashPrefix="#yuva-discussion-",cacheFor=60000,loads=new Map;function forget(prefix){for(let key of loads.keys())if(key.startsWith(prefix))loads.delete(key)}var svg=(path)=>`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${path}</svg>`,icons={up:svg('<path d="M12 19V5M5 12l7-7 7 7"/>'),comment:svg('<path d="M21 12a8 8 0 01-11.6 7.1L4 20l1-4.6A8 8 0 1121 12z"/>'),check:svg('<path d="M20 6L9 17l-5-5"/>'),lock:svg('<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 018 0v4"/>'),clock:svg('<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>')},styles=`
|
|
54
50
|
.frame { display: flex; flex-direction: column; gap: 16px; }
|
|
55
51
|
:host { --yuva-success: #1a7f37; --yuva-warn: #9a6700; }
|
|
56
52
|
@media (prefers-color-scheme: dark) { :host { --yuva-success: #3fb950; --yuva-warn: #d29922; } }
|
|
@@ -105,69 +101,16 @@ button { font: inherit; color: inherit; }
|
|
|
105
101
|
.badge.locked { opacity: 0.75; }
|
|
106
102
|
.empty { padding: 28px 16px; text-align: center; border: 1px dashed var(--yuva-border); border-radius: 12px; }
|
|
107
103
|
.empty p + p { margin-block-start: 4px; }
|
|
108
|
-
.thread { display: flex; flex-direction: column; gap: 12px; }
|
|
109
|
-
.thread-head { display: flex; flex-direction: column; gap: 8px; }
|
|
110
|
-
.post { display: flex; gap: 12px; padding: 14px; border: 1px solid var(--yuva-border); border-radius: 12px; }
|
|
111
|
-
.post.accepted { border-color: var(--yuva-success); box-shadow: inset 0 0 0 1px var(--yuva-success); }
|
|
112
|
-
.post.pending { border-style: dashed; }
|
|
113
|
-
.side { display: flex; flex-direction: column; align-items: center; gap: 6px; }
|
|
114
|
-
.vote {
|
|
115
|
-
display: inline-flex; flex-direction: column; align-items: center; gap: 0; min-inline-size: 40px; padding: 4px 6px;
|
|
116
|
-
border: 1px solid var(--yuva-border); border-radius: 8px; background: none; cursor: pointer; font-size: 0.85em; font-weight: 600;
|
|
117
|
-
}
|
|
118
|
-
.vote:hover:not(:disabled) { border-color: var(--yuva-accent); }
|
|
119
|
-
.vote[aria-pressed="true"] { border-color: var(--yuva-accent); color: var(--yuva-accent); background: var(--yuva-soft); }
|
|
120
|
-
.post-body { flex: 1; min-inline-size: 0; display: flex; flex-direction: column; gap: 8px; }
|
|
121
|
-
.post-head { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 8px; font-size: 0.88em; }
|
|
122
|
-
.name { font-weight: 600; }
|
|
123
|
-
.answer-label { display: flex; align-items: center; gap: 6px; color: var(--yuva-success); font-weight: 600; font-size: 0.85em; }
|
|
124
|
-
.tools { display: flex; flex-wrap: wrap; gap: 4px 8px; align-items: center; }
|
|
125
|
-
.children { display: flex; flex-direction: column; gap: 10px; margin-block-start: 4px; padding-inline-start: 14px; border-inline-start: 2px solid var(--yuva-border); }
|
|
126
|
-
.children .post { padding: 10px 0; border: 0; box-shadow: none; }
|
|
127
|
-
.children .post + .post { border-block-start: 1px solid var(--yuva-border); border-radius: 0; }
|
|
128
|
-
.deleted { font-style: italic; opacity: 0.65; }
|
|
129
104
|
.notice { padding: 10px 12px; border-radius: 10px; background: var(--yuva-soft); font-size: 0.9em; display: flex; gap: 8px; align-items: flex-start; }
|
|
130
105
|
.notice svg { flex-shrink: 0; margin-block-start: 3px; }
|
|
131
|
-
.signin { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 8px 16px; padding: 14px; border: 1px solid var(--yuva-border); border-radius: 12px; }
|
|
132
|
-
.composer { display: flex; flex-direction: column; border: 1px solid var(--yuva-border); border-radius: 12px; overflow: hidden; }
|
|
133
|
-
.composer:focus-within { border-color: var(--yuva-accent); }
|
|
134
|
-
.composer .ctabs { display: flex; gap: 4px; padding: 0 8px; border-block-end: 1px solid var(--yuva-border); }
|
|
135
|
-
.composer .ctab { padding: 7px 10px; border: 0; border-block-end: 2px solid transparent; background: none; cursor: pointer; font-size: 0.88em; opacity: 0.75; margin-block-end: -1px; }
|
|
136
|
-
.composer .ctab[aria-selected="true"] { border-block-end-color: var(--yuva-accent); font-weight: 600; opacity: 1; }
|
|
137
|
-
.composer .ctab:focus-visible { outline: 2px solid var(--yuva-accent); outline-offset: -2px; }
|
|
138
|
-
.composer textarea, .composer .preview { border: 0; border-radius: 0; min-block-size: 110px; padding: 10px 12px; }
|
|
139
|
-
.composer textarea:focus-visible { outline: none; }
|
|
140
|
-
.composer .preview { overflow-wrap: anywhere; }
|
|
141
|
-
.composer .foot { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; justify-content: space-between; padding: 8px 10px; border-block-start: 1px solid var(--yuva-border); }
|
|
142
|
-
.composer .hint { font-size: 0.8em; opacity: 0.7; }
|
|
143
|
-
.composer .buttons { display: flex; gap: 8px; margin-inline-start: auto; }
|
|
144
|
-
.field-title { font-size: 1.05em; font-weight: 600; }
|
|
145
|
-
.form { display: flex; flex-direction: column; gap: 10px; }
|
|
146
106
|
.more { align-self: center; }
|
|
147
|
-
.md { overflow-wrap: anywhere; }
|
|
148
|
-
.md > :first-child { margin-block-start: 0; }
|
|
149
|
-
.md > :last-child { margin-block-end: 0; }
|
|
150
|
-
.md p, .md ul, .md ol, .md pre, .md blockquote, .md table { margin: 0 0 0.75em; }
|
|
151
|
-
.md h1, .md h2, .md h3, .md h4, .md h5, .md h6 { margin: 0.9em 0 0.4em; font-size: 1em; font-weight: 600; }
|
|
152
|
-
.md h1, .md h3 { font-size: 1.1em; }
|
|
153
|
-
.md ul, .md ol { padding-inline-start: 1.5em; }
|
|
154
|
-
.md a { color: var(--yuva-accent); }
|
|
155
|
-
.md code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.88em; padding: 1px 5px; border-radius: 5px; background: var(--yuva-soft); }
|
|
156
|
-
.md pre { padding: 10px 12px; border-radius: 8px; background: var(--yuva-soft); overflow-x: auto; }
|
|
157
|
-
.md pre code { padding: 0; background: none; }
|
|
158
|
-
.md blockquote { padding-inline-start: 12px; border-inline-start: 3px solid var(--yuva-border); opacity: 0.85; }
|
|
159
|
-
.md table { border-collapse: collapse; display: block; overflow-x: auto; }
|
|
160
|
-
.md th, .md td { border: 1px solid var(--yuva-border); padding: 4px 8px; }
|
|
161
|
-
.md img { max-inline-size: 100%; }
|
|
162
|
-
.md hr { border: 0; border-block-start: 1px solid var(--yuva-border); }
|
|
163
107
|
.skeleton { block-size: 64px; border-radius: 12px; background: var(--yuva-soft); }
|
|
164
108
|
@media (max-width: 560px) {
|
|
165
109
|
.item { gap: 10px; padding: 12px; }
|
|
166
110
|
.item .avatar { display: none; }
|
|
167
|
-
.post { padding: 12px; gap: 10px; }
|
|
168
111
|
.bar .send { inline-size: 100%; }
|
|
169
112
|
}
|
|
170
|
-
`;function hue(text){let hash=0;for(let char of text)hash=hash*31+char.charCodeAt(0)|0;return Math.abs(hash)%360}function excerptOf(html){let template=document.createElement("template");return template.innerHTML=html,(template.content.textContent??"").replace(/\s+/g," ").trim().slice(0,240)}class Composer{area=el("textarea");previewing=!1;constructor(rows){this.area.rows=rows,this.area.maxLength=20000,this.area.dir="auto"}get value(){return this.area.value.trim()}clear(){this.area.value="",this.previewing=!1}}class YuvaDiscussionsElement extends YuvaDocsElement{#view={kind:"list"};#sort="new";#items=[];#cursor;#listState="loading";#loadedFor="";#thread=null;#threadState="loading";#writer=null;#reader=null;#offReader=null;#busy=new Set;#notice="";#error="";#confirm="";#reply=new Composer(4);#inline=null;#edit=null;#draft=new Composer(6);#title=el("input");#focus="";constructor(){super();this.#title.maxLength=200,this.#title.dir="auto",this.#title.className="field-title";for(let area of[this.#reply.area,this.#draft.area])area.addEventListener("input",()=>this.#syncSend());this.#title.addEventListener("input",()=>this.#syncSend())}get discussions(){return this.#items}get reader(){return this.#reader}#hashChanged=()=>this.#fromHash();connectedCallback(){super.connectedCallback(),window.addEventListener("hashchange",this.#hashChanged),this.#watchReader()}disconnectedCallback(){super.disconnectedCallback(),window.removeEventListener("hashchange",this.#hashChanged),this.#offReader?.(),this.#offReader=null}attributeChangedCallback(name,previous,value){if(super.attributeChangedCallback(name,previous,value),previous===value||!this.isConnected)return;if(name==="channel"||name==="server")this.#offReader?.(),this.#offReader=null,this.#watchReader();else if(name==="identity-token")this.#refreshWriter(!0)}setIdentityToken(source){super.setIdentityToken(source),this.#refreshWriter(!0)}#watchReader(){if(!this.channel||this.#offReader)return;let client=this.client();this.#reader=client.reader,this.#offReader=client.on("reader",(reader)=>{this.#reader=reader,this.emit("yuva-reader",reader?reader.reader:null),this.#refreshWriter(!0)}),this.#refreshWriter(!1)}async#refreshWriter(reload){if(!this.channel)return;let writer=await this.client().discussionWriter().catch(()=>null),changed=writer!==this.#writer;if(this.#writer=writer,reload&&changed){if(this.#loadedFor="",this.#load(!1),this.#view.kind==="thread")this.#open(this.#view.id,!1)}this.render()}reset(){this.#view={kind:"list"},this.#items=[],this.#cursor=void 0,this.#listState="loading",this.#loadedFor="",this.#thread=null,this.#notice="",this.#error="",this.#confirm="",this.#inline=null,this.#edit=null,this.#reply.clear()}pageChanged(){this.#load(!1),this.#fromHash()}#linked(){let hash=location.hash;return hash.startsWith(hashPrefix)?decodeURIComponent(hash.slice(hashPrefix.length)):""}#fromHash(){let id=this.#linked();if(!id||!this.channel||this.refused)return;if(this.#view.kind==="thread"&&this.#view.id===id)return;this.#inline=null,this.#edit=null,this.#confirm="",this.#open(id,!0),this.scrollIntoView({block:"start"})}reload(){return this.#load(!0)}open(id){return this.#open(id,!0)}signIn(){return this.#error="",this.client().readerSignIn().then(()=>{return}).catch((error)=>{let code=error instanceof ApiError2?error.code:"";if(code==="sign_in_cancelled")return;this.#error=code==="popup_blocked"?this.t({id:"nW3go1"}):this.#failure(error),this.render()})}signOut(){return this.client().readerSignOut()}get#prefix(){return`${this.server} ${this.channel} ${this.pageUrl} `}async#load(force,more=!1){let page=this.pageUrl;if(!this.channel||!page||this.refused)return;let reader=this.client().reader,auth=reader?reader.token.slice(-12):this.#writer??"-",key=`${this.#prefix}${this.#sort} ${auth}`;if(!force&&!more&&this.#loadedFor===key)return;this.#loadedFor=key;let request;if(more)request=this.client().listDiscussions(page,{sort:this.#sort,cursor:this.#cursor});else{let load=loads.get(key);if(force||!load||Date.now()-load.at>cacheFor){load={at:Date.now(),request:this.client().listDiscussions(page,{sort:this.#sort})},loads.set(key,load);let current=load;load.request.catch(()=>loads.get(key)===current&&loads.delete(key))}if(request=load.request,!this.#items.length)this.#listState="loading"}if(more)this.#busy.add("more");this.render();try{let result=await request;if(this.#loadedFor!==key)return;this.#items=more?[...this.#items,...result.items.filter((d)=>!this.#items.some((i)=>i.id===d.id))]:result.items,this.#cursor=result.next_cursor,this.#listState="ready"}catch(error){if(this.#loadedFor!==key||this.refusal(error))return;if(!more)this.#loadedFor="";if(this.#listState=error instanceof ApiError2&&error.code==="discussions_off"?"off":more?"ready":"error",more)this.#error=this.#failure(error)}finally{this.#busy.delete("more")}this.render()}async#open(id,focus){let page=this.pageUrl,known=this.#thread?.discussion.id===id?this.#thread:null;this.#view={kind:"thread",id};let listed=this.#items.find((d)=>d.id===id);if(this.#thread=known??(listed?{discussion:listed,posts:[]}:null),this.#threadState=known?"ready":"loading",focus)this.#notice=known?this.#notice:"",this.#error="",this.#focus="thread-title";this.render();try{let detail=await this.client().getDiscussion(id);if(this.pageUrl!==page||this.#view.kind!=="thread"||this.#view.id!==id)return;let titled=!!this.#thread;if(this.#thread=detail,this.#threadState="ready",focus&&!titled)this.#focus="thread-title";this.#items=this.#items.map((d)=>d.id===id?detail.discussion:d)}catch(error){if(this.pageUrl!==page||this.#view.kind!=="thread"||this.#view.id!==id)return;if(this.refusal(error,!1))return;this.#threadState=error instanceof ApiError2&&error.status===404?"missing":"error"}this.render()}#toList(){if(this.#linked()){let url=new URL(location.href);url.hash="",history.replaceState(history.state,"",url.href)}this.#view={kind:"list"},this.#inline=null,this.#edit=null,this.#confirm="",this.#error="",this.#focus=this.#thread?`open-${this.#thread.discussion.id}`:"start",this.render(),this.#load(!1)}#failure(error){let code=error instanceof ApiError2?error.code:"";if(code==="sign_in_required")return this.t({id:"LwDe8g"});if(code==="discussion_locked")return this.t({id:"KEjhwb"});if(code==="edit_window_closed")return this.t({id:"b_f4xj"});if(code==="discussions_off")return this.t({id:"tayT8P"});if(code==="forbidden")return this.t({id:"8Ekoev"});if(code==="validation_failed")return this.t({id:"Su3Vyp"});return this.errorText(error)}async#act(key,action){if(this.#busy.has(key))return;this.#busy.add(key),this.#error="",this.render();try{return await action()}catch(error){if(!this.refusal(error,!1))this.#error=this.#failure(error);if(error instanceof ApiError2&&error.code==="sign_in_required")this.#refreshWriter(!1);return}finally{this.#busy.delete(key),this.render()}}async#start(){let title=this.#title.value.trim(),body=this.#draft.value;if(title.length<3||!body)return;let page=this.pageUrl,discussion=await this.#act("start",()=>this.client().startDiscussion({page_url:page,page_title:this.pageTitle||void 0,title,body}));if(!discussion)return;if(forget(this.#prefix),this.emit("yuva-discussion",{page,discussion_id:discussion.id,state:discussion.state}),this.pageUrl!==page)return;this.#title.value="",this.#draft.clear(),this.#items=[discussion,...this.#items.filter((d)=>d.id!==discussion.id)],this.#notice=discussion.state==="pending"?this.t({id:"NrGspR"}):"",this.#thread={discussion,posts:[]},await this.#open(discussion.id,!0)}async#send(composer,parent){let thread=this.#thread,body=composer.value;if(!thread||!body)return;let page=this.pageUrl,id=thread.discussion.id,post=await this.#act(parent?`reply-${parent}`:"reply",()=>this.client().replyToDiscussion(id,{body,parent_post_id:parent}));if(!post)return;if(forget(this.#prefix),this.emit("yuva-post",{page,discussion_id:id,post_id:post.id,state:post.state}),composer.clear(),parent)this.#inline=null;if(this.#notice=post.state==="pending"?this.t({id:"YZayoP"}):"",this.#thread?.discussion.id===id)this.#thread={...this.#thread,posts:[...this.#thread.posts,post]},this.#focus=`post-${post.id}`,this.render(),this.#open(id,!1)}async#vote(post,opening){if(!this.#writer)return void this.signIn();let updated=await this.#act(`vote-${post.id}`,()=>this.client().voteDiscussionPost(post.id,!post.voted));if(!updated||!this.#thread)return;if(forget(this.#prefix),opening){let discussion={...this.#thread.discussion,votes:updated.votes,voted:updated.voted};this.#thread={...this.#thread,discussion},this.#items=this.#items.map((d)=>d.id===discussion.id?discussion:d)}else this.#thread={...this.#thread,posts:this.#thread.posts.map((p)=>p.id===updated.id?{...p,...updated}:p)}}async#follow(){let thread=this.#thread;if(!thread)return;if(!this.#writer)return void this.signIn();let following=!thread.discussion.following;if(await this.#act("follow",()=>this.client().followDiscussion(thread.discussion.id,following).then(()=>!0))&&this.#thread?.discussion.id===thread.discussion.id)this.#thread={...this.#thread,discussion:{...this.#thread.discussion,following}}}async#accept(post){let thread=this.#thread;if(!thread)return;let discussion=await this.#act(`accept-${post?.id??"clear"}`,()=>this.client().acceptDiscussionAnswer(thread.discussion.id,post?.id??null));if(!discussion)return;forget(this.#prefix),this.#focus=post?`post-${post.id}`:"thread-title",await this.#open(discussion.id,!1)}async#saveEdit(){let edit=this.#edit,thread=this.#thread;if(!edit||!thread)return;let body=edit.composer.value,opening=!edit.post,title=edit.title.value.trim();if(!body||opening&&title.length<3)return;let postId=edit.post?.id??thread.discussion.opening_post_id;if(!await this.#act(`edit-${postId}`,()=>this.client().editDiscussionPost(postId,opening?{body,title}:{body})))return;forget(this.#prefix),this.#edit=null,this.#focus=opening?"thread-title":`post-${postId}`,await this.#open(thread.discussion.id,!1)}async#delete(postId,opening){let thread=this.#thread;if(!thread)return;let done=await this.#act(`delete-${postId}`,()=>this.client().deleteDiscussionPost(postId).then(()=>!0));if(this.#confirm="",!done)return;if(forget(this.#prefix),opening)try{await this.client().getDiscussion(thread.discussion.id)}catch{return this.#items=this.#items.filter((d)=>d.id!==thread.discussion.id),this.#thread=null,this.#toList()}await this.#open(thread.discussion.id,!1)}#syncSend(){for(let button of this.root.querySelectorAll("[data-requires]")){let needs=button.dataset.requires,busy=this.#busy.has(button.dataset.busy??""),ok=needs==="start"?this.#title.value.trim().length>=3&&this.#draft.value!=="":needs==="reply"?this.#reply.value!=="":needs==="inline"?!!this.#inline?.composer.value:needs==="edit"?!!this.#edit?.composer.value&&(!!this.#edit.post||this.#edit.title.value.trim().length>=3):!0;button.disabled=busy||!ok}}get#mode(){return this.inbox?.chat.discussions??"moderated"}#button(className,text,key,onClick,html=""){let button=el("button",className);if(button.type="button",html)button.innerHTML=html;return button.append(text),button.dataset.key=key,button.addEventListener("click",onClick),button}#authorName(author){if(author.deleted)return author.kind==="member"?this.t({id:"-UxBoG"}):this.t({id:"FMWGhb"});if(author.kind==="anonymous")return this.t({id:"D9CFV5"});return author.name||(author.kind==="member"?this.t({id:"nLqMRA"}):this.t({id:"zmA6sS"}))}#avatar(author,small=!1){let avatar=el("span",`avatar${small?" small":""}`,author.deleted?"":author.initials||"?");if(avatar.setAttribute("aria-hidden","true"),author.deleted||author.kind==="anonymous")avatar.classList.add("gone");else if(author.kind==="member")avatar.classList.add("team");else avatar.style.setProperty("--avatar",`hsl(${hue(author.name||author.initials)} 45% 42%)`);return avatar}#badge(kind,short=!1){let text=kind==="answered"?this.t({id:"GqCA_t"}):kind==="pending"?short?this.t({id:"UbRKMZ"}):this.t({id:"lWv8id"}):kind==="team"?this.t({id:"KM6m8p"}):this.t({id:"G2fuEb"}),badge=el("span",`badge ${kind}`);if(kind!=="team")badge.innerHTML=kind==="answered"?icons.check:kind==="pending"?icons.clock:icons.lock;return badge.append(text),badge}#time(value){let time=el("time");time.dateTime=value;let date=new Date(value);time.title=date.toLocaleString(this.locale);let seconds=(date.getTime()-Date.now())/1000,steps=[["second",60],["minute",60],["hour",24],["day",30],["month",12],["year",1/0]],amount=seconds;for(let[unit,size]of steps){if(Math.abs(amount)<size){time.textContent=unit==="second"?this.t({id:"xOTzt5"}):new Intl.RelativeTimeFormat(this.locale,{numeric:"auto"}).format(Math.round(amount),unit);break}amount/=size}return time}#md(html){let body=el("div","md");body.dir="auto",body.innerHTML=html;for(let link of body.querySelectorAll("a[href]"))link.setAttribute("target","_blank");return body}#composer(composer,options){let box=el("div","composer"),tabs=el("div","ctabs");tabs.setAttribute("role","tablist"),tabs.setAttribute("aria-label",options.label);let panelId=`p-${options.focusKey}`,write=this.#button("ctab",this.t({id:"i4_LY_"}),`${options.focusKey}-write`,()=>{composer.previewing=!1,this.#focus=options.focusKey,this.render()}),show=this.#button("ctab",this.t({id:"rdUucN"}),`${options.focusKey}-preview`,()=>{composer.previewing=!0,this.render()});for(let[tab,selected]of[[write,!composer.previewing],[show,composer.previewing]])tab.setAttribute("role","tab"),tab.setAttribute("aria-selected",String(selected)),tab.setAttribute("aria-controls",panelId),tab.tabIndex=selected?0:-1,tab.addEventListener("keydown",(event)=>{if(event.key!=="ArrowLeft"&&event.key!=="ArrowRight")return;event.preventDefault(),composer.previewing=!composer.previewing,this.#focus=`${options.focusKey}-${composer.previewing?"preview":"write"}`,this.render()});if(tabs.append(write,show),box.append(tabs),composer.previewing){let panel=el("div","preview md");if(panel.dir="auto",panel.id=panelId,panel.setAttribute("role","tabpanel"),panel.setAttribute("aria-label",this.t({id:"rdUucN"})),composer.value)panel.append(preview(composer.area.value));else panel.append(el("p","muted",this.t({id:"3PqJQG"})));box.append(panel)}else composer.area.id=panelId,composer.area.placeholder=options.placeholder,composer.area.setAttribute("aria-label",options.label),composer.area.dataset.key=options.focusKey,composer.area.disabled=this.#busy.has(options.busy),composer.area.onkeydown=(event)=>{if(event.key==="Enter"&&(event.metaKey||event.ctrlKey))event.preventDefault(),options.onSubmit();else if(event.key==="Escape"&&options.onCancel)options.onCancel()},box.append(composer.area);let foot=el("div","foot");foot.append(el("span","hint",this.t({id:"Vwy_nT"})));let buttons=el("div","buttons");if(options.onCancel)buttons.append(this.#button("ghost",this.t({id:"dEgA5A"}),`${options.focusKey}-cancel`,options.onCancel));let submit=this.#button("send",this.#busy.has(options.busy)?this.t({id:"Sad2tK"}):options.submit,`${options.focusKey}-submit`,options.onSubmit);return submit.dataset.requires=options.requires,submit.dataset.busy=options.busy,buttons.append(submit),foot.append(buttons),box.append(foot),box}#signInBox(text){let box=el("div","signin");return box.append(el("p","",text)),box.append(this.#button("send",this.t({id:"5lWFkC"}),"sign-in-box",()=>void this.signIn())),box}#header(){let head=el("div","head");head.append(el("h2","",this.t({id:"7oGBMv"})));let who=el("div","who"),reader=this.#reader;if(reader){let name=reader.reader.name||this.t({id:"zmA6sS"});who.append(this.#avatar({kind:"reader",name,initials:reader.reader.initials,deleted:!1},!0)),who.append(el("span","",name)),who.append(this.#button("plain",this.t({id:"fcWrnU"}),"sign-out",()=>void this.signOut()))}else if(!this.#writer&&this.#mode!=="off")who.append(this.#button("ghost",this.t({id:"5lWFkC"}),"sign-in",()=>void this.signIn()));return head.append(who),head}#listView(){let nodes=[],bar=el("div","bar"),tabs=el("div","tabs");tabs.setAttribute("role","tablist"),tabs.setAttribute("aria-label",this.t({id:"78dEKp"}));let sorts=[["new",this.t({id:"isRobC"})],["top",this.t({id:"WWy8TN"})],["unanswered",this.t({id:"2lF8Zj"})]];sorts.forEach(([sort,label],index)=>{let tab=this.#button("tab",label,`sort-${sort}`,()=>this.#setSort(sort));tab.setAttribute("role","tab"),tab.setAttribute("aria-selected",String(this.#sort===sort)),tab.setAttribute("aria-controls","yuva-discussion-list"),tab.tabIndex=this.#sort===sort?0:-1,tab.addEventListener("keydown",(event)=>{let step=event.key==="ArrowRight"?1:event.key==="ArrowLeft"?-1:0;if(!step)return;event.preventDefault();let forward=this.direction==="rtl"?-step:step,next=sorts[(index+forward+sorts.length)%sorts.length];if(next)this.#setSort(next[0])}),tabs.append(tab)});let start=this.#button("send",this.t({id:"z1qf6l"}),"start",()=>{this.#view={kind:"new"},this.#error="",this.#notice="",this.#focus="new-title",this.render()});if(bar.append(tabs,start),nodes.push(bar),this.#listState==="loading"&&!this.#items.length){let skeleton=el("div","skeleton");return skeleton.setAttribute("aria-busy","true"),skeleton.setAttribute("aria-label",this.t({id:"pzatAP"})),nodes.push(skeleton),nodes}if(this.#listState==="error"&&!this.#items.length){let box=el("div","empty");box.append(el("p","",this.t({id:"MDmQKn"})));let retry=this.#button("ghost",this.t({id:"KDw4GX"}),"retry",()=>void this.#load(!0));return retry.style.marginBlockStart="8px",box.append(retry),nodes.push(box),nodes}if(!this.#items.length){let box=el("div","empty");if(box.append(el("p","",this.#sort==="unanswered"?this.t({id:"twEQ41"}):this.t({id:"rpfOwz"}))),this.#sort!=="unanswered")box.append(el("p","muted",this.t({id:"b6Orhy"})));return nodes.push(box),nodes}let list=el("ul","list");list.id="yuva-discussion-list",list.setAttribute("aria-label",this.t({id:"j-3eim"})),list.setAttribute("aria-busy",String(this.#listState==="loading"));for(let discussion of this.#items){let item=el("li","item");item.append(this.#avatar(discussion.author));let main=el("div","main"),title=this.#button("title",discussion.title,`open-${discussion.id}`,()=>void this.#open(discussion.id,!0));title.dir="auto",main.append(title);let excerpt=discussion.deleted?"":excerptOf(discussion.body_html);if(excerpt){let text=el("p","excerpt",excerpt);text.dir="auto",main.append(text)}let meta=el("div","meta");if(meta.append(el("span","",this.#authorName(discussion.author)),this.#time(discussion.created_at)),discussion.author.kind==="member"&&!discussion.author.deleted)meta.append(this.#badge("team"));if(discussion.answer_post_id)meta.append(this.#badge("answered"));if(discussion.state==="pending")meta.append(this.#badge("pending"));if(discussion.locked)meta.append(this.#badge("locked"));main.append(meta);let counts=el("div","counts"),votes=el("span","count");votes.innerHTML=icons.up,votes.append(String(discussion.votes)),votes.setAttribute("aria-label",this.t({id:"8ntmc1",values:{0:discussion.votes}})),votes.title=votes.getAttribute("aria-label")??"";let replies=el("span","count");replies.innerHTML=icons.comment,replies.append(String(discussion.reply_count)),replies.setAttribute("aria-label",this.t({id:"Hw3P48",values:{0:discussion.reply_count}})),replies.title=replies.getAttribute("aria-label")??"",counts.append(votes,replies),item.append(main,counts),list.append(item)}if(nodes.push(list),this.#cursor){let more=this.#button("ghost more",this.#busy.has("more")?this.t({id:"Pwqkdw"}):this.t({id:"fMPkxb"}),"more",()=>void this.#load(!1,!0));more.disabled=this.#busy.has("more"),nodes.push(more)}return nodes}#setSort(sort){if(this.#sort===sort)return;this.#sort=sort,this.#items=[],this.#cursor=void 0,this.#listState="loading",this.#focus=`sort-${sort}`,this.#load(!1)}#back(){let back=this.#button("plain",this.t({id:"3CApMv"}),"back",()=>this.#toList(),icons.back);back.style.alignSelf="flex-start",back.style.display="inline-flex",back.style.gap="6px",back.style.alignItems="center";let arrow=back.querySelector("svg");if(arrow&&this.direction==="rtl")arrow.style.transform="scaleX(-1)";return back}#newView(){let form=el("div","form");if(form.append(el("h3","",this.t({id:"z1qf6l"}))),!this.#writer)return form.append(this.#signInBox(this.t({id:"99w-GZ"}))),[this.#back(),form];if(this.#title.placeholder=this.t({id:"MHrjPM"}),this.#title.setAttribute("aria-label",this.t({id:"MHrjPM"})),this.#title.dataset.key="new-title",this.#title.disabled=this.#busy.has("start"),form.append(this.#title),form.append(this.#composer(this.#draft,{label:this.t({id:"PN38hZ"}),placeholder:this.t({id:"NjUiZ4"}),submit:this.t({id:"n5vqdp"}),busy:"start",requires:"start",focusKey:"new-body",onSubmit:()=>void this.#start(),onCancel:()=>this.#toList()})),this.#mode==="moderated"&&this.#reader)form.append(el("p","muted",this.t({id:"RqsQKK"})));return[this.#back(),form]}#editable(post){return!!post.mine&&!this.#thread?.discussion.locked&&Date.now()-Date.parse(post.created_at)<editWindow}#postTools(post,top){let thread=this.#thread;if(!thread)return null;let discussion=thread.discussion,opening=!post,id=post?.id??discussion.opening_post_id,mine=opening?!!discussion.mine:!!post.mine,deleted=opening?!!discussion.deleted:post.deleted,tools=el("div","tools");if(deleted)return null;if(!opening&&top&&!discussion.locked&&this.#writer&&post.state==="published")tools.append(this.#button("plain",this.t({id:"ImOQa9"}),`reply-to-${post.id}`,()=>{this.#inline=this.#inline?.target===top.id?this.#inline:{target:top.id,composer:new Composer(3)},this.#inline.composer.area.oninput=()=>this.#syncSend(),this.#focus=`inline-${top.id}`,this.render()}));if(!opening&&discussion.mine&&!post.parent_post_id&&post.state==="published"&&!discussion.locked){let accepted=discussion.answer_post_id===post.id,accept=this.#button("plain",accepted?this.t({id:"4-S4QM"}):this.t({id:"jhu92n"}),`accept-${post.id}`,()=>void this.#accept(accepted?null:post),accepted?"":icons.checkCircle);accept.style.display="inline-flex",accept.style.gap="4px",accept.style.alignItems="center",accept.disabled=this.#busy.has(`accept-${post.id}`)||this.#busy.has("accept-clear"),tools.append(accept)}if(mine&&this.#editable(opening?discussion:post))tools.append(this.#button("plain",this.t({id:"ePK91l"}),`edit-${id}`,()=>{let composer=new Composer(opening?6:4);composer.area.value=opening?discussion.body:post.body,composer.area.oninput=()=>this.#syncSend();let title=el("input");title.className="field-title",title.maxLength=200,title.dir="auto",title.value=discussion.title,title.oninput=()=>this.#syncSend(),this.#edit={post,composer,title},this.#focus=opening?"edit-title":`edit-body-${id}`,this.render()}));if(mine)if(this.#confirm===id){let yes=this.#button("plain danger",this.t({id:"cnGeoo"}),`delete-yes-${id}`,()=>void this.#delete(id,opening));yes.disabled=this.#busy.has(`delete-${id}`),tools.append(el("span","muted",opening?this.t({id:"rAl91-"}):this.t({id:"Klsidc"})),yes,this.#button("plain",this.t({id:"PZ_kxo"}),`delete-no-${id}`,()=>{this.#confirm="",this.#focus=`delete-${id}`,this.render()}))}else tools.append(this.#button("plain",this.t({id:"cnGeoo"}),`delete-${id}`,()=>{this.#confirm=id,this.#focus=`delete-no-${id}`,this.render()}));return tools.childElementCount?tools:null}#voteButton(target,opening){let vote=this.#button("vote",String(target.votes),`vote-${target.id}`,()=>void this.#vote(target,opening),icons.up);return vote.setAttribute("aria-pressed",String(!!target.voted)),vote.setAttribute("aria-label",target.voted?this.t({id:"OVijcR",values:{0:target.votes}}):this.t({id:"dNOvhg",values:{0:target.votes}})),vote.disabled=!!target.mine||!!this.#thread?.discussion.locked||this.#busy.has(`vote-${target.id}`),vote}#postCard(post,top,children=[]){let accepted=this.#thread.discussion.answer_post_id===post.id,card=el("article",`post${accepted?" accepted":""}${post.state==="pending"?" pending":""}`);card.dataset.key=`post-${post.id}`,card.tabIndex=-1,card.setAttribute("aria-label",this.#authorName(post.author));let side=el("div","side");if(!post.deleted)side.append(this.#voteButton(post,!1));if(!top||top.id===post.id)card.append(side);let body=el("div","post-body");if(accepted){let label=el("div","answer-label");label.innerHTML=icons.checkCircle,label.append(this.t({id:"y-KXxN"})),body.append(label)}if(body.append(this.#postHead(post.author,post.created_at,post.edited_at,post.state,post.deleted)),this.#edit?.post?.id===post.id)body.append(this.#editForm());else if(post.deleted)body.append(el("p","deleted",this.t({id:"HkXOWm"})));else body.append(this.#md(post.body_html));let tools=this.#postTools(post,top);if(tools)body.append(tools);if(children.length||this.#inline?.target===post.id){let nested=el("div","children");for(let child of children)nested.append(this.#postCard(child,post));if(this.#inline?.target===post.id){let inline=this.#inline;nested.append(this.#composer(inline.composer,{label:this.t({id:"F_vGso"}),placeholder:this.t({id:"2Hlmdt"}),submit:this.t({id:"ImOQa9"}),busy:`reply-${post.id}`,requires:"inline",focusKey:`inline-${post.id}`,onSubmit:()=>void this.#send(inline.composer,post.id),onCancel:()=>{this.#inline=null,this.#focus=`reply-to-${post.id}`,this.render()}}))}body.append(nested)}return card.append(body),card}#postHead(author,created,edited,state,deleted){let head=el("div","post-head");if(!deleted){if(head.append(this.#avatar(author,!0),el("span","name",this.#authorName(author))),author.kind==="member"&&!author.deleted)head.append(this.#badge("team"))}if(head.append(this.#time(created)),edited&&!deleted)head.append(el("span","muted",this.t({id:"k4b5_X"})));if(state==="pending")head.append(this.#badge("pending"));return head}#editForm(){let edit=this.#edit,form=el("div","form");if(!edit.post)edit.title.setAttribute("aria-label",this.t({id:"MHrjPM"})),edit.title.dataset.key="edit-title",form.append(edit.title);let id=edit.post?.id??this.#thread.discussion.opening_post_id;return form.append(this.#composer(edit.composer,{label:this.t({id:"qzVesX"}),placeholder:"",submit:this.t({id:"tfDRzk"}),busy:`edit-${id}`,requires:"edit",focusKey:`edit-body-${id}`,onSubmit:()=>void this.#saveEdit(),onCancel:()=>{this.#edit=null,this.#focus=`edit-${id}`,this.render()}})),form}#threadView(){let nodes=[this.#back()],thread=this.#thread;if(!thread||this.#threadState==="missing"){let box=el("div","empty");return box.append(el("p","",this.#threadState==="loading"?this.t({id:"Pwqkdw"}):this.t({id:"VGqKyv"}))),nodes.push(box),nodes}let discussion=thread.discussion,view=el("div","thread"),head=el("div","thread-head");if(this.#edit&&!this.#edit.post)head.append(this.#postHead(discussion.author,discussion.created_at,discussion.edited_at,discussion.state,!1)),head.append(this.#editForm()),view.append(head);else{let title=el("h3","",discussion.title);title.dir="auto",title.tabIndex=-1,title.dataset.key="thread-title",head.append(title);let meta=el("div","meta");if(discussion.answer_post_id)meta.append(this.#badge("answered"));if(discussion.state==="pending")meta.append(this.#badge("pending"));if(discussion.locked)meta.append(this.#badge("locked"));if(meta.childElementCount)head.append(meta);view.append(head);let opening=el("article",`post${discussion.state==="pending"?" pending":""}`),side=el("div","side");if(!discussion.deleted)side.append(this.#voteButton({id:discussion.opening_post_id,votes:discussion.votes,voted:discussion.voted,mine:discussion.mine},!0));let body=el("div","post-body");body.append(this.#postHead(discussion.author,discussion.created_at,discussion.edited_at,discussion.state,!!discussion.deleted)),body.append(discussion.deleted?el("p","deleted",this.t({id:"8wRl7c"})):this.#md(discussion.body_html));let tools=this.#postTools(null,null);if(tools)body.append(tools);opening.append(side,body),view.append(opening)}let actions=el("div","bar"),follow=this.#button("ghost",discussion.following?this.t({id:"y6sq5j"}):this.t({id:"MKEPCY"}),"follow",()=>void this.#follow(),icons.bell);follow.setAttribute("aria-pressed",String(!!discussion.following)),follow.title=this.t({id:"Kl3TuI"}),follow.disabled=this.#busy.has("follow");let count=el("span","muted",this.t({id:"Hw3P48",values:{0:discussion.reply_count}}));if(actions.append(count,follow),view.append(actions),this.#threadState==="loading"&&!thread.posts.length&&discussion.reply_count>0){let skeleton=el("div","skeleton");skeleton.setAttribute("aria-busy","true"),skeleton.setAttribute("aria-label",this.t({id:"Pwqkdw"})),view.append(skeleton)}let tops=thread.posts.filter((p)=>!p.parent_post_id),replies=el("div","thread");for(let top of tops)replies.append(this.#postCard(top,top,thread.posts.filter((p)=>p.parent_post_id===top.id)));if(tops.length)view.append(replies);if(this.#notice)view.append(this.#noticeBox(this.#notice));if(discussion.locked)view.append(this.#noticeBox(this.t({id:"JfAIiv"}),icons.lock));else if(!this.#writer)view.append(this.#signInBox(this.t({id:"PL0621"})));else view.append(this.#composer(this.#reply,{label:this.t({id:"F_vGso"}),placeholder:this.t({id:"2Hlmdt"}),submit:this.t({id:"ImOQa9"}),busy:"reply",requires:"reply",focusKey:"reply",onSubmit:()=>void this.#send(this.#reply)}));return nodes.push(view),nodes}#noticeBox(text,icon=icons.clock){let box=el("div","notice");return box.setAttribute("role","status"),box.innerHTML=icon,box.append(el("p","",text)),box}render(){if(this.refused||!this.channel){this.root.replaceChildren();return}let focused="";try{focused=this.root.activeElement?.dataset?.key??""}catch{}let children=[this.#header()];if(this.#mode==="off"||this.#listState==="off")children.push(el("p","muted",this.t({id:"tayT8P"})));else if(this.#view.kind==="thread")children.push(...this.#threadView());else if(this.#view.kind==="new")children.push(...this.#newView());else{if(this.#notice)children.push(this.#noticeBox(this.#notice));children.push(...this.#listView())}if(this.#error){let error=el("p","error",this.#error);error.setAttribute("role","alert"),children.push(error)}this.frame(styles,...children),this.#syncSend();let wanted=this.#focus;this.#focus="";let key=wanted||focused;if(!key)return;let active=null;try{active=this.root.activeElement}catch{}if(active instanceof HTMLElement&&active.dataset.key===key)return;[...this.root.querySelectorAll("[data-key]")].find((node)=>node.dataset.key===key)?.focus({preventScroll:!wanted})}}var maxRemembered=500,thumb=(down)=>`<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"${down?' style="transform:scaleY(-1)"':""}><path d="M7 10v11H3V10zM7 10l4-8a3 3 0 013 3v4h6a2 2 0 012 2.3l-1.4 8A2 2 0 0118.6 21H7"/></svg>`,styles2=`
|
|
113
|
+
`;function hue(text){let hash=0;for(let char of text)hash=hash*31+char.charCodeAt(0)|0;return Math.abs(hash)%360}function excerptOf(html){let template=document.createElement("template");return template.innerHTML=html,(template.content.textContent??"").replace(/\s+/g," ").trim().slice(0,240)}class YuvaDiscussionsElement extends YuvaDocsElement{static loadThread;#s={view:{kind:"list"},items:[],thread:null,threadState:"loading",writer:null,reader:null,busy:new Set,notice:"",error:"",confirm:"",focus:""};#sort="new";#cursor;#listState="loading";#loadedFor="";#offReader=null;#thread=null;#threadLoad=null;#threadStyles="";get discussions(){return this.#s.items}get reader(){return this.#s.reader}#hashChanged=()=>this.#fromHash();connectedCallback(){super.connectedCallback(),window.addEventListener("hashchange",this.#hashChanged),this.#watchReader()}disconnectedCallback(){super.disconnectedCallback(),window.removeEventListener("hashchange",this.#hashChanged),this.#offReader?.(),this.#offReader=null}attributeChangedCallback(name,previous,value){if(super.attributeChangedCallback(name,previous,value),previous===value||!this.isConnected)return;if(name==="channel"||name==="server")this.#offReader?.(),this.#offReader=null,this.#watchReader();else if(name==="identity-token")this.#refreshWriter(!0)}setIdentityToken(source){super.setIdentityToken(source),this.#refreshWriter(!0)}#watchReader(){if(!this.channel||this.#offReader)return;let client=this.client();this.#s.reader=client.reader,this.#offReader=client.on("reader",(reader)=>{this.#s.reader=reader,this.emit("yuva-reader",reader?reader.reader:null),this.#refreshWriter(!0)}),this.#refreshWriter(!1)}async#refreshWriter(reload){if(!this.channel)return;let writer=await this.client().discussionWriter().catch(()=>null),changed=writer!==this.#s.writer;if(this.#s.writer=writer,reload&&changed){if(this.#loadedFor="",this.#load(!1),this.#s.view.kind==="thread")this.#open(this.#s.view.id,!1)}this.render()}reset(){let s=this.#s;s.view={kind:"list"},s.items=[],this.#cursor=void 0,this.#listState="loading",this.#loadedFor="",s.thread=null,s.notice="",s.error="",s.confirm="",this.#thread?.reset()}pageChanged(){this.#load(!1),this.#fromHash()}#linked(){let hash=location.hash;return hash.startsWith(hashPrefix)?decodeURIComponent(hash.slice(hashPrefix.length)):""}#fromHash(){let id=this.#linked();if(!id||!this.channel||this.refused)return;if(this.#s.view.kind==="thread"&&this.#s.view.id===id)return;this.#thread?.close(),this.#s.confirm="",this.#open(id,!0),this.scrollIntoView({block:"start"})}#prefetchOn(button){let prefetch=()=>void this.#loadThread();button.addEventListener("pointerenter",prefetch,{once:!0}),button.addEventListener("focus",prefetch,{once:!0})}#loadThread(){return this.#threadLoad??=YuvaDiscussionsElement.loadThread().then((module)=>{if(this.#threadStyles=module.styles,this.#thread=module.createThread(this.#host),this.#s.view.kind!=="list")this.render();return this.#thread},()=>{if(this.#threadLoad=null,this.#s.view.kind!=="list")this.#s.view={kind:"list"},this.#s.error=this.t({id:"D16wQE"}),this.render();return null}),this.#threadLoad}#host=this.#makeHost();#makeHost(){return{s:this.#s,icons,root:this.root,locale:()=>this.locale,direction:()=>this.direction,page:()=>this.pageUrl,pageTitle:()=>this.pageTitle,mode:()=>this.#mode,client:()=>this.client(),render:()=>this.render(),emit:(type,detail)=>this.emit(type,detail),act:(key,action)=>this.#act(key,action),signIn:()=>this.signIn(),open:(id,focus)=>this.#open(id,focus),toList:()=>this.#toList(),forget:()=>forget(this.#prefix),button:(className,text,key,onClick,html)=>this.#button(className,text,key,onClick,html),avatar:(author,small)=>this.#avatar(author,small),badge:(kind,short)=>this.#badge(kind,short),time:(value)=>this.#time(value),authorName:(author)=>this.#authorName(author),noticeBox:(text,icon)=>this.#noticeBox(text,icon)}}reload(){return this.#load(!0)}open(id){return this.#open(id,!0)}signIn(){return this.#s.error="",this.client().readerSignIn().then(()=>{return}).catch((error)=>{let code=error instanceof ApiError2?error.code:"";if(code==="sign_in_cancelled")return;this.#s.error=code==="popup_blocked"?this.t({id:"nW3go1"}):this.#failure(error),this.render()})}signOut(){return this.client().readerSignOut()}get#prefix(){return`${this.server} ${this.channel} ${this.pageUrl} `}async#load(force,more=!1){let page=this.pageUrl;if(!this.channel||!page||this.refused)return;let reader=this.client().reader,auth=reader?reader.token.slice(-12):this.#s.writer??"-",key=`${this.#prefix}${this.#sort} ${auth}`;if(!force&&!more&&this.#loadedFor===key)return;this.#loadedFor=key;let request;if(more)request=this.client().listDiscussions(page,{sort:this.#sort,cursor:this.#cursor});else{let load=loads.get(key);if(force||!load||Date.now()-load.at>cacheFor){load={at:Date.now(),request:this.client().listDiscussions(page,{sort:this.#sort})},loads.set(key,load);let current=load;load.request.catch(()=>loads.get(key)===current&&loads.delete(key))}if(request=load.request,!this.#s.items.length)this.#listState="loading"}if(more)this.#s.busy.add("more");this.render();try{let result=await request;if(this.#loadedFor!==key)return;this.#s.items=more?[...this.#s.items,...result.items.filter((d)=>!this.#s.items.some((i)=>i.id===d.id))]:result.items,this.#cursor=result.next_cursor,this.#listState="ready"}catch(error){if(this.#loadedFor!==key||this.refusal(error))return;if(!more)this.#loadedFor="";if(this.#listState=error instanceof ApiError2&&error.code==="discussions_off"?"off":more?"ready":"error",more)this.#s.error=this.#failure(error)}finally{this.#s.busy.delete("more")}this.render()}async#open(id,focus){let s=this.#s,page=this.pageUrl,known=s.thread?.discussion.id===id?s.thread:null;this.#loadThread(),s.view={kind:"thread",id};let listed=s.items.find((d)=>d.id===id);if(s.thread=known??(listed?{discussion:listed,posts:[]}:null),s.threadState=known?"ready":"loading",focus)s.notice=known?s.notice:"",s.error="",s.focus="thread-title";this.render();try{let detail=await this.client().getDiscussion(id);if(this.pageUrl!==page||s.view.kind!=="thread"||s.view.id!==id)return;let titled=!!s.thread;if(s.thread=detail,s.threadState="ready",focus&&!titled)s.focus="thread-title";s.items=s.items.map((d)=>d.id===id?detail.discussion:d)}catch(error){if(this.pageUrl!==page||s.view.kind!=="thread"||s.view.id!==id)return;if(this.refusal(error,!1))return;s.threadState=error instanceof ApiError2&&error.status===404?"missing":"error"}this.render()}#toList(){let s=this.#s;if(this.#linked()){let url=new URL(location.href);url.hash="",history.replaceState(history.state,"",url.href)}s.view={kind:"list"},this.#thread?.close(),s.confirm="",s.error="",s.focus=s.thread?`open-${s.thread.discussion.id}`:"start",this.render(),this.#load(!1)}#failure(error){let code=error instanceof ApiError2?error.code:"";if(code==="sign_in_required")return this.t({id:"LwDe8g"});if(code==="discussion_locked")return this.t({id:"KEjhwb"});if(code==="edit_window_closed")return this.t({id:"b_f4xj"});if(code==="discussions_off")return this.t({id:"tayT8P"});if(code==="forbidden")return this.t({id:"8Ekoev"});if(code==="validation_failed")return this.t({id:"Su3Vyp"});return this.errorText(error)}async#act(key,action){let s=this.#s;if(s.busy.has(key))return;s.busy.add(key),s.error="",this.render();try{return await action()}catch(error){if(!this.refusal(error,!1))s.error=this.#failure(error);if(error instanceof ApiError2&&error.code==="sign_in_required")this.#refreshWriter(!1);return}finally{s.busy.delete(key),this.render()}}get#mode(){return this.inbox?.chat.discussions??"moderated"}#button(className,text,key,onClick,html=""){let button=el("button",className);if(button.type="button",html)button.innerHTML=html;return button.append(text),button.dataset.key=key,button.addEventListener("click",onClick),button}#authorName(author){if(author.deleted)return author.kind==="member"?this.t({id:"-UxBoG"}):this.t({id:"FMWGhb"});if(author.kind==="anonymous")return this.t({id:"D9CFV5"});return author.name||(author.kind==="member"?this.t({id:"nLqMRA"}):this.t({id:"zmA6sS"}))}#avatar(author,small=!1){let avatar=el("span",`avatar${small?" small":""}`,author.deleted?"":author.initials||"?");if(avatar.setAttribute("aria-hidden","true"),author.deleted||author.kind==="anonymous")avatar.classList.add("gone");else if(author.kind==="member")avatar.classList.add("team");else avatar.style.setProperty("--avatar",`hsl(${hue(author.name||author.initials)} 45% 42%)`);return avatar}#badge(kind,short=!1){let text=kind==="answered"?this.t({id:"GqCA_t"}):kind==="pending"?short?this.t({id:"UbRKMZ"}):this.t({id:"lWv8id"}):kind==="team"?this.t({id:"KM6m8p"}):this.t({id:"G2fuEb"}),badge=el("span",`badge ${kind}`);if(kind!=="team")badge.innerHTML=kind==="answered"?icons.check:kind==="pending"?icons.clock:icons.lock;return badge.append(text),badge}#time(value){let time=el("time");time.dateTime=value;let date=new Date(value);time.title=date.toLocaleString(this.locale);let seconds=(date.getTime()-Date.now())/1000,steps=[["second",60],["minute",60],["hour",24],["day",30],["month",12],["year",1/0]],amount=seconds;for(let[unit,size]of steps){if(Math.abs(amount)<size){time.textContent=unit==="second"?this.t({id:"xOTzt5"}):new Intl.RelativeTimeFormat(this.locale,{numeric:"auto"}).format(Math.round(amount),unit);break}amount/=size}return time}#header(){let head=el("div","head");head.append(el("h2","",this.t({id:"7oGBMv"})));let who=el("div","who"),reader=this.#s.reader;if(reader){let name=reader.reader.name||this.t({id:"zmA6sS"});who.append(this.#avatar({kind:"reader",name,initials:reader.reader.initials,deleted:!1},!0)),who.append(el("span","",name)),who.append(this.#button("plain",this.t({id:"fcWrnU"}),"sign-out",()=>void this.signOut()))}else if(!this.#s.writer&&this.#mode!=="off")who.append(this.#button("ghost",this.t({id:"5lWFkC"}),"sign-in",()=>void this.signIn()));return head.append(who),head}#listView(){let nodes=[],bar=el("div","bar"),tabs=el("div","tabs");tabs.setAttribute("role","tablist"),tabs.setAttribute("aria-label",this.t({id:"78dEKp"}));let sorts=[["new",this.t({id:"isRobC"})],["top",this.t({id:"WWy8TN"})],["unanswered",this.t({id:"2lF8Zj"})]];sorts.forEach(([sort,label],index)=>{let tab=this.#button("tab",label,`sort-${sort}`,()=>this.#setSort(sort));tab.setAttribute("role","tab"),tab.setAttribute("aria-selected",String(this.#sort===sort)),tab.setAttribute("aria-controls","yuva-discussion-list"),tab.tabIndex=this.#sort===sort?0:-1,tab.addEventListener("keydown",(event)=>{let step=event.key==="ArrowRight"?1:event.key==="ArrowLeft"?-1:0;if(!step)return;event.preventDefault();let forward=this.direction==="rtl"?-step:step,next=sorts[(index+forward+sorts.length)%sorts.length];if(next)this.#setSort(next[0])}),tabs.append(tab)});let start=this.#button("send",this.t({id:"z1qf6l"}),"start",()=>{this.#loadThread(),this.#s.view={kind:"new"},this.#s.error="",this.#s.notice="",this.#s.focus="new-title",this.render()});if(this.#prefetchOn(start),bar.append(tabs,start),nodes.push(bar),this.#listState==="loading"&&!this.#s.items.length){let skeleton=el("div","skeleton");return skeleton.setAttribute("aria-busy","true"),skeleton.setAttribute("aria-label",this.t({id:"pzatAP"})),nodes.push(skeleton),nodes}if(this.#listState==="error"&&!this.#s.items.length){let box=el("div","empty");box.append(el("p","",this.t({id:"MDmQKn"})));let retry=this.#button("ghost",this.t({id:"KDw4GX"}),"retry",()=>void this.#load(!0));return retry.style.marginBlockStart="8px",box.append(retry),nodes.push(box),nodes}if(!this.#s.items.length){let box=el("div","empty");if(box.append(el("p","",this.#sort==="unanswered"?this.t({id:"twEQ41"}):this.t({id:"rpfOwz"}))),this.#sort!=="unanswered")box.append(el("p","muted",this.t({id:"b6Orhy"})));return nodes.push(box),nodes}let list=el("ul","list");list.id="yuva-discussion-list",list.setAttribute("aria-label",this.t({id:"j-3eim"})),list.setAttribute("aria-busy",String(this.#listState==="loading"));for(let discussion of this.#s.items){let item=el("li","item");item.append(this.#avatar(discussion.author));let main=el("div","main"),title=this.#button("title",discussion.title,`open-${discussion.id}`,()=>void this.#open(discussion.id,!0));title.dir="auto",this.#prefetchOn(title),main.append(title);let excerpt=discussion.deleted?"":excerptOf(discussion.body_html);if(excerpt){let text=el("p","excerpt",excerpt);text.dir="auto",main.append(text)}let meta=el("div","meta");if(meta.append(el("span","",this.#authorName(discussion.author)),this.#time(discussion.created_at)),discussion.author.kind==="member"&&!discussion.author.deleted)meta.append(this.#badge("team"));if(discussion.answer_post_id)meta.append(this.#badge("answered"));if(discussion.state==="pending")meta.append(this.#badge("pending"));if(discussion.locked)meta.append(this.#badge("locked"));main.append(meta);let counts=el("div","counts"),votes=el("span","count");votes.innerHTML=icons.up,votes.append(String(discussion.votes)),votes.setAttribute("aria-label",this.t({id:"8ntmc1",values:{0:discussion.votes}})),votes.title=votes.getAttribute("aria-label")??"";let replies=el("span","count");replies.innerHTML=icons.comment,replies.append(String(discussion.reply_count)),replies.setAttribute("aria-label",this.t({id:"Hw3P48",values:{0:discussion.reply_count}})),replies.title=replies.getAttribute("aria-label")??"",counts.append(votes,replies),item.append(main,counts),list.append(item)}if(nodes.push(list),this.#cursor){let more=this.#button("ghost more",this.#s.busy.has("more")?this.t({id:"Pwqkdw"}):this.t({id:"fMPkxb"}),"more",()=>void this.#load(!1,!0));more.disabled=this.#s.busy.has("more"),nodes.push(more)}return nodes}#setSort(sort){if(this.#sort===sort)return;this.#sort=sort,this.#s.items=[],this.#cursor=void 0,this.#listState="loading",this.#s.focus=`sort-${sort}`,this.#load(!1)}#noticeBox(text,icon=icons.clock){let box=el("div","notice");return box.setAttribute("role","status"),box.innerHTML=icon,box.append(el("p","",text)),box}render(){if(this.refused||!this.channel){this.root.replaceChildren();return}let focused="";try{focused=this.root.activeElement?.dataset?.key??""}catch{}let children=[this.#header()];if(this.#mode==="off"||this.#listState==="off")children.push(el("p","muted",this.t({id:"tayT8P"})));else if(this.#s.view.kind!=="list"){let thread=this.#thread;if(thread)children.push(...this.#s.view.kind==="thread"?thread.threadView():thread.newView());else{let skeleton=el("div","skeleton");skeleton.setAttribute("aria-busy","true"),skeleton.setAttribute("aria-label",this.t({id:"Pwqkdw"})),children.push(skeleton)}}else{if(this.#s.notice)children.push(this.#noticeBox(this.#s.notice));children.push(...this.#listView())}if(this.#s.error){let error=el("p","error",this.#s.error);error.setAttribute("role","alert"),children.push(error)}if(this.frame(styles+this.#threadStyles,...children),this.#s.view.kind!=="list"&&!this.#thread)return;this.#thread?.syncSend();let wanted=this.#s.focus;this.#s.focus="";let key=wanted||focused;if(!key)return;let active=null;try{active=this.root.activeElement}catch{}if(active instanceof HTMLElement&&active.dataset.key===key)return;[...this.root.querySelectorAll("[data-key]")].find((node)=>node.dataset.key===key)?.focus({preventScroll:!wanted})}}var maxRemembered=500,thumb=(down)=>`<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"${down?' style="transform:scaleY(-1)"':""}><path d="M7 10v11H3V10zM7 10l4-8a3 3 0 013 3v4h6a2 2 0 012 2.3l-1.4 8A2 2 0 0118.6 21H7"/></svg>`,styles2=`
|
|
171
114
|
.frame { display: flex; flex-direction: column; gap: 12px; }
|
|
172
115
|
.ask { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; }
|
|
173
116
|
.question { font-weight: 600; }
|
|
@@ -188,4 +131,4 @@ button { font: inherit; color: inherit; }
|
|
|
188
131
|
.choice[aria-pressed="true"] { background: var(--yuva-soft); }
|
|
189
132
|
.choice:disabled { cursor: default; }
|
|
190
133
|
.choice:focus-visible { outline: 2px solid var(--yuva-accent); outline-offset: 2px; }
|
|
191
|
-
`;function storageKey(channel){return`yuva:${channel}:page-ratings`}function remembered(channel){try{let raw=localStorage.getItem(storageKey(channel));return raw?JSON.parse(raw):{}}catch{return{}}}function remember(channel,page,rating){try{let ratings=remembered(channel);delete ratings[page],ratings[page]=rating;let pages=Object.keys(ratings);for(let old of pages.slice(0,Math.max(0,pages.length-maxRemembered)))delete ratings[old];localStorage.setItem(storageKey(channel),JSON.stringify(ratings))}catch{}}class YuvaPageFeedbackElement extends YuvaDocsElement{#phase="ask";#rating;#error="";#comment=el("textarea");#email=el("input");constructor(){super();this.#comment.rows=3,this.#comment.maxLength=5000,this.#comment.dir="auto",this.#comment.addEventListener("input",()=>this.#syncSend()),this.#email.type="email",this.#email.autocomplete="email"}get rating(){return this.#rating??null}reset(){this.#phase="ask",this.#error="",this.#comment.value="",this.#rating=this.channel?remembered(this.channel)[this.pageUrl]:void 0}pageChanged(){if(this.#phase==="ask"&&!this.#error)this.#rating=this.channel?remembered(this.channel)[this.pageUrl]:void 0;this.render()}async rate(rating){let channel=this.channel;if(!channel||this.refused||this.#phase==="rating"||this.#phase==="sending")return;let page=this.pageUrl,previous=remembered(channel)[page];if(this.#error="",previous===rating){this.#rating=rating,this.#phase=this.canWrite?"form":"thanks",this.render(),this.#comment.focus({preventScroll:!0});return}this.#phase="rating",this.#rating=rating,this.render();try{await this.client().ratePage({page,title:this.pageTitle||void 0,rating,previous})}catch(error){if(this.pageUrl!==page||this.refusal(error))return;this.#rating=previous,this.#phase="ask",this.#error=this.errorText(error),this.render();return}if(remember(channel,page,rating),this.emit("yuva-rating",{page,rating,previous:previous??null}),this.pageUrl!==page)return;this.#phase=this.canWrite?"form":"thanks",this.render(),this.#comment.focus({preventScroll:!0})}async#send(){let body=this.#comment.value.trim(),email=this.#email.value.trim(),rating=this.#rating;if(!body||this.#phase!=="form")return;if(email&&!this.#email.checkValidity()){this.#error=this.t({id:"E_qvzP"}),this.render();return}let page=this.pageUrl;this.#phase="sending",this.#error="",this.render();try{let{conversation}=await this.client().sendFeedback({page_url:page,page_title:this.pageTitle||void 0,rating,body,locale:this.locale,allow_email:this.identified||!!email,email:!this.identified&&email?email:void 0});if(this.emit("yuva-feedback",{page,rating:rating??null,conversation_id:conversation.id}),this.pageUrl!==page)return;this.#comment.value="",this.#phase="thanks"}catch(error){if(this.pageUrl!==page||this.refusal(error,!1))return;this.#phase="form",this.#error=this.errorText(error)}this.render()}#syncSend(){let send=this.root.querySelector(".send");if(send)send.disabled=this.#phase!=="form"||this.#comment.value.trim()===""}render(){if(this.refused||!this.channel){this.root.replaceChildren();return}let question=this.t({id:"SOvBw9"}),ask=el("div","ask");ask.setAttribute("role","group"),ask.setAttribute("aria-label",question);let choices=el("div","choices");for(let value of["up","down"]){let button=el("button","choice");button.type="button",button.innerHTML=thumb(value==="down"),button.append(el("span","",value==="up"?this.t({id:"l75CjT"}):this.t({id:"1UzENP"}))),button.setAttribute("aria-pressed",String(this.#rating===value)),button.disabled=this.#phase==="rating"||this.#phase==="sending",button.addEventListener("click",()=>void this.rate(value)),choices.append(button)}ask.append(el("p","question",question),choices);let children=[ask];if(this.#phase==="form"||this.#phase==="sending"){let form=el("form");form.noValidate=!0,form.addEventListener("submit",(event)=>{event.preventDefault(),this.#send()});let prompt=this.#rating==="down"?this.t({id:"U7H5Fm"}):this.t({id:"EmiQvf"});if(this.#comment.placeholder=prompt,this.#comment.setAttribute("aria-label",prompt),this.#comment.disabled=this.#phase==="sending",form.append(this.#comment),!this.identified)this.#email.placeholder=this.t({id:"a_qtPP"}),this.#email.setAttribute("aria-label",this.t({id:"XJURKP"})),this.#email.disabled=this.#phase==="sending",form.append(this.#email);let skip=el("button","link",this.t({id:"tA4dAO"}));skip.type="button",skip.disabled=this.#phase==="sending",skip.addEventListener("click",()=>{this.#phase="thanks",this.#error="",this.render()});let send=el("button","send",this.#phase==="sending"?this.t({id:"Sad2tK"}):this.t({id:"JlFcis"}));send.type="submit";let actions=el("div","actions");actions.append(skip,send),form.append(actions),children.push(form)}else if(this.#phase==="thanks"){let thanks=el("p","muted",this.t({id:"d6N994"}));thanks.setAttribute("role","status"),children.push(thanks)}if(this.#error){let error=el("p","error",this.#error);error.setAttribute("role","alert"),children.push(error)}this.frame(styles2,...children),this.#syncSend()}}function defineDocs(){if(typeof customElements>"u")return;if(!customElements.get("yuva-discussions"))customElements.define("yuva-discussions",YuvaDiscussionsElement);if(!customElements.get("yuva-page-feedback"))customElements.define("yuva-page-feedback",YuvaPageFeedbackElement)}defineDocs();export{YuvaDiscussionsElement,YuvaPageFeedbackElement,defineDocs};
|
|
134
|
+
`;function storageKey(channel){return`yuva:${channel}:page-ratings`}function remembered(channel){try{let raw=localStorage.getItem(storageKey(channel));return raw?JSON.parse(raw):{}}catch{return{}}}function remember(channel,page,rating){try{let ratings=remembered(channel);delete ratings[page],ratings[page]=rating;let pages=Object.keys(ratings);for(let old of pages.slice(0,Math.max(0,pages.length-maxRemembered)))delete ratings[old];localStorage.setItem(storageKey(channel),JSON.stringify(ratings))}catch{}}class YuvaPageFeedbackElement extends YuvaDocsElement{#phase="ask";#rating;#error="";#comment=el("textarea");#email=el("input");constructor(){super();this.#comment.rows=3,this.#comment.maxLength=5000,this.#comment.dir="auto",this.#comment.addEventListener("input",()=>this.#syncSend()),this.#email.type="email",this.#email.autocomplete="email"}get rating(){return this.#rating??null}reset(){this.#phase="ask",this.#error="",this.#comment.value="",this.#rating=this.channel?remembered(this.channel)[this.pageUrl]:void 0}pageChanged(){if(this.#phase==="ask"&&!this.#error)this.#rating=this.channel?remembered(this.channel)[this.pageUrl]:void 0;this.render()}async rate(rating){let channel=this.channel;if(!channel||this.refused||this.#phase==="rating"||this.#phase==="sending")return;let page=this.pageUrl,previous=remembered(channel)[page];if(this.#error="",previous===rating){this.#rating=rating,this.#phase=this.canWrite?"form":"thanks",this.render(),this.#comment.focus({preventScroll:!0});return}this.#phase="rating",this.#rating=rating,this.render();try{await this.client().ratePage({page,title:this.pageTitle||void 0,rating,previous})}catch(error){if(this.pageUrl!==page||this.refusal(error))return;this.#rating=previous,this.#phase="ask",this.#error=this.errorText(error),this.render();return}if(remember(channel,page,rating),this.emit("yuva-rating",{page,rating,previous:previous??null}),this.pageUrl!==page)return;this.#phase=this.canWrite?"form":"thanks",this.render(),this.#comment.focus({preventScroll:!0})}async#send(){let body=this.#comment.value.trim(),email=this.#email.value.trim(),rating=this.#rating;if(!body||this.#phase!=="form")return;if(email&&!this.#email.checkValidity()){this.#error=this.t({id:"E_qvzP"}),this.render();return}let page=this.pageUrl;this.#phase="sending",this.#error="",this.render();try{let{conversation}=await this.client().sendFeedback({page_url:page,page_title:this.pageTitle||void 0,rating,body,locale:this.locale,allow_email:this.identified||!!email,email:!this.identified&&email?email:void 0});if(this.emit("yuva-feedback",{page,rating:rating??null,conversation_id:conversation.id}),this.pageUrl!==page)return;this.#comment.value="",this.#phase="thanks"}catch(error){if(this.pageUrl!==page||this.refusal(error,!1))return;this.#phase="form",this.#error=this.errorText(error)}this.render()}#syncSend(){let send=this.root.querySelector(".send");if(send)send.disabled=this.#phase!=="form"||this.#comment.value.trim()===""}render(){if(this.refused||!this.channel){this.root.replaceChildren();return}let question=this.t({id:"SOvBw9"}),ask=el("div","ask");ask.setAttribute("role","group"),ask.setAttribute("aria-label",question);let choices=el("div","choices");for(let value of["up","down"]){let button=el("button","choice");button.type="button",button.innerHTML=thumb(value==="down"),button.append(el("span","",value==="up"?this.t({id:"l75CjT"}):this.t({id:"1UzENP"}))),button.setAttribute("aria-pressed",String(this.#rating===value)),button.disabled=this.#phase==="rating"||this.#phase==="sending",button.addEventListener("click",()=>void this.rate(value)),choices.append(button)}ask.append(el("p","question",question),choices);let children=[ask];if(this.#phase==="form"||this.#phase==="sending"){let form=el("form");form.noValidate=!0,form.addEventListener("submit",(event)=>{event.preventDefault(),this.#send()});let prompt=this.#rating==="down"?this.t({id:"U7H5Fm"}):this.t({id:"EmiQvf"});if(this.#comment.placeholder=prompt,this.#comment.setAttribute("aria-label",prompt),this.#comment.disabled=this.#phase==="sending",form.append(this.#comment),!this.identified)this.#email.placeholder=this.t({id:"a_qtPP"}),this.#email.setAttribute("aria-label",this.t({id:"XJURKP"})),this.#email.disabled=this.#phase==="sending",form.append(this.#email);let skip=el("button","link",this.t({id:"tA4dAO"}));skip.type="button",skip.disabled=this.#phase==="sending",skip.addEventListener("click",()=>{this.#phase="thanks",this.#error="",this.render()});let send=el("button","send",this.#phase==="sending"?this.t({id:"Sad2tK"}):this.t({id:"JlFcis"}));send.type="submit";let actions=el("div","actions");actions.append(skip,send),form.append(actions),children.push(form)}else if(this.#phase==="thanks"){let thanks=el("p","muted",this.t({id:"d6N994"}));thanks.setAttribute("role","status"),children.push(thanks)}if(this.#error){let error=el("p","error",this.#error);error.setAttribute("role","alert"),children.push(error)}this.frame(styles2,...children),this.#syncSend()}}function defineDocs(){if(typeof customElements>"u")return;if(!customElements.get("yuva-discussions"))customElements.define("yuva-discussions",YuvaDiscussionsElement);if(!customElements.get("yuva-page-feedback"))customElements.define("yuva-page-feedback",YuvaPageFeedbackElement)}YuvaDiscussionsElement.loadThread=()=>import("./thread-btm71nxt.js");defineDocs();export{YuvaDiscussionsElement,YuvaPageFeedbackElement,defineDocs};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import{ApiError2,call,mailingLists,createSubscription}from"./index-gk84nm8f.js";class Realtime{server;socketClass;handlers;#socket=null;#lastEventId=0;#attempt=0;#timer=null;#stopped=!0;constructor(server,socketClass,handlers){this.server=server;this.socketClass=socketClass;this.handlers=handlers}get connected(){return this.#socket?.readyState===1}start(){if(this.#stopped=!1,!this.#socket)this.#connect()}stop(){if(this.#stopped=!0,this.#timer)clearTimeout(this.#timer);this.#timer=null;let socket=this.#socket;this.#socket=null,socket?.close(1000)}reset(){this.#lastEventId=0}nudge(){if(this.#stopped||this.#socket)return;if(this.#timer)clearTimeout(this.#timer);this.#timer=null,this.#connect()}#connect(){let token=this.handlers.token();if(!token||this.#stopped)return;let url=new URL(`${this.server}/client/v1/realtime`,globalThis.location?.href);if(url.protocol=url.protocol==="https:"?"wss:":"ws:",this.#lastEventId>0)url.searchParams.set("last_event_id",String(this.#lastEventId));let socket;try{socket=new this.socketClass(url,["yuva",`yuva.token.${token}`])}catch{this.#schedule();return}this.#socket=socket,socket.onmessage=(event)=>{let message;try{message=JSON.parse(String(event.data))}catch{return}if(message.type==="ready")this.#attempt=0,this.#lastEventId=Math.max(this.#lastEventId,message.last_event_id);else if("id"in message&&typeof message.id==="number")this.#lastEventId=Math.max(this.#lastEventId,message.id);this.handlers.event(message)},socket.onclose=(event)=>{if(this.#socket!==socket)return;if(this.#socket=null,this.#stopped)return;if(event.code===1008){this.#lastEventId=0,this.handlers.sessionEnded();return}this.#schedule()}}#schedule(){if(this.#stopped||this.#timer)return;let attempt=this.#attempt++;this.handlers.reconnecting(attempt);let delay=Math.min(30000,1000*2**attempt)*(0.75+Math.random()*0.5);this.#timer=setTimeout(()=>{this.#timer=null,this.#connect()},delay)}}function readerConnectUrl2(server,channel,origin){let url=new URL("/account/connect",server);return url.searchParams.set("channel",channel),url.searchParams.set("origin",origin),url.href}function isReaderToken(value){let data=value;return!!data&&typeof data.token==="string"&&data.token.startsWith("yuva_rd_")&&typeof data.expires_at==="string"&&!Number.isNaN(Date.parse(data.expires_at))&&typeof data.channel_key==="string"&&typeof data.origin==="string"&&!!data.reader&&typeof data.reader.initials==="string"}function openReaderPopup2(server,channel,{width=460,height=640}={}){let serverOrigin=new URL(server).origin,origin=location.origin,left=Math.max(0,(window.screenX??0)+((window.outerWidth??width)-width)/2),top=Math.max(0,(window.screenY??0)+((window.outerHeight??height)-height)/2),popup=window.open(readerConnectUrl2(server,channel,origin),"yuva-reader",`popup=yes,width=${width},height=${height},left=${Math.round(left)},top=${Math.round(top)}`);if(!popup)return Promise.reject(new ApiError2(0,"popup_blocked"));return new Promise((resolve,reject)=>{let done=!1,finish=()=>{done=!0,window.removeEventListener("message",received),clearInterval(watch)},received=(event)=>{if(done||event.origin!==serverOrigin||event.source&&event.source!==popup)return;let data=event.data;if(!isReaderToken(data)||data.channel_key!==channel||data.origin!==origin)return;finish();try{popup.close()}catch{}resolve({token:data.token,expires_at:data.expires_at,reader:data.reader})},watch=setInterval(()=>{let closed=!1;try{closed=popup.closed}catch{}if(!closed)return;clearInterval(watch),setTimeout(()=>{if(done)return;finish(),reject(new ApiError2(0,"sign_in_cancelled"))},300)},500);window.addEventListener("message",received)})}function storageKey2(channel){return`yuva:${channel}`}function readerStorageKey2(server,channel){return`yuva:reader:${server} ${channel}`}function randomId2(){if(typeof crypto.randomUUID==="function")return crypto.randomUUID();return Array.from(crypto.getRandomValues(new Uint8Array(16)),(b)=>b.toString(16).padStart(2,"0")).join("")}function jwtSubject(token){try{let part=(token.split(".")[1]??"").replace(/-/g,"+").replace(/_/g,"/"),payload=JSON.parse(atob(part));return typeof payload.sub==="string"?payload.sub:null}catch{return null}}function defaultStorage(){try{let storage=globalThis.localStorage;if(storage)return storage}catch{}let memory=new Map;return{getItem:(key)=>memory.get(key)??null,setItem:(key,value)=>void memory.set(key,value)}}function query(params){let search=new URLSearchParams;for(let[name,value]of Object.entries(params))if(value!==void 0)search.set(name,String(value));let text=search.toString();return text?`?${text}`:""}function quoted(value){return value.replace(/"/g,"%22").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function multipart(fields,files,boundary){let parts=[];for(let[name,value]of fields)parts.push(`--${boundary}\r
|
|
2
|
+
Content-Disposition: form-data; name="${name}"\r
|
|
3
|
+
\r
|
|
4
|
+
${value}\r
|
|
5
|
+
`);for(let file of files){let filename=file.name||"file";parts.push(`--${boundary}\r
|
|
6
|
+
Content-Disposition: form-data; name="files"; filename="${quoted(filename)}"\r
|
|
7
|
+
Content-Type: ${file.type||"application/octet-stream"}\r
|
|
8
|
+
\r
|
|
9
|
+
`,file,`\r
|
|
10
|
+
`)}return parts.push(`--${boundary}--\r
|
|
11
|
+
`),new Blob(parts)}class YuvaClient2{server;channel;#fetch;#socketClass;#storage;#identity;#idempotencyKeys;#token=null;#session=null;#starting=null;#renewing=null;#realtime=null;#reader;#handlers=new Map;constructor(options){this.server=options.server.replace(/\/+$/,""),this.channel=options.channel,this.#fetch=options.fetch??((url,init)=>fetch(url,init)),this.#socketClass=options.WebSocket??globalThis.WebSocket,this.#storage=options.storage??defaultStorage(),this.#identity=options.identityToken??null,this.#idempotencyKeys=options.idempotencyKeys??typeof globalThis.document>"u"}get session(){return this.#session}get token(){return this.#token}get connected(){return this.#realtime?.connected??!1}on(type,handler){let set=this.#handlers.get(type);if(!set)this.#handlers.set(type,set=new Set);return set.add(handler),()=>void set.delete(handler)}#emit(type,value){for(let handler of this.#handlers.get(type)??[])handler(value)}stored(){try{let raw=this.#storage.getItem(storageKey2(this.channel));return raw?JSON.parse(raw):{}}catch{return{}}}#store(state){try{this.#storage.setItem(storageKey2(this.channel),JSON.stringify(state))}catch{}}channelSettings(){return this.#call(`/client/v1/channels/${encodeURIComponent(this.channel)}`)}ratePage(input){return this.#call(`/client/v1/channels/${encodeURIComponent(this.channel)}/page-ratings`,{method:"POST",json:input})}lists(){return mailingLists(this.#fetch,this.server,this.channel)}subscribe(input){return createSubscription(this.#fetch,this.server,this.channel,input)}subscriptions(){return this.#authed("/client/v1/subscriptions")}subscribeList(listId,input){return this.#authed(`/client/v1/subscriptions/${encodeURIComponent(listId)}`,{method:"PUT",json:input})}unsubscribeList(listId){return this.#authed(`/client/v1/subscriptions/${encodeURIComponent(listId)}`,{method:"DELETE"})}setIdentityToken(source){this.#identity=source,this.reset()}start(){if(this.#session)return Promise.resolve(this.#session);return this.#starting??=this.#open(!1).then((session)=>(this.#emit("session",{session,renewed:!1}),session)).finally(()=>{this.#starting=null}),this.#starting}async refresh(){let info=await this.#authed("/client/v1/session");return this.#session={...this.#session,...info},this.#emit("session",{session:this.#session,renewed:!1}),this.#session}reset(){this.#realtime?.stop(),this.#realtime?.reset(),this.#starting=null,this.#renewing=null,this.#token=null,this.#session=null}async signOut(){let token=this.#token;this.reset();let stored=this.stored();if(delete stored.session,this.#store(stored),token)await this.#call("/client/v1/session",{method:"DELETE",token}).catch(()=>{return})}async connect(){if(!this.#socketClass)throw Error("Yuva: no WebSocket in this runtime; pass options.WebSocket");if(await this.start(),this.#realtime??=new Realtime(this.server,this.#socketClass,{token:()=>this.#token,event:(message)=>{if(message.type==="ready")this.#emit("connection",{state:"open",attempt:0});this.#emit("event",message)},sessionEnded:()=>void this.#renew().catch(()=>this.#realtime?.nudge()),reconnecting:(attempt)=>{if(this.#emit("connection",{state:"reconnecting",attempt}),attempt===2)this.#authed("/client/v1/session").catch(()=>{return})}}),!this.#realtime.connected)this.#emit("connection",{state:"connecting",attempt:0});this.#realtime.start()}disconnect(){this.#realtime?.stop(),this.#emit("connection",{state:"closed",attempt:0})}reconnect(){this.#realtime?.nudge()}listConversations(page={}){return this.#authed(`/client/v1/conversations${query({...page})}`)}getConversation(id){return this.#authed(`/client/v1/conversations/${encodeURIComponent(id)}`)}startConversation(input){return this.#authed("/client/v1/conversations",this.#messageRequest(input))}listMessages(conversationId,page={}){return this.#authed(`/client/v1/conversations/${encodeURIComponent(conversationId)}/messages${query({...page})}`)}sendMessage(conversationId,input){return this.#authed(`/client/v1/conversations/${encodeURIComponent(conversationId)}/messages`,this.#messageRequest(input))}markRead(conversationId,messageId){return this.#authed(`/client/v1/conversations/${encodeURIComponent(conversationId)}/read`,{method:"POST",json:messageId?{message_id:messageId}:{}})}rate(conversationId,rating,comment){let body={rating,comment:comment?.trim()||void 0};return this.#authed(`/client/v1/conversations/${encodeURIComponent(conversationId)}/rating`,{method:"POST",json:body})}setTyping(conversationId,typing){return this.#authed(`/client/v1/conversations/${encodeURIComponent(conversationId)}/typing`,{method:"POST",json:{typing}})}setEmail(email){return this.#authed("/client/v1/contact/email",{method:"PUT",json:{email}})}attachment(id){return this.#authed(`/client/v1/attachments/${encodeURIComponent(id)}`,{blob:!0})}sendFeedback(input){let client_id=input.client_id??randomId2();return this.#authed("/client/v1/feedback",{method:"POST",headers:this.#idempotency(client_id),json:{...input,client_id}})}get reader(){if(this.#reader===void 0)try{let raw=this.#storage.getItem(readerStorageKey2(this.server,this.channel));this.#reader=raw?JSON.parse(raw):null}catch{this.#reader=null}if(this.#reader&&Date.parse(this.#reader.expires_at)<=Date.now()+30000)this.#setReader(null);return this.#reader}#setReader(reader){let changed=this.#reader?.token!==reader?.token;this.#reader=reader;try{this.#storage.setItem(readerStorageKey2(this.server,this.channel),reader?JSON.stringify(reader):"")}catch{}if(changed)this.#emit("reader",reader)}readerSignIn(options){return openReaderPopup2(this.server,this.channel,options).then((reader)=>(this.#setReader(reader),reader))}setReader(reader){this.#setReader(reader)}async readerSignOut(){let token=this.reader?.token;if(this.#setReader(null),token)await this.#call("/client/v1/reader-token",{method:"DELETE",token}).catch(()=>{return})}listDiscussions(page,options={}){return this.#discussionCall(`/client/v1/channels/${encodeURIComponent(this.channel)}/discussions${query({page,...options})}`,{},!1)}getDiscussion(id){return this.#discussionCall(`/client/v1/channels/${encodeURIComponent(this.channel)}/discussions/${encodeURIComponent(id)}`,{},!1)}startDiscussion(input){return this.#discussionCall("/client/v1/discussions",{method:"POST",json:input})}replyToDiscussion(discussionId,input){return this.#discussionCall(`/client/v1/discussions/${encodeURIComponent(discussionId)}/posts`,{method:"POST",json:input})}editDiscussionPost(postId,input){return this.#discussionCall(`/client/v1/discussion-posts/${encodeURIComponent(postId)}`,{method:"PATCH",json:input})}deleteDiscussionPost(postId){return this.#discussionCall(`/client/v1/discussion-posts/${encodeURIComponent(postId)}`,{method:"DELETE"})}voteDiscussionPost(postId,voted=!0){return this.#discussionCall(`/client/v1/discussion-posts/${encodeURIComponent(postId)}/vote`,{method:voted?"PUT":"DELETE"})}followDiscussion(discussionId,following=!0){return this.#discussionCall(`/client/v1/discussions/${encodeURIComponent(discussionId)}/follow`,{method:following?"PUT":"DELETE"})}acceptDiscussionAnswer(discussionId,postId){let path=`/client/v1/discussions/${encodeURIComponent(discussionId)}/answer`;return this.#discussionCall(path,postId?{method:"PUT",json:{post_id:postId}}:{method:"DELETE"})}async discussionWriter(){if(this.reader)return"reader";if(this.#session)return this.#session.contact.identified?"contact":null;return await this.#identity?.()?"contact":null}async#discussionCall(path,request,write=!0){let reader=this.reader;if(reader)try{return await this.#call(path,{...request,token:reader.token})}catch(error){if(!(error instanceof ApiError2)||error.status!==401||this.#reader?.token!==reader.token)throw error;if(this.#setReader(null),write)throw new ApiError2(403,"sign_in_required")}if(await this.discussionWriter()==="contact")return this.#authed(path,request);if(write)throw new ApiError2(403,"sign_in_required");return this.#call(path,request)}#idempotency(client_id){return this.#idempotencyKeys&&/^[\x20-\x7e]{1,255}$/.test(client_id)?{"Idempotency-Key":client_id}:{}}#messageRequest({body,subject,files=[],client_id=randomId2()}){let headers=this.#idempotency(client_id);if(files.length===0)return{method:"POST",headers,json:{body,subject,client_id}};let fields=[];if(subject)fields.push(["subject",subject]);if(body)fields.push(["body",body]);fields.push(["client_id",client_id]);let boundary=`yuva-${client_id.replace(/[^\w-]/g,"").slice(0,60)}-${client_id.length}`;return headers["Content-Type"]=`multipart/form-data; boundary=${boundary}`,{method:"POST",headers,body:multipart(fields,files,boundary)}}#call(path,request){return call(this.#fetch,this.server,path,request)}async#authed(path,request={},retry=!0){if(!this.#token)await this.start();try{return await this.#call(path,{...request,token:this.#token})}catch(error){if(!retry||!(error instanceof ApiError2)||error.status!==401)throw error;return await this.#renew(),this.#authed(path,request,!1)}}#renew(){return this.#renewing??=(async()=>{let session=await this.#open(!0);if(this.#realtime)this.#realtime.stop(),this.#realtime.reset(),this.#realtime.start();this.#emit("session",{session,renewed:!0})})().finally(()=>{this.#renewing=null}),this.#renewing}async#open(fresh){let stored=this.stored(),identity=await this.#identity?.()||null,subject=identity?jwtSubject(identity):null,saved=stored.session;if(!fresh&&saved&&saved.sub===subject&&Date.parse(saved.expires_at)>Date.now()+60000)try{let info=await this.#call("/client/v1/session",{token:saved.token});return this.#apply(info,saved.token,subject)}catch(error){if(!(error instanceof ApiError2)||error.status!==401&&error.status!==403)throw error}let session=await this.#call("/client/v1/session",{method:"POST",json:{channel_key:this.channel,identity_token:identity??void 0,visitor_id:stored.visitor_id}}),{token,...info}=session;return this.#apply(info,token,subject)}#apply(info,token,subject){this.#token=token,this.#session=info;let stored=this.stored();if(stored.session={token,expires_at:info.expires_at,sub:subject},info.visitor_id)stored.visitor_id=info.visitor_id;else if(info.contact.identified)delete stored.visitor_id;return this.#store(stored),info}}function createYuvaClient2(options){return new YuvaClient2(options)}
|
|
12
|
+
export{readerConnectUrl2,openReaderPopup2,storageKey2,readerStorageKey2,randomId2,YuvaClient2,createYuvaClient2};
|